text stringlengths 54 60.6k |
|---|
<commit_before><commit_msg>Adjusted the default support_points_minimal_distance to 1mm.<commit_after><|endoftext|> |
<commit_before>/// \file AddTaskEMCALTimeCalibration.C
/// \brief Configuration of task AliAnalysisTaskEMCALTimeCalib.
///
/// Configuration of task AliAnalysisTaskEMCALTimeCalib
///
/// The parameters for the analysis are:
/// \param outputFile: TString, output file name
/// \param geometryName: TString, geometry name
/// \param minClusterEne: Double_t, minimum cluster energy
/// \param maxClusterEne: Double_t, maximum cluster energy
/// \param minNcells: Int_t, minimum number of cells in cluster
/// \param maxNcells: Int_t, maximum number of cells in cluster
/// \param minLambda0LG: Double_t, minimum cluster lambda0 for cluster with low gain cell
/// \param maxLambda0LG: Double_t, maximum cluster lambda0 for cluster with low gain cell
/// \param minLambda0: Double_t, minimum cluster lambda0
/// \param maxLambda0: Double_t, maximum cluster lambda0
/// \param maxRtrack: Double_t, maximum cluster track distance
/// \param minCellEne: Double_t, minimum cell energy
/// \param referenceFileName: TString, name of reference file
/// \param referenceSMFileName: TString, name of reference file for SM by SM calib.
/// \param badReconstruction: Bool_t, flag to find L1 shift dur to errors in reconstruction
/// \param fillHeavyHistos: Bool_t, flag to fill heavy histograms with time per channel
/// \param badMapType: Int_t,settype of bad channel map acces
/// \param badMapFileName: TString, file with bad channels map (absID)
///
/// \author Adam Matyja <adam.tomasz.matyja@ifj.edu.pl>, INP PAN Cracow
///
AliAnalysisTaskEMCALTimeCalib * AddTaskEMCALTimeCalibration(TString outputFile = "", // timeResults.root
TString geometryName = "",//EMCAL_COMPLETE12SMV1_DCAL_8SM
Double_t minClusterEne = 1.0,
Double_t maxClusterEne = 500,
Int_t minNcells = 2,
Int_t maxNcells = 200,
Double_t minLambda0LG = 0.1,
Double_t maxLambda0LG = 4.0,
Double_t minLambda0 = 0.1,
Double_t maxLambda0 = 0.4,
Double_t maxRtrack = 0.025,
Double_t minCellEne = 0.4,
Double_t minTime = -20.,
Double_t maxTime = 20.,
Bool_t pileupFromSPDFlag = kFALSE,
TString referenceFileName = "",//Reference.root
TString referenceSMFileName = "",//ReferenceSM.root
Bool_t badReconstruction = kFALSE,
Bool_t fillHeavyHistos = kFALSE,
Int_t badMapType = 0,
TString badMapFileName = "")
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEMCALTimeCalibration", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEMCALTimeCalibration", "This task requires an input event handler");
return NULL;
}
AliAnalysisTaskEMCALTimeCalib *taskmbemcal = new AliAnalysisTaskEMCALTimeCalib("TimeCalibTask");
taskmbemcal->SelectCollisionCandidates(AliVEvent::kEMC1|AliVEvent::kEMC7|AliVEvent::kEMC8|AliVEvent::kEMCEJE|AliVEvent::kEMCEGA);
taskmbemcal->SetGeometryName(geometryName);
taskmbemcal->SetMinClusterEnergy (minClusterEne);
taskmbemcal->SetMaxClusterEnergy (maxClusterEne);
taskmbemcal->SetMinNcells (minNcells);
taskmbemcal->SetMaxNcells (maxNcells);
taskmbemcal->SetMinLambda0 (minLambda0);
taskmbemcal->SetMaxLambda0 (maxLambda0);
taskmbemcal->SetMinLambda0LG (minLambda0LG);
taskmbemcal->SetMaxLambda0LG (maxLambda0LG);
taskmbemcal->SetMaxRtrack (maxRtrack);
taskmbemcal->SetMinCellEnergy (minCellEne);
taskmbemcal->SetMinTime (minTime);
taskmbemcal->SetMaxTime (maxTime);
if(fillHeavyHistos) taskmbemcal->SwithOnFillHeavyHisto();
else taskmbemcal->SwithOffFillHeavyHisto();
// pass1
taskmbemcal->SetRawTimeHisto(400,400.,800.);
// pass2
if(referenceSMFileName.Length()!=0){
taskmbemcal->SetReferenceRunByRunFileName(referenceSMFileName);
taskmbemcal->LoadReferenceRunByRunHistos();
taskmbemcal->SetPassTimeHisto(800,400.,800.);
if(badReconstruction) { //add for runs before LHC15n muon_calo_pass1 in run2
taskmbemcal->SwitchOnBadReco();
taskmbemcal->SetPassTimeHisto(500,-100.,150.);
}
}
//pass3
if(referenceFileName.Length()!=0){
taskmbemcal->SetReferenceFileName(referenceFileName);
taskmbemcal->LoadReferenceHistos();
taskmbemcal->SetPassTimeHisto(1000,-250.,250.);
}
if(pileupFromSPDFlag==kTRUE) taskmbemcal->SwitchOnPileupFromSPD();
else taskmbemcal->SwitchOffPileupFromSPD();
//bad channel map
taskmbemcal->SetBadChannelMapSource(badMapType);
if(badMapType==2) taskmbemcal->SetBadChannelFileName(badMapFileName);
//taskmbemcal->PrintInfo();
if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput = mgr->CreateContainer("chistolist", TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFile.Data());
mgr->AddTask(taskmbemcal);
mgr->ConnectInput (taskmbemcal, 0, cinput1);
mgr->ConnectOutput (taskmbemcal, 1, coutput);
return taskmbemcal;
}
<commit_msg>Add additional control histograms for low gain channels - Adam M.<commit_after>/// \file AddTaskEMCALTimeCalibration.C
/// \brief Configuration of task AliAnalysisTaskEMCALTimeCalib.
///
/// Configuration of task AliAnalysisTaskEMCALTimeCalib
///
/// The parameters for the analysis are:
/// \param outputFile: TString, output file name
/// \param geometryName: TString, geometry name
/// \param minClusterEne: Double_t, minimum cluster energy
/// \param maxClusterEne: Double_t, maximum cluster energy
/// \param minNcells: Int_t, minimum number of cells in cluster
/// \param maxNcells: Int_t, maximum number of cells in cluster
/// \param minLambda0LG: Double_t, minimum cluster lambda0 for cluster with low gain cell
/// \param maxLambda0LG: Double_t, maximum cluster lambda0 for cluster with low gain cell
/// \param minLambda0: Double_t, minimum cluster lambda0
/// \param maxLambda0: Double_t, maximum cluster lambda0
/// \param maxRtrack: Double_t, maximum cluster track distance
/// \param minCellEne: Double_t, minimum cell energy
/// \param referenceFileName: TString, name of reference file
/// \param referenceSMFileName: TString, name of reference file for SM by SM calib.
/// \param badReconstruction: Bool_t, flag to find L1 shift dur to errors in reconstruction
/// \param fillHeavyHistos: Bool_t, flag to fill heavy histograms with time per channel
/// \param badMapType: Int_t,settype of bad channel map acces
/// \param badMapFileName: TString, file with bad channels map (absID)
///
/// \author Adam Matyja <adam.tomasz.matyja@ifj.edu.pl>, INP PAN Cracow
///
AliAnalysisTaskEMCALTimeCalib * AddTaskEMCALTimeCalibration(TString outputFile = "", // timeResults.root
TString geometryName = "",//EMCAL_COMPLETE12SMV1_DCAL_8SM
Double_t minClusterEne = 1.0,
Double_t maxClusterEne = 500,
Int_t minNcells = 2,
Int_t maxNcells = 200,
Double_t minLambda0LG = 0.1,
Double_t maxLambda0LG = 4.0,
Double_t minLambda0 = 0.1,
Double_t maxLambda0 = 0.4,
Double_t maxRtrack = 0.025,
Double_t minCellEne = 0.4,
Double_t minTime = -20.,
Double_t maxTime = 20.,
Bool_t pileupFromSPDFlag = kFALSE,
TString referenceFileName = "",//Reference.root
TString referenceSMFileName = "",//ReferenceSM.root
Bool_t badReconstruction = kFALSE,
Bool_t fillHeavyHistos = kFALSE,
Int_t badMapType = 0,
TString badMapFileName = "")
{
// Get the pointer to the existing analysis manager via the static access method.
//==============================================================================
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr)
{
::Error("AddTaskEMCALTimeCalibration", "No analysis manager to connect to.");
return NULL;
}
// Check the analysis type using the event handlers connected to the analysis manager.
//==============================================================================
if (!mgr->GetInputEventHandler())
{
::Error("AddTaskEMCALTimeCalibration", "This task requires an input event handler");
return NULL;
}
AliAnalysisTaskEMCALTimeCalib *taskmbemcal = new AliAnalysisTaskEMCALTimeCalib("TimeCalibTask");
taskmbemcal->SelectCollisionCandidates(AliVEvent::kEMC1|AliVEvent::kEMC7|AliVEvent::kEMC8|AliVEvent::kEMCEJE|AliVEvent::kEMCEGA);
taskmbemcal->SetGeometryName(geometryName);
taskmbemcal->SetMinClusterEnergy (minClusterEne);
taskmbemcal->SetMaxClusterEnergy (maxClusterEne);
taskmbemcal->SetMinNcells (minNcells);
taskmbemcal->SetMaxNcells (maxNcells);
taskmbemcal->SetMinLambda0 (minLambda0);
taskmbemcal->SetMaxLambda0 (maxLambda0);
taskmbemcal->SetMinLambda0LG (minLambda0LG);
taskmbemcal->SetMaxLambda0LG (maxLambda0LG);
taskmbemcal->SetMaxRtrack (maxRtrack);
taskmbemcal->SetMinCellEnergy (minCellEne);
taskmbemcal->SetMinTime (minTime);
taskmbemcal->SetMaxTime (maxTime);
if(fillHeavyHistos) taskmbemcal->SwithOnFillHeavyHisto();
else taskmbemcal->SwithOffFillHeavyHisto();
// pass1
taskmbemcal->SetRawTimeHisto(200,400.,800.);
taskmbemcal->SetPassTimeHisto (200,400.,800.);
// pass2
if(referenceSMFileName.Length()!=0){
taskmbemcal->SetReferenceRunByRunFileName(referenceSMFileName);
taskmbemcal->LoadReferenceRunByRunHistos();
taskmbemcal->SetPassTimeHisto(800,400.,800.);
if(badReconstruction) { //add for runs before LHC15n muon_calo_pass1 in run2
taskmbemcal->SwitchOnBadReco();
taskmbemcal->SetPassTimeHisto(500,-100.,150.);
}
}
//pass3
if(referenceFileName.Length()!=0){
taskmbemcal->SetReferenceFileName(referenceFileName);
taskmbemcal->LoadReferenceHistos();
taskmbemcal->SetPassTimeHisto(1000,-250.,250.);
}
if(pileupFromSPDFlag==kTRUE) taskmbemcal->SwitchOnPileupFromSPD();
else taskmbemcal->SwitchOffPileupFromSPD();
//bad channel map
taskmbemcal->SetBadChannelMapSource(badMapType);
if(badMapType==2) taskmbemcal->SetBadChannelFileName(badMapFileName);
//taskmbemcal->PrintInfo();
if(outputFile.Length()==0) outputFile = AliAnalysisManager::GetCommonFileName();
// Create containers for input/output
AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
AliAnalysisDataContainer *coutput = mgr->CreateContainer("chistolist", TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFile.Data());
mgr->AddTask(taskmbemcal);
mgr->ConnectInput (taskmbemcal, 0, cinput1);
mgr->ConnectOutput (taskmbemcal, 1, coutput);
return taskmbemcal;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/clock_menu_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/time_format.h"
#include "grit/generated_resources.h"
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton()
: MenuButton(NULL, std::wstring(), this, false),
clock_menu_(this) {
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
UpdateText();
}
void ClockMenuButton::SetNextTimer() {
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateText);
}
void ClockMenuButton::UpdateText() {
base::Time::Exploded now;
base::Time::Now().LocalExplode(&now);
int hour = now.hour % 12;
if (hour == 0)
hour = 12;
std::wstring hour_str = IntToWString(hour);
std::wstring min_str = IntToWString(now.minute);
// Append a "0" before the minute if it's only a single digit.
if (now.minute < 10)
min_str = IntToWString(0) + min_str;
int msg = now.hour < 12 ? IDS_STATUSBAR_CLOCK_SHORT_TIME_AM :
IDS_STATUSBAR_CLOCK_SHORT_TIME_PM;
std::wstring time_string = l10n_util::GetStringF(msg, hour_str, min_str);
SetText(time_string);
SchedulePaint();
SetNextTimer();
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::Menu2Model implementation:
int ClockMenuButton::GetItemCount() const {
return 1;
}
views::Menu2Model::ItemType ClockMenuButton::GetTypeAt(int index) const {
return views::Menu2Model::TYPE_COMMAND;
}
string16 ClockMenuButton::GetLabelAt(int index) const {
return WideToUTF16(base::TimeFormatFriendlyDate(base::Time::Now()));
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt,
gfx::NativeView hwnd) {
clock_menu_.Rebuild();
clock_menu_.UpdateStates();
clock_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
<commit_msg>Fix wrong include to fix the CromeOS build.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/clock_menu_button.h"
#include "app/gfx/canvas.h"
#include "app/gfx/font.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/i18n/time_format.h"
#include "base/string_util.h"
#include "base/time.h"
#include "grit/generated_resources.h"
// Amount of slop to add into the timer to make sure we're into the next minute
// when the timer goes off.
const int kTimerSlopSeconds = 1;
ClockMenuButton::ClockMenuButton()
: MenuButton(NULL, std::wstring(), this, false),
clock_menu_(this) {
SetFont(ResourceBundle::GetSharedInstance().GetFont(
ResourceBundle::BaseFont).DeriveFont(0, gfx::Font::BOLD));
SetEnabledColor(SK_ColorWHITE);
SetShowHighlighted(false);
UpdateText();
}
void ClockMenuButton::SetNextTimer() {
// Try to set the timer to go off at the next change of the minute. We don't
// want to have the timer go off more than necessary since that will cause
// the CPU to wake up and consume power.
base::Time now = base::Time::Now();
base::Time::Exploded exploded;
now.LocalExplode(&exploded);
// Often this will be called at minute boundaries, and we'll actually want
// 60 seconds from now.
int seconds_left = 60 - exploded.second;
if (seconds_left == 0)
seconds_left = 60;
// Make sure that the timer fires on the next minute. Without this, if it is
// called just a teeny bit early, then it will skip the next minute.
seconds_left += kTimerSlopSeconds;
timer_.Start(base::TimeDelta::FromSeconds(seconds_left), this,
&ClockMenuButton::UpdateText);
}
void ClockMenuButton::UpdateText() {
base::Time::Exploded now;
base::Time::Now().LocalExplode(&now);
int hour = now.hour % 12;
if (hour == 0)
hour = 12;
std::wstring hour_str = IntToWString(hour);
std::wstring min_str = IntToWString(now.minute);
// Append a "0" before the minute if it's only a single digit.
if (now.minute < 10)
min_str = IntToWString(0) + min_str;
int msg = now.hour < 12 ? IDS_STATUSBAR_CLOCK_SHORT_TIME_AM :
IDS_STATUSBAR_CLOCK_SHORT_TIME_PM;
std::wstring time_string = l10n_util::GetStringF(msg, hour_str, min_str);
SetText(time_string);
SchedulePaint();
SetNextTimer();
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::Menu2Model implementation:
int ClockMenuButton::GetItemCount() const {
return 1;
}
views::Menu2Model::ItemType ClockMenuButton::GetTypeAt(int index) const {
return views::Menu2Model::TYPE_COMMAND;
}
string16 ClockMenuButton::GetLabelAt(int index) const {
return WideToUTF16(base::TimeFormatFriendlyDate(base::Time::Now()));
}
////////////////////////////////////////////////////////////////////////////////
// ClockMenuButton, views::ViewMenuDelegate implementation:
void ClockMenuButton::RunMenu(views::View* source, const gfx::Point& pt,
gfx::NativeView hwnd) {
clock_menu_.Rebuild();
clock_menu_.UpdateStates();
clock_menu_.RunMenuAt(pt, views::Menu2::ALIGN_TOPRIGHT);
}
<|endoftext|> |
<commit_before>#include "taichi/ir/ir.h"
#include "taichi/ir/transforms.h"
#include "taichi/ir/analysis.h"
#include "taichi/ir/pass.h"
#include "taichi/ir/visitors.h"
#include "taichi/program/compile_config.h"
#include "taichi/program/extension.h"
#include "taichi/program/function.h"
#include "taichi/program/kernel.h"
namespace taichi::lang {
namespace irpass {
namespace {
std::function<void(const std::string &)>
make_pass_printer(bool verbose, const std::string &kernel_name, IRNode *ir) {
if (!verbose) {
return [](const std::string &) {};
}
return [ir, kernel_name](const std::string &pass) {
TI_INFO("[{}] {}:", kernel_name, pass);
std::cout << std::flush;
irpass::re_id(ir);
irpass::print(ir);
std::cout << std::flush;
};
}
} // namespace
void compile_to_offloads(IRNode *ir,
const CompileConfig &config,
Kernel *kernel,
bool verbose,
AutodiffMode autodiff_mode,
bool ad_use_stack,
bool start_from_ast) {
TI_AUTO_PROF;
auto print = make_pass_printer(verbose, kernel->get_name(), ir);
print("Initial IR");
if (autodiff_mode == AutodiffMode::kReverse) {
irpass::reverse_segments(ir);
print("Segment reversed (for autodiff)");
}
if (start_from_ast) {
irpass::frontend_type_check(ir);
irpass::lower_ast(ir);
print("Lowered");
}
if (config.real_matrix && config.real_matrix_scalarize) {
irpass::scalarize(ir);
// Remove redundant MatrixInitStmt inserted during scalarization
irpass::die(ir);
print("Scalarized");
}
irpass::lower_matrix_ptr(ir);
print("Matrix ptr lowered");
irpass::type_check(ir, config);
print("Typechecked");
irpass::analysis::verify(ir);
if (kernel->is_evaluator) {
TI_ASSERT(autodiff_mode == AutodiffMode::kNone);
irpass::demote_operations(ir, config);
print("Operations demoted");
irpass::offload(ir, config);
print("Offloaded");
irpass::analysis::verify(ir);
return;
}
// TODO: strictly enforce bit vectorization for x86 cpu and CUDA now
// create a separate CompileConfig flag for the new pass
if (arch_is_cpu(config.arch) || config.arch == Arch::cuda) {
irpass::bit_loop_vectorize(ir);
irpass::type_check(ir, config);
print("Bit Loop Vectorized");
irpass::analysis::verify(ir);
}
irpass::full_simplify(
ir, config,
{false, /*autodiff_enabled*/ autodiff_mode != AutodiffMode::kNone,
kernel->program});
print("Simplified I");
irpass::analysis::verify(ir);
if (is_extension_supported(config.arch, Extension::mesh)) {
irpass::analysis::gather_meshfor_relation_types(ir);
}
if (config.debug && autodiff_mode == AutodiffMode::kCheckAutodiffValid) {
// Check whether the kernel obeys the autodiff limitation e.g., gloabl data
// access rule
// This check should be performed in the forward kernel i.e., autodiff_mode
// == AutodiffMode::kCheckAutodiffValid
irpass::demote_atomics(ir, config);
irpass::differentiation_validation_check(ir, config, kernel->get_name());
irpass::analysis::verify(ir);
}
if (autodiff_mode != AutodiffMode::kNone) {
// Remove local atomics here so that we don't have to handle their gradients
irpass::demote_atomics(ir, config);
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ true, kernel->program});
irpass::auto_diff(ir, config, autodiff_mode, ad_use_stack);
// TODO: Be carefull with the full_simplify when do high-order autodiff
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Gradient");
irpass::analysis::verify(ir);
}
if (config.check_out_of_bound) {
irpass::check_out_of_bound(ir, config, {kernel->get_name()});
print("Bound checked");
irpass::analysis::verify(ir);
}
irpass::flag_access(ir);
print("Access flagged I");
irpass::analysis::verify(ir);
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified II");
irpass::analysis::verify(ir);
irpass::offload(ir, config);
print("Offloaded");
irpass::analysis::verify(ir);
// TODO: This pass may be redundant as cfg_optimization() is already called
// in full_simplify().
if (config.opt_level > 0 && config.cfg_optimization) {
irpass::cfg_optimization(ir, false, /*autodiff_enabled*/ false,
config.real_matrix);
print("Optimized by CFG");
irpass::analysis::verify(ir);
}
irpass::flag_access(ir);
print("Access flagged II");
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified III");
irpass::analysis::verify(ir);
}
void offload_to_executable(IRNode *ir,
const CompileConfig &config,
Kernel *kernel,
bool verbose,
bool determine_ad_stack_size,
bool lower_global_access,
bool make_thread_local,
bool make_block_local) {
TI_AUTO_PROF;
auto print = make_pass_printer(verbose, kernel->get_name(), ir);
// TODO: This is just a proof that we can demote struct-fors after offloading.
// Eventually we might want the order to be TLS/BLS -> demote struct-for.
// For now, putting this after TLS will disable TLS, because it can only
// handle range-fors at this point.
auto amgr = std::make_unique<AnalysisManager>();
print("Start offload_to_executable");
irpass::analysis::verify(ir);
if (config.detect_read_only) {
irpass::detect_read_only(ir);
print("Detect read-only accesses");
}
irpass::demote_atomics(ir, config);
print("Atomics demoted I");
irpass::analysis::verify(ir);
if (config.cache_loop_invariant_global_vars) {
irpass::cache_loop_invariant_global_vars(ir, config);
print("Cache loop-invariant global vars");
}
if (config.demote_dense_struct_fors) {
irpass::demote_dense_struct_fors(ir, config.packed);
irpass::type_check(ir, config);
print("Dense struct-for demoted");
irpass::analysis::verify(ir);
}
if (is_extension_supported(config.arch, Extension::mesh) &&
config.demote_no_access_mesh_fors) {
irpass::demote_no_access_mesh_fors(ir);
irpass::type_check(ir, config);
print("No-access mesh-for demoted");
irpass::analysis::verify(ir);
}
if (make_thread_local) {
irpass::make_thread_local(ir, config);
print("Make thread local");
}
if (is_extension_supported(config.arch, Extension::mesh)) {
irpass::make_mesh_thread_local(ir, config, {kernel->get_name()});
print("Make mesh thread local");
if (config.make_mesh_block_local && config.arch == Arch::cuda) {
irpass::make_mesh_block_local(ir, config, {kernel->get_name()});
print("Make mesh block local");
irpass::full_simplify(
ir, config, {false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified X");
}
}
if (make_block_local) {
irpass::make_block_local(ir, config, {kernel->get_name()});
print("Make block local");
}
if (is_extension_supported(config.arch, Extension::mesh)) {
irpass::demote_mesh_statements(ir, config, {kernel->get_name()});
print("Demote mesh statements");
}
irpass::demote_atomics(ir, config);
print("Atomics demoted II");
irpass::analysis::verify(ir);
if (is_extension_supported(config.arch, Extension::quant) &&
ir->get_config().quant_opt_atomic_demotion) {
irpass::analysis::gather_uniquely_accessed_bit_structs(ir, amgr.get());
}
irpass::remove_range_assumption(ir);
print("Remove range assumption");
irpass::remove_loop_unique(ir);
print("Remove loop_unique");
irpass::analysis::verify(ir);
if (lower_global_access) {
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified before lower access");
irpass::lower_access(ir, config, {kernel->no_activate, true});
print("Access lowered");
irpass::analysis::verify(ir);
irpass::die(ir);
print("DIE");
irpass::analysis::verify(ir);
irpass::flag_access(ir);
print("Access flagged III");
irpass::analysis::verify(ir);
}
irpass::demote_operations(ir, config);
print("Operations demoted");
irpass::full_simplify(
ir, config,
{lower_global_access, /*autodiff_enabled*/ false, kernel->program});
print("Simplified IV");
if (determine_ad_stack_size) {
irpass::determine_ad_stack_size(ir, config);
print("Autodiff stack size determined");
}
if (is_extension_supported(config.arch, Extension::quant)) {
irpass::optimize_bit_struct_stores(ir, config, amgr.get());
print("Bit struct stores optimized");
}
// Final field registration correctness & type checking
irpass::type_check(ir, config);
irpass::analysis::verify(ir);
}
void compile_to_executable(IRNode *ir,
const CompileConfig &config,
Kernel *kernel,
AutodiffMode autodiff_mode,
bool ad_use_stack,
bool verbose,
bool lower_global_access,
bool make_thread_local,
bool make_block_local,
bool start_from_ast) {
TI_AUTO_PROF;
compile_to_offloads(ir, config, kernel, verbose, autodiff_mode, ad_use_stack,
start_from_ast);
offload_to_executable(
ir, config, kernel, verbose,
/*determine_ad_stack_size=*/autodiff_mode == AutodiffMode::kReverse &&
ad_use_stack,
lower_global_access, make_thread_local, make_block_local);
}
void compile_function(IRNode *ir,
const CompileConfig &config,
Function *func,
AutodiffMode autodiff_mode,
bool verbose,
bool start_from_ast) {
TI_AUTO_PROF;
auto print = make_pass_printer(verbose, func->get_name(), ir);
print("Initial IR");
if (autodiff_mode == AutodiffMode::kReverse) {
irpass::reverse_segments(ir);
print("Segment reversed (for autodiff)");
}
if (start_from_ast) {
irpass::frontend_type_check(ir);
irpass::lower_ast(ir);
print("Lowered");
}
irpass::lower_access(ir, config, {{}, true});
print("Access lowered");
irpass::analysis::verify(ir);
irpass::die(ir);
print("DIE");
irpass::analysis::verify(ir);
irpass::flag_access(ir);
print("Access flagged III");
irpass::analysis::verify(ir);
irpass::type_check(ir, config);
print("Typechecked");
irpass::demote_operations(ir, config);
print("Operations demoted");
irpass::full_simplify(
ir, config, {false, autodiff_mode != AutodiffMode::kNone, func->program});
print("Simplified");
irpass::analysis::verify(ir);
}
} // namespace irpass
} // namespace taichi::lang
<commit_msg>[autodiff] Skip gradient kernel compilation for validation kernel (#6356)<commit_after>#include "taichi/ir/ir.h"
#include "taichi/ir/transforms.h"
#include "taichi/ir/analysis.h"
#include "taichi/ir/pass.h"
#include "taichi/ir/visitors.h"
#include "taichi/program/compile_config.h"
#include "taichi/program/extension.h"
#include "taichi/program/function.h"
#include "taichi/program/kernel.h"
namespace taichi::lang {
namespace irpass {
namespace {
std::function<void(const std::string &)>
make_pass_printer(bool verbose, const std::string &kernel_name, IRNode *ir) {
if (!verbose) {
return [](const std::string &) {};
}
return [ir, kernel_name](const std::string &pass) {
TI_INFO("[{}] {}:", kernel_name, pass);
std::cout << std::flush;
irpass::re_id(ir);
irpass::print(ir);
std::cout << std::flush;
};
}
} // namespace
void compile_to_offloads(IRNode *ir,
const CompileConfig &config,
Kernel *kernel,
bool verbose,
AutodiffMode autodiff_mode,
bool ad_use_stack,
bool start_from_ast) {
TI_AUTO_PROF;
auto print = make_pass_printer(verbose, kernel->get_name(), ir);
print("Initial IR");
if (autodiff_mode == AutodiffMode::kReverse) {
irpass::reverse_segments(ir);
print("Segment reversed (for autodiff)");
}
if (start_from_ast) {
irpass::frontend_type_check(ir);
irpass::lower_ast(ir);
print("Lowered");
}
if (config.real_matrix && config.real_matrix_scalarize) {
irpass::scalarize(ir);
// Remove redundant MatrixInitStmt inserted during scalarization
irpass::die(ir);
print("Scalarized");
}
irpass::lower_matrix_ptr(ir);
print("Matrix ptr lowered");
irpass::type_check(ir, config);
print("Typechecked");
irpass::analysis::verify(ir);
if (kernel->is_evaluator) {
TI_ASSERT(autodiff_mode == AutodiffMode::kNone);
irpass::demote_operations(ir, config);
print("Operations demoted");
irpass::offload(ir, config);
print("Offloaded");
irpass::analysis::verify(ir);
return;
}
// TODO: strictly enforce bit vectorization for x86 cpu and CUDA now
// create a separate CompileConfig flag for the new pass
if (arch_is_cpu(config.arch) || config.arch == Arch::cuda) {
irpass::bit_loop_vectorize(ir);
irpass::type_check(ir, config);
print("Bit Loop Vectorized");
irpass::analysis::verify(ir);
}
irpass::full_simplify(
ir, config,
{false, /*autodiff_enabled*/ autodiff_mode != AutodiffMode::kNone,
kernel->program});
print("Simplified I");
irpass::analysis::verify(ir);
if (is_extension_supported(config.arch, Extension::mesh)) {
irpass::analysis::gather_meshfor_relation_types(ir);
}
if (config.debug && autodiff_mode == AutodiffMode::kCheckAutodiffValid) {
// Check whether the kernel obeys the autodiff limitation e.g., gloabl data
// access rule
// This check should be performed in the forward kernel i.e., autodiff_mode
// == AutodiffMode::kCheckAutodiffValid
irpass::demote_atomics(ir, config);
irpass::differentiation_validation_check(ir, config, kernel->get_name());
irpass::analysis::verify(ir);
}
if (autodiff_mode == AutodiffMode::kReverse ||
autodiff_mode == AutodiffMode::kForward) {
// Remove local atomics here so that we don't have to handle their gradients
irpass::demote_atomics(ir, config);
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ true, kernel->program});
irpass::auto_diff(ir, config, autodiff_mode, ad_use_stack);
// TODO: Be carefull with the full_simplify when do high-order autodiff
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Gradient");
irpass::analysis::verify(ir);
}
if (config.check_out_of_bound) {
irpass::check_out_of_bound(ir, config, {kernel->get_name()});
print("Bound checked");
irpass::analysis::verify(ir);
}
irpass::flag_access(ir);
print("Access flagged I");
irpass::analysis::verify(ir);
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified II");
irpass::analysis::verify(ir);
irpass::offload(ir, config);
print("Offloaded");
irpass::analysis::verify(ir);
// TODO: This pass may be redundant as cfg_optimization() is already called
// in full_simplify().
if (config.opt_level > 0 && config.cfg_optimization) {
irpass::cfg_optimization(ir, false, /*autodiff_enabled*/ false,
config.real_matrix);
print("Optimized by CFG");
irpass::analysis::verify(ir);
}
irpass::flag_access(ir);
print("Access flagged II");
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified III");
irpass::analysis::verify(ir);
}
void offload_to_executable(IRNode *ir,
const CompileConfig &config,
Kernel *kernel,
bool verbose,
bool determine_ad_stack_size,
bool lower_global_access,
bool make_thread_local,
bool make_block_local) {
TI_AUTO_PROF;
auto print = make_pass_printer(verbose, kernel->get_name(), ir);
// TODO: This is just a proof that we can demote struct-fors after offloading.
// Eventually we might want the order to be TLS/BLS -> demote struct-for.
// For now, putting this after TLS will disable TLS, because it can only
// handle range-fors at this point.
auto amgr = std::make_unique<AnalysisManager>();
print("Start offload_to_executable");
irpass::analysis::verify(ir);
if (config.detect_read_only) {
irpass::detect_read_only(ir);
print("Detect read-only accesses");
}
irpass::demote_atomics(ir, config);
print("Atomics demoted I");
irpass::analysis::verify(ir);
if (config.cache_loop_invariant_global_vars) {
irpass::cache_loop_invariant_global_vars(ir, config);
print("Cache loop-invariant global vars");
}
if (config.demote_dense_struct_fors) {
irpass::demote_dense_struct_fors(ir, config.packed);
irpass::type_check(ir, config);
print("Dense struct-for demoted");
irpass::analysis::verify(ir);
}
if (is_extension_supported(config.arch, Extension::mesh) &&
config.demote_no_access_mesh_fors) {
irpass::demote_no_access_mesh_fors(ir);
irpass::type_check(ir, config);
print("No-access mesh-for demoted");
irpass::analysis::verify(ir);
}
if (make_thread_local) {
irpass::make_thread_local(ir, config);
print("Make thread local");
}
if (is_extension_supported(config.arch, Extension::mesh)) {
irpass::make_mesh_thread_local(ir, config, {kernel->get_name()});
print("Make mesh thread local");
if (config.make_mesh_block_local && config.arch == Arch::cuda) {
irpass::make_mesh_block_local(ir, config, {kernel->get_name()});
print("Make mesh block local");
irpass::full_simplify(
ir, config, {false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified X");
}
}
if (make_block_local) {
irpass::make_block_local(ir, config, {kernel->get_name()});
print("Make block local");
}
if (is_extension_supported(config.arch, Extension::mesh)) {
irpass::demote_mesh_statements(ir, config, {kernel->get_name()});
print("Demote mesh statements");
}
irpass::demote_atomics(ir, config);
print("Atomics demoted II");
irpass::analysis::verify(ir);
if (is_extension_supported(config.arch, Extension::quant) &&
ir->get_config().quant_opt_atomic_demotion) {
irpass::analysis::gather_uniquely_accessed_bit_structs(ir, amgr.get());
}
irpass::remove_range_assumption(ir);
print("Remove range assumption");
irpass::remove_loop_unique(ir);
print("Remove loop_unique");
irpass::analysis::verify(ir);
if (lower_global_access) {
irpass::full_simplify(ir, config,
{false, /*autodiff_enabled*/ false, kernel->program});
print("Simplified before lower access");
irpass::lower_access(ir, config, {kernel->no_activate, true});
print("Access lowered");
irpass::analysis::verify(ir);
irpass::die(ir);
print("DIE");
irpass::analysis::verify(ir);
irpass::flag_access(ir);
print("Access flagged III");
irpass::analysis::verify(ir);
}
irpass::demote_operations(ir, config);
print("Operations demoted");
irpass::full_simplify(
ir, config,
{lower_global_access, /*autodiff_enabled*/ false, kernel->program});
print("Simplified IV");
if (determine_ad_stack_size) {
irpass::determine_ad_stack_size(ir, config);
print("Autodiff stack size determined");
}
if (is_extension_supported(config.arch, Extension::quant)) {
irpass::optimize_bit_struct_stores(ir, config, amgr.get());
print("Bit struct stores optimized");
}
// Final field registration correctness & type checking
irpass::type_check(ir, config);
irpass::analysis::verify(ir);
}
void compile_to_executable(IRNode *ir,
const CompileConfig &config,
Kernel *kernel,
AutodiffMode autodiff_mode,
bool ad_use_stack,
bool verbose,
bool lower_global_access,
bool make_thread_local,
bool make_block_local,
bool start_from_ast) {
TI_AUTO_PROF;
compile_to_offloads(ir, config, kernel, verbose, autodiff_mode, ad_use_stack,
start_from_ast);
offload_to_executable(
ir, config, kernel, verbose,
/*determine_ad_stack_size=*/autodiff_mode == AutodiffMode::kReverse &&
ad_use_stack,
lower_global_access, make_thread_local, make_block_local);
}
void compile_function(IRNode *ir,
const CompileConfig &config,
Function *func,
AutodiffMode autodiff_mode,
bool verbose,
bool start_from_ast) {
TI_AUTO_PROF;
auto print = make_pass_printer(verbose, func->get_name(), ir);
print("Initial IR");
if (autodiff_mode == AutodiffMode::kReverse) {
irpass::reverse_segments(ir);
print("Segment reversed (for autodiff)");
}
if (start_from_ast) {
irpass::frontend_type_check(ir);
irpass::lower_ast(ir);
print("Lowered");
}
irpass::lower_access(ir, config, {{}, true});
print("Access lowered");
irpass::analysis::verify(ir);
irpass::die(ir);
print("DIE");
irpass::analysis::verify(ir);
irpass::flag_access(ir);
print("Access flagged III");
irpass::analysis::verify(ir);
irpass::type_check(ir, config);
print("Typechecked");
irpass::demote_operations(ir, config);
print("Operations demoted");
irpass::full_simplify(
ir, config, {false, autodiff_mode != AutodiffMode::kNone, func->program});
print("Simplified");
irpass::analysis::verify(ir);
}
} // namespace irpass
} // namespace taichi::lang
<|endoftext|> |
<commit_before>//===----------- OrcCBindings.cpp - C bindings for the Orc APIs -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "OrcCBindingsStack.h"
#include "llvm-c/OrcBindings.h"
using namespace llvm;
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(OrcCBindingsStack, LLVMOrcJITStackRef);
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef);
LLVMOrcJITStackRef LLVMOrcCreateInstance(LLVMTargetMachineRef TM,
LLVMContextRef Context) {
TargetMachine *TM2(unwrap(TM));
LLVMContext &Ctx = *unwrap(Context);
Triple T(TM2->getTargetTriple());
auto CallbackMgrBuilder = OrcCBindingsStack::createCallbackManagerBuilder(T);
auto IndirectStubsMgrBuilder =
OrcCBindingsStack::createIndirectStubsMgrBuilder(T);
OrcCBindingsStack *JITStack =
new OrcCBindingsStack(*TM2, Ctx, CallbackMgrBuilder,
IndirectStubsMgrBuilder);
return wrap(JITStack);
}
void LLVMOrcGetMangledSymbol(LLVMOrcJITStackRef JITStack, char **MangledName,
const char *SymbolName) {
OrcCBindingsStack &J = *unwrap(JITStack);
std::string Mangled = J.mangle(SymbolName);
*MangledName = new char[Mangled.size() + 1];
strcpy(*MangledName, Mangled.c_str());
}
void LLVMOrcDisposeMangledSymbol(char *MangledName) {
delete[] MangledName;
}
LLVMOrcModuleHandle
LLVMOrcAddEagerlyCompiledIR(LLVMOrcJITStackRef JITStack, LLVMModuleRef Mod,
LLVMOrcSymbolResolverFn SymbolResolver,
void *SymbolResolverCtx) {
OrcCBindingsStack &J = *unwrap(JITStack);
Module *M(unwrap(Mod));
return J.addIRModuleEager(M, SymbolResolver, SymbolResolverCtx);
}
LLVMOrcModuleHandle
LLVMOrcAddLazilyCompiledIR(LLVMOrcJITStackRef JITStack, LLVMModuleRef Mod,
LLVMOrcSymbolResolverFn SymbolResolver,
void *SymbolResolverCtx) {
OrcCBindingsStack &J = *unwrap(JITStack);
Module *M(unwrap(Mod));
return J.addIRModuleLazy(M, SymbolResolver, SymbolResolverCtx);
}
void LLVMOrcRemoveModule(LLVMOrcJITStackRef JITStack, LLVMOrcModuleHandle H) {
OrcCBindingsStack &J = *unwrap(JITStack);
J.removeModule(H);
}
LLVMOrcTargetAddress LLVMOrcGetSymbolAddress(LLVMOrcJITStackRef JITStack,
const char *SymbolName) {
OrcCBindingsStack &J = *unwrap(JITStack);
auto Sym = J.findSymbol(SymbolName, true);
return Sym.getAddress();
}
void LLVMOrcDisposeInstance(LLVMOrcJITStackRef JITStack) {
delete unwrap(JITStack);
}
<commit_msg>[Orc] Remove unnecessary semicolon. NFC.<commit_after>//===----------- OrcCBindings.cpp - C bindings for the Orc APIs -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "OrcCBindingsStack.h"
#include "llvm-c/OrcBindings.h"
using namespace llvm;
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(OrcCBindingsStack, LLVMOrcJITStackRef)
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(TargetMachine, LLVMTargetMachineRef)
LLVMOrcJITStackRef LLVMOrcCreateInstance(LLVMTargetMachineRef TM,
LLVMContextRef Context) {
TargetMachine *TM2(unwrap(TM));
LLVMContext &Ctx = *unwrap(Context);
Triple T(TM2->getTargetTriple());
auto CallbackMgrBuilder = OrcCBindingsStack::createCallbackManagerBuilder(T);
auto IndirectStubsMgrBuilder =
OrcCBindingsStack::createIndirectStubsMgrBuilder(T);
OrcCBindingsStack *JITStack =
new OrcCBindingsStack(*TM2, Ctx, CallbackMgrBuilder,
IndirectStubsMgrBuilder);
return wrap(JITStack);
}
void LLVMOrcGetMangledSymbol(LLVMOrcJITStackRef JITStack, char **MangledName,
const char *SymbolName) {
OrcCBindingsStack &J = *unwrap(JITStack);
std::string Mangled = J.mangle(SymbolName);
*MangledName = new char[Mangled.size() + 1];
strcpy(*MangledName, Mangled.c_str());
}
void LLVMOrcDisposeMangledSymbol(char *MangledName) {
delete[] MangledName;
}
LLVMOrcModuleHandle
LLVMOrcAddEagerlyCompiledIR(LLVMOrcJITStackRef JITStack, LLVMModuleRef Mod,
LLVMOrcSymbolResolverFn SymbolResolver,
void *SymbolResolverCtx) {
OrcCBindingsStack &J = *unwrap(JITStack);
Module *M(unwrap(Mod));
return J.addIRModuleEager(M, SymbolResolver, SymbolResolverCtx);
}
LLVMOrcModuleHandle
LLVMOrcAddLazilyCompiledIR(LLVMOrcJITStackRef JITStack, LLVMModuleRef Mod,
LLVMOrcSymbolResolverFn SymbolResolver,
void *SymbolResolverCtx) {
OrcCBindingsStack &J = *unwrap(JITStack);
Module *M(unwrap(Mod));
return J.addIRModuleLazy(M, SymbolResolver, SymbolResolverCtx);
}
void LLVMOrcRemoveModule(LLVMOrcJITStackRef JITStack, LLVMOrcModuleHandle H) {
OrcCBindingsStack &J = *unwrap(JITStack);
J.removeModule(H);
}
LLVMOrcTargetAddress LLVMOrcGetSymbolAddress(LLVMOrcJITStackRef JITStack,
const char *SymbolName) {
OrcCBindingsStack &J = *unwrap(JITStack);
auto Sym = J.findSymbol(SymbolName, true);
return Sym.getAddress();
}
void LLVMOrcDisposeInstance(LLVMOrcJITStackRef JITStack) {
delete unwrap(JITStack);
}
<|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 "chrome/browser/history/in_memory_database.h"
#include "base/logging.h"
#include "base/string_util.h"
namespace history {
InMemoryDatabase::InMemoryDatabase() : URLDatabase(), db_(NULL) {
}
InMemoryDatabase::~InMemoryDatabase() {
}
bool InMemoryDatabase::InitDB() {
DCHECK(!db_) << "Already initialized!";
if (sqlite3_open(":memory:", &db_) != SQLITE_OK) {
NOTREACHED() << "Cannot open memory database";
return false;
}
statement_cache_ = new SqliteStatementCache(db_);
DBCloseScoper scoper(&db_, &statement_cache_); // closes the DB on error
// No reason to leave data behind in memory when rows are removed.
sqlite3_exec(db_, "PRAGMA auto_vacuum=1", NULL, NULL, NULL);
// Set the database page size to 4K for better performance.
sqlite3_exec(db_, "PRAGMA page_size=4096", NULL, NULL, NULL);
// Ensure this is really an in-memory-only cache.
sqlite3_exec(db_, "PRAGMA temp_store=MEMORY", NULL, NULL, NULL);
// Create the URL table, but leave it empty for now.
if (!CreateURLTable(false)) {
NOTREACHED() << "Unable to create table";
return false;
}
// Succeeded, keep the DB open.
scoper.Detach();
db_closer_.Attach(&db_, &statement_cache_);
return true;
}
bool InMemoryDatabase::InitFromScratch() {
if (!InitDB())
return false;
// InitDB doesn't create the index so in the disk-loading case, it can be
// added afterwards.
CreateMainURLIndex();
return true;
}
bool InMemoryDatabase::InitFromDisk(const std::wstring& history_name) {
if (!InitDB())
return false;
// Attach to the history database on disk. (We can't ATTACH in the middle of
// a transaction.)
SQLStatement attach;
if (attach.prepare(db_, "ATTACH ? AS history") != SQLITE_OK) {
NOTREACHED() << "Unable to attach to history database.";
return false;
}
attach.bind_string(0, WideToUTF8(history_name));
if (attach.step() != SQLITE_DONE) {
NOTREACHED() << "Unable to bind";
return false;
}
// Copy URL data to memory.
if (sqlite3_exec(db_,
"INSERT INTO urls SELECT * FROM history.urls WHERE typed_count > 0",
NULL, NULL, NULL) != SQLITE_OK) {
// Unable to get data from the history database. This is OK, the file may
// just not exist yet.
}
// Detach from the history database on disk.
if (sqlite3_exec(db_, "DETACH history", NULL, NULL, NULL) != SQLITE_OK) {
NOTREACHED() << "Unable to detach from history database.";
return false;
}
// Index the table, this is faster than creating the index first and then
// inserting into it.
CreateMainURLIndex();
return true;
}
sqlite3* InMemoryDatabase::GetDB() {
return db_;
}
SqliteStatementCache& InMemoryDatabase::GetStatementCache() {
return *statement_cache_;
}
} // namespace history
<commit_msg>Metrics for the in-memory DB size to see if we spend too much time loading it, and how big it ends up being.<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 "chrome/browser/history/in_memory_database.h"
#include "base/histogram.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/time.h"
namespace history {
InMemoryDatabase::InMemoryDatabase() : URLDatabase(), db_(NULL) {
}
InMemoryDatabase::~InMemoryDatabase() {
}
bool InMemoryDatabase::InitDB() {
DCHECK(!db_) << "Already initialized!";
if (sqlite3_open(":memory:", &db_) != SQLITE_OK) {
NOTREACHED() << "Cannot open memory database";
return false;
}
statement_cache_ = new SqliteStatementCache(db_);
DBCloseScoper scoper(&db_, &statement_cache_); // closes the DB on error
// No reason to leave data behind in memory when rows are removed.
sqlite3_exec(db_, "PRAGMA auto_vacuum=1", NULL, NULL, NULL);
// Set the database page size to 4K for better performance.
sqlite3_exec(db_, "PRAGMA page_size=4096", NULL, NULL, NULL);
// Ensure this is really an in-memory-only cache.
sqlite3_exec(db_, "PRAGMA temp_store=MEMORY", NULL, NULL, NULL);
// Create the URL table, but leave it empty for now.
if (!CreateURLTable(false)) {
NOTREACHED() << "Unable to create table";
return false;
}
// Succeeded, keep the DB open.
scoper.Detach();
db_closer_.Attach(&db_, &statement_cache_);
return true;
}
bool InMemoryDatabase::InitFromScratch() {
if (!InitDB())
return false;
// InitDB doesn't create the index so in the disk-loading case, it can be
// added afterwards.
CreateMainURLIndex();
return true;
}
bool InMemoryDatabase::InitFromDisk(const std::wstring& history_name) {
if (!InitDB())
return false;
// Attach to the history database on disk. (We can't ATTACH in the middle of
// a transaction.)
SQLStatement attach;
if (attach.prepare(db_, "ATTACH ? AS history") != SQLITE_OK) {
NOTREACHED() << "Unable to attach to history database.";
return false;
}
attach.bind_string(0, WideToUTF8(history_name));
if (attach.step() != SQLITE_DONE) {
NOTREACHED() << "Unable to bind";
return false;
}
// Copy URL data to memory.
base::TimeTicks begin_load = base::TimeTicks::Now();
if (sqlite3_exec(db_,
"INSERT INTO urls SELECT * FROM history.urls WHERE typed_count > 0",
NULL, NULL, NULL) != SQLITE_OK) {
// Unable to get data from the history database. This is OK, the file may
// just not exist yet.
}
base::TimeTicks end_load = base::TimeTicks::Now();
UMA_HISTOGRAM_MEDIUM_TIMES("History.InMemoryDBPopulate",
end_load - begin_load);
UMA_HISTOGRAM_COUNTS("History.InMemoryDBItemCount", sqlite3_changes(db_));
// Detach from the history database on disk.
if (sqlite3_exec(db_, "DETACH history", NULL, NULL, NULL) != SQLITE_OK) {
NOTREACHED() << "Unable to detach from history database.";
return false;
}
// Index the table, this is faster than creating the index first and then
// inserting into it.
CreateMainURLIndex();
return true;
}
sqlite3* InMemoryDatabase::GetDB() {
return db_;
}
SqliteStatementCache& InMemoryDatabase::GetStatementCache() {
return *statement_cache_;
}
} // namespace history
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void handleCorrectGuess(int* streak, int playsLeft)
{
*streak = *streak + 1;
cout << "\n\nYou guessed correct! "<< playsLeft << " plays left, with a streak of " << *streak << "!";
}
void handleIncorrectGuess(int* streak, int playsLeft)
{
*streak = 0;
cout << "\n\nUnlucky, you were wrong! " << playsLeft << " plays left!";
}
int main()
{
int guess;
int playsLeft = 5;
int streak = 0;
char playAgain = 'y';
char cashIn = 'n';
cout <<"\n\n Welcome to Coin Toss Game!!" <<endl;
cout <<"\n\nRules:\nGuess 5 coin tosses in a row to win the 1,000,000 dollar Jackpot.";
cout <<"\nGuess 3 in a row, and cash in for 100 dollars";
while (playAgain =='y')
{
do
{
srand(static_cast<unsigned int>(time(0)));
int coinFace = rand() % 2+1;
cout << "\n\nHeads or Tails? (1 or 2)" <<endl;
cin >> guess;
--playsLeft;
if(coinFace == 1)
{
cout << "\nThe coin landed Heads up!";
if(guess == coinFace)
{
handleCorrectGuess(&streak, playsLeft);
}
else
{
handleIncorrectGuess(&streak, playsLeft);
}
}
else if(coinFace == 2)
{
cout << "\nThe coin landed Tails up! ";
if(guess == coinFace)
{
handleCorrectGuess(&streak, playsLeft);
}
else
{
handleIncorrectGuess(&streak, playsLeft);
}
}
if(streak == 3)
{
cout << "\n\nYou have reached a streak of three!! Cash in?(y/n)";
cin >>cashIn;
}
else if(streak == 5)
{
cashIn = 'y';
}
if(playsLeft == 0)
{
cashIn = 'y';
}
}while (cashIn != 'y');
if(streak == 3 && cashIn == 'y')
{
cout << "\n\nCONGRATULATIONS!!";
cout << "\nYou have cashed in for 100 dollars with a streak of 3!"<<endl;
}
else if(streak == 5 && cashIn == 'y')
{
cout << "\n\nCONGRATULATIONS!!";
cout << "\nYou win the Jackpot of 1,000,000 dollars with a streak of FIVE!!!"<<endl;
}
else if(streak != 5 && cashIn == 'y')
{
cout << "\n\nYou have run out of plays! Better luck next time!"<<endl;
}
cout << "\n\nDo you wish to play again?(y/n)" ;
cin >> playAgain;
playsLeft = 5;
cashIn = 'n';
streak = 0;
}
cout << "\n\nOk, cya!!"<<endl;
return 0;
}
<commit_msg>finished refactoring handling guesses<commit_after>#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
void handleCorrectGuess(int* streak, int playsLeft)
{
*streak = *streak + 1;
cout << "\n\nYou guessed correct! "<< playsLeft << " plays left, with a streak of " << *streak << "!";
}
void handleIncorrectGuess(int* streak, int playsLeft)
{
*streak = 0;
cout << "\n\nUnlucky, you were wrong! " << playsLeft << " plays left!";
}
void checkAndHandleGuess(int guess, int coinFace, int* streak, int playsLeft)
{
if(guess == coinFace)
{
handleCorrectGuess(streak, playsLeft);
}
else
{
handleIncorrectGuess(streak, playsLeft);
}
}
int main()
{
int guess;
int playsLeft = 5;
int streak = 0;
char playAgain = 'y';
char cashIn = 'n';
cout <<"\n\n Welcome to Coin Toss Game!!" <<endl;
cout <<"\n\nRules:\nGuess 5 coin tosses in a row to win the 1,000,000 dollar Jackpot.";
cout <<"\nGuess 3 in a row, and cash in for 100 dollars";
while (playAgain =='y')
{
do
{
srand(static_cast<unsigned int>(time(0)));
int coinFace = rand() % 2+1;
cout << "\n\nHeads or Tails? (1 or 2)" <<endl;
cin >> guess;
--playsLeft;
if(coinFace == 1)
{
cout << "\nThe coin landed Heads up!";
checkAndHandleGuess(guess, coinFace, &streak, playsLeft);
}
else if(coinFace == 2)
{
cout << "\nThe coin landed Tails up! ";
checkAndHandleGuess(guess, coinFace, &streak, playsLeft);
}
if(streak == 3)
{
cout << "\n\nYou have reached a streak of three!! Cash in?(y/n)";
cin >>cashIn;
}
else if(streak == 5)
{
cashIn = 'y';
}
if(playsLeft == 0)
{
cashIn = 'y';
}
}while (cashIn != 'y');
if(streak == 3 && cashIn == 'y')
{
cout << "\n\nCONGRATULATIONS!!";
cout << "\nYou have cashed in for 100 dollars with a streak of 3!"<<endl;
}
else if(streak == 5 && cashIn == 'y')
{
cout << "\n\nCONGRATULATIONS!!";
cout << "\nYou win the Jackpot of 1,000,000 dollars with a streak of FIVE!!!"<<endl;
}
else if(streak != 5 && cashIn == 'y')
{
cout << "\n\nYou have run out of plays! Better luck next time!"<<endl;
}
cout << "\n\nDo you wish to play again?(y/n)" ;
cin >> playAgain;
playsLeft = 5;
cashIn = 'n';
streak = 0;
}
cout << "\n\nOk, cya!!"<<endl;
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CustomAnimationPreset.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:50:54 $
*
* 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 _SD_CUSTOMANIMATIONPRESET_HXX
#define _SD_CUSTOMANIMATIONPRESET_HXX
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_ANIMATIONNODETYPE_HPP_
#include <com/sun/star/animations/AnimationNodeType.hpp>
#endif
#ifndef _UTL_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _SD_CUSTOMANIMATIONEFFECT_HXX
#include <CustomAnimationEffect.hxx>
#endif
namespace sd {
typedef std::hash_map<rtl::OUString, CustomAnimationEffectPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectsSubTypeMap;
typedef std::hash_map<rtl::OUString, rtl::OUString, comphelper::UStringHash, comphelper::UStringEqual> UStringMap;
typedef std::vector< rtl::OUString > UStringList;
class CustomAnimationPreset
{
friend class CustomAnimationPresets;
public:
CustomAnimationPreset( CustomAnimationEffectPtr pEffect );
void add( CustomAnimationEffectPtr pEffect );
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > create( const rtl::OUString& rstrSubType );
const rtl::OUString& getPresetId() const { return maPresetId; }
const rtl::OUString& getProperty() const { return maProperty; }
const rtl::OUString& getLabel() const { return maLabel; }
sal_Int16 getPresetClass() const { return mnPresetClass; }
double getDuration() const { return mfDuration; }
UStringList getSubTypes();
UStringList getProperties() const;
bool hasProperty( const rtl::OUString& rProperty ) const;
bool isTextOnly() const { return mbIsTextOnly; }
private:
rtl::OUString maPresetId;
rtl::OUString maProperty;
sal_Int16 mnPresetClass;
rtl::OUString maLabel;
rtl::OUString maDefaultSubTyp;
double mfDuration;
bool mbIsTextOnly;
EffectsSubTypeMap maSubTypes;
};
typedef boost::shared_ptr< CustomAnimationPreset > CustomAnimationPresetPtr;
typedef std::hash_map<rtl::OUString, CustomAnimationPresetPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectDescriptorMap;
typedef std::vector< CustomAnimationPresetPtr > EffectDescriptorList;
struct PresetCategory
{
rtl::OUString maLabel;
EffectDescriptorList maEffects;
PresetCategory( const rtl::OUString& rLabel, const EffectDescriptorList& rEffects )
: maLabel( rLabel ), maEffects( rEffects ) {}
};
typedef boost::shared_ptr< PresetCategory > PresetCategoryPtr;
typedef std::vector< PresetCategoryPtr > PresetCategoryList;
class CustomAnimationPresets
{
public:
CustomAnimationPresets();
virtual ~CustomAnimationPresets();
void init();
static const CustomAnimationPresets& getCustomAnimationPresets();
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > getRandomPreset( sal_Int16 nPresetClass ) const;
CustomAnimationPresetPtr getEffectDescriptor( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId, const rtl::OUString& rPresetSubType ) const;
const rtl::OUString& getUINameForPresetId( const rtl::OUString& rPresetId ) const;
const rtl::OUString& getUINameForProperty( const rtl::OUString& rProperty ) const;
const PresetCategoryList& getEntrancePresets() const { return maEntrancePresets; }
const PresetCategoryList& getEmphasisPresets() const { return maEmphasisPresets; }
const PresetCategoryList& getExitPresets() const { return maExitPresets; }
const PresetCategoryList& getMotionPathsPresets() const { return maMotionPathsPresets; }
void changePresetSubType( CustomAnimationEffectPtr pEffect, const rtl::OUString& rPresetSubType ) const;
private:
void importEffects();
void importResources();
void importPresets( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xConfigProvider, const rtl::OUString& rNodePath, PresetCategoryList& rPresetMap );
const rtl::OUString& translateName( const rtl::OUString& rId, const UStringMap& rNameMap ) const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxRootNode;
EffectDescriptorMap maEffectDiscriptorMap;
UStringMap maEffectNameMap;
UStringMap maPropertyNameMap;
PresetCategoryList maEntrancePresets;
PresetCategoryList maEmphasisPresets;
PresetCategoryList maExitPresets;
PresetCategoryList maMotionPathsPresets;
static CustomAnimationPresets* mpCustomAnimationPresets;
};
typedef boost::shared_ptr< CustomAnimationPresets > CustomAnimationPresetsPtr;
}
#endif // _SD_CUSTOMANIMATIONEFFECTS_HXX
<commit_msg>#i71977# Missing include added (patch by pjanik).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: CustomAnimationPreset.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2006-11-27 09:39:18 $
*
* 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 _SD_CUSTOMANIMATIONPRESET_HXX
#define _SD_CUSTOMANIMATIONPRESET_HXX
#ifndef BOOST_SHARED_PTR_HPP_INCLUDED
#include <boost/shared_ptr.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_ANIMATIONS_ANIMATIONNODETYPE_HPP_
#include <com/sun/star/animations/AnimationNodeType.hpp>
#endif
#ifndef _UTL_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _SD_CUSTOMANIMATIONEFFECT_HXX
#include <CustomAnimationEffect.hxx>
#endif
#include <hash_map>
namespace sd {
typedef std::hash_map<rtl::OUString, CustomAnimationEffectPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectsSubTypeMap;
typedef std::hash_map<rtl::OUString, rtl::OUString, comphelper::UStringHash, comphelper::UStringEqual> UStringMap;
typedef std::vector< rtl::OUString > UStringList;
class CustomAnimationPreset
{
friend class CustomAnimationPresets;
public:
CustomAnimationPreset( CustomAnimationEffectPtr pEffect );
void add( CustomAnimationEffectPtr pEffect );
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > create( const rtl::OUString& rstrSubType );
const rtl::OUString& getPresetId() const { return maPresetId; }
const rtl::OUString& getProperty() const { return maProperty; }
const rtl::OUString& getLabel() const { return maLabel; }
sal_Int16 getPresetClass() const { return mnPresetClass; }
double getDuration() const { return mfDuration; }
UStringList getSubTypes();
UStringList getProperties() const;
bool hasProperty( const rtl::OUString& rProperty ) const;
bool isTextOnly() const { return mbIsTextOnly; }
private:
rtl::OUString maPresetId;
rtl::OUString maProperty;
sal_Int16 mnPresetClass;
rtl::OUString maLabel;
rtl::OUString maDefaultSubTyp;
double mfDuration;
bool mbIsTextOnly;
EffectsSubTypeMap maSubTypes;
};
typedef boost::shared_ptr< CustomAnimationPreset > CustomAnimationPresetPtr;
typedef std::hash_map<rtl::OUString, CustomAnimationPresetPtr, comphelper::UStringHash, comphelper::UStringEqual> EffectDescriptorMap;
typedef std::vector< CustomAnimationPresetPtr > EffectDescriptorList;
struct PresetCategory
{
rtl::OUString maLabel;
EffectDescriptorList maEffects;
PresetCategory( const rtl::OUString& rLabel, const EffectDescriptorList& rEffects )
: maLabel( rLabel ), maEffects( rEffects ) {}
};
typedef boost::shared_ptr< PresetCategory > PresetCategoryPtr;
typedef std::vector< PresetCategoryPtr > PresetCategoryList;
class CustomAnimationPresets
{
public:
CustomAnimationPresets();
virtual ~CustomAnimationPresets();
void init();
static const CustomAnimationPresets& getCustomAnimationPresets();
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > getRandomPreset( sal_Int16 nPresetClass ) const;
CustomAnimationPresetPtr getEffectDescriptor( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId ) const;
// const AnimationEffect* getEffect( const rtl::OUString& rPresetId, const rtl::OUString& rPresetSubType ) const;
const rtl::OUString& getUINameForPresetId( const rtl::OUString& rPresetId ) const;
const rtl::OUString& getUINameForProperty( const rtl::OUString& rProperty ) const;
const PresetCategoryList& getEntrancePresets() const { return maEntrancePresets; }
const PresetCategoryList& getEmphasisPresets() const { return maEmphasisPresets; }
const PresetCategoryList& getExitPresets() const { return maExitPresets; }
const PresetCategoryList& getMotionPathsPresets() const { return maMotionPathsPresets; }
void changePresetSubType( CustomAnimationEffectPtr pEffect, const rtl::OUString& rPresetSubType ) const;
private:
void importEffects();
void importResources();
void importPresets( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xConfigProvider, const rtl::OUString& rNodePath, PresetCategoryList& rPresetMap );
const rtl::OUString& translateName( const rtl::OUString& rId, const UStringMap& rNameMap ) const;
private:
::com::sun::star::uno::Reference< ::com::sun::star::animations::XAnimationNode > mxRootNode;
EffectDescriptorMap maEffectDiscriptorMap;
UStringMap maEffectNameMap;
UStringMap maPropertyNameMap;
PresetCategoryList maEntrancePresets;
PresetCategoryList maEmphasisPresets;
PresetCategoryList maExitPresets;
PresetCategoryList maMotionPathsPresets;
static CustomAnimationPresets* mpCustomAnimationPresets;
};
typedef boost::shared_ptr< CustomAnimationPresets > CustomAnimationPresetsPtr;
}
#endif // _SD_CUSTOMANIMATIONEFFECTS_HXX
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstring>
#include <algorithm>
#include <limits>
#include <glm/glm.hpp>
#include <vtkType.h>
#include <vtkDataSetAttributes.h>
#include <vtkDataSet.h>
#include "glt/util.h"
#include "volume.h"
static const std::array<float, 42> CUBE_STRIP = {
1, 1, 0,
0, 1, 0,
1, 1, 1,
0, 1, 1,
0, 0, 1,
0, 1, 0,
0, 0, 0,
1, 1, 0,
1, 0, 0,
1, 1, 1,
1, 0, 1,
0, 0, 1,
1, 0, 0,
0, 0, 0
};
static void vtk_type_to_gl(const int vtk, GLenum &gl_internal, GLenum &gl_type, GLenum &pixel_format) {
pixel_format = GL_RED;
switch (vtk) {
case VTK_CHAR:
case VTK_UNSIGNED_CHAR:
gl_internal = GL_R8;
gl_type = GL_UNSIGNED_BYTE;
break;
case VTK_FLOAT:
gl_internal = GL_R32F;
gl_type = GL_FLOAT;
break;
case VTK_INT:
gl_internal = GL_R32I;
gl_type = GL_INT;
pixel_format = GL_RED_INTEGER;
break;
default:
throw std::runtime_error("Unsupported VTK data type '" + std::to_string(vtk) + "'");
}
}
Volume::Volume(vtkImageData *vol, const std::string &array_name)
: vol_data(vol), uploaded(false), isovalue(0.f), show_isosurface(false),
transform_dirty(true), translation(0), scaling(1)
{
vtkDataSetAttributes *fields = vol->GetAttributes(vtkDataSet::POINT);
int idx = 0;
vtk_data = fields->GetArray(array_name.c_str(), idx);
if (!vtk_data) {
throw std::runtime_error("Nonexistant field '" + array_name + "'");
}
std::cout << "FIELD DATA for VOLUME\n";
vtk_data->PrintSelf(std::cout, vtkIndent(2));
std::cout << "-----\n";
vtk_type_to_gl(vtk_data->GetDataType(), internal_format, format, pixel_format);
for (size_t i = 0; i < 3; ++i) {
dims[i] = vol->GetDimensions()[i];
vol_render_size[i] = vol->GetSpacing()[i];
}
std::cout << "dims = { " << dims[0] << ", " << dims[1] << ", " << dims[2] << " }\n";
// Center the volume in the world
translate(glm::vec3(vol_render_size[0], vol_render_size[1], vol_render_size[2])
* glm::vec3(-0.5));
build_histogram();
}
Volume::~Volume(){
if (allocator){
allocator->free(cube_buf);
allocator->free(vol_props);
glDeleteVertexArrays(1, &vao);
glDeleteTextures(1, &texture);
glDeleteProgram(shader);
}
}
void Volume::translate(const glm::vec3 &v){
translation += v;
transform_dirty = true;
}
void Volume::scale(const glm::vec3 &v){
scaling *= v;
transform_dirty = true;
}
void Volume::rotate(const glm::quat &r){
rotation = r * rotation;
transform_dirty = true;
}
void Volume::set_base_matrix(const glm::mat4 &m){
base_matrix = m;
transform_dirty = true;
}
void Volume::render(std::shared_ptr<glt::BufferAllocator> &buf_allocator) {
// We need to apply the inverse volume transform to the eye to get it in the volume's space
glm::mat4 vol_transform = glm::translate(translation) * glm::mat4_cast(rotation)
* glm::scale(scaling * vol_render_size) * base_matrix;
// Setup shaders, vao and volume texture
if (!allocator){
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
allocator = buf_allocator;
// Setup our cube tri strip to draw the bounds of the volume to raycast against
cube_buf = buf_allocator->alloc(sizeof(float) * CUBE_STRIP.size());
{
float *buf = reinterpret_cast<float*>(cube_buf.map(GL_ARRAY_BUFFER,
GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT));
for (size_t i = 0; i < CUBE_STRIP.size(); ++i){
buf[i] = CUBE_STRIP[i];
}
cube_buf.unmap(GL_ARRAY_BUFFER);
}
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)cube_buf.offset);
vol_props = buf_allocator->alloc(2 * sizeof(glm::mat4) + sizeof(glm::vec4) + sizeof(glm::vec2),
glt::BufAlignment::UNIFORM_BUFFER);
{
char *buf = reinterpret_cast<char*>(vol_props.map(GL_UNIFORM_BUFFER,
GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT));
glm::mat4 *mats = reinterpret_cast<glm::mat4*>(buf);
glm::vec4 *vecs = reinterpret_cast<glm::vec4*>(buf + 2 * sizeof(glm::mat4));
glm::vec2 *scale_bias = reinterpret_cast<glm::vec2*>(buf + 2 * sizeof(glm::mat4) + sizeof(glm::vec4));
mats[0] = vol_transform;
mats[1] = glm::inverse(mats[0]);
vecs[0] = glm::vec4{static_cast<float>(dims[0]), static_cast<float>(dims[1]),
static_cast<float>(dims[2]), 0};
// Set scaling and bias to scale the volume values
*scale_bias = glm::vec2{1.f / (vol_max - vol_min), -vol_min};
// TODO: Again how will this interact with multiple folks doing this?
glBindBufferRange(GL_UNIFORM_BUFFER, 1, vol_props.buffer, vol_props.offset, vol_props.size);
vol_props.unmap(GL_UNIFORM_BUFFER);
transform_dirty = false;
}
glGenTextures(1, &texture);
// TODO: If drawing multiple volumes they can all share the same program
const std::string resource_path = glt::get_resource_path();
shader = glt::load_program({std::make_pair(GL_VERTEX_SHADER, resource_path + "vol_vert.glsl"),
std::make_pair(GL_FRAGMENT_SHADER, resource_path + "vol_frag.glsl")});
glUseProgram(shader);
// TODO: how does this interact with having multiple volumes? should we just
// have GL4.5 as a hard requirement for DSA? Can I get 4.5 on my laptop?
glUniform1i(glGetUniformLocation(shader, "volume"), 1);
glUniform1i(glGetUniformLocation(shader, "ivolume"), 1);
glUniform1i(glGetUniformLocation(shader, "int_texture"), pixel_format == GL_RED_INTEGER ? 1 : 0);
glUniform1i(glGetUniformLocation(shader, "palette"), 2);
isovalue_unif = glGetUniformLocation(shader, "isovalue");
isosurface_unif = glGetUniformLocation(shader, "isosurface");
}
// Upload the volume data, it's changed
if (!uploaded){
uploaded = true;
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_3D, texture);
glTexImage3D(GL_TEXTURE_3D, 0, internal_format, dims[0], dims[1], dims[2], 0, pixel_format,
format, vtk_data->GetVoidPointer(0));
if (pixel_format == GL_RED_INTEGER) {
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
} else {
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
// We're changing the volume so also update the volume properties buffer
{
char *buf = reinterpret_cast<char*>(vol_props.map(GL_UNIFORM_BUFFER, GL_MAP_WRITE_BIT));
glm::mat4 *mats = reinterpret_cast<glm::mat4*>(buf);
glm::vec4 *vecs = reinterpret_cast<glm::vec4*>(buf + 2 * sizeof(glm::mat4));
glm::vec2 *scale_bias = reinterpret_cast<glm::vec2*>(buf + 2 * sizeof(glm::mat4) + sizeof(glm::vec4));
mats[0] = vol_transform;
mats[1] = glm::inverse(mats[0]);
vecs[0] = glm::vec4{ static_cast<float>(dims[0]), static_cast<float>(dims[1]),
static_cast<float>(dims[2]), 0 };
// Set scaling and bias to scale the volume values
*scale_bias = glm::vec2{1.f / (vol_max - vol_min), -vol_min};
vol_props.unmap(GL_UNIFORM_BUFFER);
transform_dirty = false;
}
}
if (transform_dirty){
char *buf = reinterpret_cast<char*>(vol_props.map(GL_UNIFORM_BUFFER, GL_MAP_WRITE_BIT));
glm::mat4 *mats = reinterpret_cast<glm::mat4*>(buf);
mats[0] = vol_transform;
mats[1] = glm::inverse(mats[0]);
vol_props.unmap(GL_UNIFORM_BUFFER);
transform_dirty = false;
}
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glBindBufferRange(GL_UNIFORM_BUFFER, 1, vol_props.buffer, vol_props.offset, vol_props.size);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_3D, texture);
glUseProgram(shader);
glUniform1f(isovalue_unif, isovalue);
glUniform1i(isosurface_unif, show_isosurface ? 1 : 0);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLE_STRIP, 0, CUBE_STRIP.size() / 3);
glCullFace(GL_BACK);
glDisable(GL_CULL_FACE);
}
void Volume::set_isovalue(float i) {
isovalue = i;
}
void Volume::toggle_isosurface(bool on) {
show_isosurface = on;
}
void Volume::build_histogram(){
// Find scale & bias for the volume data
// For non f32 or f16 textures GL will normalize for us, given that we've done
// the proper range correction above if needed (e.g. for R16)
if (internal_format == GL_R8) {
std::cout << "Setting gl min max to {0, 1} for R8 data\n";
vol_min = 0;
vol_max = 1;
} else {
// Find the min/max values in the volume
vol_min = vtk_data->GetRange()[0];
vol_max = vtk_data->GetRange()[1];
std::cout << "Found min max = {" << vol_min << ", " << vol_max << "}\n";
}
// Build the histogram for the data
histogram.clear();
histogram.resize(128, 0);
const size_t num_voxels = dims[0] * dims[1] * dims[2];
if (format == GL_FLOAT){
float *data_ptr = reinterpret_cast<float*>(vtk_data->GetVoidPointer(0));
for (size_t i = 0; i < num_voxels; ++i){
size_t bin = static_cast<size_t>((data_ptr[i] - vol_min) / (vol_max - vol_min) * histogram.size());
bin = glm::clamp(bin, size_t{0}, histogram.size() - 1);
++histogram[bin];
}
} else if (format == GL_INT){
int32_t *data_ptr = reinterpret_cast<int32_t*>(vtk_data->GetVoidPointer(0));
for (size_t i = 0; i < num_voxels; ++i){
size_t bin = static_cast<size_t>(static_cast<float>(data_ptr[i] - vol_min)
/ (vol_max - vol_min) * histogram.size());
bin = glm::clamp(bin, size_t{0}, histogram.size() - 1);
++histogram[bin];
}
} else if (format == GL_UNSIGNED_BYTE){
uint8_t *data_ptr = reinterpret_cast<uint8_t*>(vtk_data->GetVoidPointer(0));
for (size_t i = 0; i < num_voxels; ++i){
size_t bin = static_cast<size_t>((data_ptr[i] - vol_min) / (vol_max - vol_min) * histogram.size());
bin = glm::clamp(bin, size_t{0}, histogram.size() - 1);
++histogram[bin];
}
}
}
<commit_msg>vtk doing some bullshit<commit_after>#include <iostream>
#include <cstring>
#include <algorithm>
#include <limits>
#include <glm/glm.hpp>
#include <vtkType.h>
#include <vtkDataSetAttributes.h>
#include <vtkDataSet.h>
#include "glt/util.h"
#include "volume.h"
static const std::array<float, 42> CUBE_STRIP = {
1, 1, 0,
0, 1, 0,
1, 1, 1,
0, 1, 1,
0, 0, 1,
0, 1, 0,
0, 0, 0,
1, 1, 0,
1, 0, 0,
1, 1, 1,
1, 0, 1,
0, 0, 1,
1, 0, 0,
0, 0, 0
};
static void vtk_type_to_gl(const int vtk, GLenum &gl_internal, GLenum &gl_type, GLenum &pixel_format) {
pixel_format = GL_RED;
switch (vtk) {
case VTK_CHAR:
case VTK_UNSIGNED_CHAR:
gl_internal = GL_R8;
gl_type = GL_UNSIGNED_BYTE;
break;
case VTK_FLOAT:
gl_internal = GL_R32F;
gl_type = GL_FLOAT;
break;
case VTK_INT:
gl_internal = GL_R32I;
gl_type = GL_INT;
pixel_format = GL_RED_INTEGER;
break;
default:
throw std::runtime_error("Unsupported VTK data type '" + std::to_string(vtk) + "'");
}
}
Volume::Volume(vtkImageData *vol, const std::string &array_name)
: vol_data(vol), uploaded(false), isovalue(0.f), show_isosurface(false),
transform_dirty(true), translation(0), scaling(1)
{
vtkDataSetAttributes *fields = vol->GetAttributes(vtkDataSet::POINT);
int idx = 0;
vtk_data = fields->GetArray(array_name.c_str(), idx);
if (!vtk_data) {
throw std::runtime_error("Nonexistant field '" + array_name + "'");
}
std::cout << "FIELD DATA for VOLUME\n";
vtk_data->PrintSelf(std::cout, vtkIndent(2));
std::cout << "-----\n";
vtk_type_to_gl(vtk_data->GetDataType(), internal_format, format, pixel_format);
for (size_t i = 0; i < 3; ++i) {
dims[i] = vol->GetDimensions()[i];
vol_render_size[i] = vol->GetSpacing()[i];
}
std::cout << "dims = { " << dims[0] << ", " << dims[1] << ", " << dims[2] << " }\n";
// Center the volume in the world
translate(glm::vec3(vol_render_size[0], vol_render_size[1], vol_render_size[2])
* glm::vec3(-0.5));
build_histogram();
}
Volume::~Volume(){
if (allocator){
allocator->free(cube_buf);
allocator->free(vol_props);
glDeleteVertexArrays(1, &vao);
glDeleteTextures(1, &texture);
glDeleteProgram(shader);
}
}
void Volume::translate(const glm::vec3 &v){
translation += v;
transform_dirty = true;
}
void Volume::scale(const glm::vec3 &v){
scaling *= v;
transform_dirty = true;
}
void Volume::rotate(const glm::quat &r){
rotation = r * rotation;
transform_dirty = true;
}
void Volume::set_base_matrix(const glm::mat4 &m){
base_matrix = m;
transform_dirty = true;
}
void Volume::render(std::shared_ptr<glt::BufferAllocator> &buf_allocator) {
// We need to apply the inverse volume transform to the eye to get it in the volume's space
glm::mat4 vol_transform = glm::translate(translation) * glm::mat4_cast(rotation)
* glm::scale(scaling * vol_render_size) * base_matrix;
// Setup shaders, vao and volume texture
if (!allocator){
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
allocator = buf_allocator;
// Setup our cube tri strip to draw the bounds of the volume to raycast against
cube_buf = buf_allocator->alloc(sizeof(float) * CUBE_STRIP.size());
{
float *buf = reinterpret_cast<float*>(cube_buf.map(GL_ARRAY_BUFFER,
GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT));
for (size_t i = 0; i < CUBE_STRIP.size(); ++i){
buf[i] = CUBE_STRIP[i];
}
cube_buf.unmap(GL_ARRAY_BUFFER);
}
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)cube_buf.offset);
vol_props = buf_allocator->alloc(2 * sizeof(glm::mat4) + sizeof(glm::vec4) + sizeof(glm::vec2),
glt::BufAlignment::UNIFORM_BUFFER);
{
char *buf = reinterpret_cast<char*>(vol_props.map(GL_UNIFORM_BUFFER,
GL_MAP_INVALIDATE_RANGE_BIT | GL_MAP_WRITE_BIT));
glm::mat4 *mats = reinterpret_cast<glm::mat4*>(buf);
glm::vec4 *vecs = reinterpret_cast<glm::vec4*>(buf + 2 * sizeof(glm::mat4));
glm::vec2 *scale_bias = reinterpret_cast<glm::vec2*>(buf + 2 * sizeof(glm::mat4) + sizeof(glm::vec4));
mats[0] = vol_transform;
mats[1] = glm::inverse(mats[0]);
vecs[0] = glm::vec4{static_cast<float>(dims[0]), static_cast<float>(dims[1]),
static_cast<float>(dims[2]), 0};
// Set scaling and bias to scale the volume values
*scale_bias = glm::vec2{1.f / (vol_max - vol_min), -vol_min};
// TODO: Again how will this interact with multiple folks doing this?
glBindBufferRange(GL_UNIFORM_BUFFER, 1, vol_props.buffer, vol_props.offset, vol_props.size);
vol_props.unmap(GL_UNIFORM_BUFFER);
transform_dirty = false;
}
glGenTextures(1, &texture);
// TODO: If drawing multiple volumes they can all share the same program
const std::string resource_path = glt::get_resource_path();
shader = glt::load_program({std::make_pair(GL_VERTEX_SHADER, resource_path + "vol_vert.glsl"),
std::make_pair(GL_FRAGMENT_SHADER, resource_path + "vol_frag.glsl")});
glUseProgram(shader);
// TODO: how does this interact with having multiple volumes? should we just
// have GL4.5 as a hard requirement for DSA? Can I get 4.5 on my laptop?
glUniform1i(glGetUniformLocation(shader, "volume"), 1);
glUniform1i(glGetUniformLocation(shader, "ivolume"), 1);
glUniform1i(glGetUniformLocation(shader, "int_texture"), pixel_format == GL_RED_INTEGER ? 1 : 0);
glUniform1i(glGetUniformLocation(shader, "palette"), 2);
isovalue_unif = glGetUniformLocation(shader, "isovalue");
isosurface_unif = glGetUniformLocation(shader, "isosurface");
}
// Upload the volume data, it's changed
if (!uploaded){
uploaded = true;
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_3D, texture);
// VTK may have not exported the image in the right row-major ordering so make sure
// the pixels are in the right order here.
{
#if 0
// TODO: Doesn't work re-ordering the data this way but code seems right??
const size_t dtype_size = vtk_data->GetDataTypeSize();
std::vector<uint8_t> img_bytes(dims[0] * dims[1] * dims[2] * dtype_size, 0);
std::cout << "# bytes in img " << img_bytes.size() << "\n";
std::cout << "dtype size = " << dtype_size << "\n";
for (size_t z = 0; z < dims[2]; ++z) {
for (size_t y = 0; y < dims[1]; ++y) {
for (size_t x = 0; x < dims[0]; ++x) {
const size_t i = x + dims[0] * (y + dims[1] * z);
const uint8_t *byte_data = static_cast<const uint8_t*>(vtk_data->GetVoidPointer(i));
for (size_t b = 0; b < dtype_size; ++b) {
img_bytes[i * dtype_size + b] = byte_data[b];
}
}
}
}
glTexImage3D(GL_TEXTURE_3D, 0, internal_format, dims[0], dims[1], dims[2], 0, pixel_format,
format, img_bytes.data());
#else
glTexImage3D(GL_TEXTURE_3D, 0, internal_format, dims[0], dims[1], dims[2], 0, pixel_format,
format, NULL);
for (size_t z = 0; z < dims[2]; ++z) {
for (size_t y = 0; y < dims[1]; ++y) {
for (size_t x = 0; x < dims[0]; ++x) {
glTexSubImage3D(GL_TEXTURE_3D, 0, x, y, z, 1, 1, 1, pixel_format,
format, static_cast<void*>(vtk_data->GetVoidPointer(x + dims[0] * (y + dims[1] * z))));
}
}
}
#endif
}
if (pixel_format == GL_RED_INTEGER) {
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
} else {
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_BORDER);
// We're changing the volume so also update the volume properties buffer
{
char *buf = reinterpret_cast<char*>(vol_props.map(GL_UNIFORM_BUFFER, GL_MAP_WRITE_BIT));
glm::mat4 *mats = reinterpret_cast<glm::mat4*>(buf);
glm::vec4 *vecs = reinterpret_cast<glm::vec4*>(buf + 2 * sizeof(glm::mat4));
glm::vec2 *scale_bias = reinterpret_cast<glm::vec2*>(buf + 2 * sizeof(glm::mat4) + sizeof(glm::vec4));
mats[0] = vol_transform;
mats[1] = glm::inverse(mats[0]);
vecs[0] = glm::vec4{ static_cast<float>(dims[0]), static_cast<float>(dims[1]),
static_cast<float>(dims[2]), 0 };
// Set scaling and bias to scale the volume values
*scale_bias = glm::vec2{1.f / (vol_max - vol_min), -vol_min};
vol_props.unmap(GL_UNIFORM_BUFFER);
transform_dirty = false;
}
}
if (transform_dirty){
char *buf = reinterpret_cast<char*>(vol_props.map(GL_UNIFORM_BUFFER, GL_MAP_WRITE_BIT));
glm::mat4 *mats = reinterpret_cast<glm::mat4*>(buf);
mats[0] = vol_transform;
mats[1] = glm::inverse(mats[0]);
vol_props.unmap(GL_UNIFORM_BUFFER);
transform_dirty = false;
}
glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glBindBufferRange(GL_UNIFORM_BUFFER, 1, vol_props.buffer, vol_props.offset, vol_props.size);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_3D, texture);
glUseProgram(shader);
glUniform1f(isovalue_unif, isovalue);
glUniform1i(isosurface_unif, show_isosurface ? 1 : 0);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLE_STRIP, 0, CUBE_STRIP.size() / 3);
glCullFace(GL_BACK);
glDisable(GL_CULL_FACE);
}
void Volume::set_isovalue(float i) {
isovalue = i;
}
void Volume::toggle_isosurface(bool on) {
show_isosurface = on;
}
void Volume::build_histogram(){
// Find scale & bias for the volume data
// For non f32 or f16 textures GL will normalize for us, given that we've done
// the proper range correction above if needed (e.g. for R16)
if (internal_format == GL_R8) {
std::cout << "Setting gl min max to {0, 1} for R8 data\n";
vol_min = 0;
vol_max = 1;
} else {
// Find the min/max values in the volume
vol_min = vtk_data->GetRange()[0];
vol_max = vtk_data->GetRange()[1];
std::cout << "Found min max = {" << vol_min << ", " << vol_max << "}\n";
}
// Build the histogram for the data
histogram.clear();
histogram.resize(128, 0);
const size_t num_voxels = dims[0] * dims[1] * dims[2];
if (format == GL_FLOAT){
float *data_ptr = reinterpret_cast<float*>(vtk_data->GetVoidPointer(0));
for (size_t i = 0; i < num_voxels; ++i){
size_t bin = static_cast<size_t>((data_ptr[i] - vol_min) / (vol_max - vol_min) * histogram.size());
bin = glm::clamp(bin, size_t{0}, histogram.size() - 1);
++histogram[bin];
}
} else if (format == GL_INT){
int32_t *data_ptr = reinterpret_cast<int32_t*>(vtk_data->GetVoidPointer(0));
for (size_t i = 0; i < num_voxels; ++i){
size_t bin = static_cast<size_t>(static_cast<float>(data_ptr[i] - vol_min)
/ (vol_max - vol_min) * histogram.size());
bin = glm::clamp(bin, size_t{0}, histogram.size() - 1);
++histogram[bin];
}
} else if (format == GL_UNSIGNED_BYTE){
uint8_t *data_ptr = reinterpret_cast<uint8_t*>(vtk_data->GetVoidPointer(0));
const float data_min = vtk_data->GetRange()[0];
const float data_max = vtk_data->GetRange()[1];
for (size_t i = 0; i < num_voxels; ++i){
size_t bin = static_cast<size_t>((data_ptr[i] - data_min) / (data_max - data_min) * histogram.size());
bin = glm::clamp(bin, size_t{0}, histogram.size() - 1);
++histogram[bin];
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2019 Istio 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 "extensions/common/context.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "extensions/common/node_info_bfbs_generated.h"
#include "extensions/common/util.h"
// WASM_PROLOG
#ifndef NULL_PLUGIN
#include "proxy_wasm_intrinsics.h"
#else // NULL_PLUGIN
#include "absl/strings/str_split.h"
#include "include/proxy-wasm/null_plugin.h"
using proxy_wasm::WasmHeaderMapType;
using proxy_wasm::null_plugin::getHeaderMapValue;
using proxy_wasm::null_plugin::getValue;
#endif // NULL_PLUGIN
// END WASM_PROLOG
namespace Wasm {
namespace Common {
const char kBlackHoleCluster[] = "BlackHoleCluster";
const char kPassThroughCluster[] = "PassthroughCluster";
const char kBlackHoleRouteName[] = "block_all";
const char kPassThroughRouteName[] = "allow_any";
const char kInboundPassthroughClusterIpv4[] = "InboundPassthroughClusterIpv4";
const char kInboundPassthroughClusterIpv6[] = "InboundPassthroughClusterIpv6";
namespace {
// Extract service name from service host.
void extractServiceName(const std::string& host,
const std::string& destination_namespace,
std::string* service_name) {
auto name_pos = host.find_first_of(".:");
if (name_pos == std::string::npos) {
// host is already a short service name. return it directly.
*service_name = host;
return;
}
if (host[name_pos] == ':') {
// host is `short_service:port`, return short_service name.
*service_name = host.substr(0, name_pos);
return;
}
auto namespace_pos = host.find_first_of(".:", name_pos + 1);
std::string service_namespace = "";
if (namespace_pos == std::string::npos) {
service_namespace = host.substr(name_pos + 1);
} else {
int namespace_size = namespace_pos - name_pos - 1;
service_namespace = host.substr(name_pos + 1, namespace_size);
}
// check if namespace in host is same as destination namespace.
// If it is the same, return the first part of host as service name.
// Otherwise fallback to request host.
if (service_namespace == destination_namespace) {
*service_name = host.substr(0, name_pos);
} else {
*service_name = host;
}
}
// Get destination service host and name based on destination cluster name and
// host header.
// * If cluster name is one of passthrough and blackhole clusters, use cluster
// name as destination service name and host header as destination host.
// * If cluster name follows Istio convention (four parts separated by pipe),
// use the last part as destination host; Otherwise, use host header as
// destination host. To get destination service name from host: if destination
// host is already a short name, use that as destination service; otherwise if
// the second part of destination host is destination namespace, use first
// part as destination service name. Otherwise, fallback to use destination
// host for destination service name.
void getDestinationService(const std::string& dest_namespace,
bool use_host_header, std::string* dest_svc_host,
std::string* dest_svc_name,
const std::string& cluster_name,
const std::string& route_name) {
*dest_svc_host = use_host_header
? getHeaderMapValue(WasmHeaderMapType::RequestHeaders,
kAuthorityHeaderKey)
->toString()
: "unknown";
// override the cluster name if this is being sent to the
// blackhole or passthrough cluster
if (route_name == kBlackHoleRouteName) {
*dest_svc_name = kBlackHoleCluster;
return;
} else if (route_name == kPassThroughRouteName) {
*dest_svc_name = kPassThroughCluster;
return;
}
if (cluster_name == kInboundPassthroughClusterIpv4 ||
cluster_name == kInboundPassthroughClusterIpv6) {
*dest_svc_name = cluster_name;
return;
}
std::vector<absl::string_view> parts = absl::StrSplit(cluster_name, '|');
if (parts.size() == 4) {
*dest_svc_host = std::string(parts[3].data(), parts[3].size());
}
extractServiceName(*dest_svc_host, dest_namespace, dest_svc_name);
}
void populateRequestInfo(bool outbound, bool use_host_header_fallback,
RequestInfo* request_info,
const std::string& destination_namespace) {
request_info->is_populated = true;
getValue({"cluster_name"}, &request_info->upstream_cluster);
getValue({"route_name"}, &request_info->route_name);
// Fill in request info.
// Get destination service name and host based on cluster name and host
// header.
getDestinationService(destination_namespace, use_host_header_fallback,
&request_info->destination_service_host,
&request_info->destination_service_name,
request_info->upstream_cluster,
request_info->route_name);
getValue({"request", "url_path"}, &request_info->request_url_path);
uint64_t destination_port = 0;
if (outbound) {
getValue({"upstream", "port"}, &destination_port);
getValue({"upstream", "uri_san_peer_certificate"},
&request_info->destination_principal);
getValue({"upstream", "uri_san_local_certificate"},
&request_info->source_principal);
} else {
getValue({"destination", "port"}, &destination_port);
bool mtls = false;
if (getValue({"connection", "mtls"}, &mtls)) {
request_info->service_auth_policy =
mtls ? ::Wasm::Common::ServiceAuthenticationPolicy::MutualTLS
: ::Wasm::Common::ServiceAuthenticationPolicy::None;
}
getValue({"connection", "uri_san_local_certificate"},
&request_info->destination_principal);
getValue({"connection", "uri_san_peer_certificate"},
&request_info->source_principal);
}
request_info->destination_port = destination_port;
uint64_t response_flags = 0;
getValue({"response", "flags"}, &response_flags);
request_info->response_flag = parseResponseFlag(response_flags);
}
} // namespace
StringView AuthenticationPolicyString(ServiceAuthenticationPolicy policy) {
switch (policy) {
case ServiceAuthenticationPolicy::None:
return kNone;
case ServiceAuthenticationPolicy::MutualTLS:
return kMutualTLS;
default:
break;
}
return {};
}
StringView TCPConnectionStateString(TCPConnectionState state) {
switch (state) {
case TCPConnectionState::Open:
return kOpen;
case TCPConnectionState::Connected:
return kConnected;
case TCPConnectionState::Close:
return kClose;
default:
break;
}
return {};
}
// Retrieves the traffic direction from the configuration context.
TrafficDirection getTrafficDirection() {
int64_t direction;
if (getValue({"listener_direction"}, &direction)) {
return static_cast<TrafficDirection>(direction);
}
return TrafficDirection::Unspecified;
}
void extractEmptyNodeFlatBuffer(std::string* out) {
flatbuffers::FlatBufferBuilder fbb;
FlatNodeBuilder node(fbb);
auto data = node.Finish();
fbb.Finish(data);
out->assign(reinterpret_cast<const char*>(fbb.GetBufferPointer()),
fbb.GetSize());
}
bool extractPartialLocalNodeFlatBuffer(std::string* out) {
flatbuffers::FlatBufferBuilder fbb;
flatbuffers::Offset<flatbuffers::String> name, namespace_, owner,
workload_name, istio_version, mesh_id, cluster_id;
std::vector<flatbuffers::Offset<KeyVal>> labels;
std::string value;
if (getValue({"node", "metadata", "NAME"}, &value)) {
name = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "NAMESPACE"}, &value)) {
namespace_ = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "OWNER"}, &value)) {
owner = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "WORKLOAD_NAME"}, &value)) {
workload_name = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "ISTIO_VERSION"}, &value)) {
istio_version = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "MESH_ID"}, &value)) {
mesh_id = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "CLUSTER_ID"}, &value)) {
cluster_id = fbb.CreateString(value);
}
for (const auto& label : kDefaultLabels) {
if (getValue({"node", "metadata", "LABELS", label}, &value)) {
labels.push_back(
CreateKeyVal(fbb, fbb.CreateString(label), fbb.CreateString(value)));
}
}
auto labels_offset = fbb.CreateVectorOfSortedTables(&labels);
FlatNodeBuilder node(fbb);
node.add_name(name);
node.add_namespace_(namespace_);
node.add_owner(owner);
node.add_workload_name(workload_name);
node.add_istio_version(istio_version);
node.add_mesh_id(mesh_id);
node.add_cluster_id(cluster_id);
node.add_labels(labels_offset);
auto data = node.Finish();
fbb.Finish(data);
out->assign(reinterpret_cast<const char*>(fbb.GetBufferPointer()),
fbb.GetSize());
return true;
}
// Host header is used if use_host_header_fallback==true.
// Normally it is ok to use host header within the mesh, but not at ingress.
void populateHTTPRequestInfo(bool outbound, bool use_host_header_fallback,
RequestInfo* request_info,
const std::string& destination_namespace) {
populateRequestInfo(outbound, use_host_header_fallback, request_info,
destination_namespace);
int64_t response_code = 0;
if (getValue({"response", "code"}, &response_code)) {
request_info->response_code = response_code;
}
int64_t grpc_status_code = 2;
getValue({"response", "grpc_status"}, &grpc_status_code);
request_info->grpc_status = grpc_status_code;
if (kGrpcContentTypes.count(
getHeaderMapValue(WasmHeaderMapType::RequestHeaders,
kContentTypeHeaderKey)
->toString()) != 0) {
request_info->request_protocol = kProtocolGRPC;
} else {
// TODO Add http/1.1, http/1.0, http/2 in a separate attribute.
// http|grpc classification is compatible with Mixerclient
request_info->request_protocol = kProtocolHTTP;
}
request_info->request_operation =
getHeaderMapValue(WasmHeaderMapType::RequestHeaders, kMethodHeaderKey)
->toString();
getValue({"request", "time"}, &request_info->start_time);
getValue({"request", "duration"}, &request_info->duration);
getValue({"request", "total_size"}, &request_info->request_size);
getValue({"response", "total_size"}, &request_info->response_size);
}
absl::string_view nodeInfoSchema() {
return absl::string_view(
reinterpret_cast<const char*>(FlatNodeBinarySchema::data()),
FlatNodeBinarySchema::size());
}
void populateExtendedHTTPRequestInfo(RequestInfo* request_info) {
populateExtendedRequestInfo(request_info);
getValue({"request", "referer"}, &request_info->referer);
getValue({"request", "user_agent"}, &request_info->user_agent);
getValue({"request", "id"}, &request_info->request_id);
std::string trace_sampled;
if (getValue({"request", "headers", "x-b3-sampled"}, &trace_sampled) &&
trace_sampled == "1") {
getValue({"request", "headers", "x-b3-traceid"},
&request_info->b3_trace_id);
getValue({"request", "headers", "x-b3-spanid"}, &request_info->b3_span_id);
request_info->b3_trace_sampled = true;
}
getValue({"request", "url_path"}, &request_info->url_path);
getValue({"request", "host"}, &request_info->url_host);
getValue({"request", "scheme"}, &request_info->url_scheme);
}
void populateExtendedRequestInfo(RequestInfo* request_info) {
getValue({"source", "address"}, &request_info->source_address);
getValue({"destination", "address"}, &request_info->destination_address);
getValue({"source", "port"}, &request_info->source_port);
getValue({"connection_id"}, &request_info->connection_id);
getValue({"upstream", "address"}, &request_info->upstream_host);
getValue({"connection", "requested_server_name"},
&request_info->request_serever_name);
auto envoy_original_path = getHeaderMapValue(
WasmHeaderMapType::RequestHeaders, kEnvoyOriginalPathKey);
request_info->x_envoy_original_path =
envoy_original_path ? envoy_original_path->toString() : "";
auto envoy_original_dst_host = getHeaderMapValue(
WasmHeaderMapType::RequestHeaders, kEnvoyOriginalDstHostKey);
request_info->x_envoy_original_dst_host =
envoy_original_dst_host ? envoy_original_dst_host->toString() : "";
}
void populateTCPRequestInfo(bool outbound, RequestInfo* request_info,
const std::string& destination_namespace) {
// host_header_fallback is for HTTP/gRPC only.
populateRequestInfo(outbound, false, request_info, destination_namespace);
request_info->request_protocol = kProtocolTCP;
}
} // namespace Common
} // namespace Wasm
<commit_msg>Fix Blackthrough Passthrough clusters destination service name refactoring (#2964)<commit_after>/* Copyright 2019 Istio 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 "extensions/common/context.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "extensions/common/node_info_bfbs_generated.h"
#include "extensions/common/util.h"
// WASM_PROLOG
#ifndef NULL_PLUGIN
#include "proxy_wasm_intrinsics.h"
#else // NULL_PLUGIN
#include "absl/strings/str_split.h"
#include "include/proxy-wasm/null_plugin.h"
using proxy_wasm::WasmHeaderMapType;
using proxy_wasm::null_plugin::getHeaderMapValue;
using proxy_wasm::null_plugin::getValue;
#endif // NULL_PLUGIN
// END WASM_PROLOG
namespace Wasm {
namespace Common {
const char kBlackHoleCluster[] = "BlackHoleCluster";
const char kPassThroughCluster[] = "PassthroughCluster";
const char kBlackHoleRouteName[] = "block_all";
const char kPassThroughRouteName[] = "allow_any";
const char kInboundPassthroughClusterIpv4[] = "InboundPassthroughClusterIpv4";
const char kInboundPassthroughClusterIpv6[] = "InboundPassthroughClusterIpv6";
namespace {
// Extract service name from service host.
void extractServiceName(const std::string& host,
const std::string& destination_namespace,
std::string* service_name) {
auto name_pos = host.find_first_of(".:");
if (name_pos == std::string::npos) {
// host is already a short service name. return it directly.
*service_name = host;
return;
}
if (host[name_pos] == ':') {
// host is `short_service:port`, return short_service name.
*service_name = host.substr(0, name_pos);
return;
}
auto namespace_pos = host.find_first_of(".:", name_pos + 1);
std::string service_namespace = "";
if (namespace_pos == std::string::npos) {
service_namespace = host.substr(name_pos + 1);
} else {
int namespace_size = namespace_pos - name_pos - 1;
service_namespace = host.substr(name_pos + 1, namespace_size);
}
// check if namespace in host is same as destination namespace.
// If it is the same, return the first part of host as service name.
// Otherwise fallback to request host.
if (service_namespace == destination_namespace) {
*service_name = host.substr(0, name_pos);
} else {
*service_name = host;
}
}
// Get destination service host and name based on destination cluster name and
// host header.
// * If cluster name is one of passthrough and blackhole clusters, use cluster
// name as destination service name and host header as destination host.
// * If cluster name follows Istio convention (four parts separated by pipe),
// use the last part as destination host; Otherwise, use host header as
// destination host. To get destination service name from host: if destination
// host is already a short name, use that as destination service; otherwise if
// the second part of destination host is destination namespace, use first
// part as destination service name. Otherwise, fallback to use destination
// host for destination service name.
void getDestinationService(const std::string& dest_namespace,
bool use_host_header, std::string* dest_svc_host,
std::string* dest_svc_name,
const std::string& cluster_name,
const std::string& route_name) {
*dest_svc_host = use_host_header
? getHeaderMapValue(WasmHeaderMapType::RequestHeaders,
kAuthorityHeaderKey)
->toString()
: "unknown";
// override the cluster name if this is being sent to the
// blackhole or passthrough cluster
if (route_name == kBlackHoleRouteName) {
*dest_svc_name = kBlackHoleCluster;
return;
} else if (route_name == kPassThroughRouteName) {
*dest_svc_name = kPassThroughCluster;
return;
}
if (cluster_name == kBlackHoleCluster ||
cluster_name == kPassThroughCluster ||
cluster_name == kInboundPassthroughClusterIpv4 ||
cluster_name == kInboundPassthroughClusterIpv6) {
*dest_svc_name = cluster_name;
return;
}
std::vector<absl::string_view> parts = absl::StrSplit(cluster_name, '|');
if (parts.size() == 4) {
*dest_svc_host = std::string(parts[3].data(), parts[3].size());
}
extractServiceName(*dest_svc_host, dest_namespace, dest_svc_name);
}
void populateRequestInfo(bool outbound, bool use_host_header_fallback,
RequestInfo* request_info,
const std::string& destination_namespace) {
request_info->is_populated = true;
getValue({"cluster_name"}, &request_info->upstream_cluster);
getValue({"route_name"}, &request_info->route_name);
// Fill in request info.
// Get destination service name and host based on cluster name and host
// header.
getDestinationService(destination_namespace, use_host_header_fallback,
&request_info->destination_service_host,
&request_info->destination_service_name,
request_info->upstream_cluster,
request_info->route_name);
getValue({"request", "url_path"}, &request_info->request_url_path);
uint64_t destination_port = 0;
if (outbound) {
getValue({"upstream", "port"}, &destination_port);
getValue({"upstream", "uri_san_peer_certificate"},
&request_info->destination_principal);
getValue({"upstream", "uri_san_local_certificate"},
&request_info->source_principal);
} else {
getValue({"destination", "port"}, &destination_port);
bool mtls = false;
if (getValue({"connection", "mtls"}, &mtls)) {
request_info->service_auth_policy =
mtls ? ::Wasm::Common::ServiceAuthenticationPolicy::MutualTLS
: ::Wasm::Common::ServiceAuthenticationPolicy::None;
}
getValue({"connection", "uri_san_local_certificate"},
&request_info->destination_principal);
getValue({"connection", "uri_san_peer_certificate"},
&request_info->source_principal);
}
request_info->destination_port = destination_port;
uint64_t response_flags = 0;
getValue({"response", "flags"}, &response_flags);
request_info->response_flag = parseResponseFlag(response_flags);
}
} // namespace
StringView AuthenticationPolicyString(ServiceAuthenticationPolicy policy) {
switch (policy) {
case ServiceAuthenticationPolicy::None:
return kNone;
case ServiceAuthenticationPolicy::MutualTLS:
return kMutualTLS;
default:
break;
}
return {};
}
StringView TCPConnectionStateString(TCPConnectionState state) {
switch (state) {
case TCPConnectionState::Open:
return kOpen;
case TCPConnectionState::Connected:
return kConnected;
case TCPConnectionState::Close:
return kClose;
default:
break;
}
return {};
}
// Retrieves the traffic direction from the configuration context.
TrafficDirection getTrafficDirection() {
int64_t direction;
if (getValue({"listener_direction"}, &direction)) {
return static_cast<TrafficDirection>(direction);
}
return TrafficDirection::Unspecified;
}
void extractEmptyNodeFlatBuffer(std::string* out) {
flatbuffers::FlatBufferBuilder fbb;
FlatNodeBuilder node(fbb);
auto data = node.Finish();
fbb.Finish(data);
out->assign(reinterpret_cast<const char*>(fbb.GetBufferPointer()),
fbb.GetSize());
}
bool extractPartialLocalNodeFlatBuffer(std::string* out) {
flatbuffers::FlatBufferBuilder fbb;
flatbuffers::Offset<flatbuffers::String> name, namespace_, owner,
workload_name, istio_version, mesh_id, cluster_id;
std::vector<flatbuffers::Offset<KeyVal>> labels;
std::string value;
if (getValue({"node", "metadata", "NAME"}, &value)) {
name = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "NAMESPACE"}, &value)) {
namespace_ = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "OWNER"}, &value)) {
owner = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "WORKLOAD_NAME"}, &value)) {
workload_name = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "ISTIO_VERSION"}, &value)) {
istio_version = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "MESH_ID"}, &value)) {
mesh_id = fbb.CreateString(value);
}
if (getValue({"node", "metadata", "CLUSTER_ID"}, &value)) {
cluster_id = fbb.CreateString(value);
}
for (const auto& label : kDefaultLabels) {
if (getValue({"node", "metadata", "LABELS", label}, &value)) {
labels.push_back(
CreateKeyVal(fbb, fbb.CreateString(label), fbb.CreateString(value)));
}
}
auto labels_offset = fbb.CreateVectorOfSortedTables(&labels);
FlatNodeBuilder node(fbb);
node.add_name(name);
node.add_namespace_(namespace_);
node.add_owner(owner);
node.add_workload_name(workload_name);
node.add_istio_version(istio_version);
node.add_mesh_id(mesh_id);
node.add_cluster_id(cluster_id);
node.add_labels(labels_offset);
auto data = node.Finish();
fbb.Finish(data);
out->assign(reinterpret_cast<const char*>(fbb.GetBufferPointer()),
fbb.GetSize());
return true;
}
// Host header is used if use_host_header_fallback==true.
// Normally it is ok to use host header within the mesh, but not at ingress.
void populateHTTPRequestInfo(bool outbound, bool use_host_header_fallback,
RequestInfo* request_info,
const std::string& destination_namespace) {
populateRequestInfo(outbound, use_host_header_fallback, request_info,
destination_namespace);
int64_t response_code = 0;
if (getValue({"response", "code"}, &response_code)) {
request_info->response_code = response_code;
}
int64_t grpc_status_code = 2;
getValue({"response", "grpc_status"}, &grpc_status_code);
request_info->grpc_status = grpc_status_code;
if (kGrpcContentTypes.count(
getHeaderMapValue(WasmHeaderMapType::RequestHeaders,
kContentTypeHeaderKey)
->toString()) != 0) {
request_info->request_protocol = kProtocolGRPC;
} else {
// TODO Add http/1.1, http/1.0, http/2 in a separate attribute.
// http|grpc classification is compatible with Mixerclient
request_info->request_protocol = kProtocolHTTP;
}
request_info->request_operation =
getHeaderMapValue(WasmHeaderMapType::RequestHeaders, kMethodHeaderKey)
->toString();
getValue({"request", "time"}, &request_info->start_time);
getValue({"request", "duration"}, &request_info->duration);
getValue({"request", "total_size"}, &request_info->request_size);
getValue({"response", "total_size"}, &request_info->response_size);
}
absl::string_view nodeInfoSchema() {
return absl::string_view(
reinterpret_cast<const char*>(FlatNodeBinarySchema::data()),
FlatNodeBinarySchema::size());
}
void populateExtendedHTTPRequestInfo(RequestInfo* request_info) {
populateExtendedRequestInfo(request_info);
getValue({"request", "referer"}, &request_info->referer);
getValue({"request", "user_agent"}, &request_info->user_agent);
getValue({"request", "id"}, &request_info->request_id);
std::string trace_sampled;
if (getValue({"request", "headers", "x-b3-sampled"}, &trace_sampled) &&
trace_sampled == "1") {
getValue({"request", "headers", "x-b3-traceid"},
&request_info->b3_trace_id);
getValue({"request", "headers", "x-b3-spanid"}, &request_info->b3_span_id);
request_info->b3_trace_sampled = true;
}
getValue({"request", "url_path"}, &request_info->url_path);
getValue({"request", "host"}, &request_info->url_host);
getValue({"request", "scheme"}, &request_info->url_scheme);
}
void populateExtendedRequestInfo(RequestInfo* request_info) {
getValue({"source", "address"}, &request_info->source_address);
getValue({"destination", "address"}, &request_info->destination_address);
getValue({"source", "port"}, &request_info->source_port);
getValue({"connection_id"}, &request_info->connection_id);
getValue({"upstream", "address"}, &request_info->upstream_host);
getValue({"connection", "requested_server_name"},
&request_info->request_serever_name);
auto envoy_original_path = getHeaderMapValue(
WasmHeaderMapType::RequestHeaders, kEnvoyOriginalPathKey);
request_info->x_envoy_original_path =
envoy_original_path ? envoy_original_path->toString() : "";
auto envoy_original_dst_host = getHeaderMapValue(
WasmHeaderMapType::RequestHeaders, kEnvoyOriginalDstHostKey);
request_info->x_envoy_original_dst_host =
envoy_original_dst_host ? envoy_original_dst_host->toString() : "";
}
void populateTCPRequestInfo(bool outbound, RequestInfo* request_info,
const std::string& destination_namespace) {
// host_header_fallback is for HTTP/gRPC only.
populateRequestInfo(outbound, false, request_info, destination_namespace);
request_info->request_protocol = kProtocolTCP;
}
} // namespace Common
} // namespace Wasm
<|endoftext|> |
<commit_before><commit_msg>The Firefox3XImporter test was incorrectly deleting a ref counted object causing an ASSERT to fire resulting in this test to randomly fail on the Vista dbg builder.<commit_after><|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 "mitkBasicCombinationOpenCVImageFilter.h"
namespace mitk {
bool BasicCombinationOpenCVImageFilter::OnFilterImage( cv::Mat& image )
{
int imageId = this->GetCurrentImageId();
// go through the list of all filters
for ( auto it
= m_FilterList.begin(); it != m_FilterList.end(); ++it )
{
// apply current filter and return false if the filter returned false
if (! (*it)->FilterImage(image, imageId) ) { return false; }
}
return true;
}
void BasicCombinationOpenCVImageFilter::PushFilter( AbstractOpenCVImageFilter::Pointer filter )
{
m_FilterList.push_back(filter);
}
AbstractOpenCVImageFilter::Pointer BasicCombinationOpenCVImageFilter::PopFilter( )
{
AbstractOpenCVImageFilter::Pointer lastFilter = m_FilterList.at(m_FilterList.size()-1);
m_FilterList.pop_back();
return lastFilter;
}
bool BasicCombinationOpenCVImageFilter::RemoveFilter( AbstractOpenCVImageFilter::Pointer filter )
{
for ( auto it
= m_FilterList.begin(); it != m_FilterList.end(); it++ )
{
if (*it == filter) {
m_FilterList.erase(it);
return true;
}
}
return false;
}
bool BasicCombinationOpenCVImageFilter::GetIsFilterOnTheList( AbstractOpenCVImageFilter::Pointer filter )
{
return std::find(m_FilterList.begin(), m_FilterList.end(), filter) != m_FilterList.end();
}
bool BasicCombinationOpenCVImageFilter::GetIsEmpty()
{
return m_FilterList.empty();
}
} // namespace mitk
<commit_msg>Add missing include<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 "mitkBasicCombinationOpenCVImageFilter.h"
#include <algorithm>
namespace mitk {
bool BasicCombinationOpenCVImageFilter::OnFilterImage( cv::Mat& image )
{
int imageId = this->GetCurrentImageId();
// go through the list of all filters
for ( auto it
= m_FilterList.begin(); it != m_FilterList.end(); ++it )
{
// apply current filter and return false if the filter returned false
if (! (*it)->FilterImage(image, imageId) ) { return false; }
}
return true;
}
void BasicCombinationOpenCVImageFilter::PushFilter( AbstractOpenCVImageFilter::Pointer filter )
{
m_FilterList.push_back(filter);
}
AbstractOpenCVImageFilter::Pointer BasicCombinationOpenCVImageFilter::PopFilter( )
{
AbstractOpenCVImageFilter::Pointer lastFilter = m_FilterList.at(m_FilterList.size()-1);
m_FilterList.pop_back();
return lastFilter;
}
bool BasicCombinationOpenCVImageFilter::RemoveFilter( AbstractOpenCVImageFilter::Pointer filter )
{
for ( auto it
= m_FilterList.begin(); it != m_FilterList.end(); it++ )
{
if (*it == filter) {
m_FilterList.erase(it);
return true;
}
}
return false;
}
bool BasicCombinationOpenCVImageFilter::GetIsFilterOnTheList( AbstractOpenCVImageFilter::Pointer filter )
{
return std::find(m_FilterList.begin(), m_FilterList.end(), filter) != m_FilterList.end();
}
bool BasicCombinationOpenCVImageFilter::GetIsEmpty()
{
return m_FilterList.empty();
}
} // namespace mitk
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cassert>
#include <iostream>
#include <limits>
#include <ostream>
#include <GL/glew.h>
#include <osg/MatrixTransform>
#include <osg/StateSet>
#include <osg/TriangleFunctor>
#include <cover/coVRPluginSupport.h>
#include <cover/VRViewer.h>
#include <visionaray/detail/aligned_vector.h>
#include <visionaray/math/math.h>
#include <visionaray/bvh.h>
#include <visionaray/kernels.h>
#include <visionaray/point_light.h>
#include <visionaray/render_target.h>
#include <visionaray/scheduler.h>
#include "visionaray_plugin.h"
namespace visionaray { namespace cover {
//-------------------------------------------------------------------------------------------------
// Type definitions
//
using triangle_type = basic_triangle<3, float>;
using triangle_list = aligned_vector<triangle_type>;
using normal_list = aligned_vector<vec3>;
using host_ray_type = basic_ray<simd::float4>;
using host_bvh_type = bvh<triangle_type>;
using host_sched_type = tiled_sched<host_ray_type>;
//-------------------------------------------------------------------------------------------------
// Functor that stores triangles from osg::Drawable
//
class store_triangle
{
public:
store_triangle() : triangles_(nullptr) {}
void set_lists(triangle_list& tris, normal_list& norms)
{
triangles_ = &tris;
normals_ = &norms;
}
void operator()(osg::Vec3 const& v1, osg::Vec3 const& v2, osg::Vec3 const& v3, bool) const
{
assert( triangles_ && normals_ );
triangle_type tri;
tri.prim_id = static_cast<unsigned>(triangles_->size());
tri.geom_id = 0;
tri.v1 = vec3(v1.x(), v1.y(), v1.z());
tri.e1 = vec3(v2.x(), v2.y(), v2.z()) - tri.v1;
tri.e2 = vec3(v3.x(), v3.y(), v3.z()) - tri.v1;
triangles_->push_back(tri);
normals_->push_back( normalize(cross(tri.e1, tri.e2)) );
assert( triangles_->size() == normals_->size() );
}
private:
// Store pointers because osg::TriangleFunctor is shitty..
triangle_list* triangles_;
normal_list* normals_;
};
//-------------------------------------------------------------------------------------------------
// Visitor to acquire scene data
//
class get_scene_visitor : public osg::NodeVisitor
{
public:
using base_type = osg::NodeVisitor;
using base_type::apply;
get_scene_visitor(triangle_list& tris, normal_list& norms, TraversalMode tm)
: base_type(tm)
, triangles_(tris)
, normals_(norms)
{
}
void apply(osg::Geode& geode)
{
for (size_t i = 0; i < geode.getNumDrawables(); ++i)
{
auto drawable = geode.getDrawable(i);
if (drawable)
{
osg::TriangleFunctor<store_triangle> tf;
tf.set_lists(triangles_, normals_);
drawable->accept(tf);
}
}
base_type::traverse(geode);
}
private:
triangle_list& triangles_;
normal_list& normals_;
};
//-------------------------------------------------------------------------------------------------
// Private implementation
//
struct Visionaray::impl
{
impl()
: visitor(triangles, normals, osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
{
}
triangle_list triangles;
normal_list normals;
host_bvh_type host_bvh;
host_sched_type host_sched;
cpu_buffer_rt host_rt;
recti viewport;
get_scene_visitor visitor;
osg::ref_ptr<osg::MatrixTransform> transform;
osg::ref_ptr<osg::Geode> geode;
};
Visionaray::Visionaray()
: impl_(new impl)
{
setSupportsDisplayList(false);
}
Visionaray::Visionaray(Visionaray const& rhs, osg::CopyOp const& op)
: Drawable(rhs, op)
, impl_(new impl)
{
setSupportsDisplayList(false);
}
Visionaray::~Visionaray()
{
impl_->transform->removeChild(impl_->geode);
opencover::cover->getObjectsRoot()->removeChild(impl_->transform);
}
bool Visionaray::init()
{
using namespace osg;
opencover::VRViewer::instance()->culling(false);
std::cout << "Init Visionaray Plugin!!" << std::endl;
ref_ptr<osg::StateSet> state = new osg::StateSet();
state->setGlobalDefaults();
impl_->geode = new osg::Geode;
impl_->geode->setStateSet(state);
impl_->geode->addDrawable(this);
impl_->transform = new osg::MatrixTransform();
impl_->transform->addChild(impl_->geode);
opencover::cover->getObjectsRoot()->addChild(impl_->transform);
return true;
}
void Visionaray::preFrame()
{
}
void Visionaray::drawImplementation(osg::RenderInfo&) const
{
// TODO?
static bool glewed = false;
if (!glewed)
{
glewed = glewInit() == GLEW_OK;
}
// Scene data
if (impl_->triangles.size() == 0)
{
// TODO: no dynamic scenes for now :(
impl_->visitor.apply(*opencover::cover->getObjectsRoot());
if (impl_->triangles.size() == 0)
{
return;
}
impl_->host_bvh = build<host_bvh_type>(impl_->triangles.data(), impl_->triangles.size());
}
aabb bounds( vec3(std::numeric_limits<float>::max()), -vec3(std::numeric_limits<float>::max()) );
for (auto const& tri : impl_->triangles)
{
auto v1 = tri.v1;
auto v2 = tri.v1 + tri.e1;
auto v3 = tri.v1 + tri.e2;
bounds = combine(bounds, aabb(v1, v1));
bounds = combine(bounds, aabb(v2, v2));
bounds = combine(bounds, aabb(v3, v3));
}
// Sched params
GLfloat view[16];
glGetFloatv(GL_MODELVIEW_MATRIX, view);
GLfloat proj[16];
glGetFloatv(GL_PROJECTION_MATRIX, proj);
GLint vp[4] = { 0, 0, 0, 0 };
glGetIntegerv(GL_VIEWPORT, vp);
mat4 view_matrix(view);
mat4 proj_matrix(proj);
recti viewport(vp[0], vp[1], vp[2], vp[3]);
auto sparams = make_sched_params<pixel_sampler::uniform_type>( view_matrix, proj_matrix, viewport, impl_->host_rt );
if (impl_->viewport != viewport)
{
impl_->host_rt.resize(vp[2], vp[3]);
impl_->viewport = viewport;
}
// Kernel params
aligned_vector<host_bvh_type::bvh_ref> host_primitives;
host_primitives.push_back(impl_->host_bvh.ref());
aligned_vector<phong<float>> materials;
phong<float> m;
m.set_cd( vec3(0.8f, 0.8f, 0.8f) );
m.set_kd( 1.0f );
m.set_ks( 1.0f );
m.set_specular_exp( 32.0f );
materials.push_back(m);
vec4 lpos;
glGetLightfv(GL_LIGHT0, GL_POSITION, lpos.data());
aligned_vector<point_light<float>> lights;
vec3 light0_pos = (inverse(view_matrix) * lpos).xyz();
lights.push_back({ light0_pos });
auto kparams = make_params
(
host_primitives.data(),
host_primitives.data() + host_primitives.size(),
impl_->normals.data(),
materials.data(),
lights.data(),
lights.data() + lights.size()
);
// Render
auto kern = simple::kernel<vector<4, simd::float4>, decltype(kparams)>();
kern.params = kparams;
impl_->host_sched.frame(kern, sparams);
impl_->host_rt.display_color_buffer();
}
}} // namespace visionaray::cover
COVERPLUGIN(visionaray::cover::Visionaray)
<commit_msg>Support materials in COVER plugin<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cassert>
#include <algorithm>
#include <iostream>
#include <limits>
#include <ostream>
#include <GL/glew.h>
#include <osg/Material>
#include <osg/MatrixTransform>
#include <osg/StateSet>
#include <osg/TriangleFunctor>
#include <cover/coVRPluginSupport.h>
#include <cover/VRViewer.h>
#include <visionaray/detail/aligned_vector.h>
#include <visionaray/math/math.h>
#include <visionaray/bvh.h>
#include <visionaray/kernels.h>
#include <visionaray/point_light.h>
#include <visionaray/render_target.h>
#include <visionaray/scheduler.h>
#include "visionaray_plugin.h"
namespace visionaray { namespace cover {
//-------------------------------------------------------------------------------------------------
// Type definitions
//
using triangle_type = basic_triangle<3, float>;
using triangle_list = aligned_vector<triangle_type>;
using normal_list = aligned_vector<vec3>;
using material_list = aligned_vector<phong<float>>;
using host_ray_type = basic_ray<simd::float4>;
using host_bvh_type = bvh<triangle_type>;
using host_sched_type = tiled_sched<host_ray_type>;
//-------------------------------------------------------------------------------------------------
// Functor that stores triangles from osg::Drawable
//
class store_triangle
{
public:
store_triangle() : triangles_(nullptr) {}
void init(triangle_list& tris, normal_list& norms, unsigned geom_id)
{
triangles_ = &tris;
normals_ = &norms;
geom_id_ = geom_id;
}
void operator()(osg::Vec3 const& v1, osg::Vec3 const& v2, osg::Vec3 const& v3, bool) const
{
assert( triangles_ && normals_ );
triangle_type tri;
tri.prim_id = static_cast<unsigned>(triangles_->size());
tri.geom_id = geom_id_;
tri.v1 = vec3(v1.x(), v1.y(), v1.z());
tri.e1 = vec3(v2.x(), v2.y(), v2.z()) - tri.v1;
tri.e2 = vec3(v3.x(), v3.y(), v3.z()) - tri.v1;
triangles_->push_back(tri);
normals_->push_back( normalize(cross(tri.e1, tri.e2)) );
assert( triangles_->size() == normals_->size() );
}
private:
// Store pointers because osg::TriangleFunctor is shitty..
triangle_list* triangles_;
normal_list* normals_;
unsigned geom_id_;
};
//-------------------------------------------------------------------------------------------------
// Visitor to acquire scene data
//
class get_scene_visitor : public osg::NodeVisitor
{
public:
using base_type = osg::NodeVisitor;
using base_type::apply;
get_scene_visitor(triangle_list& tris, normal_list& norms, material_list& mats, TraversalMode tm)
: base_type(tm)
, triangles_(tris)
, normals_(norms)
, materials_(mats)
{
}
void apply(osg::Geode& geode)
{
for (size_t i = 0; i < geode.getNumDrawables(); ++i)
{
auto drawable = geode.getDrawable(i);
if (drawable)
{
auto set = drawable->getOrCreateStateSet();
auto attr = set->getAttribute(osg::StateAttribute::MATERIAL);
auto mat = dynamic_cast<osg::Material*>(attr);
if (mat)
{
auto cd = mat->getDiffuse(osg::Material::Face::FRONT);
auto cs = mat->getSpecular(osg::Material::Face::FRONT);
phong<float> vsnray_mat;
vsnray_mat.set_cd( vec3(cd.x(), cd.y(), cd.z()) );
vsnray_mat.set_kd( 1.0f );
vsnray_mat.set_ks( cs.x() ); // TODO: e.g. luminance?
vsnray_mat.set_specular_exp( mat->getShininess(osg::Material::Face::FRONT) );
materials_.push_back(vsnray_mat);
}
assert( static_cast<material_list::size_type>(static_cast<unsigned>(materials.size()) == materials.size()) );
osg::TriangleFunctor<store_triangle> tf;
tf.init( triangles_, normals_, std::max(0U, static_cast<unsigned>(materials_.size()) - 1) );
drawable->accept(tf);
}
}
base_type::traverse(geode);
}
private:
triangle_list& triangles_;
normal_list& normals_;
material_list& materials_;
};
//-------------------------------------------------------------------------------------------------
// Private implementation
//
struct Visionaray::impl
{
impl()
: visitor(triangles, normals, materials, osg::NodeVisitor::TRAVERSE_ALL_CHILDREN)
{
}
triangle_list triangles;
normal_list normals;
material_list materials;
host_bvh_type host_bvh;
host_sched_type host_sched;
cpu_buffer_rt host_rt;
recti viewport;
get_scene_visitor visitor;
osg::ref_ptr<osg::MatrixTransform> transform;
osg::ref_ptr<osg::Geode> geode;
};
Visionaray::Visionaray()
: impl_(new impl)
{
setSupportsDisplayList(false);
}
Visionaray::Visionaray(Visionaray const& rhs, osg::CopyOp const& op)
: Drawable(rhs, op)
, impl_(new impl)
{
setSupportsDisplayList(false);
}
Visionaray::~Visionaray()
{
impl_->transform->removeChild(impl_->geode);
opencover::cover->getObjectsRoot()->removeChild(impl_->transform);
}
bool Visionaray::init()
{
using namespace osg;
opencover::VRViewer::instance()->culling(false);
std::cout << "Init Visionaray Plugin!!" << std::endl;
ref_ptr<osg::StateSet> state = new osg::StateSet();
state->setGlobalDefaults();
impl_->geode = new osg::Geode;
impl_->geode->setStateSet(state);
impl_->geode->addDrawable(this);
impl_->transform = new osg::MatrixTransform();
impl_->transform->addChild(impl_->geode);
opencover::cover->getObjectsRoot()->addChild(impl_->transform);
return true;
}
void Visionaray::preFrame()
{
}
void Visionaray::drawImplementation(osg::RenderInfo&) const
{
// TODO?
static bool glewed = false;
if (!glewed)
{
glewed = glewInit() == GLEW_OK;
}
// Scene data
if (impl_->triangles.size() == 0)
{
// TODO: no dynamic scenes for now :(
impl_->visitor.apply(*opencover::cover->getObjectsRoot());
if (impl_->triangles.size() == 0)
{
return;
}
impl_->host_bvh = build<host_bvh_type>(impl_->triangles.data(), impl_->triangles.size());
}
aabb bounds( vec3(std::numeric_limits<float>::max()), -vec3(std::numeric_limits<float>::max()) );
for (auto const& tri : impl_->triangles)
{
auto v1 = tri.v1;
auto v2 = tri.v1 + tri.e1;
auto v3 = tri.v1 + tri.e2;
bounds = combine(bounds, aabb(v1, v1));
bounds = combine(bounds, aabb(v2, v2));
bounds = combine(bounds, aabb(v3, v3));
}
// Sched params
GLfloat view[16];
glGetFloatv(GL_MODELVIEW_MATRIX, view);
GLfloat proj[16];
glGetFloatv(GL_PROJECTION_MATRIX, proj);
GLint vp[4] = { 0, 0, 0, 0 };
glGetIntegerv(GL_VIEWPORT, vp);
mat4 view_matrix(view);
mat4 proj_matrix(proj);
recti viewport(vp[0], vp[1], vp[2], vp[3]);
auto sparams = make_sched_params<pixel_sampler::uniform_type>( view_matrix, proj_matrix, viewport, impl_->host_rt );
if (impl_->viewport != viewport)
{
impl_->host_rt.resize(vp[2], vp[3]);
impl_->viewport = viewport;
}
// Kernel params
aligned_vector<host_bvh_type::bvh_ref> host_primitives;
host_primitives.push_back(impl_->host_bvh.ref());
vec4 lpos;
glGetLightfv(GL_LIGHT0, GL_POSITION, lpos.data());
aligned_vector<point_light<float>> lights;
vec3 light0_pos = (inverse(view_matrix) * lpos).xyz();
lights.push_back({ light0_pos });
auto kparams = make_params
(
host_primitives.data(),
host_primitives.data() + host_primitives.size(),
impl_->normals.data(),
impl_->materials.data(),
lights.data(),
lights.data() + lights.size()
);
// Render
auto kern = simple::kernel<vector<4, simd::float4>, decltype(kparams)>();
kern.params = kparams;
impl_->host_sched.frame(kern, sparams);
impl_->host_rt.display_color_buffer();
}
}} // namespace visionaray::cover
COVERPLUGIN(visionaray::cover::Visionaray)
<|endoftext|> |
<commit_before>/* Copyright 2015 Jonas Platte
*
* This file is part of Cyvasse Online.
*
* Cyvasse Online 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.
*
* Cyvasse Online 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 <cyvws/json_notification.hpp>
#include <json/value.h>
#include <cyvws/common.hpp>
#include <cyvws/msg.hpp>
#include <cyvws/notification.hpp>
using namespace std;
namespace cyvws
{
namespace json
{
Json::Value notification(const Json::Value& notificationData)
{
Json::Value val;
val[MSG_TYPE] = MsgType::NOTIFICATION;
val[NOTIFICATION_DATA] = notificationData;
return val;
}
Json::Value commErr(const string& errMsg)
{
Json::Value data;
data[TYPE] = NotificationType::COMM_ERROR;
data[ERR_MSG] = errMsg;
return notification(data);
}
Json::Value listUpdate(const string& listName, const GamesListMap& curList)
{
Json::Value data;
data[TYPE] = NotificationType::LIST_UPDATE;
data[LIST_NAME] = listName;
auto& listContent = data[LIST_CONTENT];
for (auto&& game : curList)
{
Json::Value gameVal;
gameVal[MATCH_ID] = game.first;
gameVal[TITLE] = game.second.title;
//gameVal[RULE_SET]
gameVal[PLAY_AS] = PlayersColorToStr(game.second.playAs);
//gameVal[EXTRA_RULES]
listContent.append(gameVal);
}
return notification(data);
}
Json::Value userJoined(const string& screenName, bool registered, const string& role)
{
Json::Value data;
data[TYPE] = NotificationType::USER_JOINED;
data[SCREEN_NAME] = screenName;
data[REGISTERED] = registered;
data[ROLE] = role;
return notification(data);
}
Json::Value userLeft(const string& screenName)
{
Json::Value data;
data[TYPE] = NotificationType::USER_LEFT;
data[SCREEN_NAME] = screenName;
return notification(data);
}
}
}
<commit_msg>Fixed listContent being null instead of [] when games list is empty (listUpdate notification)<commit_after>/* Copyright 2015 Jonas Platte
*
* This file is part of Cyvasse Online.
*
* Cyvasse Online 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.
*
* Cyvasse Online 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 <cyvws/json_notification.hpp>
#include <json/value.h>
#include <cyvws/common.hpp>
#include <cyvws/msg.hpp>
#include <cyvws/notification.hpp>
using namespace std;
namespace cyvws
{
namespace json
{
Json::Value notification(const Json::Value& notificationData)
{
Json::Value val;
val[MSG_TYPE] = MsgType::NOTIFICATION;
val[NOTIFICATION_DATA] = notificationData;
return val;
}
Json::Value commErr(const string& errMsg)
{
Json::Value data;
data[TYPE] = NotificationType::COMM_ERROR;
data[ERR_MSG] = errMsg;
return notification(data);
}
Json::Value listUpdate(const string& listName, const GamesListMap& curList)
{
Json::Value data;
data[TYPE] = NotificationType::LIST_UPDATE;
data[LIST_NAME] = listName;
auto& listContent = data[LIST_CONTENT] = Json::Value(Json::arrayValue);
for (auto&& game : curList)
{
Json::Value gameVal;
gameVal[MATCH_ID] = game.first;
gameVal[TITLE] = game.second.title;
//gameVal[RULE_SET]
gameVal[PLAY_AS] = PlayersColorToStr(game.second.playAs);
//gameVal[EXTRA_RULES]
listContent.append(gameVal);
}
return notification(data);
}
Json::Value userJoined(const string& screenName, bool registered, const string& role)
{
Json::Value data;
data[TYPE] = NotificationType::USER_JOINED;
data[SCREEN_NAME] = screenName;
data[REGISTERED] = registered;
data[ROLE] = role;
return notification(data);
}
Json::Value userLeft(const string& screenName)
{
Json::Value data;
data[TYPE] = NotificationType::USER_LEFT;
data[SCREEN_NAME] = screenName;
return notification(data);
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Registers the XLA_GPU device, which is an XlaDevice instantiation that runs
// operators using XLA via the XLA "CUDA" (GPU) backend.
#include "absl/memory/memory.h"
#include "tensorflow/compiler/jit/kernels/xla_ops.h"
#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_device_ops.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/lib/core/status.h"
namespace tensorflow {
class XlaGpuDeviceFactory : public DeviceFactory {
public:
Status CreateDevices(const SessionOptions& options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) override;
};
Status XlaGpuDeviceFactory::CreateDevices(
const SessionOptions& session_options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) {
XlaOpRegistry::DeviceRegistration registration;
registration.compilation_device_name = DEVICE_GPU_XLA_JIT;
registration.autoclustering_policy =
XlaOpRegistry::AutoclusteringPolicy::kAlways;
registration.compile_resource_ops = true;
XlaOpRegistry::RegisterCompilationDevice(DEVICE_XLA_GPU, registration);
static XlaDeviceOpRegistrations* registrations =
RegisterXlaDeviceKernels(DEVICE_XLA_GPU, DEVICE_GPU_XLA_JIT);
(void)registrations;
auto platform = se::MultiPlatformManager::PlatformWithName("CUDA");
if (!platform.ok()) {
// Treat failures as non-fatal; there might not be a GPU in the machine.
VLOG(1) << "Failed to create XLA_GPU device: " << platform.status();
return Status::OK();
}
for (int i = 0; i < platform.ValueOrDie()->VisibleDeviceCount(); ++i) {
XlaDevice::Options options;
options.platform = platform.ValueOrDie();
options.device_name_prefix = name_prefix;
options.device_name = DEVICE_XLA_GPU;
options.device_ordinal = i;
options.compilation_device_name = DEVICE_GPU_XLA_JIT;
options.use_multiple_streams = true;
auto device = absl::make_unique<XlaDevice>(session_options, options);
Status status = device->UseGpuDeviceInfo();
if (!status.ok()) {
errors::AppendToMessage(&status, "while setting up ", DEVICE_GPU_XLA_JIT,
" device number ", i);
return status;
}
devices->push_back(std::move(device));
}
return Status::OK();
}
REGISTER_LOCAL_DEVICE_FACTORY(DEVICE_XLA_GPU, XlaGpuDeviceFactory);
// Kernel registrations
constexpr std::array<DataType, 13> kAllXlaGpuTypes = {
{DT_UINT8, DT_QUINT8, DT_INT8, DT_QINT8, DT_INT32, DT_QINT32, DT_INT64,
DT_HALF, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_BOOL, DT_BFLOAT16}};
REGISTER_XLA_LAUNCH_KERNEL(DEVICE_XLA_GPU, XlaLocalLaunchOp, kAllXlaGpuTypes);
REGISTER_XLA_COMPILE_KERNEL(DEVICE_XLA_GPU, XlaCompileOp, kAllXlaGpuTypes);
REGISTER_XLA_RUN_KERNEL(DEVICE_XLA_GPU, XlaRunOp, kAllXlaGpuTypes);
REGISTER_XLA_DEVICE_KERNELS(DEVICE_XLA_GPU, kAllXlaGpuTypes);
} // namespace tensorflow
<commit_msg>Use session config when creating XLA devices<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Registers the XLA_GPU device, which is an XlaDevice instantiation that runs
// operators using XLA via the XLA "CUDA" (GPU) backend.
#include "absl/memory/memory.h"
#include "tensorflow/compiler/jit/kernels/xla_ops.h"
#include "tensorflow/compiler/jit/xla_device.h"
#include "tensorflow/compiler/jit/xla_device_ops.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace tensorflow {
class XlaGpuDeviceFactory : public DeviceFactory {
public:
Status CreateDevices(const SessionOptions& options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) override;
};
Status XlaGpuDeviceFactory::CreateDevices(
const SessionOptions& session_options, const string& name_prefix,
std::vector<std::unique_ptr<Device>>* devices) {
XlaOpRegistry::DeviceRegistration registration;
registration.compilation_device_name = DEVICE_GPU_XLA_JIT;
registration.autoclustering_policy =
XlaOpRegistry::AutoclusteringPolicy::kAlways;
registration.compile_resource_ops = true;
XlaOpRegistry::RegisterCompilationDevice(DEVICE_XLA_GPU, registration);
static XlaDeviceOpRegistrations* registrations =
RegisterXlaDeviceKernels(DEVICE_XLA_GPU, DEVICE_GPU_XLA_JIT);
(void)registrations;
auto platform = se::MultiPlatformManager::PlatformWithName("CUDA");
if (!platform.ok()) {
// Treat failures as non-fatal; there might not be a GPU in the machine.
VLOG(1) << "Failed to create XLA_GPU device: " << platform.status();
return Status::OK();
}
const auto& allowed_gpus =
session_options.config.gpu_options().visible_device_list();
std::unordered_set<int> gpu_ids;
int num_visible_devices = platform.ValueOrDie()->VisibleDeviceCount();
if (allowed_gpus.empty()) {
for (int i = 0; i < num_visible_devices; ++i) gpu_ids.insert(i);
} else {
const std::vector<string> visible_devices =
str_util::Split(allowed_gpus, ',');
// copied from gpu/gpu_device.cc Should be redundant since code would fail
// there before it gets to here.
for (const string& platform_gpu_id_str : visible_devices) {
int32 platform_gpu_id;
if (!strings::safe_strto32(platform_gpu_id_str, &platform_gpu_id)) {
return errors::InvalidArgument(
"Could not parse entry in 'visible_device_list': '",
platform_gpu_id_str, "'. visible_device_list = ", allowed_gpus);
}
if (platform_gpu_id < 0 || platform_gpu_id >= num_visible_devices) {
return errors::InvalidArgument(
"'visible_device_list' listed an invalid GPU id '", platform_gpu_id,
"' but visible device count is ", num_visible_devices);
}
gpu_ids.insert(platform_gpu_id);
}
}
for (int i = 0; i < num_visible_devices; ++i) {
if (gpu_ids.count(i) == 0) continue;
XlaDevice::Options options;
options.platform = platform.ValueOrDie();
options.device_name_prefix = name_prefix;
options.device_name = DEVICE_XLA_GPU;
options.device_ordinal = i;
options.compilation_device_name = DEVICE_GPU_XLA_JIT;
options.use_multiple_streams = true;
auto device = absl::make_unique<XlaDevice>(session_options, options);
Status status = device->UseGpuDeviceInfo();
if (!status.ok()) {
errors::AppendToMessage(&status, "while setting up ", DEVICE_GPU_XLA_JIT,
" device number ", i);
return status;
}
devices->push_back(std::move(device));
}
return Status::OK();
}
REGISTER_LOCAL_DEVICE_FACTORY(DEVICE_XLA_GPU, XlaGpuDeviceFactory);
// Kernel registrations
constexpr std::array<DataType, 13> kAllXlaGpuTypes = {
{DT_UINT8, DT_QUINT8, DT_INT8, DT_QINT8, DT_INT32, DT_QINT32, DT_INT64,
DT_HALF, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_BOOL, DT_BFLOAT16}};
REGISTER_XLA_LAUNCH_KERNEL(DEVICE_XLA_GPU, XlaLocalLaunchOp, kAllXlaGpuTypes);
REGISTER_XLA_COMPILE_KERNEL(DEVICE_XLA_GPU, XlaCompileOp, kAllXlaGpuTypes);
REGISTER_XLA_RUN_KERNEL(DEVICE_XLA_GPU, XlaRunOp, kAllXlaGpuTypes);
REGISTER_XLA_DEVICE_KERNELS(DEVICE_XLA_GPU, kAllXlaGpuTypes);
} // namespace tensorflow
<|endoftext|> |
<commit_before>#include "contextproperty.h"
#include "propertylistener.h"
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <QDebug>
int main(int argc, char **argv)
{
setenv("CONTEXT_PROVIDERS", ".", 0);
ContextProperty::setTypeCheck(true);
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
if (args.count() <= 1) {
QTextStream out(stdout);
out << "Usage: " << app.arguments().at(0) << " <properties...>" << endl;
return 0;
}
args.pop_front();
foreach (QString key, args) {
ContextProperty* prop = new ContextProperty(key);
prop->setParent(new PropertyListener(prop, &app));
}
return app.exec();
}
<commit_msg>libcontextsubscriber/cli: exit on any kind of stdin activity<commit_after>#include "contextproperty.h"
#include "propertylistener.h"
#include "sconnect.h"
#include <QSocketNotifier>
#include <QCoreApplication>
#include <QString>
#include <QStringList>
#include <QDebug>
int main(int argc, char **argv)
{
setenv("CONTEXT_PROVIDERS", ".", 0);
ContextProperty::setTypeCheck(true);
QCoreApplication app(argc, argv);
QStringList args = app.arguments();
if (args.count() <= 1) {
QTextStream out(stdout);
out << "Usage: " << app.arguments().at(0) << " <properties...>" << endl;
return 0;
}
args.pop_front();
foreach (QString key, args) {
ContextProperty* prop = new ContextProperty(key);
prop->setParent(new PropertyListener(prop, &app));
}
QSocketNotifier stdinWatcher(0, QSocketNotifier::Read, &app);
sconnect(&stdinWatcher,
SIGNAL(activated(int)),
&app,
SLOT(quit()));
return app.exec();
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/transport/bdp_estimator.h"
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/useful.h>
#include <gtest/gtest.h>
#include <limits.h>
#include "src/core/lib/iomgr/timer_manager.h"
#include "src/core/lib/support/string.h"
#include "test/core/util/test_config.h"
extern "C" gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type);
namespace grpc_core {
namespace testing {
namespace {
int g_clock = 0;
gpr_timespec fake_gpr_now(gpr_clock_type clock_type) {
return (gpr_timespec){
.tv_sec = g_clock, .tv_nsec = 0, .clock_type = clock_type,
};
}
void inc_time(void) { g_clock += 30; }
} // namespace
TEST(BdpEstimatorTest, NoOp) { BdpEstimator est("test"); }
TEST(BdpEstimatorTest, EstimateBdpNoSamples) {
BdpEstimator est("test");
int64_t estimate;
est.EstimateBdp(&estimate);
}
namespace {
void AddSamples(BdpEstimator *estimator, int64_t *samples, size_t n) {
estimator->AddIncomingBytes(1234567);
inc_time();
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
EXPECT_TRUE(estimator->NeedPing(&exec_ctx));
estimator->SchedulePing();
estimator->StartPing();
for (size_t i = 0; i < n; i++) {
estimator->AddIncomingBytes(samples[i]);
EXPECT_FALSE(estimator->NeedPing(&exec_ctx));
}
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(1, GPR_TIMESPAN)));
grpc_exec_ctx_invalidate_now(&exec_ctx);
estimator->CompletePing(&exec_ctx);
grpc_exec_ctx_finish(&exec_ctx);
}
void AddSample(BdpEstimator *estimator, int64_t sample) {
AddSamples(estimator, &sample, 1);
}
} // namespace
TEST(BdpEstimatorTest, GetEstimate1Sample) {
BdpEstimator est("test");
AddSample(&est, 100);
int64_t estimate;
est.EstimateBdp(&estimate);
}
TEST(BdpEstimatorTest, GetEstimate2Samples) {
BdpEstimator est("test");
AddSample(&est, 100);
AddSample(&est, 100);
int64_t estimate;
est.EstimateBdp(&estimate);
}
TEST(BdpEstimatorTest, GetEstimate3Samples) {
BdpEstimator est("test");
AddSample(&est, 100);
AddSample(&est, 100);
AddSample(&est, 100);
int64_t estimate;
est.EstimateBdp(&estimate);
}
namespace {
static int64_t GetEstimate(const BdpEstimator &estimator) {
int64_t out;
EXPECT_TRUE(estimator.EstimateBdp(&out));
return out;
}
int64_t NextPow2(int64_t v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
} // namespace
class BdpEstimatorRandomTest : public ::testing::TestWithParam<size_t> {};
TEST_P(BdpEstimatorRandomTest, GetEstimateRandomValues) {
BdpEstimator est("test");
const int kMaxSample = 65535;
int min = kMaxSample;
int max = 0;
for (size_t i = 0; i < GetParam(); i++) {
int sample = rand() % (kMaxSample + 1);
if (sample < min) min = sample;
if (sample > max) max = sample;
AddSample(&est, sample);
if (i >= 3) {
EXPECT_LE(GetEstimate(est), GPR_MAX(65536, 2 * NextPow2(max)))
<< " min:" << min << " max:" << max << " sample:" << sample;
}
}
}
INSTANTIATE_TEST_CASE_P(TooManyNames, BdpEstimatorRandomTest,
::testing::Values(3, 4, 6, 9, 13, 19, 28, 42, 63, 94,
141, 211, 316, 474, 711));
} // namespace testing
} // namespace grpc_core
int main(int argc, char **argv) {
grpc_test_init(argc, argv);
gpr_now_impl = grpc_core::testing::fake_gpr_now;
grpc_init();
grpc_timer_manager_set_threading(false);
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
grpc_shutdown();
return ret;
}
<commit_msg>Fix windows portability<commit_after>/*
*
* Copyright 2016 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/transport/bdp_estimator.h"
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>
#include <grpc/support/useful.h>
#include <gtest/gtest.h>
#include <limits.h>
#include "src/core/lib/iomgr/timer_manager.h"
#include "src/core/lib/support/string.h"
#include "test/core/util/test_config.h"
extern "C" gpr_timespec (*gpr_now_impl)(gpr_clock_type clock_type);
namespace grpc_core {
namespace testing {
namespace {
int g_clock = 0;
gpr_timespec fake_gpr_now(gpr_clock_type clock_type) {
gpr_timespec ts;
ts.tv_sec = g_clock;
ts.tv_nsec = 0;
ts.clock_type = clock_type;
return ts;
}
void inc_time(void) { g_clock += 30; }
} // namespace
TEST(BdpEstimatorTest, NoOp) { BdpEstimator est("test"); }
TEST(BdpEstimatorTest, EstimateBdpNoSamples) {
BdpEstimator est("test");
int64_t estimate;
est.EstimateBdp(&estimate);
}
namespace {
void AddSamples(BdpEstimator *estimator, int64_t *samples, size_t n) {
estimator->AddIncomingBytes(1234567);
inc_time();
grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
EXPECT_TRUE(estimator->NeedPing(&exec_ctx));
estimator->SchedulePing();
estimator->StartPing();
for (size_t i = 0; i < n; i++) {
estimator->AddIncomingBytes(samples[i]);
EXPECT_FALSE(estimator->NeedPing(&exec_ctx));
}
gpr_sleep_until(gpr_time_add(gpr_now(GPR_CLOCK_REALTIME),
gpr_time_from_millis(1, GPR_TIMESPAN)));
grpc_exec_ctx_invalidate_now(&exec_ctx);
estimator->CompletePing(&exec_ctx);
grpc_exec_ctx_finish(&exec_ctx);
}
void AddSample(BdpEstimator *estimator, int64_t sample) {
AddSamples(estimator, &sample, 1);
}
} // namespace
TEST(BdpEstimatorTest, GetEstimate1Sample) {
BdpEstimator est("test");
AddSample(&est, 100);
int64_t estimate;
est.EstimateBdp(&estimate);
}
TEST(BdpEstimatorTest, GetEstimate2Samples) {
BdpEstimator est("test");
AddSample(&est, 100);
AddSample(&est, 100);
int64_t estimate;
est.EstimateBdp(&estimate);
}
TEST(BdpEstimatorTest, GetEstimate3Samples) {
BdpEstimator est("test");
AddSample(&est, 100);
AddSample(&est, 100);
AddSample(&est, 100);
int64_t estimate;
est.EstimateBdp(&estimate);
}
namespace {
static int64_t GetEstimate(const BdpEstimator &estimator) {
int64_t out;
EXPECT_TRUE(estimator.EstimateBdp(&out));
return out;
}
int64_t NextPow2(int64_t v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
} // namespace
class BdpEstimatorRandomTest : public ::testing::TestWithParam<size_t> {};
TEST_P(BdpEstimatorRandomTest, GetEstimateRandomValues) {
BdpEstimator est("test");
const int kMaxSample = 65535;
int min = kMaxSample;
int max = 0;
for (size_t i = 0; i < GetParam(); i++) {
int sample = rand() % (kMaxSample + 1);
if (sample < min) min = sample;
if (sample > max) max = sample;
AddSample(&est, sample);
if (i >= 3) {
EXPECT_LE(GetEstimate(est), GPR_MAX(65536, 2 * NextPow2(max)))
<< " min:" << min << " max:" << max << " sample:" << sample;
}
}
}
INSTANTIATE_TEST_CASE_P(TooManyNames, BdpEstimatorRandomTest,
::testing::Values(3, 4, 6, 9, 13, 19, 28, 42, 63, 94,
141, 211, 316, 474, 711));
} // namespace testing
} // namespace grpc_core
int main(int argc, char **argv) {
grpc_test_init(argc, argv);
gpr_now_impl = grpc_core::testing::fake_gpr_now;
grpc_init();
grpc_timer_manager_set_threading(false);
::testing::InitGoogleTest(&argc, argv);
int ret = RUN_ALL_TESTS();
grpc_shutdown();
return ret;
}
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Planet - An atmospheric code for planetary bodies, adapted to Titan
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
//Antioch
#include "antioch/vector_utils_decl.h"
#include "antioch/physical_constants.h"
#include "antioch/sigma_bin_converter.h"
#include "antioch/vector_utils.h"
//Planet
#include "planet/molecular_diffusion_evaluator.h"
#include "planet/planet_constants.h"
//C++
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <limits>
template<typename Scalar>
int check_test(Scalar theory, Scalar cal, const std::string &words)
{
const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 100.L;
if(std::abs((theory-cal)/theory) < tol)return 0;
std::cout << std::scientific << std::setprecision(20)
<< "failed test: " << words << "\n"
<< "theory: " << theory
<< "\ncalculated: " << cal
<< "\ndifference: " << std::abs((theory-cal)/cal)
<< "\ntolerance: " << tol << std::endl;
return 1;
}
template<typename Scalar, typename VectorScalar = std::vector<Scalar> >
void read_temperature(VectorScalar &T0, VectorScalar &Tz, const std::string &file)
{
T0.clear();
Tz.clear();
std::string line;
std::ifstream temp(file);
getline(temp,line);
while(!temp.eof())
{
Scalar t,tz,dt,dtz;
temp >> t >> tz >> dt >> dtz;
T0.push_back(t);
Tz.push_back(tz);
}
temp.close();
return;
}
template<typename Scalar>
Scalar barometry(const Scalar &zmin, const Scalar &z, const Scalar &T, const Scalar &Mm, const Scalar &botdens)
{
return botdens * Antioch::ant_exp(-(z - zmin)/((Planet::Constants::Titan::radius<Scalar>() + z) * (Planet::Constants::Titan::radius<Scalar>() + zmin) * 1e3 *
Antioch::Constants::Avogadro<Scalar>() * Planet::Constants::Universal::kb<Scalar>() * T /
(Planet::Constants::Universal::G<Scalar>() * Planet::Constants::Titan::mass<Scalar>() * Mm))
);
}
template<typename Scalar, typename VectorScalar>
void calculate_densities(VectorScalar &densities, const Scalar &tot_dens, const VectorScalar &molar_frac,
const Scalar &zmin,const Scalar &z,
const Scalar &T, const VectorScalar &mm)
{
Scalar Mm;
Antioch::set_zero(Mm);
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
Mm += molar_frac[s] * mm[s];
}
densities.clear();
densities.resize(molar_frac.size());
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
densities[s] = molar_frac[s] * barometry(zmin,z,T,Mm,tot_dens);
}
return;
}
template<typename Scalar>
Scalar binary_coefficient(const Scalar &T, const Scalar &P, const Scalar &D01, const Scalar &beta)
{
return D01 * Planet::Constants::Convention::P_normal<Scalar>() / P * Antioch::ant_pow(T/Planet::Constants::Convention::T_standard<Scalar>(),beta);
}
template<typename Scalar>
Scalar binary_coefficient(const Scalar &Dii, const Scalar &Mi, const Scalar &Mj)
{
return (Mj < Mi)?Dii * Antioch::ant_sqrt((Mj/Mi + Scalar(1.L))/Scalar(2.L))
:
Dii * Antioch::ant_sqrt((Mj/Mi));
}
template<typename Scalar>
Scalar pressure(const Scalar &n, const Scalar &T)
{
return n * 1e6L * Planet::Constants::Universal::kb<Scalar>() * T; //cm-3 -> m-3
}
template <typename Scalar>
int tester(const std::string &input_T)
{
//description
std::vector<std::string> neutrals;
std::vector<std::string> ions;
neutrals.push_back("N2");
neutrals.push_back("CH4");
neutrals.push_back("C2H");
//ionic system contains neutral system
ions = neutrals;
ions.push_back("N2+");
Scalar MN(14.008e-3L), MC(12.011e-3L), MH(1.008e-3L);
Scalar MN2 = 2.L*MN , MCH4 = MC + 4.L*MH, MC2H = 2.L * MC + MH;
std::vector<Scalar> Mm;
Mm.push_back(MN2);
Mm.push_back(MCH4);
Mm.push_back(MC2H);
std::vector<std::string> medium;
medium.push_back("N2");
medium.push_back("CH4");
//densities
std::vector<Scalar> molar_frac;
molar_frac.push_back(0.95999L);
molar_frac.push_back(0.04000L);
molar_frac.push_back(0.00001L);
molar_frac.push_back(0.L);
Scalar dens_tot(1e12L);
//zenith angle
//not necessary
//photon flux
//not necessary
////cross-section
//not necessary
//altitudes
Scalar zmin(600.),zmax(1400.),zstep(10.);
//binary diffusion
Scalar bCN1(1.04e-5 * 1e-4),bCN2(1.76); //cm2 -> m2
Planet::DiffusionType CN_model(Planet::DiffusionType::Wakeham);
Scalar bCC1(5.73e16 * 1e-4),bCC2(0.5); //cm2 -> m2
Planet::DiffusionType CC_model(Planet::DiffusionType::Wilson);
Scalar bNN1(0.1783 * 1e-4),bNN2(1.81); //cm2 -> m2
Planet::DiffusionType NN_model(Planet::DiffusionType::Massman);
/************************
* first level
************************/
//neutrals
Antioch::ChemicalMixture<Scalar> neutral_species(neutrals);
//ions
Antioch::ChemicalMixture<Scalar> ionic_species(ions);
//chapman
//not needed
//binary diffusion
Planet::BinaryDiffusion<Scalar> N2N2( 0, 0 , bNN1, bNN2, NN_model);
Planet::BinaryDiffusion<Scalar> N2CH4( 0, 1, bCN1, bCN2, CN_model);
Planet::BinaryDiffusion<Scalar> CH4CH4( 1, 1, bCC1, bCC2, CC_model);
Planet::BinaryDiffusion<Scalar> N2C2H( 0, 2);
Planet::BinaryDiffusion<Scalar> CH4C2H( 1, 2);
std::vector<std::vector<Planet::BinaryDiffusion<Scalar> > > bin_diff_coeff;
bin_diff_coeff.resize(2);
bin_diff_coeff[0].push_back(N2N2);
bin_diff_coeff[0].push_back(N2CH4);
bin_diff_coeff[0].push_back(N2C2H);
bin_diff_coeff[1].push_back(N2CH4);
bin_diff_coeff[1].push_back(CH4CH4);
bin_diff_coeff[1].push_back(CH4C2H);
/************************
* second level
************************/
//temperature
std::vector<Scalar> T0,Tz;
read_temperature<Scalar>(T0,Tz,input_T);
Planet::AtmosphericTemperature<Scalar, std::vector<Scalar> > temperature(T0, T0, Tz, Tz);
//photon opacity
//not needed
//reaction sets
//not needed
/************************
* third level
************************/
//atmospheric mixture
Planet::AtmosphericMixture<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > composition(neutral_species, ionic_species, temperature);
composition.init_composition(molar_frac,dens_tot,zmin,zmax);
//kinetics evaluators
//not needed
/************************
* fourth level
************************/
//photon evaluator
//not needed
//molecular diffusion
Planet::MolecularDiffusionEvaluator<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > molecular_diffusion(bin_diff_coeff,composition,temperature,medium);
//eddy diffusion
//not needed
/************************
* checks
************************/
molar_frac.pop_back();//get the ion outta here
Scalar Matm(0.L);
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
Matm += molar_frac[s] * composition.neutral_composition().M(s);
}
//N2, CH4, C2H
std::vector<std::vector<Scalar> > Dij;
Dij.resize(2);
Dij[0].resize(3,0.L);
Dij[1].resize(3,0.L);
int return_flag(0);
for(Scalar z = zmin; z <= zmax; z += zstep)
{
Scalar T = temperature.neutral_temperature(z);
Scalar nTot = barometry(zmin,z,T,Matm,dens_tot);
Scalar P = pressure(nTot,T);
std::vector<Scalar> densities;
calculate_densities(densities, dens_tot, molar_frac, zmin, z, T, Mm);
std::vector<Scalar> molecular_diffusion_Dtilde;
molecular_diffusion.Dtilde(densities,z,molecular_diffusion_Dtilde);
Dij[0][0] = binary_coefficient(T,P,bNN1,bNN2); //N2 N2
Dij[0][1] = binary_coefficient(T,P,bCN1 * Antioch::ant_pow(Planet::Constants::Convention::T_standard<Scalar>(),bCN2),bCN2); //N2 CH4
Dij[0][2] = binary_coefficient(Dij[0][0],Mm[0],Mm[2]); //N2 C2H
Dij[1][0] = Dij[0][1]; //CH4 N2
Dij[1][1] = binary_coefficient(T,P,bCC1 * Antioch::ant_pow(Planet::Constants::Convention::T_standard<Scalar>(),bCC2 + Scalar(1.L))
* Planet::Constants::Universal::kb<Scalar>()
/ Planet::Constants::Convention::P_normal<Scalar>(),bCC2 + Scalar(1.L)); //CH4 CH4
Dij[1][2] = binary_coefficient(Dij[1][1],Mm[1],Mm[2]); //CH4 C2H
return_flag = return_flag ||
check_test(Dij[0][0],molecular_diffusion.binary_coefficient(0,0,T,P),"binary molecular coefficient N2 N2 at altitude") ||
check_test(Dij[0][1],molecular_diffusion.binary_coefficient(0,1,T,P),"binary molecular coefficient N2 CH4 at altitude") ||
check_test(Dij[0][2],molecular_diffusion.binary_coefficient(0,2,T,P),"binary molecular coefficient N2 C2H at altitude") ||
check_test(Dij[1][1],molecular_diffusion.binary_coefficient(1,1,T,P),"binary molecular coefficient CH4 CH4 at altitude") ||
check_test(Dij[1][2],molecular_diffusion.binary_coefficient(1,2,T,P),"binary molecular coefficient CH4 C2H at altitude");
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
Scalar tmp(0.L);
for(unsigned int imedium = 0; imedium < medium.size(); imedium++)
{
if(s == imedium)continue;
tmp += densities[imedium]/Dij[imedium][s];
}
Scalar Ds = (nTot - densities[s]) / tmp;
Scalar M_diff(0.L);
Scalar totdens_diff(0.L);
for(unsigned int j = 0; j < molar_frac.size(); j++)
{
if(s == j)continue;
M_diff += densities[j] * Mm[j];
totdens_diff += densities[j];
}
M_diff /= totdens_diff;
Scalar Dtilde = Ds / (Scalar(1.L) - molar_frac[s] * (Scalar(1.L) - composition.neutral_composition().M(s)/M_diff));
return_flag = return_flag ||
check_test(Dtilde,molecular_diffusion_Dtilde[s],"Dtilde of species at altitude");
}
}
return return_flag;
}
int main(int argc, char** argv)
{
// Check command line count.
if( argc < 2 )
{
// TODO: Need more consistent error handling.
std::cerr << "Error: Must specify input file." << std::endl;
antioch_error();
}
return (tester<float>(std::string(argv[1])) ||
tester<double>(std::string(argv[1])));//||
//tester<long double>(std::string(argv[1])));
}
<commit_msg>not as precise as before...<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// Planet - An atmospheric code for planetary bodies, adapted to Titan
//
// Copyright (C) 2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA 02110-1301 USA
//
//-----------------------------------------------------------------------el-
//Antioch
#include "antioch/vector_utils_decl.h"
#include "antioch/physical_constants.h"
#include "antioch/sigma_bin_converter.h"
#include "antioch/vector_utils.h"
//Planet
#include "planet/molecular_diffusion_evaluator.h"
#include "planet/planet_constants.h"
//C++
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <limits>
template<typename Scalar>
int check_test(Scalar theory, Scalar cal, const std::string &words)
{
const Scalar tol = std::numeric_limits<Scalar>::epsilon() * 500.L;
if(std::abs((theory-cal)/theory) < tol)return 0;
std::cout << std::scientific << std::setprecision(20)
<< "failed test: " << words << "\n"
<< "theory: " << theory
<< "\ncalculated: " << cal
<< "\ndifference: " << std::abs((theory-cal)/cal)
<< "\ntolerance: " << tol << std::endl;
return 1;
}
template<typename Scalar, typename VectorScalar = std::vector<Scalar> >
void read_temperature(VectorScalar &T0, VectorScalar &Tz, const std::string &file)
{
T0.clear();
Tz.clear();
std::string line;
std::ifstream temp(file);
getline(temp,line);
while(!temp.eof())
{
Scalar t,tz,dt,dtz;
temp >> t >> tz >> dt >> dtz;
T0.push_back(t);
Tz.push_back(tz);
}
temp.close();
return;
}
template<typename Scalar>
Scalar barometry(const Scalar &zmin, const Scalar &z, const Scalar &T, const Scalar &Mm, const Scalar &botdens)
{
return botdens * Antioch::ant_exp(-(z - zmin)/((Planet::Constants::Titan::radius<Scalar>() + z) * (Planet::Constants::Titan::radius<Scalar>() + zmin) * 1e3 *
Antioch::Constants::Avogadro<Scalar>() * Planet::Constants::Universal::kb<Scalar>() * T /
(Planet::Constants::Universal::G<Scalar>() * Planet::Constants::Titan::mass<Scalar>() * Mm))
);
}
template<typename Scalar, typename VectorScalar>
void calculate_densities(VectorScalar &densities, const Scalar &tot_dens, const VectorScalar &molar_frac,
const Scalar &zmin,const Scalar &z,
const Scalar &T, const VectorScalar &mm)
{
Scalar Mm;
Antioch::set_zero(Mm);
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
Mm += molar_frac[s] * mm[s];
}
densities.clear();
densities.resize(molar_frac.size());
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
densities[s] = molar_frac[s] * barometry(zmin,z,T,Mm,tot_dens);
}
return;
}
template<typename Scalar>
Scalar binary_coefficient(const Scalar &T, const Scalar &P, const Scalar &D01, const Scalar &beta)
{
return D01 * Planet::Constants::Convention::P_normal<Scalar>() / P * Antioch::ant_pow(T/Planet::Constants::Convention::T_standard<Scalar>(),beta);
}
template<typename Scalar>
Scalar binary_coefficient(const Scalar &Dii, const Scalar &Mi, const Scalar &Mj)
{
return (Mj < Mi)?Dii * Antioch::ant_sqrt((Mj/Mi + Scalar(1.L))/Scalar(2.L))
:
Dii * Antioch::ant_sqrt((Mj/Mi));
}
template<typename Scalar>
Scalar pressure(const Scalar &n, const Scalar &T)
{
return n * 1e6L * Planet::Constants::Universal::kb<Scalar>() * T; //cm-3 -> m-3
}
template <typename Scalar>
int tester(const std::string &input_T)
{
//description
std::vector<std::string> neutrals;
std::vector<std::string> ions;
neutrals.push_back("N2");
neutrals.push_back("CH4");
neutrals.push_back("C2H");
//ionic system contains neutral system
ions = neutrals;
ions.push_back("N2+");
Scalar MN(14.008e-3L), MC(12.011e-3L), MH(1.008e-3L);
Scalar MN2 = 2.L*MN , MCH4 = MC + 4.L*MH, MC2H = 2.L * MC + MH;
std::vector<Scalar> Mm;
Mm.push_back(MN2);
Mm.push_back(MCH4);
Mm.push_back(MC2H);
std::vector<std::string> medium;
medium.push_back("N2");
medium.push_back("CH4");
//densities
std::vector<Scalar> molar_frac;
molar_frac.push_back(0.95999L);
molar_frac.push_back(0.04000L);
molar_frac.push_back(0.00001L);
molar_frac.push_back(0.L);
Scalar dens_tot(1e12L);
//zenith angle
//not necessary
//photon flux
//not necessary
////cross-section
//not necessary
//altitudes
Scalar zmin(600.),zmax(1400.),zstep(10.);
//binary diffusion
Scalar bCN1(1.04e-5 * 1e-4),bCN2(1.76); //cm2 -> m2
Planet::DiffusionType CN_model(Planet::DiffusionType::Wakeham);
Scalar bCC1(5.73e16 * 1e-4),bCC2(0.5); //cm2 -> m2
Planet::DiffusionType CC_model(Planet::DiffusionType::Wilson);
Scalar bNN1(0.1783 * 1e-4),bNN2(1.81); //cm2 -> m2
Planet::DiffusionType NN_model(Planet::DiffusionType::Massman);
/************************
* first level
************************/
//neutrals
Antioch::ChemicalMixture<Scalar> neutral_species(neutrals);
//ions
Antioch::ChemicalMixture<Scalar> ionic_species(ions);
//chapman
//not needed
//binary diffusion
Planet::BinaryDiffusion<Scalar> N2N2( 0, 0 , bNN1, bNN2, NN_model);
Planet::BinaryDiffusion<Scalar> N2CH4( 0, 1, bCN1, bCN2, CN_model);
Planet::BinaryDiffusion<Scalar> CH4CH4( 1, 1, bCC1, bCC2, CC_model);
Planet::BinaryDiffusion<Scalar> N2C2H( 0, 2);
Planet::BinaryDiffusion<Scalar> CH4C2H( 1, 2);
std::vector<std::vector<Planet::BinaryDiffusion<Scalar> > > bin_diff_coeff;
bin_diff_coeff.resize(2);
bin_diff_coeff[0].push_back(N2N2);
bin_diff_coeff[0].push_back(N2CH4);
bin_diff_coeff[0].push_back(N2C2H);
bin_diff_coeff[1].push_back(N2CH4);
bin_diff_coeff[1].push_back(CH4CH4);
bin_diff_coeff[1].push_back(CH4C2H);
/************************
* second level
************************/
//temperature
std::vector<Scalar> T0,Tz;
read_temperature<Scalar>(T0,Tz,input_T);
Planet::AtmosphericTemperature<Scalar, std::vector<Scalar> > temperature(T0, T0, Tz, Tz);
//photon opacity
//not needed
//reaction sets
//not needed
/************************
* third level
************************/
//atmospheric mixture
Planet::AtmosphericMixture<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > composition(neutral_species, ionic_species, temperature);
composition.init_composition(molar_frac,dens_tot,zmin,zmax);
//kinetics evaluators
//not needed
/************************
* fourth level
************************/
//photon evaluator
//not needed
//molecular diffusion
Planet::MolecularDiffusionEvaluator<Scalar,std::vector<Scalar>, std::vector<std::vector<Scalar> > > molecular_diffusion(bin_diff_coeff,composition,temperature,medium);
//eddy diffusion
//not needed
/************************
* checks
************************/
molar_frac.pop_back();//get the ion outta here
Scalar Matm(0.L);
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
Matm += molar_frac[s] * composition.neutral_composition().M(s);
}
//N2, CH4, C2H
std::vector<std::vector<Scalar> > Dij;
Dij.resize(2);
Dij[0].resize(3,0.L);
Dij[1].resize(3,0.L);
int return_flag(0);
for(Scalar z = zmin; z <= zmax; z += zstep)
{
Scalar T = temperature.neutral_temperature(z);
Scalar nTot = barometry(zmin,z,T,Matm,dens_tot);
Scalar P = pressure(nTot,T);
std::vector<Scalar> densities;
calculate_densities(densities, dens_tot, molar_frac, zmin, z, T, Mm);
std::vector<Scalar> molecular_diffusion_Dtilde;
molecular_diffusion.Dtilde(densities,z,molecular_diffusion_Dtilde);
Dij[0][0] = binary_coefficient(T,P,bNN1,bNN2); //N2 N2
Dij[0][1] = binary_coefficient(T,P,bCN1 * Antioch::ant_pow(Planet::Constants::Convention::T_standard<Scalar>(),bCN2),bCN2); //N2 CH4
Dij[0][2] = binary_coefficient(Dij[0][0],Mm[0],Mm[2]); //N2 C2H
Dij[1][0] = Dij[0][1]; //CH4 N2
Dij[1][1] = binary_coefficient(T,P,bCC1 * Antioch::ant_pow(Planet::Constants::Convention::T_standard<Scalar>(),bCC2 + Scalar(1.L))
* Planet::Constants::Universal::kb<Scalar>()
/ Planet::Constants::Convention::P_normal<Scalar>(),bCC2 + Scalar(1.L)); //CH4 CH4
Dij[1][2] = binary_coefficient(Dij[1][1],Mm[1],Mm[2]); //CH4 C2H
return_flag = return_flag ||
check_test(Dij[0][0],molecular_diffusion.binary_coefficient(0,0,T,P),"binary molecular coefficient N2 N2 at altitude") ||
check_test(Dij[0][1],molecular_diffusion.binary_coefficient(0,1,T,P),"binary molecular coefficient N2 CH4 at altitude") ||
check_test(Dij[0][2],molecular_diffusion.binary_coefficient(0,2,T,P),"binary molecular coefficient N2 C2H at altitude") ||
check_test(Dij[1][1],molecular_diffusion.binary_coefficient(1,1,T,P),"binary molecular coefficient CH4 CH4 at altitude") ||
check_test(Dij[1][2],molecular_diffusion.binary_coefficient(1,2,T,P),"binary molecular coefficient CH4 C2H at altitude");
for(unsigned int s = 0; s < molar_frac.size(); s++)
{
Scalar tmp(0.L);
for(unsigned int imedium = 0; imedium < medium.size(); imedium++)
{
if(s == imedium)continue;
tmp += densities[imedium]/Dij[imedium][s];
}
Scalar Ds = (nTot - densities[s]) / tmp;
Scalar M_diff(0.L);
Scalar totdens_diff(0.L);
for(unsigned int j = 0; j < molar_frac.size(); j++)
{
if(s == j)continue;
M_diff += densities[j] * Mm[j];
totdens_diff += densities[j];
}
M_diff /= totdens_diff;
Scalar Dtilde = Ds / (Scalar(1.L) - molar_frac[s] * (Scalar(1.L) - composition.neutral_composition().M(s)/M_diff));
return_flag = return_flag ||
check_test(Dtilde,molecular_diffusion_Dtilde[s],"Dtilde of species at altitude");
}
}
return return_flag;
}
int main(int argc, char** argv)
{
// Check command line count.
if( argc < 2 )
{
// TODO: Need more consistent error handling.
std::cerr << "Error: Must specify input file." << std::endl;
antioch_error();
}
return (tester<float>(std::string(argv[1])) ||
tester<double>(std::string(argv[1])));//||
//tester<long double>(std::string(argv[1])));
}
<|endoftext|> |
<commit_before>//
// Created by Ivan Shynkarenka on 03.10.2016.
//
#include "catch.hpp"
#include "threads/condition_variable.h"
#include <thread>
using namespace CppCommon;
TEST_CASE("Condition variable notify one", "[CppCommon][Threads]")
{
int concurrency = 8;
int result1 = concurrency;
int result2 = concurrency;
CriticalSection cs;
ConditionVariable cv1;
ConditionVariable cv2;
// Start threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.push_back(std::thread([&cs, &cv1, &cv2, &result1, &result2]()
{
cs.Lock();
--result1;
cv1.NotifyOne();
cv2.Wait(cs, [&result2]() { return (result2 == 0); });
cs.Unlock();
}));
}
// Send one-thread notifications
for (int i = 0; i < concurrency; ++i)
{
cs.Lock();
cv1.Wait(cs, [&result1]() { return (result1 == 0); });
--result2;
cv2.NotifyOne();
cs.Unlock();
}
// Wait for all threads
for (auto& thread : threads)
thread.join();
// Check results
REQUIRE(result1 == 0);
REQUIRE(result2 == 0);
}
/*
TEST_CASE("Condition variable notify all", "[CppCommon][Threads]")
{
int concurrency = 8;
int result = 0;
CriticalSection cs;
ConditionVariable cv;
// Start threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.push_back(std::thread([&cs, &cv, &result]()
{
cs.Lock();
cv.Wait(cs);
++result;
cs.Unlock();
}));
}
// Send all-thread notification
cs.Lock();
cv.NotifyAll();
cs.Unlock();
// Wait for all threads
for (auto& thread : threads)
thread.join();
// Check result
REQUIRE(result == concurrency);
}
*/<commit_msg>Bugfixing<commit_after>//
// Created by Ivan Shynkarenka on 03.10.2016.
//
#include "catch.hpp"
#include "threads/condition_variable.h"
#include <thread>
using namespace CppCommon;
TEST_CASE("Condition variable notify one", "[CppCommon][Threads]")
{
int concurrency = 8;
int result1 = concurrency;
int result2 = concurrency;
CriticalSection cs;
ConditionVariable cv1;
ConditionVariable cv2;
// Start threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.push_back(std::thread([&cs, &cv1, &cv2, &result1, &result2]()
{
cs.Lock();
--result1;
cv1.NotifyOne();
cv2.Wait(cs, [&result2]() { return (result2 == 0); });
cs.Unlock();
}));
}
// Send one-thread notifications
for (int i = 0; i < concurrency; ++i)
{
cs.Lock();
cv1.Wait(cs, [&result1]() { return (result1 == 0); });
--result2;
cv2.NotifyOne();
cs.Unlock();
}
// Wait for all threads
for (auto& thread : threads)
thread.join();
// Check results
REQUIRE(result1 == 0);
REQUIRE(result2 == 0);
}
TEST_CASE("Condition variable notify all", "[CppCommon][Threads]")
{
int concurrency = 8;
int result1 = concurrency;
int result2 = concurrency;
CriticalSection cs;
ConditionVariable cv1;
ConditionVariable cv2;
// Start threads
std::vector<std::thread> threads;
for (int thread = 0; thread < concurrency; ++thread)
{
threads.push_back(std::thread([&cs, &cv1, &cv2, &result1, &result2]()
{
cs.Lock();
--result1;
cv1.NotifyOne();
cv2.Wait(cs, [&result2]() { return (result2 == 0); });
cs.Unlock();
}));
}
// Send all-threads notifications
for (int i = 0; i < concurrency; ++i)
{
cs.Lock();
cv1.Wait(cs, [&result1]() { return (result1 == 0); });
result2 = 0;
cv2.NotifyAll();
cs.Unlock();
}
// Wait for all threads
for (auto& thread : threads)
thread.join();
// Check results
REQUIRE(result1 == 0);
REQUIRE(result2 == 0);
}
<|endoftext|> |
<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/alert.hpp>
#include <libtorrent/alert_types.hpp>
#include <boost/python.hpp>
using namespace boost::python;
using namespace libtorrent;
extern char const* alert_doc;
extern char const* alert_msg_doc;
extern char const* alert_severity_doc;
extern char const* torrent_alert_doc;
extern char const* tracker_alert_doc;
extern char const* tracker_error_alert_doc;
extern char const* tracker_warning_alert_doc;
extern char const* tracker_reply_alert_doc;
extern char const* tracker_announce_alert_doc;
extern char const* hash_failed_alert_doc;
extern char const* peer_ban_alert_doc;
extern char const* peer_error_alert_doc;
extern char const* invalid_request_alert_doc;
extern char const* peer_request_doc;
extern char const* torrent_finished_alert_doc;
extern char const* piece_finished_alert_doc;
extern char const* block_finished_alert_doc;
extern char const* block_downloading_alert_doc;
extern char const* storage_moved_alert_doc;
extern char const* torrent_deleted_alert_doc;
extern char const* torrent_paused_alert_doc;
extern char const* torrent_checked_alert_doc;
extern char const* url_seed_alert_doc;
extern char const* file_error_alert_doc;
extern char const* metadata_failed_alert_doc;
extern char const* metadata_received_alert_doc;
extern char const* listen_failed_alert_doc;
extern char const* listen_succeeded_alert_doc;
extern char const* portmap_error_alert_doc;
extern char const* portmap_alert_doc;
extern char const* fastresume_rejected_alert_doc;
extern char const* peer_blocked_alert_doc;
extern char const* scrape_reply_alert_doc;
extern char const* scrape_failed_alert_doc;
extern char const* udp_error_alert_doc;
extern char const* external_ip_alert_doc;
extern char const* save_resume_data_alert_doc;
void bind_alert()
{
using boost::noncopyable;
{
scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init)
.def(
"msg", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
.def("severity", &alert::severity, alert_severity_doc)
.def(
"__str__", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
;
enum_<alert::severity_t>("severity_levels")
.value("debug", alert::debug)
.value("info", alert::info)
.value("warning", alert::warning)
.value("critical", alert::critical)
.value("fatal", alert::fatal)
.value("none", alert::none)
;
}
class_<torrent_alert, bases<alert>, noncopyable>(
"torrent_alert", torrent_alert_doc, no_init
)
.def_readonly("handle", &torrent_alert::handle)
;
class_<tracker_alert, bases<torrent_alert>, noncopyable>(
"tracker_alert", tracker_alert_doc, no_init
)
.def_readonly("url", &tracker_alert::url)
;
class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(
"tracker_error_alert", tracker_error_alert_doc, no_init
)
.def_readonly("times_in_row", &tracker_error_alert::times_in_row)
.def_readonly("status_code", &tracker_error_alert::status_code)
;
class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(
"tracker_warning_alert", tracker_warning_alert_doc, no_init
);
class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(
"tracker_reply_alert", tracker_reply_alert_doc, no_init
)
.def_readonly("num_peers", &tracker_reply_alert::num_peers)
;
class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(
"tracker_announce_alert", tracker_announce_alert_doc, no_init
);
class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(
"hash_failed_alert", hash_failed_alert_doc, no_init
)
.def_readonly("piece_index", &hash_failed_alert::piece_index)
;
class_<peer_ban_alert, bases<torrent_alert>, noncopyable>(
"peer_ban_alert", peer_ban_alert_doc, no_init
)
.def_readonly("ip", &peer_ban_alert::ip)
;
class_<peer_error_alert, bases<alert>, noncopyable>(
"peer_error_alert", peer_error_alert_doc, no_init
)
.def_readonly("ip", &peer_error_alert::ip)
.def_readonly("pid", &peer_error_alert::pid)
;
class_<invalid_request_alert, bases<torrent_alert>, noncopyable>(
"invalid_request_alert", invalid_request_alert_doc, no_init
)
.def_readonly("ip", &invalid_request_alert::ip)
.def_readonly("request", &invalid_request_alert::request)
.def_readonly("pid", &invalid_request_alert::pid)
;
class_<peer_request>("peer_request", peer_request_doc)
.def_readonly("piece", &peer_request::piece)
.def_readonly("start", &peer_request::start)
.def_readonly("length", &peer_request::length)
.def(self == self)
;
class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(
"torrent_finished_alert", torrent_finished_alert_doc, no_init
);
class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(
"piece_finished_alert", piece_finished_alert_doc, no_init
)
.def_readonly("piece_index", &piece_finished_alert::piece_index)
;
class_<block_finished_alert, bases<torrent_alert>, noncopyable>(
"block_finished_alert", block_finished_alert_doc, no_init
)
.def_readonly("block_index", &block_finished_alert::block_index)
.def_readonly("piece_index", &block_finished_alert::piece_index)
;
class_<block_downloading_alert, bases<torrent_alert>, noncopyable>(
"block_downloading_alert", block_downloading_alert_doc, no_init
)
.def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg)
.def_readonly("block_index", &block_downloading_alert::block_index)
.def_readonly("piece_index", &block_downloading_alert::piece_index)
;
class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(
"storage_moved_alert", storage_moved_alert_doc, no_init
);
class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(
"torrent_deleted_alert", torrent_deleted_alert_doc, no_init
);
class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(
"torrent_paused_alert", torrent_paused_alert_doc, no_init
);
class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(
"torrent_checked_alert", torrent_checked_alert_doc, no_init
);
class_<url_seed_alert, bases<torrent_alert>, noncopyable>(
"url_seed_alert", url_seed_alert_doc, no_init
)
.def_readonly("url", &url_seed_alert::url)
;
class_<file_error_alert, bases<torrent_alert>, noncopyable>(
"file_error_alert", file_error_alert_doc, no_init
)
.def_readonly("file", &file_error_alert::file)
;
class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(
"metadata_failed_alert", metadata_failed_alert_doc, no_init
);
class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(
"metadata_received_alert", metadata_received_alert_doc, no_init
);
class_<listen_failed_alert, bases<alert>, noncopyable>(
"listen_failed_alert", listen_failed_alert_doc, no_init
);
class_<listen_succeeded_alert, bases<alert>, noncopyable>(
"listen_succeeded_alert", listen_succeeded_alert_doc, no_init
)
.def_readonly("endpoint", &listen_succeeded_alert::endpoint)
;
class_<portmap_error_alert, bases<alert>, noncopyable>(
"portmap_error_alert", portmap_error_alert_doc, no_init
)
.def_readonly("mapping", &portmap_error_alert::mapping)
.def_readonly("type", &portmap_error_alert::type)
;
class_<portmap_alert, bases<alert>, noncopyable>(
"portmap_alert", portmap_alert_doc, no_init
)
.def_readonly("mapping", &portmap_alert::mapping)
.def_readonly("external_port", &portmap_alert::external_port)
.def_readonly("type", &portmap_alert::type)
;
class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(
"fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init
);
class_<peer_blocked_alert, bases<alert>, noncopyable>(
"peer_blocked_alert", peer_blocked_alert_doc, no_init
)
.def_readonly("ip", &peer_blocked_alert::ip)
;
class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(
"scrape_reply_alert", scrape_reply_alert_doc, no_init
)
.def_readonly("incomplete", &scrape_reply_alert::incomplete)
.def_readonly("complete", &scrape_reply_alert::complete)
;
class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(
"scrape_failed_alert", scrape_failed_alert_doc, no_init
);
class_<udp_error_alert, bases<alert>, noncopyable>(
"udp_error_alert", udp_error_alert_doc, no_init
)
.def_readonly("endpoint", &udp_error_alert::endpoint)
;
class_<external_ip_alert, bases<alert>, noncopyable>(
"external_ip_alert", external_ip_alert_doc, no_init
)
.def_readonly("external_address", &external_ip_alert::external_address)
;
class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(
"save_resume_data_alert", save_resume_data_alert_doc, no_init
)
.def_readonly("resume_data", &save_resume_data_alert::resume_data)
;
class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(
"file_renamed_alert", no_init
)
.def_readonly("name", &file_renamed_alert::name)
;
class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(
"torrent_resumed_alert", no_init
);
}
<commit_msg>Add state_changed_alert to python bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/alert.hpp>
#include <libtorrent/alert_types.hpp>
#include <boost/python.hpp>
using namespace boost::python;
using namespace libtorrent;
extern char const* alert_doc;
extern char const* alert_msg_doc;
extern char const* alert_severity_doc;
extern char const* torrent_alert_doc;
extern char const* tracker_alert_doc;
extern char const* tracker_error_alert_doc;
extern char const* tracker_warning_alert_doc;
extern char const* tracker_reply_alert_doc;
extern char const* tracker_announce_alert_doc;
extern char const* hash_failed_alert_doc;
extern char const* peer_ban_alert_doc;
extern char const* peer_error_alert_doc;
extern char const* invalid_request_alert_doc;
extern char const* peer_request_doc;
extern char const* torrent_finished_alert_doc;
extern char const* piece_finished_alert_doc;
extern char const* block_finished_alert_doc;
extern char const* block_downloading_alert_doc;
extern char const* storage_moved_alert_doc;
extern char const* torrent_deleted_alert_doc;
extern char const* torrent_paused_alert_doc;
extern char const* torrent_checked_alert_doc;
extern char const* url_seed_alert_doc;
extern char const* file_error_alert_doc;
extern char const* metadata_failed_alert_doc;
extern char const* metadata_received_alert_doc;
extern char const* listen_failed_alert_doc;
extern char const* listen_succeeded_alert_doc;
extern char const* portmap_error_alert_doc;
extern char const* portmap_alert_doc;
extern char const* fastresume_rejected_alert_doc;
extern char const* peer_blocked_alert_doc;
extern char const* scrape_reply_alert_doc;
extern char const* scrape_failed_alert_doc;
extern char const* udp_error_alert_doc;
extern char const* external_ip_alert_doc;
extern char const* save_resume_data_alert_doc;
void bind_alert()
{
using boost::noncopyable;
{
scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init)
.def(
"msg", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
.def("severity", &alert::severity, alert_severity_doc)
.def(
"__str__", &alert::msg, return_value_policy<copy_const_reference>()
, alert_msg_doc
)
;
enum_<alert::severity_t>("severity_levels")
.value("debug", alert::debug)
.value("info", alert::info)
.value("warning", alert::warning)
.value("critical", alert::critical)
.value("fatal", alert::fatal)
.value("none", alert::none)
;
}
class_<torrent_alert, bases<alert>, noncopyable>(
"torrent_alert", torrent_alert_doc, no_init
)
.def_readonly("handle", &torrent_alert::handle)
;
class_<tracker_alert, bases<torrent_alert>, noncopyable>(
"tracker_alert", tracker_alert_doc, no_init
)
.def_readonly("url", &tracker_alert::url)
;
class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(
"tracker_error_alert", tracker_error_alert_doc, no_init
)
.def_readonly("times_in_row", &tracker_error_alert::times_in_row)
.def_readonly("status_code", &tracker_error_alert::status_code)
;
class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(
"tracker_warning_alert", tracker_warning_alert_doc, no_init
);
class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(
"tracker_reply_alert", tracker_reply_alert_doc, no_init
)
.def_readonly("num_peers", &tracker_reply_alert::num_peers)
;
class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(
"tracker_announce_alert", tracker_announce_alert_doc, no_init
);
class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(
"hash_failed_alert", hash_failed_alert_doc, no_init
)
.def_readonly("piece_index", &hash_failed_alert::piece_index)
;
class_<peer_ban_alert, bases<torrent_alert>, noncopyable>(
"peer_ban_alert", peer_ban_alert_doc, no_init
)
.def_readonly("ip", &peer_ban_alert::ip)
;
class_<peer_error_alert, bases<alert>, noncopyable>(
"peer_error_alert", peer_error_alert_doc, no_init
)
.def_readonly("ip", &peer_error_alert::ip)
.def_readonly("pid", &peer_error_alert::pid)
;
class_<invalid_request_alert, bases<torrent_alert>, noncopyable>(
"invalid_request_alert", invalid_request_alert_doc, no_init
)
.def_readonly("ip", &invalid_request_alert::ip)
.def_readonly("request", &invalid_request_alert::request)
.def_readonly("pid", &invalid_request_alert::pid)
;
class_<peer_request>("peer_request", peer_request_doc)
.def_readonly("piece", &peer_request::piece)
.def_readonly("start", &peer_request::start)
.def_readonly("length", &peer_request::length)
.def(self == self)
;
class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(
"torrent_finished_alert", torrent_finished_alert_doc, no_init
);
class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(
"piece_finished_alert", piece_finished_alert_doc, no_init
)
.def_readonly("piece_index", &piece_finished_alert::piece_index)
;
class_<block_finished_alert, bases<torrent_alert>, noncopyable>(
"block_finished_alert", block_finished_alert_doc, no_init
)
.def_readonly("block_index", &block_finished_alert::block_index)
.def_readonly("piece_index", &block_finished_alert::piece_index)
;
class_<block_downloading_alert, bases<torrent_alert>, noncopyable>(
"block_downloading_alert", block_downloading_alert_doc, no_init
)
.def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg)
.def_readonly("block_index", &block_downloading_alert::block_index)
.def_readonly("piece_index", &block_downloading_alert::piece_index)
;
class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(
"storage_moved_alert", storage_moved_alert_doc, no_init
);
class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(
"torrent_deleted_alert", torrent_deleted_alert_doc, no_init
);
class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(
"torrent_paused_alert", torrent_paused_alert_doc, no_init
);
class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(
"torrent_checked_alert", torrent_checked_alert_doc, no_init
);
class_<url_seed_alert, bases<torrent_alert>, noncopyable>(
"url_seed_alert", url_seed_alert_doc, no_init
)
.def_readonly("url", &url_seed_alert::url)
;
class_<file_error_alert, bases<torrent_alert>, noncopyable>(
"file_error_alert", file_error_alert_doc, no_init
)
.def_readonly("file", &file_error_alert::file)
;
class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(
"metadata_failed_alert", metadata_failed_alert_doc, no_init
);
class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(
"metadata_received_alert", metadata_received_alert_doc, no_init
);
class_<listen_failed_alert, bases<alert>, noncopyable>(
"listen_failed_alert", listen_failed_alert_doc, no_init
);
class_<listen_succeeded_alert, bases<alert>, noncopyable>(
"listen_succeeded_alert", listen_succeeded_alert_doc, no_init
)
.def_readonly("endpoint", &listen_succeeded_alert::endpoint)
;
class_<portmap_error_alert, bases<alert>, noncopyable>(
"portmap_error_alert", portmap_error_alert_doc, no_init
)
.def_readonly("mapping", &portmap_error_alert::mapping)
.def_readonly("type", &portmap_error_alert::type)
;
class_<portmap_alert, bases<alert>, noncopyable>(
"portmap_alert", portmap_alert_doc, no_init
)
.def_readonly("mapping", &portmap_alert::mapping)
.def_readonly("external_port", &portmap_alert::external_port)
.def_readonly("type", &portmap_alert::type)
;
class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(
"fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init
);
class_<peer_blocked_alert, bases<alert>, noncopyable>(
"peer_blocked_alert", peer_blocked_alert_doc, no_init
)
.def_readonly("ip", &peer_blocked_alert::ip)
;
class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(
"scrape_reply_alert", scrape_reply_alert_doc, no_init
)
.def_readonly("incomplete", &scrape_reply_alert::incomplete)
.def_readonly("complete", &scrape_reply_alert::complete)
;
class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(
"scrape_failed_alert", scrape_failed_alert_doc, no_init
);
class_<udp_error_alert, bases<alert>, noncopyable>(
"udp_error_alert", udp_error_alert_doc, no_init
)
.def_readonly("endpoint", &udp_error_alert::endpoint)
;
class_<external_ip_alert, bases<alert>, noncopyable>(
"external_ip_alert", external_ip_alert_doc, no_init
)
.def_readonly("external_address", &external_ip_alert::external_address)
;
class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(
"save_resume_data_alert", save_resume_data_alert_doc, no_init
)
.def_readonly("resume_data", &save_resume_data_alert::resume_data)
;
class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(
"file_renamed_alert", no_init
)
.def_readonly("name", &file_renamed_alert::name)
;
class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(
"torrent_resumed_alert", no_init
);
class_<state_changed_alert, bases<torrent_alert>, noncopyable>(
"state_changed_alert", no_init
)
.def_readonly("state", &state_changed_alert::state)
;
}
<|endoftext|> |
<commit_before>/**
* Copyright 2013 Truphone
*/
#include "include/cli.h"
#include <QCoreApplication>
#include <QDebug>
namespace truphone
{
namespace test
{
namespace cascades
{
namespace cli
{
const char * HarnessCli::STATE_NAMES[] =
{
"Waiting for Server",
"Waiting for Reply",
"Waiting for Recording to start",
"Waiting for a Recorded Command",
"Disconnected"
};
const char * HarnessCli::EVENT_NAMES[] =
{
"Received Initial Message",
"Received Command Reply",
"Received Record Command",
"No more commands to play",
"Disconnected",
"Error"
};
HarnessCli::HarnessCli(QString host,
quint16 port,
bool isRecord,
QFile * const inFile,
QFile * const outFile,
QObject * parent)
: QObject(parent),
stateMachine(WAITING_FOR_SERVER),
recordingMode(isRecord),
stream(new QTcpSocket(this)),
inputFile(inFile),
outputFile(outFile)
{
if (this->stream)
{
bool ok;
ok = connect(this->stream,
SIGNAL(connected()),
SLOT(connectedOk()));
if (ok)
{
ok = connect(this->stream,
SIGNAL(disconnected()),
SLOT(disconnected()));
if (ok)
{
this->stream->connectToHost(host, port);
if (not this->recordingMode)
{
this->outputFile->write(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
this->outputFile->write("<results>\r\n");
}
}
}
}
}
HarnessCli::~HarnessCli()
{
if (this->stream)
{
if (this->stream->isOpen())
{
this->stream->close();
}
}
}
void HarnessCli::connectedOk(void)
{
if (this->stream)
{
const bool ok = connect(this->stream,
SIGNAL(readyRead()),
SLOT(dataReady()));
if (not ok)
{
this->stream->close();
}
}
}
void HarnessCli::postEventToStateMachine(const event_t event)
{
#if defined(QT_DEBUG)
qDebug() << "------------------------------------";
qDebug() << "## Current State: " \
<< STATE_NAMES[this->stateMachine.state()] \
<< " event: " \
<< EVENT_NAMES[event];
#endif // QT_DEBUG
// process any transitions
switch (this->stateMachine.state())
{
case WAITING_FOR_SERVER:
switch (event)
{
case RECEIVED_INITIAL_MESSAGE:
if (this->recordingMode)
{
this->startRecording();
}
else
{
this->transmitNextCommand();
}
break;
case ERROR:
this->shutdown(1);
break;
case DISCONNECT:
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case WAITING_FOR_REPLY:
switch (event)
{
case RECEIVED_COMMAND_REPLY:
this->transmitNextCommand();
break;
case NO_MORE_COMMANDS_TO_PLAY:
this->shutdown();
break;
case ERROR:
this->shutdown(1);
break;
case DISCONNECT:
this->outputFile->write("\t\t<fail terminated=\"true\"/>\r\n");
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case WAITING_FOR_RECORDING_START:
switch (event)
{
case RECEIVED_COMMAND_REPLY:
this->waitForCommandToRecord();
break;
case DISCONNECT:
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case WAITING_FOR_RECORDED_COMMAND:
switch (event)
{
case RECEIVED_RECORD_COMMAND:
this->waitForCommandToRecord();
break;
case DISCONNECT:
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case DISCONNECTED:
/* ignore all events */
break;
}
#if defined(QT_DEBUG)
qDebug() << "## New State : " \
<< STATE_NAMES[this->stateMachine.state()];
#endif // QT_DEBUG
}
void HarnessCli::unexpectedTransition(const event_t event)
{
qDebug() << "Unexpected state transition, State: " \
<< STATE_NAMES[this->stateMachine.state()] \
<< ", event " \
<< EVENT_NAMES[event];
}
void HarnessCli::shutdown(const int exitCode)
{
this->stateMachine.setState(DISCONNECTED);
if (this->inputFile)
{
if (not this->recordingMode)
{
const qint64 bytesAvailable = this->inputFile->bytesAvailable();
if (bytesAvailable > 0)
{
this->outputFile->write("\t<command>\r\n");
this->outputFile->write("\t\t<request terminated=\"true\"/>\r\n");
this->outputFile->write("\t\t<fail terminated=\"true\" bytesLeftInFile=\"");
this->outputFile->write(QString::number(bytesAvailable).toUtf8().constData());
this->outputFile->write("\"/>\r\n");
this->outputFile->write("\t</command>\r\n");
}
this->outputFile->write("</results>\r\n");
}
}
if (this->stream)
{
if (this->stream->isOpen())
{
this->stream->close();
}
}
QCoreApplication::exit(exitCode);
}
void HarnessCli::startRecording()
{
this->stateMachine.setState(WAITING_FOR_RECORDING_START);
this->stream->write("record\r\n");
}
void HarnessCli::waitForCommandToRecord()
{
this->stateMachine.setState(WAITING_FOR_RECORDED_COMMAND);
}
void HarnessCli::transmitNextCommand()
{
const Buffer outputBuffer;
this->stateMachine.setState(WAITING_FOR_REPLY);
qint64 bytesRead = this->inputFile->readLine(outputBuffer.data(),
outputBuffer.length());
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand read" << bytesRead << "bytes";
#endif
if (bytesRead <= 0)
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
while(bytesRead > 0)
{
if (bytesRead > 0)
{
const char * const raw = outputBuffer.cdata();
if (raw[0] == '#')
{
bytesRead = this->inputFile->readLine(outputBuffer.data(),
outputBuffer.length());
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand read" << bytesRead << "bytes";
#endif
if (bytesRead <= 0)
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
}
else if (strcmp(raw, "\r\n")==0 || strcmp(raw, "\n")==0)
{
bytesRead = this->inputFile->readLine(outputBuffer.data(),
outputBuffer.length());
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand read" << bytesRead << "bytes";
#endif
if (bytesRead <= 0)
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
}
else
{
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand writing" << bytesRead << "bytes";
#endif
this->stream->write(outputBuffer.cdata(), bytesRead);
this->outputFile->write("\t<command>\r\n");
this->outputFile->write("\t\t<request sent=\"");
stripNl(outputBuffer.data(), outputBuffer.length());
qDebug() << "<<" << outputBuffer.cdata();
this->outputFile->write(outputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
break;
}
}
else
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
}
}
void HarnessCli::disconnected(void)
{
this->postEventToStateMachine(DISCONNECT);
}
void HarnessCli::stripNl(char * const buffer, const size_t max_len)
{
const size_t slen = strnlen(buffer, max_len);
for (size_t i = 0 ; i < slen ; i++)
{
if (buffer[i] == '\r' or buffer[i] == '\n')
{
buffer[i] = '\0';
}
}
}
void HarnessCli::dataReady(void)
{
if (this->stream)
{
while (this->stream->bytesAvailable())
{
const Buffer inputBuffer;
this->stream->readLine(inputBuffer.data(),
inputBuffer.length());
// don't strip the new lines from a recording buffer
// as the buffer may be too big for the tcp frames
// and get truncated into multiple packets and we'll
// get truncated lines in the script file
if (not this->recordingMode)
{
stripNl(inputBuffer.data(), inputBuffer.length());
}
qDebug() << ">>" << inputBuffer.cdata();
switch (this->stateMachine.state())
{
case WAITING_FOR_SERVER:
if (not this->recordingMode)
{
this->outputFile->write("\t<welcome message=\"");
this->outputFile->write(inputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
}
this->postEventToStateMachine(RECEIVED_INITIAL_MESSAGE);
break;
case WAITING_FOR_RECORDING_START:
this->postEventToStateMachine(RECEIVED_COMMAND_REPLY);
break;
case WAITING_FOR_REPLY:
{
const bool ok = strncmp(inputBuffer.cdata(), "OK", 2) == 0;
if (ok)
{
// thats fine
this->outputFile->write("\t\t<pass recv=\"");
this->outputFile->write(inputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
}
else
{
this->outputFile->write("\t\t<fail recv=\"");
this->outputFile->write(inputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
}
this->outputFile->write("\t</command>\r\n");
if (ok)
{
this->postEventToStateMachine(RECEIVED_COMMAND_REPLY);
}
else
{
this->postEventToStateMachine(ERROR);
}
break;
}
case WAITING_FOR_RECORDED_COMMAND:
this->inputFile->write(inputBuffer.cdata());
this->inputFile->flush();
this->postEventToStateMachine(RECEIVED_RECORD_COMMAND);
break;
default:
break;
}
}
}
}
} // namespace cli
} // namespace cascades
} // namespace test
} // namespace truphone
<commit_msg>Print out comments to the stdout of the cli<commit_after>/**
* Copyright 2013 Truphone
*/
#include "include/cli.h"
#include <QCoreApplication>
#include <QDebug>
namespace truphone
{
namespace test
{
namespace cascades
{
namespace cli
{
const char * HarnessCli::STATE_NAMES[] =
{
"Waiting for Server",
"Waiting for Reply",
"Waiting for Recording to start",
"Waiting for a Recorded Command",
"Disconnected"
};
const char * HarnessCli::EVENT_NAMES[] =
{
"Received Initial Message",
"Received Command Reply",
"Received Record Command",
"No more commands to play",
"Disconnected",
"Error"
};
HarnessCli::HarnessCli(QString host,
quint16 port,
bool isRecord,
QFile * const inFile,
QFile * const outFile,
QObject * parent)
: QObject(parent),
stateMachine(WAITING_FOR_SERVER),
recordingMode(isRecord),
stream(new QTcpSocket(this)),
inputFile(inFile),
outputFile(outFile)
{
if (this->stream)
{
bool ok;
ok = connect(this->stream,
SIGNAL(connected()),
SLOT(connectedOk()));
if (ok)
{
ok = connect(this->stream,
SIGNAL(disconnected()),
SLOT(disconnected()));
if (ok)
{
this->stream->connectToHost(host, port);
if (not this->recordingMode)
{
this->outputFile->write(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
this->outputFile->write("<results>\r\n");
}
}
}
}
}
HarnessCli::~HarnessCli()
{
if (this->stream)
{
if (this->stream->isOpen())
{
this->stream->close();
}
}
}
void HarnessCli::connectedOk(void)
{
if (this->stream)
{
const bool ok = connect(this->stream,
SIGNAL(readyRead()),
SLOT(dataReady()));
if (not ok)
{
this->stream->close();
}
}
}
void HarnessCli::postEventToStateMachine(const event_t event)
{
#if defined(QT_DEBUG)
qDebug() << "------------------------------------";
qDebug() << "## Current State: " \
<< STATE_NAMES[this->stateMachine.state()] \
<< " event: " \
<< EVENT_NAMES[event];
#endif // QT_DEBUG
// process any transitions
switch (this->stateMachine.state())
{
case WAITING_FOR_SERVER:
switch (event)
{
case RECEIVED_INITIAL_MESSAGE:
if (this->recordingMode)
{
this->startRecording();
}
else
{
this->transmitNextCommand();
}
break;
case ERROR:
this->shutdown(1);
break;
case DISCONNECT:
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case WAITING_FOR_REPLY:
switch (event)
{
case RECEIVED_COMMAND_REPLY:
this->transmitNextCommand();
break;
case NO_MORE_COMMANDS_TO_PLAY:
this->shutdown();
break;
case ERROR:
this->shutdown(1);
break;
case DISCONNECT:
this->outputFile->write("\t\t<fail terminated=\"true\"/>\r\n");
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case WAITING_FOR_RECORDING_START:
switch (event)
{
case RECEIVED_COMMAND_REPLY:
this->waitForCommandToRecord();
break;
case DISCONNECT:
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case WAITING_FOR_RECORDED_COMMAND:
switch (event)
{
case RECEIVED_RECORD_COMMAND:
this->waitForCommandToRecord();
break;
case DISCONNECT:
this->shutdown();
break;
default:
this->unexpectedTransition(event);
break;
}
break;
case DISCONNECTED:
/* ignore all events */
break;
}
#if defined(QT_DEBUG)
qDebug() << "## New State : " \
<< STATE_NAMES[this->stateMachine.state()];
#endif // QT_DEBUG
}
void HarnessCli::unexpectedTransition(const event_t event)
{
qDebug() << "Unexpected state transition, State: " \
<< STATE_NAMES[this->stateMachine.state()] \
<< ", event " \
<< EVENT_NAMES[event];
}
void HarnessCli::shutdown(const int exitCode)
{
this->stateMachine.setState(DISCONNECTED);
if (this->inputFile)
{
if (not this->recordingMode)
{
const qint64 bytesAvailable = this->inputFile->bytesAvailable();
if (bytesAvailable > 0)
{
this->outputFile->write("\t<command>\r\n");
this->outputFile->write("\t\t<request terminated=\"true\"/>\r\n");
this->outputFile->write("\t\t<fail terminated=\"true\" bytesLeftInFile=\"");
this->outputFile->write(QString::number(bytesAvailable).toUtf8().constData());
this->outputFile->write("\"/>\r\n");
this->outputFile->write("\t</command>\r\n");
}
this->outputFile->write("</results>\r\n");
}
}
if (this->stream)
{
if (this->stream->isOpen())
{
this->stream->close();
}
}
QCoreApplication::exit(exitCode);
}
void HarnessCli::startRecording()
{
this->stateMachine.setState(WAITING_FOR_RECORDING_START);
this->stream->write("record\r\n");
}
void HarnessCli::waitForCommandToRecord()
{
this->stateMachine.setState(WAITING_FOR_RECORDED_COMMAND);
}
void HarnessCli::transmitNextCommand()
{
const Buffer outputBuffer;
this->stateMachine.setState(WAITING_FOR_REPLY);
qint64 bytesRead = this->inputFile->readLine(outputBuffer.data(),
outputBuffer.length());
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand read" << bytesRead << "bytes";
#endif
if (bytesRead <= 0)
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
while(bytesRead > 0)
{
if (bytesRead > 0)
{
const char * const raw = outputBuffer.cdata();
if (raw[0] == '#')
{
qDebug() << "CC" << QString(raw).trimmed();
bytesRead = this->inputFile->readLine(outputBuffer.data(),
outputBuffer.length());
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand read" << bytesRead << "bytes";
#endif
if (bytesRead <= 0)
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
}
else if (strcmp(raw, "\r\n")==0 || strcmp(raw, "\n")==0)
{
qDebug() << "CC";
bytesRead = this->inputFile->readLine(outputBuffer.data(),
outputBuffer.length());
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand read" << bytesRead << "bytes";
#endif
if (bytesRead <= 0)
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
}
else
{
#if defined(QT_DEBUG)
qDebug() << "transmitNextCommand writing" << bytesRead << "bytes";
#endif
this->stream->write(outputBuffer.cdata(), bytesRead);
this->outputFile->write("\t<command>\r\n");
this->outputFile->write("\t\t<request sent=\"");
stripNl(outputBuffer.data(), outputBuffer.length());
qDebug() << "<<" << outputBuffer.cdata();
this->outputFile->write(outputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
break;
}
}
else
{
this->postEventToStateMachine(NO_MORE_COMMANDS_TO_PLAY);
}
}
}
void HarnessCli::disconnected(void)
{
this->postEventToStateMachine(DISCONNECT);
}
void HarnessCli::stripNl(char * const buffer, const size_t max_len)
{
const size_t slen = strnlen(buffer, max_len);
for (size_t i = 0 ; i < slen ; i++)
{
if (buffer[i] == '\r' or buffer[i] == '\n')
{
buffer[i] = '\0';
}
}
}
void HarnessCli::dataReady(void)
{
if (this->stream)
{
while (this->stream->bytesAvailable())
{
const Buffer inputBuffer;
this->stream->readLine(inputBuffer.data(),
inputBuffer.length());
// don't strip the new lines from a recording buffer
// as the buffer may be too big for the tcp frames
// and get truncated into multiple packets and we'll
// get truncated lines in the script file
if (not this->recordingMode)
{
stripNl(inputBuffer.data(), inputBuffer.length());
}
qDebug() << ">>" << inputBuffer.cdata();
switch (this->stateMachine.state())
{
case WAITING_FOR_SERVER:
if (not this->recordingMode)
{
this->outputFile->write("\t<welcome message=\"");
this->outputFile->write(inputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
}
this->postEventToStateMachine(RECEIVED_INITIAL_MESSAGE);
break;
case WAITING_FOR_RECORDING_START:
this->postEventToStateMachine(RECEIVED_COMMAND_REPLY);
break;
case WAITING_FOR_REPLY:
{
const bool ok = strncmp(inputBuffer.cdata(), "OK", 2) == 0;
if (ok)
{
// thats fine
this->outputFile->write("\t\t<pass recv=\"");
this->outputFile->write(inputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
}
else
{
this->outputFile->write("\t\t<fail recv=\"");
this->outputFile->write(inputBuffer.cdata());
this->outputFile->write("\"/>\r\n");
}
this->outputFile->write("\t</command>\r\n");
if (ok)
{
this->postEventToStateMachine(RECEIVED_COMMAND_REPLY);
}
else
{
this->postEventToStateMachine(ERROR);
}
break;
}
case WAITING_FOR_RECORDED_COMMAND:
this->inputFile->write(inputBuffer.cdata());
this->inputFile->flush();
this->postEventToStateMachine(RECEIVED_RECORD_COMMAND);
break;
default:
break;
}
}
}
}
} // namespace cli
} // namespace cascades
} // namespace test
} // namespace truphone
<|endoftext|> |
<commit_before>// RUN: rm -rf %t
// Test that only forward declarations are emitted for types dfined in modules.
// Modules:
// RUN: %clang_cc1 -x objective-c++ -std=c++11 -g -dwarf-ext-refs -fmodules \
// RUN: -fmodule-format=obj -fimplicit-module-maps -DMODULES \
// RUN: -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t-mod.ll
// RUN: cat %t-mod.ll | FileCheck %s
// PCH:
// RUN: %clang_cc1 -x c++ -std=c++11 -fmodule-format=obj -emit-pch -I%S/Inputs \
// RUN: -o %t.pch %S/Inputs/DebugCXX.h
// RUN: %clang_cc1 -std=c++11 -g -dwarf-ext-refs -fmodule-format=obj \
// RUN: -include-pch %t.pch %s -emit-llvm -o %t-pch.ll %s
// RUN: cat %t-pch.ll | FileCheck %s
#ifdef MODULES
@import DebugCXX;
#endif
using DebugCXX::Struct;
Struct s;
DebugCXX::Enum e;
DebugCXX::Template<long> implicitTemplate;
DebugCXX::Template<int> explicitTemplate;
DebugCXX::FloatInstatiation typedefTemplate;
int Struct::static_member = -1;
enum {
e3 = -1
} conflicting_uid = e3;
auto anon_enum = DebugCXX::e2;
char _anchor = anon_enum + conflicting_uid;
// CHECK: ![[ANON_ENUM:[0-9]+]] = !DICompositeType(tag: DW_TAG_enumeration_type
// CHECK-SAME: scope: ![[MOD:[0-9]+]],
// CHECK-SAME: {{.*}}line: 16, {{.*}}, elements: ![[EE:[0-9]+]])
// CHECK: ![[NS:.*]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]],
// CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX
// CHECK: ![[EE]] = !{![[E2:[0-9]+]]}
// CHECK: ![[E2]] = !DIEnumerator(name: "e2", value: 50)
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE")
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE")
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "static_member",
// CHECK-SAME: scope: !"_ZTSN8DebugCXX6StructE"
// CHECK: !DIGlobalVariable(name: "anon_enum", {{.*}}, type: ![[ANON_ENUM]]
// CHECK: !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: !0, entity: !"_ZTSN8DebugCXX6StructE", line: [[@LINE-53]])
<commit_msg>clang/test/Modules/ExtDebugInfo.cpp: Use %itanium_abi_triple.<commit_after>// RUN: rm -rf %t
// Test that only forward declarations are emitted for types dfined in modules.
// Modules:
// RUN: %clang_cc1 -x objective-c++ -std=c++11 -g -dwarf-ext-refs -fmodules \
// RUN: -triple %itanium_abi_triple \
// RUN: -fmodule-format=obj -fimplicit-module-maps -DMODULES \
// RUN: -fmodules-cache-path=%t %s -I %S/Inputs -I %t -emit-llvm -o %t-mod.ll
// RUN: cat %t-mod.ll | FileCheck %s
// PCH:
// RUN: %clang_cc1 -x c++ -std=c++11 -fmodule-format=obj -emit-pch -I%S/Inputs \
// RUN: -triple %itanium_abi_triple \
// RUN: -o %t.pch %S/Inputs/DebugCXX.h
// RUN: %clang_cc1 -std=c++11 -g -dwarf-ext-refs -fmodule-format=obj \
// RUN: -triple %itanium_abi_triple \
// RUN: -include-pch %t.pch %s -emit-llvm -o %t-pch.ll %s
// RUN: cat %t-pch.ll | FileCheck %s
#ifdef MODULES
@import DebugCXX;
#endif
using DebugCXX::Struct;
Struct s;
DebugCXX::Enum e;
DebugCXX::Template<long> implicitTemplate;
DebugCXX::Template<int> explicitTemplate;
DebugCXX::FloatInstatiation typedefTemplate;
int Struct::static_member = -1;
enum {
e3 = -1
} conflicting_uid = e3;
auto anon_enum = DebugCXX::e2;
char _anchor = anon_enum + conflicting_uid;
// CHECK: ![[ANON_ENUM:[0-9]+]] = !DICompositeType(tag: DW_TAG_enumeration_type
// CHECK-SAME: scope: ![[MOD:[0-9]+]],
// CHECK-SAME: {{.*}}line: 16, {{.*}}, elements: ![[EE:[0-9]+]])
// CHECK: ![[NS:.*]] = !DINamespace(name: "DebugCXX", scope: ![[MOD:[0-9]+]],
// CHECK: ![[MOD]] = !DIModule(scope: null, name: {{.*}}DebugCXX
// CHECK: ![[EE]] = !{![[E2:[0-9]+]]}
// CHECK: ![[E2]] = !DIEnumerator(name: "e2", value: 50)
// CHECK: !DICompositeType(tag: DW_TAG_structure_type, name: "Struct",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX6StructE")
// CHECK: !DICompositeType(tag: DW_TAG_enumeration_type, name: "Enum",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX4EnumE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<int, DebugCXX::traits<int> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIiNS_6traitsIiEEEE")
// CHECK: !DICompositeType(tag: DW_TAG_class_type,
// CHECK-SAME: name: "Template<float, DebugCXX::traits<float> >",
// CHECK-SAME: scope: ![[NS]],
// CHECK-SAME: flags: DIFlagFwdDecl,
// CHECK-SAME: identifier: "_ZTSN8DebugCXX8TemplateIfNS_6traitsIfEEEE")
// CHECK: !DIDerivedType(tag: DW_TAG_member, name: "static_member",
// CHECK-SAME: scope: !"_ZTSN8DebugCXX6StructE"
// CHECK: !DIGlobalVariable(name: "anon_enum", {{.*}}, type: ![[ANON_ENUM]]
// CHECK: !DIImportedEntity(tag: DW_TAG_imported_declaration, scope: !0, entity: !"_ZTSN8DebugCXX6StructE", line: [[@LINE-53]])
<|endoftext|> |
<commit_before><commit_msg>Fixed Windows compiler warning<commit_after><|endoftext|> |
<commit_before><commit_msg>fix: remove CR before comparing to the reference<commit_after><|endoftext|> |
<commit_before><commit_msg>Steam integration for MoF, SA, UFO<commit_after><|endoftext|> |
<commit_before>/*
kopetesockettimeoutwatcher.cpp - Kopete Socket Timeout Watcher
Copyright (c) 2009 Roman Jarosz <kedgedev@centrum.cz>
Kopete (c) 2009 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetesockettimeoutwatcher.h"
#ifdef Q_WS_X11
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#endif
#include <kdebug.h>
#include <QAbstractSocket>
#include <QTimer>
#include <QHostAddress>
namespace Kopete
{
QSet<QAbstractSocket*> SocketTimeoutWatcher::watchedSocketSet;
SocketTimeoutWatcher* SocketTimeoutWatcher::watch( QAbstractSocket* socket, quint32 msecTimeout )
{
if (watchedSocketSet.contains(socket))
{
kDebug() << "Socket is already being watched " << socket;
return 0;
}
return new Kopete::SocketTimeoutWatcher( socket, msecTimeout );
}
SocketTimeoutWatcher::SocketTimeoutWatcher( QAbstractSocket* socket, quint32 msecTimeout )
: QObject(socket), mSocket(socket), mActive(true), mTimeoutThreshold(msecTimeout)
{
watchedSocketSet.insert( mSocket );
mAckCheckTimer = new QTimer();
connect( socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten()) );
connect( socket, SIGNAL(disconnected()), mAckCheckTimer, SLOT(stop()) );
connect( socket, SIGNAL(error(QAbstractSocket::SocketError)), mAckCheckTimer, SLOT(stop()) );
connect( mAckCheckTimer, SIGNAL(timeout()), this, SLOT(ackTimeoutCheck()) );
mAckCheckTimer->setInterval( mTimeoutThreshold );
}
SocketTimeoutWatcher::~SocketTimeoutWatcher()
{
watchedSocketSet.remove( mSocket );
delete mAckCheckTimer;
}
void SocketTimeoutWatcher::bytesWritten()
{
if ( !mActive )
return;
if ( mSocket->socketDescriptor() != -1 )
{
if ( !mAckCheckTimer->isActive() )
mAckCheckTimer->start();
}
else
{
if ( mAckCheckTimer->isActive() )
mAckCheckTimer->stop();
}
}
void SocketTimeoutWatcher::ackTimeoutCheck()
{
const int sDesc = mSocket->socketDescriptor();
if ( sDesc != -1 )
{
#ifdef Q_OS_LINUX
struct tcp_info info;
int info_length = sizeof(info);
if ( getsockopt( sDesc, SOL_TCP, TCP_INFO, (void*)&info, (socklen_t*)&info_length ) == 0 )
{
if ( info.tcpi_last_ack_recv >= info.tcpi_last_data_sent && (info.tcpi_last_ack_recv - info.tcpi_last_data_sent) > mTimeoutThreshold )
{
kWarning() << "Connection timeout for " << mSocket->peerAddress();
mAckCheckTimer->stop();
emit error( QAbstractSocket::RemoteHostClosedError );
emit errorInt( QAbstractSocket::RemoteHostClosedError );
mSocket->abort();
}
else if ( info.tcpi_last_ack_recv < info.tcpi_last_data_sent )
{
mAckCheckTimer->stop();
}
return;
}
#endif
if ( mActive )
{
mAckCheckTimer->stop();
mActive = false;
kWarning() << "Timeout watcher not active for " << mSocket->peerAddress();
}
}
else
{
mAckCheckTimer->stop();
}
}
}
#include "kopetesockettimeoutwatcher.moc"
<commit_msg>Use correct macro, forgot to change it in previous commit.<commit_after>/*
kopetesockettimeoutwatcher.cpp - Kopete Socket Timeout Watcher
Copyright (c) 2009 Roman Jarosz <kedgedev@centrum.cz>
Kopete (c) 2009 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "kopetesockettimeoutwatcher.h"
#ifdef Q_OS_LINUX
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#endif
#include <kdebug.h>
#include <QAbstractSocket>
#include <QTimer>
#include <QHostAddress>
namespace Kopete
{
QSet<QAbstractSocket*> SocketTimeoutWatcher::watchedSocketSet;
SocketTimeoutWatcher* SocketTimeoutWatcher::watch( QAbstractSocket* socket, quint32 msecTimeout )
{
if (watchedSocketSet.contains(socket))
{
kDebug() << "Socket is already being watched " << socket;
return 0;
}
return new Kopete::SocketTimeoutWatcher( socket, msecTimeout );
}
SocketTimeoutWatcher::SocketTimeoutWatcher( QAbstractSocket* socket, quint32 msecTimeout )
: QObject(socket), mSocket(socket), mActive(true), mTimeoutThreshold(msecTimeout)
{
watchedSocketSet.insert( mSocket );
mAckCheckTimer = new QTimer();
connect( socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten()) );
connect( socket, SIGNAL(disconnected()), mAckCheckTimer, SLOT(stop()) );
connect( socket, SIGNAL(error(QAbstractSocket::SocketError)), mAckCheckTimer, SLOT(stop()) );
connect( mAckCheckTimer, SIGNAL(timeout()), this, SLOT(ackTimeoutCheck()) );
mAckCheckTimer->setInterval( mTimeoutThreshold );
}
SocketTimeoutWatcher::~SocketTimeoutWatcher()
{
watchedSocketSet.remove( mSocket );
delete mAckCheckTimer;
}
void SocketTimeoutWatcher::bytesWritten()
{
if ( !mActive )
return;
if ( mSocket->socketDescriptor() != -1 )
{
if ( !mAckCheckTimer->isActive() )
mAckCheckTimer->start();
}
else
{
if ( mAckCheckTimer->isActive() )
mAckCheckTimer->stop();
}
}
void SocketTimeoutWatcher::ackTimeoutCheck()
{
const int sDesc = mSocket->socketDescriptor();
if ( sDesc != -1 )
{
#ifdef Q_OS_LINUX
struct tcp_info info;
int info_length = sizeof(info);
if ( getsockopt( sDesc, SOL_TCP, TCP_INFO, (void*)&info, (socklen_t*)&info_length ) == 0 )
{
if ( info.tcpi_last_ack_recv >= info.tcpi_last_data_sent && (info.tcpi_last_ack_recv - info.tcpi_last_data_sent) > mTimeoutThreshold )
{
kWarning() << "Connection timeout for " << mSocket->peerAddress();
mAckCheckTimer->stop();
emit error( QAbstractSocket::RemoteHostClosedError );
emit errorInt( QAbstractSocket::RemoteHostClosedError );
mSocket->abort();
}
else if ( info.tcpi_last_ack_recv < info.tcpi_last_data_sent )
{
mAckCheckTimer->stop();
}
return;
}
#endif
if ( mActive )
{
mAckCheckTimer->stop();
mActive = false;
kWarning() << "Timeout watcher not active for " << mSocket->peerAddress();
}
}
else
{
mAckCheckTimer->stop();
}
}
}
#include "kopetesockettimeoutwatcher.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2010 by Arduino LLC. All rights reserved.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as
* published by the Free Software Foundation.
*/
#include <stdio.h>
#include <string.h>
#include "w5100.h"
// W5100 controller instance
W5100Class W5100;
#define TX_RX_MAX_BUF_SIZE 2048
#define TX_BUF 0x1100
#define RX_BUF (TX_BUF + TX_RX_MAX_BUF_SIZE)
#define TXBUF_BASE 0x4000
#define RXBUF_BASE 0x6000
void W5100Class::init(void)
{
delay(300);
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
SPI.begin();
initSS();
#else
SPI.begin(SPI_CS);
// Set clock to 4Mhz (W5100 should support up to about 14Mhz)
SPI.setClockDivider(SPI_CS, 21);
SPI.setDataMode(SPI_CS, SPI_MODE0);
#endif
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
writeMR(1<<RST);
writeTMSR(0x55);
writeRMSR(0x55);
SPI.endTransaction();
for (int i=0; i<MAX_SOCK_NUM; i++) {
SBASE[i] = TXBUF_BASE + SSIZE * i;
RBASE[i] = RXBUF_BASE + RSIZE * i;
}
}
uint16_t W5100Class::getTXFreeSize(SOCKET s)
{
uint16_t val=0, val1=0;
do {
val1 = readSnTX_FSR(s);
if (val1 != 0)
val = readSnTX_FSR(s);
}
while (val != val1);
return val;
}
uint16_t W5100Class::getRXReceivedSize(SOCKET s)
{
uint16_t val=0,val1=0;
do {
val1 = readSnRX_RSR(s);
if (val1 != 0)
val = readSnRX_RSR(s);
}
while (val != val1);
return val;
}
void W5100Class::send_data_processing(SOCKET s, const uint8_t *data, uint16_t len)
{
// This is same as having no offset in a call to send_data_processing_offset
send_data_processing_offset(s, 0, data, len);
}
void W5100Class::send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len)
{
uint16_t ptr = readSnTX_WR(s);
ptr += data_offset;
uint16_t offset = ptr & SMASK;
uint16_t dstAddr = offset + SBASE[s];
if (offset + len > SSIZE)
{
// Wrap around circular buffer
uint16_t size = SSIZE - offset;
write(dstAddr, data, size);
write(SBASE[s], data + size, len - size);
}
else {
write(dstAddr, data, len);
}
ptr += len;
writeSnTX_WR(s, ptr);
}
void W5100Class::recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek)
{
uint16_t ptr;
ptr = readSnRX_RD(s);
read_data(s, ptr, data, len);
if (!peek)
{
ptr += len;
writeSnRX_RD(s, ptr);
}
}
void W5100Class::read_data(SOCKET s, volatile uint16_t src, volatile uint8_t *dst, uint16_t len)
{
uint16_t size;
uint16_t src_mask;
uint16_t src_ptr;
src_mask = src & RMASK;
src_ptr = RBASE[s] + src_mask;
if( (src_mask + len) > RSIZE )
{
size = RSIZE - src_mask;
read(src_ptr, (uint8_t *)dst, size);
dst += size;
read(RBASE[s], (uint8_t *) dst, len - size);
}
else
read(src_ptr, (uint8_t *) dst, len);
}
uint8_t W5100Class::write(uint16_t _addr, uint8_t _data)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0xF0);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
SPI.transfer(_data);
resetSS();
#else
SPI.transfer(SPI_CS, 0xF0, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE);
SPI.transfer(SPI_CS, _data);
#endif
return 1;
}
uint16_t W5100Class::write(uint16_t _addr, const uint8_t *_buf, uint16_t _len)
{
for (uint16_t i=0; i<_len; i++)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0xF0);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
_addr++;
SPI.transfer(_buf[i]);
resetSS();
#else
SPI.transfer(SPI_CS, 0xF0, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE);
SPI.transfer(SPI_CS, _buf[i]);
_addr++;
#endif
}
return _len;
}
uint8_t W5100Class::read(uint16_t _addr)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0x0F);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
uint8_t _data = SPI.transfer(0);
resetSS();
#else
SPI.transfer(SPI_CS, 0x0F, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE);
uint8_t _data = SPI.transfer(SPI_CS, 0);
#endif
return _data;
}
uint16_t W5100Class::read(uint16_t _addr, uint8_t *_buf, uint16_t _len)
{
for (uint16_t i=0; i<_len; i++)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0x0F);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
_addr++;
_buf[i] = SPI.transfer(0);
resetSS();
#else
SPI.transfer(SPI_CS, 0x0F, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(SPI_CS, _addr & 0xFF, SPI_CONTINUE);
_buf[i] = SPI.transfer(SPI_CS, 0);
_addr++;
#endif
}
return _len;
}
void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) {
// Send command to socket
writeSnCR(s, _cmd);
// Wait for command to complete
while (readSnCR(s))
;
}
<commit_msg>Ethernet: fixed regression for SAM (Arduino Due)<commit_after>/*
* Copyright (c) 2010 by Arduino LLC. All rights reserved.
*
* This file is free software; you can redistribute it and/or modify
* it under the terms of either the GNU General Public License version 2
* or the GNU Lesser General Public License version 2.1, both as
* published by the Free Software Foundation.
*/
#include <stdio.h>
#include <string.h>
#include "w5100.h"
// W5100 controller instance
W5100Class W5100;
#define TX_RX_MAX_BUF_SIZE 2048
#define TX_BUF 0x1100
#define RX_BUF (TX_BUF + TX_RX_MAX_BUF_SIZE)
#define TXBUF_BASE 0x4000
#define RXBUF_BASE 0x6000
void W5100Class::init(void)
{
delay(300);
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
SPI.begin();
initSS();
#else
SPI.begin(ETHERNET_SHIELD_SPI_CS);
// Set clock to 4Mhz (W5100 should support up to about 14Mhz)
SPI.setClockDivider(ETHERNET_SHIELD_SPI_CS, 21);
SPI.setDataMode(ETHERNET_SHIELD_SPI_CS, SPI_MODE0);
#endif
SPI.beginTransaction(SPI_ETHERNET_SETTINGS);
writeMR(1<<RST);
writeTMSR(0x55);
writeRMSR(0x55);
SPI.endTransaction();
for (int i=0; i<MAX_SOCK_NUM; i++) {
SBASE[i] = TXBUF_BASE + SSIZE * i;
RBASE[i] = RXBUF_BASE + RSIZE * i;
}
}
uint16_t W5100Class::getTXFreeSize(SOCKET s)
{
uint16_t val=0, val1=0;
do {
val1 = readSnTX_FSR(s);
if (val1 != 0)
val = readSnTX_FSR(s);
}
while (val != val1);
return val;
}
uint16_t W5100Class::getRXReceivedSize(SOCKET s)
{
uint16_t val=0,val1=0;
do {
val1 = readSnRX_RSR(s);
if (val1 != 0)
val = readSnRX_RSR(s);
}
while (val != val1);
return val;
}
void W5100Class::send_data_processing(SOCKET s, const uint8_t *data, uint16_t len)
{
// This is same as having no offset in a call to send_data_processing_offset
send_data_processing_offset(s, 0, data, len);
}
void W5100Class::send_data_processing_offset(SOCKET s, uint16_t data_offset, const uint8_t *data, uint16_t len)
{
uint16_t ptr = readSnTX_WR(s);
ptr += data_offset;
uint16_t offset = ptr & SMASK;
uint16_t dstAddr = offset + SBASE[s];
if (offset + len > SSIZE)
{
// Wrap around circular buffer
uint16_t size = SSIZE - offset;
write(dstAddr, data, size);
write(SBASE[s], data + size, len - size);
}
else {
write(dstAddr, data, len);
}
ptr += len;
writeSnTX_WR(s, ptr);
}
void W5100Class::recv_data_processing(SOCKET s, uint8_t *data, uint16_t len, uint8_t peek)
{
uint16_t ptr;
ptr = readSnRX_RD(s);
read_data(s, ptr, data, len);
if (!peek)
{
ptr += len;
writeSnRX_RD(s, ptr);
}
}
void W5100Class::read_data(SOCKET s, volatile uint16_t src, volatile uint8_t *dst, uint16_t len)
{
uint16_t size;
uint16_t src_mask;
uint16_t src_ptr;
src_mask = src & RMASK;
src_ptr = RBASE[s] + src_mask;
if( (src_mask + len) > RSIZE )
{
size = RSIZE - src_mask;
read(src_ptr, (uint8_t *)dst, size);
dst += size;
read(RBASE[s], (uint8_t *) dst, len - size);
}
else
read(src_ptr, (uint8_t *) dst, len);
}
uint8_t W5100Class::write(uint16_t _addr, uint8_t _data)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0xF0);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
SPI.transfer(_data);
resetSS();
#else
SPI.transfer(ETHERNET_SHIELD_SPI_CS, 0xF0, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr & 0xFF, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _data);
#endif
return 1;
}
uint16_t W5100Class::write(uint16_t _addr, const uint8_t *_buf, uint16_t _len)
{
for (uint16_t i=0; i<_len; i++)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0xF0);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
_addr++;
SPI.transfer(_buf[i]);
resetSS();
#else
SPI.transfer(ETHERNET_SHIELD_SPI_CS, 0xF0, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr & 0xFF, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _buf[i]);
_addr++;
#endif
}
return _len;
}
uint8_t W5100Class::read(uint16_t _addr)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0x0F);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
uint8_t _data = SPI.transfer(0);
resetSS();
#else
SPI.transfer(ETHERNET_SHIELD_SPI_CS, 0x0F, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr & 0xFF, SPI_CONTINUE);
uint8_t _data = SPI.transfer(ETHERNET_SHIELD_SPI_CS, 0);
#endif
return _data;
}
uint16_t W5100Class::read(uint16_t _addr, uint8_t *_buf, uint16_t _len)
{
for (uint16_t i=0; i<_len; i++)
{
#if !defined(SPI_HAS_EXTENDED_CS_PIN_HANDLING)
setSS();
SPI.transfer(0x0F);
SPI.transfer(_addr >> 8);
SPI.transfer(_addr & 0xFF);
_addr++;
_buf[i] = SPI.transfer(0);
resetSS();
#else
SPI.transfer(ETHERNET_SHIELD_SPI_CS, 0x0F, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr >> 8, SPI_CONTINUE);
SPI.transfer(ETHERNET_SHIELD_SPI_CS, _addr & 0xFF, SPI_CONTINUE);
_buf[i] = SPI.transfer(ETHERNET_SHIELD_SPI_CS, 0);
_addr++;
#endif
}
return _len;
}
void W5100Class::execCmdSn(SOCKET s, SockCMD _cmd) {
// Send command to socket
writeSnCR(s, _cmd);
// Wait for command to complete
while (readSnCR(s))
;
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief shutdown request handler
///
/// @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 Max Neunhoeffer
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "RestShutdownHandler.h"
#include "Basics/json.h"
#include "Basics/tri-strings.h"
#include "Rest/HttpRequest.h"
using namespace std;
using namespace triagens::admin;
using namespace triagens::rest;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
RestShutdownHandler::RestShutdownHandler (triagens::rest::HttpRequest* request,
void* applicationServer)
: RestBaseHandler(request),
_applicationServer(
static_cast<triagens::rest::ApplicationServer*>(applicationServer)) {
}
// -----------------------------------------------------------------------------
// --SECTION-- Handler methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool RestShutdownHandler::isDirect () const {
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_get_api_initiate
/// @brief initiates the shutdown sequence
///
/// @RESTHEADER{GET /_admin/shutdown, Initiate shutdown sequence}
///
/// @RESTDESCRIPTION
/// This call initiates a clean shutdown sequence.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned in all cases.
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////
HttpHandler::status_t RestShutdownHandler::execute () {
_applicationServer->beginShutdown();
TRI_json_t result;
TRI_InitStringJson(&result, TRI_DuplicateStringZ(TRI_CORE_MEM_ZONE, "OK"), strlen("OK"));
generateResult(&result);
TRI_DestroyJson(TRI_CORE_MEM_ZONE, &result);
return status_t(HANDLER_DONE);
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>The ShutdownHandler now uses VelocityPack instead of TRI_json_t<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief shutdown request handler
///
/// @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 Max Neunhoeffer
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "RestShutdownHandler.h"
#include "Rest/HttpRequest.h"
using namespace std;
using namespace triagens::admin;
using namespace triagens::rest;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
RestShutdownHandler::RestShutdownHandler (triagens::rest::HttpRequest* request,
void* applicationServer)
: RestBaseHandler(request),
_applicationServer(
static_cast<triagens::rest::ApplicationServer*>(applicationServer)) {
}
// -----------------------------------------------------------------------------
// --SECTION-- Handler methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool RestShutdownHandler::isDirect () const {
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @startDocuBlock JSF_get_api_initiate
/// @brief initiates the shutdown sequence
///
/// @RESTHEADER{GET /_admin/shutdown, Initiate shutdown sequence}
///
/// @RESTDESCRIPTION
/// This call initiates a clean shutdown sequence.
///
/// @RESTRETURNCODES
///
/// @RESTRETURNCODE{200}
/// is returned in all cases.
/// @endDocuBlock
////////////////////////////////////////////////////////////////////////////////
HttpHandler::status_t RestShutdownHandler::execute () {
_applicationServer->beginShutdown();
try {
VPackBuilder json;
json.add(VPackValue("OK"));
VPackSlice slice(json.start());
generateResult(slice);
}
catch (...) {
// Ignore the error
}
return status_t(HANDLER_DONE);
}
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>#include "ClassServer_wrap.h"
#include <boost/python/class.hpp>
//#include <boost/python/return_value_policy.hpp>
//#include <boost/python/reference_existing_object.hpp>
//#include <boost/python/overloads.hpp>
#include <opencog/atomspace/ClassServer.h>
using namespace opencog;
using namespace boost::python;
//BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(addLink_overloads, addLink, 1, 11)
void init_ClassServer_py()
{
class_<ClassServer, boost::noncopyable>("ClassServer", no_init)
.def("getType", &ClassServer::getType)
;
}
<commit_msg>Exposed createInstance() method of ClassServer class.<commit_after>#include "ClassServer_wrap.h"
#include <boost/python/class.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/manage_new_object.hpp>
//#include <boost/python/overloads.hpp>
#include <opencog/atomspace/ClassServer.h>
using namespace opencog;
using namespace boost::python;
//BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(addLink_overloads, addLink, 1, 11)
void init_ClassServer_py()
{
class_<ClassServer, boost::noncopyable>("ClassServer", no_init)
.def("createInstance", &ClassServer::createInstance,
return_value_policy<manage_new_object>())
.staticmethod("createInstance")
.def("getType", &ClassServer::getType)
;
}
<|endoftext|> |
<commit_before>#include "../base/SRC_FIRST.hpp"
#include "../base/mutex.hpp"
#include "../base/timer.hpp"
#include "../base/logging.hpp"
#include "../std/bind.hpp"
#include "../yg/internal/opengl.hpp"
#include "../yg/render_state.hpp"
#include "../yg/rendercontext.hpp"
#include "../yg/framebuffer.hpp"
#include "../yg/renderbuffer.hpp"
#include "../yg/texture.hpp"
#include "../yg/resource_manager.hpp"
#include "../yg/screen.hpp"
#include "../yg/pen_info.hpp"
#include "../yg/skin.hpp"
#include "../indexer/scales.hpp"
#include "events.hpp"
#include "drawer_yg.hpp"
#include "window_handle.hpp"
#include "render_queue_routine.hpp"
RenderQueueRoutine::RenderModelCommand::RenderModelCommand(ScreenBase const & frameScreen,
render_fn_t renderFn)
: m_frameScreen(frameScreen),
m_renderFn(renderFn)
{}
RenderQueueRoutine::RenderQueueRoutine(shared_ptr<yg::gl::RenderState> const & renderState,
string const & skinName,
bool isMultiSampled,
bool doPeriodicalUpdate)
{
m_skinName = skinName;
m_visualScale = 0;
m_renderState = renderState;
m_renderState->addInvalidateFn(bind(&RenderQueueRoutine::invalidate, this));
m_isMultiSampled = isMultiSampled;
m_doPeriodicalUpdate = doPeriodicalUpdate;
}
void RenderQueueRoutine::Cancel()
{
IRoutine::Cancel();
/// Waking up the sleeping thread...
m_hasRenderCommands.Signal();
/// ...Or cancelling the current rendering command in progress.
if (m_currentRenderCommand != 0)
m_currentRenderCommand->m_paintEvent->setIsCancelled(true);
}
void RenderQueueRoutine::processResize(ScreenBase const & /*frameScreen*/)
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
if (m_renderState->m_isResized)
{
size_t texW = m_renderState->m_textureWidth;
size_t texH = m_renderState->m_textureHeight;
m_renderState->m_backBufferLayers.clear();
m_renderState->m_backBufferLayers.push_back(make_shared_ptr(new yg::gl::RawRGBA8Texture(texW, texH)));
/// layer for texts
m_renderState->m_backBufferLayers.push_back(make_shared_ptr(new yg::gl::RawRGBA8Texture(texW, texH)));
m_renderState->m_depthBuffer.reset();
if (!m_isMultiSampled)
{
m_renderState->m_depthBuffer = make_shared_ptr(new yg::gl::RenderBuffer(texW, texH, true));
m_threadDrawer->screen()->frameBuffer()->setDepthBuffer(m_renderState->m_depthBuffer);
}
m_threadDrawer->onSize(texW, texH);
m_threadDrawer->screen()->frameBuffer()->onSize(texW, texH);
m_renderState->m_actualTarget.reset();
m_renderState->m_actualTarget = make_shared_ptr(new yg::gl::RawRGBA8Texture(texW, texH));
m_auxScreen->onSize(texW, texH);
m_auxScreen->setRenderTarget(m_renderState->m_actualTarget);
m_auxScreen->beginFrame();
m_auxScreen->clear();
m_auxScreen->endFrame();
// m_renderState->m_actualTarget->fill(yg::Color(192, 192, 192, 255));
for (size_t i = 0; i < m_renderState->m_backBufferLayers.size(); ++i)
{
m_auxScreen->setRenderTarget(m_renderState->m_backBufferLayers[i]);
m_auxScreen->beginFrame();
m_auxScreen->clear();
m_auxScreen->endFrame();
}
// m_renderState->m_backBufferLayers[i]->fill(yg::Color(192, 192, 192, 255));
m_renderState->m_doRepaintAll = true;
m_renderState->m_isResized = false;
}
}
void RenderQueueRoutine::getUpdateAreas(vector<m2::RectI> & areas)
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
size_t w = m_renderState->m_textureWidth;
size_t h = m_renderState->m_textureHeight;
if (m_renderState->m_doRepaintAll)
{
m_renderState->m_doRepaintAll = false;
areas.push_back(m2::RectI(0, 0, w, h));
return;
}
if (m_renderState->isPanning())
{
/// adding two rendering sub-commands to render new areas, opened by panning.
double dx = 0;
double dy = 0;
m_renderState->m_actualScreen.PtoG(dx, dy);
m_renderState->m_currentScreen.GtoP(dx, dy);
if (dx > 0)
dx = ceil(dx);
else
dx = floor(dx);
if (dy > 0)
dy = ceil(dy);
else
dy = floor(dy);
double minX, maxX;
double minY, maxY;
if (dx > 0)
minX = 0;
else
minX = w + dx;
maxX = minX + my::Abs(dx);
if (dy > 0)
minY = 0;
else
minY = h + dy;
maxY = minY + my::Abs(dy);
if ((my::Abs(dx) > w) || (my::Abs(dy) > h))
areas.push_back(m2::RectI(0, 0, w, h));
else
{
if (minX != maxX)
areas.push_back(m2::RectI(minX, 0, maxX, h));
if (minY != maxY)
{
if (minX == 0)
areas.push_back(m2::RectI(maxX, minY, w, maxY));
else
areas.push_back(m2::RectI(0, minY, minX, maxY));
}
}
}
else
{
areas.push_back(m2::RectI(0, 0, w, h));
/* int rectW = (w + 9) / 5;
int rectH = (h + 9) / 5;
m2::RectI r( 2 * rectW, 2 * rectH, 3 * rectW, 3 * rectH);
areas.push_back(r);
areas.push_back(m2::Offset(r, -rectW, 0));
areas.push_back(m2::Offset(r, -rectW, -rectH));
areas.push_back(m2::Offset(r, 0, -rectH));
areas.push_back(m2::Offset(r, rectW, -rectH));
areas.push_back(m2::Offset(r, rectW, 0));
areas.push_back(m2::Offset(r, rectW, rectH));
areas.push_back(m2::Offset(r, 0, rectH));
areas.push_back(m2::Offset(r, -rectW, rectH));
areas.push_back(m2::Offset(r, -2 * rectW, rectH));
areas.push_back(m2::Offset(r, -2 * rectW, 0));
areas.push_back(m2::Offset(r, -2 * rectW, -rectH));
areas.push_back(m2::Offset(r, -2 * rectW, -2*rectH));
areas.push_back(m2::Offset(r, -rectW, -2*rectH));
areas.push_back(m2::Offset(r, 0, -2*rectH));
areas.push_back(m2::Offset(r, rectW, -2*rectH));
areas.push_back(m2::Offset(r, 2 * rectW, -2*rectH));
areas.push_back(m2::Offset(r, 2 * rectW, -rectH));
areas.push_back(m2::Offset(r, 2 * rectW, 0));
areas.push_back(m2::Offset(r, 2 * rectW, rectH));
areas.push_back(m2::Offset(r, 2 * rectW, 2*rectH));
areas.push_back(m2::Offset(r, rectW, 2*rectH));
areas.push_back(m2::Offset(r, 0, 2*rectH));
areas.push_back(m2::Offset(r, -rectW, 2*rectH));
areas.push_back(m2::Offset(r, -2*rectW, 2*rectH));
*/
}
}
void RenderQueueRoutine::setVisualScale(double visualScale)
{
m_visualScale = visualScale;
}
void RenderQueueRoutine::Do()
{
m_renderContext->makeCurrent();
m_frameBuffer = make_shared_ptr(new yg::gl::FrameBuffer());
DrawerYG::params_t params;
params.m_resourceManager = m_resourceManager;
params.m_isMultiSampled = m_isMultiSampled;
params.m_frameBuffer = m_frameBuffer;
params.m_renderState = m_renderState;
params.m_doPeriodicalUpdate = m_doPeriodicalUpdate;
params.m_textTreeAutoClean = false;
m_threadDrawer = make_shared_ptr(new DrawerYG(m_skinName, params));
yg::gl::Screen::Params auxParams;
auxParams.m_frameBuffer = m_frameBuffer;
m_auxScreen = make_shared_ptr(new yg::gl::Screen(auxParams));
CHECK(m_visualScale != 0, ("Set the VisualScale first!"));
m_threadDrawer->SetVisualScale(m_visualScale);
m_fakeTarget = make_shared_ptr(new yg::gl::RGBA8Texture(2, 2));
yg::gl::RenderState s;
while (!IsCancelled())
{
{
threads::ConditionGuard guard(m_hasRenderCommands);
while (m_renderCommands.empty())
{
guard.Wait();
if (IsCancelled())
break;
}
if (IsCancelled())
break;
/// Preparing render command for execution.
m_currentRenderCommand = m_renderCommands.front();
m_renderCommands.erase(m_renderCommands.begin());
processResize(m_currentRenderCommand->m_frameScreen);
m_threadDrawer->screen()->setRenderTarget(m_renderState->m_backBufferLayers.front());
m_currentRenderCommand->m_paintEvent = make_shared_ptr(new PaintEvent(m_threadDrawer));
/// this prevents the framework from flooding us with a bunch of RenderCommands with the same screen.
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
m_renderState->m_currentScreen = m_currentRenderCommand->m_frameScreen;
s = *m_renderState.get();
}
}
my::Timer timer;
/// At this point renderQueue->mutex is released to allow
/// main thread to add new rendering tasks and blit already
/// rendered model while the current command is actually rendering.
if (m_currentRenderCommand != 0)
{
/// update areas in pixel coordinates.
vector<m2::RectI> areas;
getUpdateAreas(areas);
m_threadDrawer->beginFrame();
m_threadDrawer->screen()->enableClipRect(true);
m_threadDrawer->screen()->setClipRect(m2::RectI(0, 0, s.m_textureWidth, s.m_textureHeight));
m_threadDrawer->clear();
if (s.isPanning())
{
m_threadDrawer->screen()->blit(
s.m_actualTarget,
s.m_actualScreen,
s.m_currentScreen);
m2::RectD curRect(0, 0, s.m_textureWidth, s.m_textureHeight);
m2::RectD oldRect(s.m_currentScreen.GtoP(s.m_actualScreen.PtoG(m2::PointD(0, 0))),
s.m_currentScreen.GtoP(s.m_actualScreen.PtoG(m2::PointD(s.m_textureWidth, s.m_textureHeight))));
if (!curRect.Intersect(oldRect))
curRect = m2::RectD(0, 0, 0, 0);
m_threadDrawer->screen()->offsetTextTree(
s.m_currentScreen.GtoP(s.m_actualScreen.PtoG(m2::PointD(0, 0))),
curRect);
}
else
m_threadDrawer->screen()->clearTextTree();
ScreenBase const & frameScreen = m_currentRenderCommand->m_frameScreen;
m2::RectD glbRect;
frameScreen.PtoG(m2::RectD(0, 0, s.m_surfaceWidth, s.m_surfaceHeight), glbRect);
int scaleLevel = scales::GetScaleLevel(glbRect);
for (size_t i = 0; i < areas.size(); ++i)
{
if ((areas[i].SizeX() != 0) && (areas[i].SizeY() != 0))
{
frameScreen.PtoG(m2::Inflate<double>(m2::RectD(areas[i]), 30 * m_visualScale, 30 * m_visualScale), glbRect);
if ((glbRect.SizeX() == 0) || (glbRect.SizeY() == 0))
continue;
m_threadDrawer->screen()->setClipRect(areas[i]);
m_currentRenderCommand->m_renderFn(
m_currentRenderCommand->m_paintEvent,
m_currentRenderCommand->m_frameScreen,
glbRect,
scaleLevel);
}
}
/// setting the "whole texture" clip rect to render texts opened by panning.
m_threadDrawer->screen()->setClipRect(m2::RectI(0, 0, s.m_textureWidth, s.m_textureHeight));
m_threadDrawer->endFrame();
}
double duration = timer.ElapsedSeconds();
// LOG(LINFO, ("FrameDuration: ", duration));
if (!IsCancelled())
{
/// We shouldn't update the actual target as it's already happened (through callback function)
/// in the endFrame function
/// updateActualTarget();
m_currentRenderCommand.reset();
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
m_renderState->m_duration = duration;
}
invalidate();
}
}
// By VNG: We can't destroy render context in drawing thread.
// Notify render context instead.
m_renderContext->endThreadDrawing();
}
void RenderQueueRoutine::addWindowHandle(shared_ptr<WindowHandle> window)
{
m_windowHandles.push_back(window);
}
void RenderQueueRoutine::invalidate()
{
for_each(m_windowHandles.begin(),
m_windowHandles.end(),
bind(&WindowHandle::invalidate, _1));
}
void RenderQueueRoutine::addCommand(render_fn_t const & fn, ScreenBase const & frameScreen)
{
/// Command queue modification is syncronized by mutex
threads::ConditionGuard guard(m_hasRenderCommands);
bool needToSignal = m_renderCommands.empty();
/// Clearing a list of commands.
m_renderCommands.clear();
/// pushing back new RenderCommand.
m_renderCommands.push_back(make_shared_ptr(new RenderModelCommand(frameScreen, fn)));
/// if we are not panning, we should cancel the render command in progress to start a new one
if ((m_currentRenderCommand != 0) && (!IsPanning(m_currentRenderCommand->m_frameScreen, frameScreen)))
m_currentRenderCommand->m_paintEvent->setIsCancelled(true);
if (needToSignal)
guard.Signal();
}
void RenderQueueRoutine::initializeGL(shared_ptr<yg::gl::RenderContext> const & renderContext,
shared_ptr<yg::ResourceManager> const & resourceManager)
{
m_renderContext = renderContext;
m_resourceManager = resourceManager;
m_threadRenderer.init(renderContext->createShared(), m_renderState);
}
<commit_msg>"first redraw with multisampling on" fix.<commit_after>#include "../base/SRC_FIRST.hpp"
#include "../base/mutex.hpp"
#include "../base/timer.hpp"
#include "../base/logging.hpp"
#include "../std/bind.hpp"
#include "../yg/internal/opengl.hpp"
#include "../yg/render_state.hpp"
#include "../yg/rendercontext.hpp"
#include "../yg/framebuffer.hpp"
#include "../yg/renderbuffer.hpp"
#include "../yg/texture.hpp"
#include "../yg/resource_manager.hpp"
#include "../yg/screen.hpp"
#include "../yg/pen_info.hpp"
#include "../yg/skin.hpp"
#include "../indexer/scales.hpp"
#include "events.hpp"
#include "drawer_yg.hpp"
#include "window_handle.hpp"
#include "render_queue_routine.hpp"
RenderQueueRoutine::RenderModelCommand::RenderModelCommand(ScreenBase const & frameScreen,
render_fn_t renderFn)
: m_frameScreen(frameScreen),
m_renderFn(renderFn)
{}
RenderQueueRoutine::RenderQueueRoutine(shared_ptr<yg::gl::RenderState> const & renderState,
string const & skinName,
bool isMultiSampled,
bool doPeriodicalUpdate)
{
m_skinName = skinName;
m_visualScale = 0;
m_renderState = renderState;
m_renderState->addInvalidateFn(bind(&RenderQueueRoutine::invalidate, this));
m_isMultiSampled = isMultiSampled;
m_doPeriodicalUpdate = doPeriodicalUpdate;
}
void RenderQueueRoutine::Cancel()
{
IRoutine::Cancel();
/// Waking up the sleeping thread...
m_hasRenderCommands.Signal();
/// ...Or cancelling the current rendering command in progress.
if (m_currentRenderCommand != 0)
m_currentRenderCommand->m_paintEvent->setIsCancelled(true);
}
void RenderQueueRoutine::processResize(ScreenBase const & /*frameScreen*/)
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
if (m_renderState->m_isResized)
{
size_t texW = m_renderState->m_textureWidth;
size_t texH = m_renderState->m_textureHeight;
m_renderState->m_backBufferLayers.clear();
m_renderState->m_backBufferLayers.push_back(make_shared_ptr(new yg::gl::RawRGBA8Texture(texW, texH)));
/// layer for texts
m_renderState->m_backBufferLayers.push_back(make_shared_ptr(new yg::gl::RawRGBA8Texture(texW, texH)));
m_renderState->m_depthBuffer.reset();
if (!m_isMultiSampled)
{
m_renderState->m_depthBuffer = make_shared_ptr(new yg::gl::RenderBuffer(texW, texH, true));
m_threadDrawer->screen()->frameBuffer()->setDepthBuffer(m_renderState->m_depthBuffer);
}
m_threadDrawer->onSize(texW, texH);
m_threadDrawer->screen()->frameBuffer()->onSize(texW, texH);
m_renderState->m_actualTarget.reset();
m_renderState->m_actualTarget = make_shared_ptr(new yg::gl::RawRGBA8Texture(texW, texH));
m_auxScreen->onSize(texW, texH);
m_auxScreen->setRenderTarget(m_renderState->m_actualTarget);
m_auxScreen->beginFrame();
m_auxScreen->clear();
m_auxScreen->endFrame();
// m_renderState->m_actualTarget->fill(yg::Color(192, 192, 192, 255));
for (size_t i = 0; i < m_renderState->m_backBufferLayers.size(); ++i)
{
m_auxScreen->setRenderTarget(m_renderState->m_backBufferLayers[i]);
m_auxScreen->beginFrame();
m_auxScreen->clear();
m_auxScreen->endFrame();
}
// m_renderState->m_backBufferLayers[i]->fill(yg::Color(192, 192, 192, 255));
m_renderState->m_doRepaintAll = true;
m_renderState->m_isResized = false;
}
}
void RenderQueueRoutine::getUpdateAreas(vector<m2::RectI> & areas)
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
size_t w = m_renderState->m_textureWidth;
size_t h = m_renderState->m_textureHeight;
if (m_renderState->m_doRepaintAll)
{
m_renderState->m_doRepaintAll = false;
areas.push_back(m2::RectI(0, 0, w, h));
return;
}
if (m_renderState->isPanning())
{
/// adding two rendering sub-commands to render new areas, opened by panning.
double dx = 0;
double dy = 0;
m_renderState->m_actualScreen.PtoG(dx, dy);
m_renderState->m_currentScreen.GtoP(dx, dy);
if (dx > 0)
dx = ceil(dx);
else
dx = floor(dx);
if (dy > 0)
dy = ceil(dy);
else
dy = floor(dy);
double minX, maxX;
double minY, maxY;
if (dx > 0)
minX = 0;
else
minX = w + dx;
maxX = minX + my::Abs(dx);
if (dy > 0)
minY = 0;
else
minY = h + dy;
maxY = minY + my::Abs(dy);
if ((my::Abs(dx) > w) || (my::Abs(dy) > h))
areas.push_back(m2::RectI(0, 0, w, h));
else
{
if (minX != maxX)
areas.push_back(m2::RectI(minX, 0, maxX, h));
if (minY != maxY)
{
if (minX == 0)
areas.push_back(m2::RectI(maxX, minY, w, maxY));
else
areas.push_back(m2::RectI(0, minY, minX, maxY));
}
}
}
else
{
areas.push_back(m2::RectI(0, 0, w, h));
/* int rectW = (w + 9) / 5;
int rectH = (h + 9) / 5;
m2::RectI r( 2 * rectW, 2 * rectH, 3 * rectW, 3 * rectH);
areas.push_back(r);
areas.push_back(m2::Offset(r, -rectW, 0));
areas.push_back(m2::Offset(r, -rectW, -rectH));
areas.push_back(m2::Offset(r, 0, -rectH));
areas.push_back(m2::Offset(r, rectW, -rectH));
areas.push_back(m2::Offset(r, rectW, 0));
areas.push_back(m2::Offset(r, rectW, rectH));
areas.push_back(m2::Offset(r, 0, rectH));
areas.push_back(m2::Offset(r, -rectW, rectH));
areas.push_back(m2::Offset(r, -2 * rectW, rectH));
areas.push_back(m2::Offset(r, -2 * rectW, 0));
areas.push_back(m2::Offset(r, -2 * rectW, -rectH));
areas.push_back(m2::Offset(r, -2 * rectW, -2*rectH));
areas.push_back(m2::Offset(r, -rectW, -2*rectH));
areas.push_back(m2::Offset(r, 0, -2*rectH));
areas.push_back(m2::Offset(r, rectW, -2*rectH));
areas.push_back(m2::Offset(r, 2 * rectW, -2*rectH));
areas.push_back(m2::Offset(r, 2 * rectW, -rectH));
areas.push_back(m2::Offset(r, 2 * rectW, 0));
areas.push_back(m2::Offset(r, 2 * rectW, rectH));
areas.push_back(m2::Offset(r, 2 * rectW, 2*rectH));
areas.push_back(m2::Offset(r, rectW, 2*rectH));
areas.push_back(m2::Offset(r, 0, 2*rectH));
areas.push_back(m2::Offset(r, -rectW, 2*rectH));
areas.push_back(m2::Offset(r, -2*rectW, 2*rectH));
*/
}
}
void RenderQueueRoutine::setVisualScale(double visualScale)
{
m_visualScale = visualScale;
}
void RenderQueueRoutine::Do()
{
m_renderContext->makeCurrent();
m_frameBuffer = make_shared_ptr(new yg::gl::FrameBuffer());
DrawerYG::params_t params;
params.m_resourceManager = m_resourceManager;
params.m_isMultiSampled = m_isMultiSampled;
params.m_frameBuffer = m_frameBuffer;
params.m_renderState = m_renderState;
params.m_doPeriodicalUpdate = m_doPeriodicalUpdate;
params.m_textTreeAutoClean = false;
m_threadDrawer = make_shared_ptr(new DrawerYG(m_skinName, params));
yg::gl::Screen::Params auxParams;
auxParams.m_frameBuffer = m_frameBuffer;
m_auxScreen = make_shared_ptr(new yg::gl::Screen(auxParams));
CHECK(m_visualScale != 0, ("Set the VisualScale first!"));
m_threadDrawer->SetVisualScale(m_visualScale);
m_fakeTarget = make_shared_ptr(new yg::gl::RGBA8Texture(2, 2));
yg::gl::RenderState s;
while (!IsCancelled())
{
{
threads::ConditionGuard guard(m_hasRenderCommands);
while (m_renderCommands.empty())
{
guard.Wait();
if (IsCancelled())
break;
}
if (IsCancelled())
break;
/// Preparing render command for execution.
m_currentRenderCommand = m_renderCommands.front();
m_renderCommands.erase(m_renderCommands.begin());
processResize(m_currentRenderCommand->m_frameScreen);
// m_threadDrawer->screen()->setRenderTarget(m_renderState->m_backBufferLayers.front());
m_currentRenderCommand->m_paintEvent = make_shared_ptr(new PaintEvent(m_threadDrawer));
/// this prevents the framework from flooding us with a bunch of RenderCommands with the same screen.
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
m_renderState->m_currentScreen = m_currentRenderCommand->m_frameScreen;
s = *m_renderState.get();
}
}
my::Timer timer;
/// At this point renderQueue->mutex is released to allow
/// main thread to add new rendering tasks and blit already
/// rendered model while the current command is actually rendering.
if (m_currentRenderCommand != 0)
{
/// update areas in pixel coordinates.
vector<m2::RectI> areas;
getUpdateAreas(areas);
m_threadDrawer->beginFrame();
/// this fixes some strange issue with multisampled framebuffer.
/// setRenderTarget should be made here.
m_threadDrawer->screen()->setRenderTarget(s.m_backBufferLayers.front());
m_threadDrawer->screen()->enableClipRect(true);
m_threadDrawer->screen()->setClipRect(m2::RectI(0, 0, s.m_textureWidth, s.m_textureHeight));
m_threadDrawer->clear();
if (s.isPanning())
{
m_threadDrawer->screen()->blit(
s.m_actualTarget,
s.m_actualScreen,
s.m_currentScreen);
m2::RectD curRect(0, 0, s.m_textureWidth, s.m_textureHeight);
m2::RectD oldRect(s.m_currentScreen.GtoP(s.m_actualScreen.PtoG(m2::PointD(0, 0))),
s.m_currentScreen.GtoP(s.m_actualScreen.PtoG(m2::PointD(s.m_textureWidth, s.m_textureHeight))));
if (!curRect.Intersect(oldRect))
curRect = m2::RectD(0, 0, 0, 0);
m_threadDrawer->screen()->offsetTextTree(
s.m_currentScreen.GtoP(s.m_actualScreen.PtoG(m2::PointD(0, 0))),
curRect);
}
else
m_threadDrawer->screen()->clearTextTree();
ScreenBase const & frameScreen = m_currentRenderCommand->m_frameScreen;
m2::RectD glbRect;
frameScreen.PtoG(m2::RectD(0, 0, s.m_surfaceWidth, s.m_surfaceHeight), glbRect);
int scaleLevel = scales::GetScaleLevel(glbRect);
for (size_t i = 0; i < areas.size(); ++i)
{
if ((areas[i].SizeX() != 0) && (areas[i].SizeY() != 0))
{
frameScreen.PtoG(m2::Inflate<double>(m2::RectD(areas[i]), 30 * m_visualScale, 30 * m_visualScale), glbRect);
if ((glbRect.SizeX() == 0) || (glbRect.SizeY() == 0))
continue;
m_threadDrawer->screen()->setClipRect(areas[i]);
m_currentRenderCommand->m_renderFn(
m_currentRenderCommand->m_paintEvent,
m_currentRenderCommand->m_frameScreen,
glbRect,
scaleLevel);
}
}
/// setting the "whole texture" clip rect to render texts opened by panning.
m_threadDrawer->screen()->setClipRect(m2::RectI(0, 0, s.m_textureWidth, s.m_textureHeight));
m_threadDrawer->endFrame();
}
double duration = timer.ElapsedSeconds();
// LOG(LINFO, ("FrameDuration: ", duration));
if (!IsCancelled())
{
/// We shouldn't update the actual target as it's already happened (through callback function)
/// in the endFrame function
/// updateActualTarget();
m_currentRenderCommand.reset();
{
threads::MutexGuard guard(*m_renderState->m_mutex.get());
m_renderState->m_duration = duration;
}
invalidate();
}
}
// By VNG: We can't destroy render context in drawing thread.
// Notify render context instead.
m_renderContext->endThreadDrawing();
}
void RenderQueueRoutine::addWindowHandle(shared_ptr<WindowHandle> window)
{
m_windowHandles.push_back(window);
}
void RenderQueueRoutine::invalidate()
{
for_each(m_windowHandles.begin(),
m_windowHandles.end(),
bind(&WindowHandle::invalidate, _1));
}
void RenderQueueRoutine::addCommand(render_fn_t const & fn, ScreenBase const & frameScreen)
{
/// Command queue modification is syncronized by mutex
threads::ConditionGuard guard(m_hasRenderCommands);
bool needToSignal = m_renderCommands.empty();
/// Clearing a list of commands.
m_renderCommands.clear();
/// pushing back new RenderCommand.
m_renderCommands.push_back(make_shared_ptr(new RenderModelCommand(frameScreen, fn)));
/// if we are not panning, we should cancel the render command in progress to start a new one
if ((m_currentRenderCommand != 0) && (!IsPanning(m_currentRenderCommand->m_frameScreen, frameScreen)))
m_currentRenderCommand->m_paintEvent->setIsCancelled(true);
if (needToSignal)
guard.Signal();
}
void RenderQueueRoutine::initializeGL(shared_ptr<yg::gl::RenderContext> const & renderContext,
shared_ptr<yg::ResourceManager> const & resourceManager)
{
m_renderContext = renderContext;
m_resourceManager = resourceManager;
m_threadRenderer.init(renderContext->createShared(), m_renderState);
}
<|endoftext|> |
<commit_before>/*********************************************************************
*
* Copyright (C) 2007, Simon Kagstrom
*
* Filename: mips.hh
* Author: Simon Kagstrom <simon.kagstrom@gmail.com>
* Description: MIPS stuff
*
* $Id:$
*
********************************************************************/
#ifndef __MIPS_HH__
#define __MIPS_HH__
#include <stdint.h>
typedef enum
{
R_ZERO = 0,
R_AT = 1,
R_V0 = 2,
R_V1 = 3,
R_A0 = 4,
R_A1 = 5,
R_A2 = 6,
R_A3 = 7,
R_T0 = 8,
R_T1 = 9,
R_T2 = 10,
R_T3 = 11,
R_T4 = 12,
R_T5 = 13,
R_T6 = 14,
R_T7 = 15,
R_S0 = 16,
R_S1 = 17,
R_S2 = 18,
R_S3 = 19,
R_S4 = 20,
R_S5 = 21,
R_S6 = 22,
R_S7 = 23,
R_T8 = 24,
R_T9 = 25,
R_K0 = 26,
R_K1 = 27,
R_GP = 28,
R_SP = 29,
R_S8 = 30,
R_RA = 31,
R_HI = 32,
R_LO = 33,
R_F0 = 40,
R_F1 = 41,
R_F2 = 42,
R_F3 = 43,
R_F4 = 44,
R_F5 = 45,
R_F6 = 46,
R_F7 = 47,
R_F8 = 48,
R_F9 = 49,
R_F10 = 50,
R_F11 = 51,
R_F12 = 52,
R_F13 = 53,
R_F14 = 54,
R_F15 = 55,
R_F16 = 56,
R_F17 = 57,
R_F18 = 58,
R_F19 = 59,
R_F20 = 60,
R_F21 = 61,
R_F22 = 62,
R_F23 = 63,
R_F24 = 64,
R_F25 = 65,
R_F26 = 66,
R_F27 = 67,
R_F28 = 68,
R_F29 = 69,
R_F30 = 70,
R_F31 = 71,
/* Special registers */
R_CPC = 72,
R_CM0 = 73,
R_CM1 = 74,
R_CM2 = 75,
R_CM3 = 76,
R_CM4 = 77,
R_CM5 = 78,
R_CM6 = 79,
R_CM7 = 80,
R_MADR= 81,
R_ECB = 82,
R_EAR = 83,
R_FNA = 84,
R_MEM = 85
} MIPS_register_t;
#define N_REGS 86
typedef enum
{
OP_ADD = 1,
OP_ADDI = 2,
OP_ADDIU = 3,
OP_ADDU = 4,
OP_AND = 5,
OP_ANDI = 6,
OP_BEQ = 7,
OP_BGEZ = 8,
OP_BGEZAL = 9,
OP_BGTZ = 10,
OP_BLEZ = 11,
OP_BLTZ = 12,
OP_BLTZAL = 13,
OP_BNE = 14,
OP_DIV = 16,
OP_DIVU = 17,
OP_J = 18,
OP_JAL = 19,
OP_JALR = 20,
OP_JR = 21,
OP_LB = 22,
OP_LBU = 23,
OP_LH = 24,
OP_LHU = 25,
OP_LUI = 26,
OP_LW = 27,
OP_LWL = 28,
OP_LWR = 29,
OP_MFHI = 31,
OP_MFLO = 32,
OP_MTHI = 34,
OP_MTLO = 35,
OP_MULT = 36,
OP_MULTU = 37,
OP_NOR = 38,
OP_OR = 39,
OP_ORI = 40,
OP_RFE = 41,
OP_SB = 42,
OP_SH = 43,
OP_SLL = 44,
OP_SLLV = 45,
OP_SLT = 46,
OP_SLTI = 47,
OP_SLTIU = 48,
OP_SLTU = 49,
OP_SRA = 50,
OP_SRAV = 51,
OP_SRL = 52,
OP_SRLV = 53,
OP_SUB = 54,
OP_SUBU = 55,
OP_SW = 56,
OP_SWL = 57,
OP_SWR = 58,
OP_XOR = 59,
OP_XORI = 60,
OP_SYSCALL= 61,
OP_UNIMP = 62,
OP_RES = 63,
OP_MFCP0 = 65,
OP_MTCP0 = 66,
OP_CFCP0 = 67,
OP_CTCP0 = 68,
OP_BCCP0 = 69,
OP_TLBR = 70,
OP_TLBWI = 71,
OP_TLBWR = 72,
OP_TLBP = 73,
OP_COP1 = 75,
OP_COP2 = 76,
OP_COP3 = 77,
OP_BREAK = 78,
/* FPU ops */
OP_MFC_1 = 79,
OP_CFC_1 = 80,
OP_MTC_1 = 81,
OP_CTC_1 = 82,
OP_BC1F = 83,
OP_BC1T = 84,
OP_LWC1 = 85,
OP_SWC1 = 86,
OP_FADD = 87,
OP_FSUB = 88,
OP_FMUL = 89,
OP_FDIV = 90,
OP_FSQRT = 91,
OP_FABS = 92,
OP_FMOV = 93,
OP_FNEG = 94,
OP_ROUND_L= 95,
OP_TRUNC_L= 96,
OP_CEIL_L = 98,
OP_FLOOR_L= 99,
OP_CEIL_W = 100,
OP_FLOOR_W= 101,
OP_ROUND_W= 102,
OP_TRUNC_W= 103,
OP_CVT_S = 104,
OP_CVT_D = 105,
OP_CVT_W = 106,
OP_CVT_L = 107,
OP_C_F = 108,
OP_C_UN = 109,
OP_C_EQ = 110,
OP_C_UEQ = 111,
OP_C_OLT = 112,
OP_C_ULT = 113,
OP_C_OLE = 114,
OP_C_ULE = 115,
OP_C_SF = 116,
OP_C_NGLE = 117,
OP_C_SEQ = 118,
OP_C_NGL = 119,
OP_C_LT = 120,
OP_C_NGE = 121,
OP_C_LE = 122,
OP_C_NGT = 123,
SPECIAL = 124,
BCOND = 125,
COP0 = 126,
COP1 = 127,
COP2 = 128,
COP3 = 129,
CIBYL_SYSCALL = 130, /* Needed? */
CIBYL_REGISTER_ARGUMENT = 131,
CIBYL_ASSIGN_MEMREG = 132,
} mips_opcode_t;
#define N_INSNS 133
typedef enum
{
IFMT = 1,
JFMT = 2,
RFMT = 3
} mips_fmt_t;
typedef struct
{
mips_opcode_t type;
mips_fmt_t fmt;
} mips_op_entry_t;
extern mips_op_entry_t mips_op_entries[];
extern mips_opcode_t mips_special_table[];
extern mips_opcode_t mips_cop1_table[];
extern const char *mips_op_strings[];
extern const char *mips_reg_strings[];
/**
* Zero-terminated list of caller-saved MIPS registers
*/
extern MIPS_register_t mips_caller_saved[];
bool mips_zero_extend_opcode(mips_opcode_t opcode);
static inline MIPS_register_t mips_encoding_get_rs(uint32_t word)
{
return (MIPS_register_t)((word >> 21) & 0x1f);
}
static inline MIPS_register_t mips_encoding_get_rt(uint32_t word)
{
return (MIPS_register_t)((word >> 16) & 0x1f);
}
static inline MIPS_register_t mips_encoding_get_rd(uint32_t word)
{
return (MIPS_register_t)((word >> 11) & 0x1f);
}
static inline MIPS_register_t mips_encoding_get_fs(uint32_t word)
{
return (MIPS_register_t)( ((int)mips_encoding_get_rs(word)) + R_F0);
}
static inline MIPS_register_t mips_encoding_get_ft(uint32_t word)
{
return (MIPS_register_t)( ((int)mips_encoding_get_rt(word)) + R_F0);
}
static inline MIPS_register_t mips_encoding_get_fd(uint32_t word)
{
return (MIPS_register_t)( ((word >> 6) & 0x1f) + R_F0);
}
static inline int mips_encoding_get_cp1_fmt(uint32_t word)
{
return (word >> 21) & 0x1f;
}
static inline int mips_encoding_get_cp1_func(uint32_t word)
{
return word & 0x3f;
}
static inline MIPS_register_t mips_int_to_fpu_reg(int v)
{
return (MIPS_register_t)(v + R_F0);
}
static inline bool mips_cp1_fmt_is_double(int fmt)
{
return (fmt & 1) == 1;
}
#endif /* !__MIPS_HH__ */
<commit_msg>Comment reg types<commit_after>/*********************************************************************
*
* Copyright (C) 2007, Simon Kagstrom
*
* Filename: mips.hh
* Author: Simon Kagstrom <simon.kagstrom@gmail.com>
* Description: MIPS stuff
*
* $Id:$
*
********************************************************************/
#ifndef __MIPS_HH__
#define __MIPS_HH__
#include <stdint.h>
typedef enum
{
R_ZERO = 0,
R_AT = 1,
R_V0 = 2,
R_V1 = 3,
R_A0 = 4,
R_A1 = 5,
R_A2 = 6,
R_A3 = 7,
R_T0 = 8,
R_T1 = 9,
R_T2 = 10,
R_T3 = 11,
R_T4 = 12,
R_T5 = 13,
R_T6 = 14,
R_T7 = 15,
R_S0 = 16,
R_S1 = 17,
R_S2 = 18,
R_S3 = 19,
R_S4 = 20,
R_S5 = 21,
R_S6 = 22,
R_S7 = 23,
R_T8 = 24,
R_T9 = 25,
R_K0 = 26,
R_K1 = 27,
R_GP = 28,
R_SP = 29,
R_S8 = 30,
R_RA = 31,
R_HI = 32,
R_LO = 33,
R_F0 = 40,
R_F1 = 41,
R_F2 = 42,
R_F3 = 43,
R_F4 = 44,
R_F5 = 45,
R_F6 = 46,
R_F7 = 47,
R_F8 = 48,
R_F9 = 49,
R_F10 = 50,
R_F11 = 51,
R_F12 = 52,
R_F13 = 53,
R_F14 = 54,
R_F15 = 55,
R_F16 = 56,
R_F17 = 57,
R_F18 = 58,
R_F19 = 59,
R_F20 = 60,
R_F21 = 61,
R_F22 = 62,
R_F23 = 63,
R_F24 = 64,
R_F25 = 65,
R_F26 = 66,
R_F27 = 67,
R_F28 = 68,
R_F29 = 69,
R_F30 = 70,
R_F31 = 71,
/* Special registers */
R_CPC = 72,
R_CM0 = 73,
R_CM1 = 74,
R_CM2 = 75,
R_CM3 = 76,
R_CM4 = 77,
R_CM5 = 78,
R_CM6 = 79,
R_CM7 = 80,
R_MADR= 81, /* Memory address temp for jsr lb/lh/sb/sh */
R_ECB = 82, /* Exception call back address */
R_EAR = 83, /* Exception argument (to function) */
R_FNA = 84, /* Function index (for multi-function methods) */
R_MEM = 85 /* Virtual memory "register" */
} MIPS_register_t;
#define N_REGS 86
typedef enum
{
OP_ADD = 1,
OP_ADDI = 2,
OP_ADDIU = 3,
OP_ADDU = 4,
OP_AND = 5,
OP_ANDI = 6,
OP_BEQ = 7,
OP_BGEZ = 8,
OP_BGEZAL = 9,
OP_BGTZ = 10,
OP_BLEZ = 11,
OP_BLTZ = 12,
OP_BLTZAL = 13,
OP_BNE = 14,
OP_DIV = 16,
OP_DIVU = 17,
OP_J = 18,
OP_JAL = 19,
OP_JALR = 20,
OP_JR = 21,
OP_LB = 22,
OP_LBU = 23,
OP_LH = 24,
OP_LHU = 25,
OP_LUI = 26,
OP_LW = 27,
OP_LWL = 28,
OP_LWR = 29,
OP_MFHI = 31,
OP_MFLO = 32,
OP_MTHI = 34,
OP_MTLO = 35,
OP_MULT = 36,
OP_MULTU = 37,
OP_NOR = 38,
OP_OR = 39,
OP_ORI = 40,
OP_RFE = 41,
OP_SB = 42,
OP_SH = 43,
OP_SLL = 44,
OP_SLLV = 45,
OP_SLT = 46,
OP_SLTI = 47,
OP_SLTIU = 48,
OP_SLTU = 49,
OP_SRA = 50,
OP_SRAV = 51,
OP_SRL = 52,
OP_SRLV = 53,
OP_SUB = 54,
OP_SUBU = 55,
OP_SW = 56,
OP_SWL = 57,
OP_SWR = 58,
OP_XOR = 59,
OP_XORI = 60,
OP_SYSCALL= 61,
OP_UNIMP = 62,
OP_RES = 63,
OP_MFCP0 = 65,
OP_MTCP0 = 66,
OP_CFCP0 = 67,
OP_CTCP0 = 68,
OP_BCCP0 = 69,
OP_TLBR = 70,
OP_TLBWI = 71,
OP_TLBWR = 72,
OP_TLBP = 73,
OP_COP1 = 75,
OP_COP2 = 76,
OP_COP3 = 77,
OP_BREAK = 78,
/* FPU ops */
OP_MFC_1 = 79,
OP_CFC_1 = 80,
OP_MTC_1 = 81,
OP_CTC_1 = 82,
OP_BC1F = 83,
OP_BC1T = 84,
OP_LWC1 = 85,
OP_SWC1 = 86,
OP_FADD = 87,
OP_FSUB = 88,
OP_FMUL = 89,
OP_FDIV = 90,
OP_FSQRT = 91,
OP_FABS = 92,
OP_FMOV = 93,
OP_FNEG = 94,
OP_ROUND_L= 95,
OP_TRUNC_L= 96,
OP_CEIL_L = 98,
OP_FLOOR_L= 99,
OP_CEIL_W = 100,
OP_FLOOR_W= 101,
OP_ROUND_W= 102,
OP_TRUNC_W= 103,
OP_CVT_S = 104,
OP_CVT_D = 105,
OP_CVT_W = 106,
OP_CVT_L = 107,
OP_C_F = 108,
OP_C_UN = 109,
OP_C_EQ = 110,
OP_C_UEQ = 111,
OP_C_OLT = 112,
OP_C_ULT = 113,
OP_C_OLE = 114,
OP_C_ULE = 115,
OP_C_SF = 116,
OP_C_NGLE = 117,
OP_C_SEQ = 118,
OP_C_NGL = 119,
OP_C_LT = 120,
OP_C_NGE = 121,
OP_C_LE = 122,
OP_C_NGT = 123,
SPECIAL = 124,
BCOND = 125,
COP0 = 126,
COP1 = 127,
COP2 = 128,
COP3 = 129,
CIBYL_SYSCALL = 130, /* Needed? */
CIBYL_REGISTER_ARGUMENT = 131,
CIBYL_ASSIGN_MEMREG = 132,
} mips_opcode_t;
#define N_INSNS 133
typedef enum
{
IFMT = 1,
JFMT = 2,
RFMT = 3
} mips_fmt_t;
typedef struct
{
mips_opcode_t type;
mips_fmt_t fmt;
} mips_op_entry_t;
extern mips_op_entry_t mips_op_entries[];
extern mips_opcode_t mips_special_table[];
extern mips_opcode_t mips_cop1_table[];
extern const char *mips_op_strings[];
extern const char *mips_reg_strings[];
/**
* Zero-terminated list of caller-saved MIPS registers
*/
extern MIPS_register_t mips_caller_saved[];
bool mips_zero_extend_opcode(mips_opcode_t opcode);
static inline MIPS_register_t mips_encoding_get_rs(uint32_t word)
{
return (MIPS_register_t)((word >> 21) & 0x1f);
}
static inline MIPS_register_t mips_encoding_get_rt(uint32_t word)
{
return (MIPS_register_t)((word >> 16) & 0x1f);
}
static inline MIPS_register_t mips_encoding_get_rd(uint32_t word)
{
return (MIPS_register_t)((word >> 11) & 0x1f);
}
static inline MIPS_register_t mips_encoding_get_fs(uint32_t word)
{
return (MIPS_register_t)( ((int)mips_encoding_get_rs(word)) + R_F0);
}
static inline MIPS_register_t mips_encoding_get_ft(uint32_t word)
{
return (MIPS_register_t)( ((int)mips_encoding_get_rt(word)) + R_F0);
}
static inline MIPS_register_t mips_encoding_get_fd(uint32_t word)
{
return (MIPS_register_t)( ((word >> 6) & 0x1f) + R_F0);
}
static inline int mips_encoding_get_cp1_fmt(uint32_t word)
{
return (word >> 21) & 0x1f;
}
static inline int mips_encoding_get_cp1_func(uint32_t word)
{
return word & 0x3f;
}
static inline MIPS_register_t mips_int_to_fpu_reg(int v)
{
return (MIPS_register_t)(v + R_F0);
}
static inline bool mips_cp1_fmt_is_double(int fmt)
{
return (fmt & 1) == 1;
}
#endif /* !__MIPS_HH__ */
<|endoftext|> |
<commit_before>#include "controllers.h"
#include "ast/all.h"
using namespace Mugen;
StateParameterMap::StateParameterMap(){
}
StateParameterMap::StateParameterMap(const StateParameterMap & copy){
this->parameters = copy.parameters;
}
StateParameterMap::~StateParameterMap(){
}
const StateParameterMap & StateParameterMap::operator=(const StateParameterMap & copy){
this->parameters = copy.parameters;
}
void StateParameterMap::add(const std::string & param, Ast::AttributeSimple * simple){
parameters[param].push_back(simple);
}
std::vector<Ast::AttributeSimple *> * StateParameterMap::find(const std::string & param){
std::map<std::string, std::vector<Ast::AttributeSimple *> >::iterator found = parameters.find(param);
if (found != parameters.end()){
return &(*found).second;
}
return NULL;
}
StateControllerStore::StateControllerStore(){
}
StateControllerStore::~StateControllerStore(){
}
void StateControllerStore::newController(){
controllerParameters.push_back(StateParameterMap());
}
StateParameterMap & StateControllerStore::getCurrentController(){
return controllerParameters.back();
}
void StateControllerStore::addToDefinition(PythonDefinition & definition){
// TODO Go through current parameters and create new classes based on 'type' and add to definition
for (std::vector<StateParameterMap>::iterator i = controllerParameters.begin(); i != controllerParameters.end(); ++i){
std::vector<Ast::AttributeSimple *> * type = (*i).find("type");
if (type != NULL){
std::stringstream line;
line << "# Found controller type '" << type->back()->valueAsString() << "' on line " << type->back()->getLine();
definition.addContent(Content(1, line.str()));
}
}
// FIXME Remove this line when the state function has been populated
definition.addContent(Content(1, "pass"));
}
StateController::StateController(const StateParameterMap & parameters):
parameters(parameters){
}
StateController::~StateController(){
}
<commit_msg>Add factory for state controller types<commit_after>#include "controllers.h"
#include "ast/all.h"
using namespace Mugen;
Content getController(const std::string & type){
if (type == "AfterImage"){
} else if (type == "AfterImageTime"){
} else if (type == "AllPalFX"){
} else if (type == "AngleAdd"){
} else if (type == "AngleDraw"){
} else if (type == "AngleMul"){
} else if (type == "AngleSet"){
} else if (type == "AppendToClipboard"){
} else if (type == "AssertSpecial"){
} else if (type == "AttackDist"){
} else if (type == "AttackMulSet"){
} else if (type == "BGPalFX"){
} else if (type == "BindToParent"){
} else if (type == "BindToRoot"){
} else if (type == "BindToTarget"){
} else if (type == "ChangeAnim"){
} else if (type == "ChangeAnim2"){
} else if (type == "ChangeState"){
} else if (type == "ClearClipboard"){
} else if (type == "CtrlSet"){
} else if (type == "DefenceMulSet"){
} else if (type == "DestroySelf"){
} else if (type == "DisplayToClipboard"){
} else if (type == "EnvColor"){
} else if (type == "EnvShake"){
} else if (type == "Explod"){
} else if (type == "ExplodBindTime"){
} else if (type == "FallEnvShake"){
} else if (type == "ForceFeedback"){
} else if (type == "GameMakeAnim"){
} else if (type == "Gravity"){
} else if (type == "Helper"){
} else if (type == "HitAdd"){
} else if (type == "HitBy"){
} else if (type == "HitDef"){
} else if (type == "HitFallDamage"){
} else if (type == "HitFallSet"){
} else if (type == "HitFallVel"){
} else if (type == "HitOverride"){
} else if (type == "HitVelSet"){
} else if (type == "LifeAdd"){
} else if (type == "LifeSet"){
} else if (type == "MakeDust"){
} else if (type == "ModifyExplod"){
} else if (type == "MoveHitReset"){
} else if (type == "NotHitBy"){
} else if (type == "Null"){
} else if (type == "Offset"){
} else if (type == "PalFX"){
} else if (type == "ParentVarAdd"){
} else if (type == "ParentVarSet"){
} else if (type == "Pause"){
} else if (type == "PlaySnd"){
} else if (type == "PlayerPush"){
} else if (type == "PosAdd"){
} else if (type == "PosFreeze"){
} else if (type == "PosSet"){
} else if (type == "PowerAdd"){
} else if (type == "PowerSet"){
} else if (type == "Projectile"){
} else if (type == "RemapPal"){
} else if (type == "RemoveExplod"){
} else if (type == "ReversalDef"){
} else if (type == "ScreenBound"){
} else if (type == "SelfState"){
} else if (type == "SndPan"){
} else if (type == "SprPriority"){
} else if (type == "StateTypeSet"){
} else if (type == "StopSnd"){
} else if (type == "SuperPause"){
} else if (type == "TargetBind"){
} else if (type == "TargetDrop"){
} else if (type == "TargetFacing"){
} else if (type == "TargetLifeAdd"){
} else if (type == "TargetPowerAdd"){
} else if (type == "TargetState"){
} else if (type == "TargetVelAdd"){
} else if (type == "TargetVelSet"){
} else if (type == "Trans"){
} else if (type == "Turn"){
} else if (type == "VarAdd"){
} else if (type == "VarRandom"){
} else if (type == "VarRangeSet"){
} else if (type == "VarSet"){
} else if (type == "VelAdd"){
} else if (type == "VelMul"){
} else if (type == "VelSet"){
} else if (type == "VictoryQuote"){
} else if (type == "Width"){
} else {
std::cout << "Unhandled Controller Type: " << type << std::endl;
}
// Set to pass if state controller can't be determined
return Content(1, "pass");
}
StateParameterMap::StateParameterMap(){
}
StateParameterMap::StateParameterMap(const StateParameterMap & copy){
this->parameters = copy.parameters;
}
StateParameterMap::~StateParameterMap(){
}
const StateParameterMap & StateParameterMap::operator=(const StateParameterMap & copy){
this->parameters = copy.parameters;
}
void StateParameterMap::add(const std::string & param, Ast::AttributeSimple * simple){
parameters[param].push_back(simple);
}
std::vector<Ast::AttributeSimple *> * StateParameterMap::find(const std::string & param){
std::map<std::string, std::vector<Ast::AttributeSimple *> >::iterator found = parameters.find(param);
if (found != parameters.end()){
return &(*found).second;
}
return NULL;
}
StateControllerStore::StateControllerStore(){
}
StateControllerStore::~StateControllerStore(){
}
void StateControllerStore::newController(){
controllerParameters.push_back(StateParameterMap());
}
StateParameterMap & StateControllerStore::getCurrentController(){
return controllerParameters.back();
}
void StateControllerStore::addToDefinition(PythonDefinition & definition){
// TODO Go through current parameters and create new classes based on 'type' and add to definition
for (std::vector<StateParameterMap>::iterator i = controllerParameters.begin(); i != controllerParameters.end(); ++i){
std::vector<Ast::AttributeSimple *> * type = (*i).find("type");
if (type != NULL){
std::stringstream line;
const std::string & ctrl = type->back()->valueAsString();
line << "# Found controller type '" << ctrl << "' on line " << type->back()->getLine();
definition.addContent(Content(1, line.str()));
definition.addContent(getController(ctrl));
}
}
}
StateController::StateController(const StateParameterMap & parameters):
parameters(parameters){
}
StateController::~StateController(){
}
<|endoftext|> |
<commit_before>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// Basket ball demo.
// Serves as a test for the sphere vs trimesh collider
// By Bram Stolk.
// Press the spacebar to reset the position of the ball.
#include <ode/config.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ode/ode.h>
#include <drawstuff/drawstuff.h>
#include "basket_geom.h" // this is our world mesh
#ifdef _MSC_VER
#pragma warning(disable:4244 4305) // for VC++, no precision loss complaints
#endif
// some constants
#define RADIUS 0.14
// dynamics and collision objects (chassis, 3 wheels, environment)
static dWorldID world;
static dSpaceID space;
static dBodyID sphbody;
static dGeomID sphgeom;
static dJointGroupID contactgroup;
static dGeomID world_mesh;
// this is called by dSpaceCollide when two objects in space are
// potentially colliding.
static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
assert(o1);
assert(o2);
if (dGeomIsSpace(o1) || dGeomIsSpace(o2))
{
fprintf(stderr,"testing space %p %p\n", o1,o2);
// colliding a space with something
dSpaceCollide2(o1,o2,data,&nearCallback);
// Note we do not want to test intersections within a space,
// only between spaces.
return;
}
// fprintf(stderr,"testing geoms %p %p\n", o1, o2);
const int N = 32;
dContact contact[N];
int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));
if (n > 0)
{
for (int i=0; i<n; i++)
{
// Paranoia
dIASSERT(dVALIDVEC3(contact[i].geom.pos));
dIASSERT(dVALIDVEC3(contact[i].geom.normal));
dIASSERT(!dIsNan(contact[i].geom.depth));
contact[i].surface.slip1 = 0.7;
contact[i].surface.slip2 = 0.7;
contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;
contact[i].surface.mu = 50.0; // was: dInfinity
contact[i].surface.soft_erp = 0.96;
contact[i].surface.soft_cfm = 0.04;
dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);
dJointAttach (c,
dGeomGetBody(contact[i].geom.g1),
dGeomGetBody(contact[i].geom.g2));
}
}
}
// start simulation - set viewpoint
static void start()
{
static float xyz[3] = {-8,0,5};
static float hpr[3] = {0.0f,-29.5000f,0.0000f};
dsSetViewpoint (xyz,hpr);
}
static void reset_ball(void)
{
float sx=0.0, sy=3.40, sz=6.80;
dBodySetPosition (sphbody, sx, sy, sz);
dBodySetLinearVel (sphbody, 0,0,0);
dBodySetAngularVel (sphbody, 0,0,0);
}
// called when a key pressed
static void command (int cmd)
{
switch (cmd)
{
case ' ':
reset_ball();
break;
}
}
// simulation loop
static void simLoop (int pause)
{
double simstep = 0.001; // 1ms simulation steps
double dt = dsElapsedTime();
int nrofsteps = (int) ceilf(dt/simstep);
// fprintf(stderr, "dt=%f, nr of steps = %d\n", dt, nrofsteps);
for (int i=0; i<nrofsteps && !pause; i++)
{
dSpaceCollide (space,0,&nearCallback);
dWorldQuickStep (world, simstep);
dJointGroupEmpty (contactgroup);
}
dsSetColor (1,1,1);
const dReal *SPos = dBodyGetPosition(sphbody);
const dReal *SRot = dBodyGetRotation(sphbody);
float spos[3] = {SPos[0], SPos[1], SPos[2]};
float srot[12] = { SRot[0], SRot[1], SRot[2], SRot[3], SRot[4], SRot[5], SRot[6], SRot[7], SRot[8], SRot[9], SRot[10], SRot[11] };
dsDrawSphere
(
spos,
srot,
RADIUS
);
// draw world trimesh
dsSetColor(0.4,0.7,0.9);
dsSetTexture (DS_NONE);
const dReal* Pos = dGeomGetPosition(world_mesh);
dIASSERT(dVALIDVEC3(Pos));
float pos[3] = { Pos[0], Pos[1], Pos[2] };
const dReal* Rot = dGeomGetRotation(world_mesh);
dIASSERT(dVALIDMAT(Rot));
float rot[12] = { Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8], Rot[9], Rot[10], Rot[11] };
int numi = sizeof(world_indices) / sizeof(int);
for (int i=0; i<numi/3; i++)
{
int i0 = world_indices[i*3+0];
int i1 = world_indices[i*3+1];
int i2 = world_indices[i*3+2];
float *v0 = world_vertices+i0*3;
float *v1 = world_vertices+i1*3;
float *v2 = world_vertices+i2*3;
dsDrawTriangle(pos, rot, v0,v1,v2, true); // single precision draw
}
}
int main (int argc, char **argv)
{
dMass m;
dMatrix3 R;
// setup pointers to drawstuff callback functions
dsFunctions fn;
fn.version = DS_VERSION;
fn.start = &start;
fn.step = &simLoop;
fn.command = &command;
fn.stop = 0;
fn.path_to_textures = "../../drawstuff/textures";
if(argc==2)
fn.path_to_textures = argv[1];
// create world
world = dWorldCreate();
space = dHashSpaceCreate (0);
contactgroup = dJointGroupCreate (0);
dWorldSetGravity (world,0,0,-9.8);
dWorldSetQuickStepNumIterations (world, 64);
// Create a static world using a triangle mesh that we can collide with.
int numv = sizeof(world_vertices)/(3*sizeof(float));
int numi = sizeof(world_indices)/ sizeof(int);
printf("numv=%d, numi=%d\n", numv, numi);
dTriMeshDataID Data = dGeomTriMeshDataCreate();
// fprintf(stderr,"Building Single Precision Mesh\n");
dGeomTriMeshDataBuildSingle
(
Data,
world_vertices,
3 * sizeof(float),
numv,
world_indices,
numi,
3 * sizeof(int)
);
world_mesh = dCreateTriMesh(space, Data, 0, 0, 0);
dGeomTriMeshEnableTC(world_mesh, dSphereClass, false);
dGeomTriMeshEnableTC(world_mesh, dBoxClass, false);
dGeomSetPosition(world_mesh, 0, 0, 0.5);
dRFromAxisAndAngle (R, 0,1,0, 0.0);
dGeomSetRotation (world_mesh, R);
float sx=0.0, sy=3.40, sz=6.80;
sphbody = dBodyCreate (world);
dMassSetSphere (&m,1,RADIUS);
dBodySetMass (sphbody,&m);
sphgeom = dCreateSphere(0, RADIUS);
dGeomSetBody (sphgeom,sphbody);
reset_ball();
dSpaceAdd (space, sphgeom);
// run simulation
dsSimulationLoop (argc,argv,352,288,&fn);
// Causes segm violation? Why?
// (because dWorldDestroy() destroys body connected to geom; must call first!)
dGeomDestroy(sphgeom);
dGeomDestroy (world_mesh);
dJointGroupEmpty (contactgroup);
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
return 0;
}
<commit_msg>Reset orientation for a consistant behaviour between shots.<commit_after>/*************************************************************************
* *
* Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *
* All rights reserved. Email: russ@q12.org Web: www.q12.org *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of EITHER: *
* (1) The GNU Lesser General Public License as published by the Free *
* Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. The text of the GNU Lesser *
* General Public License is included with this library in the *
* file LICENSE.TXT. *
* (2) The BSD-style license that is included with this library in *
* the file LICENSE-BSD.TXT. *
* *
* 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 files *
* LICENSE.TXT and LICENSE-BSD.TXT for more details. *
* *
*************************************************************************/
// Basket ball demo.
// Serves as a test for the sphere vs trimesh collider
// By Bram Stolk.
// Press the spacebar to reset the position of the ball.
#include <ode/config.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <ode/ode.h>
#include <drawstuff/drawstuff.h>
#include "basket_geom.h" // this is our world mesh
#ifdef _MSC_VER
#pragma warning(disable:4244 4305) // for VC++, no precision loss complaints
#endif
// some constants
#define RADIUS 0.14
// dynamics and collision objects (chassis, 3 wheels, environment)
static dWorldID world;
static dSpaceID space;
static dBodyID sphbody;
static dGeomID sphgeom;
static dJointGroupID contactgroup;
static dGeomID world_mesh;
// this is called by dSpaceCollide when two objects in space are
// potentially colliding.
static void nearCallback (void *data, dGeomID o1, dGeomID o2)
{
assert(o1);
assert(o2);
if (dGeomIsSpace(o1) || dGeomIsSpace(o2))
{
fprintf(stderr,"testing space %p %p\n", o1,o2);
// colliding a space with something
dSpaceCollide2(o1,o2,data,&nearCallback);
// Note we do not want to test intersections within a space,
// only between spaces.
return;
}
// fprintf(stderr,"testing geoms %p %p\n", o1, o2);
const int N = 32;
dContact contact[N];
int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));
if (n > 0)
{
for (int i=0; i<n; i++)
{
// Paranoia
dIASSERT(dVALIDVEC3(contact[i].geom.pos));
dIASSERT(dVALIDVEC3(contact[i].geom.normal));
dIASSERT(!dIsNan(contact[i].geom.depth));
contact[i].surface.slip1 = 0.7;
contact[i].surface.slip2 = 0.7;
contact[i].surface.mode = dContactSoftERP | dContactSoftCFM | dContactApprox1 | dContactSlip1 | dContactSlip2;
contact[i].surface.mu = 50.0; // was: dInfinity
contact[i].surface.soft_erp = 0.96;
contact[i].surface.soft_cfm = 0.04;
dJointID c = dJointCreateContact (world,contactgroup,&contact[i]);
dJointAttach (c,
dGeomGetBody(contact[i].geom.g1),
dGeomGetBody(contact[i].geom.g2));
}
}
}
// start simulation - set viewpoint
static void start()
{
static float xyz[3] = {-8,0,5};
static float hpr[3] = {0.0f,-29.5000f,0.0000f};
dsSetViewpoint (xyz,hpr);
}
static void reset_ball(void)
{
float sx=0.0, sy=3.40, sz=6.80;
dQuaternion q;
dQSetIdentity(q);
dBodySetPosition (sphbody, sx, sy, sz);
dBodySetQuaternion(sphbody, q);
dBodySetLinearVel (sphbody, 0,0,0);
dBodySetAngularVel (sphbody, 0,0,0);
}
// called when a key pressed
static void command (int cmd)
{
switch (cmd)
{
case ' ':
reset_ball();
break;
}
}
// simulation loop
static void simLoop (int pause)
{
double simstep = 0.001; // 1ms simulation steps
double dt = dsElapsedTime();
int nrofsteps = (int) ceilf(dt/simstep);
// fprintf(stderr, "dt=%f, nr of steps = %d\n", dt, nrofsteps);
for (int i=0; i<nrofsteps && !pause; i++)
{
dSpaceCollide (space,0,&nearCallback);
dWorldQuickStep (world, simstep);
dJointGroupEmpty (contactgroup);
}
dsSetColor (1,1,1);
const dReal *SPos = dBodyGetPosition(sphbody);
const dReal *SRot = dBodyGetRotation(sphbody);
float spos[3] = {SPos[0], SPos[1], SPos[2]};
float srot[12] = { SRot[0], SRot[1], SRot[2], SRot[3], SRot[4], SRot[5], SRot[6], SRot[7], SRot[8], SRot[9], SRot[10], SRot[11] };
dsDrawSphere
(
spos,
srot,
RADIUS
);
// draw world trimesh
dsSetColor(0.4,0.7,0.9);
dsSetTexture (DS_NONE);
const dReal* Pos = dGeomGetPosition(world_mesh);
dIASSERT(dVALIDVEC3(Pos));
float pos[3] = { Pos[0], Pos[1], Pos[2] };
const dReal* Rot = dGeomGetRotation(world_mesh);
dIASSERT(dVALIDMAT(Rot));
float rot[12] = { Rot[0], Rot[1], Rot[2], Rot[3], Rot[4], Rot[5], Rot[6], Rot[7], Rot[8], Rot[9], Rot[10], Rot[11] };
int numi = sizeof(world_indices) / sizeof(int);
for (int i=0; i<numi/3; i++)
{
int i0 = world_indices[i*3+0];
int i1 = world_indices[i*3+1];
int i2 = world_indices[i*3+2];
float *v0 = world_vertices+i0*3;
float *v1 = world_vertices+i1*3;
float *v2 = world_vertices+i2*3;
dsDrawTriangle(pos, rot, v0,v1,v2, true); // single precision draw
}
}
int main (int argc, char **argv)
{
dMass m;
dMatrix3 R;
// setup pointers to drawstuff callback functions
dsFunctions fn;
fn.version = DS_VERSION;
fn.start = &start;
fn.step = &simLoop;
fn.command = &command;
fn.stop = 0;
fn.path_to_textures = "../../drawstuff/textures";
if(argc==2)
fn.path_to_textures = argv[1];
// create world
world = dWorldCreate();
space = dHashSpaceCreate (0);
contactgroup = dJointGroupCreate (0);
dWorldSetGravity (world,0,0,-9.8);
dWorldSetQuickStepNumIterations (world, 64);
// Create a static world using a triangle mesh that we can collide with.
int numv = sizeof(world_vertices)/(3*sizeof(float));
int numi = sizeof(world_indices)/ sizeof(int);
printf("numv=%d, numi=%d\n", numv, numi);
dTriMeshDataID Data = dGeomTriMeshDataCreate();
// fprintf(stderr,"Building Single Precision Mesh\n");
dGeomTriMeshDataBuildSingle
(
Data,
world_vertices,
3 * sizeof(float),
numv,
world_indices,
numi,
3 * sizeof(int)
);
world_mesh = dCreateTriMesh(space, Data, 0, 0, 0);
dGeomTriMeshEnableTC(world_mesh, dSphereClass, false);
dGeomTriMeshEnableTC(world_mesh, dBoxClass, false);
dGeomSetPosition(world_mesh, 0, 0, 0.5);
dRFromAxisAndAngle (R, 0,1,0, 0.0);
dGeomSetRotation (world_mesh, R);
float sx=0.0, sy=3.40, sz=6.80;
sphbody = dBodyCreate (world);
dMassSetSphere (&m,1,RADIUS);
dBodySetMass (sphbody,&m);
sphgeom = dCreateSphere(0, RADIUS);
dGeomSetBody (sphgeom,sphbody);
reset_ball();
dSpaceAdd (space, sphgeom);
// run simulation
dsSimulationLoop (argc,argv,352,288,&fn);
// Causes segm violation? Why?
// (because dWorldDestroy() destroys body connected to geom; must call first!)
dGeomDestroy(sphgeom);
dGeomDestroy (world_mesh);
dJointGroupEmpty (contactgroup);
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This class is in interface to OmxCodec from the media playback
// pipeline. It interacts with OmxCodec and the VideoDecoderImpl
// in the media pipeline.
//
// THREADING SEMANTICS
//
// This class is created by VideoDecoderImpl and lives on the thread
// that VideoDecoderImpl lives. This class is given the message loop
// for the above thread. The same message loop is used to host
// OmxCodec which is the interface to the actual OpenMAX hardware.
// OmxCodec gurantees that all the callbacks are executed on the
// hosting message loop. This essentially means that all methods in
// this class are executed on the same thread as VideoDecoderImpl.
// Because of that there's no need for locking anywhere.
#include "media/filters/omx_video_decode_engine.h"
#include "base/message_loop.h"
#include "media/base/callback.h"
#include "media/ffmpeg/ffmpeg_common.h"
namespace media {
OmxVideoDecodeEngine::OmxVideoDecodeEngine()
: state_(kCreated),
frame_bytes_(0),
has_fed_on_eos_(false),
message_loop_(NULL) {
}
OmxVideoDecodeEngine::~OmxVideoDecodeEngine() {
}
void OmxVideoDecodeEngine::Initialize(AVStream* stream, Task* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
AutoTaskRunner done_runner(done_cb);
omx_codec_ = new media::OmxCodec(message_loop_);
width_ = stream->codec->width;
height_ = stream->codec->height;
// TODO(ajwong): Extract magic formula to something based on output
// pixel format.
frame_bytes_ = (width_ * height_ * 3) / 2;
y_buffer_.reset(new uint8[width_ * height_]);
u_buffer_.reset(new uint8[width_ * height_ / 4]);
v_buffer_.reset(new uint8[width_ * height_ / 4]);
// TODO(ajwong): Find the right way to determine the Omx component name.
OmxConfigurator::MediaFormat input_format, output_format;
memset(&input_format, 0, sizeof(input_format));
memset(&output_format, 0, sizeof(output_format));
input_format.codec = OmxConfigurator::kCodecH264;
output_format.codec = OmxConfigurator::kCodecRaw;
omx_codec_->Setup(new OmxDecoderConfigurator(input_format, output_format));
omx_codec_->SetErrorCallback(
NewCallback(this, &OmxVideoDecodeEngine::OnHardwareError));
omx_codec_->SetFormatCallback(
NewCallback(this, &OmxVideoDecodeEngine::OnFormatChange));
omx_codec_->Start();
state_ = kNormal;
}
void OmxVideoDecodeEngine::OnFormatChange(
const OmxConfigurator::MediaFormat& input_format,
const OmxConfigurator::MediaFormat& output_format) {
DCHECK_EQ(message_loop_, MessageLoop::current());
// TODO(jiesun): We should not need this for here, because width and height
// are already known from upper layer of the stack.
}
void OmxVideoDecodeEngine::OnHardwareError() {
DCHECK_EQ(message_loop_, MessageLoop::current());
state_ = kError;
}
// This method assumes the input buffer contains exactly one frame or is an
// end-of-stream buffer. The logic of this method and in OnReadComplete() is
// based on this assumation.
//
// For every input buffer received here, we submit one read request to the
// decoder. So when a read complete callback is received, a corresponding
// decode request must exist.
void OmxVideoDecodeEngine::DecodeFrame(const Buffer& buffer,
AVFrame* yuv_frame,
bool* got_result,
Task* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
if (state_ != kNormal) {
return;
}
if (!has_fed_on_eos_) {
// TODO(ajwong): This is a memcpy() of the compressed frame. Avoid?
uint8* data = new uint8[buffer.GetDataSize()];
memcpy(data, buffer.GetData(), buffer.GetDataSize());
OmxInputBuffer* input_buffer =
new OmxInputBuffer(data, buffer.GetDataSize());
// Feed in the new buffer regardless.
//
// TODO(ajwong): This callback stuff is messy. Cleanup.
CleanupCallback<OmxCodec::FeedCallback>* feed_done =
new CleanupCallback<OmxCodec::FeedCallback>(
NewCallback(this, &OmxVideoDecodeEngine::OnFeedDone));
feed_done->DeleteWhenDone(input_buffer);
omx_codec_->Feed(input_buffer, feed_done);
if (buffer.IsEndOfStream()) {
has_fed_on_eos_ = true;
}
}
// Enqueue the decode request and the associated buffer.
decode_request_queue_.push_back(
DecodeRequest(yuv_frame, got_result, done_cb));
// Submit a read request to the decoder.
omx_codec_->Read(NewCallback(this, &OmxVideoDecodeEngine::OnReadComplete));
}
void OmxVideoDecodeEngine::OnFeedDone(OmxInputBuffer* buffer) {
DCHECK_EQ(message_loop_, MessageLoop::current());
// TODO(ajwong): Add a DoNothingCallback or similar.
}
void OmxVideoDecodeEngine::Flush(Task* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
omx_codec_->Flush(TaskToCallbackAdapter::NewCallback(done_cb));
}
VideoSurface::Format OmxVideoDecodeEngine::GetSurfaceFormat() const {
return VideoSurface::YV12;
}
void OmxVideoDecodeEngine::Stop(Callback0::Type* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
omx_codec_->Stop(done_cb);
state_ = kStopped;
}
void OmxVideoDecodeEngine::OnReadComplete(uint8* buffer, int size) {
DCHECK_EQ(message_loop_, MessageLoop::current());
if ((size_t)size != frame_bytes_) {
LOG(ERROR) << "Read completed with weird size: " << size;
}
// Merge the buffer into previous buffers.
MergeBytesFrameQueue(buffer, size);
// We assume that when we receive a read complete callback from
// OmxCodec there was a read request made.
CHECK(!decode_request_queue_.empty());
const DecodeRequest request = decode_request_queue_.front();
decode_request_queue_.pop_front();
*request.got_result = false;
// Detect if we have received a full decoded frame.
if (DecodedFrameAvailable()) {
// |frame| carries the decoded frame.
scoped_ptr<YuvFrame> frame(yuv_frame_queue_.front());
yuv_frame_queue_.pop_front();
*request.got_result = true;
// TODO(ajwong): This is a memcpy(). Avoid this.
// TODO(ajwong): This leaks memory. Fix by not using AVFrame.
const int pixels = width_ * height_;
request.frame->data[0] = y_buffer_.get();
request.frame->data[1] = u_buffer_.get();
request.frame->data[2] = v_buffer_.get();
request.frame->linesize[0] = width_;
request.frame->linesize[1] = width_ / 2;
request.frame->linesize[2] = width_ / 2;
memcpy(request.frame->data[0], frame->data, pixels);
memcpy(request.frame->data[1], frame->data + pixels,
pixels / 4);
memcpy(request.frame->data[2],
frame->data + pixels + pixels /4,
pixels / 4);
}
request.done_cb->Run();
}
bool OmxVideoDecodeEngine::IsFrameComplete(const YuvFrame* frame) {
return frame->size == frame_bytes_;
}
bool OmxVideoDecodeEngine::DecodedFrameAvailable() {
return (!yuv_frame_queue_.empty() &&
IsFrameComplete(yuv_frame_queue_.front()));
}
void OmxVideoDecodeEngine::MergeBytesFrameQueue(uint8* buffer, int size) {
int amount_left = size;
// TODO(ajwong): Do the swizzle here instead of in DecodeFrame. This
// should be able to avoid 1 memcpy.
while (amount_left > 0) {
if (yuv_frame_queue_.empty() || IsFrameComplete(yuv_frame_queue_.back())) {
yuv_frame_queue_.push_back(new YuvFrame(frame_bytes_));
}
YuvFrame* frame = yuv_frame_queue_.back();
int amount_to_copy = std::min((int)(frame_bytes_ - frame->size), size);
frame->size += amount_to_copy;
memcpy(frame->data, buffer, amount_to_copy);
amount_left -= amount_to_copy;
}
}
} // namespace media
<commit_msg>Fix using of OmxInputBuffer<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This class is in interface to OmxCodec from the media playback
// pipeline. It interacts with OmxCodec and the VideoDecoderImpl
// in the media pipeline.
//
// THREADING SEMANTICS
//
// This class is created by VideoDecoderImpl and lives on the thread
// that VideoDecoderImpl lives. This class is given the message loop
// for the above thread. The same message loop is used to host
// OmxCodec which is the interface to the actual OpenMAX hardware.
// OmxCodec gurantees that all the callbacks are executed on the
// hosting message loop. This essentially means that all methods in
// this class are executed on the same thread as VideoDecoderImpl.
// Because of that there's no need for locking anywhere.
#include "media/filters/omx_video_decode_engine.h"
#include "base/message_loop.h"
#include "media/base/callback.h"
#include "media/ffmpeg/ffmpeg_common.h"
namespace media {
OmxVideoDecodeEngine::OmxVideoDecodeEngine()
: state_(kCreated),
frame_bytes_(0),
has_fed_on_eos_(false),
message_loop_(NULL) {
}
OmxVideoDecodeEngine::~OmxVideoDecodeEngine() {
}
void OmxVideoDecodeEngine::Initialize(AVStream* stream, Task* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
AutoTaskRunner done_runner(done_cb);
omx_codec_ = new media::OmxCodec(message_loop_);
width_ = stream->codec->width;
height_ = stream->codec->height;
// TODO(ajwong): Extract magic formula to something based on output
// pixel format.
frame_bytes_ = (width_ * height_ * 3) / 2;
y_buffer_.reset(new uint8[width_ * height_]);
u_buffer_.reset(new uint8[width_ * height_ / 4]);
v_buffer_.reset(new uint8[width_ * height_ / 4]);
// TODO(ajwong): Find the right way to determine the Omx component name.
OmxConfigurator::MediaFormat input_format, output_format;
memset(&input_format, 0, sizeof(input_format));
memset(&output_format, 0, sizeof(output_format));
input_format.codec = OmxConfigurator::kCodecH264;
output_format.codec = OmxConfigurator::kCodecRaw;
omx_codec_->Setup(new OmxDecoderConfigurator(input_format, output_format));
omx_codec_->SetErrorCallback(
NewCallback(this, &OmxVideoDecodeEngine::OnHardwareError));
omx_codec_->SetFormatCallback(
NewCallback(this, &OmxVideoDecodeEngine::OnFormatChange));
omx_codec_->Start();
state_ = kNormal;
}
void OmxVideoDecodeEngine::OnFormatChange(
const OmxConfigurator::MediaFormat& input_format,
const OmxConfigurator::MediaFormat& output_format) {
DCHECK_EQ(message_loop_, MessageLoop::current());
// TODO(jiesun): We should not need this for here, because width and height
// are already known from upper layer of the stack.
}
void OmxVideoDecodeEngine::OnHardwareError() {
DCHECK_EQ(message_loop_, MessageLoop::current());
state_ = kError;
}
// This method assumes the input buffer contains exactly one frame or is an
// end-of-stream buffer. The logic of this method and in OnReadComplete() is
// based on this assumation.
//
// For every input buffer received here, we submit one read request to the
// decoder. So when a read complete callback is received, a corresponding
// decode request must exist.
void OmxVideoDecodeEngine::DecodeFrame(const Buffer& buffer,
AVFrame* yuv_frame,
bool* got_result,
Task* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
if (state_ != kNormal) {
return;
}
if (!has_fed_on_eos_) {
OmxInputBuffer* input_buffer;
if (buffer.IsEndOfStream()) {
input_buffer = new OmxInputBuffer(NULL, 0);
} else {
// TODO(ajwong): This is a memcpy() of the compressed frame. Avoid?
uint8* data = new uint8[buffer.GetDataSize()];
memcpy(data, buffer.GetData(), buffer.GetDataSize());
input_buffer = new OmxInputBuffer(data, buffer.GetDataSize());
}
omx_codec_->Feed(input_buffer,
NewCallback(this, &OmxVideoDecodeEngine::OnFeedDone));
if (buffer.IsEndOfStream()) {
has_fed_on_eos_ = true;
}
}
// Enqueue the decode request and the associated buffer.
decode_request_queue_.push_back(
DecodeRequest(yuv_frame, got_result, done_cb));
// Submit a read request to the decoder.
omx_codec_->Read(NewCallback(this, &OmxVideoDecodeEngine::OnReadComplete));
}
void OmxVideoDecodeEngine::OnFeedDone(OmxInputBuffer* buffer) {
DCHECK_EQ(message_loop_, MessageLoop::current());
// TODO(ajwong): Add a DoNothingCallback or similar.
}
void OmxVideoDecodeEngine::Flush(Task* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
omx_codec_->Flush(TaskToCallbackAdapter::NewCallback(done_cb));
}
VideoSurface::Format OmxVideoDecodeEngine::GetSurfaceFormat() const {
return VideoSurface::YV12;
}
void OmxVideoDecodeEngine::Stop(Callback0::Type* done_cb) {
DCHECK_EQ(message_loop_, MessageLoop::current());
omx_codec_->Stop(done_cb);
state_ = kStopped;
}
void OmxVideoDecodeEngine::OnReadComplete(uint8* buffer, int size) {
DCHECK_EQ(message_loop_, MessageLoop::current());
if ((size_t)size != frame_bytes_) {
LOG(ERROR) << "Read completed with weird size: " << size;
}
// Merge the buffer into previous buffers.
MergeBytesFrameQueue(buffer, size);
// We assume that when we receive a read complete callback from
// OmxCodec there was a read request made.
CHECK(!decode_request_queue_.empty());
const DecodeRequest request = decode_request_queue_.front();
decode_request_queue_.pop_front();
*request.got_result = false;
// Detect if we have received a full decoded frame.
if (DecodedFrameAvailable()) {
// |frame| carries the decoded frame.
scoped_ptr<YuvFrame> frame(yuv_frame_queue_.front());
yuv_frame_queue_.pop_front();
*request.got_result = true;
// TODO(ajwong): This is a memcpy(). Avoid this.
// TODO(ajwong): This leaks memory. Fix by not using AVFrame.
const int pixels = width_ * height_;
request.frame->data[0] = y_buffer_.get();
request.frame->data[1] = u_buffer_.get();
request.frame->data[2] = v_buffer_.get();
request.frame->linesize[0] = width_;
request.frame->linesize[1] = width_ / 2;
request.frame->linesize[2] = width_ / 2;
memcpy(request.frame->data[0], frame->data, pixels);
memcpy(request.frame->data[1], frame->data + pixels,
pixels / 4);
memcpy(request.frame->data[2],
frame->data + pixels + pixels /4,
pixels / 4);
}
request.done_cb->Run();
}
bool OmxVideoDecodeEngine::IsFrameComplete(const YuvFrame* frame) {
return frame->size == frame_bytes_;
}
bool OmxVideoDecodeEngine::DecodedFrameAvailable() {
return (!yuv_frame_queue_.empty() &&
IsFrameComplete(yuv_frame_queue_.front()));
}
void OmxVideoDecodeEngine::MergeBytesFrameQueue(uint8* buffer, int size) {
int amount_left = size;
// TODO(ajwong): Do the swizzle here instead of in DecodeFrame. This
// should be able to avoid 1 memcpy.
while (amount_left > 0) {
if (yuv_frame_queue_.empty() || IsFrameComplete(yuv_frame_queue_.back())) {
yuv_frame_queue_.push_back(new YuvFrame(frame_bytes_));
}
YuvFrame* frame = yuv_frame_queue_.back();
int amount_to_copy = std::min((int)(frame_bytes_ - frame->size), size);
frame->size += amount_to_copy;
memcpy(frame->data, buffer, amount_to_copy);
amount_left -= amount_to_copy;
}
}
} // namespace media
<|endoftext|> |
<commit_before>// Copyright (c) 2011 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 "ui/aura/root_window.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "ui/aura/event.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/window_delegate.h"
#include "ui/base/events.h"
namespace aura {
namespace internal {
RootWindow::RootWindow()
: Window(NULL),
mouse_pressed_handler_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(focus_manager_(new FocusManager(this))) {
set_name(ASCIIToUTF16("RootWindow"));
}
RootWindow::~RootWindow() {
}
bool RootWindow::HandleMouseEvent(const MouseEvent& event) {
Window* target = mouse_pressed_handler_;
if (!target)
target = GetEventHandlerForPoint(event.location());
if (event.type() == ui::ET_MOUSE_PRESSED && !mouse_pressed_handler_)
mouse_pressed_handler_ = target;
if (event.type() == ui::ET_MOUSE_RELEASED)
mouse_pressed_handler_ = NULL;
if (target->delegate()) {
MouseEvent translated_event(event, this, target);
return target->OnMouseEvent(&translated_event);
}
return false;
}
bool RootWindow::HandleKeyEvent(const KeyEvent& event) {
Window* focused_window = GetFocusManager()->focused_window();
if (focused_window) {
KeyEvent translated_event(event);
return GetFocusManager()->focused_window()->OnKeyEvent(&translated_event);
}
return false;
}
FocusManager* RootWindow::GetFocusManager() {
return focus_manager_.get();
}
} // namespace internal
} // namespace aura
<commit_msg>aura: Fix a crash when moving mouse over the empty space on the root window.<commit_after>// Copyright (c) 2011 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 "ui/aura/root_window.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "ui/aura/event.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/window_delegate.h"
#include "ui/base/events.h"
namespace aura {
namespace internal {
RootWindow::RootWindow()
: Window(NULL),
mouse_pressed_handler_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(focus_manager_(new FocusManager(this))) {
set_name(ASCIIToUTF16("RootWindow"));
}
RootWindow::~RootWindow() {
}
bool RootWindow::HandleMouseEvent(const MouseEvent& event) {
Window* target = mouse_pressed_handler_;
if (!target)
target = GetEventHandlerForPoint(event.location());
if (event.type() == ui::ET_MOUSE_PRESSED && !mouse_pressed_handler_)
mouse_pressed_handler_ = target;
if (event.type() == ui::ET_MOUSE_RELEASED)
mouse_pressed_handler_ = NULL;
if (target && target->delegate()) {
MouseEvent translated_event(event, this, target);
return target->OnMouseEvent(&translated_event);
}
return false;
}
bool RootWindow::HandleKeyEvent(const KeyEvent& event) {
Window* focused_window = GetFocusManager()->focused_window();
if (focused_window) {
KeyEvent translated_event(event);
return GetFocusManager()->focused_window()->OnKeyEvent(&translated_event);
}
return false;
}
FocusManager* RootWindow::GetFocusManager() {
return focus_manager_.get();
}
} // namespace internal
} // namespace aura
<|endoftext|> |
<commit_before>//
// yas_ui_collider.cpp
//
#include "yas_ui_collider.h"
#include "yas_observing.h"
#include "yas_property.h"
#include "yas_to_bool.h"
using namespace yas;
#pragma mark - shape
bool ui::anywhere_shape::hit_test(ui::point const &) const {
return true;
}
bool ui::circle_shape::hit_test(ui::point const &pos) const {
return std::powf(pos.x - this->center.x, 2.0f) + std::powf(pos.y - this->center.y, 2.0f) <
std::powf(this->radius, 2.0f);
}
bool ui::rect_shape::hit_test(ui::point const &pos) const {
return contains(this->rect, pos);
}
struct ui::shape::impl_base : base::impl {
virtual std::type_info const &type() const = 0;
virtual bool hit_test(ui::point const &) = 0;
};
template <typename T>
struct ui::shape::impl : impl_base {
typename T::type _value;
impl(typename T::type &&value) : _value(std::move(value)) {
}
std::type_info const &type() const override {
return typeid(T);
}
bool hit_test(ui::point const &pos) override {
return this->_value.hit_test(pos);
}
};
ui::shape::shape(anywhere::type shape) : base(std::make_shared<impl<anywhere>>(std::move(shape))) {
}
ui::shape::shape(circle::type shape) : base(std::make_shared<impl<circle>>(std::move(shape))) {
}
ui::shape::shape(rect::type shape) : base(std::make_shared<impl<rect>>(std::move(shape))) {
}
ui::shape::shape(std::nullptr_t) : base(nullptr) {
}
ui::shape::~shape() = default;
std::type_info const &ui::shape::type_info() const {
return impl_ptr<impl_base>()->type();
}
bool ui::shape::hit_test(ui::point const &pos) const {
return impl_ptr<impl_base>()->hit_test(pos);
}
template <typename T>
typename T::type const &ui::shape::get() const {
if (auto ip = std::dynamic_pointer_cast<impl<T>>(impl_ptr())) {
return ip->_value;
}
static const typename T::type _default{};
return _default;
}
template ui::anywhere_shape const &ui::shape::get<ui::shape::anywhere>() const;
template ui::circle_shape const &ui::shape::get<ui::shape::circle>() const;
template ui::rect_shape const &ui::shape::get<ui::shape::rect>() const;
#pragma mark - collider
struct ui::collider::impl : base::impl, renderable_collider::impl {
property<ui::shape> _shape_property{{.value = nullptr}};
property<bool> _enabled_property{{.value = true}};
subject_t _subject;
impl(ui::shape &&shape) : _shape_property({.value = std::move(shape)}) {
this->_property_observers.reserve(2);
}
void dispatch_method(ui::collider::method const method) {
if (this->_property_observers.count(method)) {
return;
}
auto weak_collider = to_weak(cast<ui::collider>());
base observer = nullptr;
auto make_observer = [](auto const method, auto property, auto weak_collider) {
return property.subject().make_observer(property_method::did_change,
[weak_collider, method](auto const &context) {
if (auto node = weak_collider.lock()) {
node.subject().notify(method, node);
}
});
};
switch (method) {
case ui::collider::method::shape_changed:
observer = make_observer(method, this->_shape_property, weak_collider);
break;
case ui::collider::method::enabled_changed:
observer = make_observer(method, this->_enabled_property, weak_collider);
break;
}
this->_property_observers.emplace(std::make_pair(method, std::move(observer)));
}
bool hit_test(ui::point const &loc) {
auto const &shape = this->_shape_property.value();
if (shape && this->_enabled_property.value()) {
auto pos = simd::float4x4(matrix_invert(this->_matrix)) * to_float4(loc.v);
return shape.hit_test({pos.x, pos.y});
}
return false;
}
simd::float4x4 const &matrix() const override {
return this->_matrix;
}
void set_matrix(simd::float4x4 &&matrix) override {
this->_matrix = std::move(matrix);
}
private:
simd::float4x4 _matrix = matrix_identity_float4x4;
std::unordered_map<ui::collider::method, base> _property_observers;
};
ui::collider::collider() : base(std::make_shared<impl>(nullptr)) {
}
ui::collider::collider(ui::shape shape) : base(std::make_shared<impl>(std::move(shape))) {
}
ui::collider::collider(std::nullptr_t) : base(nullptr) {
}
ui::collider::~collider() = default;
void ui::collider::set_shape(ui::shape shape) {
impl_ptr<impl>()->_shape_property.set_value(std::move(shape));
}
ui::shape const &ui::collider::shape() const {
return impl_ptr<impl>()->_shape_property.value();
}
void ui::collider::set_enabled(bool const enabled) {
impl_ptr<impl>()->_enabled_property.set_value(enabled);
}
bool ui::collider::is_enabled() const {
return impl_ptr<impl>()->_enabled_property.value();
}
bool ui::collider::hit_test(ui::point const &pos) const {
return impl_ptr<impl>()->hit_test(pos);
}
ui::collider::subject_t &ui::collider::subject() {
return impl_ptr<impl>()->_subject;
}
void ui::collider::dispatch_method(ui::collider::method const method) {
impl_ptr<impl>()->dispatch_method(method);
}
flow::receiver<ui::shape> &ui::collider::shape_receiver() {
return impl_ptr<impl>()->_shape_property.receiver();
}
flow::receiver<bool> &ui::collider::enabled_receiver() {
return impl_ptr<impl>()->_enabled_property.receiver();
}
ui::renderable_collider &ui::collider::renderable() {
if (!this->_renderable) {
this->_renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()};
}
return this->_renderable;
}
<commit_msg>collider property<commit_after>//
// yas_ui_collider.cpp
//
#include "yas_ui_collider.h"
#include "yas_observing.h"
#include "yas_to_bool.h"
using namespace yas;
#pragma mark - shape
bool ui::anywhere_shape::hit_test(ui::point const &) const {
return true;
}
bool ui::circle_shape::hit_test(ui::point const &pos) const {
return std::powf(pos.x - this->center.x, 2.0f) + std::powf(pos.y - this->center.y, 2.0f) <
std::powf(this->radius, 2.0f);
}
bool ui::rect_shape::hit_test(ui::point const &pos) const {
return contains(this->rect, pos);
}
struct ui::shape::impl_base : base::impl {
virtual std::type_info const &type() const = 0;
virtual bool hit_test(ui::point const &) = 0;
};
template <typename T>
struct ui::shape::impl : impl_base {
typename T::type _value;
impl(typename T::type &&value) : _value(std::move(value)) {
}
std::type_info const &type() const override {
return typeid(T);
}
bool hit_test(ui::point const &pos) override {
return this->_value.hit_test(pos);
}
};
ui::shape::shape(anywhere::type shape) : base(std::make_shared<impl<anywhere>>(std::move(shape))) {
}
ui::shape::shape(circle::type shape) : base(std::make_shared<impl<circle>>(std::move(shape))) {
}
ui::shape::shape(rect::type shape) : base(std::make_shared<impl<rect>>(std::move(shape))) {
}
ui::shape::shape(std::nullptr_t) : base(nullptr) {
}
ui::shape::~shape() = default;
std::type_info const &ui::shape::type_info() const {
return impl_ptr<impl_base>()->type();
}
bool ui::shape::hit_test(ui::point const &pos) const {
return impl_ptr<impl_base>()->hit_test(pos);
}
template <typename T>
typename T::type const &ui::shape::get() const {
if (auto ip = std::dynamic_pointer_cast<impl<T>>(impl_ptr())) {
return ip->_value;
}
static const typename T::type _default{};
return _default;
}
template ui::anywhere_shape const &ui::shape::get<ui::shape::anywhere>() const;
template ui::circle_shape const &ui::shape::get<ui::shape::circle>() const;
template ui::rect_shape const &ui::shape::get<ui::shape::rect>() const;
#pragma mark - collider
struct ui::collider::impl : base::impl, renderable_collider::impl {
flow::property<ui::shape> _shape_property{nullptr};
flow::property<bool> _enabled_property{true};
subject_t _subject;
impl(ui::shape &&shape) : _shape_property(std::move(shape)) {
this->_property_flows.reserve(2);
}
void dispatch_method(ui::collider::method const method) {
if (this->_property_flows.count(method)) {
return;
}
auto weak_collider = to_weak(cast<ui::collider>());
flow::observer flow = nullptr;
auto make_flow = [](auto const method, auto property, auto weak_collider) {
return property.begin()
.perform([weak_collider, method](auto const &) {
if (auto node = weak_collider.lock()) {
node.subject().notify(method, node);
}
})
.end();
};
switch (method) {
case ui::collider::method::shape_changed:
flow = make_flow(method, this->_shape_property, weak_collider);
break;
case ui::collider::method::enabled_changed:
flow = make_flow(method, this->_enabled_property, weak_collider);
break;
}
this->_property_flows.emplace(std::make_pair(method, std::move(flow)));
}
bool hit_test(ui::point const &loc) {
auto const &shape = this->_shape_property.value();
if (shape && this->_enabled_property.value()) {
auto pos = simd::float4x4(matrix_invert(this->_matrix)) * to_float4(loc.v);
return shape.hit_test({pos.x, pos.y});
}
return false;
}
simd::float4x4 const &matrix() const override {
return this->_matrix;
}
void set_matrix(simd::float4x4 &&matrix) override {
this->_matrix = std::move(matrix);
}
private:
simd::float4x4 _matrix = matrix_identity_float4x4;
std::unordered_map<ui::collider::method, flow::observer> _property_flows;
};
ui::collider::collider() : base(std::make_shared<impl>(nullptr)) {
}
ui::collider::collider(ui::shape shape) : base(std::make_shared<impl>(std::move(shape))) {
}
ui::collider::collider(std::nullptr_t) : base(nullptr) {
}
ui::collider::~collider() = default;
void ui::collider::set_shape(ui::shape shape) {
impl_ptr<impl>()->_shape_property.set_value(std::move(shape));
}
ui::shape const &ui::collider::shape() const {
return impl_ptr<impl>()->_shape_property.value();
}
void ui::collider::set_enabled(bool const enabled) {
impl_ptr<impl>()->_enabled_property.set_value(enabled);
}
bool ui::collider::is_enabled() const {
return impl_ptr<impl>()->_enabled_property.value();
}
bool ui::collider::hit_test(ui::point const &pos) const {
return impl_ptr<impl>()->hit_test(pos);
}
ui::collider::subject_t &ui::collider::subject() {
return impl_ptr<impl>()->_subject;
}
void ui::collider::dispatch_method(ui::collider::method const method) {
impl_ptr<impl>()->dispatch_method(method);
}
flow::receiver<ui::shape> &ui::collider::shape_receiver() {
return impl_ptr<impl>()->_shape_property.receiver();
}
flow::receiver<bool> &ui::collider::enabled_receiver() {
return impl_ptr<impl>()->_enabled_property.receiver();
}
ui::renderable_collider &ui::collider::renderable() {
if (!this->_renderable) {
this->_renderable = ui::renderable_collider{impl_ptr<ui::renderable_collider::impl>()};
}
return this->_renderable;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_DIST_FUNCTION_HPP
#define MFEM_DIST_FUNCTION_HPP
#include "mfem.hpp"
namespace mfem
{
class DistanceSolver
{
protected:
void ScalarDistToVector(ParGridFunction &dist_s, ParGridFunction &dist_v);
public:
// 0 is nothing / 1 is the main solver / 2 is full (solver + precond).
int print_level = 0;
DistanceSolver() { }
virtual ~DistanceSolver() { }
// Computes a scalar ParGridFunction which is the length of the shortest
// path to the zero level set of the given Coefficient.
// It is expected that [distance] has a valid (scalar) ParFiniteElementSpace,
// and the result is computed in the same space.
// Some implementations may output a "signed" distance, i.e., the distance
// has different signs on both sides of the zeto level set.
virtual void ComputeScalarDistance(Coefficient &zero_level_set,
ParGridFunction &distance) = 0;
// Computes a vector ParGridFunction where the magnitude is the length of
// the shortest path to the zero level set of the given Coefficient, and
// the direction is the starting direction of the shortest path.
// It is expected that [distance] has a valid (vector) ParFiniteElementSpace,
// and the result is computed in the same space.
virtual void ComputeVectorDistance(Coefficient &zero_level_set,
ParGridFunction &distance);
};
// K. Crane et al:
// Geodesics in Heat: A New Approach to Computing Distance Based on Heat Flow
class HeatDistanceSolver : public DistanceSolver
{
public:
HeatDistanceSolver(double diff_coeff)
: DistanceSolver(), parameter_t(diff_coeff), smooth_steps(0),
diffuse_iter(1), transform(true), vis_glvis(false) { }
// The computed distance is not "signed".
// In addition to the standard usage (with zero level sets), this function
// can be applied to point sources when transform = false.
void ComputeScalarDistance(Coefficient &zero_level_set,
ParGridFunction &distance);
int parameter_t, smooth_steps, diffuse_iter;
bool transform, vis_glvis;
};
class NormalizedGradCoefficient : public VectorCoefficient
{
private:
const GridFunction &u;
public:
NormalizedGradCoefficient(const GridFunction &u_gf, int dim)
: VectorCoefficient(dim), u(u_gf) { }
void Eval(Vector &V, ElementTransformation &T, const IntegrationPoint &ip)
{
T.SetIntPoint(&ip);
u.GetGradient(T, V);
const double norm = V.Norml2() + 1e-12;
V /= -norm;
}
};
//Product of the modulus of the first coefficient and the second coefficient
class PProductCoefficient : public Coefficient
{
private:
Coefficient *basef, *corrf;
public:
PProductCoefficient(Coefficient& basec_,Coefficient& corrc_)
{
basef=&basec_;
corrf=&corrc_;
}
virtual
double Eval(ElementTransformation &T, const IntegrationPoint &ip)
{
T.SetIntPoint(&ip);
double u=basef->Eval(T,ip);
double c=corrf->Eval(T,ip);
if (u<0.0) { u*=-1.0;}
return u*c;
}
};
//Formulation for the ScreenedPoisson equation
//The positive part of the input coefficient supply unit volumetric loading
//The negative part - negative unit volumetric loading
//The parameter rh is the radius of a linear cone filter which will deliver
//similar smoothing effect as the Screened Poisson euation
//It determines the length scale of the smoothing.
class ScreenedPoisson: public NonlinearFormIntegrator
{
protected:
double diffcoef;
mfem::Coefficient* func;
public:
ScreenedPoisson(mfem::Coefficient& nfunc, double rh):func(&nfunc)
{
double rd=rh/(2*std::sqrt(3.0));
diffcoef= rd*rd;
}
~ScreenedPoisson() { }
void SetInput(mfem::Coefficient& nfunc) { func = &nfunc; }
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun) override;
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
Vector &elvect) override;
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
DenseMatrix &elmat) override;
};
/// The VectorCoefficent should return a vector with entries:
/// [0] - derivative with respect to x
/// [1] - derivative with respect to y
/// [2] - derivative with respect to z
class PUMPLaplacian: public NonlinearFormIntegrator
{
protected:
mfem::Coefficient *func;
mfem::VectorCoefficient *fgrad;
bool ownership;
double pp, ee;
public:
PUMPLaplacian(Coefficient* nfunc, VectorCoefficient* nfgrad,
bool ownership_=true)
{
func=nfunc;
fgrad=nfgrad;
ownership=ownership_;
pp=2.0;
ee=1e-7;
}
void SetPower(double pp_) { pp = pp_; }
void SetReg(double ee_) { ee = ee_; }
virtual ~PUMPLaplacian()
{
if (ownership)
{
delete func;
delete fgrad;
}
}
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun) override;
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
Vector &elvect) override;
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
DenseMatrix &elmat) override;
};
class PDEFilter
{
public:
PDEFilter(mfem::ParMesh& mesh, double rh, int order_=2,
int maxiter=100, double rtol=1e-7, double atol=1e-15, int print_lv=0)
{
int dim=mesh.Dimension();
lcom=mesh.GetComm();
rr=rh;
fecp=new mfem::H1_FECollection(order_,dim);
fesp=new mfem::ParFiniteElementSpace(&mesh,fecp,1,mfem::Ordering::byVDIM);
sv = fesp->NewTrueDofVector();
bv = fesp->NewTrueDofVector();
gf = new mfem::ParGridFunction(fesp);
nf=new mfem::ParNonlinearForm(fesp);
prec=new mfem::HypreBoomerAMG();
prec->SetPrintLevel(print_lv);
gmres = new mfem::GMRESSolver(lcom);
gmres->SetAbsTol(atol);
gmres->SetRelTol(rtol);
gmres->SetMaxIter(maxiter);
gmres->SetPrintLevel(print_lv);
gmres->SetPreconditioner(*prec);
K=nullptr;
sint=nullptr;
}
~PDEFilter()
{
delete gmres;
delete prec;
delete nf;
delete gf;
delete bv;
delete sv;
delete fesp;
delete fecp;
}
void Filter(mfem::ParGridFunction& func, mfem::ParGridFunction ffield)
{
mfem::GridFunctionCoefficient gfc(&func);
Filter(gfc,ffield);
}
void Filter(mfem::Coefficient& func, mfem::ParGridFunction& ffield)
{
if (sint==nullptr)
{
sint=new mfem::ScreenedPoisson(func,rr);
nf->AddDomainIntegrator(sint);
*sv=0.0;
K=&(nf->GetGradient(*sv));
gmres->SetOperator(*K);
}
else
{
sint->SetInput(func);
}
//form RHS
*sv=0.0;
nf->Mult(*sv,*bv);
//filter the input field
gmres->Mult(*bv,*sv);
gf->SetFromTrueDofs(*sv);
mfem::GridFunctionCoefficient gfc(gf);
ffield.ProjectCoefficient(gfc);
}
private:
MPI_Comm lcom;
mfem::H1_FECollection* fecp;
mfem::ParFiniteElementSpace* fesp;
mfem::ParNonlinearForm* nf;
mfem::HypreBoomerAMG* prec;
mfem::GMRESSolver *gmres;
mfem::HypreParVector *sv;
mfem::HypreParVector *bv;
mfem::ParGridFunction* gf;
mfem::Operator* K;
mfem::ScreenedPoisson* sint;
double rr;
};
class PLapDistanceSolver : public DistanceSolver
{
public:
PLapDistanceSolver(int maxp_ = 30, int newton_iter_ = 10,
double rtol = 1e-7, double atol = 1e-12, int print_lv = 0)
: maxp(maxp_), newton_iter(newton_iter_),
newton_rel_tol(rtol), newton_abs_tol(atol)
{
print_level = print_lv;
}
void SetMaxPower(int new_pp) { maxp = new_pp; }
// Ths computed distance is "signed".
void ComputeScalarDistance(Coefficient& func, ParGridFunction& fdist);
private:
int maxp; //maximum value of the power p
double newton_abs_tol;
double newton_rel_tol;
int newton_iter;
};
} // namespace mfem
#endif
<commit_msg>Minor.<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_DIST_FUNCTION_HPP
#define MFEM_DIST_FUNCTION_HPP
#include "mfem.hpp"
namespace mfem
{
class DistanceSolver
{
protected:
void ScalarDistToVector(ParGridFunction &dist_s, ParGridFunction &dist_v);
public:
// 0 is nothing / 1 is the main solver / 2 is full (solver + precond).
int print_level = 0;
DistanceSolver() { }
virtual ~DistanceSolver() { }
// Computes a scalar ParGridFunction which is the length of the shortest
// path to the zero level set of the given Coefficient.
// It is expected that [distance] has a valid (scalar) ParFiniteElementSpace,
// and the result is computed in the same space.
// Some implementations may output a "signed" distance, i.e., the distance
// has different signs on both sides of the zeto level set.
virtual void ComputeScalarDistance(Coefficient &zero_level_set,
ParGridFunction &distance) = 0;
// Computes a vector ParGridFunction where the magnitude is the length of
// the shortest path to the zero level set of the given Coefficient, and
// the direction is the starting direction of the shortest path.
// It is expected that [distance] has a valid (vector) ParFiniteElementSpace,
// and the result is computed in the same space.
virtual void ComputeVectorDistance(Coefficient &zero_level_set,
ParGridFunction &distance);
};
// K. Crane et al:
// Geodesics in Heat: A New Approach to Computing Distance Based on Heat Flow
class HeatDistanceSolver : public DistanceSolver
{
public:
HeatDistanceSolver(double diff_coeff)
: DistanceSolver(), parameter_t(diff_coeff), smooth_steps(0),
diffuse_iter(1), transform(true), vis_glvis(false) { }
// The computed distance is not "signed".
// In addition to the standard usage (with zero level sets), this function
// can be applied to point sources when transform = false.
void ComputeScalarDistance(Coefficient &zero_level_set,
ParGridFunction &distance);
int parameter_t, smooth_steps, diffuse_iter;
bool transform, vis_glvis;
};
// Belyaev et al:
// On Variational and PDE-based Distance Function Approximations, Section 7.
class PLapDistanceSolver : public DistanceSolver
{
public:
PLapDistanceSolver(int maxp_ = 30, int newton_iter_ = 10,
double rtol = 1e-7, double atol = 1e-12, int print_lv = 0)
: maxp(maxp_), newton_iter(newton_iter_),
newton_rel_tol(rtol), newton_abs_tol(atol)
{
print_level = print_lv;
}
void SetMaxPower(int new_pp) { maxp = new_pp; }
// Ths computed distance is "signed".
void ComputeScalarDistance(Coefficient& func, ParGridFunction& fdist);
private:
int maxp; //maximum value of the power p
double newton_abs_tol;
double newton_rel_tol;
int newton_iter;
};
class NormalizedGradCoefficient : public VectorCoefficient
{
private:
const GridFunction &u;
public:
NormalizedGradCoefficient(const GridFunction &u_gf, int dim)
: VectorCoefficient(dim), u(u_gf) { }
void Eval(Vector &V, ElementTransformation &T, const IntegrationPoint &ip)
{
T.SetIntPoint(&ip);
u.GetGradient(T, V);
const double norm = V.Norml2() + 1e-12;
V /= -norm;
}
};
// Product of the modulus of the first coefficient and the second coefficient
class PProductCoefficient : public Coefficient
{
private:
Coefficient &basef, &corrf;
public:
PProductCoefficient(Coefficient& basec_, Coefficient& corrc_)
: basef(basec_), corrf(corrc_) { }
virtual double Eval(ElementTransformation &T, const IntegrationPoint &ip)
{
T.SetIntPoint(&ip);
double u = basef.Eval(T,ip);
double c = corrf.Eval(T,ip);
if (u<0.0) { u*=-1.0; }
return u*c;
}
};
//Formulation for the ScreenedPoisson equation
//The positive part of the input coefficient supply unit volumetric loading
//The negative part - negative unit volumetric loading
//The parameter rh is the radius of a linear cone filter which will deliver
//similar smoothing effect as the Screened Poisson euation
//It determines the length scale of the smoothing.
class ScreenedPoisson: public NonlinearFormIntegrator
{
protected:
double diffcoef;
mfem::Coefficient* func;
public:
ScreenedPoisson(mfem::Coefficient& nfunc, double rh):func(&nfunc)
{
double rd=rh/(2*std::sqrt(3.0));
diffcoef= rd*rd;
}
~ScreenedPoisson() { }
void SetInput(mfem::Coefficient& nfunc) { func = &nfunc; }
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun) override;
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
Vector &elvect) override;
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
DenseMatrix &elmat) override;
};
// The VectorCoefficent should return a vector with entries:
// [0] - derivative with respect to x
// [1] - derivative with respect to y
// [2] - derivative with respect to z
class PUMPLaplacian: public NonlinearFormIntegrator
{
protected:
mfem::Coefficient *func;
mfem::VectorCoefficient *fgrad;
bool ownership;
double pp, ee;
public:
PUMPLaplacian(Coefficient* nfunc, VectorCoefficient* nfgrad,
bool ownership_=true)
{
func=nfunc;
fgrad=nfgrad;
ownership=ownership_;
pp=2.0;
ee=1e-7;
}
void SetPower(double pp_) { pp = pp_; }
void SetReg(double ee_) { ee = ee_; }
virtual ~PUMPLaplacian()
{
if (ownership)
{
delete func;
delete fgrad;
}
}
virtual double GetElementEnergy(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun) override;
virtual void AssembleElementVector(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
Vector &elvect) override;
virtual void AssembleElementGrad(const FiniteElement &el,
ElementTransformation &trans,
const Vector &elfun,
DenseMatrix &elmat) override;
};
class PDEFilter
{
public:
PDEFilter(mfem::ParMesh& mesh, double rh, int order_=2,
int maxiter=100, double rtol=1e-7, double atol=1e-15, int print_lv=0)
{
int dim=mesh.Dimension();
lcom=mesh.GetComm();
rr=rh;
fecp=new mfem::H1_FECollection(order_,dim);
fesp=new mfem::ParFiniteElementSpace(&mesh,fecp,1,mfem::Ordering::byVDIM);
sv = fesp->NewTrueDofVector();
bv = fesp->NewTrueDofVector();
gf = new mfem::ParGridFunction(fesp);
nf=new mfem::ParNonlinearForm(fesp);
prec=new mfem::HypreBoomerAMG();
prec->SetPrintLevel(print_lv);
gmres = new mfem::GMRESSolver(lcom);
gmres->SetAbsTol(atol);
gmres->SetRelTol(rtol);
gmres->SetMaxIter(maxiter);
gmres->SetPrintLevel(print_lv);
gmres->SetPreconditioner(*prec);
K=nullptr;
sint=nullptr;
}
~PDEFilter()
{
delete gmres;
delete prec;
delete nf;
delete gf;
delete bv;
delete sv;
delete fesp;
delete fecp;
}
void Filter(mfem::ParGridFunction& func, mfem::ParGridFunction ffield)
{
mfem::GridFunctionCoefficient gfc(&func);
Filter(gfc,ffield);
}
void Filter(mfem::Coefficient& func, mfem::ParGridFunction& ffield)
{
if (sint==nullptr)
{
sint=new mfem::ScreenedPoisson(func,rr);
nf->AddDomainIntegrator(sint);
*sv=0.0;
K=&(nf->GetGradient(*sv));
gmres->SetOperator(*K);
}
else
{
sint->SetInput(func);
}
//form RHS
*sv=0.0;
nf->Mult(*sv,*bv);
//filter the input field
gmres->Mult(*bv,*sv);
gf->SetFromTrueDofs(*sv);
mfem::GridFunctionCoefficient gfc(gf);
ffield.ProjectCoefficient(gfc);
}
private:
MPI_Comm lcom;
mfem::H1_FECollection* fecp;
mfem::ParFiniteElementSpace* fesp;
mfem::ParNonlinearForm* nf;
mfem::HypreBoomerAMG* prec;
mfem::GMRESSolver *gmres;
mfem::HypreParVector *sv;
mfem::HypreParVector *bv;
mfem::ParGridFunction* gf;
mfem::Operator* K;
mfem::ScreenedPoisson* sint;
double rr;
};
} // namespace mfem
#endif
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file data.hpp
* \brief Contains basic data manipulation functions.
*/
#ifndef CPP_UTILS_DATA_HPP
#define CPP_UTILS_DATA_HPP
#include <numeric> //for std::accumulate
#include <cmath> //for std::sqrt
#include "assert.hpp"
/*!
* \namespace cpp
* \brief cpp_utils main namespace
*/
namespace cpp {
/*!
* \brief Compute the mean of values of the given range
* \param first Start of the range
* \param last End of the range
* \return the mean of the values of the given range
*/
template<typename Iterator>
double mean(Iterator first, Iterator last){
return std::accumulate(first, last, 0.0) / std::distance(first, last);
}
/*!
* \brief Compute the mean of values in the given container.
* \param container The container to compute the mean from.
* \return the mean of the values in the given container.
*/
template<typename Container>
double mean(const Container& container){
return mean(std::begin(container), std::end(container));
}
/*!
* \brief Compute the standard deviation of values of the given range
* \param first Start of the range
* \param last End of the range
* \param mean The mean of the range
* \return the standard deviation of the values of the given range
*/
template<typename Iterator>
double stddev(Iterator first, Iterator last, double mean){
double std = 0.0;
for(auto it = first; it != last; ++it){
std += (*it - mean) * (*it - mean);
}
return std::sqrt(std / std::distance(first, last));
}
/*!
* \brief Compute the standard deviation of values in the given container.
* \param container The container to compute the mean from.
* \param mean The mean of the range
* \return the standard deviation of the values in the given container.
*/
template<typename Container>
double stddev(const Container& container, double mean){
return stddev(std::begin(container), std::end(container), mean);
}
/*!
* \brief Normalize all the values of the container
* \param container The container to normalize
*
* The values are normalized so the range has zero-mean and unit-variance.
*/
template<typename Container>
void normalize(Container& container){
//normalize to zero-mean
auto m = mean(container);
for(auto& v : container){
v -= m;
}
//normalize to unit variance
auto s = stddev(container, 0.0);
if(s != 0.0){
for(auto& v : container){
v /= s;
}
}
}
/*!
* \brief Normalize each value contained in the given range.
* \param first Start of the range
* \param last End of the range
*
* The values are normalized so the range has zero-mean and unit-variance.
*/
template<typename Iterator>
void normalize_each(Iterator first, Iterator last){
for(; first != last; ++first){
normalize(*first);
}
}
/*!
* \brief Normalize each value contained in the given range.
* \param container The container holding the ranges to normalize.
*
* The values are normalized so the range has zero-mean and unit-variance.
*/
template<typename Container>
void normalize_each(Container& values){
normalize_each(std::begin(values), std::end(values));
}
} //end of the cpp namespace
#endif //CPP_UTILS_ALGORITHM_HPP
<commit_msg>Fix naming<commit_after>//=======================================================================
// Copyright (c) 2013-2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file data.hpp
* \brief Contains basic data manipulation functions.
*/
#ifndef CPP_UTILS_DATA_HPP
#define CPP_UTILS_DATA_HPP
#include <numeric> //for std::accumulate
#include <cmath> //for std::sqrt
#include "assert.hpp"
/*!
* \namespace cpp
* \brief cpp_utils main namespace
*/
namespace cpp {
/*!
* \brief Compute the mean of values of the given range
* \param first Start of the range
* \param last End of the range
* \return the mean of the values of the given range
*/
template<typename Iterator>
double mean(Iterator first, Iterator last){
return std::accumulate(first, last, 0.0) / std::distance(first, last);
}
/*!
* \brief Compute the mean of values in the given container.
* \param container The container to compute the mean from.
* \return the mean of the values in the given container.
*/
template<typename Container>
double mean(const Container& container){
return mean(std::begin(container), std::end(container));
}
/*!
* \brief Compute the standard deviation of values of the given range
* \param first Start of the range
* \param last End of the range
* \param mean The mean of the range
* \return the standard deviation of the values of the given range
*/
template<typename Iterator>
double stddev(Iterator first, Iterator last, double mean){
double std = 0.0;
for(auto it = first; it != last; ++it){
std += (*it - mean) * (*it - mean);
}
return std::sqrt(std / std::distance(first, last));
}
/*!
* \brief Compute the standard deviation of values in the given container.
* \param container The container to compute the mean from.
* \param mean The mean of the range
* \return the standard deviation of the values in the given container.
*/
template<typename Container>
double stddev(const Container& container, double mean){
return stddev(std::begin(container), std::end(container), mean);
}
/*!
* \brief Normalize all the values of the container
* \param container The container to normalize
*
* The values are normalized so the range has zero-mean and unit-variance.
*/
template<typename Container>
void normalize(Container& container){
//normalize to zero-mean
auto m = mean(container);
for(auto& v : container){
v -= m;
}
//normalize to unit variance
auto s = stddev(container, 0.0);
if(s != 0.0){
for(auto& v : container){
v /= s;
}
}
}
/*!
* \brief Normalize each value contained in the given range.
* \param first Start of the range
* \param last End of the range
*
* The values are normalized so the range has zero-mean and unit-variance.
*/
template<typename Iterator>
void normalize_each(Iterator first, Iterator last){
for(; first != last; ++first){
normalize(*first);
}
}
/*!
* \brief Normalize each value contained in the given range.
* \param container The container holding the ranges to normalize.
*
* The values are normalized so the range has zero-mean and unit-variance.
*/
template<typename Container>
void normalize_each(Container& container){
normalize_each(std::begin(container), std::end(container));
}
} //end of the cpp namespace
#endif //CPP_UTILS_ALGORITHM_HPP
<|endoftext|> |
<commit_before>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkColorSpaceXform.h"
#include "SkData.h"
#include "SkMakeUnique.h"
#include "skcms.h"
class SkColorSpaceXform_skcms : public SkColorSpaceXform {
public:
SkColorSpaceXform_skcms(const skcms_ICCProfile& srcProfile,
const skcms_ICCProfile& dstProfile,
skcms_AlphaFormat premulFormat)
: fSrcProfile(srcProfile)
, fDstProfile(dstProfile)
, fPremulFormat(premulFormat) {
skcms_EnsureUsableAsDestination(&fDstProfile, skcms_sRGB_profile());
#ifndef SK_DONT_OPTIMIZE_SRC_PROFILES_FOR_SPEED
skcms_OptimizeForSpeed(&fSrcProfile);
#endif
#ifndef SK_DONT_OPTIMIZE_DST_PROFILES_FOR_SPEED
// (This doesn't do anything yet, but we'd sure like it to.)
skcms_OptimizeForSpeed(&fDstProfile);
#endif
}
bool apply(ColorFormat, void*, ColorFormat, const void*, int, SkAlphaType) const override;
private:
skcms_ICCProfile fSrcProfile;
skcms_ICCProfile fDstProfile;
skcms_AlphaFormat fPremulFormat;
};
static skcms_PixelFormat get_skcms_format(SkColorSpaceXform::ColorFormat fmt) {
switch (fmt) {
case SkColorSpaceXform::kRGBA_8888_ColorFormat:
return skcms_PixelFormat_RGBA_8888;
case SkColorSpaceXform::kBGRA_8888_ColorFormat:
return skcms_PixelFormat_BGRA_8888;
case SkColorSpaceXform::kRGB_U16_BE_ColorFormat:
return skcms_PixelFormat_RGB_161616;
case SkColorSpaceXform::kRGBA_U16_BE_ColorFormat:
return skcms_PixelFormat_RGBA_16161616;
case SkColorSpaceXform::kRGBA_F16_ColorFormat:
return skcms_PixelFormat_RGBA_hhhh;
case SkColorSpaceXform::kRGBA_F32_ColorFormat:
return skcms_PixelFormat_RGBA_ffff;
case SkColorSpaceXform::kBGR_565_ColorFormat:
return skcms_PixelFormat_BGR_565;
default:
SkDEBUGFAIL("Invalid ColorFormat");
return skcms_PixelFormat_RGBA_8888;
}
}
bool SkColorSpaceXform_skcms::apply(ColorFormat dstFormat, void* dst,
ColorFormat srcFormat, const void* src,
int count, SkAlphaType alphaType) const {
skcms_AlphaFormat srcAlpha = skcms_AlphaFormat_Unpremul;
skcms_AlphaFormat dstAlpha = kPremul_SkAlphaType == alphaType ? fPremulFormat
: skcms_AlphaFormat_Unpremul;
return skcms_Transform(src, get_skcms_format(srcFormat), srcAlpha, &fSrcProfile,
dst, get_skcms_format(dstFormat), dstAlpha, &fDstProfile, count);
}
static bool cs_to_profile(const SkColorSpace* cs, skcms_ICCProfile* profile) {
if (cs->profileData()) {
return skcms_Parse(cs->profileData()->data(), cs->profileData()->size(), profile);
}
SkMatrix44 toXYZ(SkMatrix44::kUninitialized_Constructor);
SkColorSpaceTransferFn tf;
if (cs->toXYZD50(&toXYZ) && cs->isNumericalTransferFn(&tf)) {
memset(profile, 0, sizeof(*profile));
profile->has_trc = true;
profile->trc[0].parametric.g = tf.fG;
profile->trc[0].parametric.a = tf.fA;
profile->trc[0].parametric.b = tf.fB;
profile->trc[0].parametric.c = tf.fC;
profile->trc[0].parametric.d = tf.fD;
profile->trc[0].parametric.e = tf.fE;
profile->trc[0].parametric.f = tf.fF;
profile->trc[1].parametric = profile->trc[0].parametric;
profile->trc[2].parametric = profile->trc[0].parametric;
profile->has_toXYZD50 = true;
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
profile->toXYZD50.vals[r][c] = toXYZ.get(r, c);
}
}
return true;
}
// It should be impossible to make a color space that gets here with our available factories.
// All ICC-based profiles have profileData. All remaining factories produce XYZ spaces with
// a single (numerical) transfer function.
SkDEBUGFAIL("How did we get here?");
return false;
}
std::unique_ptr<SkColorSpaceXform> MakeSkcmsXform(SkColorSpace* src, SkColorSpace* dst,
SkTransferFunctionBehavior premulBehavior) {
// Construct skcms_ICCProfiles from each color space. For now, support A2B and XYZ.
// Eventually, only need to support XYZ. Map premulBehavior to one of the two premul formats
// in skcms.
skcms_ICCProfile srcProfile, dstProfile;
if (!cs_to_profile(src, &srcProfile) || !cs_to_profile(dst, &dstProfile)) {
return nullptr;
}
skcms_AlphaFormat premulFormat = SkTransferFunctionBehavior::kRespect == premulBehavior
? skcms_AlphaFormat_PremulLinear : skcms_AlphaFormat_PremulAsEncoded;
return skstd::make_unique<SkColorSpaceXform_skcms>(srcProfile, dstProfile, premulFormat);
}
sk_sp<SkColorSpace> SkColorSpace::Make(const skcms_ICCProfile* profile) {
if (!profile) {
return nullptr;
}
if (!profile->has_toXYZD50 || !profile->has_trc) {
return nullptr;
}
if (skcms_ApproximatelyEqualProfiles(profile, skcms_sRGB_profile())) {
return SkColorSpace::MakeSRGB();
}
SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
toXYZD50.set3x3RowMajorf(&profile->toXYZD50.vals[0][0]);
if (!toXYZD50.invert(nullptr)) {
return nullptr;
}
const skcms_Curve* trc = profile->trc;
if (trc[0].table_entries ||
trc[1].table_entries ||
trc[2].table_entries ||
memcmp(&trc[0].parametric, &trc[1].parametric, sizeof(trc[0].parametric)) ||
memcmp(&trc[0].parametric, &trc[2].parametric, sizeof(trc[0].parametric))) {
return nullptr;
}
SkColorSpaceTransferFn skia_tf;
memcpy(&skia_tf, &profile->trc[0].parametric, sizeof(skia_tf));
return SkColorSpace::MakeRGB(skia_tf, toXYZD50);
}
<commit_msg>Switch to skcms_MakeUsableAsDestination<commit_after>/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkColorSpaceXform.h"
#include "SkData.h"
#include "SkMakeUnique.h"
#include "skcms.h"
class SkColorSpaceXform_skcms : public SkColorSpaceXform {
public:
SkColorSpaceXform_skcms(const skcms_ICCProfile& srcProfile,
const skcms_ICCProfile& dstProfile,
skcms_AlphaFormat premulFormat)
: fSrcProfile(srcProfile)
, fDstProfile(dstProfile)
, fPremulFormat(premulFormat) {
#ifndef SK_DONT_OPTIMIZE_SRC_PROFILES_FOR_SPEED
skcms_OptimizeForSpeed(&fSrcProfile);
#endif
#ifndef SK_DONT_OPTIMIZE_DST_PROFILES_FOR_SPEED
// (This doesn't do anything yet, but we'd sure like it to.)
skcms_OptimizeForSpeed(&fDstProfile);
#endif
}
bool apply(ColorFormat, void*, ColorFormat, const void*, int, SkAlphaType) const override;
private:
skcms_ICCProfile fSrcProfile;
skcms_ICCProfile fDstProfile;
skcms_AlphaFormat fPremulFormat;
};
static skcms_PixelFormat get_skcms_format(SkColorSpaceXform::ColorFormat fmt) {
switch (fmt) {
case SkColorSpaceXform::kRGBA_8888_ColorFormat:
return skcms_PixelFormat_RGBA_8888;
case SkColorSpaceXform::kBGRA_8888_ColorFormat:
return skcms_PixelFormat_BGRA_8888;
case SkColorSpaceXform::kRGB_U16_BE_ColorFormat:
return skcms_PixelFormat_RGB_161616;
case SkColorSpaceXform::kRGBA_U16_BE_ColorFormat:
return skcms_PixelFormat_RGBA_16161616;
case SkColorSpaceXform::kRGBA_F16_ColorFormat:
return skcms_PixelFormat_RGBA_hhhh;
case SkColorSpaceXform::kRGBA_F32_ColorFormat:
return skcms_PixelFormat_RGBA_ffff;
case SkColorSpaceXform::kBGR_565_ColorFormat:
return skcms_PixelFormat_BGR_565;
default:
SkDEBUGFAIL("Invalid ColorFormat");
return skcms_PixelFormat_RGBA_8888;
}
}
bool SkColorSpaceXform_skcms::apply(ColorFormat dstFormat, void* dst,
ColorFormat srcFormat, const void* src,
int count, SkAlphaType alphaType) const {
skcms_AlphaFormat srcAlpha = skcms_AlphaFormat_Unpremul;
skcms_AlphaFormat dstAlpha = kPremul_SkAlphaType == alphaType ? fPremulFormat
: skcms_AlphaFormat_Unpremul;
return skcms_Transform(src, get_skcms_format(srcFormat), srcAlpha, &fSrcProfile,
dst, get_skcms_format(dstFormat), dstAlpha, &fDstProfile, count);
}
static bool cs_to_profile(const SkColorSpace* cs, skcms_ICCProfile* profile) {
if (cs->profileData()) {
return skcms_Parse(cs->profileData()->data(), cs->profileData()->size(), profile);
}
SkMatrix44 toXYZ(SkMatrix44::kUninitialized_Constructor);
SkColorSpaceTransferFn tf;
if (cs->toXYZD50(&toXYZ) && cs->isNumericalTransferFn(&tf)) {
memset(profile, 0, sizeof(*profile));
profile->has_trc = true;
profile->trc[0].parametric.g = tf.fG;
profile->trc[0].parametric.a = tf.fA;
profile->trc[0].parametric.b = tf.fB;
profile->trc[0].parametric.c = tf.fC;
profile->trc[0].parametric.d = tf.fD;
profile->trc[0].parametric.e = tf.fE;
profile->trc[0].parametric.f = tf.fF;
profile->trc[1].parametric = profile->trc[0].parametric;
profile->trc[2].parametric = profile->trc[0].parametric;
profile->has_toXYZD50 = true;
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 3; ++c) {
profile->toXYZD50.vals[r][c] = toXYZ.get(r, c);
}
}
return true;
}
// It should be impossible to make a color space that gets here with our available factories.
// All ICC-based profiles have profileData. All remaining factories produce XYZ spaces with
// a single (numerical) transfer function.
SkDEBUGFAIL("How did we get here?");
return false;
}
std::unique_ptr<SkColorSpaceXform> MakeSkcmsXform(SkColorSpace* src, SkColorSpace* dst,
SkTransferFunctionBehavior premulBehavior) {
// Construct skcms_ICCProfiles from each color space. For now, support A2B and XYZ.
// Eventually, only need to support XYZ. Map premulBehavior to one of the two premul formats
// in skcms.
skcms_ICCProfile srcProfile, dstProfile;
if (!cs_to_profile(src, &srcProfile) || !cs_to_profile(dst, &dstProfile)) {
return nullptr;
}
if (!skcms_MakeUsableAsDestination(&dstProfile)) {
return nullptr;
}
skcms_AlphaFormat premulFormat = SkTransferFunctionBehavior::kRespect == premulBehavior
? skcms_AlphaFormat_PremulLinear : skcms_AlphaFormat_PremulAsEncoded;
return skstd::make_unique<SkColorSpaceXform_skcms>(srcProfile, dstProfile, premulFormat);
}
sk_sp<SkColorSpace> SkColorSpace::Make(const skcms_ICCProfile* profile) {
if (!profile) {
return nullptr;
}
if (!profile->has_toXYZD50 || !profile->has_trc) {
return nullptr;
}
if (skcms_ApproximatelyEqualProfiles(profile, skcms_sRGB_profile())) {
return SkColorSpace::MakeSRGB();
}
SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
toXYZD50.set3x3RowMajorf(&profile->toXYZD50.vals[0][0]);
if (!toXYZD50.invert(nullptr)) {
return nullptr;
}
const skcms_Curve* trc = profile->trc;
if (trc[0].table_entries ||
trc[1].table_entries ||
trc[2].table_entries ||
memcmp(&trc[0].parametric, &trc[1].parametric, sizeof(trc[0].parametric)) ||
memcmp(&trc[0].parametric, &trc[2].parametric, sizeof(trc[0].parametric))) {
return nullptr;
}
SkColorSpaceTransferFn skia_tf;
memcpy(&skia_tf, &profile->trc[0].parametric, sizeof(skia_tf));
return SkColorSpace::MakeRGB(skia_tf, toXYZD50);
}
<|endoftext|> |
<commit_before>/*
* Skaffari - a mail account administration web interface based on Cutelyst
* Copyright (C) 2018 Matthias Fehring <mf@huessenbergnetz.de>
*
* 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 "stringlistsortfilter.h"
#include <QVariant>
#include <QLocale>
#include <QCollator>
#include <QStringList>
#include <cutelee5/cutelee/util.h>
QVariant StringListSortFilter::doFilter(const QVariant &input, const QVariant &argument, bool autoescape) const
{
QVariant ret;
Q_UNUSED(autoescape);
if (!input.canConvert<QStringList>()) {
return ret;
}
QStringList sl = input.toStringList();
if (sl.size() > 1) {
const Cutelee::SafeString loc = Cutelee::getSafeString(argument);
const QLocale locale(loc);
QCollator col(locale);
std::sort(sl.begin(), sl.end(), col);
}
ret.setValue<QStringList>(sl);
return ret;
}
<commit_msg>Update cutlee header file names<commit_after>/*
* Skaffari - a mail account administration web interface based on Cutelyst
* Copyright (C) 2018 Matthias Fehring <mf@huessenbergnetz.de>
*
* 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 "stringlistsortfilter.h"
#include <QVariant>
#include <QLocale>
#include <QCollator>
#include <QStringList>
#include <cutelee/util.h>
QVariant StringListSortFilter::doFilter(const QVariant &input, const QVariant &argument, bool autoescape) const
{
QVariant ret;
Q_UNUSED(autoescape);
if (!input.canConvert<QStringList>()) {
return ret;
}
QStringList sl = input.toStringList();
if (sl.size() > 1) {
const Cutelee::SafeString loc = Cutelee::getSafeString(argument);
const QLocale locale(loc);
QCollator col(locale);
std::sort(sl.begin(), sl.end(), col);
}
ret.setValue<QStringList>(sl);
return ret;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2007 Apple 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE 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.
*/
#include "config.h"
#include "core/page/Console.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptProfiler.h"
#include "core/dom/Document.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InspectorConsoleInstrumentation.h"
#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/ScriptProfile.h"
#include "core/page/ConsoleTypes.h"
#include "core/platform/chromium/TraceEvent.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
ConsoleBase::~ConsoleBase()
{
}
void ConsoleBase::debug(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, DebugMessageLevel, state, arguments);
}
void ConsoleBase::error(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, ErrorMessageLevel, state, arguments);
}
void ConsoleBase::info(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
log(state, arguments);
}
void ConsoleBase::log(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::warn(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, WarningMessageLevel, state, arguments);
}
void ConsoleBase::dir(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(DirMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::dirxml(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(DirXMLMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::table(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(TableMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::clear(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, ClearMessageType, LogMessageLevel, String(), state, arguments);
}
void ConsoleBase::trace(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(TraceMessageType, LogMessageLevel, state, arguments, true, true);
}
void ConsoleBase::assertCondition(ScriptState* state, PassRefPtr<ScriptArguments> arguments, bool condition)
{
if (condition)
return;
internalAddMessage(AssertMessageType, ErrorMessageLevel, state, arguments, true);
}
void ConsoleBase::count(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::consoleCount(context(), state, arguments);
}
void ConsoleBase::markTimeline(PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::consoleTimeStamp(context(), arguments);
}
void ConsoleBase::profile(ScriptState* state, const String& title)
{
ScriptExecutionContext* context = this->context();
if (!context)
return;
// FIXME: log a console message when profiling is disabled.
if (!profilerEnabled())
return;
String resolvedTitle = title;
if (title.isNull()) // no title so give it the next user initiated profile title.
resolvedTitle = InspectorInstrumentation::getCurrentUserInitiatedProfileName(context, true);
ScriptProfiler::start(resolvedTitle);
RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, 1));
const ScriptCallFrame& lastCaller = callStack->at(0);
InspectorInstrumentation::addStartProfilingMessageToConsole(context, resolvedTitle, lastCaller.lineNumber(), lastCaller.sourceURL());
}
void ConsoleBase::profileEnd(ScriptState* state, const String& title)
{
ScriptExecutionContext* context = this->context();
if (!context)
return;
if (!profilerEnabled())
return;
RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
if (!profile)
return;
RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, 1));
InspectorInstrumentation::addProfile(context, profile, callStack);
}
void ConsoleBase::time(const String& title)
{
InspectorInstrumentation::startConsoleTiming(context(), title);
TRACE_EVENT_COPY_ASYNC_BEGIN0("webkit", title.utf8().data(), this);
}
void ConsoleBase::timeEnd(ScriptState* state, const String& title)
{
TRACE_EVENT_COPY_ASYNC_END0("webkit", title.utf8().data(), this);
RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state));
InspectorInstrumentation::stopConsoleTiming(context(), title, callStack.release());
}
void ConsoleBase::timeStamp(PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::consoleTimeStamp(context(), arguments);
}
void ConsoleBase::group(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupMessageType, LogMessageLevel, String(), state, arguments);
}
void ConsoleBase::groupCollapsed(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupCollapsedMessageType, LogMessageLevel, String(), state, arguments);
}
void ConsoleBase::groupEnd()
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, EndGroupMessageType, LogMessageLevel, String(), 0);
}
void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* state, PassRefPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace)
{
if (!context())
return;
RefPtr<ScriptArguments> arguments = scriptArguments;
if (!acceptNoArguments && !arguments->argumentCount())
return;
size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1;
RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, stackSize));
const ScriptCallFrame& lastCaller = callStack->at(0);
String message;
bool gotStringMessage = arguments->getFirstArgumentAsString(message);
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, type, level, message, state, arguments);
if (gotStringMessage)
reportMessageToClient(level, message, callStack);
}
} // namespace WebCore
<commit_msg>Put console.time into a separate trace event category.<commit_after>/*
* Copyright (C) 2007 Apple 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE 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.
*/
#include "config.h"
#include "core/page/Console.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptProfiler.h"
#include "core/dom/Document.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InspectorConsoleInstrumentation.h"
#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/ScriptProfile.h"
#include "core/page/ConsoleTypes.h"
#include "core/platform/chromium/TraceEvent.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
ConsoleBase::~ConsoleBase()
{
}
void ConsoleBase::debug(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, DebugMessageLevel, state, arguments);
}
void ConsoleBase::error(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, ErrorMessageLevel, state, arguments);
}
void ConsoleBase::info(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
log(state, arguments);
}
void ConsoleBase::log(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::warn(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(LogMessageType, WarningMessageLevel, state, arguments);
}
void ConsoleBase::dir(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(DirMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::dirxml(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(DirXMLMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::table(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(TableMessageType, LogMessageLevel, state, arguments);
}
void ConsoleBase::clear(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, ClearMessageType, LogMessageLevel, String(), state, arguments);
}
void ConsoleBase::trace(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
internalAddMessage(TraceMessageType, LogMessageLevel, state, arguments, true, true);
}
void ConsoleBase::assertCondition(ScriptState* state, PassRefPtr<ScriptArguments> arguments, bool condition)
{
if (condition)
return;
internalAddMessage(AssertMessageType, ErrorMessageLevel, state, arguments, true);
}
void ConsoleBase::count(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::consoleCount(context(), state, arguments);
}
void ConsoleBase::markTimeline(PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::consoleTimeStamp(context(), arguments);
}
void ConsoleBase::profile(ScriptState* state, const String& title)
{
ScriptExecutionContext* context = this->context();
if (!context)
return;
// FIXME: log a console message when profiling is disabled.
if (!profilerEnabled())
return;
String resolvedTitle = title;
if (title.isNull()) // no title so give it the next user initiated profile title.
resolvedTitle = InspectorInstrumentation::getCurrentUserInitiatedProfileName(context, true);
ScriptProfiler::start(resolvedTitle);
RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, 1));
const ScriptCallFrame& lastCaller = callStack->at(0);
InspectorInstrumentation::addStartProfilingMessageToConsole(context, resolvedTitle, lastCaller.lineNumber(), lastCaller.sourceURL());
}
void ConsoleBase::profileEnd(ScriptState* state, const String& title)
{
ScriptExecutionContext* context = this->context();
if (!context)
return;
if (!profilerEnabled())
return;
RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
if (!profile)
return;
RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, 1));
InspectorInstrumentation::addProfile(context, profile, callStack);
}
void ConsoleBase::time(const String& title)
{
InspectorInstrumentation::startConsoleTiming(context(), title);
TRACE_EVENT_COPY_ASYNC_BEGIN0("webkit.console", title.utf8().data(), this);
}
void ConsoleBase::timeEnd(ScriptState* state, const String& title)
{
TRACE_EVENT_COPY_ASYNC_END0("webkit.console", title.utf8().data(), this);
RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state));
InspectorInstrumentation::stopConsoleTiming(context(), title, callStack.release());
}
void ConsoleBase::timeStamp(PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::consoleTimeStamp(context(), arguments);
}
void ConsoleBase::group(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupMessageType, LogMessageLevel, String(), state, arguments);
}
void ConsoleBase::groupCollapsed(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupCollapsedMessageType, LogMessageLevel, String(), state, arguments);
}
void ConsoleBase::groupEnd()
{
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, EndGroupMessageType, LogMessageLevel, String(), 0);
}
void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* state, PassRefPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace)
{
if (!context())
return;
RefPtr<ScriptArguments> arguments = scriptArguments;
if (!acceptNoArguments && !arguments->argumentCount())
return;
size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1;
RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, stackSize));
const ScriptCallFrame& lastCaller = callStack->at(0);
String message;
bool gotStringMessage = arguments->getFirstArgumentAsString(message);
InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, type, level, message, state, arguments);
if (gotStringMessage)
reportMessageToClient(level, message, callStack);
}
} // namespace WebCore
<|endoftext|> |
<commit_before>/*
* test.cpp
*
* Created on: Jun 24, 2012
* Author: cryan
*/
#include "headings.h"
#include "libaps.h"
#include "test.h"
void test::programSquareWaves() {
int waveformLen = 1001;
int pulseLen = 500;
int cnt;
int ret;
short int * pulseMem = 0;
pulseMem = (short int *) buildPulseMemory(waveformLen , pulseLen,INT_TYPE);
if (pulseMem == 0) return;
// load memory
for (cnt = 0 ; cnt < 4; cnt++ ) {
printf("Loading Waveform: %i\n", cnt);
fflush(stdout);
ret = set_waveform_int(0, cnt, pulseMem, waveformLen);
if (ret < 0)
printf("Error: %i\n",ret);
else
printf("Done\n");
}
if (pulseMem) free(pulseMem);
}
void test::loadSequenceFile() {
set_trigger_interval(0, 0.001);
load_sequence_file(0, "U:\\AWG-Edison\\Ramsey\\Ramsey-BBNAPS1.h5");
for (int ch = 0; ch < 4; ch++ ) {
set_channel_enabled(0, ch, 1);
}
set_run_mode(0, 0, 1);
set_run_mode(0, 2, 1);
}
void test::streaming() {
set_trigger_interval(0, 0.001);
// set_trigger_source(0, 1);
load_sequence_file(0, "U:\\APS\\Ramsey-Streaming.h5");
set_channel_enabled(0, 0, 1);
set_run_mode(0, 0, 1);
run(0);
Sleep(10000);
stop(0);
}
void test::offsetScale() {
test::programSquareWaves();
set_channel_offset(0, 0, 0.1);
set_channel_scale(0, 0, 0.5);
}
void test::doBulkStateFileTest() {
programSquareWaves();
save_bulk_state_file();
read_bulk_state_file();
}
void test::doStateFilesTest() {
programSquareWaves();
save_state_files();
read_state_files();
}
void * test::buildPulseMemory(int waveformLen , int pulseLen, int pulseType) {
int cnt;
void * pulseMem;
float * pulseMemFloat;
short int * pulseMemInt;
if (pulseType == INT_TYPE) {
pulseMemInt = (short int *) malloc(waveformLen * sizeof(short int));
pulseMem = (void *) pulseMemInt;
} else {
pulseMemFloat = (float *) malloc(waveformLen * sizeof(float));
pulseMem = (void *) pulseMemFloat;
}
if (!pulseMem) {
printf("Error Allocating Memory\n");
return 0;
}
for(cnt = 0; cnt < waveformLen; cnt++) {
if (pulseType == INT_TYPE) {
pulseMemInt[cnt] = (cnt < pulseLen) ? (int) floor(0.8*8192) : 0;
} else {
pulseMemFloat[cnt] = (cnt < pulseLen) ? 1.0 : 0;
}
}
return pulseMem;
}
void test::doToggleTest() {
int ask;
char cmd;
programSquareWaves();
set_trigger_source(0,0);
//Enable all channels
for (int ct=0; ct<4; ct++){
set_channel_enabled(0, ct, 1);
}
ask = 1;
cout << "Cmd: [t]rigger [d]isable e[x]it: ";
while(ask) {
cmd = getchar();
switch (toupper(cmd)) {
case 'T':
printf("Triggering");
run(0);
break;
case 'D':
printf("Disabling");
stop(0);
break;
case 'X':case 'x':
printf("Exiting\n");
stop(0);
ask = 0;
continue;
case '\r':
case '\n':
continue;
default:
printf("No command: %c", cmd);
break;
}
// written this way to handle interactive session where
// input is buffered until \n'
cout << "\nCmd: [t]rigger [d]isable e[x]it: ";
}
close(0);
}
void test::doStoreLoadTest() {
int waveformLen = 1000;
int pulseLen = 500;
float * pulseMem;
int cnt;
pulseMem = (float *) buildPulseMemory(waveformLen , pulseLen, FLOAT_TYPE);
if (pulseMem == 0) return;
printf("Storing Waveform\n");
for( cnt = 0; cnt < 4; cnt++)
set_waveform_float(0, cnt, pulseMem, waveformLen);
printf("Saving Cache\n");
//saveCache(0,0);
printf("Loading Cache\n");
//loadCache(0,0);
printf("Triggering:\n");
set_trigger_source(0, 0);
run(0);
printf("Press key:\n");
getchar();
stop(0);
}
void test::getSetTriggerInterval(){
set_trigger_interval(0, 10e-3);
double interval = get_trigger_interval(0);
printf("Set trigger interval to 10e-3. Read back: %f\n", interval);
}
void test::printHelp(){
string spacing = " ";
cout << "BBN APS C++ Test Bench" << endl;
cout << spacing << "-b <bitfile> Path to bit file" << endl;
cout << spacing << "-t Toggle Test" << endl;
cout << spacing << "-w Run Waveform StoreLoad Tests" << endl;
cout << spacing << "-stream LL Streaming Test" << endl;
cout << spacing << "-bf Run Bulk State File Test" << endl;
cout << spacing << "-sf Run State File Test" << endl;
cout << spacing << "-d Used default DACII bitfile" << endl;
cout << spacing << "-0 Redirect log to stdout" << endl;
cout << spacing << "-h Print This Help Message" << endl;
cout << spacing << "-wf Program square wave" << endl;
cout << spacing << "-trig Get/Set trigger interval" << endl;
cout << spacing << "-seq Load sequence file" << endl;
cout << spacing << "-offset Set offset and scale" << endl;
}
// command options functions taken from:
// http://stackoverflow.com/questions/865668/parse-command-line-arguments
string getCmdOption(char ** begin, char ** end, const std::string & option)
{
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end)
{
return string(*itr);
}
return "";
}
bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
int main(int argc, char** argv) {
int err;
set_logging_level(logDEBUG1);
if (cmdOptionExists(argv, argv + argc, "-h")) {
test::printHelp();
return 0;
}
string bitFile = getCmdOption(argv, argv + argc, "-b");
if (cmdOptionExists(argv, argv + argc, "-d")) {
bitFile = "../bitfiles/mqco_dac2_latest";
}
if (bitFile.length() == 0) {
bitFile = "../bitfiles/mqco_aps_latest";
}
cout << "Programming using: " << string(bitFile) << endl;
//Initialize the APSRack from the DLL
init();
if (cmdOptionExists(argv, argv + argc, "-0")) {
char s[] = "stdout";
set_log(s);
}
//Connect to device
connect_by_ID(0);
err = initAPS(0, const_cast<char*>(bitFile.c_str()), true);
if (err != APS_OK) {
cout << "Error initializing APS Rack: " << err << endl;
exit(-1);
}
// vector<float> waveform(0);
//
// for(int ct=0; ct<1000;ct++){
// waveform.push_back(float(ct)/1000);
// }
// stop(0);
// set_waveform_float(0, 0, &waveform.front(), waveform.size());
// set_run_mode(0, 0, 0);
// run(0);
// Sleep(1);
// stop(0);
// select test to run
if (cmdOptionExists(argv, argv + argc, "-wf")) {
test::programSquareWaves();
}
if (cmdOptionExists(argv, argv + argc, "-stream")) {
test::streaming();
}
if (cmdOptionExists(argv, argv + argc, "-t")) {
test::doToggleTest();
}
if (cmdOptionExists(argv, argv + argc, "-w")) {
test::doStoreLoadTest();
}
if (cmdOptionExists(argv, argv + argc, "-bf")) {
test::doBulkStateFileTest();
}
if (cmdOptionExists(argv, argv + argc, "-sf")) {
test::doStateFilesTest();
}
if (cmdOptionExists(argv, argv + argc, "-trig")) {
test::getSetTriggerInterval();
}
if (cmdOptionExists(argv, argv + argc, "-seq")) {
test::loadSequenceFile();
}
if (cmdOptionExists(argv, argv + argc, "-offset")) {
test::offsetScale();
}
disconnect_by_ID(0);
cout << "Made it through!" << endl;
return 0;
}
<commit_msg>Allow tests on different device IDs<commit_after>/*
* test.cpp
*
* Created on: Jun 24, 2012
* Author: cryan
*/
#include "headings.h"
#include "libaps.h"
#include "test.h"
void test::programSquareWaves() {
int waveformLen = 1001;
int pulseLen = 500;
int cnt;
int ret;
short int * pulseMem = 0;
pulseMem = (short int *) buildPulseMemory(waveformLen , pulseLen,INT_TYPE);
if (pulseMem == 0) return;
// load memory
for (cnt = 0 ; cnt < 4; cnt++ ) {
printf("Loading Waveform: %i\n", cnt);
fflush(stdout);
ret = set_waveform_int(0, cnt, pulseMem, waveformLen);
if (ret < 0)
printf("Error: %i\n",ret);
else
printf("Done\n");
}
if (pulseMem) free(pulseMem);
}
void test::loadSequenceFile() {
set_trigger_interval(0, 0.001);
load_sequence_file(0, "U:\\AWG-Edison\\Ramsey\\Ramsey-BBNAPS1.h5");
for (int ch = 0; ch < 4; ch++ ) {
set_channel_enabled(0, ch, 1);
}
set_run_mode(0, 0, 1);
set_run_mode(0, 2, 1);
}
void test::streaming() {
set_trigger_interval(0, 0.001);
// set_trigger_source(0, 1);
load_sequence_file(0, "U:\\APS\\Ramsey-Streaming.h5");
set_channel_enabled(0, 0, 1);
set_run_mode(0, 0, 1);
run(0);
Sleep(10000);
stop(0);
}
void test::offsetScale() {
test::programSquareWaves();
set_channel_offset(0, 0, 0.1);
set_channel_scale(0, 0, 0.5);
}
void test::doBulkStateFileTest() {
programSquareWaves();
save_bulk_state_file();
read_bulk_state_file();
}
void test::doStateFilesTest() {
programSquareWaves();
save_state_files();
read_state_files();
}
void * test::buildPulseMemory(int waveformLen , int pulseLen, int pulseType) {
int cnt;
void * pulseMem;
float * pulseMemFloat;
short int * pulseMemInt;
if (pulseType == INT_TYPE) {
pulseMemInt = (short int *) malloc(waveformLen * sizeof(short int));
pulseMem = (void *) pulseMemInt;
} else {
pulseMemFloat = (float *) malloc(waveformLen * sizeof(float));
pulseMem = (void *) pulseMemFloat;
}
if (!pulseMem) {
printf("Error Allocating Memory\n");
return 0;
}
for(cnt = 0; cnt < waveformLen; cnt++) {
if (pulseType == INT_TYPE) {
pulseMemInt[cnt] = (cnt < pulseLen) ? (int) floor(0.8*8192) : 0;
} else {
pulseMemFloat[cnt] = (cnt < pulseLen) ? 1.0 : 0;
}
}
return pulseMem;
}
void test::doToggleTest() {
int ask;
char cmd;
programSquareWaves();
set_trigger_source(0,0);
//Enable all channels
for (int ct=0; ct<4; ct++){
set_channel_enabled(0, ct, 1);
}
ask = 1;
cout << "Cmd: [t]rigger [d]isable e[x]it: ";
while(ask) {
cmd = getchar();
switch (toupper(cmd)) {
case 'T':
printf("Triggering");
run(0);
break;
case 'D':
printf("Disabling");
stop(0);
break;
case 'X':case 'x':
printf("Exiting\n");
stop(0);
ask = 0;
continue;
case '\r':
case '\n':
continue;
default:
printf("No command: %c", cmd);
break;
}
// written this way to handle interactive session where
// input is buffered until \n'
cout << "\nCmd: [t]rigger [d]isable e[x]it: ";
}
close(0);
}
void test::doStoreLoadTest() {
int waveformLen = 1000;
int pulseLen = 500;
float * pulseMem;
int cnt;
pulseMem = (float *) buildPulseMemory(waveformLen , pulseLen, FLOAT_TYPE);
if (pulseMem == 0) return;
printf("Storing Waveform\n");
for( cnt = 0; cnt < 4; cnt++)
set_waveform_float(0, cnt, pulseMem, waveformLen);
printf("Saving Cache\n");
//saveCache(0,0);
printf("Loading Cache\n");
//loadCache(0,0);
printf("Triggering:\n");
set_trigger_source(0, 0);
run(0);
printf("Press key:\n");
getchar();
stop(0);
}
void test::getSetTriggerInterval(){
set_trigger_interval(0, 10e-3);
double interval = get_trigger_interval(0);
printf("Set trigger interval to 10e-3. Read back: %f\n", interval);
}
void test::printHelp(){
string spacing = " ";
cout << "BBN APS C++ Test Bench" << endl;
cout << "Usage: test device_id <options>" << endl;
cout << "Where <options> can be any of the following:" << endl;
cout << spacing << "-b <bitfile> Path to bit file" << endl;
cout << spacing << "-t Toggle Test" << endl;
cout << spacing << "-w Run Waveform StoreLoad Tests" << endl;
cout << spacing << "-stream LL Streaming Test" << endl;
cout << spacing << "-bf Run Bulk State File Test" << endl;
cout << spacing << "-sf Run State File Test" << endl;
cout << spacing << "-0 Redirect log to stdout" << endl;
cout << spacing << "-h Print This Help Message" << endl;
cout << spacing << "-wf Program square wave" << endl;
cout << spacing << "-trig Get/Set trigger interval" << endl;
cout << spacing << "-seq Load sequence file" << endl;
cout << spacing << "-offset Set offset and scale" << endl;
}
// command options functions taken from:
// http://stackoverflow.com/questions/865668/parse-command-line-arguments
string getCmdOption(char ** begin, char ** end, const std::string & option)
{
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end)
{
return string(*itr);
}
return "";
}
bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
int main(int argc, char** argv) {
int err;
set_logging_level(logDEBUG1);
if (argc < 2 || cmdOptionExists(argv, argv + argc, "-h")) {
test::printHelp();
return 0;
}
int device_id = atoi(argv[1]);
string bitFile = getCmdOption(argv, argv + argc, "-b");
if (bitFile.length() == 0) {
bitFile = "../../bitfiles/mqco_aps_latest";
}
cout << "Programming device " << device_id << " using: " << string(bitFile) << endl;
//Initialize the APSRack from the DLL
init();
if (cmdOptionExists(argv, argv + argc, "-0")) {
char s[] = "stdout";
set_log(s);
}
//Connect to device
connect_by_ID(device_id);
err = initAPS(device_id, const_cast<char*>(bitFile.c_str()), true);
if (err != APS_OK) {
cout << "Error initializing APS Rack: " << err << endl;
exit(-1);
}
// vector<float> waveform(0);
//
// for(int ct=0; ct<1000;ct++){
// waveform.push_back(float(ct)/1000);
// }
// stop(0);
// set_waveform_float(0, 0, &waveform.front(), waveform.size());
// set_run_mode(0, 0, 0);
// run(0);
// Sleep(1);
// stop(0);
// select test to run
if (cmdOptionExists(argv, argv + argc, "-wf")) {
test::programSquareWaves();
}
if (cmdOptionExists(argv, argv + argc, "-stream")) {
test::streaming();
}
if (cmdOptionExists(argv, argv + argc, "-t")) {
test::doToggleTest();
}
if (cmdOptionExists(argv, argv + argc, "-w")) {
test::doStoreLoadTest();
}
if (cmdOptionExists(argv, argv + argc, "-bf")) {
test::doBulkStateFileTest();
}
if (cmdOptionExists(argv, argv + argc, "-sf")) {
test::doStateFilesTest();
}
if (cmdOptionExists(argv, argv + argc, "-trig")) {
test::getSetTriggerInterval();
}
if (cmdOptionExists(argv, argv + argc, "-seq")) {
test::loadSequenceFile();
}
if (cmdOptionExists(argv, argv + argc, "-offset")) {
test::offsetScale();
}
disconnect_by_ID(device_id);
cout << "Made it through!" << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
// $ g++ -O3 -o createdSortedJaccsFile createdSortedJaccsFile.cpp
// $ ./createdSortedJaccsFile network.jaccs sortedjaccs.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <utility> // for pairs
#include <algorithm> // for swap
#define MIN_DIFF_BW_JACCS 0.0001
using namespace std;
int main (int argc, char const *argv[]){
//************* make sure args are present:
if (argc != 3){
cout << "ERROR: something wrong with the inputs" << endl;
cout << "usage:\n " << argv[0] << " network.jaccs sortedjaccs.csv" << endl;
exit(1);
}
//************* got the args
clock_t begin = clock();
ifstream jaccFile;
jaccFile.open( argv[1] );
if (!jaccFile) {
cout << "ERROR: unable to open jaccards file" << endl;
exit(1); // terminate with error
}
int edgeId1,edgeId2;
float jacc;
set<float> thresholdSet;
set<float> ::reverse_iterator thIt;
// read each line from the jacc file
while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) {
// if this value of jacc does exists
// then add inser the value
if(thresholdSet.count(jacc) == 0)
thresholdSet.insert(jacc);
}
jaccFile.close();jaccFile.clear();
cout << "Done with thresholdSet creation. total unique jaccs:" << thresholdSet.size() << endl;
// create the file
// if exists then overwrite everything
FILE * sortedJaccsFile = fopen( argv[2], "w" );
fclose(sortedJaccsFile);
for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
jacc = *thIt;
// open the file
sortedJaccsFile = fopen( argv[2], "a" );
fprintf( sortedJaccsFile, "%.6f \n", jacc);
fclose(sortedJaccsFile);
}
thresholdSet.clear();
cout << "Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
return 0;
}
<commit_msg>Update createdSortedJaccsFile.cpp<commit_after>/*
// $ g++ -O3 -o createdSortedJaccsFile createdSortedJaccsFile.cpp
// $ ./createdSortedJaccsFile network.jaccs newSortedNewtwork.jaccs sortedJaccs.csv
*/
#include <math.h>
#include <ctime>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <set>
#include <map>
#include <utility> // for pairs
#include <algorithm> // for swap
#define MIN_DIFF_BW_JACCS 0.0001
using namespace std;
int main (int argc, char const *argv[]){
//************* make sure args are present:
if (argc != 4){
cout << "ERROR: something wrong with the inputs" << endl;
cout << "usage:\n " << argv[0] << " network.jaccs newSortedNewtwork.jaccs sortedJaccs.csv" << endl;
exit(1);
}
//************* got the args
clock_t begin = clock();
ifstream jaccFile;
jaccFile.open( argv[1] );
if (!jaccFile) {
cout << "ERROR: unable to open jaccards file" << endl;
exit(1); // terminate with error
}
set<pair<float, pair<int, int> > > jaccsEdgeEdgeSet;
int edgeId1,edgeId2;
float jacc;
set<float> thresholdSet;
// read each line from the jacc file
while ( jaccFile >> edgeId1 >> edgeId2 >> jacc ) {
// if this value of jacc does exists
// then add inser the value
jaccsEdgeEdgeSet.insert(make_pair(jacc, make_pair(edgeId1, edgeId2)));
if(thresholdSet.count(jacc) == 0)
thresholdSet.insert(jacc);
}
jaccFile.close();jaccFile.clear();
cout << "Done with thresholdSet creation. total unique jaccs:" << thresholdSet.size() << endl;
// create the file
// if exists then overwrite everything
FILE * sortedJaccsFile = fopen( argv[3], "w" );
set<float> ::reverse_iterator thIt;
for(thIt = thresholdSet.rbegin(); thIt!=thresholdSet.rend(); thIt++){
jacc = *thIt;
// open the file
fprintf( sortedJaccsFile, "%.6f \n", jacc);
}
fclose(sortedJaccsFile);
thresholdSet.clear();
cout << "Done writing unique jaccs! ";
clock_t end1 = clock();
cout << "Time taken = " << double(end1 - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
//------------------------
// Create a file with sorted in on-increasing order jaccs with:
// < edgeId edgeId jaccs > on each line
long long done = 0;
float percDone = 0.01;
FILE * sortedNewNWJaccsFile = fopen( argv[2], "w" );
set<pair<float, pair<int, int> > >::reverse_iterator jaccsEdgeEdgeSetIt;
for(jaccsEdgeEdgeSetIt = jaccsEdgeEdgeSet.rbegin();
thIt!=jaccsEdgeEdgeSet.rend(); jaccsEdgeEdgeSetIt++){
jacc = (*jaccsEdgeEdgeSetIt)->first;
edgeId1 = (*jaccsEdgeEdgeSetIt)->second->first;
edgeId2 = (*jaccsEdgeEdgeSetIt)->second->second;
// open the file
fprintf( sortedNewNWJaccsFile, "%lld %lld %.6f\n", edgeId1, edgeId2, jacc);
done++;
if((float)done/(float)jaccsEdgeEdgeSet.size() >= percDone){
cout << percDone*100 << " pc done.\n" << endl;
percDone += 0.01;
}
}
fclose(sortedNewNWJaccsFile);
jaccsEdgeEdgeSet.clear();
cout << "Done writing sorted New NW JaccsFile! ";
cout << "Time taken = " << double(clock() - end1)/ CLOCKS_PER_SEC << " seconds. "<< endl;
cout << "Total Time taken = " << double(clock() - begin)/ CLOCKS_PER_SEC << " seconds. "<< endl;
return 0;
}
<|endoftext|> |
<commit_before>//
// TapeUEF.cpp
// Clock Signal
//
// Created by Thomas Harte on 18/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "TapeUEF.hpp"
#include <string.h>
Storage::UEF::UEF(const char *file_name) :
_chunk_id(0), _chunk_length(0), _chunk_position(0),
_time_base(1200)
{
_file = gzopen(file_name, "rb");
char identifier[10];
int bytes_read = gzread(_file, identifier, 10);
if(bytes_read < 10 || strcmp(identifier, "UEF File!"))
{
// exception?
}
int minor, major;
minor = gzgetc(_file);
major = gzgetc(_file);
if(major > 0 || minor > 10 || major < 0 || minor < 0)
{
// exception?
}
find_next_tape_chunk();
}
Storage::UEF::~UEF()
{
gzclose(_file);
}
void Storage::UEF::reset()
{
gzseek(_file, 12, SEEK_SET);
}
Storage::Tape::Pulse Storage::UEF::get_next_pulse()
{
Pulse next_pulse;
if(!_bit_position && chunk_is_finished())
{
find_next_tape_chunk();
}
next_pulse.length.clock_rate = _time_base * 2;
switch(_chunk_id)
{
case 0x0100: case 0x0102:
{
// In the ordinary ("1200 baud") data encoding format,
// a zero bit is encoded as one complete cycle at the base frequency.
// A one bit is two complete cycles at twice the base frequency.
if(!_bit_position)
{
_current_bit = get_next_bit();
}
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = _current_bit ? 1 : 2;
_bit_position = (_bit_position+1)&(_current_bit ? 3 : 1);
} break;
case 0x0110:
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = 2;
_bit_position ^= 1;
if(!_bit_position) _chunk_position++;
break;
case 0x0112:
case 0x0116:
next_pulse.type = Pulse::Zero;
next_pulse.length.length = _tone_length;
_chunk_position++;
break;
}
return next_pulse;
}
void Storage::UEF::find_next_tape_chunk()
{
int reset_count = 0;
_chunk_position = 0;
_bit_position = 0;
while(1)
{
// read chunk ID
_chunk_id = (uint16_t)gzgetc(_file);
_chunk_id |= (uint16_t)(gzgetc(_file) << 8);
_chunk_length = (uint32_t)(gzgetc(_file) << 0);
_chunk_length |= (uint32_t)(gzgetc(_file) << 8);
_chunk_length |= (uint32_t)(gzgetc(_file) << 16);
_chunk_length |= (uint32_t)(gzgetc(_file) << 24);
if(gzeof(_file))
{
reset_count++;
if(reset_count == 2) break;
reset();
continue;
}
switch(_chunk_id)
{
case 0x0100: case 0x0102: // implicit and explicit bit patterns
case 0x0112: case 0x0116: // gaps
return;
case 0x0110: // carrier tone
_tone_length = (uint16_t)gzgetc(_file);
_tone_length |= (uint16_t)(gzgetc(_file) << 8);
gzseek(_file, _chunk_length - 2, SEEK_CUR);
return;
case 0x0111: // carrier tone with dummy byte
// TODO: read length
return;
case 0x0114: // security cycles
// TODO: read number, Ps and Ws
break;
case 0x113: // change of base rate
break;
default:
gzseek(_file, _chunk_length, SEEK_CUR);
break;
}
}
}
bool Storage::UEF::chunk_is_finished()
{
switch(_chunk_id)
{
case 0x0100: return (_chunk_position / 10) == _chunk_length;
case 0x0102: return (_chunk_position / 8) == _chunk_length;
case 0x0111: return _chunk_position == _tone_length;
case 0x0112:
case 0x0116: return _chunk_position ? true : false;
default: return true;
}
}
bool Storage::UEF::get_next_bit()
{
switch(_chunk_id)
{
case 0x0100:
{
uint32_t bit_position = _chunk_position%10;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
if(bit_position == 0) return false;
if(bit_position == 9) return true;
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0102:
{
uint32_t bit_position = _chunk_position%8;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0110:
_chunk_position++;
return true;
default: return true;
}
}
<commit_msg>Update TapeUEF.cpp<commit_after>//
// TapeUEF.cpp
// Clock Signal
//
// Created by Thomas Harte on 18/01/2016.
// Copyright © 2016 Thomas Harte. All rights reserved.
//
#include "TapeUEF.hpp"
#include <string.h>
Storage::UEF::UEF(const char *file_name) :
_chunk_id(0), _chunk_length(0), _chunk_position(0),
_time_base(1200)
{
_file = gzopen(file_name, "rb");
char identifier[10];
int bytes_read = gzread(_file, identifier, 10);
if(bytes_read < 10 || strcmp(identifier, "UEF File!"))
{
// exception?
}
int minor, major;
minor = gzgetc(_file);
major = gzgetc(_file);
if(major > 0 || minor > 10 || major < 0 || minor < 0)
{
// exception?
}
find_next_tape_chunk();
}
Storage::UEF::~UEF()
{
gzclose(_file);
}
void Storage::UEF::reset()
{
gzseek(_file, 12, SEEK_SET);
}
Storage::Tape::Pulse Storage::UEF::get_next_pulse()
{
Pulse next_pulse;
if(!_bit_position && chunk_is_finished())
{
find_next_tape_chunk();
}
next_pulse.length.clock_rate = _time_base * 2;
switch(_chunk_id)
{
case 0x0100: case 0x0102:
{
// In the ordinary ("1200 baud") data encoding format,
// a zero bit is encoded as one complete cycle at the base frequency.
// A one bit is two complete cycles at twice the base frequency.
if(!_bit_position)
{
_current_bit = get_next_bit();
}
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = _current_bit ? 1 : 2;
_bit_position = (_bit_position+1)&(_current_bit ? 3 : 1);
} break;
case 0x0110:
next_pulse.type = (_bit_position&1) ? Pulse::High : Pulse::Low;
next_pulse.length.length = 1;
_bit_position ^= 1;
if(!_bit_position) _chunk_position++;
break;
case 0x0112:
case 0x0116:
next_pulse.type = Pulse::Zero;
next_pulse.length.length = _tone_length;
_chunk_position++;
break;
}
return next_pulse;
}
void Storage::UEF::find_next_tape_chunk()
{
int reset_count = 0;
_chunk_position = 0;
_bit_position = 0;
while(1)
{
// read chunk ID
_chunk_id = (uint16_t)gzgetc(_file);
_chunk_id |= (uint16_t)(gzgetc(_file) << 8);
_chunk_length = (uint32_t)(gzgetc(_file) << 0);
_chunk_length |= (uint32_t)(gzgetc(_file) << 8);
_chunk_length |= (uint32_t)(gzgetc(_file) << 16);
_chunk_length |= (uint32_t)(gzgetc(_file) << 24);
if(gzeof(_file))
{
reset_count++;
if(reset_count == 2) break;
reset();
continue;
}
switch(_chunk_id)
{
case 0x0100: case 0x0102: // implicit and explicit bit patterns
case 0x0112: case 0x0116: // gaps
return;
case 0x0110: // carrier tone
_tone_length = (uint16_t)gzgetc(_file);
_tone_length |= (uint16_t)(gzgetc(_file) << 8);
gzseek(_file, _chunk_length - 2, SEEK_CUR);
return;
case 0x0111: // carrier tone with dummy byte
// TODO: read length
return;
case 0x0114: // security cycles
// TODO: read number, Ps and Ws
break;
case 0x113: // change of base rate
break;
default:
gzseek(_file, _chunk_length, SEEK_CUR);
break;
}
}
}
bool Storage::UEF::chunk_is_finished()
{
switch(_chunk_id)
{
case 0x0100: return (_chunk_position / 10) == _chunk_length;
case 0x0102: return (_chunk_position / 8) == _chunk_length;
case 0x0110: return _chunk_position == _tone_length;
case 0x0112:
case 0x0116: return _chunk_position ? true : false;
default: return true;
}
}
bool Storage::UEF::get_next_bit()
{
switch(_chunk_id)
{
case 0x0100:
{
uint32_t bit_position = _chunk_position%10;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
if(bit_position == 0) return false;
if(bit_position == 9) return true;
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0102:
{
uint32_t bit_position = _chunk_position%8;
_chunk_position++;
if(!bit_position)
{
_current_byte = (uint8_t)gzgetc(_file);
}
bool result = (_current_byte&1) ? true : false;
_current_byte >>= 1;
return result;
}
break;
case 0x0110:
_chunk_position++;
return true;
default: return true;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resultsethelper.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 14:56:40 $
*
* 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_ucbhelper.hxx"
/**************************************************************************
TODO
**************************************************************************
- This implementation is far away from completion. It has no interface
for changes notifications etc.
*************************************************************************/
#ifndef _COM_SUN_STAR_UCB_LISTACTIONTYPE_HPP_
#include <com/sun/star/ucb/ListActionType.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_WELCOMEDYNAMICRESULTSETSTRUCT_HPP_
#include <com/sun/star/ucb/WelcomeDynamicResultSetStruct.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCACHEDDYNAMICRESULTSETSTUBFACTORY_HPP_
#include <com/sun/star/ucb/XCachedDynamicResultSetStubFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XSOURCEINITIALIZATION_HPP_
#include <com/sun/star/ucb/XSourceInitialization.hpp>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#include "osl/diagnose.h"
using namespace com::sun::star;
//=========================================================================
//=========================================================================
//
// ResultSetImplHelper Implementation.
//
//=========================================================================
//=========================================================================
namespace ucbhelper {
//=========================================================================
ResultSetImplHelper::ResultSetImplHelper(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr )
: m_pDisposeEventListeners( 0 ),
m_bStatic( sal_False ),
m_bInitDone( sal_False ),
m_xSMgr( rxSMgr )
{
}
//=========================================================================
ResultSetImplHelper::ResultSetImplHelper(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
const com::sun::star::ucb::OpenCommandArgument2& rCommand )
: m_pDisposeEventListeners( 0 ),
m_bStatic( sal_False ),
m_bInitDone( sal_False ),
m_aCommand( rCommand ),
m_xSMgr( rxSMgr )
{
}
//=========================================================================
// virtual
ResultSetImplHelper::~ResultSetImplHelper()
{
delete m_pDisposeEventListeners;
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_IMPL_4( ResultSetImplHelper,
lang::XTypeProvider,
lang::XServiceInfo,
lang::XComponent, /* base of XDynamicResultSet */
com::sun::star::ucb::XDynamicResultSet );
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_IMPL_3( ResultSetImplHelper,
lang::XTypeProvider,
lang::XServiceInfo,
com::sun::star::ucb::XDynamicResultSet );
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
XSERVICEINFO_NOFACTORY_IMPL_1( ResultSetImplHelper,
rtl::OUString::createFromAscii(
"ResultSetImplHelper" ),
rtl::OUString::createFromAscii(
DYNAMICRESULTSET_SERVICE_NAME ) );
//=========================================================================
//
// XComponent methods.
//
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::dispose()
throw( uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_pDisposeEventListeners && m_pDisposeEventListeners->getLength() )
{
lang::EventObject aEvt;
aEvt.Source = static_cast< lang::XComponent * >( this );
m_pDisposeEventListeners->disposeAndClear( aEvt );
}
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::addEventListener(
const uno::Reference< lang::XEventListener >& Listener )
throw( uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( !m_pDisposeEventListeners )
m_pDisposeEventListeners
= new cppu::OInterfaceContainerHelper( m_aMutex );
m_pDisposeEventListeners->addInterface( Listener );
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::removeEventListener(
const uno::Reference< lang::XEventListener >& Listener )
throw( uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_pDisposeEventListeners )
m_pDisposeEventListeners->removeInterface( Listener );
}
//=========================================================================
//
// XDynamicResultSet methods.
//
//=========================================================================
// virtual
uno::Reference< sdbc::XResultSet > SAL_CALL
ResultSetImplHelper::getStaticResultSet()
throw( com::sun::star::ucb::ListenerAlreadySetException,
uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_xListener.is() )
throw com::sun::star::ucb::ListenerAlreadySetException();
init( sal_True );
return m_xResultSet1;
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::setListener(
const uno::Reference< com::sun::star::ucb::XDynamicResultSetListener >&
Listener )
throw( com::sun::star::ucb::ListenerAlreadySetException,
uno::RuntimeException )
{
osl::ClearableMutexGuard aGuard( m_aMutex );
if ( m_bStatic || m_xListener.is() )
throw com::sun::star::ucb::ListenerAlreadySetException();
m_xListener = Listener;
//////////////////////////////////////////////////////////////////////
// Create "welcome event" and send it to listener.
//////////////////////////////////////////////////////////////////////
// Note: We only have the implementation for a static result set at the
// moment (src590). The dynamic result sets passed to the listener
// are a fake. This implementation will never call "notify" at the
// listener to propagate any changes!!!
init( sal_False );
uno::Any aInfo;
aInfo <<= com::sun::star::ucb::WelcomeDynamicResultSetStruct(
m_xResultSet1 /* "old" */,
m_xResultSet2 /* "new" */ );
uno::Sequence< com::sun::star::ucb::ListAction > aActions( 1 );
aActions.getArray()[ 0 ]
= com::sun::star::ucb::ListAction(
0, // Position; not used
0, // Count; not used
com::sun::star::ucb::ListActionType::WELCOME,
aInfo );
aGuard.clear();
Listener->notify(
com::sun::star::ucb::ListEvent(
static_cast< cppu::OWeakObject * >( this ), aActions ) );
}
//=========================================================================
// virtual
sal_Int16 SAL_CALL ResultSetImplHelper::getCapabilities()
throw( uno::RuntimeException )
{
// ! com::sun::star::ucb::ContentResultSetCapability::SORTED
return 0;
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::connectToCache(
const uno::Reference< com::sun::star::ucb::XDynamicResultSet > &
xCache )
throw( com::sun::star::ucb::ListenerAlreadySetException,
com::sun::star::ucb::AlreadyInitializedException,
com::sun::star::ucb::ServiceNotFoundException,
uno::RuntimeException )
{
if ( m_xListener.is() )
throw com::sun::star::ucb::ListenerAlreadySetException();
if ( m_bStatic )
throw com::sun::star::ucb::ListenerAlreadySetException();
uno::Reference< com::sun::star::ucb::XSourceInitialization >
xTarget( xCache, uno::UNO_QUERY );
if ( xTarget.is() )
{
uno::Reference<
com::sun::star::ucb::XCachedDynamicResultSetStubFactory >
xStubFactory;
try
{
xStubFactory
= uno::Reference<
com::sun::star::ucb::XCachedDynamicResultSetStubFactory >(
m_xSMgr->createInstance(
rtl::OUString::createFromAscii(
"com.sun.star.ucb.CachedDynamicResultSetStubFactory" ) ),
uno::UNO_QUERY );
}
catch ( uno::Exception const & )
{
}
if ( xStubFactory.is() )
{
xStubFactory->connectToCache(
this, xCache, m_aCommand.SortingInfo, 0 );
return;
}
}
throw com::sun::star::ucb::ServiceNotFoundException();
}
//=========================================================================
//
// Non-interface methods.
//
//=========================================================================
void ResultSetImplHelper::init( sal_Bool bStatic )
{
osl::MutexGuard aGuard( m_aMutex );
if ( !m_bInitDone )
{
if ( bStatic )
{
// virtual... derived class fills m_xResultSet1
initStatic();
OSL_ENSURE( m_xResultSet1.is(),
"ResultSetImplHelper::init - No 1st result set!" );
m_bStatic = sal_True;
}
else
{
// virtual... derived class fills m_xResultSet1 and m_xResultSet2
initDynamic();
OSL_ENSURE( m_xResultSet1.is(),
"ResultSetImplHelper::init - No 1st result set!" );
OSL_ENSURE( m_xResultSet2.is(),
"ResultSetImplHelper::init - No 2nd result set!" );
m_bStatic = sal_False;
}
m_bInitDone = sal_True;
}
}
} // namespace ucbhelper
<commit_msg>INTEGRATION: CWS changefileheader (1.6.42); FILE MERGED 2008/04/01 16:02:49 thb 1.6.42.3: #i85898# Stripping all external header guards 2008/04/01 12:58:50 thb 1.6.42.2: #i85898# Stripping all external header guards 2008/03/31 15:31:36 rt 1.6.42.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: resultsethelper.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_ucbhelper.hxx"
/**************************************************************************
TODO
**************************************************************************
- This implementation is far away from completion. It has no interface
for changes notifications etc.
*************************************************************************/
#include <com/sun/star/ucb/ListActionType.hpp>
#include <com/sun/star/ucb/WelcomeDynamicResultSetStruct.hpp>
#include <com/sun/star/ucb/XCachedDynamicResultSetStubFactory.hpp>
#include <com/sun/star/ucb/XSourceInitialization.hpp>
#include <cppuhelper/interfacecontainer.hxx>
#include <ucbhelper/resultsethelper.hxx>
#include "osl/diagnose.h"
using namespace com::sun::star;
//=========================================================================
//=========================================================================
//
// ResultSetImplHelper Implementation.
//
//=========================================================================
//=========================================================================
namespace ucbhelper {
//=========================================================================
ResultSetImplHelper::ResultSetImplHelper(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr )
: m_pDisposeEventListeners( 0 ),
m_bStatic( sal_False ),
m_bInitDone( sal_False ),
m_xSMgr( rxSMgr )
{
}
//=========================================================================
ResultSetImplHelper::ResultSetImplHelper(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
const com::sun::star::ucb::OpenCommandArgument2& rCommand )
: m_pDisposeEventListeners( 0 ),
m_bStatic( sal_False ),
m_bInitDone( sal_False ),
m_aCommand( rCommand ),
m_xSMgr( rxSMgr )
{
}
//=========================================================================
// virtual
ResultSetImplHelper::~ResultSetImplHelper()
{
delete m_pDisposeEventListeners;
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_IMPL_4( ResultSetImplHelper,
lang::XTypeProvider,
lang::XServiceInfo,
lang::XComponent, /* base of XDynamicResultSet */
com::sun::star::ucb::XDynamicResultSet );
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_IMPL_3( ResultSetImplHelper,
lang::XTypeProvider,
lang::XServiceInfo,
com::sun::star::ucb::XDynamicResultSet );
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
XSERVICEINFO_NOFACTORY_IMPL_1( ResultSetImplHelper,
rtl::OUString::createFromAscii(
"ResultSetImplHelper" ),
rtl::OUString::createFromAscii(
DYNAMICRESULTSET_SERVICE_NAME ) );
//=========================================================================
//
// XComponent methods.
//
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::dispose()
throw( uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_pDisposeEventListeners && m_pDisposeEventListeners->getLength() )
{
lang::EventObject aEvt;
aEvt.Source = static_cast< lang::XComponent * >( this );
m_pDisposeEventListeners->disposeAndClear( aEvt );
}
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::addEventListener(
const uno::Reference< lang::XEventListener >& Listener )
throw( uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( !m_pDisposeEventListeners )
m_pDisposeEventListeners
= new cppu::OInterfaceContainerHelper( m_aMutex );
m_pDisposeEventListeners->addInterface( Listener );
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::removeEventListener(
const uno::Reference< lang::XEventListener >& Listener )
throw( uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_pDisposeEventListeners )
m_pDisposeEventListeners->removeInterface( Listener );
}
//=========================================================================
//
// XDynamicResultSet methods.
//
//=========================================================================
// virtual
uno::Reference< sdbc::XResultSet > SAL_CALL
ResultSetImplHelper::getStaticResultSet()
throw( com::sun::star::ucb::ListenerAlreadySetException,
uno::RuntimeException )
{
osl::MutexGuard aGuard( m_aMutex );
if ( m_xListener.is() )
throw com::sun::star::ucb::ListenerAlreadySetException();
init( sal_True );
return m_xResultSet1;
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::setListener(
const uno::Reference< com::sun::star::ucb::XDynamicResultSetListener >&
Listener )
throw( com::sun::star::ucb::ListenerAlreadySetException,
uno::RuntimeException )
{
osl::ClearableMutexGuard aGuard( m_aMutex );
if ( m_bStatic || m_xListener.is() )
throw com::sun::star::ucb::ListenerAlreadySetException();
m_xListener = Listener;
//////////////////////////////////////////////////////////////////////
// Create "welcome event" and send it to listener.
//////////////////////////////////////////////////////////////////////
// Note: We only have the implementation for a static result set at the
// moment (src590). The dynamic result sets passed to the listener
// are a fake. This implementation will never call "notify" at the
// listener to propagate any changes!!!
init( sal_False );
uno::Any aInfo;
aInfo <<= com::sun::star::ucb::WelcomeDynamicResultSetStruct(
m_xResultSet1 /* "old" */,
m_xResultSet2 /* "new" */ );
uno::Sequence< com::sun::star::ucb::ListAction > aActions( 1 );
aActions.getArray()[ 0 ]
= com::sun::star::ucb::ListAction(
0, // Position; not used
0, // Count; not used
com::sun::star::ucb::ListActionType::WELCOME,
aInfo );
aGuard.clear();
Listener->notify(
com::sun::star::ucb::ListEvent(
static_cast< cppu::OWeakObject * >( this ), aActions ) );
}
//=========================================================================
// virtual
sal_Int16 SAL_CALL ResultSetImplHelper::getCapabilities()
throw( uno::RuntimeException )
{
// ! com::sun::star::ucb::ContentResultSetCapability::SORTED
return 0;
}
//=========================================================================
// virtual
void SAL_CALL ResultSetImplHelper::connectToCache(
const uno::Reference< com::sun::star::ucb::XDynamicResultSet > &
xCache )
throw( com::sun::star::ucb::ListenerAlreadySetException,
com::sun::star::ucb::AlreadyInitializedException,
com::sun::star::ucb::ServiceNotFoundException,
uno::RuntimeException )
{
if ( m_xListener.is() )
throw com::sun::star::ucb::ListenerAlreadySetException();
if ( m_bStatic )
throw com::sun::star::ucb::ListenerAlreadySetException();
uno::Reference< com::sun::star::ucb::XSourceInitialization >
xTarget( xCache, uno::UNO_QUERY );
if ( xTarget.is() )
{
uno::Reference<
com::sun::star::ucb::XCachedDynamicResultSetStubFactory >
xStubFactory;
try
{
xStubFactory
= uno::Reference<
com::sun::star::ucb::XCachedDynamicResultSetStubFactory >(
m_xSMgr->createInstance(
rtl::OUString::createFromAscii(
"com.sun.star.ucb.CachedDynamicResultSetStubFactory" ) ),
uno::UNO_QUERY );
}
catch ( uno::Exception const & )
{
}
if ( xStubFactory.is() )
{
xStubFactory->connectToCache(
this, xCache, m_aCommand.SortingInfo, 0 );
return;
}
}
throw com::sun::star::ucb::ServiceNotFoundException();
}
//=========================================================================
//
// Non-interface methods.
//
//=========================================================================
void ResultSetImplHelper::init( sal_Bool bStatic )
{
osl::MutexGuard aGuard( m_aMutex );
if ( !m_bInitDone )
{
if ( bStatic )
{
// virtual... derived class fills m_xResultSet1
initStatic();
OSL_ENSURE( m_xResultSet1.is(),
"ResultSetImplHelper::init - No 1st result set!" );
m_bStatic = sal_True;
}
else
{
// virtual... derived class fills m_xResultSet1 and m_xResultSet2
initDynamic();
OSL_ENSURE( m_xResultSet1.is(),
"ResultSetImplHelper::init - No 1st result set!" );
OSL_ENSURE( m_xResultSet2.is(),
"ResultSetImplHelper::init - No 2nd result set!" );
m_bStatic = sal_False;
}
m_bInitDone = sal_True;
}
}
} // namespace ucbhelper
<|endoftext|> |
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Wim Meeussen */
#include <boost/algorithm/string.hpp>
#include <ros/ros.h>
#include <vector>
#include "urdf/model.h"
namespace urdf{
Model::Model()
{
this->clear();
}
void Model::clear()
{
name_.clear();
this->links_.clear();
this->joints_.clear();
this->materials_.clear();
this->root_link_.reset();
}
bool Model::initFile(const std::string& filename)
{
TiXmlDocument xml_doc;
xml_doc.LoadFile(filename);
return initXml(&xml_doc);
}
bool Model::initParam(const std::string& param)
{
ros::NodeHandle nh;
std::string xml_string;
if (!nh.getParam(param, xml_string)){
ROS_ERROR("Could not find parameter %s on parameter server", param.c_str());
return false;
}
return initString(xml_string);
}
bool Model::initString(const std::string& xml_string)
{
TiXmlDocument xml_doc;
xml_doc.Parse(xml_string.c_str());
return initXml(&xml_doc);
}
bool Model::initXml(TiXmlDocument *xml_doc)
{
if (!xml_doc)
{
ROS_ERROR("Could not parse the xml");
return false;
}
TiXmlElement *robot_xml = xml_doc->FirstChildElement("robot");
if (!robot_xml)
{
ROS_ERROR("Could not find the 'robot' element in the xml file");
return false;
}
return initXml(robot_xml);
}
bool Model::initXml(TiXmlElement *robot_xml)
{
this->clear();
ROS_DEBUG("Parsing robot xml");
if (!robot_xml) return false;
// Get robot name
const char *name = robot_xml->Attribute("name");
if (!name)
{
ROS_ERROR("No name given for the robot.");
return false;
}
this->name_ = std::string(name);
// Get all Material elements
for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
{
boost::shared_ptr<Material> material;
material.reset(new Material);
if (material->initXml(material_xml))
{
if (this->getMaterial(material->name))
{
ROS_ERROR("material '%s' is not unique.", material->name.c_str());
material.reset();
return false;
}
else
{
this->materials_.insert(make_pair(material->name,material));
ROS_DEBUG("successfully added a new material '%s'", material->name.c_str());
}
}
else
{
ROS_ERROR("material xml is not initialized correctly");
material.reset();
return false;
}
}
// Get all Link elements
for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
{
boost::shared_ptr<Link> link;
link.reset(new Link);
if (link->initXml(link_xml))
{
if (this->getLink(link->name))
{
ROS_ERROR("link '%s' is not unique.", link->name.c_str());
link.reset();
return false;
}
else
{
// set link visual material
ROS_DEBUG("setting link '%s' material", link->name.c_str());
if (link->visual)
{
if (!link->visual->material_name.empty())
{
if (this->getMaterial(link->visual->material_name))
{
ROS_DEBUG("setting link '%s' material to '%s'", link->name.c_str(),link->visual->material_name.c_str());
link->visual->material = this->getMaterial( link->visual->material_name.c_str() );
}
else
{
if (link->visual->material)
{
ROS_DEBUG("link '%s' material '%s' defined in Visual.", link->name.c_str(),link->visual->material_name.c_str());
this->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
}
else
{
ROS_ERROR("link '%s' material '%s' undefined.", link->name.c_str(),link->visual->material_name.c_str());
link.reset();
return false;
}
}
}
}
this->links_.insert(make_pair(link->name,link));
ROS_DEBUG("successfully added a new link '%s'", link->name.c_str());
}
}
else
{
ROS_ERROR("link xml is not initialized correctly");
link.reset();
return false;
}
}
// Get all Joint elements
for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
{
boost::shared_ptr<Joint> joint;
joint.reset(new Joint);
if (joint->initXml(joint_xml))
{
if (this->getJoint(joint->name))
{
ROS_ERROR("joint '%s' is not unique.", joint->name.c_str());
joint.reset();
return false;
}
else
{
this->joints_.insert(make_pair(joint->name,joint));
ROS_DEBUG("successfully added a new joint '%s'", joint->name.c_str());
}
}
else
{
ROS_ERROR("joint xml is not initialized correctly");
joint.reset();
return false;
}
}
// every link has children links and joints, but no parents, so we create a
// local convenience data structure for keeping child->parent relations
std::map<std::string, std::string> parent_link_tree;
parent_link_tree.clear();
// building tree: name mapping
if (!this->initTree(parent_link_tree))
{
ROS_ERROR("failed to build tree");
return false;
}
// find the root link
if (!this->initRoot(parent_link_tree))
{
ROS_ERROR("failed to find root link");
return false;
}
return true;
}
bool Model::initTree(std::map<std::string, std::string> &parent_link_tree)
{
// loop through all joints, for every link, assign children links and children joints
for (std::map<std::string,boost::shared_ptr<Joint> >::iterator joint = this->joints_.begin();joint != this->joints_.end(); joint++)
{
std::string parent_link_name = joint->second->parent_link_name;
std::string child_link_name = joint->second->child_link_name;
ROS_DEBUG("build tree: joint: '%s' has parent link '%s' and child link '%s'", joint->first.c_str(), parent_link_name.c_str(),child_link_name.c_str());
if (parent_link_name.empty() && !child_link_name.empty())
{
ROS_ERROR(" Joint %s specifies child link but not parent link.",(joint->second)->name.c_str());
return false;
}
else if (!parent_link_name.empty() && child_link_name.empty())
{
ROS_ERROR(" Joint %s specifies parent link but not child link.",(joint->second)->name.c_str());
return false;
}
else if (parent_link_name.empty() && child_link_name.empty())
{
ROS_DEBUG(" Joint %s specifies no parent link and no child link. This is an abstract joint.",(joint->second)->name.c_str());
}
else
{
// find child and parent links
boost::shared_ptr<Link> child_link, parent_link;
this->getLink(child_link_name, child_link);
if (!child_link)
{
ROS_ERROR(" child link '%s' of joint '%s' not found", child_link_name.c_str(), joint->first.c_str() );
return false;
}
this->getLink(parent_link_name, parent_link);
if (!parent_link)
{
ROS_DEBUG(" parent link '%s' of joint '%s' not found. Automatically adding it. This must be the root link",
parent_link_name.c_str(), joint->first.c_str() );
parent_link.reset(new Link);
parent_link->name = parent_link_name;
this->links_.insert(make_pair(parent_link->name, parent_link));
ROS_DEBUG(" successfully added new link '%s'", parent_link->name.c_str());
}
//set parent link for child link
child_link->setParent(parent_link);
//set parent joint for child link
child_link->setParentJoint(joint->second);
//set child joint for parent link
parent_link->addChildJoint(joint->second);
//set child link for parent link
parent_link->addChild(child_link);
// fill in child/parent string map
parent_link_tree[child_link->name] = parent_link_name;
ROS_DEBUG(" now Link '%s' has %i children ", parent_link->name.c_str(), (int)parent_link->child_links.size());
}
}
return true;
}
bool Model::initRoot(std::map<std::string, std::string> &parent_link_tree)
{
this->root_link_.reset();
// for (std::map<std::string, std::string>::iterator p=parent_link_tree.begin(); p!=parent_link_tree.end(); p++)
// find the links that have no parent in the tree
for (std::map<std::string, boost::shared_ptr<Link> >::iterator l=this->links_.begin(); l!=this->links_.end(); l++)
{
std::map<std::string, std::string >::iterator parent = parent_link_tree.find(l->first);
if (parent == parent_link_tree.end())
{
// store root link
if (!this->root_link_)
{
getLink(l->first, this->root_link_);
}
// we already found a root link
else{
ROS_ERROR("Two root links found: '%s' and '%s'", this->root_link_->name.c_str(), l->first.c_str());
return false;
}
}
}
if (!this->root_link_)
{
ROS_ERROR("No root link found. The robot xml is not a valid tree.");
return false;
}
ROS_DEBUG("Link '%s' is the root link", this->root_link_->name.c_str());
return true;
}
boost::shared_ptr<Material> Model::getMaterial(const std::string& name) const
{
boost::shared_ptr<Material> ptr;
if (this->materials_.find(name) == this->materials_.end())
ptr.reset();
else
ptr = this->materials_.find(name)->second;
return ptr;
}
boost::shared_ptr<const Link> Model::getLink(const std::string& name) const
{
boost::shared_ptr<const Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
return ptr;
}
void Model::getLinks(std::vector<boost::shared_ptr<Link> >& links) const
{
for (std::map<std::string,boost::shared_ptr<Link> >::const_iterator link = this->links_.begin();link != this->links_.end(); link++)
{
links.push_back(link->second);
}
}
void Model::getLink(const std::string& name,boost::shared_ptr<Link> &link) const
{
boost::shared_ptr<Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
link = ptr;
}
boost::shared_ptr<const Joint> Model::getJoint(const std::string& name) const
{
boost::shared_ptr<const Joint> ptr;
if (this->joints_.find(name) == this->joints_.end())
ptr.reset();
else
ptr = this->joints_.find(name)->second;
return ptr;
}
}
<commit_msg>Deprecate parsing of joints that are not attached to any links. This is not supported by the URDF spec, but the parser used to allow this. #4448<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Wim Meeussen */
#include <boost/algorithm/string.hpp>
#include <ros/ros.h>
#include <vector>
#include "urdf/model.h"
namespace urdf{
Model::Model()
{
this->clear();
}
void Model::clear()
{
name_.clear();
this->links_.clear();
this->joints_.clear();
this->materials_.clear();
this->root_link_.reset();
}
bool Model::initFile(const std::string& filename)
{
TiXmlDocument xml_doc;
xml_doc.LoadFile(filename);
return initXml(&xml_doc);
}
bool Model::initParam(const std::string& param)
{
ros::NodeHandle nh;
std::string xml_string;
if (!nh.getParam(param, xml_string)){
ROS_ERROR("Could not find parameter %s on parameter server", param.c_str());
return false;
}
return initString(xml_string);
}
bool Model::initString(const std::string& xml_string)
{
TiXmlDocument xml_doc;
xml_doc.Parse(xml_string.c_str());
return initXml(&xml_doc);
}
bool Model::initXml(TiXmlDocument *xml_doc)
{
if (!xml_doc)
{
ROS_ERROR("Could not parse the xml");
return false;
}
TiXmlElement *robot_xml = xml_doc->FirstChildElement("robot");
if (!robot_xml)
{
ROS_ERROR("Could not find the 'robot' element in the xml file");
return false;
}
return initXml(robot_xml);
}
bool Model::initXml(TiXmlElement *robot_xml)
{
this->clear();
ROS_DEBUG("Parsing robot xml");
if (!robot_xml) return false;
// Get robot name
const char *name = robot_xml->Attribute("name");
if (!name)
{
ROS_ERROR("No name given for the robot.");
return false;
}
this->name_ = std::string(name);
// Get all Material elements
for (TiXmlElement* material_xml = robot_xml->FirstChildElement("material"); material_xml; material_xml = material_xml->NextSiblingElement("material"))
{
boost::shared_ptr<Material> material;
material.reset(new Material);
if (material->initXml(material_xml))
{
if (this->getMaterial(material->name))
{
ROS_ERROR("material '%s' is not unique.", material->name.c_str());
material.reset();
return false;
}
else
{
this->materials_.insert(make_pair(material->name,material));
ROS_DEBUG("successfully added a new material '%s'", material->name.c_str());
}
}
else
{
ROS_ERROR("material xml is not initialized correctly");
material.reset();
return false;
}
}
// Get all Link elements
for (TiXmlElement* link_xml = robot_xml->FirstChildElement("link"); link_xml; link_xml = link_xml->NextSiblingElement("link"))
{
boost::shared_ptr<Link> link;
link.reset(new Link);
if (link->initXml(link_xml))
{
if (this->getLink(link->name))
{
ROS_ERROR("link '%s' is not unique.", link->name.c_str());
link.reset();
return false;
}
else
{
// set link visual material
ROS_DEBUG("setting link '%s' material", link->name.c_str());
if (link->visual)
{
if (!link->visual->material_name.empty())
{
if (this->getMaterial(link->visual->material_name))
{
ROS_DEBUG("setting link '%s' material to '%s'", link->name.c_str(),link->visual->material_name.c_str());
link->visual->material = this->getMaterial( link->visual->material_name.c_str() );
}
else
{
if (link->visual->material)
{
ROS_DEBUG("link '%s' material '%s' defined in Visual.", link->name.c_str(),link->visual->material_name.c_str());
this->materials_.insert(make_pair(link->visual->material->name,link->visual->material));
}
else
{
ROS_ERROR("link '%s' material '%s' undefined.", link->name.c_str(),link->visual->material_name.c_str());
link.reset();
return false;
}
}
}
}
this->links_.insert(make_pair(link->name,link));
ROS_DEBUG("successfully added a new link '%s'", link->name.c_str());
}
}
else
{
ROS_ERROR("link xml is not initialized correctly");
link.reset();
return false;
}
}
// Get all Joint elements
for (TiXmlElement* joint_xml = robot_xml->FirstChildElement("joint"); joint_xml; joint_xml = joint_xml->NextSiblingElement("joint"))
{
boost::shared_ptr<Joint> joint;
joint.reset(new Joint);
if (joint->initXml(joint_xml))
{
if (this->getJoint(joint->name))
{
ROS_ERROR("joint '%s' is not unique.", joint->name.c_str());
joint.reset();
return false;
}
else
{
this->joints_.insert(make_pair(joint->name,joint));
ROS_DEBUG("successfully added a new joint '%s'", joint->name.c_str());
}
}
else
{
ROS_ERROR("joint xml is not initialized correctly");
joint.reset();
return false;
}
}
// every link has children links and joints, but no parents, so we create a
// local convenience data structure for keeping child->parent relations
std::map<std::string, std::string> parent_link_tree;
parent_link_tree.clear();
// building tree: name mapping
if (!this->initTree(parent_link_tree))
{
ROS_ERROR("failed to build tree");
return false;
}
// find the root link
if (!this->initRoot(parent_link_tree))
{
ROS_ERROR("failed to find root link");
return false;
}
return true;
}
bool Model::initTree(std::map<std::string, std::string> &parent_link_tree)
{
// loop through all joints, for every link, assign children links and children joints
for (std::map<std::string,boost::shared_ptr<Joint> >::iterator joint = this->joints_.begin();joint != this->joints_.end(); joint++)
{
std::string parent_link_name = joint->second->parent_link_name;
std::string child_link_name = joint->second->child_link_name;
ROS_DEBUG("build tree: joint: '%s' has parent link '%s' and child link '%s'", joint->first.c_str(), parent_link_name.c_str(),child_link_name.c_str());
if (parent_link_name.empty() && !child_link_name.empty())
{
ROS_ERROR(" Joint %s specifies child link but not parent link.",(joint->second)->name.c_str());
return false;
}
else if (!parent_link_name.empty() && child_link_name.empty())
{
ROS_ERROR(" Joint %s specifies parent link but not child link.",(joint->second)->name.c_str());
return false;
}
else if (parent_link_name.empty() && child_link_name.empty())
{
ROS_WARN(" Joint %s specifies no parent link and no child link. The Boxturtle urdf parser had a bug that allowed this type of joints, but this is not a valid joint according to the URDF spec.",(joint->second)->name.c_str());
}
else
{
// find child and parent links
boost::shared_ptr<Link> child_link, parent_link;
this->getLink(child_link_name, child_link);
if (!child_link)
{
ROS_ERROR(" child link '%s' of joint '%s' not found", child_link_name.c_str(), joint->first.c_str() );
return false;
}
this->getLink(parent_link_name, parent_link);
if (!parent_link)
{
ROS_DEBUG(" parent link '%s' of joint '%s' not found. Automatically adding it. This must be the root link",
parent_link_name.c_str(), joint->first.c_str() );
parent_link.reset(new Link);
parent_link->name = parent_link_name;
this->links_.insert(make_pair(parent_link->name, parent_link));
ROS_DEBUG(" successfully added new link '%s'", parent_link->name.c_str());
}
//set parent link for child link
child_link->setParent(parent_link);
//set parent joint for child link
child_link->setParentJoint(joint->second);
//set child joint for parent link
parent_link->addChildJoint(joint->second);
//set child link for parent link
parent_link->addChild(child_link);
// fill in child/parent string map
parent_link_tree[child_link->name] = parent_link_name;
ROS_DEBUG(" now Link '%s' has %i children ", parent_link->name.c_str(), (int)parent_link->child_links.size());
}
}
return true;
}
bool Model::initRoot(std::map<std::string, std::string> &parent_link_tree)
{
this->root_link_.reset();
// find the links that have no parent in the tree
for (std::map<std::string, boost::shared_ptr<Link> >::iterator l=this->links_.begin(); l!=this->links_.end(); l++)
{
std::map<std::string, std::string >::iterator parent = parent_link_tree.find(l->first);
if (parent == parent_link_tree.end())
{
// store root link
if (!this->root_link_)
{
getLink(l->first, this->root_link_);
}
// we already found a root link
else{
ROS_ERROR("Two root links found: '%s' and '%s'", this->root_link_->name.c_str(), l->first.c_str());
return false;
}
}
}
if (!this->root_link_)
{
ROS_ERROR("No root link found. The robot xml is not a valid tree.");
return false;
}
ROS_DEBUG("Link '%s' is the root link", this->root_link_->name.c_str());
return true;
}
boost::shared_ptr<Material> Model::getMaterial(const std::string& name) const
{
boost::shared_ptr<Material> ptr;
if (this->materials_.find(name) == this->materials_.end())
ptr.reset();
else
ptr = this->materials_.find(name)->second;
return ptr;
}
boost::shared_ptr<const Link> Model::getLink(const std::string& name) const
{
boost::shared_ptr<const Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
return ptr;
}
void Model::getLinks(std::vector<boost::shared_ptr<Link> >& links) const
{
for (std::map<std::string,boost::shared_ptr<Link> >::const_iterator link = this->links_.begin();link != this->links_.end(); link++)
{
links.push_back(link->second);
}
}
void Model::getLink(const std::string& name,boost::shared_ptr<Link> &link) const
{
boost::shared_ptr<Link> ptr;
if (this->links_.find(name) == this->links_.end())
ptr.reset();
else
ptr = this->links_.find(name)->second;
link = ptr;
}
boost::shared_ptr<const Joint> Model::getJoint(const std::string& name) const
{
boost::shared_ptr<const Joint> ptr;
if (this->joints_.find(name) == this->joints_.end())
ptr.reset();
else
ptr = this->joints_.find(name)->second;
return ptr;
}
}
<|endoftext|> |
<commit_before>/*
* drakeUtil.cpp
*
* Created on: Jun 19, 2013
* Author: russt
*/
#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>
using namespace std;
bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
mxArray* plhs;
mxArray* prhs[2];
prhs[0] = const_cast<mxArray*>(mxa);
prhs[1] = mxCreateString(class_str);
mexCallMATLAB(1,&plhs,2,prhs,"isa");
bool tf = *mxGetLogicals(plhs);
mxDestroyArray(plhs);
mxDestroyArray(prhs[1]);
return tf;
}
bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
int i;
mxArray* ex = mexCallMATLABWithTrap(nlhs,plhs,nrhs,prhs,filename);
if (ex) {
mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n",filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mxArray *report;
mexCallMATLAB(1,&report,1,&ex,"getReport");
char *errmsg = mxArrayToString(report);
mexPrintf(errmsg);
mxFree(errmsg);
mxDestroyArray(report);
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
mxDestroyArray(ex);
return true;
}
for (i=0; i<nlhs; i++)
if (!plhs[i]) {
mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs","Asked for %d outputs, but function only returned %d\n",nrhs,i);
return true;
}
return false;
}
/*
* @param subclass_name (optional) if you want to call a class that derives from
* DrakeMexPointer (e.g. so that you can refer to it as something more specific in
* your matlab code), then you can pass in the alternative name here. The constructor
* for this class must take the same inputs as the DrakeMexPointer constructor.
*/
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
mxClassID cid;
if (sizeof(ptr)==4) cid = mxUINT32_CLASS;
else if (sizeof(ptr)==8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize","Are you on a 32-bit machine or 64-bit machine??");
int nrhs=3+num_additional_inputs;
mxArray *plhs[1];
mxArray **prhs; prhs = new mxArray*[nrhs];
prhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
memcpy(mxGetData(prhs[0]),&ptr,sizeof(ptr));
prhs[1] = mxCreateString(mexFunctionName());
prhs[2] = mxCreateString(name);
for (int i=0; i<num_additional_inputs; i++)
prhs[3+i] = delete_fcn_additional_inputs[i];
// mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);
// call matlab to construct mex pointer object
if (subclass_name) {
mexCallMATLABsafe(1,plhs,nrhs,prhs,subclass_name);
if (!isa(plhs[0],"DrakeMexPointer")) {
mxDestroyArray(plhs[0]);
mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass","subclass_name is not a valid subclass of DrakeMexPointer");
}
}
else
mexCallMATLABsafe(1,plhs,nrhs,prhs,"DrakeMexPointer");
mexLock();
// mexPrintf("incrementing lock count\n");
delete[] prhs;
return plhs[0];
}
void* getDrakeMexPointer(const mxArray* mx)
{
void* ptr = NULL;
if (!mxIsClass(mx, "DrakeMexPointer")) {
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs", "getDrakeMexPointer can only be called on arguments which correspond to DrakeMexPointer objects");
}
// todo: optimize this by caching the pointer values, as described in
// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
mxArray* ptrArray = mxGetProperty(mx,0,"ptr");
if (!ptrArray)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?");
if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray)!=1)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
memcpy(&ptr,mxGetData(ptrArray),sizeof(ptr)); // note: could use a reinterpret_cast here instead
return ptr;
}
double angleAverage(double theta1, double theta2) {
// Computes the average between two angles by averaging points on the unit
// circle and taking the arctan of the result.
// see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
// theta1 is a scalar or column vector of angles (rad)
// theta2 is a scalar or column vector of angles (rad)
double x_mean = 0.5*(cos(theta1)+cos(theta2));
double y_mean = 0.5*(sin(theta1)+sin(theta2));
double angle_mean = atan2(y_mean,x_mean);
return angle_mean;
}
std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
// TODO: implement multi-column version
using namespace Eigen;
if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
}
Vector3d cop;
double normal_torque_at_cop;
double fz = normal.dot(force);
bool cop_exists = abs(fz) > 1e-12;
if (cop_exists) {
auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
auto torque_at_cop = torque - cop.cross(force);
normal_torque_at_cop = normal.dot(torque_at_cop);
}
else {
cop.setConstant(std::numeric_limits<double>::quiet_NaN());
normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
}
return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}
double * mxGetPrSafe(const mxArray *pobj) {
if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles");
return mxGetPr(pobj);
}
void sizecheck(const mxArray* mat, int M, int N) {
if (mxGetM(mat) != M) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat));
}
if (mxGetN(mat) != N) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat));
}
return;
}
<commit_msg>fixed formatting<commit_after>/*
* drakeUtil.cpp
*
* Created on: Jun 19, 2013
* Author: russt
*/
#include "drakeUtil.h"
#include <string.h>
#include <string>
#include <math.h>
#include <limits>
#include <Eigen/Dense>
using namespace std;
bool isa(const mxArray* mxa, const char* class_str)
// mxIsClass seems to not be able to handle derived classes. so i'll implement what I need by calling back to matlab
{
mxArray* plhs;
mxArray* prhs[2];
prhs[0] = const_cast<mxArray*>(mxa);
prhs[1] = mxCreateString(class_str);
mexCallMATLAB(1,&plhs,2,prhs,"isa");
bool tf = *mxGetLogicals(plhs);
mxDestroyArray(plhs);
mxDestroyArray(prhs[1]);
return tf;
}
bool mexCallMATLABsafe(int nlhs, mxArray* plhs[], int nrhs, mxArray* prhs[], const char* filename)
{
int i;
mxArray* ex = mexCallMATLABWithTrap(nlhs,plhs,nrhs,prhs,filename);
if (ex) {
mexPrintf("DrakeSystem S-Function: error when calling ''%s'' with the following arguments:\n",filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mxArray *report;
mexCallMATLAB(1,&report,1,&ex,"getReport");
char *errmsg = mxArrayToString(report);
mexPrintf(errmsg);
mxFree(errmsg);
mxDestroyArray(report);
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:CallbackError", "Error in MATLAB callback.\nSee additional debugging information above");
mxDestroyArray(ex);
return true;
}
for (i=0; i<nlhs; i++)
if (!plhs[i]) {
mexPrintf("Drake mexCallMATLABsafe: error when calling ''%s'' with the following arguments:\n", filename);
for (i=0; i<nrhs; i++)
mexCallMATLAB(0,NULL,1,&prhs[i],"disp");
mexErrMsgIdAndTxt("Drake:mexCallMATLABsafe:NotEnoughOutputs","Asked for %d outputs, but function only returned %d\n",nrhs,i);
return true;
}
return false;
}
/*
* @param subclass_name (optional) if you want to call a class that derives from
* DrakeMexPointer (e.g. so that you can refer to it as something more specific in
* your matlab code), then you can pass in the alternative name here. The constructor
* for this class must take the same inputs as the DrakeMexPointer constructor.
*/
mxArray* createDrakeMexPointer(void* ptr, const char* name, int num_additional_inputs, mxArray* delete_fcn_additional_inputs[], const char* subclass_name)
{
mxClassID cid;
if (sizeof(ptr)==4) cid = mxUINT32_CLASS;
else if (sizeof(ptr)==8) cid = mxUINT64_CLASS;
else mexErrMsgIdAndTxt("Drake:constructDrakeMexPointer:PointerSize","Are you on a 32-bit machine or 64-bit machine??");
int nrhs=3+num_additional_inputs;
mxArray *plhs[1];
mxArray **prhs; prhs = new mxArray*[nrhs];
prhs[0] = mxCreateNumericMatrix(1,1,cid,mxREAL);
memcpy(mxGetData(prhs[0]),&ptr,sizeof(ptr));
prhs[1] = mxCreateString(mexFunctionName());
prhs[2] = mxCreateString(name);
for (int i=0; i<num_additional_inputs; i++)
prhs[3+i] = delete_fcn_additional_inputs[i];
// mexPrintf("deleteMethod = %s\n name =%s\n", deleteMethod,name);
// call matlab to construct mex pointer object
if (subclass_name) {
mexCallMATLABsafe(1,plhs,nrhs,prhs,subclass_name);
if (!isa(plhs[0],"DrakeMexPointer")) {
mxDestroyArray(plhs[0]);
mexErrMsgIdAndTxt("Drake:createDrakeMexPointer:InvalidSubclass","subclass_name is not a valid subclass of DrakeMexPointer");
}
}
else
mexCallMATLABsafe(1,plhs,nrhs,prhs,"DrakeMexPointer");
mexLock();
// mexPrintf("incrementing lock count\n");
delete[] prhs;
return plhs[0];
}
void* getDrakeMexPointer(const mxArray* mx)
{
void* ptr = NULL;
if (!mxIsClass(mx, "DrakeMexPointer"))
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs", "getDrakeMexPointer can only be called on arguments which correspond to DrakeMexPointer objects");
// todo: optimize this by caching the pointer values, as described in
// http://groups.csail.mit.edu/locomotion/bugs/show_bug.cgi?id=1590
mxArray* ptrArray = mxGetProperty(mx,0,"ptr");
if (!ptrArray)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","cannot retrieve 'ptr' field from this mxArray. are you sure it's a valid DrakeMexPointer object?");
if (!mxIsNumeric(ptrArray) || mxGetNumberOfElements(ptrArray)!=1)
mexErrMsgIdAndTxt("Drake:getDrakeMexPointer:BadInputs","the ptr property of this DrakeMexPointer does not appear to contain a valid pointer");
memcpy(&ptr,mxGetData(ptrArray),sizeof(ptr)); // note: could use a reinterpret_cast here instead
return ptr;
}
double angleAverage(double theta1, double theta2) {
// Computes the average between two angles by averaging points on the unit
// circle and taking the arctan of the result.
// see: http://en.wikipedia.org/wiki/Mean_of_circular_quantities
// theta1 is a scalar or column vector of angles (rad)
// theta2 is a scalar or column vector of angles (rad)
double x_mean = 0.5*(cos(theta1)+cos(theta2));
double y_mean = 0.5*(sin(theta1)+sin(theta2));
double angle_mean = atan2(y_mean,x_mean);
return angle_mean;
}
std::pair<Eigen::Vector3d, double> resolveCenterOfPressure(Eigen::Vector3d torque, Eigen::Vector3d force, Eigen::Vector3d normal, Eigen::Vector3d point_on_contact_plane)
{
// TODO: implement multi-column version
using namespace Eigen;
if (abs(normal.squaredNorm() - 1.0) > 1e-12) {
mexErrMsgIdAndTxt("Drake:resolveCenterOfPressure:BadInputs", "normal should be a unit vector");
}
Vector3d cop;
double normal_torque_at_cop;
double fz = normal.dot(force);
bool cop_exists = abs(fz) > 1e-12;
if (cop_exists) {
auto torque_at_point_on_contact_plane = torque - point_on_contact_plane.cross(force);
double normal_torque_at_point_on_contact_plane = normal.dot(torque_at_point_on_contact_plane);
auto tangential_torque = torque_at_point_on_contact_plane - normal * normal_torque_at_point_on_contact_plane;
cop = normal.cross(tangential_torque) / fz + point_on_contact_plane;
auto torque_at_cop = torque - cop.cross(force);
normal_torque_at_cop = normal.dot(torque_at_cop);
}
else {
cop.setConstant(std::numeric_limits<double>::quiet_NaN());
normal_torque_at_cop = std::numeric_limits<double>::quiet_NaN();
}
return std::pair<Vector3d, double>(cop, normal_torque_at_cop);
}
double * mxGetPrSafe(const mxArray *pobj) {
if (!mxIsDouble(pobj)) mexErrMsgIdAndTxt("Drake:mxGetPrSafe:BadInputs", "mxGetPr can only be called on arguments which correspond to Matlab doubles");
return mxGetPr(pobj);
}
void sizecheck(const mxArray* mat, int M, int N) {
if (mxGetM(mat) != M) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of rows. Expected: %d but got: %d", M, mxGetM(mat));
}
if (mxGetN(mat) != N) {
mexErrMsgIdAndTxt("Drake:WrongSize", "wrong number of columns. Expected: %d but got: %d", N, mxGetN(mat));
}
return;
}
<|endoftext|> |
<commit_before>/***************************************************************************
main.cpp - description
-------------------
begin : Sat Nov 4 21:16:33 CST 2000
copyright : (C) 2000 by Jon S. Berndt
email : jsb@hal-pc.org
compile this under windows like this:
g++ -o simplot datafile.cpp main.cpp -I/usr/local/dislin -L/usr/local/dislin -ldisgcc -lgdi32 -lcomdlg32
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream.h>
#include <fstream.h>
#include <cstdio>
#include <cstdlib>
#include "dislin.h"
#include "datafile.h"
void plotdata(ifstream* datafile);
int main(int argc, char *argv[])
{
string commands_str, digits = "0123456789", displaytype="CONS", next;
string savefile="", pngFName_str="JSBSim", time_str, float_digits=".0123456789";
vector <int> commands_vec;
size_t start = 0, end = 0, namelen;
char pngFName[200]="JSBSim";
float sf, ef;
char scratch;
if (argc > 3 || argc == 1 ) {
cout << endl << "Usage: SimPlot <data_file_name.csv> [<autoplot file>]" << endl << endl;
exit(-1);
}
DataFile df(argv[1]);
ifstream f;
if (argc == 3) {
f.open(argv[2]);
if (!f) {
cerr << "Could not open autoplot file " << argv[2] << endl << endl;
} else {
f.setf(ios::skipws);
}
plotdata(&f);
exit(0);
}
cout << endl << endl << "Here are the available parameters which may be plotted: " << endl;
cout << endl;
namelen = 0;
for (unsigned int i=0; i<df.names.size();i++) {
namelen = namelen > df.names[i].size() ? namelen : df.names[i].size();
}
nextplot:
commands_str = "";
time_str = "";
start=0;
end=0;
commands_vec.clear();
bool col1 = true;
unsigned int i;
for (i=0; i<df.names.size();i++) {
cout << i << ") " << df.names[i];
if (col1) {
for (unsigned int j=0; j<= namelen - df.names[i].size() + 2; j++) cout << " ";
if (i<10) cout << " ";
} else {
cout << endl;
}
col1=!col1;
}
int numvars = df.GetNumFields();
int numpoints = df.GetNumRecords();
float starttime = df.GetStartTime();
float endtime = df.GetEndTime();
cout << endl;
cout << endl << "Data file contains " << numvars << " independent variables." << endl;
cout << "Number of data points: " << numpoints << endl;
cout << "Time goes from " << starttime << " to " << endtime << " seconds." << endl;
entertime:
cout << endl << "Enter new time range [#.#-#.# or -]: ";
cin >> time_str;
sf = starttime;
ef = endtime;
if (time_str[0] != '-') {
sscanf(time_str.c_str(),"%f %c %f",&sf, &scratch, &ef);
bool redo = true;
if (ef <= sf) {
cout << "The end time must be greater than the start time" << endl;
} else if (ef <= 0.0) {
cout << "The end time must be greater than zero" << endl;
} else if (sf < 0.000) {
cout << "The start time must not be less than zero" << endl;
} else if (sf < starttime) {
cout << "The start time must not be less than " << starttime << endl;
} else if (ef > endtime) {
cout << "The end time must not be greater than " << endtime << endl;
} else {
for (int pt=0; pt<df.GetNumRecords(); pt++) {
if (df.Data[pt][0] <= sf) df.SetStartIdx(pt);
if (df.Data[pt][0] <= ef) {
df.SetEndIdx(pt);
} else {
break;
}
}
redo = false;
}
if (redo) goto entertime;
} else {
df.SetStartIdx(0);
df.SetEndIdx(df.GetNumRecords()-1);
}
cout << endl << "Enter a comma-separated list of the items to be plotted (or 'q' to quit): ";
cin >> commands_str;
if (commands_str[0] == 'q') exit(0);
while (1) {
start = commands_str.find_first_of(digits,start);
if (start >= string::npos) break;
end = commands_str.find_first_not_of(digits,start);
commands_vec.push_back(atoi(commands_str.substr(start, end-start).c_str()));
start=end;
}
cout << "Initializing plot page ..." << endl;
savepng:
// Set page format
metafl((char*)displaytype.c_str());
setpag("da4l");
// Initialization
disini();
// Set Plot Parameters
pagera();
serif();
shdcha();
chncrv("color");
// Set plot axis system
axspos(450,1800);
axslen(2200,1200);
// Set plot titles
int thisplot;
int numtraces = commands_vec.size();
name("Time (in seconds)","x");
string longaxistext;
for (thisplot=0; thisplot < numtraces; thisplot++) {
longaxistext = longaxistext + " " + df.names[commands_vec[thisplot]];
}
name((char*)(longaxistext.c_str()),"y");
labdig(3,"xy");
ticks(10,"xy");
titlin("JSBSim plot",1);
string subtitle = "";
for (thisplot=0; thisplot < numtraces; thisplot++) {
if (thisplot == 0) subtitle = df.names[commands_vec[thisplot]];
else subtitle = subtitle + ", " + df.names[commands_vec[thisplot]];
}
subtitle = subtitle + string(" vs. Time");
titlin((char*)(subtitle.c_str()),3);
// Plot data
float *timarray = new float[df.GetEndIdx()-df.GetStartIdx()+1]; // new jsb 11/9
for (int pt=df.GetStartIdx(), pti=0; pt<=df.GetEndIdx(); pt++, pti++) {
timarray[pti] = df.Data[pt][0];
}
float axismax = df.GetAutoAxisMax(commands_vec[0]);
float axismin = df.GetAutoAxisMin(commands_vec[0]);
for (thisplot=1; thisplot < numtraces; thisplot++) {
axismax = axismax > df.GetAutoAxisMax(commands_vec[thisplot]) ? axismax : df.GetAutoAxisMax(commands_vec[thisplot]);
axismin = axismin < df.GetAutoAxisMin(commands_vec[thisplot]) ? axismin : df.GetAutoAxisMin(commands_vec[thisplot]);
}
float spread = axismax - axismin;
if (spread < 1.0) labdig(3,"y");
else if (spread < 10.0) labdig(2,"y");
else if (spread < 100.0) labdig(1,"y");
else labdig(0,"y");
if (spread > 1000.0) {
labdig(2,"y");
labels("fexp","y");
} else {
labels("float","y");
}
spread = df.Data[df.GetEndIdx()][0] - df.Data[df.GetStartIdx()][0];
if (spread < 1.0) labdig(3,"x");
else if (spread < 10.0) labdig(2,"x");
else if (spread < 100.0) labdig(1,"x");
else labdig(0,"x");
float fac = ((int)(spread + 0.5))/10.00;
if (spread > 1000.0) labels("fexp","x");
else labels("float","x");
graf( df.Data[df.GetStartIdx()][0], // starttime
df.Data[df.GetEndIdx()][0], // endtime
df.Data[df.GetStartIdx()][0], // starttime
fac,
axismin,
axismax,
axismin,
(axismax - axismin)/10.0);
title();
color("blue");
grid(1,1);
for (thisplot=0; thisplot < numtraces; thisplot++) {
float *datarray = new float[df.GetEndIdx()-df.GetStartIdx()+1];
for (int pt=df.GetStartIdx(), pti=0; pt<=df.GetEndIdx(); pt++, pti++) {
datarray[pti] = df.Data[pt][commands_vec[thisplot]];
}
color("red");
curve(timarray,datarray,df.GetEndIdx()-df.GetStartIdx()+1);
delete[] datarray;
}
char legendtext[numtraces*(namelen)];
color("blue");
legini(legendtext, numtraces, (namelen));
legtit("Legend");
for (thisplot=0; thisplot < numtraces; thisplot++) {
leglin(legendtext, (char*)df.names[commands_vec[thisplot]].c_str(), thisplot+1);
}
legend(legendtext, 3);
// Terminate
disfin();
// Request to save
if (displaytype == "CONS") {
cout << endl << "Save graph as a .png file [y|N]: ";
cin >> savefile;
if (savefile[0] == 'y') {
displaytype = "PNG";
pngFName_str = dwgtxt("Enter filename:",pngFName);
if (pngFName_str.find_first_of("png",0) == string::npos) {
pngFName_str = pngFName_str + ".png";
}
setfil((char*)pngFName_str.c_str());
goto savepng;
}
} else {
displaytype = "CONS";
}
cout << endl << "Create another plot? [Y|n]: ";
cin >> next;
if (next[0] == 'n') {
return EXIT_SUCCESS;
} else {
goto nextplot;
}
}
void plotdata(ifstream* datafile)
{
string data_str;
string Title, Y_Axis_Caption, X_Axis_Caption;
string Y_Variables;
string X_Variable;
string Ranges;
double xmin, ymin, xmax, ymax;
int delim;
while (!datafile->eof()) {
getline(*datafile, Title);
getline(*datafile, X_Axis_Caption);
getline(*datafile, Y_Axis_Caption);
getline(*datafile, Ranges);
getline(*datafile, X_Variable);
getline(*datafile, Y_Variables);
if (datafile->eof()) break;
if (Ranges.find("auto") != string::npos) { // autoscaling
xmin = xmax = ymin = ymax = 0.00;
cout << "Autoscaling ..." << endl;
} else {
delim = Ranges.find_first_of("|");
xmin = strtod(Ranges.substr(0, delim-1).c_str(), NULL);
cout << "Range: " << xmin;
}
}
}
<commit_msg>Further mods for plotting program to aid in automated analysis - you'll like this<commit_after>/***************************************************************************
main.cpp - description
-------------------
begin : Sat Nov 4 21:16:33 CST 2000
copyright : (C) 2000 by Jon S. Berndt
email : jsb@hal-pc.org
compile this under windows like this:
g++ -o simplot datafile.cpp main.cpp -I/usr/local/dislin -L/usr/local/dislin -ldisgcc -lgdi32 -lcomdlg32
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iostream.h>
#include <fstream.h>
#include <cstdio>
#include <cstdlib>
#include "dislin.h"
#include "datafile.h"
void plotdata(ifstream* datafile);
int main(int argc, char *argv[])
{
string commands_str, digits = "0123456789", displaytype="CONS", next;
string savefile="", pngFName_str="JSBSim", time_str, float_digits=".0123456789";
vector <int> commands_vec;
size_t start = 0, end = 0, namelen;
char pngFName[200]="JSBSim";
float sf, ef;
char scratch;
if (argc > 3 || argc == 1 ) {
cout << endl << "Usage: SimPlot <data_file_name.csv> [<autoplot file>]" << endl << endl;
exit(-1);
}
DataFile df(argv[1]);
ifstream f;
if (argc == 3) {
f.open(argv[2]);
if (!f) {
cerr << "Could not open autoplot file " << argv[2] << endl << endl;
} else {
f.setf(ios::skipws);
}
plotdata(&f);
exit(0);
}
cout << endl << endl << "Here are the available parameters which may be plotted: " << endl;
cout << endl;
namelen = 0;
for (unsigned int i=0; i<df.names.size();i++) {
namelen = namelen > df.names[i].size() ? namelen : df.names[i].size();
}
nextplot:
commands_str = "";
time_str = "";
start=0;
end=0;
commands_vec.clear();
bool col1 = true;
unsigned int i;
for (i=0; i<df.names.size();i++) {
cout << i << ") " << df.names[i];
if (col1) {
for (unsigned int j=0; j<= namelen - df.names[i].size() + 2; j++) cout << " ";
if (i<10) cout << " ";
} else {
cout << endl;
}
col1=!col1;
}
int numvars = df.GetNumFields();
int numpoints = df.GetNumRecords();
float starttime = df.GetStartTime();
float endtime = df.GetEndTime();
cout << endl;
cout << endl << "Data file contains " << numvars << " independent variables." << endl;
cout << "Number of data points: " << numpoints << endl;
cout << "Time goes from " << starttime << " to " << endtime << " seconds." << endl;
entertime:
cout << endl << "Enter new time range [#.#-#.# or -]: ";
cin >> time_str;
sf = starttime;
ef = endtime;
if (time_str[0] != '-') {
sscanf(time_str.c_str(),"%f %c %f",&sf, &scratch, &ef);
bool redo = true;
if (ef <= sf) {
cout << "The end time must be greater than the start time" << endl;
} else if (ef <= 0.0) {
cout << "The end time must be greater than zero" << endl;
} else if (sf < 0.000) {
cout << "The start time must not be less than zero" << endl;
} else if (sf < starttime) {
cout << "The start time must not be less than " << starttime << endl;
} else if (ef > endtime) {
cout << "The end time must not be greater than " << endtime << endl;
} else {
for (int pt=0; pt<df.GetNumRecords(); pt++) {
if (df.Data[pt][0] <= sf) df.SetStartIdx(pt);
if (df.Data[pt][0] <= ef) {
df.SetEndIdx(pt);
} else {
break;
}
}
redo = false;
}
if (redo) goto entertime;
} else {
df.SetStartIdx(0);
df.SetEndIdx(df.GetNumRecords()-1);
}
cout << endl << "Enter a comma-separated list of the items to be plotted (or 'q' to quit): ";
cin >> commands_str;
if (commands_str[0] == 'q') exit(0);
while (1) {
start = commands_str.find_first_of(digits,start);
if (start >= string::npos) break;
end = commands_str.find_first_not_of(digits,start);
commands_vec.push_back(atoi(commands_str.substr(start, end-start).c_str()));
start=end;
}
cout << "Initializing plot page ..." << endl;
savepng:
// Set page format
metafl((char*)displaytype.c_str());
setpag("da4l");
// Initialization
disini();
// Set Plot Parameters
pagera();
serif();
shdcha();
chncrv("color");
// Set plot axis system
axspos(450,1800);
axslen(2200,1200);
// Set plot titles
int thisplot;
int numtraces = commands_vec.size();
name("Time (in seconds)","x");
string longaxistext;
for (thisplot=0; thisplot < numtraces; thisplot++) {
longaxistext = longaxistext + " " + df.names[commands_vec[thisplot]];
}
name((char*)(longaxistext.c_str()),"y");
labdig(3,"xy");
ticks(10,"xy");
titlin("JSBSim plot",1);
string subtitle = "";
for (thisplot=0; thisplot < numtraces; thisplot++) {
if (thisplot == 0) subtitle = df.names[commands_vec[thisplot]];
else subtitle = subtitle + ", " + df.names[commands_vec[thisplot]];
}
subtitle = subtitle + string(" vs. Time");
titlin((char*)(subtitle.c_str()),3);
// Plot data
float *timarray = new float[df.GetEndIdx()-df.GetStartIdx()+1]; // new jsb 11/9
for (int pt=df.GetStartIdx(), pti=0; pt<=df.GetEndIdx(); pt++, pti++) {
timarray[pti] = df.Data[pt][0];
}
float axismax = df.GetAutoAxisMax(commands_vec[0]);
float axismin = df.GetAutoAxisMin(commands_vec[0]);
for (thisplot=1; thisplot < numtraces; thisplot++) {
axismax = axismax > df.GetAutoAxisMax(commands_vec[thisplot]) ? axismax : df.GetAutoAxisMax(commands_vec[thisplot]);
axismin = axismin < df.GetAutoAxisMin(commands_vec[thisplot]) ? axismin : df.GetAutoAxisMin(commands_vec[thisplot]);
}
float spread = axismax - axismin;
if (spread < 1.0) labdig(3,"y");
else if (spread < 10.0) labdig(2,"y");
else if (spread < 100.0) labdig(1,"y");
else labdig(0,"y");
if (spread > 1000.0) {
labdig(2,"y");
labels("fexp","y");
} else {
labels("float","y");
}
spread = df.Data[df.GetEndIdx()][0] - df.Data[df.GetStartIdx()][0];
if (spread < 1.0) labdig(3,"x");
else if (spread < 10.0) labdig(2,"x");
else if (spread < 100.0) labdig(1,"x");
else labdig(0,"x");
float fac = ((int)(spread + 0.5))/10.00;
if (spread > 1000.0) labels("fexp","x");
else labels("float","x");
graf( df.Data[df.GetStartIdx()][0], // starttime
df.Data[df.GetEndIdx()][0], // endtime
df.Data[df.GetStartIdx()][0], // starttime
fac,
axismin,
axismax,
axismin,
(axismax - axismin)/10.0);
title();
color("blue");
grid(1,1);
for (thisplot=0; thisplot < numtraces; thisplot++) {
float *datarray = new float[df.GetEndIdx()-df.GetStartIdx()+1];
for (int pt=df.GetStartIdx(), pti=0; pt<=df.GetEndIdx(); pt++, pti++) {
datarray[pti] = df.Data[pt][commands_vec[thisplot]];
}
color("red");
curve(timarray,datarray,df.GetEndIdx()-df.GetStartIdx()+1);
delete[] datarray;
}
char legendtext[numtraces*(namelen)];
color("blue");
legini(legendtext, numtraces, (namelen));
legtit("Legend");
for (thisplot=0; thisplot < numtraces; thisplot++) {
leglin(legendtext, (char*)df.names[commands_vec[thisplot]].c_str(), thisplot+1);
}
legend(legendtext, 3);
// Terminate
disfin();
// Request to save
if (displaytype == "CONS") {
cout << endl << "Save graph as a .png file [y|N]: ";
cin >> savefile;
if (savefile[0] == 'y') {
displaytype = "PNG";
pngFName_str = dwgtxt("Enter filename:",pngFName);
if (pngFName_str.find_first_of("png",0) == string::npos) {
pngFName_str = pngFName_str + ".png";
}
setfil((char*)pngFName_str.c_str());
goto savepng;
}
} else {
displaytype = "CONS";
}
cout << endl << "Create another plot? [Y|n]: ";
cin >> next;
if (next[0] == 'n') {
return EXIT_SUCCESS;
} else {
goto nextplot;
}
}
void plotdata(ifstream* datafile)
{
string data_str;
string Title, Y_Axis_Caption, X_Axis_Caption;
string Y_Variables;
string X_Variable;
string Ranges;
double xmin, ymin, xmax, ymax;
int delim;
vector <int> IDs;
while (!datafile->eof()) {
getline(*datafile, Title);
getline(*datafile, X_Axis_Caption);
getline(*datafile, Y_Axis_Caption);
getline(*datafile, Ranges);
getline(*datafile, X_Variable);
getline(*datafile, Y_Variables);
if (datafile->eof()) break;
if (Ranges.find("auto") != string::npos) { // autoscaling
xmin = xmax = ymin = ymax = 0.00;
cout << "Autoscaling ..." << endl;
} else {
delim = Ranges.find_first_of("|");
xmin = strtod(Ranges.substr(0, delim-1).c_str(), NULL);
cout << "Range: xmin=" << xmin;
Ranges = Ranges.substr(delim+1);
delim = Ranges.find_first_of("|");
ymin = strtod(Ranges.substr(0, delim-1).c_str(), NULL);
cout << " ymin=" << ymin;
Ranges = Ranges.substr(delim+1);
delim = Ranges.find_first_of("|");
xmax = strtod(Ranges.substr(0, delim-1).c_str(), NULL);
cout << " xmax=" << xmax;
Ranges = Ranges.substr(delim+1);
delim = Ranges.find_first_of("|");
ymax = strtod(Ranges.substr(0, delim-1).c_str(), NULL);
cout << " ymax=" << ymax;
}
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013 JCube001
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 "vector.h"
namespace fusion {
/**
* @brief Addition.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector to add.
* @return The sum of the vectors.
*/
inline Vector3 operator+(Vector3 lhs, const Vector3& rhs) {
lhs += rhs;
return lhs;
}
/**
* @brief Subtraction.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector to subtract by.
* @return The difference of the vectors.
*/
inline Vector3 operator-(Vector3 lhs, const Vector3& rhs) {
lhs -= rhs;
return lhs;
}
/**
* @brief Unary negation.
*
* @return The negated vector.
*/
inline Vector3 operator-(const Vector3& rhs) {
return Vector3(-rhs.x(), -rhs.y(), -rhs.z());
}
/**
* @brief Scalar multiplication.
*
* @param lhs The left hand side scalar to multiply by.
* @param rhs The right hand side vector.
* @return The product of the vector times the scalar.
*/
inline Vector3 operator*(float lhs, Vector3 rhs) {
rhs *= lhs;
return rhs;
}
/**
* @brief Scalar multiplication.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side scalar to multiply by.
* @return The product of the vector times the scalar.
*/
inline Vector3 operator*(Vector3 lhs, float rhs) {
lhs *= rhs;
return lhs;
}
/**
* @brief Cross product multiplication.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector to multiply by.
* @return The cross product of the vectors.
*/
inline Vector3 operator*(Vector3 lhs, const Vector3& rhs) {
lhs *= rhs;
return lhs;
}
/**
* @brief Scalar division.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side scalar value to divide by.
* @return The quotient of the vector divided by the scalar.
*/
inline Vector3 operator/(Vector3 lhs, float rhs) {
lhs /= rhs;
return lhs;
}
/**
* @brief Equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if both vectors are equal, otherwise false.
*/
inline bool operator==(const Vector3& lhs, const Vector3& rhs) {
return ((lhs.x() == rhs.x()) &&
(lhs.y() == rhs.y()) &&
(lhs.z() == rhs.z()));
}
/**
* @brief Not equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if both vectors are not equal, otherwise false.
*/
inline bool operator!=(const Vector3& lhs, const Vector3& rhs) {
return !operator==(lhs, rhs);
}
/**
* @brief Less than.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is less than the right hand side
* norm, otherwise false.
*/
inline bool operator<(const Vector3& lhs, const Vector3& rhs) {
return (lhs.norm() < rhs.norm());
}
/**
* @brief Greater than.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is greater than the right hand side
* norm, otherwise false.
*/
inline bool operator>(const Vector3& lhs, const Vector3& rhs) {
return operator<(rhs, lhs);
}
/**
* @brief Less than or equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is less than or equal to the right
* hand side norm, otherwise false.
*/
inline bool operator<=(const Vector3& lhs, const Vector3& rhs) {
return !operator>(lhs, rhs);
}
/**
* @brief Greater than or equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is greater than or equal to the
* right hand side norm, otherwise false.
*/
inline bool operator>=(const Vector3& lhs, const Vector3& rhs) {
return !operator<(lhs, rhs);
}
} // namespace fusion
<commit_msg>Forgot a doc string<commit_after>/*******************************************************************************
The MIT License (MIT)
Copyright (c) 2013 JCube001
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 "vector.h"
namespace fusion {
/**
* @brief Addition.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector to add.
* @return The sum of the vectors.
*/
inline Vector3 operator+(Vector3 lhs, const Vector3& rhs) {
lhs += rhs;
return lhs;
}
/**
* @brief Subtraction.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector to subtract by.
* @return The difference of the vectors.
*/
inline Vector3 operator-(Vector3 lhs, const Vector3& rhs) {
lhs -= rhs;
return lhs;
}
/**
* @brief Unary negation.
*
* @param rhs The vector to negate.
* @return The negated vector.
*/
inline Vector3 operator-(const Vector3& rhs) {
return Vector3(-rhs.x(), -rhs.y(), -rhs.z());
}
/**
* @brief Scalar multiplication.
*
* @param lhs The left hand side scalar to multiply by.
* @param rhs The right hand side vector.
* @return The product of the vector times the scalar.
*/
inline Vector3 operator*(float lhs, Vector3 rhs) {
rhs *= lhs;
return rhs;
}
/**
* @brief Scalar multiplication.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side scalar to multiply by.
* @return The product of the vector times the scalar.
*/
inline Vector3 operator*(Vector3 lhs, float rhs) {
lhs *= rhs;
return lhs;
}
/**
* @brief Cross product multiplication.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector to multiply by.
* @return The cross product of the vectors.
*/
inline Vector3 operator*(Vector3 lhs, const Vector3& rhs) {
lhs *= rhs;
return lhs;
}
/**
* @brief Scalar division.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side scalar value to divide by.
* @return The quotient of the vector divided by the scalar.
*/
inline Vector3 operator/(Vector3 lhs, float rhs) {
lhs /= rhs;
return lhs;
}
/**
* @brief Equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if both vectors are equal, otherwise false.
*/
inline bool operator==(const Vector3& lhs, const Vector3& rhs) {
return ((lhs.x() == rhs.x()) &&
(lhs.y() == rhs.y()) &&
(lhs.z() == rhs.z()));
}
/**
* @brief Not equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if both vectors are not equal, otherwise false.
*/
inline bool operator!=(const Vector3& lhs, const Vector3& rhs) {
return !operator==(lhs, rhs);
}
/**
* @brief Less than.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is less than the right hand side
* norm, otherwise false.
*/
inline bool operator<(const Vector3& lhs, const Vector3& rhs) {
return (lhs.norm() < rhs.norm());
}
/**
* @brief Greater than.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is greater than the right hand side
* norm, otherwise false.
*/
inline bool operator>(const Vector3& lhs, const Vector3& rhs) {
return operator<(rhs, lhs);
}
/**
* @brief Less than or equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is less than or equal to the right
* hand side norm, otherwise false.
*/
inline bool operator<=(const Vector3& lhs, const Vector3& rhs) {
return !operator>(lhs, rhs);
}
/**
* @brief Greater than or equal to.
*
* @param lhs The left hand side vector.
* @param rhs The right hand side vector.
* @return True if the left hand side norm is greater than or equal to the
* right hand side norm, otherwise false.
*/
inline bool operator>=(const Vector3& lhs, const Vector3& rhs) {
return !operator<(lhs, rhs);
}
} // namespace fusion
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3223
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3223 to 3224<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3224
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3212
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3212 to 3213<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3213
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3345
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3345 to 3346<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3346
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3445
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from 3445 to 3446<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_
#include "utils/macros.hpp"
#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif // AMD_PLATFORM_NAME
#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3446
#endif // AMD_PLATFORM_BUILD_NUMBER
#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif // AMD_PLATFORM_REVISION_NUMBER
#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif // AMD_PLATFORM_RELEASE_INFO
#define AMD_BUILD_STRING \
XSTR(AMD_PLATFORM_BUILD_NUMBER) \
"." XSTR(AMD_PLATFORM_REVISION_NUMBER)
#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO \
"AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY( \
"." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif // ATI_PLATFORM_INFO
#endif // VERSIONS_HPP_
<|endoftext|> |
<commit_before>/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/identity-management/auth/STSProfileCredentialsProvider.h>
#include <aws/sts/model/AssumeRoleRequest.h>
#include <aws/sts/STSClient.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/utils/Outcome.h>
#include <utility>
using namespace Aws;
using namespace Aws::Auth;
constexpr char CLASS_TAG[] = "STSProfileCredentialsProvider";
STSProfileCredentialsProvider::STSProfileCredentialsProvider()
: STSProfileCredentialsProvider(GetConfigProfileName(), std::chrono::minutes(60)/*duration*/, nullptr/*stsClientFactory*/)
{
}
STSProfileCredentialsProvider::STSProfileCredentialsProvider(const Aws::String& profileName, std::chrono::minutes duration)
: STSProfileCredentialsProvider(profileName, duration, nullptr/*stsClientFactory*/)
{
}
STSProfileCredentialsProvider::STSProfileCredentialsProvider(const Aws::String& profileName, std::chrono::minutes duration, const std::function<Aws::STS::STSClient*(const AWSCredentials&)> &stsClientFactory)
: m_profileName(profileName),
m_configFileLoader(GetConfigProfileFilename()),
m_duration(duration),
m_reloadFrequency(std::chrono::minutes(std::max(int64_t(5), static_cast<int64_t>(duration.count()))) - std::chrono::minutes(5)),
m_stsClientFactory(stsClientFactory)
{
}
AWSCredentials STSProfileCredentialsProvider::GetAWSCredentials()
{
RefreshIfExpired();
Utils::Threading::ReaderLockGuard guard(m_reloadLock);
return m_credentials;
}
void STSProfileCredentialsProvider::RefreshIfExpired()
{
Utils::Threading::ReaderLockGuard guard(m_reloadLock);
if (!IsTimeToRefresh(static_cast<long>(m_reloadFrequency.count())) || !m_credentials.IsExpiredOrEmpty())
{
return;
}
guard.UpgradeToWriterLock();
if (!IsTimeToRefresh(static_cast<long>(m_reloadFrequency.count())) || !m_credentials.IsExpiredOrEmpty()) // double-checked lock to avoid refreshing twice
{
return;
}
Reload();
}
enum class ProfileState
{
Invalid,
Static,
Process,
SourceProfile,
SelfReferencing, // special case of SourceProfile.
};
/*
* A valid profile can be in one of the following states. Any other state is considered invalid.
+---------+-----------+-----------+--------------+
| | | | |
| Role | Source | Process | Static |
| ARN | Profile | | Credentials |
+------------------------------------------------+
| | | | |
| false | false | false | TRUE |
| | | | |
| false | false | TRUE | false |
| | | | |
| TRUE | TRUE | false | false |
| | | | |
| TRUE | TRUE | false | TRUE |
| | | | |
+---------+-----------+-----------+--------------+
*/
static ProfileState CheckProfile(const Aws::Config::Profile& profile, bool topLevelProfile)
{
constexpr int STATIC_CREDENTIALS = 1;
constexpr int PROCESS_CREDENTIALS = 2;
constexpr int SOURCE_PROFILE = 4;
constexpr int ROLE_ARN = 8;
int state = 0;
if (!profile.GetCredentials().IsExpiredOrEmpty())
{
state += STATIC_CREDENTIALS;
}
if (!profile.GetCredentialProcess().empty())
{
state += PROCESS_CREDENTIALS;
}
if (!profile.GetSourceProfile().empty())
{
state += SOURCE_PROFILE;
}
if (!profile.GetRoleArn().empty())
{
state += ROLE_ARN;
}
if (topLevelProfile)
{
switch(state)
{
case 1:
return ProfileState::Static;
case 2:
return ProfileState::Process;
case 12: // just source profile && role arn available
return ProfileState::SourceProfile;
case 13: // static creds && source profile && role arn
if (profile.GetName() == profile.GetSourceProfile())
{
return ProfileState::SelfReferencing;
}
// source-profile over-rule static credentials in top-level profiles (except when self-referencing)
return ProfileState::SourceProfile;
default:
// All other cases are considered malformed configuration.
return ProfileState::Invalid;
}
}
else
{
switch(state)
{
case 1:
return ProfileState::Static;
case 2:
return ProfileState::Process;
case 12: // just source profile && role arn available
return ProfileState::SourceProfile;
case 13: // static creds && source profile && role arn
if (profile.GetName() == profile.GetSourceProfile())
{
return ProfileState::SelfReferencing;
}
return ProfileState::Static; // static credentials over-rule source-profile (except when self-referencing)
default:
// All other cases are considered malformed configuration.
return ProfileState::Invalid;
}
}
}
void STSProfileCredentialsProvider::Reload()
{
m_configFileLoader.Load();
// make a copy of the profiles map to be able to set credentials on the individual profiles when assuming role
auto loadedProfiles = m_configFileLoader.GetProfiles();
auto profileIt = loadedProfiles.find(m_profileName);
if(profileIt == loadedProfiles.end())
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << m_profileName <<" was not found in the shared configuration file.");
m_credentials = {};
return;
}
ProfileState profileState = CheckProfile(profileIt->second, true/*topLevelProfile*/);
if (profileState == ProfileState::Static)
{
m_credentials = profileIt->second.GetCredentials();
AWSCredentialsProvider::Reload();
return;
}
if (profileState == ProfileState::Process)
{
const auto& creds = GetCredentialsFromProcess(profileIt->second.GetCredentialProcess());
if (!creds.IsExpiredOrEmpty())
{
m_credentials = creds;
AWSCredentialsProvider::Reload();
}
return;
}
if (profileState == ProfileState::Invalid)
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << profileIt->second.GetName() << " is invalid. Check its configuration.");
m_credentials = {};
return;
}
if (profileState == ProfileState::SourceProfile)
{
// A top level profile with a 'SourceProfile' state (determined by CheckProfile rules) means that its static
// credentials will be ignored. So, it's ok to clear them out here to simplify the logic in the chaining loop
// below.
profileIt->second.SetCredentials({});
}
AWS_LOGSTREAM_INFO(CLASS_TAG, "Profile " << profileIt->second.GetName()
<< " has a role ARN. Attempting to load its source credentials from profile "
<< profileIt->second.GetSourceProfile());
Aws::Vector<Config::AWSProfileConfigLoader::ProfilesContainer::iterator> sourceProfiles;
Aws::Set<Aws::String> visitedProfiles;
auto currentProfile = profileIt;
sourceProfiles.push_back(currentProfile);
// build the chain (DAG)
while(!currentProfile->second.GetSourceProfile().empty())
{
ProfileState currentProfileState = CheckProfile(currentProfile->second, false /*topLevelProfile*/);
auto currentProfileName = currentProfile->second.GetName();
if (currentProfileState == ProfileState::Invalid)
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << profileIt->second.GetName() << " is invalid. Check its configuration.");
m_credentials = {};
return;
}
// terminate the chain as soon as we hit a profile with either static credentials or credential process
if (currentProfileState == ProfileState::Static || currentProfileState == ProfileState::Process)
{
break;
}
if (currentProfileState == ProfileState::SelfReferencing)
{
sourceProfiles.push_back(currentProfile);
break;
}
// check if we have a circular reference in the graph.
if (visitedProfiles.find(currentProfileName) != visitedProfiles.end())
{
// TODO: print the whole DAG for better debugging
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << currentProfileName << " has a circular reference. Aborting.");
m_credentials = {};
return;
}
visitedProfiles.emplace(currentProfileName);
const auto it = loadedProfiles.find(currentProfile->second.GetSourceProfile());
if(it == loadedProfiles.end())
{
// TODO: print the whole DAG for better debugging
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << currentProfileName << " has an invalid source profile " << currentProfile->second.GetSourceProfile());
m_credentials = {};
return;
}
currentProfile = it;
sourceProfiles.push_back(currentProfile);
}
// The last profile added to the stack is not checked. Check it now.
if (!sourceProfiles.empty())
{
if (CheckProfile(sourceProfiles.back()->second, false /*topLevelProfile*/) == ProfileState::Invalid)
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << sourceProfiles.back()->second.GetName() << " is invalid. Check its configuration.");
m_credentials = {};
return;
}
}
while (sourceProfiles.size() > 1)
{
const auto profile = sourceProfiles.back()->second;
sourceProfiles.pop_back();
AWSCredentials stsCreds;
if (profile.GetCredentialProcess().empty())
{
assert(!profile.GetCredentials().IsEmpty());
stsCreds = profile.GetCredentials();
}
else
{
stsCreds = GetCredentialsFromProcess(profile.GetCredentialProcess());
}
// get the role arn from the profile at the top of the stack (which hasn't been popped out yet)
const auto arn = sourceProfiles.back()->second.GetRoleArn();
const auto& assumedCreds = GetCredentialsFromSTS(stsCreds, arn);
sourceProfiles.back()->second.SetCredentials(assumedCreds);
}
if (!sourceProfiles.empty())
{
assert(profileIt == sourceProfiles.back());
assert(!profileIt->second.GetCredentials().IsEmpty());
}
m_credentials = profileIt->second.GetCredentials();
AWSCredentialsProvider::Reload();
}
AWSCredentials STSProfileCredentialsProvider::GetCredentialsFromSTSInternal(const Aws::String& roleArn, Aws::STS::STSClient* client)
{
using namespace Aws::STS::Model;
AssumeRoleRequest assumeRoleRequest;
assumeRoleRequest
.WithRoleArn(roleArn)
.WithDurationSeconds(static_cast<int>(std::chrono::seconds(m_duration).count()));
auto outcome = client->AssumeRole(assumeRoleRequest);
if (outcome.IsSuccess())
{
const auto& modelCredentials = outcome.GetResult().GetCredentials();
return {modelCredentials.GetAccessKeyId(),
modelCredentials.GetSecretAccessKey(),
modelCredentials.GetSessionToken(),
modelCredentials.GetExpiration()};
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Failed to assume role " << roleArn);
}
return {};
}
AWSCredentials STSProfileCredentialsProvider::GetCredentialsFromSTS(const AWSCredentials& credentials, const Aws::String& roleArn)
{
using namespace Aws::STS::Model;
if (m_stsClientFactory) {
return GetCredentialsFromSTSInternal(roleArn, m_stsClientFactory(credentials));
}
Aws::STS::STSClient stsClient {credentials};
return GetCredentialsFromSTSInternal(roleArn, &stsClient);
}
<commit_msg>Provide role session name in STSProfileCredentialsProvider::GetCredentialsFromSTSInternal()<commit_after>/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/identity-management/auth/STSProfileCredentialsProvider.h>
#include <aws/sts/model/AssumeRoleRequest.h>
#include <aws/sts/STSClient.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/core/utils/Outcome.h>
#include <aws/core/utils/UUID.h>
#include <utility>
using namespace Aws;
using namespace Aws::Auth;
constexpr char CLASS_TAG[] = "STSProfileCredentialsProvider";
STSProfileCredentialsProvider::STSProfileCredentialsProvider()
: STSProfileCredentialsProvider(GetConfigProfileName(), std::chrono::minutes(60)/*duration*/, nullptr/*stsClientFactory*/)
{
}
STSProfileCredentialsProvider::STSProfileCredentialsProvider(const Aws::String& profileName, std::chrono::minutes duration)
: STSProfileCredentialsProvider(profileName, duration, nullptr/*stsClientFactory*/)
{
}
STSProfileCredentialsProvider::STSProfileCredentialsProvider(const Aws::String& profileName, std::chrono::minutes duration, const std::function<Aws::STS::STSClient*(const AWSCredentials&)> &stsClientFactory)
: m_profileName(profileName),
m_configFileLoader(GetConfigProfileFilename()),
m_duration(duration),
m_reloadFrequency(std::chrono::minutes(std::max(int64_t(5), static_cast<int64_t>(duration.count()))) - std::chrono::minutes(5)),
m_stsClientFactory(stsClientFactory)
{
}
AWSCredentials STSProfileCredentialsProvider::GetAWSCredentials()
{
RefreshIfExpired();
Utils::Threading::ReaderLockGuard guard(m_reloadLock);
return m_credentials;
}
void STSProfileCredentialsProvider::RefreshIfExpired()
{
Utils::Threading::ReaderLockGuard guard(m_reloadLock);
if (!IsTimeToRefresh(static_cast<long>(m_reloadFrequency.count())) || !m_credentials.IsExpiredOrEmpty())
{
return;
}
guard.UpgradeToWriterLock();
if (!IsTimeToRefresh(static_cast<long>(m_reloadFrequency.count())) || !m_credentials.IsExpiredOrEmpty()) // double-checked lock to avoid refreshing twice
{
return;
}
Reload();
}
enum class ProfileState
{
Invalid,
Static,
Process,
SourceProfile,
SelfReferencing, // special case of SourceProfile.
};
/*
* A valid profile can be in one of the following states. Any other state is considered invalid.
+---------+-----------+-----------+--------------+
| | | | |
| Role | Source | Process | Static |
| ARN | Profile | | Credentials |
+------------------------------------------------+
| | | | |
| false | false | false | TRUE |
| | | | |
| false | false | TRUE | false |
| | | | |
| TRUE | TRUE | false | false |
| | | | |
| TRUE | TRUE | false | TRUE |
| | | | |
+---------+-----------+-----------+--------------+
*/
static ProfileState CheckProfile(const Aws::Config::Profile& profile, bool topLevelProfile)
{
constexpr int STATIC_CREDENTIALS = 1;
constexpr int PROCESS_CREDENTIALS = 2;
constexpr int SOURCE_PROFILE = 4;
constexpr int ROLE_ARN = 8;
int state = 0;
if (!profile.GetCredentials().IsExpiredOrEmpty())
{
state += STATIC_CREDENTIALS;
}
if (!profile.GetCredentialProcess().empty())
{
state += PROCESS_CREDENTIALS;
}
if (!profile.GetSourceProfile().empty())
{
state += SOURCE_PROFILE;
}
if (!profile.GetRoleArn().empty())
{
state += ROLE_ARN;
}
if (topLevelProfile)
{
switch(state)
{
case 1:
return ProfileState::Static;
case 2:
return ProfileState::Process;
case 12: // just source profile && role arn available
return ProfileState::SourceProfile;
case 13: // static creds && source profile && role arn
if (profile.GetName() == profile.GetSourceProfile())
{
return ProfileState::SelfReferencing;
}
// source-profile over-rule static credentials in top-level profiles (except when self-referencing)
return ProfileState::SourceProfile;
default:
// All other cases are considered malformed configuration.
return ProfileState::Invalid;
}
}
else
{
switch(state)
{
case 1:
return ProfileState::Static;
case 2:
return ProfileState::Process;
case 12: // just source profile && role arn available
return ProfileState::SourceProfile;
case 13: // static creds && source profile && role arn
if (profile.GetName() == profile.GetSourceProfile())
{
return ProfileState::SelfReferencing;
}
return ProfileState::Static; // static credentials over-rule source-profile (except when self-referencing)
default:
// All other cases are considered malformed configuration.
return ProfileState::Invalid;
}
}
}
void STSProfileCredentialsProvider::Reload()
{
m_configFileLoader.Load();
// make a copy of the profiles map to be able to set credentials on the individual profiles when assuming role
auto loadedProfiles = m_configFileLoader.GetProfiles();
auto profileIt = loadedProfiles.find(m_profileName);
if(profileIt == loadedProfiles.end())
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << m_profileName <<" was not found in the shared configuration file.");
m_credentials = {};
return;
}
ProfileState profileState = CheckProfile(profileIt->second, true/*topLevelProfile*/);
if (profileState == ProfileState::Static)
{
m_credentials = profileIt->second.GetCredentials();
AWSCredentialsProvider::Reload();
return;
}
if (profileState == ProfileState::Process)
{
const auto& creds = GetCredentialsFromProcess(profileIt->second.GetCredentialProcess());
if (!creds.IsExpiredOrEmpty())
{
m_credentials = creds;
AWSCredentialsProvider::Reload();
}
return;
}
if (profileState == ProfileState::Invalid)
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << profileIt->second.GetName() << " is invalid. Check its configuration.");
m_credentials = {};
return;
}
if (profileState == ProfileState::SourceProfile)
{
// A top level profile with a 'SourceProfile' state (determined by CheckProfile rules) means that its static
// credentials will be ignored. So, it's ok to clear them out here to simplify the logic in the chaining loop
// below.
profileIt->second.SetCredentials({});
}
AWS_LOGSTREAM_INFO(CLASS_TAG, "Profile " << profileIt->second.GetName()
<< " has a role ARN. Attempting to load its source credentials from profile "
<< profileIt->second.GetSourceProfile());
Aws::Vector<Config::AWSProfileConfigLoader::ProfilesContainer::iterator> sourceProfiles;
Aws::Set<Aws::String> visitedProfiles;
auto currentProfile = profileIt;
sourceProfiles.push_back(currentProfile);
// build the chain (DAG)
while(!currentProfile->second.GetSourceProfile().empty())
{
ProfileState currentProfileState = CheckProfile(currentProfile->second, false /*topLevelProfile*/);
auto currentProfileName = currentProfile->second.GetName();
if (currentProfileState == ProfileState::Invalid)
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << profileIt->second.GetName() << " is invalid. Check its configuration.");
m_credentials = {};
return;
}
// terminate the chain as soon as we hit a profile with either static credentials or credential process
if (currentProfileState == ProfileState::Static || currentProfileState == ProfileState::Process)
{
break;
}
if (currentProfileState == ProfileState::SelfReferencing)
{
sourceProfiles.push_back(currentProfile);
break;
}
// check if we have a circular reference in the graph.
if (visitedProfiles.find(currentProfileName) != visitedProfiles.end())
{
// TODO: print the whole DAG for better debugging
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << currentProfileName << " has a circular reference. Aborting.");
m_credentials = {};
return;
}
visitedProfiles.emplace(currentProfileName);
const auto it = loadedProfiles.find(currentProfile->second.GetSourceProfile());
if(it == loadedProfiles.end())
{
// TODO: print the whole DAG for better debugging
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << currentProfileName << " has an invalid source profile " << currentProfile->second.GetSourceProfile());
m_credentials = {};
return;
}
currentProfile = it;
sourceProfiles.push_back(currentProfile);
}
// The last profile added to the stack is not checked. Check it now.
if (!sourceProfiles.empty())
{
if (CheckProfile(sourceProfiles.back()->second, false /*topLevelProfile*/) == ProfileState::Invalid)
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Profile " << sourceProfiles.back()->second.GetName() << " is invalid. Check its configuration.");
m_credentials = {};
return;
}
}
while (sourceProfiles.size() > 1)
{
const auto profile = sourceProfiles.back()->second;
sourceProfiles.pop_back();
AWSCredentials stsCreds;
if (profile.GetCredentialProcess().empty())
{
assert(!profile.GetCredentials().IsEmpty());
stsCreds = profile.GetCredentials();
}
else
{
stsCreds = GetCredentialsFromProcess(profile.GetCredentialProcess());
}
// get the role arn from the profile at the top of the stack (which hasn't been popped out yet)
const auto arn = sourceProfiles.back()->second.GetRoleArn();
const auto& assumedCreds = GetCredentialsFromSTS(stsCreds, arn);
sourceProfiles.back()->second.SetCredentials(assumedCreds);
}
if (!sourceProfiles.empty())
{
assert(profileIt == sourceProfiles.back());
assert(!profileIt->second.GetCredentials().IsEmpty());
}
m_credentials = profileIt->second.GetCredentials();
AWSCredentialsProvider::Reload();
}
AWSCredentials STSProfileCredentialsProvider::GetCredentialsFromSTSInternal(const Aws::String& roleArn, Aws::STS::STSClient* client)
{
using namespace Aws::STS::Model;
AssumeRoleRequest assumeRoleRequest;
assumeRoleRequest
.WithRoleArn(roleArn)
.WithRoleSessionName(Aws::Utils::UUID::RandomUUID())
.WithDurationSeconds(static_cast<int>(std::chrono::seconds(m_duration).count()));
auto outcome = client->AssumeRole(assumeRoleRequest);
if (outcome.IsSuccess())
{
const auto& modelCredentials = outcome.GetResult().GetCredentials();
return {modelCredentials.GetAccessKeyId(),
modelCredentials.GetSecretAccessKey(),
modelCredentials.GetSessionToken(),
modelCredentials.GetExpiration()};
}
else
{
AWS_LOGSTREAM_ERROR(CLASS_TAG, "Failed to assume role " << roleArn);
}
return {};
}
AWSCredentials STSProfileCredentialsProvider::GetCredentialsFromSTS(const AWSCredentials& credentials, const Aws::String& roleArn)
{
using namespace Aws::STS::Model;
if (m_stsClientFactory) {
return GetCredentialsFromSTSInternal(roleArn, m_stsClientFactory(credentials));
}
Aws::STS::STSClient stsClient {credentials};
return GetCredentialsFromSTSInternal(roleArn, &stsClient);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE = 0,
HEADLESS,
REPORT,
UPDATE,
// exit status codes
ES_PASS = 0,
ES_FATAL,
ES_FAIL,
ES_INVALID,
ES_NA,
ES_SKIP,
ES_UNCERTAIN
};
const char* StatusStrings[] = {
"pass",
"fatal",
"fail",
"invalid",
"?",
"skip",
"uncertain",
};
struct ForkStatus {
pid_t pid;
std::string url;
int code;
public:
ForkStatus() : pid(-1), code(-1) {}
};
size_t forkMax = 1;
size_t forkTop = 0;
size_t forkCount = 0;
std::vector<ForkStatus> forkStates(1);
size_t uncertainCount = 0;
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
exit(EXIT_FAILURE);
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
return result;
}
int reduce(std::ostream& report, int option = 0)
{
int count;
int op = (forkCount < forkMax) ? option : 0;
for (count = 0; count < forkCount; ++count) {
int status;
pid_t pid = waitpid(-1, &status, op);
if (pid == 0)
break;
for (int i = 0; i < forkCount; ++i) {
auto s = &forkStates[(forkTop + i) % forkMax];
if (s->pid == pid) {
s->code = WIFEXITED(status) ? WEXITSTATUS(status) : ES_FATAL;
if (i == 0)
op = option;
break;
}
}
}
if (0 < count) {
for (count = 0; count < forkMax; ++count) {
auto s = &forkStates[(forkTop + count) % forkMax];
if (s->code == -1)
break;
if (s->code == ES_UNCERTAIN)
++uncertainCount;
if (s->code != ES_NA)
std::cout << s->url << '\t' << StatusStrings[s->code] << '\n';
report << s->url << '\t' << StatusStrings[s->code] << '\n';
s->code = -1;
}
assert(count <= forkCount);
forkTop += count;
forkTop %= forkMax;
forkCount -= count;
}
return count;
}
void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
assert(forkCount < forkMax);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
exit(EXIT_FAILURE);
}
if (pid == 0) {
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
int status = ES_NA;
if (!result.compare(0, 4, "pass"))
status = ES_PASS;
else if (!result.compare(0, 5, "fatal"))
status = ES_FATAL;
else if (!result.compare(0, 4, "fail"))
status = ES_FAIL;
else if (!result.compare(0, 7, "invalid"))
status = ES_INVALID;
else if (!result.compare(0, 4, "skip"))
status = ES_SKIP;
else if (!result.compare(0, 9, "uncertain"))
status = ES_UNCERTAIN;
exit(status);
} else {
auto s = &forkStates[(forkTop + forkCount) % forkMax];
s->url = url;
s->pid = pid;
++forkCount;
reduce(report, WNOHANG);
}
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
case 'j':
forkMax = strtoul(argv[argi] + 2, 0, 10);
if (forkMax == 0)
forkMax = 1;
forkStates.resize(forkMax);
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty())
continue;
if (line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
reduce(report);
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
switch (mode) {
case HEADLESS:
case UPDATE:
map(report, mode, argc - argi, args, url, userStyle, testFonts, timeout);
break;
default:
result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout);
if (result != "undo")
report << url << '\t' << result << '\n';
break;
}
}
if (mode == HEADLESS || mode == UPDATE)
reduce(report);
report.close();
return (0 < uncertainCount) ? EXIT_FAILURE : EXIT_SUCCESS;
}
<commit_msg>(harness) : Change the base URL to http://localhost/suites/css2.1/20110323/<commit_after>/*
* Copyright 2011, 2012 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE = 0,
HEADLESS,
REPORT,
UPDATE,
// exit status codes
ES_PASS = 0,
ES_FATAL,
ES_FAIL,
ES_INVALID,
ES_NA,
ES_SKIP,
ES_UNCERTAIN
};
const char* StatusStrings[] = {
"pass",
"fatal",
"fail",
"invalid",
"?",
"skip",
"uncertain",
};
struct ForkStatus {
pid_t pid;
std::string url;
int code;
public:
ForkStatus() : pid(-1), code(-1) {}
};
size_t forkMax = 1;
size_t forkTop = 0;
size_t forkCount = 0;
std::vector<ForkStatus> forkStates(1);
size_t uncertainCount = 0;
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
char testfontsOption[] = "-testfonts";
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] = testfontsOption;
url = "http://localhost/suites/css2.1/20110323/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
exit(EXIT_FAILURE);
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
return result;
}
int reduce(std::ostream& report, int option = 0)
{
size_t count;
int op = (forkCount < forkMax) ? option : 0;
for (count = 0; count < forkCount; ++count) {
int status;
pid_t pid = waitpid(-1, &status, op);
if (pid == 0)
break;
for (size_t i = 0; i < forkCount; ++i) {
auto s = &forkStates[(forkTop + i) % forkMax];
if (s->pid == pid) {
s->code = WIFEXITED(status) ? WEXITSTATUS(status) : ES_FATAL;
if (i == 0)
op = option;
break;
}
}
}
if (0 < count) {
for (count = 0; count < forkMax; ++count) {
auto s = &forkStates[(forkTop + count) % forkMax];
if (s->code == -1)
break;
if (s->code == ES_UNCERTAIN)
++uncertainCount;
if (s->code != ES_NA)
std::cout << s->url << '\t' << StatusStrings[s->code] << '\n';
report << s->url << '\t' << StatusStrings[s->code] << '\n';
s->code = -1;
}
assert(count <= forkCount);
forkTop += count;
forkTop %= forkMax;
forkCount -= count;
}
return count;
}
void map(std::ostream& report, int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
assert(forkCount < forkMax);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
exit(EXIT_FAILURE);
}
if (pid == 0) {
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
int status = ES_NA;
if (!result.compare(0, 4, "pass"))
status = ES_PASS;
else if (!result.compare(0, 5, "fatal"))
status = ES_FATAL;
else if (!result.compare(0, 4, "fail"))
status = ES_FAIL;
else if (!result.compare(0, 7, "invalid"))
status = ES_INVALID;
else if (!result.compare(0, 4, "skip"))
status = ES_SKIP;
else if (!result.compare(0, 9, "uncertain"))
status = ES_UNCERTAIN;
exit(status);
} else {
auto s = &forkStates[(forkTop + forkCount) % forkMax];
s->url = url;
s->pid = pid;
++forkCount;
reduce(report, WNOHANG);
}
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
case 'j':
forkMax = strtoul(argv[argi] + 2, 0, 10);
if (forkMax == 0)
forkMax = 1;
forkStates.resize(forkMax);
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty())
continue;
if (line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
reduce(report);
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
switch (mode) {
case HEADLESS:
case UPDATE:
map(report, mode, argc - argi, args, url, userStyle, testFonts, timeout);
break;
default:
result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout);
if (result != "undo")
report << url << '\t' << result << '\n';
break;
}
}
if (mode == HEADLESS || mode == UPDATE)
reduce(report);
report.close();
return (0 < uncertainCount) ? EXIT_FAILURE : EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*** repositionDefExpressions.cpp
***
*** This pass and function moves around the defPoints for variables to
*** where the first use is.
***
*** The algorithm: look at a function and collect all the variables. Push
*** all the variables down into a block if the variable isn't used at the
*** top level nor is it used in a sibling block. Repeat for each block and
*** sub-block.
***
*** vars = collectVarsInFun(f);
*** for each var in Vars
*** current_block = f->body;
*** while (true)
*** if isTopDecl(current_block, var)
*** declare var in current_block
*** break
*** else
*** childBlocks = getChildBlocks(current_block)
*** if countBlocks(childBlocks, var) > 1
*** declare var in current_block
*** break
*** else
*** current_block = getUniqueBlock(childBlocks, var)
***
*** Problem: without live variable analysis, could define variable inside
*** block where variable is live going in, thus writing over it
*** on each iteration of loop
***/
#include "astutil.h"
#include "stmt.h"
#include "symbol.h"
// Gets a total on the number of blocks within some vector of blocks (likely
// captured via getChildBlocks) which contain var. Useful in determining if
// a variable is used in multiple locations.
int countBlocks(Vec<BlockStmt*>& check_vec_block, VarSymbol* var) {
int answer = 0;
forv_Vec(BlockStmt*, block, check_vec_block) {
Vec<SymExpr*> symbols;
collectSymExprs(block, symbols);
forv_Vec(SymExpr, symbol, symbols) {
if (toVarSymbol(symbol->var) == var) {
answer++;
break;
}
}
}
return answer;
}
// Gets a vector of the block statements in a given block of code. For
// example, if some code contains 2 declarations, an if statement, and
// a while loop, the resulting vector would have two elements: the if
// and the while.
Vec<BlockStmt*> getChildBlocks(BlockStmt* check_block) {
Vec<BlockStmt*> answer;
for_alist(expr, check_block->body) {
if (BlockStmt* block = toBlockStmt(expr)) {
answer.add(block);
} else {
if (CondStmt* cond = toCondStmt(expr)) {
if (BlockStmt* thenclause = toBlockStmt(cond->thenStmt)) {
answer.add(thenclause);
}
if (BlockStmt* elseclause = toBlockStmt(cond->elseStmt)) {
answer.add(elseclause);
}
}
}
}
return answer;
}
// Returns the first block statement within a vector of blocks that
// contains a variable.
BlockStmt* getUniqueBlock(Vec<BlockStmt*>& check_vec_block, VarSymbol* var) {
forv_Vec(BlockStmt*, block, check_vec_block) {
Vec<SymExpr*> symbols;
collectSymExprs(block, symbols);
forv_Vec(SymExpr, symbol, symbols) {
if (symbol->var == var) {
return block;
}
}
}
return NULL;
}
// Returns true if a variable appears at the top level of a block. For
// example, if some code contains 2 declarations, one for x and another
// for y, an if statement, and a while loop (which contains z), this
// function would return true if called with x, but false if called with
// z.
bool isTopDecl(BlockStmt* check_block, VarSymbol* var) {
for_alist(expr, check_block->body) {
Vec<SymExpr*> syms;
if ( (!(toBlockStmt(expr))) &&
(!(toCondStmt(expr))) ) {
collectSymExprs(expr, syms);
} else if (BlockStmt* new_block = toBlockStmt(expr)) {
if (new_block->blockInfo) {
collectSymExprs(new_block->blockInfo, syms);
}
} else if (CondStmt* new_cond = toCondStmt(expr)) {
collectSymExprs(new_cond->condExpr, syms);
}
forv_Vec(SymExpr, sym, syms) {
if (sym->var == var)
return true;
}
}
return false;
}
void repositionDefExpressions(void) {
if (fNoRepositionDefExpr) return;
forv_Vec(FnSymbol, fn, gFnSymbols) {
Vec<DefExpr*> vars;
Vec<DefExpr*> defs;
// Collect all the variables defined in function
collectDefExprs(fn, defs);
forv_Vec(DefExpr*, def, defs) {
if (isVarSymbol(def->sym)) {
vars.add(def);
}
}
forv_Vec(DefExpr*, def, vars) {
BlockStmt* current_block = fn->body;
VarSymbol* var = toVarSymbol(def->sym);
while (true) {
if (isTopDecl(current_block, var)) {
// declare var here
if (!toTypeSymbol(def->sym)) {
current_block->insertAtHead(def->remove());
}
break;
} else {
Vec<BlockStmt*> childBlocks = getChildBlocks(current_block);
if (countBlocks(childBlocks, var) > 1) {
// declare var here
if (!toTypeSymbol(def->sym)) {
current_block->insertAtHead(def->remove());
}
break;
} else {
current_block = getUniqueBlock(childBlocks, var);
if (!current_block) break;
}
}
}
}
}
}
<commit_msg><commit_after>/*** repositionDefExpressions.cpp
***
*** This pass and function moves around the defPoints for variables to
*** where the first parallel (PRIM_BLOCK_XMT_PRAGMA_FORALL_I_IN_N) use is.
***
*** The algorithm: look at a function and collect all the variables. Push
*** all the variables down into a parallel block if the variable isn't used
*** at the top level nor is it used in a sibling block. Repeat for each block
*** and sub-block.
***
*** vars = collectVarsInFun(f)
*** for each var in Vars
*** current_block = f->body
*** top_par_block = current_block
*** while (true)
*** if isTopDecl(current_block, var)
*** declare var in top_par_block
*** break
*** else
*** childBlocks = getChildBlocks(current_block)
*** if countBlocks(childBlocks, var) > 1
*** declare var in top_par_block
*** break
*** else
*** current_block = getUniqueBlock(childBlocks, var)
*** if current_block->blockInfo PRIM_BLOCK_XMT_PRAGMA_FORALL_I_IN_N
*** top_par_block = current_block
***
*** Problem: without live variable analysis, could define variable inside
*** block where variable is live going in, thus writing over it
*** on each iteration of loop
***
*** Note: algorithm changed to only consider parallel construct:
*** PRIM_BLOCK_XMT_PRAGMA_FORALL_I_IN_N. Therefore, this pass is only
*** relevant on an XMT. I've left the old code mostly extant such that
*** if we ever want to go back to declaring variables at the top of
*** every block, if, then, or else clause, it'll be easy.
***
*** The CondStmt code is in getChildBlocks() and isTopDecl().
***/
#include "astutil.h"
#include "stmt.h"
#include "symbol.h"
// Gets a total on the number of blocks within some vector of blocks (likely
// captured via getChildBlocks) which contain var. Useful in determining if
// a variable is used in multiple locations.
int countBlocks(Vec<BlockStmt*>& check_vec_block, VarSymbol* var) {
int answer = 0;
forv_Vec(BlockStmt*, block, check_vec_block) {
Vec<SymExpr*> symbols;
collectSymExprs(block, symbols);
forv_Vec(SymExpr, symbol, symbols) {
if (toVarSymbol(symbol->var) == var) {
answer++;
break;
}
}
}
return answer;
}
// Gets a vector of the block statements in a given block of code. For
// example, if some code contains 2 declarations, an if statement, and
// a while loop, the resulting vector would have two elements: the if
// and the while.
Vec<BlockStmt*> getChildBlocks(BlockStmt* check_block) {
Vec<BlockStmt*> answer;
for_alist(expr, check_block->body) {
if (BlockStmt* block = toBlockStmt(expr)) {
answer.add(block);
} else {
if (CondStmt* cond = toCondStmt(expr)) {
if (BlockStmt* thenclause = toBlockStmt(cond->thenStmt)) {
answer.add(thenclause);
}
if (BlockStmt* elseclause = toBlockStmt(cond->elseStmt)) {
answer.add(elseclause);
}
}
}
}
return answer;
}
// Returns the first block statement within a vector of blocks that
// contains a variable.
BlockStmt* getUniqueBlock(Vec<BlockStmt*>& check_vec_block, VarSymbol* var) {
forv_Vec(BlockStmt*, block, check_vec_block) {
Vec<SymExpr*> symbols;
collectSymExprs(block, symbols);
forv_Vec(SymExpr, symbol, symbols) {
if (symbol->var == var) {
return block;
}
}
}
return NULL;
}
// Returns true if a variable appears at the top level of a block. For
// example, if some code contains 2 declarations, one for x and another
// for y, an if statement, and a while loop (which contains z), this
// function would return true if called with x, but false if called with
// z.
bool isTopDecl(BlockStmt* check_block, VarSymbol* var) {
for_alist(expr, check_block->body) {
Vec<SymExpr*> syms;
if ( (!(toBlockStmt(expr))) &&
(!(toCondStmt(expr))) ) {
collectSymExprs(expr, syms);
} else if (BlockStmt* new_block = toBlockStmt(expr)) {
if (new_block->blockInfo) {
collectSymExprs(new_block->blockInfo, syms);
}
} else if (CondStmt* new_cond = toCondStmt(expr)) {
collectSymExprs(new_cond->condExpr, syms);
}
forv_Vec(SymExpr, sym, syms) {
if (sym->var == var)
return true;
}
}
return false;
}
void repositionDefExpressions(void) {
if (fNoRepositionDefExpr) return;
forv_Vec(FnSymbol, fn, gFnSymbols) {
Vec<DefExpr*> vars;
Vec<DefExpr*> defs;
// Collect all the variables defined in function
collectDefExprs(fn, defs);
forv_Vec(DefExpr*, def, defs) {
if (isVarSymbol(def->sym)) {
vars.add(def);
}
}
forv_Vec(DefExpr*, def, vars) {
BlockStmt* current_block = fn->body;
BlockStmt* top_par_block = current_block;
VarSymbol* var = toVarSymbol(def->sym);
while (true) {
if (isTopDecl(current_block, var)) {
// declare var here
if (!toTypeSymbol(def->sym)) {
top_par_block->insertAtHead(def->remove());
}
break;
} else {
Vec<BlockStmt*> childBlocks = getChildBlocks(current_block);
if (countBlocks(childBlocks, var) > 1) {
// declare var here
if (!toTypeSymbol(def->sym)) {
top_par_block->insertAtHead(def->remove());
}
break;
} else {
current_block = getUniqueBlock(childBlocks, var);
if (!current_block) break;
if (current_block->blockInfo)
if (current_block->blockInfo->isPrimitive(PRIM_BLOCK_XMT_PRAGMA_FORALL_I_IN_N))
top_par_block = current_block;
}
}
}
}
}
}
<|endoftext|> |
<commit_before>//===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This test suite verifies basic MCJIT functionality such as making function
// calls, using global variables, and compiling multpile modules.
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/MCJIT.h"
#include "MCJITTestBase.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
class MCJITTest : public testing::Test, public MCJITTestBase {
protected:
void SetUp() override { M.reset(createEmptyModule("<main>")); }
};
// FIXME: Ensure creating an execution engine does not crash when constructed
// with a null module.
/*
TEST_F(MCJITTest, null_module) {
createJIT(0);
}
*/
// FIXME: In order to JIT an empty module, there needs to be
// an interface to ExecutionEngine that forces compilation but
// does not require retrieval of a pointer to a function/global.
/*
TEST_F(MCJITTest, empty_module) {
createJIT(M.take());
//EXPECT_NE(0, TheJIT->getObjectImage())
// << "Unable to generate executable loaded object image";
}
*/
TEST_F(MCJITTest, global_variable) {
SKIP_UNSUPPORTED_PLATFORM;
int initialValue = 5;
GlobalValue *Global = insertGlobalInt32(M.get(), "test_global", initialValue);
createJIT(std::move(M));
void *globalPtr = TheJIT->getPointerToGlobal(Global);
EXPECT_TRUE(nullptr != globalPtr)
<< "Unable to get pointer to global value from JIT";
EXPECT_EQ(initialValue, *(int32_t*)globalPtr)
<< "Unexpected initial value of global";
}
TEST_F(MCJITTest, add_function) {
SKIP_UNSUPPORTED_PLATFORM;
Function *F = insertAddFunction(M.get());
createJIT(std::move(M));
uint64_t addPtr = TheJIT->getFunctionAddress(F->getName().str());
EXPECT_TRUE(0 != addPtr)
<< "Unable to get pointer to function from JIT";
ASSERT_TRUE(addPtr != 0) << "Unable to get pointer to function .";
int (*AddPtr)(int, int) = (int(*)(int, int))addPtr ;
EXPECT_EQ(0, AddPtr(0, 0));
EXPECT_EQ(1, AddPtr(1, 0));
EXPECT_EQ(3, AddPtr(1, 2));
EXPECT_EQ(-5, AddPtr(-2, -3));
EXPECT_EQ(30, AddPtr(10, 20));
EXPECT_EQ(-30, AddPtr(-10, -20));
EXPECT_EQ(-40, AddPtr(-10, -30));
}
TEST_F(MCJITTest, run_main) {
SKIP_UNSUPPORTED_PLATFORM;
int rc = 6;
Function *Main = insertMainFunction(M.get(), 6);
createJIT(std::move(M));
uint64_t ptr = TheJIT->getFunctionAddress(Main->getName().str());
EXPECT_TRUE(0 != ptr)
<< "Unable to get pointer to main() from JIT";
int (*FuncPtr)(void) = (int(*)(void))ptr;
int returnCode = FuncPtr();
EXPECT_EQ(returnCode, rc);
}
TEST_F(MCJITTest, return_global) {
SKIP_UNSUPPORTED_PLATFORM;
int32_t initialNum = 7;
GlobalVariable *GV = insertGlobalInt32(M.get(), "myglob", initialNum);
Function *ReturnGlobal = startFunction<int32_t(void)>(M.get(),
"ReturnGlobal");
Value *ReadGlobal = Builder.CreateLoad(GV);
endFunctionWithRet(ReturnGlobal, ReadGlobal);
createJIT(std::move(M));
uint64_t rgvPtr = TheJIT->getFunctionAddress(ReturnGlobal->getName().str());
EXPECT_TRUE(0 != rgvPtr);
int32_t(*FuncPtr)(void) = (int32_t(*)(void))rgvPtr;
EXPECT_EQ(initialNum, FuncPtr())
<< "Invalid value for global returned from JITted function";
}
// FIXME: This case fails due to a bug with getPointerToGlobal().
// The bug is due to MCJIT not having an implementation of getPointerToGlobal()
// which results in falling back on the ExecutionEngine implementation that
// allocates a new memory block for the global instead of using the same
// global variable that is emitted by MCJIT. Hence, the pointer (gvPtr below)
// has the correct initial value, but updates to the real global (accessed by
// JITted code) are not propagated. Instead, getPointerToGlobal() should return
// a pointer into the loaded ObjectImage to reference the emitted global.
/*
TEST_F(MCJITTest, increment_global) {
SKIP_UNSUPPORTED_PLATFORM;
int32_t initialNum = 5;
Function *IncrementGlobal = startFunction<int32_t(void)>(M.get(), "IncrementGlobal");
GlobalVariable *GV = insertGlobalInt32(M.get(), "my_global", initialNum);
Value *DerefGV = Builder.CreateLoad(GV);
Value *AddResult = Builder.CreateAdd(DerefGV,
ConstantInt::get(Context, APInt(32, 1)));
Builder.CreateStore(AddResult, GV);
endFunctionWithRet(IncrementGlobal, AddResult);
createJIT(M.take());
void *gvPtr = TheJIT->getPointerToGlobal(GV);
EXPECT_EQ(initialNum, *(int32_t*)gvPtr);
void *vPtr = TheJIT->getFunctionAddress(IncrementGlobal->getName().str());
EXPECT_TRUE(0 != vPtr)
<< "Unable to get pointer to main() from JIT";
int32_t(*FuncPtr)(void) = (int32_t(*)(void))(intptr_t)vPtr;
for(int i = 1; i < 3; ++i) {
int32_t result = FuncPtr();
EXPECT_EQ(initialNum + i, result); // OK
EXPECT_EQ(initialNum + i, *(int32_t*)gvPtr); // FAILS
}
}
*/
// PR16013: XFAIL this test on ARM, which currently can't handle multiple relocations.
#if !defined(__arm__)
TEST_F(MCJITTest, multiple_functions) {
SKIP_UNSUPPORTED_PLATFORM;
unsigned int numLevels = 23;
int32_t innerRetVal= 5;
Function *Inner = startFunction<int32_t(void)>(M.get(), "Inner");
endFunctionWithRet(Inner, ConstantInt::get(Context, APInt(32, innerRetVal)));
Function *Outer;
for (unsigned int i = 0; i < numLevels; ++i) {
std::stringstream funcName;
funcName << "level_" << i;
Outer = startFunction<int32_t(void)>(M.get(), funcName.str());
Value *innerResult = Builder.CreateCall(Inner, {});
endFunctionWithRet(Outer, innerResult);
Inner = Outer;
}
createJIT(std::move(M));
uint64_t ptr = TheJIT->getFunctionAddress(Outer->getName().str());
EXPECT_TRUE(0 != ptr)
<< "Unable to get pointer to outer function from JIT";
int32_t(*FuncPtr)(void) = (int32_t(*)(void))ptr;
EXPECT_EQ(innerRetVal, FuncPtr())
<< "Incorrect result returned from function";
}
#endif /*!defined(__arm__)*/
TEST_F(MCJITTest, multiple_decl_lookups) {
SKIP_UNSUPPORTED_PLATFORM;
Function *Foo = insertExternalReferenceToFunction<void(void)>(M.get(), "_exit");
createJIT(std::move(M));
void *A = TheJIT->getPointerToFunction(Foo);
void *B = TheJIT->getPointerToFunction(Foo);
EXPECT_TRUE(A != 0) << "Failed lookup - test not correctly configured.";
EXPECT_EQ(A, B) << "Repeat calls to getPointerToFunction fail.";
}
typedef void * (*FunctionHandlerPtr)(const std::string &str);
TEST_F(MCJITTest, lazy_function_creator_pointer) {
SKIP_UNSUPPORTED_PLATFORM;
Function *Foo = insertExternalReferenceToFunction<int32_t(void)>(M.get(),
"\1Foo");
Function *Parent = startFunction<int32_t(void)>(M.get(), "Parent");
CallInst *Call = Builder.CreateCall(Foo, {});
Builder.CreateRet(Call);
createJIT(std::move(M));
// Set up the lazy function creator that records the name of the last
// unresolved external function found in the module. Using a function pointer
// prevents us from capturing local variables, which is why this is static.
static std::string UnresolvedExternal;
FunctionHandlerPtr UnresolvedHandler = [] (const std::string &str) {
UnresolvedExternal = str;
return (void *)(uintptr_t)-1;
};
TheJIT->InstallLazyFunctionCreator(UnresolvedHandler);
// JIT the module.
TheJIT->finalizeObject();
// Verify that our handler was called.
EXPECT_EQ(UnresolvedExternal, "Foo");
}
TEST_F(MCJITTest, lazy_function_creator_lambda) {
SKIP_UNSUPPORTED_PLATFORM;
Function *Foo1 = insertExternalReferenceToFunction<int32_t(void)>(M.get(),
"\1Foo1");
Function *Foo2 = insertExternalReferenceToFunction<int32_t(void)>(M.get(),
"\1Foo2");
Function *Parent = startFunction<int32_t(void)>(M.get(), "Parent");
CallInst *Call1 = Builder.CreateCall(Foo1, {});
CallInst *Call2 = Builder.CreateCall(Foo2, {});
Value *Result = Builder.CreateAdd(Call1, Call2);
Builder.CreateRet(Result);
createJIT(std::move(M));
// Set up the lazy function creator that records the name of unresolved
// external functions in the module.
std::vector<std::string> UnresolvedExternals;
auto UnresolvedHandler = [&UnresolvedExternals] (const std::string &str) {
llvm:dbgs() << "str is '" << str << "'\n";
UnresolvedExternals.push_back(str);
return (void *)(uintptr_t)-1;
};
TheJIT->InstallLazyFunctionCreator(UnresolvedHandler);
// JIT the module.
TheJIT->finalizeObject();
// Verify that our handler was called for each unresolved function.
auto I = UnresolvedExternals.begin(), E = UnresolvedExternals.end();
EXPECT_EQ(UnresolvedExternals.size(), 2);
EXPECT_FALSE(std::find(I, E, "Foo1") == E);
EXPECT_FALSE(std::find(I, E, "Foo2") == E);
}
}
<commit_msg>[ExecutionEngine] Remove cruft and fix a couple of warnings in the test case for r241962.<commit_after>//===- MCJITTest.cpp - Unit tests for the MCJIT ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This test suite verifies basic MCJIT functionality such as making function
// calls, using global variables, and compiling multpile modules.
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/MCJIT.h"
#include "MCJITTestBase.h"
#include "gtest/gtest.h"
using namespace llvm;
namespace {
class MCJITTest : public testing::Test, public MCJITTestBase {
protected:
void SetUp() override { M.reset(createEmptyModule("<main>")); }
};
// FIXME: Ensure creating an execution engine does not crash when constructed
// with a null module.
/*
TEST_F(MCJITTest, null_module) {
createJIT(0);
}
*/
// FIXME: In order to JIT an empty module, there needs to be
// an interface to ExecutionEngine that forces compilation but
// does not require retrieval of a pointer to a function/global.
/*
TEST_F(MCJITTest, empty_module) {
createJIT(M.take());
//EXPECT_NE(0, TheJIT->getObjectImage())
// << "Unable to generate executable loaded object image";
}
*/
TEST_F(MCJITTest, global_variable) {
SKIP_UNSUPPORTED_PLATFORM;
int initialValue = 5;
GlobalValue *Global = insertGlobalInt32(M.get(), "test_global", initialValue);
createJIT(std::move(M));
void *globalPtr = TheJIT->getPointerToGlobal(Global);
EXPECT_TRUE(nullptr != globalPtr)
<< "Unable to get pointer to global value from JIT";
EXPECT_EQ(initialValue, *(int32_t*)globalPtr)
<< "Unexpected initial value of global";
}
TEST_F(MCJITTest, add_function) {
SKIP_UNSUPPORTED_PLATFORM;
Function *F = insertAddFunction(M.get());
createJIT(std::move(M));
uint64_t addPtr = TheJIT->getFunctionAddress(F->getName().str());
EXPECT_TRUE(0 != addPtr)
<< "Unable to get pointer to function from JIT";
ASSERT_TRUE(addPtr != 0) << "Unable to get pointer to function .";
int (*AddPtr)(int, int) = (int(*)(int, int))addPtr ;
EXPECT_EQ(0, AddPtr(0, 0));
EXPECT_EQ(1, AddPtr(1, 0));
EXPECT_EQ(3, AddPtr(1, 2));
EXPECT_EQ(-5, AddPtr(-2, -3));
EXPECT_EQ(30, AddPtr(10, 20));
EXPECT_EQ(-30, AddPtr(-10, -20));
EXPECT_EQ(-40, AddPtr(-10, -30));
}
TEST_F(MCJITTest, run_main) {
SKIP_UNSUPPORTED_PLATFORM;
int rc = 6;
Function *Main = insertMainFunction(M.get(), 6);
createJIT(std::move(M));
uint64_t ptr = TheJIT->getFunctionAddress(Main->getName().str());
EXPECT_TRUE(0 != ptr)
<< "Unable to get pointer to main() from JIT";
int (*FuncPtr)(void) = (int(*)(void))ptr;
int returnCode = FuncPtr();
EXPECT_EQ(returnCode, rc);
}
TEST_F(MCJITTest, return_global) {
SKIP_UNSUPPORTED_PLATFORM;
int32_t initialNum = 7;
GlobalVariable *GV = insertGlobalInt32(M.get(), "myglob", initialNum);
Function *ReturnGlobal = startFunction<int32_t(void)>(M.get(),
"ReturnGlobal");
Value *ReadGlobal = Builder.CreateLoad(GV);
endFunctionWithRet(ReturnGlobal, ReadGlobal);
createJIT(std::move(M));
uint64_t rgvPtr = TheJIT->getFunctionAddress(ReturnGlobal->getName().str());
EXPECT_TRUE(0 != rgvPtr);
int32_t(*FuncPtr)(void) = (int32_t(*)(void))rgvPtr;
EXPECT_EQ(initialNum, FuncPtr())
<< "Invalid value for global returned from JITted function";
}
// FIXME: This case fails due to a bug with getPointerToGlobal().
// The bug is due to MCJIT not having an implementation of getPointerToGlobal()
// which results in falling back on the ExecutionEngine implementation that
// allocates a new memory block for the global instead of using the same
// global variable that is emitted by MCJIT. Hence, the pointer (gvPtr below)
// has the correct initial value, but updates to the real global (accessed by
// JITted code) are not propagated. Instead, getPointerToGlobal() should return
// a pointer into the loaded ObjectImage to reference the emitted global.
/*
TEST_F(MCJITTest, increment_global) {
SKIP_UNSUPPORTED_PLATFORM;
int32_t initialNum = 5;
Function *IncrementGlobal = startFunction<int32_t(void)>(M.get(), "IncrementGlobal");
GlobalVariable *GV = insertGlobalInt32(M.get(), "my_global", initialNum);
Value *DerefGV = Builder.CreateLoad(GV);
Value *AddResult = Builder.CreateAdd(DerefGV,
ConstantInt::get(Context, APInt(32, 1)));
Builder.CreateStore(AddResult, GV);
endFunctionWithRet(IncrementGlobal, AddResult);
createJIT(M.take());
void *gvPtr = TheJIT->getPointerToGlobal(GV);
EXPECT_EQ(initialNum, *(int32_t*)gvPtr);
void *vPtr = TheJIT->getFunctionAddress(IncrementGlobal->getName().str());
EXPECT_TRUE(0 != vPtr)
<< "Unable to get pointer to main() from JIT";
int32_t(*FuncPtr)(void) = (int32_t(*)(void))(intptr_t)vPtr;
for(int i = 1; i < 3; ++i) {
int32_t result = FuncPtr();
EXPECT_EQ(initialNum + i, result); // OK
EXPECT_EQ(initialNum + i, *(int32_t*)gvPtr); // FAILS
}
}
*/
// PR16013: XFAIL this test on ARM, which currently can't handle multiple relocations.
#if !defined(__arm__)
TEST_F(MCJITTest, multiple_functions) {
SKIP_UNSUPPORTED_PLATFORM;
unsigned int numLevels = 23;
int32_t innerRetVal= 5;
Function *Inner = startFunction<int32_t(void)>(M.get(), "Inner");
endFunctionWithRet(Inner, ConstantInt::get(Context, APInt(32, innerRetVal)));
Function *Outer;
for (unsigned int i = 0; i < numLevels; ++i) {
std::stringstream funcName;
funcName << "level_" << i;
Outer = startFunction<int32_t(void)>(M.get(), funcName.str());
Value *innerResult = Builder.CreateCall(Inner, {});
endFunctionWithRet(Outer, innerResult);
Inner = Outer;
}
createJIT(std::move(M));
uint64_t ptr = TheJIT->getFunctionAddress(Outer->getName().str());
EXPECT_TRUE(0 != ptr)
<< "Unable to get pointer to outer function from JIT";
int32_t(*FuncPtr)(void) = (int32_t(*)(void))ptr;
EXPECT_EQ(innerRetVal, FuncPtr())
<< "Incorrect result returned from function";
}
#endif /*!defined(__arm__)*/
TEST_F(MCJITTest, multiple_decl_lookups) {
SKIP_UNSUPPORTED_PLATFORM;
Function *Foo = insertExternalReferenceToFunction<void(void)>(M.get(), "_exit");
createJIT(std::move(M));
void *A = TheJIT->getPointerToFunction(Foo);
void *B = TheJIT->getPointerToFunction(Foo);
EXPECT_TRUE(A != 0) << "Failed lookup - test not correctly configured.";
EXPECT_EQ(A, B) << "Repeat calls to getPointerToFunction fail.";
}
typedef void * (*FunctionHandlerPtr)(const std::string &str);
TEST_F(MCJITTest, lazy_function_creator_pointer) {
SKIP_UNSUPPORTED_PLATFORM;
Function *Foo = insertExternalReferenceToFunction<int32_t(void)>(M.get(),
"\1Foo");
startFunction<int32_t(void)>(M.get(), "Parent");
CallInst *Call = Builder.CreateCall(Foo, {});
Builder.CreateRet(Call);
createJIT(std::move(M));
// Set up the lazy function creator that records the name of the last
// unresolved external function found in the module. Using a function pointer
// prevents us from capturing local variables, which is why this is static.
static std::string UnresolvedExternal;
FunctionHandlerPtr UnresolvedHandler = [] (const std::string &str) {
UnresolvedExternal = str;
return (void *)(uintptr_t)-1;
};
TheJIT->InstallLazyFunctionCreator(UnresolvedHandler);
// JIT the module.
TheJIT->finalizeObject();
// Verify that our handler was called.
EXPECT_EQ(UnresolvedExternal, "Foo");
}
TEST_F(MCJITTest, lazy_function_creator_lambda) {
SKIP_UNSUPPORTED_PLATFORM;
Function *Foo1 = insertExternalReferenceToFunction<int32_t(void)>(M.get(),
"\1Foo1");
Function *Foo2 = insertExternalReferenceToFunction<int32_t(void)>(M.get(),
"\1Foo2");
startFunction<int32_t(void)>(M.get(), "Parent");
CallInst *Call1 = Builder.CreateCall(Foo1, {});
CallInst *Call2 = Builder.CreateCall(Foo2, {});
Value *Result = Builder.CreateAdd(Call1, Call2);
Builder.CreateRet(Result);
createJIT(std::move(M));
// Set up the lazy function creator that records the name of unresolved
// external functions in the module.
std::vector<std::string> UnresolvedExternals;
auto UnresolvedHandler = [&UnresolvedExternals] (const std::string &str) {
UnresolvedExternals.push_back(str);
return (void *)(uintptr_t)-1;
};
TheJIT->InstallLazyFunctionCreator(UnresolvedHandler);
// JIT the module.
TheJIT->finalizeObject();
// Verify that our handler was called for each unresolved function.
auto I = UnresolvedExternals.begin(), E = UnresolvedExternals.end();
EXPECT_EQ(UnresolvedExternals.size(), 2);
EXPECT_FALSE(std::find(I, E, "Foo1") == E);
EXPECT_FALSE(std::find(I, E, "Foo2") == E);
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
//
// Jet fragmentation transverse momentum (j_T) analysis task
//
// Author: Beomkyu Kim, Beomsu Chang, Dongjo Kim
#include <TClonesArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TList.h>
#include <TProfile.h>
#include <TLorentzVector.h>
#include <TVector.h>
#include <TGraphErrors.h>
#include <TGrid.h>
#include <TSystem.h>
#include <TFile.h>
#include "AliCentrality.h"
#include "AliVCluster.h"
#include "AliAODCaloCluster.h"
#include "AliESDCaloCluster.h"
#include "AliVTrack.h"
#include "AliEmcalJet.h"
#include "AliRhoParameter.h"
#include "AliLog.h"
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliPicoTrack.h"
#include "AliJBaseTrack.h"
#include "AliJJet.h"
#include "AliJJetTask.h"
ClassImp(AliJJetTask);
//________________________________________________________________________
AliJJetTask::AliJJetTask() :
AliAnalysisTaskEmcalJet("AliJJetTask", kTRUE),
fJetsCont(),
fTracksCont(),
fCaloClustersCont(),
fJTracks("AliJBaseTrack",1000),
fJJets(),
fTaskEntry(-1),
fJetFinderString(),
fTrackArrayName("nonejk"),
fNJetFinder(0),
debug(0)
{
// Default constructor.
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliJJetTask::AliJJetTask(const char *name, const int nJetFinder) :
AliAnalysisTaskEmcalJet(name, kTRUE),
fJetsCont(nJetFinder),
fTracksCont(nJetFinder),
fCaloClustersCont(nJetFinder),
fJTracks("AliJBaseTrack",1000),
fJJets(),
fTaskEntry(-1),
fJetFinderString(nJetFinder),
fTrackArrayName("nonejk"),
fNJetFinder(nJetFinder),
debug(0)
{
SetMakeGeneralHistograms(kTRUE);
}
AliJJetTask::AliJJetTask(const AliJJetTask& ap) :
AliAnalysisTaskEmcalJet(ap.fName, kTRUE),
fJetsCont(ap.fJetsCont),
fTracksCont(ap.fTracksCont),
fCaloClustersCont(ap.fCaloClustersCont),
fJTracks(ap.fJTracks),
fJJets(ap.fJJets),
fTaskEntry(ap.fTaskEntry),
fJetFinderString(ap.fJetFinderString),
fTrackArrayName(ap.fTrackArrayName),
fNJetFinder(ap.fNJetFinder),
debug(ap.debug)
{
}
AliJJetTask& AliJJetTask::operator = (const AliJJetTask& ap)
{
this->~AliJJetTask();
new(this) AliJJetTask(ap);
return *this;
}
//________________________________________________________________________
AliJJetTask::~AliJJetTask()
{
// Destructor.
//delete[] fJJets;
}
//________________________________________________________________________
void AliJJetTask::UserCreateOutputObjects()
{
// Create user output.
fJetsCont.resize(fNJetFinder);
fJJets.clear();
fJJets.resize(fNJetFinder, TClonesArray("AliJJet",1000));
fTracksCont.resize(fNJetFinder);
fCaloClustersCont.resize(fNJetFinder);
AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
//fJJets = new TClonesArray[fNJetFinder];
fJetFinderString.clear();
for (int i=0; i<fNJetFinder; i++){
fJetsCont[i] = GetJetContainer(i);
fJetFinderString.push_back(fJetsCont[i]->GetArrayName());
cout << i <<"\t" << fJetFinderString[i] << endl;
fTracksCont[i] = GetParticleContainer(0);
fCaloClustersCont[i] = GetClusterContainer(0);
fTracksCont[i]->SetClassName("AliVTrack");
fCaloClustersCont[i]->SetClassName("AliAODCaloCluster");
//fJJets.push_back(TClonesArray("AliJJet",1000));
}
}
//________________________________________________________________________
Bool_t AliJJetTask::FillHistograms()
{
for (int itrack = 0; itrack<fTracksCont[0]->GetNParticles(); itrack++){
AliVTrack *track = static_cast<AliVTrack*>(fTracksCont[0]->GetParticle(itrack));
new (fJTracks[itrack]) AliJBaseTrack(track->Px(),track->Py(), track->Pz(), track->E(), itrack,0,0);
}
for (int i=0; i<fNJetFinder; i++){
AliEmcalJet *jet = fJetsCont[i]->GetNextAcceptJet(0);
int iJet =0;
//fills fJJets[icontainer][ijet] and histograms
while(jet){
TClonesArray & jets = fJJets[i];
new (jets[iJet]) AliJJet(jet->Px(),jet->Py(), jet->Pz(), jet->E(), jet->GetLabel(),0,0);
AliJJet * j = (AliJJet*) fJJets[i][iJet];
j->SetArea(jet->Area() );
Int_t nConstituents = jet->GetNumberOfTracks();
for (int it=0; it<nConstituents; it++){
int iTrack = jet->TrackAt(it);
j->AddConstituent(fJTracks[iTrack]);
}
if (debug>0) { cout<<" iContainer : "<<i<<
" iJet : "<<iJet<<
" nConstituents : "<<nConstituents<<endl;
}
//Goes to the next jet
jet = fJetsCont[i]->GetNextAcceptJet();
if (debug>0) {
cout<<" fJJets N lists : "<<fJJets[i].GetEntries()<<
" fJJets constituents : "<<((AliJJet*)fJJets[i][iJet])->GetConstituents()->GetEntries()<<endl;
}
iJet++;
}
}
return kTRUE;
}
//________________________________________________________________________
void AliJJetTask::ExecOnce() {
if(debug > 0){
cout << "AliJJetTask::ExecOnce(): " << endl;
}
AliAnalysisTaskEmcalJet::ExecOnce();
for (int i=0; i<fNJetFinder; i++){
if (fJetsCont[i] && fJetsCont[i]->GetArray() == 0) fJetsCont[i] = 0;
if (fTracksCont[i] && fTracksCont[i]->GetArray() == 0) fTracksCont[i] = 0;
if (fCaloClustersCont[i] && fCaloClustersCont[i]->GetArray() == 0) fCaloClustersCont[i] = 0;
}
}
//________________________________________________________________________
Bool_t AliJJetTask::Run()
{
// Run analysis code here, if needed. It will be executed before FillHistograms().
fTaskEntry = fEntry;
for (int i=0; i<fNJetFinder; i++){
fJJets[i]. Clear();
}
fJTracks.Clear();
if (debug >0 && Entry()%1000 ==0 ) cout<<Entry()<<endl;
return kTRUE; // If return kFALSE FillHistogram() will NOT be executed.
}
//________________________________________________________________________
void AliJJetTask::Terminate(Option_t *)
{
// Called once at the end of the analysis.
}
<commit_msg>Fix usage of EMCal jet framework iterator getters GetNext*() in user tasks (PWGCF)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
//
// Jet fragmentation transverse momentum (j_T) analysis task
//
// Author: Beomkyu Kim, Beomsu Chang, Dongjo Kim
#include <TClonesArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH3F.h>
#include <TList.h>
#include <TProfile.h>
#include <TLorentzVector.h>
#include <TVector.h>
#include <TGraphErrors.h>
#include <TGrid.h>
#include <TSystem.h>
#include <TFile.h>
#include "AliCentrality.h"
#include "AliVCluster.h"
#include "AliAODCaloCluster.h"
#include "AliESDCaloCluster.h"
#include "AliVTrack.h"
#include "AliEmcalJet.h"
#include "AliRhoParameter.h"
#include "AliLog.h"
#include "AliJetContainer.h"
#include "AliParticleContainer.h"
#include "AliClusterContainer.h"
#include "AliPicoTrack.h"
#include "AliJBaseTrack.h"
#include "AliJJet.h"
#include "AliJJetTask.h"
ClassImp(AliJJetTask);
//________________________________________________________________________
AliJJetTask::AliJJetTask() :
AliAnalysisTaskEmcalJet("AliJJetTask", kTRUE),
fJetsCont(),
fTracksCont(),
fCaloClustersCont(),
fJTracks("AliJBaseTrack",1000),
fJJets(),
fTaskEntry(-1),
fJetFinderString(),
fTrackArrayName("nonejk"),
fNJetFinder(0),
debug(0)
{
// Default constructor.
SetMakeGeneralHistograms(kTRUE);
}
//________________________________________________________________________
AliJJetTask::AliJJetTask(const char *name, const int nJetFinder) :
AliAnalysisTaskEmcalJet(name, kTRUE),
fJetsCont(nJetFinder),
fTracksCont(nJetFinder),
fCaloClustersCont(nJetFinder),
fJTracks("AliJBaseTrack",1000),
fJJets(),
fTaskEntry(-1),
fJetFinderString(nJetFinder),
fTrackArrayName("nonejk"),
fNJetFinder(nJetFinder),
debug(0)
{
SetMakeGeneralHistograms(kTRUE);
}
AliJJetTask::AliJJetTask(const AliJJetTask& ap) :
AliAnalysisTaskEmcalJet(ap.fName, kTRUE),
fJetsCont(ap.fJetsCont),
fTracksCont(ap.fTracksCont),
fCaloClustersCont(ap.fCaloClustersCont),
fJTracks(ap.fJTracks),
fJJets(ap.fJJets),
fTaskEntry(ap.fTaskEntry),
fJetFinderString(ap.fJetFinderString),
fTrackArrayName(ap.fTrackArrayName),
fNJetFinder(ap.fNJetFinder),
debug(ap.debug)
{
}
AliJJetTask& AliJJetTask::operator = (const AliJJetTask& ap)
{
this->~AliJJetTask();
new(this) AliJJetTask(ap);
return *this;
}
//________________________________________________________________________
AliJJetTask::~AliJJetTask()
{
// Destructor.
//delete[] fJJets;
}
//________________________________________________________________________
void AliJJetTask::UserCreateOutputObjects()
{
// Create user output.
fJetsCont.resize(fNJetFinder);
fJJets.clear();
fJJets.resize(fNJetFinder, TClonesArray("AliJJet",1000));
fTracksCont.resize(fNJetFinder);
fCaloClustersCont.resize(fNJetFinder);
AliAnalysisTaskEmcalJet::UserCreateOutputObjects();
//fJJets = new TClonesArray[fNJetFinder];
fJetFinderString.clear();
for (int i=0; i<fNJetFinder; i++){
fJetsCont[i] = GetJetContainer(i);
fJetFinderString.push_back(fJetsCont[i]->GetArrayName());
cout << i <<"\t" << fJetFinderString[i] << endl;
fTracksCont[i] = GetParticleContainer(0);
fCaloClustersCont[i] = GetClusterContainer(0);
fTracksCont[i]->SetClassName("AliVTrack");
fCaloClustersCont[i]->SetClassName("AliAODCaloCluster");
//fJJets.push_back(TClonesArray("AliJJet",1000));
}
}
//________________________________________________________________________
Bool_t AliJJetTask::FillHistograms()
{
for (int itrack = 0; itrack<fTracksCont[0]->GetNParticles(); itrack++){
AliVTrack *track = static_cast<AliVTrack*>(fTracksCont[0]->GetParticle(itrack));
new (fJTracks[itrack]) AliJBaseTrack(track->Px(),track->Py(), track->Pz(), track->E(), itrack,0,0);
}
for (int i=0; i<fNJetFinder; i++){
fJetsCont[i]->ResetCurrentID();
AliEmcalJet *jet = fJetsCont[i]->GetNextAcceptJet();
int iJet =0;
//fills fJJets[icontainer][ijet] and histograms
while(jet){
TClonesArray & jets = fJJets[i];
new (jets[iJet]) AliJJet(jet->Px(),jet->Py(), jet->Pz(), jet->E(), jet->GetLabel(),0,0);
AliJJet * j = (AliJJet*) fJJets[i][iJet];
j->SetArea(jet->Area() );
Int_t nConstituents = jet->GetNumberOfTracks();
for (int it=0; it<nConstituents; it++){
int iTrack = jet->TrackAt(it);
j->AddConstituent(fJTracks[iTrack]);
}
if (debug>0) { cout<<" iContainer : "<<i<<
" iJet : "<<iJet<<
" nConstituents : "<<nConstituents<<endl;
}
//Goes to the next jet
jet = fJetsCont[i]->GetNextAcceptJet();
if (debug>0) {
cout<<" fJJets N lists : "<<fJJets[i].GetEntries()<<
" fJJets constituents : "<<((AliJJet*)fJJets[i][iJet])->GetConstituents()->GetEntries()<<endl;
}
iJet++;
}
}
return kTRUE;
}
//________________________________________________________________________
void AliJJetTask::ExecOnce() {
if(debug > 0){
cout << "AliJJetTask::ExecOnce(): " << endl;
}
AliAnalysisTaskEmcalJet::ExecOnce();
for (int i=0; i<fNJetFinder; i++){
if (fJetsCont[i] && fJetsCont[i]->GetArray() == 0) fJetsCont[i] = 0;
if (fTracksCont[i] && fTracksCont[i]->GetArray() == 0) fTracksCont[i] = 0;
if (fCaloClustersCont[i] && fCaloClustersCont[i]->GetArray() == 0) fCaloClustersCont[i] = 0;
}
}
//________________________________________________________________________
Bool_t AliJJetTask::Run()
{
// Run analysis code here, if needed. It will be executed before FillHistograms().
fTaskEntry = fEntry;
for (int i=0; i<fNJetFinder; i++){
fJJets[i]. Clear();
}
fJTracks.Clear();
if (debug >0 && Entry()%1000 ==0 ) cout<<Entry()<<endl;
return kTRUE; // If return kFALSE FillHistogram() will NOT be executed.
}
//________________________________________________________________________
void AliJJetTask::Terminate(Option_t *)
{
// Called once at the end of the analysis.
}
<|endoftext|> |
<commit_before>#include <iostream>
/*This is a Program to interact with database*/
int main()
{
cout<<"Hello";
return 0;
}<commit_msg>Dev comment<commit_after>#include <iostream>
/*This is a Program to interact with database*/
int main()
{
cout<<"Hello";
return 0;
}
/* It is in Devlopemnent phase */<|endoftext|> |
<commit_before>#include <math.h>
#include <functional>
#include <random>
#include <gauss_multi.h>
#include <gp.h>
using namespace std;
typedef unsigned int uint;
// Random engine to use throughout
default_random_engine gen;
// How many functions to sample at each step
int n_samp = 5;
int main()
{
// Create a new Gaussian process...
// use zero-mean, squared-exponential covariance (hyperparam l = 1.0), no noise.
auto m = [](double) { return 0; };
auto k = [](double x, double y) { return exp((x - y) * (x - y) / 2.0 * 1.0); };
GP gp(m, k, 0.0);
// points to be used to plot lines
vector<double> xs;
for (double x=-1.0;x<=1.0;x+=0.001) xs.push_back(x);
// Sample the prior
vector<double> mu = gp.get_means(xs);
vector<vector<double>> Sigma = gp.get_covar(xs);
MultiGaussian N(gen, mu, Sigma);
for (int i=0;i<n_samp;i++)
{
vector<double> curr = N.sample();
for (uint j=0;j<curr.size();j++)
{
printf("%.2lf ", curr[j]);
}
printf("\n");
}
return 0;
}
<commit_msg>Worked output! (though still needlessly rugged...)<commit_after>#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <functional>
#include <random>
#include <vector>
#include <string>
#include <gauss_multi.h>
#include <gp.h>
using namespace std;
typedef unsigned int uint;
// Random engine to use throughout
default_random_engine gen;
// How many functions to sample at each step
int n_samp = 5;
void to_tikz(vector<vector<double>> X, vector<vector<double>> Y, string fname)
{
assert(X.size() == Y.size());
FILE *f = fopen(fname.c_str(), "w");
// Define colours (TODO-someday: make this parametrised...)
fprintf(f, "\\definecolor{mycolor0}{rgb}{0.00000,0.44700,0.74100}%%\n");
fprintf(f, "\\definecolor{mycolor1}{rgb}{0.85000,0.32500,0.09800}%%\n");
fprintf(f, "\\definecolor{mycolor2}{rgb}{0.92900,0.69400,0.12500}%%\n");
fprintf(f, "\\definecolor{mycolor3}{rgb}{0.49400,0.18400,0.55600}%%\n");
fprintf(f, "\\definecolor{mycolor4}{rgb}{0.46600,0.67400,0.18800}%%\n");
// Begin picture
fprintf(f, "\\begin{tikzpicture}[very thick]\n");
// Begin axis (with all parameters)
fprintf(f, "\\begin{axis}[width=6.028in, height=4.754in,\n");
fprintf(f, "scale only axis, xmin=-1, xmax=1, ymin=-100.0, ymax=100.0,\n");
fprintf(f, "axis background/.style={fill=white}]\n");
// Add plots
for (uint i=0;i<X.size();i++)
{
assert(X[i].size() == Y[i].size());
fprintf(f, "\\addplot[color=mycolor%d, solid] table[row sep=crcr]{%%\n", i);
for (uint j=0;j<X[i].size();j++)
{
fprintf(f, "%.10lf %.10lf\\\\\n", X[i][j], Y[i][j]);
}
fprintf(f, "};\n");
}
fprintf(f, "\\end{axis}\n");
fprintf(f, "\\end{tikzpicture}\n");
fclose(f);
}
int main()
{
// Create a new Gaussian process...
// use zero-mean, squared-exponential covariance (hyperparam l = 1.0), no noise.
auto m = [](double) { return 0; };
auto k = [](double x, double y) { return exp(-(x - y) * (x - y) / (2.0 * 10.0 * 10.0)); };
GP gp(m, k, 0.0);
// points to be used to plot lines
vector<double> xs;
for (double x=-1.0;x<=1.0;x+=0.001) xs.push_back(x);
// Sample the prior
vector<double> mu = gp.get_means(xs);
vector<vector<double>> Sigma = gp.get_covar(xs);
MultiGaussian N(gen, mu, Sigma);
vector<vector<double>> Xs(n_samp, xs);
vector<vector<double>> Ys(n_samp);
for (int i=0;i<n_samp;i++)
{
Ys[i] = N.sample();
}
to_tikz(Xs, Ys, "test.tex");
return 0;
}
<|endoftext|> |
<commit_before>#include "Rendering/GBuffer.h"
#include "Rendering/RenderTargetDX11.h"
#include "Rendering/DepthStencilBufferDX11.h"
#include "Rendering/Texture2dDX11.h"
#include "Rendering/BlendState.h"
constexpr unsigned int GBUFFER_RENDER_TARGET_NUM = 5;
namespace Mile
{
GBuffer::GBuffer(RendererDX11* renderer) :
m_depthStencilBuffer(nullptr),
m_positionBuffer(nullptr),
m_albedoBuffer(nullptr),
m_emissiveAOBuffer(nullptr),
m_normalBuffer(nullptr),
m_extraComponents(nullptr),
m_blendState(nullptr),
m_bBoundDepthAsShaderResource(false),
RenderObject(renderer)
{
}
GBuffer::~GBuffer()
{
SafeDelete(m_positionBuffer);
SafeDelete(m_albedoBuffer);
SafeDelete(m_emissiveAOBuffer);
SafeDelete(m_normalBuffer);
SafeDelete(m_extraComponents);
SafeDelete(m_blendState);
}
bool GBuffer::Init(unsigned int width, unsigned int height)
{
if (RenderObject::IsInitializable())
{
RendererDX11* renderer = GetRenderer();
m_positionBuffer = new RenderTargetDX11(renderer);
m_albedoBuffer = new RenderTargetDX11(renderer);
m_emissiveAOBuffer = new RenderTargetDX11(renderer);
m_normalBuffer = new RenderTargetDX11(renderer);
m_extraComponents = new RenderTargetDX11(renderer);
m_blendState = new BlendState(renderer);
bool bBuffersInitialized =
m_positionBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT) &&
m_albedoBuffer->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT) &&
m_emissiveAOBuffer->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT) &&
m_normalBuffer->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT) &&
m_extraComponents->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT);
if (bBuffersInitialized && m_blendState->Init())
{
RenderObject::ConfirmInit();
return true;
}
}
return false;
}
bool GBuffer::BindAsRenderTarget(ID3D11DeviceContext& deviceContext, bool clearRenderTargets, bool clearDepthStencil)
{
if (RenderObject::IsBindable())
{
ID3D11DepthStencilView* dsv = nullptr;
if (m_depthStencilBuffer != nullptr)
{
dsv = m_depthStencilBuffer->GetDSV();
if (clearDepthStencil)
{
deviceContext.ClearDepthStencilView(dsv,
D3D11_CLEAR_DEPTH,
1.0f,
0);
}
}
std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
m_positionBuffer->GetRTV(),
m_albedoBuffer->GetRTV(),
m_emissiveAOBuffer->GetRTV(),
m_normalBuffer->GetRTV(),
m_extraComponents->GetRTV()
};
if (clearRenderTargets)
{
const float clearColor[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
for (auto rtv : targets)
{
deviceContext.ClearRenderTargetView(rtv, clearColor);
}
}
deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), dsv);
if (m_blendState != nullptr)
{
if (m_blendState->Bind(deviceContext))
{
return true;
}
}
}
return false;
}
bool GBuffer::BindAsShaderResource(ID3D11DeviceContext& deviceContext, unsigned int startSlot, bool bBindDepthStencil)
{
if (RenderObject::IsBindable())
{
std::array<RenderTargetDX11*, GBUFFER_RENDER_TARGET_NUM> targets{
m_positionBuffer,
m_albedoBuffer,
m_emissiveAOBuffer,
m_normalBuffer,
m_extraComponents };
for (unsigned int idx = 0; idx < GBUFFER_RENDER_TARGET_NUM; ++idx)
{
if (!targets[idx]->BindAsShaderResource(deviceContext, startSlot + idx, EShaderType::PixelShader))
{
return false;
}
}
if (bBindDepthStencil)
{
ID3D11ShaderResourceView* depthSRV = m_depthStencilBuffer->GetSRV();
deviceContext.PSSetShaderResources(startSlot + GBUFFER_RENDER_TARGET_NUM, 1, &depthSRV);
m_bBoundDepthAsShaderResource = bBindDepthStencil;
}
return true;
}
return false;
}
void GBuffer::UnbindShaderResource(ID3D11DeviceContext& deviceContext)
{
if (RenderObject::IsBindable())
{
m_positionBuffer->UnbindShaderResource(deviceContext);
m_albedoBuffer->UnbindShaderResource(deviceContext);
m_emissiveAOBuffer->UnbindShaderResource(deviceContext);
m_normalBuffer->UnbindShaderResource(deviceContext);
m_extraComponents->UnbindShaderResource(deviceContext);
if (m_bBoundDepthAsShaderResource)
{
ID3D11ShaderResourceView* nullSRV = nullptr;
Texture2dDX11* positionTexture = m_positionBuffer->GetTexture();
unsigned int startSlot = positionTexture->GetBoundSlot();
deviceContext.PSSetShaderResources(startSlot + GBUFFER_RENDER_TARGET_NUM, 1, &nullSRV);
m_bBoundDepthAsShaderResource = false;
}
}
}
void GBuffer::UnbindRenderTarget(ID3D11DeviceContext& deviceContext)
{
if (RenderObject::IsBindable())
{
std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
nullptr,
nullptr,
nullptr,
nullptr,
nullptr
};
deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), nullptr);
}
}
}<commit_msg>Modify default clear color of g-buffer<commit_after>#include "Rendering/GBuffer.h"
#include "Rendering/RenderTargetDX11.h"
#include "Rendering/DepthStencilBufferDX11.h"
#include "Rendering/Texture2dDX11.h"
#include "Rendering/BlendState.h"
constexpr unsigned int GBUFFER_RENDER_TARGET_NUM = 5;
namespace Mile
{
GBuffer::GBuffer(RendererDX11* renderer) :
m_depthStencilBuffer(nullptr),
m_positionBuffer(nullptr),
m_albedoBuffer(nullptr),
m_emissiveAOBuffer(nullptr),
m_normalBuffer(nullptr),
m_extraComponents(nullptr),
m_blendState(nullptr),
m_bBoundDepthAsShaderResource(false),
RenderObject(renderer)
{
}
GBuffer::~GBuffer()
{
SafeDelete(m_positionBuffer);
SafeDelete(m_albedoBuffer);
SafeDelete(m_emissiveAOBuffer);
SafeDelete(m_normalBuffer);
SafeDelete(m_extraComponents);
SafeDelete(m_blendState);
}
bool GBuffer::Init(unsigned int width, unsigned int height)
{
if (RenderObject::IsInitializable())
{
RendererDX11* renderer = GetRenderer();
m_positionBuffer = new RenderTargetDX11(renderer);
m_albedoBuffer = new RenderTargetDX11(renderer);
m_emissiveAOBuffer = new RenderTargetDX11(renderer);
m_normalBuffer = new RenderTargetDX11(renderer);
m_extraComponents = new RenderTargetDX11(renderer);
m_blendState = new BlendState(renderer);
bool bBuffersInitialized =
m_positionBuffer->Init(width, height, DXGI_FORMAT_R32G32B32A32_FLOAT) &&
m_albedoBuffer->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT) &&
m_emissiveAOBuffer->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT) &&
m_normalBuffer->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT) &&
m_extraComponents->Init(width, height, DXGI_FORMAT_R16G16B16A16_FLOAT);
if (bBuffersInitialized && m_blendState->Init())
{
RenderObject::ConfirmInit();
return true;
}
}
return false;
}
bool GBuffer::BindAsRenderTarget(ID3D11DeviceContext& deviceContext, bool clearRenderTargets, bool clearDepthStencil)
{
if (RenderObject::IsBindable())
{
ID3D11DepthStencilView* dsv = nullptr;
if (m_depthStencilBuffer != nullptr)
{
dsv = m_depthStencilBuffer->GetDSV();
if (clearDepthStencil)
{
deviceContext.ClearDepthStencilView(dsv,
D3D11_CLEAR_DEPTH,
1.0f,
0);
}
}
std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
m_positionBuffer->GetRTV(),
m_albedoBuffer->GetRTV(),
m_emissiveAOBuffer->GetRTV(),
m_normalBuffer->GetRTV(),
m_extraComponents->GetRTV()
};
if (clearRenderTargets)
{
const float clearColor[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
for (auto rtv : targets)
{
deviceContext.ClearRenderTargetView(rtv, clearColor);
}
}
deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), dsv);
if (m_blendState != nullptr)
{
if (m_blendState->Bind(deviceContext))
{
return true;
}
}
}
return false;
}
bool GBuffer::BindAsShaderResource(ID3D11DeviceContext& deviceContext, unsigned int startSlot, bool bBindDepthStencil)
{
if (RenderObject::IsBindable())
{
std::array<RenderTargetDX11*, GBUFFER_RENDER_TARGET_NUM> targets{
m_positionBuffer,
m_albedoBuffer,
m_emissiveAOBuffer,
m_normalBuffer,
m_extraComponents };
for (unsigned int idx = 0; idx < GBUFFER_RENDER_TARGET_NUM; ++idx)
{
if (!targets[idx]->BindAsShaderResource(deviceContext, startSlot + idx, EShaderType::PixelShader))
{
return false;
}
}
if (bBindDepthStencil)
{
ID3D11ShaderResourceView* depthSRV = m_depthStencilBuffer->GetSRV();
deviceContext.PSSetShaderResources(startSlot + GBUFFER_RENDER_TARGET_NUM, 1, &depthSRV);
m_bBoundDepthAsShaderResource = bBindDepthStencil;
}
return true;
}
return false;
}
void GBuffer::UnbindShaderResource(ID3D11DeviceContext& deviceContext)
{
if (RenderObject::IsBindable())
{
m_positionBuffer->UnbindShaderResource(deviceContext);
m_albedoBuffer->UnbindShaderResource(deviceContext);
m_emissiveAOBuffer->UnbindShaderResource(deviceContext);
m_normalBuffer->UnbindShaderResource(deviceContext);
m_extraComponents->UnbindShaderResource(deviceContext);
if (m_bBoundDepthAsShaderResource)
{
ID3D11ShaderResourceView* nullSRV = nullptr;
Texture2dDX11* positionTexture = m_positionBuffer->GetTexture();
unsigned int startSlot = positionTexture->GetBoundSlot();
deviceContext.PSSetShaderResources(startSlot + GBUFFER_RENDER_TARGET_NUM, 1, &nullSRV);
m_bBoundDepthAsShaderResource = false;
}
}
}
void GBuffer::UnbindRenderTarget(ID3D11DeviceContext& deviceContext)
{
if (RenderObject::IsBindable())
{
std::array<ID3D11RenderTargetView*, GBUFFER_RENDER_TARGET_NUM> targets{
nullptr,
nullptr,
nullptr,
nullptr,
nullptr
};
deviceContext.OMSetRenderTargets(GBUFFER_RENDER_TARGET_NUM, targets.data(), nullptr);
}
}
}<|endoftext|> |
<commit_before>/*
This file is part of Akregator.
Copyright (C) 2004 Sashmit Bhaduri <smt@vfemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "akregator_plugin.h"
#include "akregator_part.h"
#include "akregator_options.h"
#include "partinterface.h"
#include <KontactInterface/Core>
#include <KAction>
#include <KActionCollection>
#include <KLocale>
EXPORT_KONTACT_PLUGIN( AkregatorPlugin, akregator )
AkregatorPlugin::AkregatorPlugin( KontactInterface::Core *core, const QVariantList & )
: KontactInterface::Plugin( core, core, "akregator" ), m_interface( 0 )
{
setComponentData( KontactPluginFactory::componentData() );
KAction *action = new KAction( KIcon( "bookmark-new" ), i18n( "New Feed..." ), this );
actionCollection()->addAction( "feed_new", action );
action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_F ) );
connect( action, SIGNAL(triggered(bool)), SLOT(addFeed()) );
insertNewAction( action );
mUniqueAppWatcher = new KontactInterface::UniqueAppWatcher(
new KontactInterface::UniqueAppHandlerFactory<AkregatorUniqueAppHandler>(), this );
}
AkregatorPlugin::~AkregatorPlugin()
{
}
bool AkregatorPlugin::isRunningStandalone() const
{
return mUniqueAppWatcher->isRunningStandalone();
}
QStringList AkregatorPlugin::invisibleToolbarActions() const
{
return QStringList( "file_new_contact" );
}
OrgKdeAkregatorPartInterface *AkregatorPlugin::interface()
{
if ( !m_interface ) {
part();
}
Q_ASSERT( m_interface );
return m_interface;
}
QString AkregatorPlugin::tipFile() const
{
// TODO: tips file
//QString file = KStandardDirs::locate("data", "akregator/tips");
QString file;
return file;
}
KParts::ReadOnlyPart *AkregatorPlugin::createPart()
{
KParts::ReadOnlyPart *part = loadPart();
if ( !part ) {
return 0;
}
connect( part, SIGNAL(showPart()), this, SLOT(showPart()) );
m_interface = new OrgKdeAkregatorPartInterface(
"org.kde.akregator", "/Akregator", QDBusConnection::sessionBus() );
m_interface->openStandardFeedList();
return part;
}
void AkregatorPlugin::showPart()
{
core()->selectPlugin( this );
}
void AkregatorPlugin::addFeed()
{
(void) part(); // ensure part is loaded
Q_ASSERT( m_interface );
m_interface->addFeed();
}
QStringList AkregatorPlugin::configModules() const
{
QStringList modules;
modules << "PIM/akregator.desktop";
return modules;
}
void AkregatorPlugin::readProperties( const KConfigGroup &config )
{
if ( part() ) {
Akregator::Part *myPart = static_cast<Akregator::Part*>( part() );
myPart->readProperties( config );
}
}
void AkregatorPlugin::saveProperties( KConfigGroup &config )
{
if ( part() ) {
Akregator::Part *myPart = static_cast<Akregator::Part*>( part() );
myPart->saveProperties( config );
}
}
void AkregatorUniqueAppHandler::loadCommandLineOptions()
{
KCmdLineArgs::addCmdLineOptions( Akregator::akregator_options() );
}
int AkregatorUniqueAppHandler::newInstance()
{
// Ensure part is loaded
(void)plugin()->part();
org::kde::akregator::part akregator(
"org.kde.akregator", "/Akregator", QDBusConnection::sessionBus() );
akregator.openStandardFeedList();
return KontactInterface::UniqueAppHandler::newInstance();
}
#include "akregator_plugin.moc"
<commit_msg>add helptext to the New action MERGE: none DO_NOT_BACKPORT: new i18n string<commit_after>/*
This file is part of Akregator.
Copyright (C) 2004 Sashmit Bhaduri <smt@vfemail.net>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "akregator_plugin.h"
#include "akregator_part.h"
#include "akregator_options.h"
#include "partinterface.h"
#include <KontactInterface/Core>
#include <KAction>
#include <KActionCollection>
#include <KLocale>
EXPORT_KONTACT_PLUGIN( AkregatorPlugin, akregator )
AkregatorPlugin::AkregatorPlugin( KontactInterface::Core *core, const QVariantList & )
: KontactInterface::Plugin( core, core, "akregator" ), m_interface( 0 )
{
setComponentData( KontactPluginFactory::componentData() );
KAction *action = new KAction( KIcon( "bookmark-new" ), i18n( "New Feed..." ), this );
actionCollection()->addAction( "feed_new", action );
action->setShortcut( QKeySequence( Qt::CTRL + Qt::SHIFT + Qt::Key_F ) );
action->setHelpText( i18n( "Create a new feed" ) );
connect( action, SIGNAL(triggered(bool)), SLOT(addFeed()) );
insertNewAction( action );
mUniqueAppWatcher = new KontactInterface::UniqueAppWatcher(
new KontactInterface::UniqueAppHandlerFactory<AkregatorUniqueAppHandler>(), this );
}
AkregatorPlugin::~AkregatorPlugin()
{
}
bool AkregatorPlugin::isRunningStandalone() const
{
return mUniqueAppWatcher->isRunningStandalone();
}
QStringList AkregatorPlugin::invisibleToolbarActions() const
{
return QStringList( "file_new_contact" );
}
OrgKdeAkregatorPartInterface *AkregatorPlugin::interface()
{
if ( !m_interface ) {
part();
}
Q_ASSERT( m_interface );
return m_interface;
}
QString AkregatorPlugin::tipFile() const
{
// TODO: tips file
//QString file = KStandardDirs::locate("data", "akregator/tips");
QString file;
return file;
}
KParts::ReadOnlyPart *AkregatorPlugin::createPart()
{
KParts::ReadOnlyPart *part = loadPart();
if ( !part ) {
return 0;
}
connect( part, SIGNAL(showPart()), this, SLOT(showPart()) );
m_interface = new OrgKdeAkregatorPartInterface(
"org.kde.akregator", "/Akregator", QDBusConnection::sessionBus() );
m_interface->openStandardFeedList();
return part;
}
void AkregatorPlugin::showPart()
{
core()->selectPlugin( this );
}
void AkregatorPlugin::addFeed()
{
(void) part(); // ensure part is loaded
Q_ASSERT( m_interface );
m_interface->addFeed();
}
QStringList AkregatorPlugin::configModules() const
{
QStringList modules;
modules << "PIM/akregator.desktop";
return modules;
}
void AkregatorPlugin::readProperties( const KConfigGroup &config )
{
if ( part() ) {
Akregator::Part *myPart = static_cast<Akregator::Part*>( part() );
myPart->readProperties( config );
}
}
void AkregatorPlugin::saveProperties( KConfigGroup &config )
{
if ( part() ) {
Akregator::Part *myPart = static_cast<Akregator::Part*>( part() );
myPart->saveProperties( config );
}
}
void AkregatorUniqueAppHandler::loadCommandLineOptions()
{
KCmdLineArgs::addCmdLineOptions( Akregator::akregator_options() );
}
int AkregatorUniqueAppHandler::newInstance()
{
// Ensure part is loaded
(void)plugin()->part();
org::kde::akregator::part akregator(
"org.kde.akregator", "/Akregator", QDBusConnection::sessionBus() );
akregator.openStandardFeedList();
return KontactInterface::UniqueAppHandler::newInstance();
}
#include "akregator_plugin.moc"
<|endoftext|> |
<commit_before>//===-- SocketTest.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
// Workaround for MSVC standard library bug, which fails to include <thread>
// when
// exceptions are disabled.
#include <eh.h>
#endif
#include <cstdio>
#include <functional>
#include <thread>
#include "gtest/gtest.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/Socket.h"
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/common/UDPSocket.h"
#ifndef LLDB_DISABLE_POSIX
#include "lldb/Host/posix/DomainSocket.h"
#endif
using namespace lldb_private;
class SocketTest : public testing::Test {
public:
void SetUp() override {
#if defined(_MSC_VER)
WSADATA data;
::WSAStartup(MAKEWORD(2, 2), &data);
#endif
}
void TearDown() override {
#if defined(_MSC_VER)
::WSACleanup();
#endif
}
protected:
static void AcceptThread(Socket *listen_socket,
const char *listen_remote_address,
bool child_processes_inherit, Socket **accept_socket,
Error *error) {
*error = listen_socket->Accept(listen_remote_address,
child_processes_inherit, *accept_socket);
}
template <typename SocketType>
void CreateConnectedSockets(
const char *listen_remote_address,
const std::function<std::string(const SocketType &)> &get_connect_addr,
std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {
bool child_processes_inherit = false;
Error error;
std::unique_ptr<SocketType> listen_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = listen_socket_up->Listen(listen_remote_address, 5);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(listen_socket_up->IsValid());
Error accept_error;
Socket *accept_socket;
std::thread accept_thread(AcceptThread, listen_socket_up.get(),
listen_remote_address, child_processes_inherit,
&accept_socket, &accept_error);
std::string connect_remote_address = get_connect_addr(*listen_socket_up);
std::unique_ptr<SocketType> connect_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = connect_socket_up->Connect(connect_remote_address);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(connect_socket_up->IsValid());
a_up->swap(connect_socket_up);
EXPECT_TRUE(error.Success());
EXPECT_NE(nullptr, a_up->get());
EXPECT_TRUE((*a_up)->IsValid());
accept_thread.join();
b_up->reset(static_cast<SocketType *>(accept_socket));
EXPECT_TRUE(accept_error.Success());
EXPECT_NE(nullptr, b_up->get());
EXPECT_TRUE((*b_up)->IsValid());
listen_socket_up.reset();
}
};
TEST_F(SocketTest, DecodeHostAndPort) {
std::string host_str;
std::string port_str;
int32_t port;
Error error;
EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
port, &error));
EXPECT_STREQ("localhost", host_str.c_str());
EXPECT_STREQ("1138", port_str.c_str());
EXPECT_EQ(1138, port);
EXPECT_TRUE(error.Success());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_TRUE(
Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
EXPECT_STREQ("", host_str.c_str());
EXPECT_STREQ("12345", port_str.c_str());
EXPECT_EQ(12345, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("0", port_str.c_str());
EXPECT_EQ(0, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("65535", port_str.c_str());
EXPECT_EQ(65535, port);
EXPECT_TRUE(error.Success());
}
#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainListenConnectAccept) {
char *file_name_str = tempnam(nullptr, nullptr);
EXPECT_NE(nullptr, file_name_str);
const std::string file_name(file_name_str);
free(file_name_str);
std::unique_ptr<DomainSocket> socket_a_up;
std::unique_ptr<DomainSocket> socket_b_up;
CreateConnectedSockets<DomainSocket>(
file_name.c_str(), [=](const DomainSocket &) { return file_name; },
&socket_a_up, &socket_b_up);
}
#endif
TEST_F(SocketTest, TCPListen0ConnectAccept) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
}
TEST_F(SocketTest, TCPGetAddress) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetRemotePortNumber());
EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
socket_a_up->GetRemotePortNumber());
EXPECT_NE(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetLocalPortNumber());
EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}
TEST_F(SocketTest, UDPConnect) {
Socket *socket_a;
Socket *socket_b;
bool child_processes_inherit = false;
auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
socket_a, socket_b);
std::unique_ptr<Socket> a_up(socket_a);
std::unique_ptr<Socket> b_up(socket_b);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(a_up->IsValid());
EXPECT_TRUE(b_up->IsValid());
}
<commit_msg>Update unittests/Host/SocketTest.cpp to also use the new one-socket API.<commit_after>//===-- SocketTest.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#if defined(_MSC_VER) && (_HAS_EXCEPTIONS == 0)
// Workaround for MSVC standard library bug, which fails to include <thread>
// when
// exceptions are disabled.
#include <eh.h>
#endif
#include <cstdio>
#include <functional>
#include <thread>
#include "gtest/gtest.h"
#include "lldb/Host/Config.h"
#include "lldb/Host/Socket.h"
#include "lldb/Host/common/TCPSocket.h"
#include "lldb/Host/common/UDPSocket.h"
#ifndef LLDB_DISABLE_POSIX
#include "lldb/Host/posix/DomainSocket.h"
#endif
using namespace lldb_private;
class SocketTest : public testing::Test {
public:
void SetUp() override {
#if defined(_MSC_VER)
WSADATA data;
::WSAStartup(MAKEWORD(2, 2), &data);
#endif
}
void TearDown() override {
#if defined(_MSC_VER)
::WSACleanup();
#endif
}
protected:
static void AcceptThread(Socket *listen_socket,
const char *listen_remote_address,
bool child_processes_inherit, Socket **accept_socket,
Error *error) {
*error = listen_socket->Accept(listen_remote_address,
child_processes_inherit, *accept_socket);
}
template <typename SocketType>
void CreateConnectedSockets(
const char *listen_remote_address,
const std::function<std::string(const SocketType &)> &get_connect_addr,
std::unique_ptr<SocketType> *a_up, std::unique_ptr<SocketType> *b_up) {
bool child_processes_inherit = false;
Error error;
std::unique_ptr<SocketType> listen_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = listen_socket_up->Listen(listen_remote_address, 5);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(listen_socket_up->IsValid());
Error accept_error;
Socket *accept_socket;
std::thread accept_thread(AcceptThread, listen_socket_up.get(),
listen_remote_address, child_processes_inherit,
&accept_socket, &accept_error);
std::string connect_remote_address = get_connect_addr(*listen_socket_up);
std::unique_ptr<SocketType> connect_socket_up(
new SocketType(child_processes_inherit, error));
EXPECT_FALSE(error.Fail());
error = connect_socket_up->Connect(connect_remote_address);
EXPECT_FALSE(error.Fail());
EXPECT_TRUE(connect_socket_up->IsValid());
a_up->swap(connect_socket_up);
EXPECT_TRUE(error.Success());
EXPECT_NE(nullptr, a_up->get());
EXPECT_TRUE((*a_up)->IsValid());
accept_thread.join();
b_up->reset(static_cast<SocketType *>(accept_socket));
EXPECT_TRUE(accept_error.Success());
EXPECT_NE(nullptr, b_up->get());
EXPECT_TRUE((*b_up)->IsValid());
listen_socket_up.reset();
}
};
TEST_F(SocketTest, DecodeHostAndPort) {
std::string host_str;
std::string port_str;
int32_t port;
Error error;
EXPECT_TRUE(Socket::DecodeHostAndPort("localhost:1138", host_str, port_str,
port, &error));
EXPECT_STREQ("localhost", host_str.c_str());
EXPECT_STREQ("1138", port_str.c_str());
EXPECT_EQ(1138, port);
EXPECT_TRUE(error.Success());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:-1138", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:-1138'",
error.AsCString());
EXPECT_FALSE(Socket::DecodeHostAndPort("google.com:65536", host_str, port_str,
port, &error));
EXPECT_TRUE(error.Fail());
EXPECT_STREQ("invalid host:port specification: 'google.com:65536'",
error.AsCString());
EXPECT_TRUE(
Socket::DecodeHostAndPort("12345", host_str, port_str, port, &error));
EXPECT_STREQ("", host_str.c_str());
EXPECT_STREQ("12345", port_str.c_str());
EXPECT_EQ(12345, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:0", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("0", port_str.c_str());
EXPECT_EQ(0, port);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(
Socket::DecodeHostAndPort("*:65535", host_str, port_str, port, &error));
EXPECT_STREQ("*", host_str.c_str());
EXPECT_STREQ("65535", port_str.c_str());
EXPECT_EQ(65535, port);
EXPECT_TRUE(error.Success());
}
#ifndef LLDB_DISABLE_POSIX
TEST_F(SocketTest, DomainListenConnectAccept) {
char *file_name_str = tempnam(nullptr, nullptr);
EXPECT_NE(nullptr, file_name_str);
const std::string file_name(file_name_str);
free(file_name_str);
std::unique_ptr<DomainSocket> socket_a_up;
std::unique_ptr<DomainSocket> socket_b_up;
CreateConnectedSockets<DomainSocket>(
file_name.c_str(), [=](const DomainSocket &) { return file_name; },
&socket_a_up, &socket_b_up);
}
#endif
TEST_F(SocketTest, TCPListen0ConnectAccept) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
}
TEST_F(SocketTest, TCPGetAddress) {
std::unique_ptr<TCPSocket> socket_a_up;
std::unique_ptr<TCPSocket> socket_b_up;
CreateConnectedSockets<TCPSocket>(
"127.0.0.1:0",
[=](const TCPSocket &s) {
char connect_remote_address[64];
snprintf(connect_remote_address, sizeof(connect_remote_address),
"localhost:%u", s.GetLocalPortNumber());
return std::string(connect_remote_address);
},
&socket_a_up, &socket_b_up);
EXPECT_EQ(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetRemotePortNumber());
EXPECT_EQ(socket_b_up->GetLocalPortNumber(),
socket_a_up->GetRemotePortNumber());
EXPECT_NE(socket_a_up->GetLocalPortNumber(),
socket_b_up->GetLocalPortNumber());
EXPECT_STREQ("127.0.0.1", socket_a_up->GetRemoteIPAddress().c_str());
EXPECT_STREQ("127.0.0.1", socket_b_up->GetRemoteIPAddress().c_str());
}
TEST_F(SocketTest, UDPConnect) {
Socket *socket;
bool child_processes_inherit = false;
auto error = UDPSocket::Connect("127.0.0.1:0", child_processes_inherit,
socket);
std::unique_ptr<Socket> socket_up(socket);
EXPECT_TRUE(error.Success());
EXPECT_TRUE(socket_up->IsValid());
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include <utility>
#include "factory/FileSystemFactory.h"
#include "filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "probe/CrawlerProbe.h"
#include "utils/Filename.h"
namespace
{
class DeviceRemovedException : public std::runtime_error
{
public:
DeviceRemovedException() noexcept
: std::runtime_error( "A device was removed during the discovery" )
{
}
};
}
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
: m_ml( ml )
, m_fsFactory( std::move( fsFactory ))
, m_cb( cb )
, m_probe( std::move( probe ) )
{
}
bool FsDiscoverer::discover( const std::string &entryPoint )
{
LOG_INFO( "Adding to discovery list: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
auto f = Folder::fromMrl( m_ml, entryPoint );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
return true;
// Fetch files explicitly
fsDir->files();
return addFolder( std::move( fsDir ), m_probe->getFolderParent().get() );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
catch ( DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_INFO( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
}
return true;
}
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
{
auto mrl = f->mrl();
auto folder = m_fsFactory->createDirectory( mrl );
assert( folder->device() != nullptr );
if ( folder->device() == nullptr )
return;
try
{
checkFolder( std::move( folder ), std::move( f ), false );
}
catch ( DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
}
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
reloadFolder( f );
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
reloadFolder( std::move( folder ) );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( m_probe->isHidden( *currentFolderFs ) == true )
{
if ( newFolder == false )
m_ml->deleteFolder( *currentFolder );
return;
}
// Ensuring that the file fetching is done in this scope, to catch errors
currentFolderFs->files();
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and IProbe::isHidden is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
auto device = currentFolderFs->device();
// The device might not be present at all, and therefor we might miss a
// representation for it.
if ( device == nullptr || device->isRemovable() )
{
// If the device is removable/missing, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
device != nullptr ? "removable" : "not found",
". Refreshing device cache..." );
m_ml->refreshDevices( *m_fsFactory );
// If the device was missing, refresh our list of devices in case
// the device was plugged back and/or we missed a notification for it
if ( device == nullptr )
device = currentFolderFs->device();
// The device presence flag will be changed in place, so simply retest it
if ( device == nullptr || device->isPresent() == false )
throw DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
if ( m_cb != nullptr )
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
if ( subFolder->device() == nullptr )
continue;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnDirectory( *subFolder ) == false )
continue;
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( m_probe->isHidden( *subFolder ) )
continue;
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get() );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != nullptr )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false );
subFoldersInDB.erase( it );
}
if ( m_probe->deleteUnseenFolders() == true )
{
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( const auto& f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs->files() )
{
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnFile( *fileFs ) == false )
continue;
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) || m_probe->forceFileRefresh() == true )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( fileFs );
files.erase( it );
}
if ( m_probe->deleteUnseenFiles() == false )
files.clear();
using FilesT = decltype( files );
using FilesToRemoveT = decltype( filesToRemove );
using FilesToAddT = decltype( filesToAdd );
sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
auto t = m_ml->getConn()->newTransaction();
for ( const auto& file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
{
auto media = f->media();
if ( media != nullptr )
media->removeFile( *f );
else
{
// If there is no media associated with this file, the file had to be removed through
// a trigger
assert( f->isDeleted() );
}
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addDiscoveredFile( p, parentFolder, parentFolderFs, m_probe->getPlaylistParent() );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
}, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
// But gracefully handle failure in release mode
if( deviceFs == nullptr )
return false;
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
if ( device == nullptr )
return false;
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true );
return true;
}
}
<commit_msg>FsDiscoverer: Add playlist deletion case<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "FsDiscoverer.h"
#include <algorithm>
#include <queue>
#include <utility>
#include "factory/FileSystemFactory.h"
#include "filesystem/IDevice.h"
#include "Media.h"
#include "File.h"
#include "Device.h"
#include "Folder.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "probe/CrawlerProbe.h"
#include "utils/Filename.h"
namespace
{
class DeviceRemovedException : public std::runtime_error
{
public:
DeviceRemovedException() noexcept
: std::runtime_error( "A device was removed during the discovery" )
{
}
};
}
namespace medialibrary
{
FsDiscoverer::FsDiscoverer( std::shared_ptr<factory::IFileSystem> fsFactory, MediaLibrary* ml, IMediaLibraryCb* cb, std::unique_ptr<prober::IProbe> probe )
: m_ml( ml )
, m_fsFactory( std::move( fsFactory ))
, m_cb( cb )
, m_probe( std::move( probe ) )
{
}
bool FsDiscoverer::discover( const std::string &entryPoint )
{
LOG_INFO( "Adding to discovery list: ", entryPoint );
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
std::shared_ptr<fs::IDirectory> fsDir = m_fsFactory->createDirectory( entryPoint );
auto fsDirMrl = fsDir->mrl(); // Saving MRL now since we might need it after fsDir is moved
auto f = Folder::fromMrl( m_ml, entryPoint );
// If the folder exists, we assume it will be handled by reload()
if ( f != nullptr )
return true;
try
{
if ( m_probe->proceedOnDirectory( *fsDir ) == false || m_probe->isHidden( *fsDir ) == true )
return true;
// Fetch files explicitly
fsDir->files();
return addFolder( std::move( fsDir ), m_probe->getFolderParent().get() );
}
catch ( std::system_error& ex )
{
LOG_WARN( entryPoint, " discovery aborted because of a filesystem error: ", ex.what() );
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
LOG_WARN( entryPoint, " discovery aborted (assuming blacklisted folder): ", ex.what() );
}
catch ( DeviceRemovedException& )
{
// Simply ignore, the device has already been marked as removed and the DB updated accordingly
LOG_INFO( "Discovery of ", fsDirMrl, " was stopped after the device was removed" );
}
return true;
}
void FsDiscoverer::reloadFolder( std::shared_ptr<Folder> f )
{
auto mrl = f->mrl();
auto folder = m_fsFactory->createDirectory( mrl );
assert( folder->device() != nullptr );
if ( folder->device() == nullptr )
return;
try
{
checkFolder( std::move( folder ), std::move( f ), false );
}
catch ( DeviceRemovedException& )
{
LOG_INFO( "Reloading of ", mrl, " was stopped after the device was removed" );
}
}
bool FsDiscoverer::reload()
{
LOG_INFO( "Reloading all folders" );
auto rootFolders = Folder::fetchRootFolders( m_ml );
for ( const auto& f : rootFolders )
reloadFolder( f );
return true;
}
bool FsDiscoverer::reload( const std::string& entryPoint )
{
if ( m_fsFactory->isMrlSupported( entryPoint ) == false )
return false;
LOG_INFO( "Reloading folder ", entryPoint );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_ERROR( "Can't reload ", entryPoint, ": folder wasn't found in database" );
return false;
}
reloadFolder( std::move( folder ) );
return true;
}
void FsDiscoverer::checkFolder( std::shared_ptr<fs::IDirectory> currentFolderFs,
std::shared_ptr<Folder> currentFolder,
bool newFolder ) const
{
try
{
// We already know of this folder, though it may now contain a .nomedia file.
// In this case, simply delete the folder.
if ( m_probe->isHidden( *currentFolderFs ) == true )
{
if ( newFolder == false )
m_ml->deleteFolder( *currentFolder );
return;
}
// Ensuring that the file fetching is done in this scope, to catch errors
currentFolderFs->files();
}
// Only check once for a system_error. They are bound to happen when we list the files/folders
// within, and IProbe::isHidden is the first place when this is done
catch ( std::system_error& ex )
{
LOG_WARN( "Failed to browse ", currentFolderFs->mrl(), ": ", ex.what() );
// Even when we're discovering a new folder, we want to rule out device removal as the cause of
// an IO error. If this is the cause, simply abort the discovery. All the folder we have
// discovered so far will be marked as non-present through sqlite hooks, and we'll resume the
// discovery when the device gets plugged back in
auto device = currentFolderFs->device();
// The device might not be present at all, and therefor we might miss a
// representation for it.
if ( device == nullptr || device->isRemovable() )
{
// If the device is removable/missing, check if it was indeed removed.
LOG_INFO( "The device containing ", currentFolderFs->mrl(), " is ",
device != nullptr ? "removable" : "not found",
". Refreshing device cache..." );
m_ml->refreshDevices( *m_fsFactory );
// If the device was missing, refresh our list of devices in case
// the device was plugged back and/or we missed a notification for it
if ( device == nullptr )
device = currentFolderFs->device();
// The device presence flag will be changed in place, so simply retest it
if ( device == nullptr || device->isPresent() == false )
throw DeviceRemovedException();
LOG_INFO( "Device was not removed" );
}
// However if the device isn't removable, we want to:
// - ignore it when we're discovering a new folder.
// - delete it when it was discovered in the past. This is likely to be due to a permission change
// as we would not check the folder if it wasn't present during the parent folder browsing
// but it might also be that we're checking an entry point.
// The error won't arise earlier, as we only perform IO when reading the folder from this function.
if ( newFolder == false )
{
// If we ever came across this folder, its content is now unaccessible: let's remove it.
m_ml->deleteFolder( *currentFolder );
}
return;
}
if ( m_cb != nullptr )
m_cb->onDiscoveryProgress( currentFolderFs->mrl() );
// Load the folders we already know of:
LOG_INFO( "Checking for modifications in ", currentFolderFs->mrl() );
// Don't try to fetch any potential sub folders if the folder was freshly added
std::vector<std::shared_ptr<Folder>> subFoldersInDB;
if ( newFolder == false )
subFoldersInDB = currentFolder->folders();
for ( const auto& subFolder : currentFolderFs->dirs() )
{
if ( subFolder->device() == nullptr )
continue;
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnDirectory( *subFolder ) == false )
continue;
auto it = std::find_if( begin( subFoldersInDB ), end( subFoldersInDB ), [&subFolder](const std::shared_ptr<Folder>& f) {
return f->mrl() == subFolder->mrl();
});
// We don't know this folder, it's a new one
if ( it == end( subFoldersInDB ) )
{
if ( m_probe->isHidden( *subFolder ) )
continue;
LOG_INFO( "New folder detected: ", subFolder->mrl() );
try
{
addFolder( subFolder, currentFolder.get() );
continue;
}
catch ( sqlite::errors::ConstraintViolation& ex )
{
// Best attempt to detect a foreign key violation, indicating the parent folders have been
// deleted due to blacklisting
if ( strstr( ex.what(), "foreign key" ) != nullptr )
{
LOG_WARN( "Creation of a folder failed because the parent is non existing: ", ex.what(),
". Assuming it was deleted due to blacklisting" );
return;
}
LOG_WARN( "Creation of a duplicated folder failed: ", ex.what(), ". Assuming it was blacklisted" );
continue;
}
}
auto folderInDb = *it;
// In any case, check for modifications, as a change related to a mountpoint might
// not update the folder modification date.
// Also, relying on the modification date probably isn't portable
checkFolder( subFolder, folderInDb, false );
subFoldersInDB.erase( it );
}
if ( m_probe->deleteUnseenFolders() == true )
{
// Now all folders we had in DB but haven't seen from the FS must have been deleted.
for ( const auto& f : subFoldersInDB )
{
LOG_INFO( "Folder ", f->mrl(), " not found in FS, deleting it" );
m_ml->deleteFolder( *f );
}
}
checkFiles( currentFolderFs, currentFolder );
LOG_INFO( "Done checking subfolders in ", currentFolderFs->mrl() );
}
void FsDiscoverer::checkFiles( std::shared_ptr<fs::IDirectory> parentFolderFs,
std::shared_ptr<Folder> parentFolder ) const
{
LOG_INFO( "Checking file in ", parentFolderFs->mrl() );
static const std::string req = "SELECT * FROM " + policy::FileTable::Name
+ " WHERE folder_id = ?";
auto files = File::fetchAll<File>( m_ml, req, parentFolder->id() );
std::vector<std::shared_ptr<fs::IFile>> filesToAdd;
std::vector<std::shared_ptr<File>> filesToRemove;
for ( const auto& fileFs: parentFolderFs->files() )
{
if ( m_probe->stopFileDiscovery() == true )
break;
if ( m_probe->proceedOnFile( *fileFs ) == false )
continue;
auto it = std::find_if( begin( files ), end( files ), [fileFs](const std::shared_ptr<File>& f) {
return f->mrl() == fileFs->mrl();
});
if ( it == end( files ) || m_probe->forceFileRefresh() == true )
{
if ( MediaLibrary::isExtensionSupported( fileFs->extension().c_str() ) == true )
filesToAdd.push_back( fileFs );
continue;
}
if ( fileFs->lastModificationDate() == (*it)->lastModificationDate() )
{
// Unchanged file
files.erase( it );
continue;
}
auto& file = (*it);
LOG_INFO( "Forcing file refresh ", fileFs->mrl() );
// Pre-cache the file's media, since we need it to remove. However, better doing it
// out of a write context, since that way, other threads can also read the database.
file->media();
filesToRemove.push_back( std::move( file ) );
filesToAdd.push_back( fileFs );
files.erase( it );
}
if ( m_probe->deleteUnseenFiles() == false )
files.clear();
using FilesT = decltype( files );
using FilesToRemoveT = decltype( filesToRemove );
using FilesToAddT = decltype( filesToAdd );
sqlite::Tools::withRetries( 3, [this, &parentFolder, &parentFolderFs]
( FilesT files, FilesToAddT filesToAdd, FilesToRemoveT filesToRemove ) {
auto t = m_ml->getConn()->newTransaction();
for ( const auto& file : files )
{
LOG_INFO( "File ", file->mrl(), " not found on filesystem, deleting it" );
auto media = file->media();
if ( media != nullptr && media->isDeleted() == false )
media->removeFile( *file );
else if ( file->isDeleted() == false )
{
// This is unexpected, as the file should have been deleted when the media was
// removed.
LOG_WARN( "Deleting a file without an associated media." );
file->destroy();
}
}
for ( auto& f : filesToRemove )
{
if ( f->type() == IFile::Type::Playlist )
{
f->destroy(); // Trigger cascade: delete Playlist, and playlist/media relations
continue;
}
auto media = f->media();
if ( media != nullptr )
media->removeFile( *f );
else
{
// If there is no media associated with this file, the file had to be removed through
// a trigger
assert( f->isDeleted() );
}
}
// Insert all files at once to avoid SQL write contention
for ( auto& p : filesToAdd )
m_ml->addDiscoveredFile( p, parentFolder, parentFolderFs, m_probe->getPlaylistParent() );
t->commit();
LOG_INFO( "Done checking files in ", parentFolderFs->mrl() );
}, std::move( files ), std::move( filesToAdd ), std::move( filesToRemove ) );
}
bool FsDiscoverer::addFolder( std::shared_ptr<fs::IDirectory> folder,
Folder* parentFolder ) const
{
auto deviceFs = folder->device();
// We are creating a folder, there has to be a device containing it.
assert( deviceFs != nullptr );
// But gracefully handle failure in release mode
if( deviceFs == nullptr )
return false;
auto device = Device::fromUuid( m_ml, deviceFs->uuid() );
if ( device == nullptr )
{
LOG_INFO( "Creating new device in DB ", deviceFs->uuid() );
device = Device::create( m_ml, deviceFs->uuid(),
utils::file::scheme( folder->mrl() ),
deviceFs->isRemovable() );
if ( device == nullptr )
return false;
}
auto f = Folder::create( m_ml, folder->mrl(),
parentFolder != nullptr ? parentFolder->id() : 0,
*device, *deviceFs );
if ( f == nullptr )
return false;
checkFolder( std::move( folder ), std::move( f ), true );
return true;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "matmethods.hpp"
#include "h5objcpp.hpp"
using namespace std;
int main(int argc, char* argv[]){
char* h5file;
char* outputfile;
H5File file;
int chunkstart, chunknum,Achunksize,Bchunksize;
int totalAchunks,totalBchunks,totalchunks;
int kfold,bsi;
if(argc!=9){
cerr<<"Usage:RMSE h5file chunkstart chunknum Achunksize Bchunksize bsi kfold outputfile"<<endl;
cerr<<"argc: "<<argc<<endl;
return(2);
}
h5file = argv[1];
chunkstart = atoi(argv[2]);
chunknum = atoi(argv[3]);
Achunksize = atoi(argv[4]);
Bchunksize = atoi(argv[5]);
bsi = atoi(argv[6]);
kfold = atoi(argv[7]);
outputfile = argv[8];
H5std_string Amatfield = "matA";
H5std_string Bmatfield= "matB";
try{
file = H5File(h5file,H5F_ACC_RDONLY);
}
catch(...)
{
cerr<<"Can't open file: "<<h5file<<endl;
throw 3;
}
vector <hsize_t> sizevec(2);
sizevec = getdims(file,Amatfield);
totalAchunks = ceil((double) sizevec[0]/(double) Achunksize);
sizevec = getdims(file,Bmatfield);
totalBchunks = ceil((double) sizevec[0]/(double) Bchunksize);
totalchunks = totalAchunks*totalBchunks;
mat A(sizevec[1],Achunksize);
mat B(sizevec[1],Bchunksize);
for( int i=0; i<chunknum; i++){
int Achunk = i/totalBchunks;
int Bchunk = i%totalBchunks;
readh5mat(file,Amatfield,Achunk,Achunksize,0,A.n_rows,A);
readh5mat(file,Bmatfield,Bchunk,Bchunksize,0,B.n_rows,B);
cout<<"Starting chunk: "<<i<<endl;
KfoldCV(A,B,kfold,i,bsi,outputfile);
}
return(0);
}
<commit_msg>removed needless diagnostics from computeRMSE<commit_after>#include <iostream>
#include "matmethods.hpp"
#include "h5objcpp.hpp"
using namespace std;
int main(int argc, char* argv[]){
char* h5file;
char* outputfile;
H5File file;
int chunkstart, chunknum,Achunksize,Bchunksize;
int totalAchunks,totalBchunks,totalchunks;
int kfold,bsi;
if(argc!=9){
cerr<<"Usage:RMSE h5file chunkstart chunknum Achunksize Bchunksize bsi kfold outputfile"<<endl;
cerr<<"argc: "<<argc<<endl;
return(2);
}
h5file = argv[1];
chunkstart = atoi(argv[2]);
chunknum = atoi(argv[3]);
Achunksize = atoi(argv[4]);
Bchunksize = atoi(argv[5]);
bsi = atoi(argv[6]);
kfold = atoi(argv[7]);
outputfile = argv[8];
H5std_string Amatfield = "matA";
H5std_string Bmatfield= "matB";
try{
file = H5File(h5file,H5F_ACC_RDONLY);
}
catch(...)
{
cerr<<"Can't open file: "<<h5file<<endl;
throw 3;
}
vector <hsize_t> sizevec(2);
sizevec = getdims(file,Amatfield);
totalAchunks = ceil((double) sizevec[0]/(double) Achunksize);
sizevec = getdims(file,Bmatfield);
totalBchunks = ceil((double) sizevec[0]/(double) Bchunksize);
totalchunks = totalAchunks*totalBchunks;
cout<<"Total Chunks="<<totalchunks<<endl;
mat A(sizevec[1],Achunksize);
mat B(sizevec[1],Bchunksize);
for( int i=0; i<chunknum; i++){
if(i>=totalchunks){
return(0);
}
int Achunk = i/totalBchunks;
int Bchunk = i%totalBchunks;
readh5mat(file,Amatfield,Achunk,Achunksize,0,A.n_rows,A);
readh5mat(file,Bmatfield,Bchunk,Bchunksize,0,B.n_rows,B);
cout<<"Starting chunk: "<<i<<endl;
KfoldCV(A,B,kfold,i,bsi,outputfile);
}
return(0);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick.Dialogs module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia 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.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickabstractdialog_p.h"
#include "qquickitem.h"
#include <private/qguiapplication_p.h>
#include <QWindow>
#include <QQmlComponent>
#include <QQuickWindow>
#include <qpa/qplatformintegration.h>
QT_BEGIN_NAMESPACE
QQmlComponent *QQuickAbstractDialog::m_decorationComponent(0);
QQuickAbstractDialog::QQuickAbstractDialog(QObject *parent)
: QObject(parent)
, m_parentWindow(0)
, m_visible(false)
, m_modality(Qt::WindowModal)
, m_qmlImplementation(0)
, m_dialogWindow(0)
, m_contentItem(0)
, m_windowDecoration(0)
, m_hasNativeWindows(QGuiApplicationPrivate::platformIntegration()->
hasCapability(QPlatformIntegration::MultipleWindows) &&
QGuiApplicationPrivate::platformIntegration()->
hasCapability(QPlatformIntegration::WindowManagement))
, m_hasAspiredPosition(false)
{
}
QQuickAbstractDialog::~QQuickAbstractDialog()
{
}
void QQuickAbstractDialog::setVisible(bool v)
{
if (m_visible == v) return;
m_visible = v;
if (helper()) {
if (v) {
Qt::WindowFlags flags = Qt::Dialog;
if (!title().isEmpty())
flags |= Qt::WindowTitleHint;
m_visible = helper()->show(flags, m_modality, parentWindow());
} else {
helper()->hide();
}
} else {
// For a pure QML implementation, there is no helper.
// But m_implementation is probably either an Item or a Window at this point.
if (!m_dialogWindow) {
m_dialogWindow = qobject_cast<QWindow *>(m_qmlImplementation);
if (!m_dialogWindow) {
m_contentItem = qobject_cast<QQuickItem *>(m_qmlImplementation);
if (m_contentItem) {
if (m_hasNativeWindows)
m_dialogWindow = m_contentItem->window();
// An Item-based dialog implementation doesn't come with a window, so
// we have to instantiate one iff the platform allows it.
if (!m_dialogWindow && m_hasNativeWindows) {
QQuickWindow *win = new QQuickWindow;
((QObject *)win)->setParent(this); // memory management only
m_dialogWindow = win;
m_contentItem->setParentItem(win->contentItem());
QSize minSize = QSize(m_contentItem->implicitWidth(), m_contentItem->implicitHeight());
QVariant minHeight = m_contentItem->property("minimumHeight");
if (minHeight.isValid()) {
if (minHeight.toInt() > minSize.height())
minSize.setHeight(minHeight.toDouble());
connect(m_contentItem, SIGNAL(minimumHeightChanged()), this, SLOT(minimumHeightChanged()));
}
QVariant minWidth = m_contentItem->property("minimumWidth");
if (minWidth.isValid()) {
if (minWidth.toInt() > minSize.width())
minSize.setWidth(minWidth.toInt());
connect(m_contentItem, SIGNAL(minimumWidthChanged()), this, SLOT(minimumWidthChanged()));
}
m_dialogWindow->setMinimumSize(minSize);
connect(win, SIGNAL(widthChanged(int)), this, SLOT(windowGeometryChanged()));
connect(win, SIGNAL(heightChanged(int)), this, SLOT(windowGeometryChanged()));
}
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
// If the platform does not support multiple windows, but the dialog is
// implemented as an Item, then try to decorate it as a fake window and make it visible.
if (parentItem && !m_dialogWindow && !m_windowDecoration) {
if (m_decorationComponent) {
if (m_decorationComponent->isLoading())
connect(m_decorationComponent, SIGNAL(statusChanged(QQmlComponent::Status)),
this, SLOT(decorationLoaded()));
else
decorationLoaded();
}
// Window decoration wasn't possible, so just reparent it into the scene
else {
m_contentItem->setParentItem(parentItem);
m_contentItem->setZ(10000);
}
}
}
}
if (m_dialogWindow) {
// "grow up" to the size and position expected to achieve
if (!m_sizeAspiration.isNull()) {
if (m_hasAspiredPosition)
m_dialogWindow->setGeometry(m_sizeAspiration);
else {
if (m_sizeAspiration.width() > 0)
m_dialogWindow->setWidth(m_sizeAspiration.width());
if (m_sizeAspiration.height() > 0)
m_dialogWindow->setHeight(m_sizeAspiration.height());
}
}
connect(m_dialogWindow, SIGNAL(visibleChanged(bool)), this, SLOT(visibleChanged(bool)));
connect(m_dialogWindow, SIGNAL(xChanged(int)), this, SLOT(setX(int)));
connect(m_dialogWindow, SIGNAL(yChanged(int)), this, SLOT(setY(int)));
connect(m_dialogWindow, SIGNAL(widthChanged(int)), this, SLOT(setWidth(int)));
connect(m_dialogWindow, SIGNAL(heightChanged(int)), this, SLOT(setHeight(int)));
}
}
if (m_windowDecoration) {
m_windowDecoration->setVisible(v);
} else if (m_dialogWindow) {
if (v) {
m_dialogWindow->setTransientParent(parentWindow());
m_dialogWindow->setTitle(title());
m_dialogWindow->setModality(m_modality);
}
m_dialogWindow->setVisible(v);
}
}
emit visibilityChanged();
}
void QQuickAbstractDialog::decorationLoaded()
{
bool ok = false;
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
while (parentItem->parentItem() && !parentItem->parentItem()->inherits("QQuickRootItem"))
parentItem = parentItem->parentItem();
if (m_decorationComponent->isError()) {
qWarning() << m_decorationComponent->errors();
} else {
QObject *decoration = m_decorationComponent->create();
m_windowDecoration = qobject_cast<QQuickItem *>(decoration);
if (m_windowDecoration) {
m_windowDecoration->setParentItem(parentItem);
// Give the window decoration its content to manage
QVariant contentVariant;
contentVariant.setValue<QQuickItem*>(m_contentItem);
m_windowDecoration->setProperty("content", contentVariant);
connect(m_windowDecoration, SIGNAL(dismissed()), this, SLOT(reject()));
ok = true;
} else {
qWarning() << m_decorationComponent->url() <<
"cannot be used as a window decoration because it's not an Item";
delete m_windowDecoration;
delete m_decorationComponent;
m_decorationComponent = 0;
}
}
// Window decoration wasn't possible, so just reparent it into the scene
if (!ok) {
m_contentItem->setParentItem(parentItem);
m_contentItem->setZ(10000);
}
}
void QQuickAbstractDialog::setModality(Qt::WindowModality m)
{
if (m_modality == m) return;
m_modality = m;
emit modalityChanged();
}
void QQuickAbstractDialog::accept()
{
setVisible(false);
emit accepted();
}
void QQuickAbstractDialog::reject()
{
setVisible(false);
emit rejected();
}
void QQuickAbstractDialog::visibleChanged(bool v)
{
m_visible = v;
emit visibilityChanged();
}
void QQuickAbstractDialog::windowGeometryChanged()
{
QQuickItem *content = qobject_cast<QQuickItem*>(m_qmlImplementation);
if (m_dialogWindow && content) {
content->setWidth(m_dialogWindow->width());
content->setHeight(m_dialogWindow->height());
}
}
void QQuickAbstractDialog::minimumWidthChanged()
{
m_dialogWindow->setMinimumWidth(qMax(m_contentItem->implicitWidth(),
m_contentItem->property("minimumWidth").toReal()));
}
void QQuickAbstractDialog::minimumHeightChanged()
{
m_dialogWindow->setMinimumHeight(qMax(m_contentItem->implicitHeight(),
m_contentItem->property("minimumHeight").toReal()));
}
QQuickWindow *QQuickAbstractDialog::parentWindow()
{
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
if (parentItem)
m_parentWindow = parentItem->window();
return m_parentWindow;
}
void QQuickAbstractDialog::setQmlImplementation(QObject *obj)
{
m_qmlImplementation = obj;
if (m_dialogWindow) {
disconnect(this, SLOT(visibleChanged(bool)));
// Can't necessarily delete because m_dialogWindow might have been provided by the QML.
m_dialogWindow = 0;
}
}
int QQuickAbstractDialog::x() const
{
if (m_dialogWindow)
return m_dialogWindow->x();
return m_sizeAspiration.x();
}
int QQuickAbstractDialog::y() const
{
if (m_dialogWindow)
return m_dialogWindow->y();
return m_sizeAspiration.y();
}
int QQuickAbstractDialog::width() const
{
if (m_dialogWindow)
return m_dialogWindow->width();
return m_sizeAspiration.width();
}
int QQuickAbstractDialog::height() const
{
if (m_dialogWindow)
return m_dialogWindow->height();
return m_sizeAspiration.height();
}
void QQuickAbstractDialog::setX(int arg)
{
m_hasAspiredPosition = true;
m_sizeAspiration.setX(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setX(arg);
} else if (m_contentItem) {
m_contentItem->setX(arg);
}
emit geometryChanged();
}
void QQuickAbstractDialog::setY(int arg)
{
m_hasAspiredPosition = true;
m_sizeAspiration.setY(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setY(arg);
} else if (m_contentItem) {
m_contentItem->setY(arg);
}
emit geometryChanged();
}
void QQuickAbstractDialog::setWidth(int arg)
{
m_sizeAspiration.setWidth(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setWidth(arg);
} else if (m_contentItem) {
m_contentItem->setWidth(arg);
}
emit geometryChanged();
}
void QQuickAbstractDialog::setHeight(int arg)
{
m_sizeAspiration.setHeight(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setHeight(arg);
} else if (m_contentItem) {
m_contentItem->setHeight(arg);
}
emit geometryChanged();
}
QT_END_NAMESPACE
<commit_msg>Dialogs: modality applies to fake window decorations too<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick.Dialogs module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, 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, Digia gives you certain additional
** rights. These rights are described in the Digia 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.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickabstractdialog_p.h"
#include "qquickitem.h"
#include <private/qguiapplication_p.h>
#include <QWindow>
#include <QQmlComponent>
#include <QQuickWindow>
#include <qpa/qplatformintegration.h>
QT_BEGIN_NAMESPACE
QQmlComponent *QQuickAbstractDialog::m_decorationComponent(0);
QQuickAbstractDialog::QQuickAbstractDialog(QObject *parent)
: QObject(parent)
, m_parentWindow(0)
, m_visible(false)
, m_modality(Qt::WindowModal)
, m_qmlImplementation(0)
, m_dialogWindow(0)
, m_contentItem(0)
, m_windowDecoration(0)
, m_hasNativeWindows(QGuiApplicationPrivate::platformIntegration()->
hasCapability(QPlatformIntegration::MultipleWindows) &&
QGuiApplicationPrivate::platformIntegration()->
hasCapability(QPlatformIntegration::WindowManagement))
, m_hasAspiredPosition(false)
{
}
QQuickAbstractDialog::~QQuickAbstractDialog()
{
}
void QQuickAbstractDialog::setVisible(bool v)
{
if (m_visible == v) return;
m_visible = v;
if (helper()) {
if (v) {
Qt::WindowFlags flags = Qt::Dialog;
if (!title().isEmpty())
flags |= Qt::WindowTitleHint;
m_visible = helper()->show(flags, m_modality, parentWindow());
} else {
helper()->hide();
}
} else {
// For a pure QML implementation, there is no helper.
// But m_implementation is probably either an Item or a Window at this point.
if (!m_dialogWindow) {
m_dialogWindow = qobject_cast<QWindow *>(m_qmlImplementation);
if (!m_dialogWindow) {
m_contentItem = qobject_cast<QQuickItem *>(m_qmlImplementation);
if (m_contentItem) {
if (m_hasNativeWindows)
m_dialogWindow = m_contentItem->window();
// An Item-based dialog implementation doesn't come with a window, so
// we have to instantiate one iff the platform allows it.
if (!m_dialogWindow && m_hasNativeWindows) {
QQuickWindow *win = new QQuickWindow;
((QObject *)win)->setParent(this); // memory management only
m_dialogWindow = win;
m_contentItem->setParentItem(win->contentItem());
QSize minSize = QSize(m_contentItem->implicitWidth(), m_contentItem->implicitHeight());
QVariant minHeight = m_contentItem->property("minimumHeight");
if (minHeight.isValid()) {
if (minHeight.toInt() > minSize.height())
minSize.setHeight(minHeight.toDouble());
connect(m_contentItem, SIGNAL(minimumHeightChanged()), this, SLOT(minimumHeightChanged()));
}
QVariant minWidth = m_contentItem->property("minimumWidth");
if (minWidth.isValid()) {
if (minWidth.toInt() > minSize.width())
minSize.setWidth(minWidth.toInt());
connect(m_contentItem, SIGNAL(minimumWidthChanged()), this, SLOT(minimumWidthChanged()));
}
m_dialogWindow->setMinimumSize(minSize);
connect(win, SIGNAL(widthChanged(int)), this, SLOT(windowGeometryChanged()));
connect(win, SIGNAL(heightChanged(int)), this, SLOT(windowGeometryChanged()));
}
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
// If the platform does not support multiple windows, but the dialog is
// implemented as an Item, then try to decorate it as a fake window and make it visible.
if (parentItem && !m_dialogWindow && !m_windowDecoration) {
if (m_decorationComponent) {
if (m_decorationComponent->isLoading())
connect(m_decorationComponent, SIGNAL(statusChanged(QQmlComponent::Status)),
this, SLOT(decorationLoaded()));
else
decorationLoaded();
}
// Window decoration wasn't possible, so just reparent it into the scene
else {
m_contentItem->setParentItem(parentItem);
m_contentItem->setZ(10000);
}
}
}
}
if (m_dialogWindow) {
// "grow up" to the size and position expected to achieve
if (!m_sizeAspiration.isNull()) {
if (m_hasAspiredPosition)
m_dialogWindow->setGeometry(m_sizeAspiration);
else {
if (m_sizeAspiration.width() > 0)
m_dialogWindow->setWidth(m_sizeAspiration.width());
if (m_sizeAspiration.height() > 0)
m_dialogWindow->setHeight(m_sizeAspiration.height());
}
}
connect(m_dialogWindow, SIGNAL(visibleChanged(bool)), this, SLOT(visibleChanged(bool)));
connect(m_dialogWindow, SIGNAL(xChanged(int)), this, SLOT(setX(int)));
connect(m_dialogWindow, SIGNAL(yChanged(int)), this, SLOT(setY(int)));
connect(m_dialogWindow, SIGNAL(widthChanged(int)), this, SLOT(setWidth(int)));
connect(m_dialogWindow, SIGNAL(heightChanged(int)), this, SLOT(setHeight(int)));
}
}
if (m_windowDecoration) {
m_windowDecoration->setProperty("dismissOnOuterClick", (m_modality == Qt::NonModal));
m_windowDecoration->setVisible(v);
} else if (m_dialogWindow) {
if (v) {
m_dialogWindow->setTransientParent(parentWindow());
m_dialogWindow->setTitle(title());
m_dialogWindow->setModality(m_modality);
}
m_dialogWindow->setVisible(v);
}
}
emit visibilityChanged();
}
void QQuickAbstractDialog::decorationLoaded()
{
bool ok = false;
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
while (parentItem->parentItem() && !parentItem->parentItem()->inherits("QQuickRootItem"))
parentItem = parentItem->parentItem();
if (m_decorationComponent->isError()) {
qWarning() << m_decorationComponent->errors();
} else {
QObject *decoration = m_decorationComponent->create();
m_windowDecoration = qobject_cast<QQuickItem *>(decoration);
if (m_windowDecoration) {
m_windowDecoration->setParentItem(parentItem);
// Give the window decoration its content to manage
QVariant contentVariant;
contentVariant.setValue<QQuickItem*>(m_contentItem);
m_windowDecoration->setProperty("content", contentVariant);
connect(m_windowDecoration, SIGNAL(dismissed()), this, SLOT(reject()));
ok = true;
} else {
qWarning() << m_decorationComponent->url() <<
"cannot be used as a window decoration because it's not an Item";
delete m_windowDecoration;
delete m_decorationComponent;
m_decorationComponent = 0;
}
}
// Window decoration wasn't possible, so just reparent it into the scene
if (!ok) {
m_contentItem->setParentItem(parentItem);
m_contentItem->setZ(10000);
}
}
void QQuickAbstractDialog::setModality(Qt::WindowModality m)
{
if (m_modality == m) return;
m_modality = m;
emit modalityChanged();
}
void QQuickAbstractDialog::accept()
{
setVisible(false);
emit accepted();
}
void QQuickAbstractDialog::reject()
{
setVisible(false);
emit rejected();
}
void QQuickAbstractDialog::visibleChanged(bool v)
{
m_visible = v;
emit visibilityChanged();
}
void QQuickAbstractDialog::windowGeometryChanged()
{
QQuickItem *content = qobject_cast<QQuickItem*>(m_qmlImplementation);
if (m_dialogWindow && content) {
content->setWidth(m_dialogWindow->width());
content->setHeight(m_dialogWindow->height());
}
}
void QQuickAbstractDialog::minimumWidthChanged()
{
m_dialogWindow->setMinimumWidth(qMax(m_contentItem->implicitWidth(),
m_contentItem->property("minimumWidth").toReal()));
}
void QQuickAbstractDialog::minimumHeightChanged()
{
m_dialogWindow->setMinimumHeight(qMax(m_contentItem->implicitHeight(),
m_contentItem->property("minimumHeight").toReal()));
}
QQuickWindow *QQuickAbstractDialog::parentWindow()
{
QQuickItem *parentItem = qobject_cast<QQuickItem *>(parent());
if (parentItem)
m_parentWindow = parentItem->window();
return m_parentWindow;
}
void QQuickAbstractDialog::setQmlImplementation(QObject *obj)
{
m_qmlImplementation = obj;
if (m_dialogWindow) {
disconnect(this, SLOT(visibleChanged(bool)));
// Can't necessarily delete because m_dialogWindow might have been provided by the QML.
m_dialogWindow = 0;
}
}
int QQuickAbstractDialog::x() const
{
if (m_dialogWindow)
return m_dialogWindow->x();
return m_sizeAspiration.x();
}
int QQuickAbstractDialog::y() const
{
if (m_dialogWindow)
return m_dialogWindow->y();
return m_sizeAspiration.y();
}
int QQuickAbstractDialog::width() const
{
if (m_dialogWindow)
return m_dialogWindow->width();
return m_sizeAspiration.width();
}
int QQuickAbstractDialog::height() const
{
if (m_dialogWindow)
return m_dialogWindow->height();
return m_sizeAspiration.height();
}
void QQuickAbstractDialog::setX(int arg)
{
m_hasAspiredPosition = true;
m_sizeAspiration.setX(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setX(arg);
} else if (m_contentItem) {
m_contentItem->setX(arg);
}
emit geometryChanged();
}
void QQuickAbstractDialog::setY(int arg)
{
m_hasAspiredPosition = true;
m_sizeAspiration.setY(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setY(arg);
} else if (m_contentItem) {
m_contentItem->setY(arg);
}
emit geometryChanged();
}
void QQuickAbstractDialog::setWidth(int arg)
{
m_sizeAspiration.setWidth(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setWidth(arg);
} else if (m_contentItem) {
m_contentItem->setWidth(arg);
}
emit geometryChanged();
}
void QQuickAbstractDialog::setHeight(int arg)
{
m_sizeAspiration.setHeight(arg);
if (helper()) {
// TODO
} else if (m_dialogWindow) {
if (sender() != m_dialogWindow)
m_dialogWindow->setHeight(arg);
} else if (m_contentItem) {
m_contentItem->setHeight(arg);
}
emit geometryChanged();
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>#include "AssetSyncOutputObject.h"
#include <maya/MGlobal.h>
#include <maya/MPlug.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnDagNode.h>
#include "AssetNode.h"
#include "AssetSyncOutputGeoPart.h"
#include "AssetSyncOutputInstance.h"
AssetSyncOutputObject::AssetSyncOutputObject(
const MPlug &outputPlug,
const MObject &assetNodeObj )
: myOutputPlug(outputPlug),
myAssetNodeObj(assetNodeObj)
{}
AssetSyncOutputObject::~AssetSyncOutputObject()
{
for(AssetSyncs::const_iterator it = myAssetSyncs.begin();
it != myAssetSyncs.end();
it++)
{
delete *it;
}
myAssetSyncs.clear();
}
MStatus
AssetSyncOutputObject::doIt()
{
MStatus status;
// Create our parts.
// An object just contains a number of parts, and no
// other information.
MFnDependencyNode assetNodeFn(myAssetNodeObj, &status);
// Parts
MPlug partsPlug = myOutputPlug.child(AssetNode::outputParts);
int partCount = partsPlug.evaluateNumElements(&status);
CHECK_MSTATUS_AND_RETURN_IT(status);
for (int i=0; i<partCount; i++)
{
AssetSync* sync = new AssetSyncOutputGeoPart(partsPlug[i], myAssetNodeObj);
sync->doIt();
myAssetSyncs.push_back(sync);
}
#if MAYA_API_VERSION >= 201400
createFluidShape();
#endif
return MStatus::kSuccess;
}
#if MAYA_API_VERSION >= 201400
MStatus
AssetSyncOutputObject::createFluidShapeNode(MObject& transform, MObject& fluid)
{
MStatus status;
transform = myDagModifier.createNode("transform", myAssetNodeObj, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
// TODO: name
status = myDagModifier.renameNode(transform, "fluid_transform");
CHECK_MSTATUS_AND_RETURN_IT(status);
fluid = myDagModifier.createNode("fluidShape", transform, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
return status;
}
MStatus
AssetSyncOutputObject::createFluidShape()
{
MStatus status;
// Look for density.
// Once we've found the first density, look again through everything
// for any volumes which share a transform with the first density,
// and add them to the fluidShape.
MPlug partsPlug = myOutputPlug.child(AssetNode::outputParts);
int partCount = partsPlug.evaluateNumElements(&status);
CHECK_MSTATUS_AND_RETURN_IT(status);
// Find density
bool hasDensity = false;
MPlug densityVolume;
for (int i=0; i<partCount; i++)
{
MPlug outputVolume = partsPlug[i].child(AssetNode::outputPartVolume);
MPlug outputPartName = partsPlug[i].child(AssetNode::outputPartName);
MPlug outputVolumeName = outputVolume.child(AssetNode::outputPartVolumeName);
MString name = outputVolumeName.asString();
if (name == "density")
{
hasDensity = true;
densityVolume = outputVolume;
break;
}
}
if (!hasDensity)
return MStatus::kSuccess;
MObject transform, fluid;
createFluidShapeNode(transform, fluid);
MPlug densityTransform = densityVolume.child(AssetNode::outputPartVolumeTransform);
MFnDependencyNode partVolumeFn(fluid, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
MFnDependencyNode partFluidTransformFn(transform, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
bool doneDensity = false;
bool doneTemperature = false;
for (int i=0; i<partCount; i++)
{
MPlug outputVolume = partsPlug[i].child(AssetNode::outputPartVolume);
MPlug outputVolumeName = outputVolume.child(AssetNode::outputPartVolumeName);
MPlug outputVolumeTransform = outputVolume.child(AssetNode::outputPartVolumeTransform);
// If the transform of the volumes are different, we don't want
// to group them together.
if (outputVolumeTransform != densityTransform.attribute())
continue;
MPlug srcPlug = outputVolume.child(AssetNode::outputPartVolumeGrid);
MString name = outputVolumeName.asString();
if (name == "density" && !doneDensity)
{
status = myDagModifier.connect(srcPlug, partVolumeFn.findPlug("inDensity"));
CHECK_MSTATUS_AND_RETURN_IT(status);
doneDensity = true;
}
else if (name == "temperature" && !doneTemperature)
{
status = myDagModifier.connect(srcPlug, partVolumeFn.findPlug("inTemperature"));
CHECK_MSTATUS_AND_RETURN_IT(status);
doneTemperature = true;
}
}
// Connect the transform, resolution, dimensions, and playFromCache
{
MPlug srcPlug;
MPlug dstPlug;
MPlug densityTransform = densityVolume.child(AssetNode::outputPartVolumeTransform);
srcPlug = densityTransform.child(AssetNode::outputPartVolumeTranslate);
dstPlug = partFluidTransformFn.findPlug("translate");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = densityTransform.child(AssetNode::outputPartVolumeRotate);
dstPlug = partFluidTransformFn.findPlug("rotate");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = densityTransform.child(AssetNode::outputPartVolumeScale);
dstPlug = partFluidTransformFn.findPlug("scale");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = densityVolume.child(AssetNode::outputPartVolumeRes);
dstPlug = partVolumeFn.findPlug("resolution");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
// Connect the dimensions and resolution
dstPlug = partVolumeFn.findPlug("dimensions");
// Connecting compound attribute to fluidShape.dimensions causes
// infinite recursion. Probably a Maya bug. Workaround it by connecting
// individual child attributes instead.
//status = myDagModifier.connect(srcPlug, dstPlug);
status = myDagModifier.connect(srcPlug.child(0), dstPlug.child(0));
status = myDagModifier.connect(srcPlug.child(1), dstPlug.child(1));
status = myDagModifier.connect(srcPlug.child(2), dstPlug.child(2));
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = myOutputPlug.child(AssetNode::outputObjectFluidFromAsset);
dstPlug = partVolumeFn.findPlug("playFromCache");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
}
status = myDagModifier.doIt();
CHECK_MSTATUS_AND_RETURN_IT(status);
}
#endif
MStatus
AssetSyncOutputObject::undoIt()
{
for(AssetSyncs::reverse_iterator iter = myAssetSyncs.rbegin();
iter != myAssetSyncs.rend();
iter++)
{
(*iter)->undoIt();
}
myDagModifier.undoIt();
return MStatus::kSuccess;
}
MStatus
AssetSyncOutputObject::redoIt()
{
myDagModifier.doIt();
for(AssetSyncs::iterator iter = myAssetSyncs.begin();
iter != myAssetSyncs.end();
iter++)
{
(*iter)->redoIt();
}
return MStatus::kSuccess;
}
<commit_msg>Adjust fluid detecting code to also detect temperature and fuel<commit_after>#include "AssetSyncOutputObject.h"
#include <maya/MGlobal.h>
#include <maya/MPlug.h>
#include <maya/MFnDependencyNode.h>
#include <maya/MFnDagNode.h>
#include "AssetNode.h"
#include "AssetSyncOutputGeoPart.h"
#include "AssetSyncOutputInstance.h"
AssetSyncOutputObject::AssetSyncOutputObject(
const MPlug &outputPlug,
const MObject &assetNodeObj )
: myOutputPlug(outputPlug),
myAssetNodeObj(assetNodeObj)
{}
AssetSyncOutputObject::~AssetSyncOutputObject()
{
for(AssetSyncs::const_iterator it = myAssetSyncs.begin();
it != myAssetSyncs.end();
it++)
{
delete *it;
}
myAssetSyncs.clear();
}
MStatus
AssetSyncOutputObject::doIt()
{
MStatus status;
// Create our parts.
// An object just contains a number of parts, and no
// other information.
MFnDependencyNode assetNodeFn(myAssetNodeObj, &status);
// Parts
MPlug partsPlug = myOutputPlug.child(AssetNode::outputParts);
int partCount = partsPlug.evaluateNumElements(&status);
CHECK_MSTATUS_AND_RETURN_IT(status);
for (int i=0; i<partCount; i++)
{
AssetSync* sync = new AssetSyncOutputGeoPart(partsPlug[i], myAssetNodeObj);
sync->doIt();
myAssetSyncs.push_back(sync);
}
#if MAYA_API_VERSION >= 201400
createFluidShape();
#endif
return MStatus::kSuccess;
}
#if MAYA_API_VERSION >= 201400
MStatus
AssetSyncOutputObject::createFluidShapeNode(MObject& transform, MObject& fluid)
{
MStatus status;
transform = myDagModifier.createNode("transform", myAssetNodeObj, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
// TODO: name
status = myDagModifier.renameNode(transform, "fluid_transform");
CHECK_MSTATUS_AND_RETURN_IT(status);
fluid = myDagModifier.createNode("fluidShape", transform, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
return status;
}
MStatus
AssetSyncOutputObject::createFluidShape()
{
MStatus status;
MPlug partsPlug = myOutputPlug.child(AssetNode::outputParts);
int partCount = partsPlug.evaluateNumElements(&status);
CHECK_MSTATUS_AND_RETURN_IT(status);
// Look for specific volume names. Once we've found the first reference
// volume, look again through everything for any volumes which share a
// transform with the first reference volume, and add them to the
// fluidShape.
bool hasFluid = false;
MPlug referenceVolume;
for (int i=0; i<partCount; i++)
{
MPlug outputVolume = partsPlug[i].child(AssetNode::outputPartVolume);
MPlug outputPartName = partsPlug[i].child(AssetNode::outputPartName);
MPlug outputVolumeName = outputVolume.child(AssetNode::outputPartVolumeName);
MString name = outputVolumeName.asString();
if (name == "density"
|| name == "temperature"
|| name == "fuel")
{
hasFluid = true;
referenceVolume = outputVolume;
break;
}
}
if (!hasFluid)
return MStatus::kSuccess;
MObject transform, fluid;
createFluidShapeNode(transform, fluid);
MPlug referenceTransform = referenceVolume.child(AssetNode::outputPartVolumeTransform);
MFnDependencyNode partVolumeFn(fluid, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
MFnDependencyNode partFluidTransformFn(transform, &status);
CHECK_MSTATUS_AND_RETURN_IT(status);
bool doneDensity = false;
bool doneTemperature = false;
bool doneFuel = false;
for (int i=0; i<partCount; i++)
{
MPlug outputVolume = partsPlug[i].child(AssetNode::outputPartVolume);
MPlug outputVolumeName = outputVolume.child(AssetNode::outputPartVolumeName);
MPlug outputVolumeTransform = outputVolume.child(AssetNode::outputPartVolumeTransform);
// If the transform of the volumes are different, we don't want
// to group them together.
if (outputVolumeTransform != referenceTransform.attribute())
continue;
MPlug srcPlug = outputVolume.child(AssetNode::outputPartVolumeGrid);
MString name = outputVolumeName.asString();
if (name == "density" && !doneDensity)
{
status = myDagModifier.connect(srcPlug, partVolumeFn.findPlug("inDensity"));
CHECK_MSTATUS_AND_RETURN_IT(status);
status = myDagModifier.newPlugValueInt(
partVolumeFn.findPlug("densityMethod"),
2
);
CHECK_MSTATUS_AND_RETURN_IT(status);
doneDensity = true;
}
else if (name == "temperature" && !doneTemperature)
{
status = myDagModifier.connect(srcPlug, partVolumeFn.findPlug("inTemperature"));
CHECK_MSTATUS_AND_RETURN_IT(status);
status = myDagModifier.newPlugValueInt(
partVolumeFn.findPlug("temperatureMethod"),
2
);
CHECK_MSTATUS_AND_RETURN_IT(status);
doneTemperature = true;
}
else if (name == "fuel" && !doneFuel)
{
status = myDagModifier.connect(srcPlug, partVolumeFn.findPlug("inReaction"));
CHECK_MSTATUS_AND_RETURN_IT(status);
status = myDagModifier.newPlugValueInt(
partVolumeFn.findPlug("fuelMethod"),
2
);
CHECK_MSTATUS_AND_RETURN_IT(status);
doneTemperature = true;
}
}
// Connect the transform, resolution, dimensions, and playFromCache
{
MPlug srcPlug;
MPlug dstPlug;
MPlug densityTransform = referenceVolume.child(AssetNode::outputPartVolumeTransform);
srcPlug = densityTransform.child(AssetNode::outputPartVolumeTranslate);
dstPlug = partFluidTransformFn.findPlug("translate");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = densityTransform.child(AssetNode::outputPartVolumeRotate);
dstPlug = partFluidTransformFn.findPlug("rotate");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = densityTransform.child(AssetNode::outputPartVolumeScale);
dstPlug = partFluidTransformFn.findPlug("scale");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = referenceVolume.child(AssetNode::outputPartVolumeRes);
dstPlug = partVolumeFn.findPlug("resolution");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
// Connect the dimensions and resolution
dstPlug = partVolumeFn.findPlug("dimensions");
// Connecting compound attribute to fluidShape.dimensions causes
// infinite recursion. Probably a Maya bug. Workaround it by connecting
// individual child attributes instead.
//status = myDagModifier.connect(srcPlug, dstPlug);
status = myDagModifier.connect(srcPlug.child(0), dstPlug.child(0));
status = myDagModifier.connect(srcPlug.child(1), dstPlug.child(1));
status = myDagModifier.connect(srcPlug.child(2), dstPlug.child(2));
CHECK_MSTATUS_AND_RETURN_IT(status);
srcPlug = myOutputPlug.child(AssetNode::outputObjectFluidFromAsset);
dstPlug = partVolumeFn.findPlug("playFromCache");
status = myDagModifier.connect(srcPlug, dstPlug);
CHECK_MSTATUS_AND_RETURN_IT(status);
}
status = myDagModifier.doIt();
CHECK_MSTATUS_AND_RETURN_IT(status);
}
#endif
MStatus
AssetSyncOutputObject::undoIt()
{
for(AssetSyncs::reverse_iterator iter = myAssetSyncs.rbegin();
iter != myAssetSyncs.rend();
iter++)
{
(*iter)->undoIt();
}
myDagModifier.undoIt();
return MStatus::kSuccess;
}
MStatus
AssetSyncOutputObject::redoIt()
{
myDagModifier.doIt();
for(AssetSyncs::iterator iter = myAssetSyncs.begin();
iter != myAssetSyncs.end();
iter++)
{
(*iter)->redoIt();
}
return MStatus::kSuccess;
}
<|endoftext|> |
<commit_before><commit_msg>planning: fix obstacle_test compile warning.<commit_after><|endoftext|> |
<commit_before>#include "vtrc-channels.h"
#include "vtrc-protocol-layer-s.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-closure-holder.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
//#include "vtrc-chrono.h"
#include "vtrc-bind.h"
namespace vtrc { namespace server {
namespace {
namespace gpb = google::protobuf;
typedef vtrc_rpc_lowlevel::lowlevel_unit lowlevel_unit_type;
typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr;
void config_message( common::connection_iface_sptr cl,
lowlevel_unit_sptr llu, unsigned mess_type )
{
const common::call_context
*c(common::call_context::get(cl.get( )));
switch( mess_type ) {
case vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK:
if( c ) {
llu->mutable_info( )->set_message_type( mess_type );
llu->set_id( c->get_lowlevel_message( )->id( ) );
break;
} else {
mess_type = vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT;
}
case vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT:
default:
llu->mutable_info( )->set_message_type( mess_type );
llu->set_id( cl->get_protocol( ).next_index( ) );
break;
};
}
class unicast_channel: public common_channel {
common::connection_iface_wptr client_;
const unsigned message_type_;
const bool disable_wait_;
public:
unicast_channel( common::connection_iface_sptr c,
unsigned mess_type, bool disable_wait)
:client_(c)
,message_type_(mess_type)
,disable_wait_(disable_wait)
{}
void send_message(lowlevel_unit_sptr llu,
const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* /*request*/,
google::protobuf::Message* response,
google::protobuf::Closure* done )
{
common::closure_holder clhl(done);
common::connection_iface_sptr clk(client_.lock( ));
if( clk.get( ) == NULL ) {
throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,
"Connection lost");
}
const vtrc_rpc_lowlevel::options &call_opt
( clk->get_protocol( ).get_method_options(method) );
config_message( clk, llu, message_type_ );
const gpb::uint64 call_id = llu->id( );
llu->set_id(call_id);
if( disable_wait_ )
llu->mutable_opt( )->set_wait(false);
else
llu->mutable_opt( )->set_wait(call_opt.wait( ));
//// WAITABLE CALL
if( llu->opt( ).wait( ) ) {
process_waitable_call( call_id, llu, response,
clk, call_opt );
} else { // NOT WAITABLE CALL
clk->get_protocol( ).call_rpc_method( *llu );
}
}
};
class broadcast_channel: public common_channel {
typedef broadcast_channel this_type;
vtrc::weak_ptr<common::connection_list> clients_;
common::connection_iface_wptr sender_;
const unsigned message_type_;
public:
broadcast_channel( vtrc::weak_ptr<common::connection_list> clients,
unsigned mess_type)
:clients_(clients)
,message_type_(mess_type)
{ }
broadcast_channel( vtrc::weak_ptr<common::connection_list> clients,
unsigned mess_type,
common::connection_iface_wptr sender)
:clients_(clients)
,message_type_(mess_type)
,sender_(sender)
{ }
static
bool send_to_client( common::connection_iface_sptr next,
common::connection_iface_sptr sender,
lowlevel_unit_sptr mess,
unsigned mess_type)
{
if( !sender || (sender != next) ) {
config_message( next, mess, mess_type );
next->get_protocol( ).call_rpc_method( *mess );
}
return true;
}
void send_message(lowlevel_unit_sptr llu,
const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* /*request*/,
google::protobuf::Message* response,
google::protobuf::Closure* done )
{
common::closure_holder clhl(done);
common::connection_iface_sptr clk(sender_.lock( ));
vtrc::shared_ptr<common::connection_list>
lck_list(clients_.lock( ));
if( !lck_list ) {
throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,
"Clients lost");
}
llu->mutable_info( )->set_message_type( message_type_ );
llu->mutable_opt( )->set_wait( false );
// const vtrc_rpc_lowlevel::options &call_opt
// ( clk->get_protocol( ).get_method_options(method));
lck_list->foreach_while(
vtrc::bind( &this_type::send_to_client, _1,
clk, llu, message_type_) );
}
};
}
namespace channels {
namespace unicast {
common_channel *create_event_channel( common::connection_iface_sptr c,
bool disable_wait)
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT);
return new unicast_channel(c, message_type, disable_wait);
}
common_channel *create_callback_channel(common::connection_iface_sptr c,
bool disable_wait)
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK);
return new unicast_channel(c, message_type, disable_wait);
}
}
namespace broadcast {
common_channel *create_event_channel(
vtrc::shared_ptr<common::connection_list> cl,
common::connection_iface_sptr c )
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT);
return new broadcast_channel(cl->weak_from_this( ),
message_type, c->weak_from_this( ));
}
common_channel *create_event_channel(
vtrc::shared_ptr<common::connection_list> cl )
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT);
return new broadcast_channel(cl->weak_from_this( ), message_type );
}
common_channel *create_callback_channel(
vtrc::shared_ptr<common::connection_list> cl,
common::connection_iface_sptr c )
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK);
return new broadcast_channel(cl->weak_from_this( ),
message_type, c->weak_from_this( ));
}
common_channel *create_callback_channel(
vtrc::shared_ptr<common::connection_list> cl)
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK);
return new broadcast_channel(cl->weak_from_this( ), message_type );
}
}
}
}}
<commit_msg>proto<commit_after>#include "vtrc-channels.h"
#include "vtrc-protocol-layer-s.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-closure-holder.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
//#include "vtrc-chrono.h"
#include "vtrc-bind.h"
namespace vtrc { namespace server {
namespace {
namespace gpb = google::protobuf;
typedef vtrc_rpc_lowlevel::lowlevel_unit lowlevel_unit_type;
typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr;
void configure_message( common::connection_iface_sptr cl,
lowlevel_unit_sptr llu, unsigned mess_type )
{
const common::call_context
*c(common::call_context::get(cl.get( )));
switch( mess_type ) {
case vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK:
if( c ) {
llu->mutable_info( )->set_message_type( mess_type );
llu->set_id( c->get_lowlevel_message( )->id( ) );
break;
} else {
mess_type = vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT;
}
case vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT:
default:
llu->mutable_info( )->set_message_type( mess_type );
llu->set_id( cl->get_protocol( ).next_index( ) );
break;
};
}
class unicast_channel: public common_channel {
common::connection_iface_wptr client_;
const unsigned message_type_;
const bool disable_wait_;
public:
unicast_channel( common::connection_iface_sptr c,
unsigned mess_type, bool disable_wait)
:client_(c)
,message_type_(mess_type)
,disable_wait_(disable_wait)
{}
void send_message(lowlevel_unit_sptr llu,
const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* /*request*/,
google::protobuf::Message* response,
google::protobuf::Closure* done )
{
common::closure_holder clhl(done);
common::connection_iface_sptr clk(client_.lock( ));
if( clk.get( ) == NULL ) {
throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,
"Connection lost");
}
const vtrc_rpc_lowlevel::options &call_opt
( clk->get_protocol( ).get_method_options(method) );
configure_message( clk, llu, message_type_ );
const gpb::uint64 call_id = llu->id( );
llu->set_id(call_id);
if( disable_wait_ )
llu->mutable_opt( )->set_wait(false);
else
llu->mutable_opt( )->set_wait(call_opt.wait( ));
//// WAITABLE CALL
if( llu->opt( ).wait( ) ) {
process_waitable_call( call_id, llu, response,
clk, call_opt );
} else { // NOT WAITABLE CALL
clk->get_protocol( ).call_rpc_method( *llu );
}
}
};
class broadcast_channel: public common_channel {
typedef broadcast_channel this_type;
vtrc::weak_ptr<common::connection_list> clients_;
common::connection_iface_wptr sender_;
const unsigned message_type_;
public:
broadcast_channel( vtrc::weak_ptr<common::connection_list> clients,
unsigned mess_type)
:clients_(clients)
,message_type_(mess_type)
{ }
broadcast_channel( vtrc::weak_ptr<common::connection_list> clients,
unsigned mess_type,
common::connection_iface_wptr sender)
:clients_(clients)
,message_type_(mess_type)
,sender_(sender)
{ }
static
bool send_to_client( common::connection_iface_sptr next,
common::connection_iface_sptr sender,
lowlevel_unit_sptr mess,
unsigned mess_type)
{
if( (sender != next) ) {
configure_message( next, mess, mess_type );
next->get_protocol( ).call_rpc_method( *mess );
}
return true;
}
static
bool send_to_client2( common::connection_iface_sptr next,
common::connection_iface_sptr sender,
lowlevel_unit_sptr mess,
unsigned mess_type)
{
configure_message( next, mess, mess_type );
next->get_protocol( ).call_rpc_method( *mess );
return true;
}
void send_message(lowlevel_unit_sptr llu,
const google::protobuf::MethodDescriptor* method,
google::protobuf::RpcController* controller,
const google::protobuf::Message* /*request*/,
google::protobuf::Message* response,
google::protobuf::Closure* done )
{
common::closure_holder clhl(done);
common::connection_iface_sptr clk(sender_.lock( ));
vtrc::shared_ptr<common::connection_list>
lck_list(clients_.lock( ));
if( !lck_list ) {
throw vtrc::common::exception( vtrc_errors::ERR_CHANNEL,
"Clients lost");
}
llu->mutable_info( )->set_message_type( message_type_ );
llu->mutable_opt( )->set_wait( false );
// const vtrc_rpc_lowlevel::options &call_opt
// ( clk->get_protocol( ).get_method_options(method));
if( clk ) {
lck_list->foreach_while(
vtrc::bind( &this_type::send_to_client, _1,
clk, llu, message_type_) );
} else {
lck_list->foreach_while(
vtrc::bind( &this_type::send_to_client2, _1,
clk, llu, message_type_) );
}
}
};
}
namespace channels {
namespace unicast {
common_channel *create_event_channel( common::connection_iface_sptr c,
bool disable_wait)
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT);
return new unicast_channel(c, message_type, disable_wait);
}
common_channel *create_callback_channel(common::connection_iface_sptr c,
bool disable_wait)
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK);
return new unicast_channel(c, message_type, disable_wait);
}
}
namespace broadcast {
common_channel *create_event_channel(
vtrc::shared_ptr<common::connection_list> cl,
common::connection_iface_sptr c )
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT);
return new broadcast_channel(cl->weak_from_this( ),
message_type, c->weak_from_this( ));
}
common_channel *create_event_channel(
vtrc::shared_ptr<common::connection_list> cl )
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_EVENT);
return new broadcast_channel(cl->weak_from_this( ), message_type );
}
common_channel *create_callback_channel(
vtrc::shared_ptr<common::connection_list> cl,
common::connection_iface_sptr c )
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK);
return new broadcast_channel(cl->weak_from_this( ),
message_type, c->weak_from_this( ));
}
common_channel *create_callback_channel(
vtrc::shared_ptr<common::connection_list> cl)
{
static const unsigned message_type
(vtrc_rpc_lowlevel::message_info::MESSAGE_CALLBACK);
return new broadcast_channel(cl->weak_from_this( ), message_type );
}
}
}
}}
<|endoftext|> |
<commit_before>#include "perf_precomp.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/opencv_modules.hpp"
#include "opencv2/flann.hpp"
namespace opencv_test
{
using namespace perf;
typedef TestBaseWithParam<size_t> FeaturesFinderVec;
typedef TestBaseWithParam<string> match;
typedef tuple<string, int> matchVector_t;
typedef TestBaseWithParam<matchVector_t> matchVector;
#define NUMBER_IMAGES testing::Values(1, 5, 20)
#define SURF_MATCH_CONFIDENCE 0.65f
#define ORB_MATCH_CONFIDENCE 0.3f
#define WORK_MEGAPIX 0.6
#ifdef HAVE_OPENCV_XFEATURES2D
#define TEST_DETECTORS testing::Values("surf", "orb")
#else
#define TEST_DETECTORS testing::Values<string>("orb")
#endif
PERF_TEST_P(FeaturesFinderVec, ParallelFeaturesFinder, NUMBER_IMAGES)
{
Mat img = imread( getDataPath("stitching/a1.png") );
vector<Mat> imgs(GetParam(), img);
vector<detail::ImageFeatures> features(imgs.size());
Ptr<detail::FeaturesFinder> featuresFinder = makePtr<detail::OrbFeaturesFinder>();
TEST_CYCLE()
{
(*featuresFinder)(imgs, features);
}
SANITY_CHECK_NOTHING();
}
PERF_TEST_P(FeaturesFinderVec, SerialFeaturesFinder, NUMBER_IMAGES)
{
Mat img = imread( getDataPath("stitching/a1.png") );
vector<Mat> imgs(GetParam(), img);
vector<detail::ImageFeatures> features(imgs.size());
Ptr<detail::FeaturesFinder> featuresFinder = makePtr<detail::OrbFeaturesFinder>();
TEST_CYCLE()
{
for (size_t i = 0; i < imgs.size(); ++i)
(*featuresFinder)(imgs[i], features[i]);
}
SANITY_CHECK_NOTHING();
}
PERF_TEST_P( match, bestOf2Nearest, TEST_DETECTORS)
{
Mat img1, img1_full = imread( getDataPath("stitching/boat1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/boat2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
if (GetParam() == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, SURF_MATCH_CONFIDENCE);
}
else if (GetParam() == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << GetParam();
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
detail::MatchesInfo pairwise_matches;
declare.in(features1.descriptors, features2.descriptors);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features1, features2, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
Mat dist (pairwise_matches.H, Range::all(), Range(2, 3));
Mat R (pairwise_matches.H, Range::all(), Range(0, 2));
// separate transform matrix, use lower error on rotations
SANITY_CHECK(dist, 1., ERROR_ABSOLUTE);
SANITY_CHECK(R, .06, ERROR_ABSOLUTE);
}
PERF_TEST_P( matchVector, bestOf2NearestVectorFeatures, testing::Combine(
TEST_DETECTORS,
testing::Values(2, 4, 8))
)
{
Mat img1, img1_full = imread( getDataPath("stitching/boat1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/boat2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
string detectorName = get<0>(GetParam());
int featuresVectorSize = get<1>(GetParam());
if (detectorName == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, SURF_MATCH_CONFIDENCE);
}
else if (detectorName == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << get<0>(GetParam());
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
vector<detail::ImageFeatures> features;
vector<detail::MatchesInfo> pairwise_matches;
for(int i = 0; i < featuresVectorSize/2; i++)
{
features.push_back(features1);
features.push_back(features2);
}
declare.time(200);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
size_t matches_count = 0;
for (size_t i = 0; i < pairwise_matches.size(); ++i)
{
if (pairwise_matches[i].src_img_idx < 0)
continue;
EXPECT_GT(pairwise_matches[i].matches.size(), 95u);
EXPECT_FALSE(pairwise_matches[i].H.empty());
++matches_count;
}
EXPECT_GT(matches_count, 0u);
SANITY_CHECK_NOTHING();
}
PERF_TEST_P( match, affineBestOf2Nearest, TEST_DETECTORS)
{
Mat img1, img1_full = imread( getDataPath("stitching/s1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/s2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
if (GetParam() == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, SURF_MATCH_CONFIDENCE);
}
else if (GetParam() == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << GetParam();
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
detail::MatchesInfo pairwise_matches;
declare.in(features1.descriptors, features2.descriptors);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features1, features2, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
// separate rotation and translation in transform matrix
Mat T (pairwise_matches.H, Range(0, 2), Range(2, 3));
Mat R (pairwise_matches.H, Range(0, 2), Range(0, 2));
Mat h (pairwise_matches.H, Range(2, 3), Range::all());
SANITY_CHECK(T, 5, ERROR_ABSOLUTE); // allow 5 pixels diff in translations
SANITY_CHECK(R, .01, ERROR_ABSOLUTE); // rotations must be more precise
// last row should be precisely (0, 0, 1) as it is just added for representation in homogeneous
// coordinates
EXPECT_DOUBLE_EQ(h.at<double>(0), 0.);
EXPECT_DOUBLE_EQ(h.at<double>(1), 0.);
EXPECT_DOUBLE_EQ(h.at<double>(2), 1.);
}
PERF_TEST_P( matchVector, affineBestOf2NearestVectorFeatures, testing::Combine(
TEST_DETECTORS,
testing::Values(2, 4, 8))
)
{
Mat img1, img1_full = imread( getDataPath("stitching/s1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/s2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
string detectorName = get<0>(GetParam());
int featuresVectorSize = get<1>(GetParam());
if (detectorName == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, SURF_MATCH_CONFIDENCE);
}
else if (detectorName == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << get<0>(GetParam());
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
vector<detail::ImageFeatures> features;
vector<detail::MatchesInfo> pairwise_matches;
for(int i = 0; i < featuresVectorSize/2; i++)
{
features.push_back(features1);
features.push_back(features2);
}
declare.time(200);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
size_t matches_count = 0;
for (size_t i = 0; i < pairwise_matches.size(); ++i)
{
if (pairwise_matches[i].src_img_idx < 0)
continue;
EXPECT_GT(pairwise_matches[i].matches.size(), (size_t)300);
EXPECT_FALSE(pairwise_matches[i].H.empty());
++matches_count;
}
EXPECT_TRUE(matches_count > 0);
SANITY_CHECK_NOTHING();
}
} // namespace
<commit_msg>stitching(perf): increase threshold of transform vector<commit_after>#include "perf_precomp.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/opencv_modules.hpp"
#include "opencv2/flann.hpp"
namespace opencv_test
{
using namespace perf;
typedef TestBaseWithParam<size_t> FeaturesFinderVec;
typedef TestBaseWithParam<string> match;
typedef tuple<string, int> matchVector_t;
typedef TestBaseWithParam<matchVector_t> matchVector;
#define NUMBER_IMAGES testing::Values(1, 5, 20)
#define SURF_MATCH_CONFIDENCE 0.65f
#define ORB_MATCH_CONFIDENCE 0.3f
#define WORK_MEGAPIX 0.6
#ifdef HAVE_OPENCV_XFEATURES2D
#define TEST_DETECTORS testing::Values("surf", "orb")
#else
#define TEST_DETECTORS testing::Values<string>("orb")
#endif
PERF_TEST_P(FeaturesFinderVec, ParallelFeaturesFinder, NUMBER_IMAGES)
{
Mat img = imread( getDataPath("stitching/a1.png") );
vector<Mat> imgs(GetParam(), img);
vector<detail::ImageFeatures> features(imgs.size());
Ptr<detail::FeaturesFinder> featuresFinder = makePtr<detail::OrbFeaturesFinder>();
TEST_CYCLE()
{
(*featuresFinder)(imgs, features);
}
SANITY_CHECK_NOTHING();
}
PERF_TEST_P(FeaturesFinderVec, SerialFeaturesFinder, NUMBER_IMAGES)
{
Mat img = imread( getDataPath("stitching/a1.png") );
vector<Mat> imgs(GetParam(), img);
vector<detail::ImageFeatures> features(imgs.size());
Ptr<detail::FeaturesFinder> featuresFinder = makePtr<detail::OrbFeaturesFinder>();
TEST_CYCLE()
{
for (size_t i = 0; i < imgs.size(); ++i)
(*featuresFinder)(imgs[i], features[i]);
}
SANITY_CHECK_NOTHING();
}
PERF_TEST_P( match, bestOf2Nearest, TEST_DETECTORS)
{
Mat img1, img1_full = imread( getDataPath("stitching/boat1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/boat2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
if (GetParam() == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, SURF_MATCH_CONFIDENCE);
}
else if (GetParam() == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << GetParam();
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
detail::MatchesInfo pairwise_matches;
declare.in(features1.descriptors, features2.descriptors);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features1, features2, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
Mat dist (pairwise_matches.H, Range::all(), Range(2, 3));
Mat R (pairwise_matches.H, Range::all(), Range(0, 2));
// separate transform matrix, use lower error on rotations
SANITY_CHECK(dist, 3., ERROR_ABSOLUTE);
SANITY_CHECK(R, .06, ERROR_ABSOLUTE);
}
PERF_TEST_P( matchVector, bestOf2NearestVectorFeatures, testing::Combine(
TEST_DETECTORS,
testing::Values(2, 4, 8))
)
{
Mat img1, img1_full = imread( getDataPath("stitching/boat1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/boat2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
string detectorName = get<0>(GetParam());
int featuresVectorSize = get<1>(GetParam());
if (detectorName == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, SURF_MATCH_CONFIDENCE);
}
else if (detectorName == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::BestOf2NearestMatcher>(false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << get<0>(GetParam());
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
vector<detail::ImageFeatures> features;
vector<detail::MatchesInfo> pairwise_matches;
for(int i = 0; i < featuresVectorSize/2; i++)
{
features.push_back(features1);
features.push_back(features2);
}
declare.time(200);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
size_t matches_count = 0;
for (size_t i = 0; i < pairwise_matches.size(); ++i)
{
if (pairwise_matches[i].src_img_idx < 0)
continue;
EXPECT_GT(pairwise_matches[i].matches.size(), 95u);
EXPECT_FALSE(pairwise_matches[i].H.empty());
++matches_count;
}
EXPECT_GT(matches_count, 0u);
SANITY_CHECK_NOTHING();
}
PERF_TEST_P( match, affineBestOf2Nearest, TEST_DETECTORS)
{
Mat img1, img1_full = imread( getDataPath("stitching/s1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/s2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
if (GetParam() == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, SURF_MATCH_CONFIDENCE);
}
else if (GetParam() == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << GetParam();
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
detail::MatchesInfo pairwise_matches;
declare.in(features1.descriptors, features2.descriptors);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features1, features2, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
// separate rotation and translation in transform matrix
Mat T (pairwise_matches.H, Range(0, 2), Range(2, 3));
Mat R (pairwise_matches.H, Range(0, 2), Range(0, 2));
Mat h (pairwise_matches.H, Range(2, 3), Range::all());
SANITY_CHECK(T, 5, ERROR_ABSOLUTE); // allow 5 pixels diff in translations
SANITY_CHECK(R, .01, ERROR_ABSOLUTE); // rotations must be more precise
// last row should be precisely (0, 0, 1) as it is just added for representation in homogeneous
// coordinates
EXPECT_DOUBLE_EQ(h.at<double>(0), 0.);
EXPECT_DOUBLE_EQ(h.at<double>(1), 0.);
EXPECT_DOUBLE_EQ(h.at<double>(2), 1.);
}
PERF_TEST_P( matchVector, affineBestOf2NearestVectorFeatures, testing::Combine(
TEST_DETECTORS,
testing::Values(2, 4, 8))
)
{
Mat img1, img1_full = imread( getDataPath("stitching/s1.jpg") );
Mat img2, img2_full = imread( getDataPath("stitching/s2.jpg") );
float scale1 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img1_full.total()));
float scale2 = (float)std::min(1.0, sqrt(WORK_MEGAPIX * 1e6 / img2_full.total()));
resize(img1_full, img1, Size(), scale1, scale1, INTER_LINEAR_EXACT);
resize(img2_full, img2, Size(), scale2, scale2, INTER_LINEAR_EXACT);
Ptr<detail::FeaturesFinder> finder;
Ptr<detail::FeaturesMatcher> matcher;
string detectorName = get<0>(GetParam());
int featuresVectorSize = get<1>(GetParam());
if (detectorName == "surf")
{
finder = makePtr<detail::SurfFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, SURF_MATCH_CONFIDENCE);
}
else if (detectorName == "orb")
{
finder = makePtr<detail::OrbFeaturesFinder>();
matcher = makePtr<detail::AffineBestOf2NearestMatcher>(false, false, ORB_MATCH_CONFIDENCE);
}
else
{
FAIL() << "Unknown 2D features type: " << get<0>(GetParam());
}
detail::ImageFeatures features1, features2;
(*finder)(img1, features1);
(*finder)(img2, features2);
vector<detail::ImageFeatures> features;
vector<detail::MatchesInfo> pairwise_matches;
for(int i = 0; i < featuresVectorSize/2; i++)
{
features.push_back(features1);
features.push_back(features2);
}
declare.time(200);
while(next())
{
cvflann::seed_random(42);//for predictive FlannBasedMatcher
startTimer();
(*matcher)(features, pairwise_matches);
stopTimer();
matcher->collectGarbage();
}
size_t matches_count = 0;
for (size_t i = 0; i < pairwise_matches.size(); ++i)
{
if (pairwise_matches[i].src_img_idx < 0)
continue;
EXPECT_GT(pairwise_matches[i].matches.size(), (size_t)300);
EXPECT_FALSE(pairwise_matches[i].H.empty());
++matches_count;
}
EXPECT_TRUE(matches_count > 0);
SANITY_CHECK_NOTHING();
}
} // namespace
<|endoftext|> |
<commit_before>#include <Game/cClientAdapter.h>
#include <Network/cUDPClientManager.h>
#include <Network/cDeliverManager.h>
#include <Network/cEventManager.h>
#include <Network/cRequestManager.h>
#include <Network/cResponseManager.h>
#include <Game/cGemManager.h>
#include <Game/cPlayerManager.h>
#include <Game/cStrategyManager.h>
#include <Game/cFieldManager.h>
#include <Game/cSubWeaponManager.h>
#include <Game/cUIManager.h>
using namespace cinder;
using namespace Network;
using namespace Network::Packet;
using namespace Network::Packet::Deliver;
using namespace Network::Packet::Event;
using namespace Network::Packet::Request;
using namespace Network::Packet::Response;
namespace Game
{
cClientAdapter::cClientAdapter( )
: mBreakBlocksPecket( new cDliBreakBlocks( ) )
{
}
cClientAdapter::~cClientAdapter( )
{
delete mBreakBlocksPecket;
}
void cClientAdapter::update( )
{
// ubN͂܂Ƃ߂ĂőM܂B
sendBreakBlocks( );
// T[o[M̂ꍇ͎oāA
// e}l[W[ɓ`܂B
recvAllPlayers( );
recvAllQuarrys( );
recvAllGems( );
recvAllBreakBlocks( );
recvAllBombs( );
recvAllCannons( );
}
void cClientAdapter::recvAllPlayers( )
{
auto e = cEventManager::getInstance( );
auto s = cResponseManager::getInstance( );
while ( auto packet = e->getEvePlayers( ) )
{
auto players = Game::cPlayerManager::getInstance( )->getPlayers( );
for ( auto& o : packet->mPlayerFormats )
{
players[o.playerId]->move( o.position - players[o.playerId]->getPos( ) );
}
}
while ( auto packet = e->getEveDamage( ) )
{
cPlayerManager::getInstance( )->getPlayers( )[packet->enemyId]->receiveDamage(
packet->damage, packet->playerId );
}
while ( auto packet = e->getEvePlayerDeath( ) )
{
// TODO:vC[LB
packet->enemyId;
packet->playerId;
}
while ( auto packet = e->getEveRespawn( ) )
{
// TODO:vC[X|[B
packet->playerId;
}
for ( auto& player : cPlayerManager::getInstance( )->getPlayers( ) )
{
player->getMainWeapon( )->pushCall( false );
player->getMainWeapon( )->pullCall( false );
}
while ( auto packet = e->getEvePlayerAttack( ) )
{
switch ( packet->call )
{
case 1:
cPlayerManager::getInstance( )->getPlayer( packet->playerId )->getMainWeapon( )->pushCall( true );
break;
case 2:
cPlayerManager::getInstance( )->getPlayer( packet->playerId )->getMainWeapon( )->pullCall( true );
break;
default:
break;
}
}
}
void cClientAdapter::recvAllQuarrys( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveSetQuarry( ) )
{
cSubWeaponManager::getInstance( )->createQuarry(
packet->mPosition
, packet->mObjectId
, packet->mPlayerId
);
}
}
void cClientAdapter::recvAllGems( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveGetJemQuarry( ) )
{
cSubWeaponManager::getInstance( )->HitDrillToGem(
packet->mObjectId,
packet->mGemId
);
}
while ( auto packet = eve->getEveGetJemPlayer( ) )
{
// TODO: vC[擾B
packet->mGemId;
packet->mPlayerId;
}
}
void cClientAdapter::recvAllBreakBlocks( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveBreakBlocks( ) )
{
for ( auto& o : packet->mBreakFormats )
{
Game::cFieldManager::getInstance( )->blockBreakNetwork(
o.position, o.radius, o.type
);
}
}
}
void cClientAdapter::recvAllBombs( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveLightBomb( ) )
{
cSubWeaponManager::getInstance( )->createLightBomb( packet->position, packet->speed, cinder::vec3(0.5F), packet->objectId, packet->playerId );
}
}
void cClientAdapter::recvAllCannons( )
{
auto e = cEventManager::getInstance( );
while ( auto packet = e->getEveAddCannonPower( ) )
{
if ( packet->teamId == Game::Player::Red )
{
cUIManager::getInstance( )->addRedCannonPower( packet->power );
}
else if ( packet->teamId == Game::Player::Blue )
{
cUIManager::getInstance( )->addBlueCannonPower( packet->power );
}
else
{
continue;
}
}
}
void cClientAdapter::sendBreakBlock( cinder::vec3 const & position, float radius, Network::ubyte1 type )
{
// ubNj͈Uobt@ɋl߂Ă܂B
mBreakBlocksPecket->mBreakFormats.emplace_back( position, radius, type );
}
void cClientAdapter::sendSetQuarry( cinder::vec3 const & position )
{
auto packet = new cReqSetQuarry( );
packet->mPosition = position;
packet->mPlayerId = cPlayerManager::getInstance( )->getActivePlayerId( );
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendPlayer( cinder::vec3 const & position, cinder::quat const & rotation )
{
auto packet = new cDliPlayer( );
packet->mFormat.playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
packet->mFormat.position = position;
packet->mFormat.rotation = rotation;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendGetGemPlayer( Network::ubyte2 gemId )
{
auto packet = new cReqGetJemPlayer( );
packet->mPlayerId = cPlayerManager::getInstance( )->getActivePlayerId( );
packet->mGemId = gemId;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendGetGemQuarry( Network::ubyte2 objectId, Network::ubyte2 gemId )
{
auto packet = new cReqGetJemQuarry( );
packet->mObjectId = objectId;
packet->mGemId = gemId;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendLightBomb( cinder::vec3 const & position, cinder::vec3 const & speed )
{
auto packet = new cReqLightBomb( );
packet->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
packet->position = position;
packet->speed = speed;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendKill( Network::ubyte1 enemyId )
{
auto p = new cReqPlayerDeath( );
p->enemyId = enemyId;
p->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendDamage( Network::ubyte1 enemyId, float damage )
{
auto p = new cReqDamage( );
p->enemyId = enemyId;
p->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
p->damage = damage;
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendRespawn( )
{
auto p = new cReqRespawn( );
p->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendAddCannonPower( Network::ubyte1 teamId, Network::ubyte1 power )
{
auto p = new cReqAddCannonPower( );
p->teamId = teamId;
p->power = power;
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendResult( )
{
auto p = new cReqResult( );
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendPlayerAttack( Network::ubyte1 playerId, Network::ubyte1 call )
{
auto p = new cReqPlayerAttack( );
p->playerId = playerId;
p->call = call;
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendBreakBlocks( )
{
if ( !mBreakBlocksPecket->mBreakFormats.empty( ) )
{
cUDPClientManager::getInstance( )->send( mBreakBlocksPecket );
mBreakBlocksPecket = new Packet::Deliver::cDliBreakBlocks( );
}
}
}
<commit_msg>プレイヤーの位置更新をもとに戻しました。<commit_after>#include <Game/cClientAdapter.h>
#include <Network/cUDPClientManager.h>
#include <Network/cDeliverManager.h>
#include <Network/cEventManager.h>
#include <Network/cRequestManager.h>
#include <Network/cResponseManager.h>
#include <Game/cGemManager.h>
#include <Game/cPlayerManager.h>
#include <Game/cStrategyManager.h>
#include <Game/cFieldManager.h>
#include <Game/cSubWeaponManager.h>
#include <Game/cUIManager.h>
using namespace cinder;
using namespace Network;
using namespace Network::Packet;
using namespace Network::Packet::Deliver;
using namespace Network::Packet::Event;
using namespace Network::Packet::Request;
using namespace Network::Packet::Response;
namespace Game
{
cClientAdapter::cClientAdapter( )
: mBreakBlocksPecket( new cDliBreakBlocks( ) )
{
}
cClientAdapter::~cClientAdapter( )
{
delete mBreakBlocksPecket;
}
void cClientAdapter::update( )
{
// ubN͂܂Ƃ߂ĂőM܂B
sendBreakBlocks( );
// T[o[M̂ꍇ͎oāA
// e}l[W[ɓ`܂B
recvAllPlayers( );
recvAllQuarrys( );
recvAllGems( );
recvAllBreakBlocks( );
recvAllBombs( );
recvAllCannons( );
}
void cClientAdapter::recvAllPlayers( )
{
auto e = cEventManager::getInstance( );
auto s = cResponseManager::getInstance( );
while ( auto packet = e->getEvePlayers( ) )
{
auto players = Game::cPlayerManager::getInstance( )->getPlayers( );
for ( auto& o : packet->mPlayerFormats )
{
players[o.playerId]->setPos( o.position );
}
}
while ( auto packet = e->getEveDamage( ) )
{
cPlayerManager::getInstance( )->getPlayers( )[packet->enemyId]->receiveDamage(
packet->damage, packet->playerId );
}
while ( auto packet = e->getEvePlayerDeath( ) )
{
// TODO:vC[LB
packet->enemyId;
packet->playerId;
}
while ( auto packet = e->getEveRespawn( ) )
{
// TODO:vC[X|[B
packet->playerId;
}
for ( auto& player : cPlayerManager::getInstance( )->getPlayers( ) )
{
player->getMainWeapon( )->pushCall( false );
player->getMainWeapon( )->pullCall( false );
}
while ( auto packet = e->getEvePlayerAttack( ) )
{
switch ( packet->call )
{
case 1:
cPlayerManager::getInstance( )->getPlayer( packet->playerId )->getMainWeapon( )->pushCall( true );
break;
case 2:
cPlayerManager::getInstance( )->getPlayer( packet->playerId )->getMainWeapon( )->pullCall( true );
break;
default:
break;
}
}
}
void cClientAdapter::recvAllQuarrys( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveSetQuarry( ) )
{
cSubWeaponManager::getInstance( )->createQuarry(
packet->mPosition
, packet->mObjectId
, packet->mPlayerId
);
}
}
void cClientAdapter::recvAllGems( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveGetJemQuarry( ) )
{
cSubWeaponManager::getInstance( )->HitDrillToGem(
packet->mObjectId,
packet->mGemId
);
}
while ( auto packet = eve->getEveGetJemPlayer( ) )
{
// TODO: vC[擾B
packet->mGemId;
packet->mPlayerId;
}
}
void cClientAdapter::recvAllBreakBlocks( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveBreakBlocks( ) )
{
for ( auto& o : packet->mBreakFormats )
{
Game::cFieldManager::getInstance( )->blockBreakNetwork(
o.position, o.radius, o.type
);
}
}
}
void cClientAdapter::recvAllBombs( )
{
auto eve = cEventManager::getInstance( );
while ( auto packet = eve->getEveLightBomb( ) )
{
cSubWeaponManager::getInstance( )->createLightBomb( packet->position, packet->speed, cinder::vec3(0.5F), packet->objectId, packet->playerId );
}
}
void cClientAdapter::recvAllCannons( )
{
auto e = cEventManager::getInstance( );
while ( auto packet = e->getEveAddCannonPower( ) )
{
if ( packet->teamId == Game::Player::Red )
{
cUIManager::getInstance( )->addRedCannonPower( packet->power );
}
else if ( packet->teamId == Game::Player::Blue )
{
cUIManager::getInstance( )->addBlueCannonPower( packet->power );
}
else
{
continue;
}
}
}
void cClientAdapter::sendBreakBlock( cinder::vec3 const & position, float radius, Network::ubyte1 type )
{
// ubNj͈Uobt@ɋl߂Ă܂B
mBreakBlocksPecket->mBreakFormats.emplace_back( position, radius, type );
}
void cClientAdapter::sendSetQuarry( cinder::vec3 const & position )
{
auto packet = new cReqSetQuarry( );
packet->mPosition = position;
packet->mPlayerId = cPlayerManager::getInstance( )->getActivePlayerId( );
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendPlayer( cinder::vec3 const & position, cinder::quat const & rotation )
{
auto packet = new cDliPlayer( );
packet->mFormat.playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
packet->mFormat.position = position;
packet->mFormat.rotation = rotation;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendGetGemPlayer( Network::ubyte2 gemId )
{
auto packet = new cReqGetJemPlayer( );
packet->mPlayerId = cPlayerManager::getInstance( )->getActivePlayerId( );
packet->mGemId = gemId;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendGetGemQuarry( Network::ubyte2 objectId, Network::ubyte2 gemId )
{
auto packet = new cReqGetJemQuarry( );
packet->mObjectId = objectId;
packet->mGemId = gemId;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendLightBomb( cinder::vec3 const & position, cinder::vec3 const & speed )
{
auto packet = new cReqLightBomb( );
packet->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
packet->position = position;
packet->speed = speed;
cUDPClientManager::getInstance( )->send( packet );
}
void cClientAdapter::sendKill( Network::ubyte1 enemyId )
{
auto p = new cReqPlayerDeath( );
p->enemyId = enemyId;
p->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendDamage( Network::ubyte1 enemyId, float damage )
{
auto p = new cReqDamage( );
p->enemyId = enemyId;
p->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
p->damage = damage;
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendRespawn( )
{
auto p = new cReqRespawn( );
p->playerId = cPlayerManager::getInstance( )->getActivePlayerId( );
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendAddCannonPower( Network::ubyte1 teamId, Network::ubyte1 power )
{
auto p = new cReqAddCannonPower( );
p->teamId = teamId;
p->power = power;
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendResult( )
{
auto p = new cReqResult( );
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendPlayerAttack( Network::ubyte1 playerId, Network::ubyte1 call )
{
auto p = new cReqPlayerAttack( );
p->playerId = playerId;
p->call = call;
cUDPClientManager::getInstance( )->send( p );
}
void cClientAdapter::sendBreakBlocks( )
{
if ( !mBreakBlocksPecket->mBreakFormats.empty( ) )
{
cUDPClientManager::getInstance( )->send( mBreakBlocksPecket );
mBreakBlocksPecket = new Packet::Deliver::cDliBreakBlocks( );
}
}
}
<|endoftext|> |
<commit_before>#include "blackhole/detail/formatter/string/parser.hpp"
#include <unordered_map>
#include <boost/algorithm/string.hpp>
#include <boost/variant/get.hpp>
namespace blackhole {
namespace detail {
namespace formatter {
namespace string {
namespace {
template<typename Iterator, class Range>
static auto starts_with(Iterator first, Iterator last, const Range& range) -> bool {
return boost::starts_with(boost::make_iterator_range(first, last), range);
}
} // namespace
struct spec_factory_t {
public:
virtual ~spec_factory_t() = default;
virtual auto initialize() const -> parser_t::token_t = 0;
virtual auto match(std::string spec) -> parser_t::token_t = 0;
};
template<typename T>
struct default_spec_factory : spec_factory_t {
virtual auto initialize() const -> parser_t::token_t {
return T();
}
};
template<>
struct spec_factory<ph::message_t> : public default_spec_factory<ph::message_t> {
auto match(std::string spec) -> parser_t::token_t {
return ph::message_t(std::move(spec));
}
};
template<>
struct spec_factory<ph::process<id>> : public default_spec_factory<ph::process<id>> {
auto match(std::string spec) -> parser_t::token_t {
BOOST_ASSERT(spec.size() > 2);
const auto type = spec.at(spec.size() - 2);
switch (type) {
case 's':
return ph::process<name>(std::move(spec));
default:
return ph::process<id>(std::move(spec));
}
}
};
template<>
struct spec_factory<ph::severity<user>> : public default_spec_factory<ph::severity<user>> {
auto match(std::string spec) -> parser_t::token_t {
BOOST_ASSERT(spec.size() > 2);
const auto type = spec.at(spec.size() - 2);
switch (type) {
case 'd':
return ph::severity<num>(std::move(spec));
default:
return ph::severity<user>(std::move(spec));
}
}
};
template<>
struct spec_factory<ph::timestamp<user>> : public default_spec_factory<ph::timestamp<user>> {
auto match(std::string spec) -> parser_t::token_t {
BOOST_ASSERT(spec.size() > 2);
const auto type = spec.at(spec.size() - 2);
switch (type) {
case 'd':
return ph::timestamp<num>(std::move(spec));
default:
return extract(spec);;
}
}
auto extract(const std::string& spec) -> ph::timestamp<user> {
// Spec always starts with "{:".
auto pos = spec.begin() + 2;
ph::timestamp<user> token;
token.spec = "{:";
if (pos != std::end(spec) && *pos == '{') {
++pos;
while (pos != std::end(spec)) {
const auto ch = *pos;
if (ch == '}') {
++pos;
break;
}
token.pattern.push_back(*pos);
++pos;
}
}
token.spec.append(std::string(pos, std::end(spec)));
return token;
}
};
parser_t::parser_t(std::string pattern) :
state(state_t::unknown),
pattern(std::move(pattern)),
pos(std::begin(this->pattern))
{
factories["message"] = std::make_shared<spec_factory<ph::message_t>>();
factories["process"] = std::make_shared<spec_factory<ph::process<id>>>();
factories["severity"] = std::make_shared<spec_factory<ph::severity<user>>>();
factories["timestamp"] = std::make_shared<spec_factory<ph::timestamp<user>>>();
}
auto
parser_t::next() -> boost::optional<token_t> {
if (state == state_t::broken) {
throw_<broken_t>();
}
if (pos == std::end(pattern)) {
return boost::none;
}
switch (state) {
case state_t::unknown:
return parse_unknown();
case state_t::literal:
return token_t(parse_literal());
case state_t::placeholder:
return parse_placeholder();
case state_t::broken:
throw_<broken_t>();
}
}
auto
parser_t::parse_unknown() -> boost::optional<token_t> {
if (exact("{")) {
if (exact(std::next(pos), "{")) {
// The "{{" will be treated as a single "{", so don't advance the cursor.
state = state_t::literal;
} else {
++pos;
state = state_t::placeholder;
}
} else {
state = state_t::literal;
}
return next();
}
auto
parser_t::parse_literal() -> literal_t {
std::string result;
while (pos != std::end(pattern)) {
// The "{{" and "}}" are treated as a single "{" and "}" respectively.
if (exact("{{") || exact("}}")) {
result.push_back(*pos);
++pos;
++pos;
continue;
} else if (exact("{")) {
state = state_t::placeholder;
++pos;
return {result};
} else if (exact("}")) {
// Unclosed single "}".
throw_<illformed_t>();
}
result.push_back(*pos);
++pos;
}
return {result};
}
auto
parser_t::parse_placeholder() -> token_t {
std::string name;
while (pos != std::end(pattern)) {
const auto ch = *pos;
if (std::isalpha(ch) || std::isdigit(ch) || ch == '_' || ch == '.') {
name.push_back(ch);
} else {
if (ch == ':') {
++pos;
const auto spec = parse_spec();
state = state_t::unknown;
const auto it = factories.find(name);
if (it == factories.end()) {
return ph::generic_t(std::move(name), std::move(spec));
} else {
return it->second->match(std::move(spec));
}
} else if (exact("}")) {
++pos;
state = state_t::unknown;
if (boost::starts_with(name, "...")) {
return ph::leftover_t{std::move(name)};
} else {
const auto it = factories.find(name);
if (it == factories.end()) {
return ph::generic_t(std::move(name));
} else {
return it->second->initialize();
}
}
} else {
throw_<invalid_placeholder_t>();
}
}
pos++;
}
throw_<illformed_t>();
}
auto
parser_t::parse_spec() -> std::string {
std::string spec("{:");
std::size_t open = 1;
while (pos != std::end(pattern)) {
const auto ch = *pos;
spec.push_back(ch);
// TODO: Here it's the right place to validate spec format, but now I don't have much
// time to implement it.
if (exact("{")) {
++open;
} else if (exact("}")) {
--open;
if (open == 0) {
++pos;
return spec;
}
}
++pos;
}
return spec;
}
template<typename Range>
auto
parser_t::exact(const Range& range) const -> bool {
return exact(pos, range);
}
template<typename Range>
auto
parser_t::exact(const_iterator pos, const Range& range) const -> bool {
return starts_with(pos, std::end(pattern), range);
}
template<class Exception, class... Args>
__attribute__((noreturn))
auto
parser_t::throw_(Args&&... args) -> void {
state = state_t::broken;
throw Exception(static_cast<std::size_t>(std::distance(std::begin(pattern), pos)), pattern,
std::forward<Args>(args)...);
}
} // namespace string
} // namespace formatter
} // namespace detail
} // namespace blackhole
<commit_msg>fix(gcc): make compilable<commit_after>#include "blackhole/detail/formatter/string/parser.hpp"
#include <unordered_map>
#include <boost/algorithm/string.hpp>
#include <boost/variant/get.hpp>
namespace blackhole {
namespace detail {
namespace formatter {
namespace string {
namespace {
template<typename Iterator, class Range>
static auto starts_with(Iterator first, Iterator last, const Range& range) -> bool {
return boost::starts_with(boost::make_iterator_range(first, last), range);
}
} // namespace
struct spec_factory_t {
public:
virtual ~spec_factory_t() {};
virtual auto initialize() const -> parser_t::token_t = 0;
virtual auto match(std::string spec) -> parser_t::token_t = 0;
};
template<typename T>
struct default_spec_factory : spec_factory_t {
virtual auto initialize() const -> parser_t::token_t {
return T();
}
};
template<>
struct spec_factory<ph::message_t> : public default_spec_factory<ph::message_t> {
auto match(std::string spec) -> parser_t::token_t {
return ph::message_t(std::move(spec));
}
};
template<>
struct spec_factory<ph::process<id>> : public default_spec_factory<ph::process<id>> {
auto match(std::string spec) -> parser_t::token_t {
BOOST_ASSERT(spec.size() > 2);
const auto type = spec.at(spec.size() - 2);
switch (type) {
case 's':
return ph::process<name>(std::move(spec));
default:
return ph::process<id>(std::move(spec));
}
}
};
template<>
struct spec_factory<ph::severity<user>> : public default_spec_factory<ph::severity<user>> {
auto match(std::string spec) -> parser_t::token_t {
BOOST_ASSERT(spec.size() > 2);
const auto type = spec.at(spec.size() - 2);
switch (type) {
case 'd':
return ph::severity<num>(std::move(spec));
default:
return ph::severity<user>(std::move(spec));
}
}
};
template<>
struct spec_factory<ph::timestamp<user>> : public default_spec_factory<ph::timestamp<user>> {
auto match(std::string spec) -> parser_t::token_t {
BOOST_ASSERT(spec.size() > 2);
const auto type = spec.at(spec.size() - 2);
switch (type) {
case 'd':
return ph::timestamp<num>(std::move(spec));
default:
return extract(spec);;
}
}
auto extract(const std::string& spec) -> ph::timestamp<user> {
// Spec always starts with "{:".
auto pos = spec.begin() + 2;
ph::timestamp<user> token;
token.spec = "{:";
if (pos != std::end(spec) && *pos == '{') {
++pos;
while (pos != std::end(spec)) {
const auto ch = *pos;
if (ch == '}') {
++pos;
break;
}
token.pattern.push_back(*pos);
++pos;
}
}
token.spec.append(std::string(pos, std::end(spec)));
return token;
}
};
parser_t::parser_t(std::string pattern) :
state(state_t::unknown),
pattern(std::move(pattern)),
pos(std::begin(this->pattern))
{
factories["message"] = std::make_shared<spec_factory<ph::message_t>>();
factories["process"] = std::make_shared<spec_factory<ph::process<id>>>();
factories["severity"] = std::make_shared<spec_factory<ph::severity<user>>>();
factories["timestamp"] = std::make_shared<spec_factory<ph::timestamp<user>>>();
}
auto
parser_t::next() -> boost::optional<token_t> {
if (state == state_t::broken) {
throw_<broken_t>();
}
if (pos == std::end(pattern)) {
return boost::none;
}
switch (state) {
case state_t::unknown:
return parse_unknown();
case state_t::literal:
return token_t(parse_literal());
case state_t::placeholder:
return parse_placeholder();
case state_t::broken:
throw_<broken_t>();
}
}
auto
parser_t::parse_unknown() -> boost::optional<token_t> {
if (exact("{")) {
if (exact(std::next(pos), "{")) {
// The "{{" will be treated as a single "{", so don't advance the cursor.
state = state_t::literal;
} else {
++pos;
state = state_t::placeholder;
}
} else {
state = state_t::literal;
}
return next();
}
auto
parser_t::parse_literal() -> literal_t {
std::string result;
while (pos != std::end(pattern)) {
// The "{{" and "}}" are treated as a single "{" and "}" respectively.
if (exact("{{") || exact("}}")) {
result.push_back(*pos);
++pos;
++pos;
continue;
} else if (exact("{")) {
state = state_t::placeholder;
++pos;
return {result};
} else if (exact("}")) {
// Unclosed single "}".
throw_<illformed_t>();
}
result.push_back(*pos);
++pos;
}
return {result};
}
auto
parser_t::parse_placeholder() -> token_t {
std::string name;
while (pos != std::end(pattern)) {
const auto ch = *pos;
if (std::isalpha(ch) || std::isdigit(ch) || ch == '_' || ch == '.') {
name.push_back(ch);
} else {
if (ch == ':') {
++pos;
const auto spec = parse_spec();
state = state_t::unknown;
const auto it = factories.find(name);
if (it == factories.end()) {
return ph::generic_t(std::move(name), std::move(spec));
} else {
return it->second->match(std::move(spec));
}
} else if (exact("}")) {
++pos;
state = state_t::unknown;
if (boost::starts_with(name, "...")) {
return ph::leftover_t{std::move(name)};
} else {
const auto it = factories.find(name);
if (it == factories.end()) {
return ph::generic_t(std::move(name));
} else {
return it->second->initialize();
}
}
} else {
throw_<invalid_placeholder_t>();
}
}
pos++;
}
throw_<illformed_t>();
}
auto
parser_t::parse_spec() -> std::string {
std::string spec("{:");
std::size_t open = 1;
while (pos != std::end(pattern)) {
const auto ch = *pos;
spec.push_back(ch);
// TODO: Here it's the right place to validate spec format, but now I don't have much
// time to implement it.
if (exact("{")) {
++open;
} else if (exact("}")) {
--open;
if (open == 0) {
++pos;
return spec;
}
}
++pos;
}
return spec;
}
template<typename Range>
auto
parser_t::exact(const Range& range) const -> bool {
return exact(pos, range);
}
template<typename Range>
auto
parser_t::exact(const_iterator pos, const Range& range) const -> bool {
return starts_with(pos, std::end(pattern), range);
}
template<class Exception, class... Args>
__attribute__((noreturn))
auto
parser_t::throw_(Args&&... args) -> void {
state = state_t::broken;
throw Exception(static_cast<std::size_t>(std::distance(std::begin(pattern), pos)), pattern,
std::forward<Args>(args)...);
}
} // namespace string
} // namespace formatter
} // namespace detail
} // namespace blackhole
<|endoftext|> |
<commit_before>
#ifndef EQUELLE_COLLOFSCALAR_HEADER_INCLUDED
#define EQUELLE_COLLOFSCALAR_HEADER_INCLUDED
//#include <thrust/device_ptr.h>
//#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
//#include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <string>
#include <fstream>
#include <iterator>
#include "equelleTypedefs.hpp"
//#include "DeviceGrid.hpp"
//#include "CollOfIndices.hpp"
// This is the header file for cuda!
//#include "EquelleRuntimeCUDA.hpp"
// Kernel declarations:
//! CUDA kernels for arithmetic operations on CollOfScalars
namespace equelleCUDA {
//! Class for the Equelle CUDA Back-end
/*!
Class for storing and handeling CollectionOfScalar variables in Equelle.
The class is part of the CUDA back-end of the Equelle compiler.
*/
class CollOfScalar
{
public:
//! Default constructor
CollOfScalar();
//! Allocating constructor
/*!
Allocates device memory for the collection. Does not initialize the collection.
\param size number of scalars in the collection.
*/
explicit CollOfScalar(const int size);
//! Constructor for uniform value
/*!
Allocates device memory and initialize all elements to the same value.
\param size Collection size
\param value Value assigned to each of the elements in the collection.
*/
explicit CollOfScalar(const int size, const double value);
//! Constructor from std::vector
/*!
Used for initialize CollOfScalar when using unit tests.
Allocates memory and copy the vector stored on the host to the device.
\param host_vec Vector with the scalar values stored in host memory
*/
explicit CollOfScalar(const std::vector<double>& host_vec);
//! Copy constructor
/*!
Allocates new device memory block, and makes a copy of the collection values.
\param coll Collection of Scalar to copy from.
*/
CollOfScalar(const CollOfScalar& coll);
//! Copy assignment operator
/*!
Overload the assignment operator. Needed for the third line here:
\code
CollOfScalar a = "something"
CollOfScalar b = "something"
a = b;
\endcode
Copy the array from other to this.
*/
CollOfScalar& operator= (const CollOfScalar& other);
//! Destructor
/*!
Frees device memory as the CollOfScalar goes out of scope.
*/
~CollOfScalar();
/*! \return The size of the collection */
int size() const;
/*!
\return A constant pointer to the device memory.
The memory block is constant as well.
*/
const double* data() const;
/*! \return A pointer to the device memory. */
double* data();
/*! \return A host vector containing the values of the collection */
std::vector<double> copyToHost() const;
//! For CUDA kernel calls.
/*!
Used for setting the CUDA grid size before calling a kernel.
\return The appropriate CUDA gridDim.x size
*/
int grid() const;
//! For CUDA kernel calls.
/*!
Used for setting the CUDA block size before calling a kernel.
\return The appropriate CUDA blockDim.x size
*/
int block() const;
private:
int size_;
double* dev_values_;
// Use 1D kernel grids for arithmetic operations
int block_x_;
int grid_x_;
// Error handling
//! check_Error throws an OPM exception if cudaStatus_ != cudaSuccess
mutable cudaError_t cudaStatus_;
void checkError_(const std::string& msg) const;
};
// ---------------- CUDA KERNELS ------------------- //
//! CUDA kernel for the minus operator
/*!
Performs elementwise operation for device arrays:
\code{.cpp} out[i] = out[i] - rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs right hand side operand.
\param[in] size number of elements.
*/
__global__ void minus_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for the plus operator
/*!
Performs elementwise operation for device arrays:
\code out[i] = out[i] + rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs Right hand side operand.
\param[in] size Number of elements.
*/
__global__ void plus_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for the multiplication operator
/*!
Performs elementwise operation for device arrays:
\code out[i] = out[i] * rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs Right hand side operand.
\param[in] size Number of elements.
*/
__global__ void multiplication_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for the division operator
/*!
Performs elementwise operation for device arrays:
\code out[i] = out[i] / rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs Right hand side operand.
\param[in] size Number of elements.
*/
__global__ void division_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for multiplication with scalar and collection
/*!
Multiply each element in out with the value scal.
\code out[i] = out[i] * scal \endcode
\param[in,out] out Input is the collection operand and is overwritten by the result.
\param[in] scal Scalar value operand.
\param[in] size Number of elements.
*/
__global__ void multScalCollection_kernel(double* out,
const double scal,
const int size);
//! CUDA kernel for division as Scalar/CollOfScalar
/*!
Set each element in out as
\code out[i] = scal/out[i] \endcode
\param[in,out] out Input is the denominator and is overwritten by the result.
\param[in] scal Scalar value numerator.
\param[in] size Number of elements.
*/
__global__ void divScalCollection_kernel( double* out,
const double scal,
const int size);
//! CUDA kernel for greater than operation
/*!
Compare elements in lhs with elements in rhs and return a Collection of Booleans.
\code out[i] = lhs[i] > rhs[i] \endcode
\param[in,out] out The resulting collection of booleans
\param[in] lhs Left hand side values
\param[in] rhs Right hand side values
\param[in] size Size of the arrays.
*/
__global__ void compGTkernel( bool* out,
const double* lhs,
const double* rhs,
const int size);
// -------------- Operation overloading ------------------- //
// Overloading of operator -
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs - rhs
\sa minus_kernel.
*/
CollOfScalar operator-(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Overloading of operator +
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs + rhs
\sa plus_kernel.
*/
CollOfScalar operator+(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Overloading of operator *
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs * rhs
\sa multiplication_kernel.
*/
CollOfScalar operator*(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Overloading of operator /
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs / rhs
\sa division_kernel.
*/
CollOfScalar operator/(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Multiplication: Scalar * Collection Of Scalars
/*!
Wrapper for the CUDA kernel which performs the operation
\param lhs Left hand side Scalar
\param rhs Right hand side Collection of Scalars
\return lhs * rhs
\sa multScalCollection_kernel
*/
CollOfScalar operator*(const Scalar& lhs, const CollOfScalar& rhs);
/*!
Since multiplication is commutative, this implementation simply return
rhs * lhs
\param lhs Left hand side Collection of Scalar
\param rhs Right han side Scalar
\return lhs * rhs
*/
CollOfScalar operator*(const CollOfScalar& lhs, const Scalar& rhs);
/*!
Implemented as (1/rhs)*lhs in order to reuse kernel
\param lhs Left hand side Collection of Scalar
\param rhs Right hand side Scalar
\return lhs / rhs
*/
CollOfScalar operator/(const CollOfScalar& lhs, const Scalar& rhs);
/*!
For Scalar / CollOfScalar. Elementwise division of the elements in
the collection.
\param lhs Scalar
\param rhs Collection of Scalars
\return out[i] = lhs / rhs[i]
*/
CollOfScalar operator/(const Scalar& lhs, const CollOfScalar& rhs);
/*!
Unary minus
\return A collection with the negative values of the inpur collection.
*/
CollOfScalar operator-(const CollOfScalar& arg);
/*!
Greater than operator
\return Collection of Booleans consisting of
\code out[i] = lhs[i] > rhs[i] \endcode
*/
CollOfBool operator>(const CollOfScalar& lhs, const CollOfScalar& rhs);
//! CollOfBool -> std::vector<bool>
/*!
Function for transforming a CollOfBool to a std::vector<bool>
*/
std::vector<bool> cob_to_std(const CollOfBool& cob);
/*!
Define max number of threads in a kernel block:
*/
const int MAX_THREADS = 7;
//const int MAX_THREADS = 512;
} // namespace equelleCUDA
#endif // EQUELLE_COLLOFSCALAR_CUDA_HEADER_INCLUDED
<commit_msg>Changed MAX_THREAD<commit_after>
#ifndef EQUELLE_COLLOFSCALAR_HEADER_INCLUDED
#define EQUELLE_COLLOFSCALAR_HEADER_INCLUDED
//#include <thrust/device_ptr.h>
//#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
//#include <cublas_v2.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <string>
#include <fstream>
#include <iterator>
#include "equelleTypedefs.hpp"
//#include "DeviceGrid.hpp"
//#include "CollOfIndices.hpp"
// This is the header file for cuda!
//#include "EquelleRuntimeCUDA.hpp"
// Kernel declarations:
//! CUDA kernels for arithmetic operations on CollOfScalars
namespace equelleCUDA {
//! Class for the Equelle CUDA Back-end
/*!
Class for storing and handeling CollectionOfScalar variables in Equelle.
The class is part of the CUDA back-end of the Equelle compiler.
*/
class CollOfScalar
{
public:
//! Default constructor
CollOfScalar();
//! Allocating constructor
/*!
Allocates device memory for the collection. Does not initialize the collection.
\param size number of scalars in the collection.
*/
explicit CollOfScalar(const int size);
//! Constructor for uniform value
/*!
Allocates device memory and initialize all elements to the same value.
\param size Collection size
\param value Value assigned to each of the elements in the collection.
*/
explicit CollOfScalar(const int size, const double value);
//! Constructor from std::vector
/*!
Used for initialize CollOfScalar when using unit tests.
Allocates memory and copy the vector stored on the host to the device.
\param host_vec Vector with the scalar values stored in host memory
*/
explicit CollOfScalar(const std::vector<double>& host_vec);
//! Copy constructor
/*!
Allocates new device memory block, and makes a copy of the collection values.
\param coll Collection of Scalar to copy from.
*/
CollOfScalar(const CollOfScalar& coll);
//! Copy assignment operator
/*!
Overload the assignment operator. Needed for the third line here:
\code
CollOfScalar a = "something"
CollOfScalar b = "something"
a = b;
\endcode
Copy the array from other to this.
*/
CollOfScalar& operator= (const CollOfScalar& other);
//! Destructor
/*!
Frees device memory as the CollOfScalar goes out of scope.
*/
~CollOfScalar();
/*! \return The size of the collection */
int size() const;
/*!
\return A constant pointer to the device memory.
The memory block is constant as well.
*/
const double* data() const;
/*! \return A pointer to the device memory. */
double* data();
/*! \return A host vector containing the values of the collection */
std::vector<double> copyToHost() const;
//! For CUDA kernel calls.
/*!
Used for setting the CUDA grid size before calling a kernel.
\return The appropriate CUDA gridDim.x size
*/
int grid() const;
//! For CUDA kernel calls.
/*!
Used for setting the CUDA block size before calling a kernel.
\return The appropriate CUDA blockDim.x size
*/
int block() const;
private:
int size_;
double* dev_values_;
// Use 1D kernel grids for arithmetic operations
int block_x_;
int grid_x_;
// Error handling
//! check_Error throws an OPM exception if cudaStatus_ != cudaSuccess
mutable cudaError_t cudaStatus_;
void checkError_(const std::string& msg) const;
};
// ---------------- CUDA KERNELS ------------------- //
//! CUDA kernel for the minus operator
/*!
Performs elementwise operation for device arrays:
\code{.cpp} out[i] = out[i] - rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs right hand side operand.
\param[in] size number of elements.
*/
__global__ void minus_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for the plus operator
/*!
Performs elementwise operation for device arrays:
\code out[i] = out[i] + rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs Right hand side operand.
\param[in] size Number of elements.
*/
__global__ void plus_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for the multiplication operator
/*!
Performs elementwise operation for device arrays:
\code out[i] = out[i] * rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs Right hand side operand.
\param[in] size Number of elements.
*/
__global__ void multiplication_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for the division operator
/*!
Performs elementwise operation for device arrays:
\code out[i] = out[i] / rhs[i] \endcode
\param[in,out] out Input is left hand side operand and is overwritten by the result.
\param[in] rhs Right hand side operand.
\param[in] size Number of elements.
*/
__global__ void division_kernel(double* out, const double* rhs, const int size);
//! CUDA kernel for multiplication with scalar and collection
/*!
Multiply each element in out with the value scal.
\code out[i] = out[i] * scal \endcode
\param[in,out] out Input is the collection operand and is overwritten by the result.
\param[in] scal Scalar value operand.
\param[in] size Number of elements.
*/
__global__ void multScalCollection_kernel(double* out,
const double scal,
const int size);
//! CUDA kernel for division as Scalar/CollOfScalar
/*!
Set each element in out as
\code out[i] = scal/out[i] \endcode
\param[in,out] out Input is the denominator and is overwritten by the result.
\param[in] scal Scalar value numerator.
\param[in] size Number of elements.
*/
__global__ void divScalCollection_kernel( double* out,
const double scal,
const int size);
//! CUDA kernel for greater than operation
/*!
Compare elements in lhs with elements in rhs and return a Collection of Booleans.
\code out[i] = lhs[i] > rhs[i] \endcode
\param[in,out] out The resulting collection of booleans
\param[in] lhs Left hand side values
\param[in] rhs Right hand side values
\param[in] size Size of the arrays.
*/
__global__ void compGTkernel( bool* out,
const double* lhs,
const double* rhs,
const int size);
// -------------- Operation overloading ------------------- //
// Overloading of operator -
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs - rhs
\sa minus_kernel.
*/
CollOfScalar operator-(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Overloading of operator +
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs + rhs
\sa plus_kernel.
*/
CollOfScalar operator+(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Overloading of operator *
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs * rhs
\sa multiplication_kernel.
*/
CollOfScalar operator*(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Overloading of operator /
/*!
Wrapper for the CUDA kernel which performs the operation.
\param lhs Left hand side operand
\param rhs Right hand side operand
\return lhs / rhs
\sa division_kernel.
*/
CollOfScalar operator/(const CollOfScalar& lhs, const CollOfScalar& rhs);
// Multiplication: Scalar * Collection Of Scalars
/*!
Wrapper for the CUDA kernel which performs the operation
\param lhs Left hand side Scalar
\param rhs Right hand side Collection of Scalars
\return lhs * rhs
\sa multScalCollection_kernel
*/
CollOfScalar operator*(const Scalar& lhs, const CollOfScalar& rhs);
/*!
Since multiplication is commutative, this implementation simply return
rhs * lhs
\param lhs Left hand side Collection of Scalar
\param rhs Right han side Scalar
\return lhs * rhs
*/
CollOfScalar operator*(const CollOfScalar& lhs, const Scalar& rhs);
/*!
Implemented as (1/rhs)*lhs in order to reuse kernel
\param lhs Left hand side Collection of Scalar
\param rhs Right hand side Scalar
\return lhs / rhs
*/
CollOfScalar operator/(const CollOfScalar& lhs, const Scalar& rhs);
/*!
For Scalar / CollOfScalar. Elementwise division of the elements in
the collection.
\param lhs Scalar
\param rhs Collection of Scalars
\return out[i] = lhs / rhs[i]
*/
CollOfScalar operator/(const Scalar& lhs, const CollOfScalar& rhs);
/*!
Unary minus
\return A collection with the negative values of the inpur collection.
*/
CollOfScalar operator-(const CollOfScalar& arg);
/*!
Greater than operator
\return Collection of Booleans consisting of
\code out[i] = lhs[i] > rhs[i] \endcode
*/
CollOfBool operator>(const CollOfScalar& lhs, const CollOfScalar& rhs);
//! CollOfBool -> std::vector<bool>
/*!
Function for transforming a CollOfBool to a std::vector<bool>
*/
std::vector<bool> cob_to_std(const CollOfBool& cob);
/*!
Define max number of threads in a kernel block:
*/
//const int MAX_THREADS = 7;
const int MAX_THREADS = 512;
} // namespace equelleCUDA
#endif // EQUELLE_COLLOFSCALAR_CUDA_HEADER_INCLUDED
<|endoftext|> |
<commit_before>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrPathRendererChain.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/GrRecordingContext.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrShaderCaps.h"
#include "src/gpu/geometry/GrStyledShape.h"
#include "src/gpu/ops/GrAAConvexPathRenderer.h"
#include "src/gpu/ops/GrAAHairLinePathRenderer.h"
#include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h"
#include "src/gpu/ops/GrAtlasPathRenderer.h"
#include "src/gpu/ops/GrDashLinePathRenderer.h"
#include "src/gpu/ops/GrDefaultPathRenderer.h"
#include "src/gpu/ops/GrSmallPathRenderer.h"
#include "src/gpu/ops/GrTriangulatingPathRenderer.h"
#include "src/gpu/tessellate/GrTessellationPathRenderer.h"
GrPathRendererChain::GrPathRendererChain(GrRecordingContext* context, const Options& options) {
const GrCaps& caps = *context->priv().caps();
if (options.fGpuPathRenderers & GpuPathRenderers::kDashLine) {
fChain.push_back(sk_make_sp<GrDashLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAConvex) {
fChain.push_back(sk_make_sp<GrAAConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAHairline) {
fChain.push_back(sk_make_sp<GrAAHairLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAALinearizing) {
fChain.push_back(sk_make_sp<GrAALinearizingConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kSmall) {
fChain.push_back(sk_make_sp<GrSmallPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAtlas) {
if (auto atlasPathRenderer = GrAtlasPathRenderer::Make(context)) {
fAtlasPathRenderer = atlasPathRenderer.get();
context->priv().addOnFlushCallbackObject(atlasPathRenderer.get());
fChain.push_back(std::move(atlasPathRenderer));
}
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTriangulating) {
fChain.push_back(sk_make_sp<GrTriangulatingPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTessellation) {
if (GrTessellationPathRenderer::IsSupported(caps)) {
auto tess = sk_make_sp<GrTessellationPathRenderer>();
fTessellationPathRenderer = tess.get();
fChain.push_back(std::move(tess));
}
}
// We always include the default path renderer (as well as SW), so we can draw any path
fChain.push_back(sk_make_sp<GrDefaultPathRenderer>());
}
GrPathRenderer* GrPathRendererChain::getPathRenderer(
const GrPathRenderer::CanDrawPathArgs& args,
DrawType drawType,
GrPathRenderer::StencilSupport* stencilSupport) {
static_assert(GrPathRenderer::kNoSupport_StencilSupport <
GrPathRenderer::kStencilOnly_StencilSupport);
static_assert(GrPathRenderer::kStencilOnly_StencilSupport <
GrPathRenderer::kNoRestriction_StencilSupport);
GrPathRenderer::StencilSupport minStencilSupport;
if (DrawType::kStencil == drawType) {
minStencilSupport = GrPathRenderer::kStencilOnly_StencilSupport;
} else if (DrawType::kStencilAndColor == drawType) {
minStencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
} else {
minStencilSupport = GrPathRenderer::kNoSupport_StencilSupport;
}
if (minStencilSupport != GrPathRenderer::kNoSupport_StencilSupport) {
// We don't support (and shouldn't need) stenciling of non-fill paths.
if (!args.fShape->style().isSimpleFill()) {
return nullptr;
}
}
GrPathRenderer* bestPathRenderer = nullptr;
for (const sk_sp<GrPathRenderer>& pr : fChain) {
GrPathRenderer::StencilSupport support = GrPathRenderer::kNoSupport_StencilSupport;
if (GrPathRenderer::kNoSupport_StencilSupport != minStencilSupport) {
support = pr->getStencilSupport(*args.fShape);
if (support < minStencilSupport) {
continue;
}
}
GrPathRenderer::CanDrawPath canDrawPath = pr->canDrawPath(args);
if (GrPathRenderer::CanDrawPath::kNo == canDrawPath) {
continue;
}
if (GrPathRenderer::CanDrawPath::kAsBackup == canDrawPath && bestPathRenderer) {
continue;
}
if (stencilSupport) {
*stencilSupport = support;
}
bestPathRenderer = pr.get();
if (GrPathRenderer::CanDrawPath::kYes == canDrawPath) {
break;
}
}
return bestPathRenderer;
}
<commit_msg>Place GrAtlasPathRenderer above GrSmallPathRenderer in the chain<commit_after>/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrPathRendererChain.h"
#include "include/gpu/GrDirectContext.h"
#include "include/gpu/GrRecordingContext.h"
#include "src/gpu/GrCaps.h"
#include "src/gpu/GrDirectContextPriv.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrShaderCaps.h"
#include "src/gpu/geometry/GrStyledShape.h"
#include "src/gpu/ops/GrAAConvexPathRenderer.h"
#include "src/gpu/ops/GrAAHairLinePathRenderer.h"
#include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h"
#include "src/gpu/ops/GrAtlasPathRenderer.h"
#include "src/gpu/ops/GrDashLinePathRenderer.h"
#include "src/gpu/ops/GrDefaultPathRenderer.h"
#include "src/gpu/ops/GrSmallPathRenderer.h"
#include "src/gpu/ops/GrTriangulatingPathRenderer.h"
#include "src/gpu/tessellate/GrTessellationPathRenderer.h"
GrPathRendererChain::GrPathRendererChain(GrRecordingContext* context, const Options& options) {
const GrCaps& caps = *context->priv().caps();
if (options.fGpuPathRenderers & GpuPathRenderers::kDashLine) {
fChain.push_back(sk_make_sp<GrDashLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAConvex) {
fChain.push_back(sk_make_sp<GrAAConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAAHairline) {
fChain.push_back(sk_make_sp<GrAAHairLinePathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAALinearizing) {
fChain.push_back(sk_make_sp<GrAALinearizingConvexPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kAtlas) {
if (auto atlasPathRenderer = GrAtlasPathRenderer::Make(context)) {
fAtlasPathRenderer = atlasPathRenderer.get();
context->priv().addOnFlushCallbackObject(atlasPathRenderer.get());
fChain.push_back(std::move(atlasPathRenderer));
}
}
if (options.fGpuPathRenderers & GpuPathRenderers::kSmall) {
fChain.push_back(sk_make_sp<GrSmallPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTriangulating) {
fChain.push_back(sk_make_sp<GrTriangulatingPathRenderer>());
}
if (options.fGpuPathRenderers & GpuPathRenderers::kTessellation) {
if (GrTessellationPathRenderer::IsSupported(caps)) {
auto tess = sk_make_sp<GrTessellationPathRenderer>();
fTessellationPathRenderer = tess.get();
fChain.push_back(std::move(tess));
}
}
// We always include the default path renderer (as well as SW), so we can draw any path
fChain.push_back(sk_make_sp<GrDefaultPathRenderer>());
}
GrPathRenderer* GrPathRendererChain::getPathRenderer(
const GrPathRenderer::CanDrawPathArgs& args,
DrawType drawType,
GrPathRenderer::StencilSupport* stencilSupport) {
static_assert(GrPathRenderer::kNoSupport_StencilSupport <
GrPathRenderer::kStencilOnly_StencilSupport);
static_assert(GrPathRenderer::kStencilOnly_StencilSupport <
GrPathRenderer::kNoRestriction_StencilSupport);
GrPathRenderer::StencilSupport minStencilSupport;
if (DrawType::kStencil == drawType) {
minStencilSupport = GrPathRenderer::kStencilOnly_StencilSupport;
} else if (DrawType::kStencilAndColor == drawType) {
minStencilSupport = GrPathRenderer::kNoRestriction_StencilSupport;
} else {
minStencilSupport = GrPathRenderer::kNoSupport_StencilSupport;
}
if (minStencilSupport != GrPathRenderer::kNoSupport_StencilSupport) {
// We don't support (and shouldn't need) stenciling of non-fill paths.
if (!args.fShape->style().isSimpleFill()) {
return nullptr;
}
}
GrPathRenderer* bestPathRenderer = nullptr;
for (const sk_sp<GrPathRenderer>& pr : fChain) {
GrPathRenderer::StencilSupport support = GrPathRenderer::kNoSupport_StencilSupport;
if (GrPathRenderer::kNoSupport_StencilSupport != minStencilSupport) {
support = pr->getStencilSupport(*args.fShape);
if (support < minStencilSupport) {
continue;
}
}
GrPathRenderer::CanDrawPath canDrawPath = pr->canDrawPath(args);
if (GrPathRenderer::CanDrawPath::kNo == canDrawPath) {
continue;
}
if (GrPathRenderer::CanDrawPath::kAsBackup == canDrawPath && bestPathRenderer) {
continue;
}
if (stencilSupport) {
*stencilSupport = support;
}
bestPathRenderer = pr.get();
if (GrPathRenderer::CanDrawPath::kYes == canDrawPath) {
break;
}
}
return bestPathRenderer;
}
<|endoftext|> |
<commit_before>/***************************************************************************//**
* FILE : threejs_export.hpp
*
* File containing a class for exporting threejs vertices and script for rendering.
*/
/* OpenCMISS-Zinc Library
*
* 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/. */
#include "general/mystring.h"
#include "graphics/graphics_library.h"
#include "graphics/render_gl.h"
#include <string>
#include "jsoncpp/json.h"
#include "opencmiss/zinc/types/graphicsid.h"
struct GT_object;
/* generic threejs_export class with many basic methods to export
* standard surfaces
*/
class Threejs_export
{
protected:
char *filename;
cmzn_streaminformation_scene_io_data_type mode;
bool morphVerticesExported, morphColoursExported, morphNormalsExported;
int morphVertices, morphColours, morphNormals;
int number_of_time_steps;
char *groupName, *regionPath;
//This is a weak pointer
cmzn_graphics_id graphics;
double textureSizes[3];
std::string verticesMorphString;
std::string colorsMorphString;
std::string normalMorphString;
std::string facesString;
std::string outputString;
bool isEmpty;
void writeVertexBuffer(const char *output_variable_name,
GLfloat *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count);
void writeMorphVertexBuffer(const char *output_variable_name,
std::string *output, GLfloat *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count, int time_step);
void writeIntegerBuffer(const char *output_variable_name,
int *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count);
void writeMorphIntegerBuffer(const char *output_variable_name,
std::string *output, int *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count, int time_step);
void writeIndexBuffer(struct GT_object *object, int typeMask,
int number_of_points, unsigned int offset);
virtual void writeIndexBufferWithoutIndex(int typeMask, int number_of_points, unsigned int offset);
void writeSpecialDataBuffer(struct GT_object *object, GLfloat *vertex_buffer,
unsigned int values_per_vertex, unsigned int vertex_count);
/* texture coordinates export*/
void writeUVsBuffer(GLfloat *texture_buffer, unsigned int values_per_vertex,
unsigned int vertex_count);
public:
Threejs_export(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn,
const char *regionPathIn, cmzn_graphics_id graphicsIn) :
filename(duplicate_string(filename_in)),
mode(mode_in),
morphVerticesExported(false),
morphColoursExported(false),
morphNormalsExported(false),
morphVertices(morphVerticesIn),
morphColours(morphColoursIn),
morphNormals(morphNormalsIn),
number_of_time_steps(number_of_time_steps_in),
groupName(groupNameIn ? duplicate_string(groupNameIn) : nullptr),
regionPath(regionPathIn ? duplicate_string(regionPathIn) : nullptr),
graphics(graphicsIn)
{
if (textureSizesIn)
{
textureSizes[0] = textureSizesIn[0];
textureSizes[1] = textureSizesIn[1];
textureSizes[2] = textureSizesIn[2];
}
else
{
textureSizes[0] = 0.0;
textureSizes[1] = 0.0;
textureSizes[2] = 0.0;
}
verticesMorphString.clear();
colorsMorphString.clear();
normalMorphString.clear();
facesString.clear();
outputString.clear();
isEmpty = false;
}
virtual ~Threejs_export();
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
void exportMaterial(cmzn_material_id material);
int beginExport();
int endExport();
bool isValid() const
{
return !isEmpty;
}
const char *getGroupName() const
{
return groupName;
}
const char *getRegionPath() const
{
return regionPath;
}
/* this return json format describing colours and transformation of the glyph */
Json::Value getExportJson();
std::string *getExportString();
bool isExportForGraphics(cmzn_graphics_id graphicsIn)
{
return (this->graphics == graphicsIn);
}
bool getMorphVerticesExported()
{
return morphVerticesExported;
}
bool getMorphColoursExported()
{
return morphColoursExported;
}
bool getMorphNormalsExported()
{
return morphNormalsExported;
}
};
/* class for export glyph into WebGL format, only
* surface glyphs are supported.
*/
class Threejs_export_glyph : public Threejs_export
{
private:
void exportStaticGlyphs(struct GT_object *object);
void exportGlyphsTransformation(struct GT_object *glyph, int time_step);
void exportGlyphsLabel(struct GT_object *glyph);
void writeGlyphIndexBuffer(struct GT_object *object, int typeMask);
Json::Value metadata, positions_json, axis1_json, axis2_json, axis3_json,
scale_json, color_json, label_json;
std::string glyphTransformationString;
char *glyphGeometriesURLName;
public:
Threejs_export_glyph(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn,
const char* regionPathIn, cmzn_graphics_id graphicsIn) :
Threejs_export(filename_in, number_of_time_steps_in,
mode_in, morphVerticesIn, morphColoursIn, morphNormalsIn, textureSizesIn,
groupNameIn, regionPathIn, graphicsIn)
{
glyphTransformationString.clear();
glyphGeometriesURLName = 0;
}
virtual ~Threejs_export_glyph();
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
/* this return json format describing colours and transformation of the glyph */
Json::Value getGlyphTransformationExportJson();
/* this return string format describing colours and transformation of the glyph */
std::string *getGlyphTransformationExportString();
void setGlyphGeometriesURLName(char *name);
};
/* class for export point into WebGL format.
*/
class Threejs_export_point : public Threejs_export
{
private:
void exportPointsLabel(struct GT_object *point);
public:
Threejs_export_point(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn, const char* regionPathIn,
cmzn_graphics_id graphicsIn) :
Threejs_export(filename_in, number_of_time_steps_in,
mode_in, morphVerticesIn, morphColoursIn, morphNormalsIn, textureSizesIn,
groupNameIn, regionPathIn, graphicsIn)
{
}
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
virtual void writeIndexBufferWithoutIndex(int typeMask, int number_of_points, unsigned int offset);
};
/* class for export point into WebGL format.
*/
class Threejs_export_line : public Threejs_export_point
{
public:
Threejs_export_line(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn, const char* regionPathIn,
cmzn_graphics_id graphicsIn) :
Threejs_export_point(filename_in, number_of_time_steps_in,
mode_in, morphVerticesIn, morphColoursIn, morphNormalsIn, textureSizesIn,
groupNameIn, regionPathIn, graphicsIn)
{
}
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
};
<commit_msg>Use cmzn_graphics * instead.<commit_after>/***************************************************************************//**
* FILE : threejs_export.hpp
*
* File containing a class for exporting threejs vertices and script for rendering.
*/
/* OpenCMISS-Zinc Library
*
* 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/. */
#include "general/mystring.h"
#include "graphics/graphics_library.h"
#include "graphics/render_gl.h"
#include <string>
#include "jsoncpp/json.h"
#include "opencmiss/zinc/types/graphicsid.h"
struct GT_object;
/* generic threejs_export class with many basic methods to export
* standard surfaces
*/
class Threejs_export
{
protected:
char *filename;
cmzn_streaminformation_scene_io_data_type mode;
bool morphVerticesExported, morphColoursExported, morphNormalsExported;
int morphVertices, morphColours, morphNormals;
int number_of_time_steps;
char *groupName, *regionPath;
cmzn_graphics *graphics; // not accessed
double textureSizes[3];
std::string verticesMorphString;
std::string colorsMorphString;
std::string normalMorphString;
std::string facesString;
std::string outputString;
bool isEmpty;
void writeVertexBuffer(const char *output_variable_name,
GLfloat *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count);
void writeMorphVertexBuffer(const char *output_variable_name,
std::string *output, GLfloat *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count, int time_step);
void writeIntegerBuffer(const char *output_variable_name,
int *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count);
void writeMorphIntegerBuffer(const char *output_variable_name,
std::string *output, int *vertex_buffer, unsigned int values_per_vertex,
unsigned int vertex_count, int time_step);
void writeIndexBuffer(struct GT_object *object, int typeMask,
int number_of_points, unsigned int offset);
virtual void writeIndexBufferWithoutIndex(int typeMask, int number_of_points, unsigned int offset);
void writeSpecialDataBuffer(struct GT_object *object, GLfloat *vertex_buffer,
unsigned int values_per_vertex, unsigned int vertex_count);
/* texture coordinates export*/
void writeUVsBuffer(GLfloat *texture_buffer, unsigned int values_per_vertex,
unsigned int vertex_count);
public:
Threejs_export(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn,
const char *regionPathIn, cmzn_graphics *graphicsIn) :
filename(duplicate_string(filename_in)),
mode(mode_in),
morphVerticesExported(false),
morphColoursExported(false),
morphNormalsExported(false),
morphVertices(morphVerticesIn),
morphColours(morphColoursIn),
morphNormals(morphNormalsIn),
number_of_time_steps(number_of_time_steps_in),
groupName(groupNameIn ? duplicate_string(groupNameIn) : nullptr),
regionPath(regionPathIn ? duplicate_string(regionPathIn) : nullptr),
graphics(graphicsIn)
{
if (textureSizesIn)
{
textureSizes[0] = textureSizesIn[0];
textureSizes[1] = textureSizesIn[1];
textureSizes[2] = textureSizesIn[2];
}
else
{
textureSizes[0] = 0.0;
textureSizes[1] = 0.0;
textureSizes[2] = 0.0;
}
verticesMorphString.clear();
colorsMorphString.clear();
normalMorphString.clear();
facesString.clear();
outputString.clear();
isEmpty = false;
}
virtual ~Threejs_export();
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
void exportMaterial(cmzn_material_id material);
int beginExport();
int endExport();
bool isValid() const
{
return !isEmpty;
}
const char *getGroupName() const
{
return groupName;
}
const char *getRegionPath() const
{
return regionPath;
}
/* this return json format describing colours and transformation of the glyph */
Json::Value getExportJson();
std::string *getExportString();
bool isExportForGraphics(cmzn_graphics *graphicsIn)
{
return (this->graphics == graphicsIn);
}
bool getMorphVerticesExported()
{
return morphVerticesExported;
}
bool getMorphColoursExported()
{
return morphColoursExported;
}
bool getMorphNormalsExported()
{
return morphNormalsExported;
}
};
/* class for export glyph into WebGL format, only
* surface glyphs are supported.
*/
class Threejs_export_glyph : public Threejs_export
{
private:
void exportStaticGlyphs(struct GT_object *object);
void exportGlyphsTransformation(struct GT_object *glyph, int time_step);
void exportGlyphsLabel(struct GT_object *glyph);
void writeGlyphIndexBuffer(struct GT_object *object, int typeMask);
Json::Value metadata, positions_json, axis1_json, axis2_json, axis3_json,
scale_json, color_json, label_json;
std::string glyphTransformationString;
char *glyphGeometriesURLName;
public:
Threejs_export_glyph(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn,
const char* regionPathIn, cmzn_graphics *graphicsIn) :
Threejs_export(filename_in, number_of_time_steps_in,
mode_in, morphVerticesIn, morphColoursIn, morphNormalsIn, textureSizesIn,
groupNameIn, regionPathIn, graphicsIn)
{
glyphTransformationString.clear();
glyphGeometriesURLName = 0;
}
virtual ~Threejs_export_glyph();
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
/* this return json format describing colours and transformation of the glyph */
Json::Value getGlyphTransformationExportJson();
/* this return string format describing colours and transformation of the glyph */
std::string *getGlyphTransformationExportString();
void setGlyphGeometriesURLName(char *name);
};
/* class for export point into WebGL format.
*/
class Threejs_export_point : public Threejs_export
{
private:
void exportPointsLabel(struct GT_object *point);
public:
Threejs_export_point(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn, const char* regionPathIn,
cmzn_graphics *graphicsIn) :
Threejs_export(filename_in, number_of_time_steps_in,
mode_in, morphVerticesIn, morphColoursIn, morphNormalsIn, textureSizesIn,
groupNameIn, regionPathIn, graphicsIn)
{
}
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
virtual void writeIndexBufferWithoutIndex(int typeMask, int number_of_points, unsigned int offset);
};
/* class for export point into WebGL format.
*/
class Threejs_export_line : public Threejs_export_point
{
public:
Threejs_export_line(const char *filename_in, int number_of_time_steps_in,
cmzn_streaminformation_scene_io_data_type mode_in,
int morphVerticesIn, int morphColoursIn, int morphNormalsIn,
double *textureSizesIn, const char *groupNameIn, const char* regionPathIn,
cmzn_graphics *graphicsIn) :
Threejs_export_point(filename_in, number_of_time_steps_in,
mode_in, morphVerticesIn, morphColoursIn, morphNormalsIn, textureSizesIn,
groupNameIn, regionPathIn, graphicsIn)
{
}
virtual int exportGraphicsObject(struct GT_object *object, int time_step);
};
<|endoftext|> |
<commit_before>#include "onoff_gpio.h"
#include <QDebug>
OnOffMorse::OnOffMorse()
{
int pin = 30;
exportPin(pin);
setDirection(pin, "out");
QString path = QString("/sys/class/gpio/gpio%1/value").arg(pin);
m_file.setFileName(path);
if (!m_file.open(QIODevice::WriteOnly)) {
qDebug() << "Failed to open pin value setter:" << m_file.errorString();
}
}
OnOffMorse::~OnOffMorse()
{
}
void OnOffMorse::setOn(bool setOn)
{
m_file.write(setOn ? "1" : "0");
}
void OnOffMorse::exportPin(int pin)
{
QString path = QString("/sys/class/gpio/export");
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write( QString::number(pin).toLatin1() );
} else {
qDebug() << "Failed to export pin:" << file.errorString();
}
}
void OnOffMorse::setDirection(int pin, const QByteArray &direction)
{
QString path = QString("/sys/class/gpio/gpio%1/direction").arg(pin);
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write(direction);
} else {
qDebug() << "Failed to set value on pin:" << file.errorString();
}
}
<commit_msg>Changed pin to 17 for raspberry pi<commit_after>#include "onoff_gpio.h"
#include <QDebug>
OnOffMorse::OnOffMorse()
{
int pin = 17;
exportPin(pin);
setDirection(pin, "out");
QString path = QString("/sys/class/gpio/gpio%1/value").arg(pin);
m_file.setFileName(path);
if (!m_file.open(QIODevice::WriteOnly)) {
qDebug() << "Failed to open pin value setter:" << m_file.errorString();
}
}
OnOffMorse::~OnOffMorse()
{
}
void OnOffMorse::setOn(bool setOn)
{
m_file.write(setOn ? "1" : "0");
}
void OnOffMorse::exportPin(int pin)
{
QString path = QString("/sys/class/gpio/export");
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write( QString::number(pin).toLatin1() );
} else {
qDebug() << "Failed to export pin:" << file.errorString();
}
}
void OnOffMorse::setDirection(int pin, const QByteArray &direction)
{
QString path = QString("/sys/class/gpio/gpio%1/direction").arg(pin);
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write(direction);
} else {
qDebug() << "Failed to set value on pin:" << file.errorString();
}
}
<|endoftext|> |
<commit_before>/*
*
* MIT License
*
* Copyright (c) 2016-2018 The Cats Project
*
* 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 <array>
#include "Cats/Corecat/Util.hpp"
using namespace Cats::Corecat;
int main() {
std::vector<std::array<std::int32_t, 3>> v(16384, {{87654321, 12345678}});
Benchmark<> benchmark;
benchmark
.add("nop", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0]; })
.add("add", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] + x[1]; })
.add("sub", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] - x[1]; })
.add("mul", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] * x[1]; })
.add("div", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] / x[1]; })
.argument()
.run();
return 0;
}
<commit_msg>Update example<commit_after>/*
*
* MIT License
*
* Copyright (c) 2016-2018 The Cats Project
*
* 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 <array>
#include "Cats/Corecat/Util/Benchmark.hpp"
using namespace Cats::Corecat;
int main() {
std::vector<std::array<std::int32_t, 3>> v(16384, {{87654321, 12345678}});
Benchmark<> benchmark;
benchmark
.add("nop", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0]; })
.add("add", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] + x[1]; })
.add("sub", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] - x[1]; })
.add("mul", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] * x[1]; })
.add("div", [&](auto _) { while(_) for(auto&& x : v) x[2] = x[0] / x[1]; })
.argument()
.run();
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file follow_me.cpp
*
* @brief Example that demonstrates the usage of Follow Me plugin.
* The example registers with FakeLocationProvider for location updates
* and sends them to the Follow Me plugin which are sent to drone. You can observe
* drone following you. We print last location of the drone in flight mode callback.
*
* @author Shakthi Prashanth <shakthi.prashanth.m@intel.com>
* @date 2018-01-03
*/
#include <chrono>
#include <dronecode_sdk/action.h>
#include <dronecode_sdk/dronecode_sdk.h>
#include <dronecode_sdk/follow_me.h>
#include <dronecode_sdk/telemetry.h>
#include <iostream>
#include <memory>
#include <thread>
#include "fake_location_provider.h"
using namespace dronecode_sdk;
using namespace std::placeholders; // for `_1`
using namespace std::chrono; // for seconds(), milliseconds(), etc
using namespace std::this_thread; // for sleep_for()
// For coloring output
#define ERROR_CONSOLE_TEXT "\033[31m" // Turn text on console red
#define TELEMETRY_CONSOLE_TEXT "\033[34m" // Turn text on console blue
#define NORMAL_CONSOLE_TEXT "\033[0m" // Restore normal console colour
inline void action_error_exit(ActionResult result, const std::string &message);
inline void follow_me_error_exit(FollowMe::Result result, const std::string &message);
inline void connection_error_exit(ConnectionResult result, const std::string &message);
void usage(std::string bin_name)
{
std::cout << NORMAL_CONSOLE_TEXT << "Usage : " << bin_name << " <connection_url>" << std::endl
<< "Connection URL format should be :" << std::endl
<< " For TCP : tcp://[server_host][:server_port]" << std::endl
<< " For UDP : udp://[bind_host][:bind_port]" << std::endl
<< " For Serial : serial:///path/to/serial/dev[:baudrate]" << std::endl
<< "For example, to connect to the simulator use URL: udp://:14540" << std::endl;
}
int main(int argc, char **argv)
{
DronecodeSDK dc;
std::string connection_url;
ConnectionResult connection_result;
if (argc == 2) {
connection_url = argv[1];
connection_result = dc.add_any_connection(connection_url);
} else {
usage(argv[0]);
return 1;
}
if (connection_result != ConnectionResult::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT
<< "Connection failed: " << connection_result_str(connection_result)
<< NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Wait for the system to connect via heartbeat
while (!dc.is_connected()) {
std::cout << "Wait for system to connect via heartbeat" << std::endl;
sleep_for(seconds(1));
}
// System got discovered.
System &system = dc.system();
auto action = std::make_shared<Action>(system);
auto follow_me = std::make_shared<FollowMe>(system);
auto telemetry = std::make_shared<Telemetry>(system);
while (!telemetry->health_all_ok()) {
std::cout << "Waiting for system to be ready" << std::endl;
sleep_for(seconds(1));
}
std::cout << "System is ready" << std::endl;
// Arm
ActionResult arm_result = action->arm();
action_error_exit(arm_result, "Arming failed");
std::cout << "Armed" << std::endl;
// Subscribe to receive updates on flight mode. You can find out whether FollowMe is active.
telemetry->flight_mode_async(std::bind(
[&](Telemetry::FlightMode flight_mode) {
const FollowMe::TargetLocation last_location = follow_me->get_last_location();
std::cout << "[FlightMode: " << Telemetry::flight_mode_str(flight_mode)
<< "] Vehicle is at: " << last_location.latitude_deg << ", "
<< last_location.longitude_deg << " degrees." << std::endl;
},
std::placeholders::_1));
// Takeoff
ActionResult takeoff_result = action->takeoff();
action_error_exit(takeoff_result, "Takeoff failed");
std::cout << "In Air..." << std::endl;
sleep_for(seconds(5)); // Wait for drone to reach takeoff altitude
// Configure Min height of the drone to be "20 meters" above home & Follow direction as "Front
// right".
FollowMe::Config config;
config.min_height_m = 10.0;
config.follow_direction = FollowMe::Config::FollowDirection::BEHIND;
FollowMe::Result follow_me_result = follow_me->set_config(config);
// Start Follow Me
follow_me_result = follow_me->start();
follow_me_error_exit(follow_me_result, "Failed to start FollowMe mode");
FakeLocationProvider location_provider;
// Register for platform-specific Location provider. We're using FakeLocationProvider for the
// example.
location_provider.request_location_updates([&system, &follow_me](double lat, double lon) {
follow_me->set_target_location({lat, lon, 0.0, 0.f, 0.f, 0.f});
});
while (location_provider.is_running()) {
sleep_for(seconds(1));
}
// Stop Follow Me
follow_me_result = follow_me->stop();
follow_me_error_exit(follow_me_result, "Failed to stop FollowMe mode");
// Stop flight mode updates.
telemetry->flight_mode_async(nullptr);
// Land
const ActionResult land_result = action->land();
action_error_exit(land_result, "Landing failed");
while (telemetry->in_air()) {
std::cout << "waiting until landed" << std::endl;
sleep_for(seconds(1));
}
std::cout << "Landed..." << std::endl;
return 0;
}
// Handles Action's result
inline void action_error_exit(ActionResult result, const std::string &message)
{
if (result != ActionResult::SUCCESS) {
std::cerr << ERROR_CONSOLE_TEXT << message << action_result_str(result)
<< NORMAL_CONSOLE_TEXT << std::endl;
exit(EXIT_FAILURE);
}
}
// Handles FollowMe's result
inline void follow_me_error_exit(FollowMe::Result result, const std::string &message)
{
if (result != FollowMe::Result::SUCCESS) {
std::cerr << ERROR_CONSOLE_TEXT << message << FollowMe::result_str(result)
<< NORMAL_CONSOLE_TEXT << std::endl;
exit(EXIT_FAILURE);
}
}
// Handles connection result
inline void connection_error_exit(ConnectionResult result, const std::string &message)
{
if (result != ConnectionResult::SUCCESS) {
std::cerr << ERROR_CONSOLE_TEXT << message << connection_result_str(result)
<< NORMAL_CONSOLE_TEXT << std::endl;
exit(EXIT_FAILURE);
}
}
<commit_msg>follow_me: capture doesn't need system capture<commit_after>/**
* @file follow_me.cpp
*
* @brief Example that demonstrates the usage of Follow Me plugin.
* The example registers with FakeLocationProvider for location updates
* and sends them to the Follow Me plugin which are sent to drone. You can observe
* drone following you. We print last location of the drone in flight mode callback.
*
* @author Shakthi Prashanth <shakthi.prashanth.m@intel.com>
* @date 2018-01-03
*/
#include <chrono>
#include <dronecode_sdk/action.h>
#include <dronecode_sdk/dronecode_sdk.h>
#include <dronecode_sdk/follow_me.h>
#include <dronecode_sdk/telemetry.h>
#include <iostream>
#include <memory>
#include <thread>
#include "fake_location_provider.h"
using namespace dronecode_sdk;
using namespace std::placeholders; // for `_1`
using namespace std::chrono; // for seconds(), milliseconds(), etc
using namespace std::this_thread; // for sleep_for()
// For coloring output
#define ERROR_CONSOLE_TEXT "\033[31m" // Turn text on console red
#define TELEMETRY_CONSOLE_TEXT "\033[34m" // Turn text on console blue
#define NORMAL_CONSOLE_TEXT "\033[0m" // Restore normal console colour
inline void action_error_exit(ActionResult result, const std::string &message);
inline void follow_me_error_exit(FollowMe::Result result, const std::string &message);
inline void connection_error_exit(ConnectionResult result, const std::string &message);
void usage(std::string bin_name)
{
std::cout << NORMAL_CONSOLE_TEXT << "Usage : " << bin_name << " <connection_url>" << std::endl
<< "Connection URL format should be :" << std::endl
<< " For TCP : tcp://[server_host][:server_port]" << std::endl
<< " For UDP : udp://[bind_host][:bind_port]" << std::endl
<< " For Serial : serial:///path/to/serial/dev[:baudrate]" << std::endl
<< "For example, to connect to the simulator use URL: udp://:14540" << std::endl;
}
int main(int argc, char **argv)
{
DronecodeSDK dc;
std::string connection_url;
ConnectionResult connection_result;
if (argc == 2) {
connection_url = argv[1];
connection_result = dc.add_any_connection(connection_url);
} else {
usage(argv[0]);
return 1;
}
if (connection_result != ConnectionResult::SUCCESS) {
std::cout << ERROR_CONSOLE_TEXT
<< "Connection failed: " << connection_result_str(connection_result)
<< NORMAL_CONSOLE_TEXT << std::endl;
return 1;
}
// Wait for the system to connect via heartbeat
while (!dc.is_connected()) {
std::cout << "Wait for system to connect via heartbeat" << std::endl;
sleep_for(seconds(1));
}
// System got discovered.
System &system = dc.system();
auto action = std::make_shared<Action>(system);
auto follow_me = std::make_shared<FollowMe>(system);
auto telemetry = std::make_shared<Telemetry>(system);
while (!telemetry->health_all_ok()) {
std::cout << "Waiting for system to be ready" << std::endl;
sleep_for(seconds(1));
}
std::cout << "System is ready" << std::endl;
// Arm
ActionResult arm_result = action->arm();
action_error_exit(arm_result, "Arming failed");
std::cout << "Armed" << std::endl;
// Subscribe to receive updates on flight mode. You can find out whether FollowMe is active.
telemetry->flight_mode_async(std::bind(
[&](Telemetry::FlightMode flight_mode) {
const FollowMe::TargetLocation last_location = follow_me->get_last_location();
std::cout << "[FlightMode: " << Telemetry::flight_mode_str(flight_mode)
<< "] Vehicle is at: " << last_location.latitude_deg << ", "
<< last_location.longitude_deg << " degrees." << std::endl;
},
std::placeholders::_1));
// Takeoff
ActionResult takeoff_result = action->takeoff();
action_error_exit(takeoff_result, "Takeoff failed");
std::cout << "In Air..." << std::endl;
sleep_for(seconds(5)); // Wait for drone to reach takeoff altitude
// Configure Min height of the drone to be "20 meters" above home & Follow direction as "Front
// right".
FollowMe::Config config;
config.min_height_m = 10.0;
config.follow_direction = FollowMe::Config::FollowDirection::BEHIND;
FollowMe::Result follow_me_result = follow_me->set_config(config);
// Start Follow Me
follow_me_result = follow_me->start();
follow_me_error_exit(follow_me_result, "Failed to start FollowMe mode");
FakeLocationProvider location_provider;
// Register for platform-specific Location provider. We're using FakeLocationProvider for the
// example.
location_provider.request_location_updates([&follow_me](double lat, double lon) {
follow_me->set_target_location({lat, lon, 0.0, 0.f, 0.f, 0.f});
});
while (location_provider.is_running()) {
sleep_for(seconds(1));
}
// Stop Follow Me
follow_me_result = follow_me->stop();
follow_me_error_exit(follow_me_result, "Failed to stop FollowMe mode");
// Stop flight mode updates.
telemetry->flight_mode_async(nullptr);
// Land
const ActionResult land_result = action->land();
action_error_exit(land_result, "Landing failed");
while (telemetry->in_air()) {
std::cout << "waiting until landed" << std::endl;
sleep_for(seconds(1));
}
std::cout << "Landed..." << std::endl;
return 0;
}
// Handles Action's result
inline void action_error_exit(ActionResult result, const std::string &message)
{
if (result != ActionResult::SUCCESS) {
std::cerr << ERROR_CONSOLE_TEXT << message << action_result_str(result)
<< NORMAL_CONSOLE_TEXT << std::endl;
exit(EXIT_FAILURE);
}
}
// Handles FollowMe's result
inline void follow_me_error_exit(FollowMe::Result result, const std::string &message)
{
if (result != FollowMe::Result::SUCCESS) {
std::cerr << ERROR_CONSOLE_TEXT << message << FollowMe::result_str(result)
<< NORMAL_CONSOLE_TEXT << std::endl;
exit(EXIT_FAILURE);
}
}
// Handles connection result
inline void connection_error_exit(ConnectionResult result, const std::string &message)
{
if (result != ConnectionResult::SUCCESS) {
std::cerr << ERROR_CONSOLE_TEXT << message << connection_result_str(result)
<< NORMAL_CONSOLE_TEXT << std::endl;
exit(EXIT_FAILURE);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/net/Connection.h"
#include "db/util/Math.h"
#include <cstring>
using namespace std;
using namespace db::io;
using namespace db::net;
using namespace db::rt;
using namespace db::util;
ConnectionInputStream::ConnectionInputStream(Connection* c)
{
mConnection = c;
mBytesRead = 0;
}
ConnectionInputStream::~ConnectionInputStream()
{
}
int ConnectionInputStream::read(char* b, int length)
{
int rval = 0;
// throttle the read as appropriate
BandwidthThrottler* bt = mConnection->getBandwidthThrottler(true);
if(bt != NULL)
{
bt->requestBytes(length, length);
}
// read from the socket input stream
rval = mConnection->getSocket()->getInputStream()->read(b, length);
if(rval > 0)
{
// update bytes read (reset as necessary)
if(mBytesRead > Math::HALF_MAX_LONG_VALUE)
{
mBytesRead = 0;
}
mBytesRead += rval;
}
return rval;
}
int ConnectionInputStream::readFully(char* b, int length)
{
int rval = 0;
// keep reading until eos, error, or length reached
int remaining = length;
int offset = 0;
int numBytes = 0;
while(remaining > 0 && (numBytes = read(b + offset, remaining)) > 0)
{
remaining -= numBytes;
offset += numBytes;
rval += numBytes;
}
if(numBytes == -1)
{
rval = -1;
}
return rval;
}
int ConnectionInputStream::readLine(string& line)
{
int rval = 0;
line.erase();
// read one character at a time
char c;
int numBytes;
while((numBytes = read(&c, 1)) > 0 && c != '\n')
{
// see if the character is a carriage return
if(c == '\r')
{
// see if the next character is an eol -- and we've found a CRLF
if(peek(&c, 1) > 0 && c == '\n')
{
// read the character in and discard it
read(&c, 1);
}
// set character to an eol since a carriage return is treated the same
c = '\n';
}
else
{
// append the character
line.push_back(c);
// a character was appended, so not end of stream
rval = 1;
}
}
if(numBytes == -1)
{
rval = -1;
}
return rval;
}
int ConnectionInputStream::readCrlf(string& line)
{
int rval = 0;
line.erase();
// peek ahead
char b[1024];
int numBytes;
bool block = false;
while(rval != 1 && (numBytes = peek(b, 1023, block)) != -1 &&
(numBytes > 0 || !block))
{
if(numBytes <= 1)
{
// not enough peek bytes available, so activate blocking
block = true;
}
else
{
// peek bytes available, so deactivate blocking
block = false;
// ensure peek buffer ends in NULL byte
b[numBytes] = 0;
// look for a CR
char* i = strchr(b, '\r');
if(i == NULL)
{
// CR not found, append all peeked bytes to string
line.append(b, numBytes);
// read and discard
read(b, numBytes);
}
else
{
// null CR for copying
i[0] = 0;
// append peeked bytes up until found CR to string
line.append(b);
// read and discard up until the CR
read(b, i - b);
// if there's room to check for an LF, do it
if((i - b) < (numBytes - 1))
{
// see if the next character is a LF
if(i[1] == '\n')
{
// CRLF found before end of stream
rval = 1;
// read and discard CRLF (2 characters)
read(b, 2);
}
else
{
// append CR to line, discard character
line.push_back('\r');
read(b, 1);
}
}
}
}
}
if(numBytes == -1)
{
rval = -1;
}
return rval;
}
int ConnectionInputStream::peek(char* b, int length, bool block)
{
// peek using socket input stream
return mConnection->getSocket()->getInputStream()->peek(b, length, block);
}
void ConnectionInputStream::close()
{
// close socket input stream
mConnection->getSocket()->getInputStream()->close();
}
unsigned long long ConnectionInputStream::getBytesRead()
{
return mBytesRead;
}
<commit_msg>Line size check and attempt to optimze readCrlf.<commit_after>/*
* Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved.
*/
#include "db/net/Connection.h"
#include "db/util/Math.h"
#include <cstring>
using namespace std;
using namespace db::io;
using namespace db::net;
using namespace db::rt;
using namespace db::util;
ConnectionInputStream::ConnectionInputStream(Connection* c)
{
mConnection = c;
mBytesRead = 0;
}
ConnectionInputStream::~ConnectionInputStream()
{
}
int ConnectionInputStream::read(char* b, int length)
{
int rval = 0;
// throttle the read as appropriate
BandwidthThrottler* bt = mConnection->getBandwidthThrottler(true);
if(bt != NULL)
{
bt->requestBytes(length, length);
}
// read from the socket input stream
rval = mConnection->getSocket()->getInputStream()->read(b, length);
if(rval > 0)
{
// update bytes read (reset as necessary)
if(mBytesRead > Math::HALF_MAX_LONG_VALUE)
{
mBytesRead = 0;
}
mBytesRead += rval;
}
return rval;
}
int ConnectionInputStream::readFully(char* b, int length)
{
int rval = 0;
// keep reading until eos, error, or length reached
int remaining = length;
int offset = 0;
int numBytes = 0;
while(remaining > 0 && (numBytes = read(b + offset, remaining)) > 0)
{
remaining -= numBytes;
offset += numBytes;
rval += numBytes;
}
if(numBytes == -1)
{
rval = -1;
}
return rval;
}
int ConnectionInputStream::readLine(string& line)
{
int rval = 0;
line.erase();
// read one character at a time
char c;
int numBytes;
while((numBytes = read(&c, 1)) > 0 && c != '\n')
{
// see if the character is a carriage return
if(c == '\r')
{
// see if the next character is an eol -- and we've found a CRLF
if(peek(&c, 1) > 0 && c == '\n')
{
// read the character in and discard it
read(&c, 1);
}
// set character to an eol since a carriage return is treated the same
c = '\n';
}
else
{
// append the character
line.push_back(c);
// a character was appended, so not end of stream
rval = 1;
}
}
if(numBytes == -1)
{
rval = -1;
}
return rval;
}
int ConnectionInputStream::readCrlf(string& line)
{
int rval = 0;
line.erase();
// peek ahead
char b[1024];
int numBytes;
bool block = false;
int readSize = 1023;
while(rval != 1 && (numBytes = peek(b, readSize, block)) != -1 &&
(numBytes > 0 || !block))
{
// read maximum amount
readSize = 1023;
// maximum line length of 1 MB
if(line.length() > (1024 << 10))
{
rval = -1;
ExceptionRef e = new Exception(
"Could not read CRLF, line too long.", "db.net.CRLFLineTooLong");
Exception::setLast(e, false);
break;
}
if(numBytes <= 1)
{
// not enough peek bytes available, so activate blocking
block = true;
}
else
{
// peek bytes available, so deactivate blocking
block = false;
// ensure peek buffer ends in NULL byte
b[numBytes] = 0;
// look for a CR
char* i = strchr(b, '\r');
if(i == NULL)
{
// CR not found, append all peeked bytes to string
line.append(b, numBytes);
// read and discard
read(b, numBytes);
}
else
{
// null CR for copying
i[0] = 0;
// append peeked bytes up until found CR to string
line.append(b);
// read and discard up until the CR
read(b, i - b);
// if there's room to check for an LF, do it
if((i - b) < (numBytes - 1))
{
// see if the next character is a LF
if(i[1] == '\n')
{
// CRLF found before end of stream
rval = 1;
// read and discard CRLF (2 characters)
read(b, 2);
}
else
{
// append CR to line, discard character
line.push_back('\r');
read(b, 1);
}
}
else
{
// read 1 more byte to find the LF
readSize = 1;
}
}
}
}
if(numBytes == -1)
{
rval = -1;
}
return rval;
}
int ConnectionInputStream::peek(char* b, int length, bool block)
{
// peek using socket input stream
return mConnection->getSocket()->getInputStream()->peek(b, length, block);
}
void ConnectionInputStream::close()
{
// close socket input stream
mConnection->getSocket()->getInputStream()->close();
}
unsigned long long ConnectionInputStream::getBytesRead()
{
return mBytesRead;
}
<|endoftext|> |
<commit_before>// easyxml.cpp - implementation of EasyXML interfaces.
#pragma warning( disable : 4786 )
#include <string.h> // strcmp()
#include <fstream>
using namespace std;
#include "easyxml.hpp"
#include "xmlparse.h"
#include "widestring.h"
////////////////////////////////////////////////////////////////////////
// Implementation of XMLAttributes.
////////////////////////////////////////////////////////////////////////
XMLAttributes::XMLAttributes ()
{
}
XMLAttributes::~XMLAttributes ()
{
}
int XMLAttributes::findAttribute (const char * name) const
{
int s = size();
for (int i = 0; i < s; i++) {
if (strcmp(name, getName(i)) == 0)
return i;
}
return -1;
}
bool XMLAttributes::hasAttribute (const char * name) const
{
return (findAttribute(name) != -1);
}
const char *XMLAttributes::getValue (const char * name) const
{
int pos = findAttribute(name);
if (pos >= 0)
return getValue(pos);
else
return 0;
}
////////////////////////////////////////////////////////////////////////
// Implementation of XMLAttributesDefault.
////////////////////////////////////////////////////////////////////////
XMLAttributesDefault::XMLAttributesDefault ()
{
}
XMLAttributesDefault::XMLAttributesDefault (const XMLAttributes &atts)
{
int s = atts.size();
for (int i = 0; i < s; i++)
addAttribute(atts.getName(i), atts.getValue(i));
}
XMLAttributesDefault::~XMLAttributesDefault ()
{
}
int XMLAttributesDefault::size () const
{
return _atts.size() / 2;
}
const char *XMLAttributesDefault::getName (int i) const
{
return _atts[i*2].c_str();
}
const char *XMLAttributesDefault::getValue (int i) const
{
return _atts[i*2+1].c_str();
}
void XMLAttributesDefault::addAttribute (const char * name, const char * value)
{
_atts.push_back(name);
_atts.push_back(value);
}
void XMLAttributesDefault::setName (int i, const char * name)
{
_atts[i*2] = name;
}
void XMLAttributesDefault::setValue (int i, const char * name)
{
_atts[i*2+1] = name;
}
void XMLAttributesDefault::setValue (const char * name, const char * value)
{
int pos = findAttribute(name);
if (pos >= 0) {
setName(pos, name);
setValue(pos, value);
} else {
addAttribute(name, value);
}
}
////////////////////////////////////////////////////////////////////////
// Attribute list wrapper for Expat.
////////////////////////////////////////////////////////////////////////
class ExpatAtts : public XMLAttributes
{
public:
ExpatAtts (const char ** atts) : _atts(atts) {}
virtual int size () const;
virtual const char * getName (int i) const;
virtual const char * getValue (int i) const;
private:
const char ** _atts;
};
int ExpatAtts::size () const
{
int s = 0;
for (int i = 0; _atts[i] != 0; i += 2)
s++;
return s;
}
const char *ExpatAtts::getName (int i) const
{
return _atts[i*2];
}
const char *ExpatAtts::getValue (int i) const
{
return _atts[i*2+1];
}
////////////////////////////////////////////////////////////////////////
// Static callback functions for Expat.
////////////////////////////////////////////////////////////////////////
#define VISITOR (*((XMLVisitor *)userData))
static void start_element (void * userData, const char * name, const char ** atts)
{
VISITOR.startElement(name, ExpatAtts(atts));
}
static void end_element (void * userData, const char * name)
{
VISITOR.endElement(name);
}
static void character_data (void * userData, const char * s, int len)
{
VISITOR.data(s, len);
}
static void processing_instruction (void * userData,
const char * target,
const char * data)
{
VISITOR.pi(target, data);
}
#undef VISITOR
////////////////////////////////////////////////////////////////////////
// Implementation of XMLReader.
////////////////////////////////////////////////////////////////////////
void readXML (istream &input, XMLVisitor &visitor, const string &path,
bool progress_callback(int))
{
XML_Parser parser = XML_ParserCreate(0);
XML_SetUserData(parser, &visitor);
XML_SetElementHandler(parser, start_element, end_element);
XML_SetCharacterDataHandler(parser, character_data);
XML_SetProcessingInstructionHandler(parser, processing_instruction);
visitor.startXML();
int progress = 0;
char buf[16384];
while (!input.eof())
{
// FIXME: get proper error string from system
if (!input.good())
{
XML_ParserFree(parser);
throw xh_io_exception("Problem reading file",
xh_location(path,
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser)),
"XML Parser");
}
input.read(buf,16384);
if (!XML_Parse(parser, buf, input.gcount(), false))
{
const XML_LChar *message = XML_ErrorString(XML_GetErrorCode(parser));
int line = XML_GetCurrentLineNumber(parser);
int col = XML_GetCurrentColumnNumber(parser);
XML_ParserFree(parser);
throw xh_io_exception(message,
xh_location(path, line, col),
"XML Parser");
}
if (progress_callback != NULL)
{
progress++;
if (progress == 400)
progress = 0;
progress_callback(progress/4);
}
}
// Verify end of document.
if (!XML_Parse(parser, buf, 0, true)) {
XML_ParserFree(parser);
throw xh_io_exception(XML_ErrorString(XML_GetErrorCode(parser)),
xh_location(path,
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser)),
"XML Parser");
}
XML_ParserFree(parser);
}
/**
* Read and parse the XML from a file.
*/
void readXML (const string &path_utf8, XMLVisitor &visitor,
bool progress_callback(int))
{
FILE *fp;
#if WIN32
// For Windows we need to convert the utf-8 path to either multi-byte
// (which might fail in some cases) or wide characters (wchar_t).
// The latter is better.
widestring fn;
fn.from_utf8(path_utf8.c_str());
fp = _wfopen(fn.c_str(), L"rb");
#elif __DARWIN_OSX__
// Mac OS X already likes utf-8.
fp = fopen(path_utf8.c_str(), "rb");
#else
// some other Unix flavor
widestring fn;
fn.from_utf8(path_utf8.c_str());
fp = fopen(fn.mb_str(), "rb");
#endif
if (!fp)
throw xh_io_exception("Failed to open file", xh_location(path_utf8),
"XML Parser");
// If it is not compressed, we can get the length of the file
int iFileLength = -1;
if (progress_callback != NULL)
{
const char *path_cstr = path_utf8.c_str();
if (strncmp(path_cstr+path_utf8.length()-1, "gz", 2))
{
fseek(fp, 0, SEEK_END);
iFileLength = ftell(fp);
rewind(fp);
}
}
#ifdef _MSC_VER
int fd = _fileno(fp);
#else
int fd = fileno(fp);
#endif
gzFile gfp = gzdopen(fd, "rb");
if (!gfp)
throw xh_io_exception("Failed to open file", xh_location(path_utf8),
"XML Parser");
try
{
readCompressedXML(gfp, visitor, path_utf8, iFileLength, progress_callback);
}
catch (xh_io_exception &e)
{
gzclose(gfp);
throw e;
}
catch (xh_throwable &t)
{
gzclose(gfp);
throw t;
}
// If it gets here, it succeeded
gzclose(gfp);
}
void readCompressedXML (gzFile fp, XMLVisitor &visitor, const string& path,
int iFileLength, bool progress_callback(int))
{
XML_Parser parser = XML_ParserCreate(0);
XML_SetUserData(parser, &visitor);
XML_SetElementHandler(parser, start_element, end_element);
XML_SetCharacterDataHandler(parser, character_data);
XML_SetProcessingInstructionHandler(parser, processing_instruction);
visitor.startXML();
const int BUFSIZE = 8192;
int progress = 0;
char buf[8192];
while (!gzeof(fp))
{
int iCount = gzread(fp, buf, BUFSIZE);
if (iCount > 0)
{
if (!XML_Parse(parser, buf, iCount, false))
{
const XML_LChar *message = XML_ErrorString(XML_GetErrorCode(parser));
int line = XML_GetCurrentLineNumber(parser);
int col = XML_GetCurrentColumnNumber(parser);
XML_ParserFree(parser);
throw xh_io_exception(message,
xh_location(path, line, col),
"XML Parser");
}
if (progress_callback != NULL)
{
if (iFileLength != -1)
{
// We know the length, so we can estimate total progress
progress += iCount;
// beware integer overflow, use doubles
double prog = (float)progress * 99.0 / iFileLength;
progress_callback((int) prog);
}
else
{
// Give a gradually advancing progress that wraps around
progress++;
if (progress == 400)
progress = 0;
progress_callback(progress/4);
}
}
}
else if (iCount < 0)
{
XML_ParserFree(parser);
throw xh_io_exception("Problem reading file",
xh_location(path,
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser)),
"XML Parser");
}
}
// Verify end of document.
if (!XML_Parse(parser, buf, 0, true))
{
XML_Error errcode = XML_GetErrorCode(parser);
const XML_LChar *errstr = XML_ErrorString(errcode);
int line = XML_GetCurrentLineNumber(parser);
int column = XML_GetCurrentColumnNumber(parser);
XML_ParserFree(parser);
throw xh_io_exception(errstr,
xh_location(path,
line,
column),
"XML Parser");
}
XML_ParserFree(parser);
}
<commit_msg>fixed check for gz files in readXML progress indication (RJ)<commit_after>// easyxml.cpp - implementation of EasyXML interfaces.
#pragma warning( disable : 4786 )
#include <string.h> // strcmp()
#include <fstream>
using namespace std;
#include "easyxml.hpp"
#include "xmlparse.h"
#include "widestring.h"
////////////////////////////////////////////////////////////////////////
// Implementation of XMLAttributes.
////////////////////////////////////////////////////////////////////////
XMLAttributes::XMLAttributes ()
{
}
XMLAttributes::~XMLAttributes ()
{
}
int XMLAttributes::findAttribute (const char * name) const
{
int s = size();
for (int i = 0; i < s; i++) {
if (strcmp(name, getName(i)) == 0)
return i;
}
return -1;
}
bool XMLAttributes::hasAttribute (const char * name) const
{
return (findAttribute(name) != -1);
}
const char *XMLAttributes::getValue (const char * name) const
{
int pos = findAttribute(name);
if (pos >= 0)
return getValue(pos);
else
return 0;
}
////////////////////////////////////////////////////////////////////////
// Implementation of XMLAttributesDefault.
////////////////////////////////////////////////////////////////////////
XMLAttributesDefault::XMLAttributesDefault ()
{
}
XMLAttributesDefault::XMLAttributesDefault (const XMLAttributes &atts)
{
int s = atts.size();
for (int i = 0; i < s; i++)
addAttribute(atts.getName(i), atts.getValue(i));
}
XMLAttributesDefault::~XMLAttributesDefault ()
{
}
int XMLAttributesDefault::size () const
{
return _atts.size() / 2;
}
const char *XMLAttributesDefault::getName (int i) const
{
return _atts[i*2].c_str();
}
const char *XMLAttributesDefault::getValue (int i) const
{
return _atts[i*2+1].c_str();
}
void XMLAttributesDefault::addAttribute (const char * name, const char * value)
{
_atts.push_back(name);
_atts.push_back(value);
}
void XMLAttributesDefault::setName (int i, const char * name)
{
_atts[i*2] = name;
}
void XMLAttributesDefault::setValue (int i, const char * name)
{
_atts[i*2+1] = name;
}
void XMLAttributesDefault::setValue (const char * name, const char * value)
{
int pos = findAttribute(name);
if (pos >= 0) {
setName(pos, name);
setValue(pos, value);
} else {
addAttribute(name, value);
}
}
////////////////////////////////////////////////////////////////////////
// Attribute list wrapper for Expat.
////////////////////////////////////////////////////////////////////////
class ExpatAtts : public XMLAttributes
{
public:
ExpatAtts (const char ** atts) : _atts(atts) {}
virtual int size () const;
virtual const char * getName (int i) const;
virtual const char * getValue (int i) const;
private:
const char ** _atts;
};
int ExpatAtts::size () const
{
int s = 0;
for (int i = 0; _atts[i] != 0; i += 2)
s++;
return s;
}
const char *ExpatAtts::getName (int i) const
{
return _atts[i*2];
}
const char *ExpatAtts::getValue (int i) const
{
return _atts[i*2+1];
}
////////////////////////////////////////////////////////////////////////
// Static callback functions for Expat.
////////////////////////////////////////////////////////////////////////
#define VISITOR (*((XMLVisitor *)userData))
static void start_element (void * userData, const char * name, const char ** atts)
{
VISITOR.startElement(name, ExpatAtts(atts));
}
static void end_element (void * userData, const char * name)
{
VISITOR.endElement(name);
}
static void character_data (void * userData, const char * s, int len)
{
VISITOR.data(s, len);
}
static void processing_instruction (void * userData,
const char * target,
const char * data)
{
VISITOR.pi(target, data);
}
#undef VISITOR
////////////////////////////////////////////////////////////////////////
// Implementation of XMLReader.
////////////////////////////////////////////////////////////////////////
/**
* Read and parse the XML from an istream.
*/
void readXML (istream &input, XMLVisitor &visitor, const string &path,
bool progress_callback(int))
{
XML_Parser parser = XML_ParserCreate(0);
XML_SetUserData(parser, &visitor);
XML_SetElementHandler(parser, start_element, end_element);
XML_SetCharacterDataHandler(parser, character_data);
XML_SetProcessingInstructionHandler(parser, processing_instruction);
visitor.startXML();
int progress = 0;
char buf[16384];
while (!input.eof())
{
// FIXME: get proper error string from system
if (!input.good())
{
XML_ParserFree(parser);
throw xh_io_exception("Problem reading file",
xh_location(path,
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser)),
"XML Parser");
}
input.read(buf,16384);
if (!XML_Parse(parser, buf, input.gcount(), false))
{
const XML_LChar *message = XML_ErrorString(XML_GetErrorCode(parser));
int line = XML_GetCurrentLineNumber(parser);
int col = XML_GetCurrentColumnNumber(parser);
XML_ParserFree(parser);
throw xh_io_exception(message,
xh_location(path, line, col),
"XML Parser");
}
if (progress_callback != NULL)
{
progress++;
if (progress == 400)
progress = 0;
progress_callback(progress/4);
}
}
// Verify end of document.
if (!XML_Parse(parser, buf, 0, true)) {
XML_ParserFree(parser);
throw xh_io_exception(XML_ErrorString(XML_GetErrorCode(parser)),
xh_location(path,
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser)),
"XML Parser");
}
XML_ParserFree(parser);
}
/**
* Read and parse the XML from a file.
*/
void readXML (const string &path_utf8, XMLVisitor &visitor,
bool progress_callback(int))
{
FILE *fp;
#if WIN32
// For Windows we need to convert the utf-8 path to either multi-byte
// (which might fail in some cases) or wide characters (wchar_t).
// The latter is better.
widestring fn;
fn.from_utf8(path_utf8.c_str());
fp = _wfopen(fn.c_str(), L"rb");
#elif __DARWIN_OSX__
// Mac OS X already likes utf-8.
fp = fopen(path_utf8.c_str(), "rb");
#else
// some other Unix flavor
widestring fn;
fn.from_utf8(path_utf8.c_str());
fp = fopen(fn.mb_str(), "rb");
#endif
if (!fp)
throw xh_io_exception("Failed to open file", xh_location(path_utf8),
"XML Parser");
// If it is not compressed, we can get the length of the file
int iFileLength = -1;
if (progress_callback != NULL)
{
const char *path_cstr = path_utf8.c_str();
// Not compressed if: filename does not end with "gz"
if (strncmp(path_cstr+path_utf8.length()-2, "gz", 2))
{
fseek(fp, 0, SEEK_END);
iFileLength = ftell(fp);
rewind(fp);
}
}
#ifdef _MSC_VER
int fd = _fileno(fp);
#else
int fd = fileno(fp);
#endif
gzFile gfp = gzdopen(fd, "rb");
if (!gfp)
throw xh_io_exception("Failed to open file", xh_location(path_utf8),
"XML Parser");
try
{
readCompressedXML(gfp, visitor, path_utf8, iFileLength, progress_callback);
}
catch (xh_io_exception &e)
{
gzclose(gfp);
throw e;
}
catch (xh_throwable &t)
{
gzclose(gfp);
throw t;
}
// If it gets here, it succeeded
gzclose(gfp);
}
void readCompressedXML (gzFile fp, XMLVisitor &visitor, const string& path,
int iFileLength, bool progress_callback(int))
{
XML_Parser parser = XML_ParserCreate(0);
XML_SetUserData(parser, &visitor);
XML_SetElementHandler(parser, start_element, end_element);
XML_SetCharacterDataHandler(parser, character_data);
XML_SetProcessingInstructionHandler(parser, processing_instruction);
visitor.startXML();
const int BUFSIZE = 8192;
int progress = 0;
char buf[8192];
while (!gzeof(fp))
{
int iCount = gzread(fp, buf, BUFSIZE);
if (iCount > 0)
{
if (!XML_Parse(parser, buf, iCount, false))
{
const XML_LChar *message = XML_ErrorString(XML_GetErrorCode(parser));
int line = XML_GetCurrentLineNumber(parser);
int col = XML_GetCurrentColumnNumber(parser);
XML_ParserFree(parser);
throw xh_io_exception(message,
xh_location(path, line, col),
"XML Parser");
}
if (progress_callback != NULL)
{
if (iFileLength != -1)
{
// We know the length, so we can estimate total progress
progress += iCount;
// beware integer overflow, use doubles
double prog = (float)progress * 99.0 / iFileLength;
progress_callback((int) prog);
}
else
{
// Give a gradually advancing progress that wraps around
progress++;
if (progress == 400)
progress = 0;
progress_callback(progress/4);
}
}
}
else if (iCount < 0)
{
XML_ParserFree(parser);
throw xh_io_exception("Problem reading file",
xh_location(path,
XML_GetCurrentLineNumber(parser),
XML_GetCurrentColumnNumber(parser)),
"XML Parser");
}
}
// Verify end of document.
if (!XML_Parse(parser, buf, 0, true))
{
XML_Error errcode = XML_GetErrorCode(parser);
const XML_LChar *errstr = XML_ErrorString(errcode);
int line = XML_GetCurrentLineNumber(parser);
int column = XML_GetCurrentColumnNumber(parser);
XML_ParserFree(parser);
throw xh_io_exception(errstr,
xh_location(path,
line,
column),
"XML Parser");
}
XML_ParserFree(parser);
}
<|endoftext|> |
<commit_before>/*
* templatelistfiltermodel.cpp - proxy model class for lists of alarm templates
* Program: kalarm
* Copyright © 2007,2009 by David Jarvie <djarvie@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h" //krazy:exclude=includes (kalarm.h must be first)
#include "templatelistfiltermodel.h"
#include "kaevent.h"
#include "kcalendar.h"
#include <kdebug.h>
// TemplateListFilterModel provides sorting and filtering for the alarm list model.
void TemplateListFilterModel::setTypeFilter(EventListModel::Type type)
{
if (type != mTypeFilter)
{
mTypeFilter = type;
filterChanged();
}
}
void TemplateListFilterModel::setTypesEnabled(EventListModel::Type type)
{
if (type != mTypesEnabled)
{
mTypesEnabled = type;
filterChanged();
}
}
bool TemplateListFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex&) const
{
QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0);
if (sourceModel()->data(sourceIndex, EventListModel::StatusRole).toInt() != KCalEvent::TEMPLATE)
return false;
if (mTypeFilter == EventListModel::ALL)
return true;
int type;
switch (static_cast<EventListModel*>(sourceModel())->event(sourceIndex)->action())
{
case KAEventData::MESSAGE:
case KAEventData::FILE: type = EventListModel::DISPLAY; break;
case KAEventData::COMMAND: type = EventListModel::COMMAND; break;
case KAEventData::EMAIL: type = EventListModel::EMAIL; break;
default: type = EventListModel::ALL; break;
}
return type & mTypeFilter;
}
bool TemplateListFilterModel::filterAcceptsColumn(int sourceCol, const QModelIndex&) const
{
return sourceCol == EventListModel::TemplateNameColumn
|| sourceCol == EventListModel::TypeColumn;
}
QModelIndex TemplateListFilterModel::mapFromSource(const QModelIndex& sourceIndex) const
{
int proxyColumn;
switch (sourceIndex.column())
{
case EventListModel::TypeColumn:
proxyColumn = TypeColumn;
break;
case EventListModel::TemplateNameColumn:
proxyColumn = TemplateNameColumn;
break;
default:
return QModelIndex();
}
QModelIndex ix = EventListFilterModel::mapFromSource(sourceIndex);
return index(ix.row(), proxyColumn, ix.parent());
}
QModelIndex TemplateListFilterModel::mapToSource(const QModelIndex& proxyIndex) const
{
int sourceColumn;
switch (proxyIndex.column())
{
case TypeColumn:
sourceColumn = EventListModel::TypeColumn;
break;
case TemplateNameColumn:
sourceColumn = EventListModel::TemplateNameColumn;
break;
default:
return QModelIndex();
}
return EventListFilterModel::mapToSource(proxyIndex);
}
Qt::ItemFlags TemplateListFilterModel::flags(const QModelIndex& index) const
{
QModelIndex sourceIndex = mapToSource(index);
Qt::ItemFlags f = sourceModel()->flags(sourceIndex);
if (mTypesEnabled == EventListModel::ALL)
return f;
int type;
switch (static_cast<EventListModel*>(sourceModel())->event(sourceIndex)->action())
{
case KAEventData::MESSAGE:
case KAEventData::FILE: type = EventListModel::DISPLAY; break;
case KAEventData::COMMAND: type = EventListModel::COMMAND; break;
case KAEventData::EMAIL: type = EventListModel::EMAIL; break;
default: type = EventListModel::ALL; break;
}
if (!(type & mTypesEnabled))
f = static_cast<Qt::ItemFlags>(f & ~(Qt::ItemIsEnabled | Qt::ItemIsSelectable));
return f;
}
<commit_msg>Fix missing AUDIO alarm type<commit_after>/*
* templatelistfiltermodel.cpp - proxy model class for lists of alarm templates
* Program: kalarm
* Copyright © 2007,2009,2010 by David Jarvie <djarvie@kde.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kalarm.h" //krazy:exclude=includes (kalarm.h must be first)
#include "templatelistfiltermodel.h"
#include "kaevent.h"
#include "kcalendar.h"
#include <kdebug.h>
// TemplateListFilterModel provides sorting and filtering for the alarm list model.
void TemplateListFilterModel::setTypeFilter(EventListModel::Type type)
{
if (type != mTypeFilter)
{
mTypeFilter = type;
filterChanged();
}
}
void TemplateListFilterModel::setTypesEnabled(EventListModel::Type type)
{
if (type != mTypesEnabled)
{
mTypesEnabled = type;
filterChanged();
}
}
bool TemplateListFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex&) const
{
QModelIndex sourceIndex = sourceModel()->index(sourceRow, 0);
if (sourceModel()->data(sourceIndex, EventListModel::StatusRole).toInt() != KCalEvent::TEMPLATE)
return false;
if (mTypeFilter == EventListModel::ALL)
return true;
int type;
switch (static_cast<EventListModel*>(sourceModel())->event(sourceIndex)->action())
{
case KAEventData::MESSAGE:
case KAEventData::FILE: type = EventListModel::DISPLAY; break;
case KAEventData::COMMAND: type = EventListModel::COMMAND; break;
case KAEventData::EMAIL: type = EventListModel::EMAIL; break;
case KAEventData::AUDIO: type = EventListModel::AUDIO; break;
default: type = EventListModel::ALL; break;
}
return type & mTypeFilter;
}
bool TemplateListFilterModel::filterAcceptsColumn(int sourceCol, const QModelIndex&) const
{
return sourceCol == EventListModel::TemplateNameColumn
|| sourceCol == EventListModel::TypeColumn;
}
QModelIndex TemplateListFilterModel::mapFromSource(const QModelIndex& sourceIndex) const
{
int proxyColumn;
switch (sourceIndex.column())
{
case EventListModel::TypeColumn:
proxyColumn = TypeColumn;
break;
case EventListModel::TemplateNameColumn:
proxyColumn = TemplateNameColumn;
break;
default:
return QModelIndex();
}
QModelIndex ix = EventListFilterModel::mapFromSource(sourceIndex);
return index(ix.row(), proxyColumn, ix.parent());
}
QModelIndex TemplateListFilterModel::mapToSource(const QModelIndex& proxyIndex) const
{
int sourceColumn;
switch (proxyIndex.column())
{
case TypeColumn:
sourceColumn = EventListModel::TypeColumn;
break;
case TemplateNameColumn:
sourceColumn = EventListModel::TemplateNameColumn;
break;
default:
return QModelIndex();
}
return EventListFilterModel::mapToSource(proxyIndex);
}
Qt::ItemFlags TemplateListFilterModel::flags(const QModelIndex& index) const
{
QModelIndex sourceIndex = mapToSource(index);
Qt::ItemFlags f = sourceModel()->flags(sourceIndex);
if (mTypesEnabled == EventListModel::ALL)
return f;
int type;
switch (static_cast<EventListModel*>(sourceModel())->event(sourceIndex)->action())
{
case KAEventData::MESSAGE:
case KAEventData::FILE: type = EventListModel::DISPLAY; break;
case KAEventData::COMMAND: type = EventListModel::COMMAND; break;
case KAEventData::EMAIL: type = EventListModel::EMAIL; break;
case KAEventData::AUDIO: type = EventListModel::AUDIO; break;
default: type = EventListModel::ALL; break;
}
if (!(type & mTypesEnabled))
f = static_cast<Qt::ItemFlags>(f & ~(Qt::ItemIsEnabled | Qt::ItemIsSelectable));
return f;
}
<|endoftext|> |
<commit_before>//===- LowerBitSets.cpp - Unit tests for bitset lowering ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/LowerBitSets.h"
#include "gtest/gtest.h"
using namespace llvm;
TEST(LowerBitSets, BitSetBuilder) {
struct {
std::vector<uint64_t> Offsets;
std::set<uint64_t> Bits;
uint64_t ByteOffset;
uint64_t BitSize;
unsigned AlignLog2;
bool IsSingleOffset;
bool IsAllOnes;
} BSBTests[] = {
{{}, {}, 0, 1, 0, false, false},
{{0}, {0}, 0, 1, 0, true, true},
{{4}, {0}, 4, 1, 0, true, true},
{{37}, {0}, 37, 1, 0, true, true},
{{0, 1}, {0, 1}, 0, 2, 0, false, true},
{{0, 4}, {0, 1}, 0, 2, 2, false, true},
{{0, uint64_t(1) << 33}, {0, 1}, 0, 2, 33, false, true},
{{3, 7}, {0, 1}, 3, 2, 2, false, true},
{{0, 1, 7}, {0, 1, 7}, 0, 8, 0, false, false},
{{0, 2, 14}, {0, 1, 7}, 0, 8, 1, false, false},
{{0, 1, 8}, {0, 1, 8}, 0, 9, 0, false, false},
{{0, 2, 16}, {0, 1, 8}, 0, 9, 1, false, false},
{{0, 1, 2, 3, 4, 5, 6, 7},
{0, 1, 2, 3, 4, 5, 6, 7},
0,
8,
0,
false,
true},
{{0, 1, 2, 3, 4, 5, 6, 7, 8},
{0, 1, 2, 3, 4, 5, 6, 7, 8},
0,
9,
0,
false,
true},
};
for (auto &&T : BSBTests) {
BitSetBuilder BSB;
for (auto Offset : T.Offsets)
BSB.addOffset(Offset);
BitSetInfo BSI = BSB.build();
EXPECT_EQ(T.Bits, BSI.Bits);
EXPECT_EQ(T.ByteOffset, BSI.ByteOffset);
EXPECT_EQ(T.BitSize, BSI.BitSize);
EXPECT_EQ(T.AlignLog2, BSI.AlignLog2);
EXPECT_EQ(T.IsSingleOffset, BSI.isSingleOffset());
EXPECT_EQ(T.IsAllOnes, BSI.isAllOnes());
for (auto Offset : T.Offsets)
EXPECT_TRUE(BSI.containsGlobalOffset(Offset));
auto I = T.Offsets.begin();
for (uint64_t NonOffset = 0; NonOffset != 256; ++NonOffset) {
if (I != T.Offsets.end() && *I == NonOffset) {
++I;
continue;
}
EXPECT_FALSE(BSI.containsGlobalOffset(NonOffset));
}
}
}
TEST(LowerBitSets, GlobalLayoutBuilder) {
struct {
uint64_t NumObjects;
std::vector<std::set<uint64_t>> Fragments;
std::vector<uint64_t> WantLayout;
} GLBTests[] = {
{0, {}, {}},
{4, {{0, 1}, {2, 3}}, {0, 1, 2, 3}},
{3, {{0, 1}, {1, 2}}, {0, 1, 2}},
{4, {{0, 1}, {1, 2}, {2, 3}}, {0, 1, 2, 3}},
{4, {{0, 1}, {2, 3}, {1, 2}}, {0, 1, 2, 3}},
{6, {{2, 5}, {0, 1, 2, 3, 4, 5}}, {0, 1, 2, 5, 3, 4}},
};
for (auto &&T : GLBTests) {
GlobalLayoutBuilder GLB(T.NumObjects);
for (auto &&F : T.Fragments)
GLB.addFragment(F);
std::vector<uint64_t> ComputedLayout;
for (auto &&F : GLB.Fragments)
ComputedLayout.insert(ComputedLayout.end(), F.begin(), F.end());
EXPECT_EQ(T.WantLayout, ComputedLayout);
}
}
TEST(LowerBitSets, ByteArrayBuilder) {
struct BABAlloc {
std::set<uint64_t> Bits;
uint64_t BitSize;
uint64_t WantByteOffset;
uint8_t WantMask;
};
struct {
std::vector<BABAlloc> Allocs;
std::vector<uint8_t> WantBytes;
} BABTests[] = {
{{{{0}, 1, 0, 1}, {{0}, 1, 0, 2}}, {3}},
{{{{0}, 16, 0, 1},
{{1}, 15, 0, 2},
{{2}, 14, 0, 4},
{{3}, 13, 0, 8},
{{4}, 12, 0, 0x10},
{{5}, 11, 0, 0x20},
{{6}, 10, 0, 0x40},
{{7}, 9, 0, 0x80},
{{0}, 7, 9, 0x80},
{{0}, 6, 10, 0x40},
{{0}, 5, 11, 0x20},
{{0}, 4, 12, 0x10},
{{0}, 3, 13, 8},
{{0}, 2, 14, 4},
{{0}, 1, 15, 2}},
{1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80, 0, 0x80, 0x40, 0x20, 0x10, 8, 4,
2}},
};
for (auto &&T : BABTests) {
ByteArrayBuilder BABuilder;
for (auto &&A : T.Allocs) {
uint64_t GotByteOffset;
uint8_t GotMask;
BABuilder.allocate(A.Bits, A.BitSize, GotByteOffset, GotMask);
EXPECT_EQ(A.WantByteOffset, GotByteOffset);
EXPECT_EQ(A.WantMask, GotMask);
}
EXPECT_EQ(T.WantBytes, BABuilder.Bytes);
}
}
<commit_msg>Add explicit type to empty std::set initializer to fix the libc++ build.<commit_after>//===- LowerBitSets.cpp - Unit tests for bitset lowering ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/IPO/LowerBitSets.h"
#include "gtest/gtest.h"
using namespace llvm;
TEST(LowerBitSets, BitSetBuilder) {
struct {
std::vector<uint64_t> Offsets;
std::set<uint64_t> Bits;
uint64_t ByteOffset;
uint64_t BitSize;
unsigned AlignLog2;
bool IsSingleOffset;
bool IsAllOnes;
} BSBTests[] = {
{{}, std::set<uint64_t>{}, 0, 1, 0, false, false},
{{0}, {0}, 0, 1, 0, true, true},
{{4}, {0}, 4, 1, 0, true, true},
{{37}, {0}, 37, 1, 0, true, true},
{{0, 1}, {0, 1}, 0, 2, 0, false, true},
{{0, 4}, {0, 1}, 0, 2, 2, false, true},
{{0, uint64_t(1) << 33}, {0, 1}, 0, 2, 33, false, true},
{{3, 7}, {0, 1}, 3, 2, 2, false, true},
{{0, 1, 7}, {0, 1, 7}, 0, 8, 0, false, false},
{{0, 2, 14}, {0, 1, 7}, 0, 8, 1, false, false},
{{0, 1, 8}, {0, 1, 8}, 0, 9, 0, false, false},
{{0, 2, 16}, {0, 1, 8}, 0, 9, 1, false, false},
{{0, 1, 2, 3, 4, 5, 6, 7},
{0, 1, 2, 3, 4, 5, 6, 7},
0,
8,
0,
false,
true},
{{0, 1, 2, 3, 4, 5, 6, 7, 8},
{0, 1, 2, 3, 4, 5, 6, 7, 8},
0,
9,
0,
false,
true},
};
for (auto &&T : BSBTests) {
BitSetBuilder BSB;
for (auto Offset : T.Offsets)
BSB.addOffset(Offset);
BitSetInfo BSI = BSB.build();
EXPECT_EQ(T.Bits, BSI.Bits);
EXPECT_EQ(T.ByteOffset, BSI.ByteOffset);
EXPECT_EQ(T.BitSize, BSI.BitSize);
EXPECT_EQ(T.AlignLog2, BSI.AlignLog2);
EXPECT_EQ(T.IsSingleOffset, BSI.isSingleOffset());
EXPECT_EQ(T.IsAllOnes, BSI.isAllOnes());
for (auto Offset : T.Offsets)
EXPECT_TRUE(BSI.containsGlobalOffset(Offset));
auto I = T.Offsets.begin();
for (uint64_t NonOffset = 0; NonOffset != 256; ++NonOffset) {
if (I != T.Offsets.end() && *I == NonOffset) {
++I;
continue;
}
EXPECT_FALSE(BSI.containsGlobalOffset(NonOffset));
}
}
}
TEST(LowerBitSets, GlobalLayoutBuilder) {
struct {
uint64_t NumObjects;
std::vector<std::set<uint64_t>> Fragments;
std::vector<uint64_t> WantLayout;
} GLBTests[] = {
{0, {}, {}},
{4, {{0, 1}, {2, 3}}, {0, 1, 2, 3}},
{3, {{0, 1}, {1, 2}}, {0, 1, 2}},
{4, {{0, 1}, {1, 2}, {2, 3}}, {0, 1, 2, 3}},
{4, {{0, 1}, {2, 3}, {1, 2}}, {0, 1, 2, 3}},
{6, {{2, 5}, {0, 1, 2, 3, 4, 5}}, {0, 1, 2, 5, 3, 4}},
};
for (auto &&T : GLBTests) {
GlobalLayoutBuilder GLB(T.NumObjects);
for (auto &&F : T.Fragments)
GLB.addFragment(F);
std::vector<uint64_t> ComputedLayout;
for (auto &&F : GLB.Fragments)
ComputedLayout.insert(ComputedLayout.end(), F.begin(), F.end());
EXPECT_EQ(T.WantLayout, ComputedLayout);
}
}
TEST(LowerBitSets, ByteArrayBuilder) {
struct BABAlloc {
std::set<uint64_t> Bits;
uint64_t BitSize;
uint64_t WantByteOffset;
uint8_t WantMask;
};
struct {
std::vector<BABAlloc> Allocs;
std::vector<uint8_t> WantBytes;
} BABTests[] = {
{{{{0}, 1, 0, 1}, {{0}, 1, 0, 2}}, {3}},
{{{{0}, 16, 0, 1},
{{1}, 15, 0, 2},
{{2}, 14, 0, 4},
{{3}, 13, 0, 8},
{{4}, 12, 0, 0x10},
{{5}, 11, 0, 0x20},
{{6}, 10, 0, 0x40},
{{7}, 9, 0, 0x80},
{{0}, 7, 9, 0x80},
{{0}, 6, 10, 0x40},
{{0}, 5, 11, 0x20},
{{0}, 4, 12, 0x10},
{{0}, 3, 13, 8},
{{0}, 2, 14, 4},
{{0}, 1, 15, 2}},
{1, 2, 4, 8, 0x10, 0x20, 0x40, 0x80, 0, 0x80, 0x40, 0x20, 0x10, 8, 4,
2}},
};
for (auto &&T : BABTests) {
ByteArrayBuilder BABuilder;
for (auto &&A : T.Allocs) {
uint64_t GotByteOffset;
uint8_t GotMask;
BABuilder.allocate(A.Bits, A.BitSize, GotByteOffset, GotMask);
EXPECT_EQ(A.WantByteOffset, GotByteOffset);
EXPECT_EQ(A.WantMask, GotMask);
}
EXPECT_EQ(T.WantBytes, BABuilder.Bytes);
}
}
<|endoftext|> |
<commit_before>//===-- io.cpp ------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// I/O routines for registered fd's
//
//===----------------------------------------------------------------------===//
#include "ipcopt.h"
#include "debug.h"
#include "ipcreg_internal.h"
#include "socket_inline.h"
#include "ipcd.h"
#include <cassert>
const size_t TRANS_THRESHOLD = 1ULL << 20;
void copy_bufsize(int src, int dst, int buftype) {
int bufsize;
socklen_t sz = sizeof(bufsize);
int ret = getsockopt(src, SOL_SOCKET, buftype, &bufsize, &sz);
assert(!ret);
// ipclog("Bufsize %d of fd %d: %d\n", buftype, src, bufsize);
ret = setsockopt(dst, SOL_SOCKET, buftype, &bufsize, sz);
assert(!ret);
}
void copy_bufsizes(int src, int dst) {
copy_bufsize(src, dst, SO_RCVBUF);
copy_bufsize(src, dst, SO_SNDBUF);
}
ssize_t do_ipc_send(int fd, const void *buf, size_t count, int flags) {
ipc_info *i = getFDDesc(fd);
assert(i->valid);
int sendfd = fd;
if (i->state == STATE_OPTIMIZED)
sendfd = i->localfd;
assert(sendfd);
ssize_t ret = __real_send(sendfd, buf, count, flags);
if (i->state == STATE_UNOPT && ret != -1) {
// Successful operation, add to running total.
i->bytes_trans += ret;
if (i->bytes_trans > TRANS_THRESHOLD) {
ipclog("send of %zu bytes crosses threshold for fd=%d\n", ret, fd);
}
// Fake localization of this for now:
i->localfd = fd;
i->state = STATE_OPTIMIZED;
}
return ret;
}
ssize_t do_ipc_recv(int fd, void *buf, size_t count, int flags) {
ipc_info *i = getFDDesc(fd);
assert(i->valid);
int recvfd = fd;
if (i->state == STATE_OPTIMIZED)
recvfd = i->localfd;
assert(recvfd);
ssize_t ret = __real_recv(recvfd, buf, count, flags);
if (i->state == STATE_UNOPT && ret != -1) {
// Successful operation, add to running total.
i->bytes_trans += ret;
if (i->bytes_trans > TRANS_THRESHOLD) {
ipclog("recv of %zu bytes crosses threshold for fd=%d\n", ret, fd);
}
// Fake localization of this for now:
i->localfd = fd;
i->state = STATE_OPTIMIZED;
}
return ret;
}
ssize_t do_ipc_sendto(int fd, const void *message, size_t length, int flags,
const struct sockaddr *dest_addr, socklen_t dest_len) {
// if (dest_addr)
// return __real_sendto(fd, message, length, flags, dest_addr, dest_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!dest_addr);
// As a bonus from the above check, we can forward to plain send()
return do_ipc_send(fd, message, length, flags);
}
ssize_t do_ipc_recvfrom(int fd, void *buffer, size_t length, int flags,
struct sockaddr *address, socklen_t *address_len) {
// if (address)
// return __real_recvfrom(fd, buffer, length, flags, address, address_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!address);
// As a bonus from the above check, we can forward to plain recv()
return do_ipc_recv(fd, buffer, length, flags);
}
<commit_msg>Whoops, only fake localization once we hit the threshold :).<commit_after>//===-- io.cpp ------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// I/O routines for registered fd's
//
//===----------------------------------------------------------------------===//
#include "ipcopt.h"
#include "debug.h"
#include "ipcreg_internal.h"
#include "socket_inline.h"
#include "ipcd.h"
#include <cassert>
const size_t TRANS_THRESHOLD = 1ULL << 20;
void copy_bufsize(int src, int dst, int buftype) {
int bufsize;
socklen_t sz = sizeof(bufsize);
int ret = getsockopt(src, SOL_SOCKET, buftype, &bufsize, &sz);
assert(!ret);
// ipclog("Bufsize %d of fd %d: %d\n", buftype, src, bufsize);
ret = setsockopt(dst, SOL_SOCKET, buftype, &bufsize, sz);
assert(!ret);
}
void copy_bufsizes(int src, int dst) {
copy_bufsize(src, dst, SO_RCVBUF);
copy_bufsize(src, dst, SO_SNDBUF);
}
ssize_t do_ipc_send(int fd, const void *buf, size_t count, int flags) {
ipc_info *i = getFDDesc(fd);
assert(i->valid);
int sendfd = fd;
if (i->state == STATE_OPTIMIZED)
sendfd = i->localfd;
assert(sendfd);
ssize_t ret = __real_send(sendfd, buf, count, flags);
if (i->state == STATE_UNOPT && ret != -1) {
// Successful operation, add to running total.
i->bytes_trans += ret;
if (i->bytes_trans > TRANS_THRESHOLD) {
ipclog("send of %zu bytes crosses threshold for fd=%d\n", ret, fd);
// Fake localization of this for now:
i->localfd = fd;
i->state = STATE_OPTIMIZED;
}
}
return ret;
}
ssize_t do_ipc_recv(int fd, void *buf, size_t count, int flags) {
ipc_info *i = getFDDesc(fd);
assert(i->valid);
int recvfd = fd;
if (i->state == STATE_OPTIMIZED)
recvfd = i->localfd;
assert(recvfd);
ssize_t ret = __real_recv(recvfd, buf, count, flags);
if (i->state == STATE_UNOPT && ret != -1) {
// Successful operation, add to running total.
i->bytes_trans += ret;
if (i->bytes_trans > TRANS_THRESHOLD) {
ipclog("recv of %zu bytes crosses threshold for fd=%d\n", ret, fd);
// Fake localization of this for now:
i->localfd = fd;
i->state = STATE_OPTIMIZED;
}
}
return ret;
}
ssize_t do_ipc_sendto(int fd, const void *message, size_t length, int flags,
const struct sockaddr *dest_addr, socklen_t dest_len) {
// if (dest_addr)
// return __real_sendto(fd, message, length, flags, dest_addr, dest_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!dest_addr);
// As a bonus from the above check, we can forward to plain send()
return do_ipc_send(fd, message, length, flags);
}
ssize_t do_ipc_recvfrom(int fd, void *buffer, size_t length, int flags,
struct sockaddr *address, socklen_t *address_len) {
// if (address)
// return __real_recvfrom(fd, buffer, length, flags, address, address_len);
// Hardly safe, but if it's non-NULL there's a chance
// the caller might want us to write something there.
assert(!address);
// As a bonus from the above check, we can forward to plain recv()
return do_ipc_recv(fd, buffer, length, flags);
}
<|endoftext|> |
<commit_before>#include "allocator_ros.h"
#include <vector>
#include <limits>
#include <eigen_conversions/eigen_msg.h>
#include "vortex_msgs/ThrusterForces.h"
#include "uranus_dp/eigen_typedefs.h"
#include "uranus_dp/eigen_helper.h"
Allocator::Allocator(ros::NodeHandle nh) : nh(nh)
{
sub = nh.subscribe("rov_forces", 10, &Allocator::callback, this);
pub = nh.advertise<vortex_msgs::ThrusterForces>("thruster_forces", 10);
if (!nh.getParam("/propulsion/dofs/num", num_dof))
ROS_FATAL("Failed to read parameter number of dofs.");
if (!nh.getParam("/propulsion/thrusters/num", num_thrusters))
ROS_FATAL("Failed to read parameter number of thrusters.");
if (!nh.getParam("/propulsion/dofs/which", dofs))
ROS_FATAL("Failed to read parameter which dofs.");
// Read thrust limits
std::vector<double> thrust;
if (!nh.getParam("/thrust", thrust))
{
min_thrust = -std::numeric_limits<double>::infinity();
max_thrust = std::numeric_limits<double>::infinity();
ROS_ERROR_STREAM("Failed to read parameters min/max thrust. Defaulting to " << min_thrust << "/" << max_thrust << ".");
}
else
{
min_thrust = thrust.front();
max_thrust = thrust.back();
}
// Read thrust config matrix
Eigen::MatrixXd thrust_configuration;
if (!getMatrixParam(nh, "propulsion/thrusters/configuration_matrix", thrust_configuration))
ROS_FATAL("Failed to read parameter thrust config matrix.");
Eigen::MatrixXd thrust_configuration_pseudoinverse;
if (!pseudoinverse(thrust_configuration, thrust_configuration_pseudoinverse))
ROS_FATAL("Failed to compute pseudoinverse of thrust config matrix.");
printEigen("T_pinv", thrust_configuration_pseudoinverse);
Eigen::MatrixXd force_coefficient_inverse = Eigen::MatrixXd::Identity(num_thrusters, num_thrusters);
pseudoinverse_allocator = new PseudoinverseAllocator(thrust_configuration_pseudoinverse, force_coefficient_inverse);
ROS_INFO("Allocator: Initialized.");
}
// inline bool saturateVector(Eigen::VectorXd &v, double min, double max)
void Allocator::callback(const geometry_msgs::Wrench &msg)
{
Eigen::VectorXd tau = rovForcesMsgToEigen(msg);
Eigen::VectorXd u(num_thrusters);
u = pseudoinverse_allocator->compute(tau);
if (isFucked(u))
{
ROS_ERROR("Thrust vector u invalid, will not publish.");
return;
}
if (!saturateVector(u, min_thrust, max_thrust))
ROS_WARN("Thrust vector u required saturation.");
vortex_msgs::ThrusterForces u_msg;
thrustEigenToMsg(u, u_msg);
pub.publish(u_msg);
}
Eigen::VectorXd Allocator::rovForcesMsgToEigen(const geometry_msgs::Wrench &msg)
{
// TODO: rewrite without a million ifs
Eigen::VectorXd tau(num_dof);
int i = 0;
if (dofs["surge"])
{
tau(i) = msg.force.x;
++i;
}
if (dofs["sway"])
{
tau(i) = msg.force.y;
++i;
}
if (dofs["heave"])
{
tau(i) = msg.force.z;
++i;
}
if (dofs["roll"])
{
tau(i) = msg.torque.x;
++i;
}
if (dofs["pitch"])
{
tau(i) = msg.torque.y;
++i;
}
if (dofs["yaw"])
{
tau(i) = msg.torque.z;
++i;
}
if (i != num_dof)
{
ROS_WARN_STREAM("Allocator: Invalid length of tau vector. Is " << i << ", should be " << num_dof << ". Returning zero thrust vector.");
return Eigen::VectorXd::Zero(num_dof);
}
return tau;
}
<commit_msg>Remove a print statement<commit_after>#include "allocator_ros.h"
#include <vector>
#include <limits>
#include <eigen_conversions/eigen_msg.h>
#include "vortex_msgs/ThrusterForces.h"
#include "uranus_dp/eigen_typedefs.h"
#include "uranus_dp/eigen_helper.h"
Allocator::Allocator(ros::NodeHandle nh) : nh(nh)
{
sub = nh.subscribe("rov_forces", 10, &Allocator::callback, this);
pub = nh.advertise<vortex_msgs::ThrusterForces>("thruster_forces", 10);
if (!nh.getParam("/propulsion/dofs/num", num_dof))
ROS_FATAL("Failed to read parameter number of dofs.");
if (!nh.getParam("/propulsion/thrusters/num", num_thrusters))
ROS_FATAL("Failed to read parameter number of thrusters.");
if (!nh.getParam("/propulsion/dofs/which", dofs))
ROS_FATAL("Failed to read parameter which dofs.");
// Read thrust limits
std::vector<double> thrust;
if (!nh.getParam("/thrust", thrust))
{
min_thrust = -std::numeric_limits<double>::infinity();
max_thrust = std::numeric_limits<double>::infinity();
ROS_ERROR_STREAM("Failed to read parameters min/max thrust. Defaulting to " << min_thrust << "/" << max_thrust << ".");
}
else
{
min_thrust = thrust.front();
max_thrust = thrust.back();
}
// Read thrust config matrix
Eigen::MatrixXd thrust_configuration;
if (!getMatrixParam(nh, "propulsion/thrusters/configuration_matrix", thrust_configuration))
ROS_FATAL("Failed to read parameter thrust config matrix.");
Eigen::MatrixXd thrust_configuration_pseudoinverse;
if (!pseudoinverse(thrust_configuration, thrust_configuration_pseudoinverse))
ROS_FATAL("Failed to compute pseudoinverse of thrust config matrix.");
Eigen::MatrixXd force_coefficient_inverse = Eigen::MatrixXd::Identity(num_thrusters, num_thrusters);
pseudoinverse_allocator = new PseudoinverseAllocator(thrust_configuration_pseudoinverse, force_coefficient_inverse);
ROS_INFO("Allocator: Initialized.");
}
// inline bool saturateVector(Eigen::VectorXd &v, double min, double max)
void Allocator::callback(const geometry_msgs::Wrench &msg)
{
Eigen::VectorXd tau = rovForcesMsgToEigen(msg);
Eigen::VectorXd u(num_thrusters);
u = pseudoinverse_allocator->compute(tau);
if (isFucked(u))
{
ROS_ERROR("Thrust vector u invalid, will not publish.");
return;
}
if (!saturateVector(u, min_thrust, max_thrust))
ROS_WARN("Thrust vector u required saturation.");
vortex_msgs::ThrusterForces u_msg;
thrustEigenToMsg(u, u_msg);
pub.publish(u_msg);
}
Eigen::VectorXd Allocator::rovForcesMsgToEigen(const geometry_msgs::Wrench &msg)
{
// TODO: rewrite without a million ifs
Eigen::VectorXd tau(num_dof);
int i = 0;
if (dofs["surge"])
{
tau(i) = msg.force.x;
++i;
}
if (dofs["sway"])
{
tau(i) = msg.force.y;
++i;
}
if (dofs["heave"])
{
tau(i) = msg.force.z;
++i;
}
if (dofs["roll"])
{
tau(i) = msg.torque.x;
++i;
}
if (dofs["pitch"])
{
tau(i) = msg.torque.y;
++i;
}
if (dofs["yaw"])
{
tau(i) = msg.torque.z;
++i;
}
if (i != num_dof)
{
ROS_WARN_STREAM("Allocator: Invalid length of tau vector. Is " << i << ", should be " << num_dof << ". Returning zero thrust vector.");
return Eigen::VectorXd::Zero(num_dof);
}
return tau;
}
<|endoftext|> |
<commit_before>/******************************************************************************
Copyright (c) Dmitri Dolzhenko
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
#pragma once
//------------------------------------------------------------------------------
// include local:
// include std:
#include <vector>
#include <list>
#include <set>
#include <cassert>
#include <string>
#include <map> // Tests
#include <algorithm> // std::find
#include <functional> // std::fucntion
#include <iostream>
#include <iomanip>
// forward declarations:
//------------------------------------------------------------------------------
namespace limo {
class LocalTestContext;
typedef std::string Name;
typedef std::function<LocalTestContext*(void)> TestContextGetter;
typedef std::function<void (TestContextGetter&)> TestFunction;
typedef std::function<void(void)> PrepareFunction;
typedef std::map<Name, TestFunction> Tests;
struct Result
{
const char* expected;
const char* recieved;
const char* file;
const int line;
const bool ok;
friend std::ostream& operator<<(std::ostream& o, const Result& result)
{
return o << result.file << ":" << result.line << ":: "
<< (result.ok ? "ok" : "failed") << ": "
<< result.expected << std::endl;
};
};
struct Statistics {
size_t total, passed, failured, crashed;
Statistics(): total(0), passed(0), failured(0), crashed(0) {}
bool is_valid() const { return total == passed + failured + crashed; }
void add_result(Result& result) {
assert(is_valid());
++total;
if(result.ok) {
++passed;
}
else {
++failured;
std::cout << result;
}
assert(is_valid());
}
void expect_true(const char* file, int line, const char* expected, bool ok) {
Result result = {expected, ok ? "true" : "false", file, line, ok};
add_result(result);
}
Statistics& operator+=(const Statistics& rhs) {
assert(is_valid() && rhs.is_valid());
total += rhs.total;
passed += rhs.passed;
failured += rhs.failured;
crashed += rhs.crashed;
return *this;
}
friend std::ostream& operator<<(std::ostream& o, const Statistics& stats) {
assert(stats.is_valid());
return o << " crashed " << stats.crashed
<< ", failured " << stats.failured
<< ", passed " << stats.passed
<< ", total " << stats.total
<< ".";
}
};
class LocalTestContext {
public:
static const bool m_verbose = true;
PrepareFunction m_before;
PrepareFunction m_after;
Statistics stats;
Name m_name;
public:
LocalTestContext(Name name)
: m_name(name)
, m_before([](){})
, m_after([](){})
{
if(m_verbose) std::cout << m_name << std::endl;
}
virtual void test(Name name, TestFunction test)
{
run_test(name, test, m_name+".");
}
void run_test(Name name, TestFunction test, Name basename) {
m_before();
LocalTestContext context(basename + name);
TestContextGetter getter = [&context]() { return &context; };
test(getter);
stats += context.stats;
m_after();
}
};
class GlobalTestContext : public LocalTestContext {
public:
Tests m_tests;
GlobalTestContext(): LocalTestContext("root") {}
void test(Name name, TestFunction test) {
m_tests[name] = test;
}
int run() {
for(const auto& test : m_tests) {
run_test(test.first, test.second, "");
}
std::cout << stats << std::endl;
return 0;
}
};
struct TestSettings {
TestSettings(Name name, LocalTestContext* suite): m_name(name), m_context(suite) {}
TestSettings& operator<<(TestFunction test) {
m_test = test;
return *this;
}
Name m_name;
LocalTestContext* m_context;
TestFunction m_test;
};
struct Registrator {
Registrator(const TestSettings& w) {
w.m_context->test(w.m_name, w.m_test);
}
};
struct To { template <class T> To(const T&) {} };
// #define LTEST(test_name, ...) \
// To doreg##test_name = \
// get_ltest_context()->add(#test_name)
// limo::TestSettings(#test_name, get_ltest_context()) << \
// [__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LTEST(test_name, ...) \
limo::Registrator ltest_ ## test_name = \
limo::TestSettings(#test_name, get_ltest_context()) << \
[__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LBEFORE get_ltest_context()->m_before = [&]()
#define LAFTER get_ltest_context()->m_after = [&]()
// Unary
#define EXPECT_TRUE(expr) get_ltest_context()->stats.expect_true(__FILE__, __LINE__, #expr, expr)
#define EXPECT_FALSE(expr) EXPECT_TRUE(!(expr))
// Binary
#define EXPECT_EQ(expr1, expr2) EXPECT_TRUE((expr1) == (expr2))
#define EXPECT_NE(expr1, expr2) EXPECT_TRUE((expr1) != (expr2))
#define EXPECT_LT(expr1, expr2) EXPECT_TRUE((expr1) < (expr2))
#define EXPECT_LE(expr1, expr2) EXPECT_TRUE((expr1) <= (expr2))
#define EXPECT_GT(expr1, expr2) EXPECT_TRUE((expr1) > (expr2))
#define EXPECT_GE(expr1, expr2) EXPECT_TRUE((expr1) >= (expr2))
// Complex
template <class T1, class T2>
bool in(const std::initializer_list<T1>& s, const T2& x) {
return std::find(s.begin(), s.end(), x) != s.end();
}
////////////////////////////////////////////////////////////////////////////////////////
} // namespace limo
//------------------------------------------------------------------------------
// globals
inline limo::GlobalTestContext* get_ltest_context() {
static limo::GlobalTestContext context;
return &context;
}
//------------------------------------------------------------------------------
<commit_msg>warnings fixed<commit_after>/******************************************************************************
Copyright (c) Dmitri Dolzhenko
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
#pragma once
//------------------------------------------------------------------------------
// include local:
// include std:
#include <vector>
#include <list>
#include <set>
#include <cassert>
#include <string>
#include <map> // Tests
#include <algorithm> // std::find
#include <functional> // std::fucntion
#include <iostream>
#include <iomanip>
// forward declarations:
//------------------------------------------------------------------------------
namespace limo {
class LocalTestContext;
typedef std::string Name;
typedef std::function<LocalTestContext*(void)> TestContextGetter;
typedef std::function<void (TestContextGetter&)> TestFunction;
typedef std::function<void(void)> PrepareFunction;
typedef std::map<Name, TestFunction> Tests;
struct Result
{
const char* expected;
const char* recieved;
const char* file;
const int line;
const bool ok;
friend std::ostream& operator<<(std::ostream& o, const Result& result)
{
return o << result.file << ":" << result.line << ":: "
<< (result.ok ? "ok" : "failed") << ": "
<< result.expected << std::endl;
};
};
struct Statistics {
size_t total, passed, failured, crashed;
Statistics(): total(0), passed(0), failured(0), crashed(0) {}
bool is_valid() const { return total == passed + failured + crashed; }
void add_result(Result& result) {
assert(is_valid());
++total;
if(result.ok) {
++passed;
}
else {
++failured;
std::cout << result;
}
assert(is_valid());
}
void expect_true(const char* file, int line, const char* expected, bool ok) {
Result result = {expected, ok ? "true" : "false", file, line, ok};
add_result(result);
}
Statistics& operator+=(const Statistics& rhs) {
assert(is_valid() && rhs.is_valid());
total += rhs.total;
passed += rhs.passed;
failured += rhs.failured;
crashed += rhs.crashed;
return *this;
}
friend std::ostream& operator<<(std::ostream& o, const Statistics& stats) {
assert(stats.is_valid());
return o << " crashed " << stats.crashed
<< ", failured " << stats.failured
<< ", passed " << stats.passed
<< ", total " << stats.total
<< ".";
}
};
class LocalTestContext {
public:
static const bool m_verbose = true;
Name m_name;
PrepareFunction m_before;
PrepareFunction m_after;
Statistics stats;
public:
LocalTestContext(Name name)
: m_name(name)
, m_before([](){})
, m_after([](){})
{
if(m_verbose) std::cout << m_name << std::endl;
}
virtual void test(Name name, TestFunction test)
{
run_test(name, test, m_name+".");
}
void run_test(Name name, TestFunction test, Name basename) {
m_before();
LocalTestContext context(basename + name);
TestContextGetter getter = [&context]() { return &context; };
test(getter);
stats += context.stats;
m_after();
}
};
class GlobalTestContext : public LocalTestContext {
public:
Tests m_tests;
GlobalTestContext(): LocalTestContext("root") {}
void test(Name name, TestFunction test) {
m_tests[name] = test;
}
int run() {
for(const auto& test : m_tests) {
run_test(test.first, test.second, "");
}
std::cout << stats << std::endl;
return 0;
}
};
struct TestSettings {
TestSettings(Name name, LocalTestContext* suite): m_name(name), m_context(suite) {}
TestSettings& operator<<(TestFunction test) {
m_test = test;
return *this;
}
Name m_name;
LocalTestContext* m_context;
TestFunction m_test;
};
struct Registrator {
Registrator(const TestSettings& w) {
w.m_context->test(w.m_name, w.m_test);
}
};
struct To { template <class T> To(const T&) {} };
#define LTEST(test_name, ...) \
limo::Registrator ltest_ ## test_name = \
limo::TestSettings(#test_name, get_ltest_context()) << \
[__VA_ARGS__](limo::TestContextGetter& get_ltest_context) mutable -> void
#define LBEFORE get_ltest_context()->m_before = [&]()
#define LAFTER get_ltest_context()->m_after = [&]()
// Unary
#define EXPECT_TRUE(expr) get_ltest_context()->stats.expect_true(__FILE__, __LINE__, #expr, expr)
#define EXPECT_FALSE(expr) EXPECT_TRUE(!(expr))
#define EXPECT(expr) EXPECT_TRUE(expr)
// Binary
#define EXPECT_EQ(expr1, expr2) EXPECT_TRUE((expr1) == (expr2))
#define EXPECT_NE(expr1, expr2) EXPECT_TRUE((expr1) != (expr2))
#define EXPECT_LT(expr1, expr2) EXPECT_TRUE((expr1) < (expr2))
#define EXPECT_LE(expr1, expr2) EXPECT_TRUE((expr1) <= (expr2))
#define EXPECT_GT(expr1, expr2) EXPECT_TRUE((expr1) > (expr2))
#define EXPECT_GE(expr1, expr2) EXPECT_TRUE((expr1) >= (expr2))
// Complex
template <class T1, class T2>
bool in(const std::initializer_list<T1>& s, const T2& x) {
return std::find(s.begin(), s.end(), x) != s.end();
}
////////////////////////////////////////////////////////////////////////////////////////
} // namespace limo
//------------------------------------------------------------------------------
// globals
inline limo::GlobalTestContext* get_ltest_context() {
static limo::GlobalTestContext context;
return &context;
}
//------------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999, 2000 Stefan Seefeld <stefan@berlin-consortium.org>
* Copyright (C) 1999 Graydon Hoare <graydon@pobox.com>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/Sys/Tracer.hh>
#include <Prague/Sys/Signal.hh>
#include <Prague/Sys/Profiler.hh>
#include <Prague/Sys/Timer.hh>
#include <Prague/Sys/Path.hh>
#include <Prague/Sys/User.hh>
#include <Prague/Sys/Fork.hh>
#include <Prague/Sys/GetOpt.hh>
#include <Warsaw/config.hh>
#include <Warsaw/resolve.hh>
#include <Warsaw/LayoutKit.hh>
#include <Warsaw/ToolKit.hh>
#include <Warsaw/DrawingKit.hh>
#include <Berlin/RCManager.hh>
#include <Berlin/ScreenImpl.hh>
#include <Berlin/ScreenManager.hh>
#include <Berlin/ServerImpl.hh>
#include <Berlin/Console.hh>
#include <Berlin/Logger.hh>
#include <Berlin/DesktopImpl.hh>
#include <fstream>
#include <strstream>
#ifdef RC_PREFIX
const std::string prefix = RC_PREFIX;
#else
const std::string prefix = "";
#endif
#ifdef VERSION
const std::string version = VERSION;
#else
const std::string version = "unknown";
#endif
#ifdef JPROF
// probably need to change include path
#include "jprof.h"
#endif
using namespace Prague;
using namespace Warsaw;
struct Dump : Signal::Notifier
{
void notify(int signo)
{
switch (signo)
{
case Signal::usr2:
Console::activate_autoplay();
Console::wakeup();
return;
case Signal::hangup: Profiler::dump(cerr); break;
case Signal::abort:
case Signal::segv:
{
std::string output = "server.log";
std::ofstream ofs(output.c_str());
Logger::dump(ofs);
Tracer::dump(ofs);
std::cerr << "Something went wrong. '" << output << "' contains a debugging log.\n"
<< "Please mail this output to bugs@berlin-consortium.org\n\n";
exit(-1);
}
}
}
};
//. Execute a client using the command in 'value'. The process is stored in
//. client
void exec_child(Fork*& child, std::string& value)
{
// Fork to create child process to execute client in
child = new Fork(true, true);
if (child->child())
{
std::vector<char*> args;
// Split 'value' into command and arguments for execvp
int start = 0, index = 0;
value.push_back('\0');
while ( (index = value.find(' ', index)) != std::string::npos)
{
value[index] = '\0';
args.push_back(&*value.begin() + start);
start = index + 1;
}
args.push_back(&*value.begin() + start);
args.push_back(0);
// Execute command
execvp(args[0], &*args.begin());
// Should not get here
perror("client execvp");
exit(1);
}
// Attempt to kill client on these signals
child->suicide_on_signal(Signal::interrupt);
child->suicide_on_signal(Signal::quit);
child->suicide_on_signal(Signal::abort);
child->suicide_on_signal(Signal::segv);
}
int main(int argc, char **argv)
{
/*
* start with some administrative stuff...
*/
Dump *dump = new Dump;
Signal::set(Signal::usr2, dump);
Signal::set(Signal::abort, dump);
Signal::set(Signal::segv, dump);
Signal::set(Signal::hangup, dump);
if (~prefix.empty()) RCManager::read(prefix + "/share/berlin/berlinrc");
const char *rcfile = getenv("BERLINRC");
if (rcfile) RCManager::read(Prague::Path::expand_user(rcfile));
else RCManager::read(std::string(User().home()) + "/.berlin");
GetOpt getopt(argv[0], "a berlin display server");
getopt.add('h', "help", GetOpt::novalue, "help message");
getopt.add('v', "version", GetOpt::novalue, "version number");
getopt.add('l', "logger", GetOpt::optional, "switch logging on");
getopt.add('t', "tracer", GetOpt::novalue, "switch tracing on");
getopt.add('p', "profiler", GetOpt::novalue, "switch profiling on");
getopt.add('d', "drawing", GetOpt::mandatory, "the DrawingKit to choose");
getopt.add('r', "resource", GetOpt::mandatory, "the resource file to load");
getopt.add('e', "execute", GetOpt::mandatory, "the command to execute upon startup");
size_t argo = getopt.parse(argc, argv);
argc -= argo;
argv += argo;
if (getopt.is_set("version")) { cout << "version is " << version << endl; return 0;}
if (getopt.is_set("help")) { getopt.usage(); return 0;}
std::string value;
if (getopt.get("resource", &value))
RCManager::read(Prague::Path::expand_user(value));
else {
getopt.usage();
exit(1);
}
value = "";
if (getopt.get("logger", &value))
{
if (!value.empty())
{
std::istrstream iss(value.c_str());
std::string token;
while (iss >> token)
{
if (token == "corba") Logger::set(Logger::corba);
else if (token == "lifecycle") Logger::set(Logger::lifecycle);
else if (token == "focus") Logger::set(Logger::focus);
else if (token == "image") Logger::set(Logger::image);
else if (token == "loader") Logger::set(Logger::loader);
else if (token == "console") Logger::set(Logger::console);
else if (token == "subject") Logger::set(Logger::subject);
else if (token == "layout") Logger::set(Logger::layout);
else if (token == "picking") Logger::set(Logger::picking);
else if (token == "drawing") Logger::set(Logger::drawing);
else if (token == "traversal") Logger::set(Logger::traversal);
else if (token == "widget") Logger::set(Logger::widget);
else if (token == "text") Logger::set(Logger::text);
else if (token == "desktop") Logger::set(Logger::desktop);
}
}
else Logger::setall();
}
if (getopt.is_set("tracer")) Tracer::logging(true);
#ifdef JPROF
if (getopt.is_set("profiler")) setupProfilingStuff();
#endif
/*
* ...then start the ORB...
*/
omniORB::maxTcpConnectionPerServer = 10;
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
PortableServer::POA_var poa = resolve_init<PortableServer::POA>(orb, "RootPOA");
PortableServer::POAManager_var pman = poa->the_POAManager();
pman->activate();
Logger::log(Logger::corba) << "root POA is activated" << std::endl;
Console::open(argc, argv, poa);
Logger::log(Logger::console) << "console is initialized" << std::endl;
/*
* ...and finally construct the server.
*/
ServerImpl *server = ServerImpl::instance();
Prague::Path path = RCManager::get_path("modulepath");
for (Prague::Path::iterator i = path.begin(); i != path.end(); ++i)
server->scan(*i);
Logger::log(Logger::loader) << "modules are loaded" << std::endl;
Kit::PropertySeq props;
props.length(1);
props[0].name = CORBA::string_dup("implementation");
value = "";
getopt.get("drawing", &value);
if (!value.empty()) props[0].value = CORBA::string_dup(value.c_str());
else props[0].value = CORBA::string_dup("LibArtDrawingKit");
DrawingKit_var drawing = server->resolve<DrawingKit>("IDL:Warsaw/DrawingKit:1.0", props, poa);
if (CORBA::is_nil(drawing))
{
std::cerr << "unable to open " << "IDL:Warsaw/DrawingKit:1.0" << " with attribute "
<< props[0].name << '=' << props[0].value << std::endl;
return -1;
}
Logger::log(Logger::drawing) << "drawing system is built" << std::endl;
// make a Screen graphic to hold this server's scene graph
ScreenImpl *screen = new ScreenImpl();
EventManager *emanager = new EventManager(Controller_var(screen->_this()), screen->allocation());
ScreenManager *smanager = new ScreenManager(Graphic_var(screen->_this()), emanager, drawing);
screen->bind_managers(emanager, smanager);
props.length(0);
ToolKit_var tools = server->resolve<ToolKit>("IDL:Warsaw/ToolKit:1.0", props, poa);
LayoutKit_var layout = server->resolve<LayoutKit>("IDL:Warsaw/LayoutKit:1.0", props, poa);
Layout::Stage_var stage = layout->create_stage();
DesktopImpl *desktop = new DesktopImpl(stage);
screen->body(Desktop_var(desktop->_this()));
screen->append_controller(Desktop_var(desktop->_this()));
Logger::log(Logger::layout) << "desktop is created" << std::endl;
// initialize the client listener
server->set_singleton("IDL:Warsaw/Desktop:1.0", Desktop_var(desktop->_this()));
server->set_singleton("IDL:Warsaw/DrawingKit:1.0", drawing);
server->start();
Logger::log(Logger::layout) << "started server" << std::endl;
bind_name(orb, Server_var(server->_this()), "IDL:Warsaw/Server:1.0");
Logger::log(Logger::corba) << "listening for clients" << std::endl;
// initialize the event distributor and draw thread
Logger::log(Logger::corba) << "event manager is constructed" << std::endl;
// Start client via --execute argument
Fork *child = NULL;
value = "";
getopt.get("execute", &value);
if (!value.empty())
exec_child(child, value);
try
{
smanager->run();
}
catch (CORBA::SystemException &se)
{
std::cout << "system exception " << std::endl;
}
catch(omniORB::fatalException &fe)
{
std::cerr << "fatal exception at " << fe.file() << " " << fe.line() << ":" << fe.errmsg() << std::endl;
}
catch (...)
{
std::cout << "unknown exception caught" << std::endl;
};
if (child) delete child;
orb->destroy();
return 0;
}
<commit_msg> * changed comment for -r option to include (mandatory) added * exception handler around bind_name() call in main(). This will catch cases where the name server is not running gracefully.<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999, 2000 Stefan Seefeld <stefan@berlin-consortium.org>
* Copyright (C) 1999 Graydon Hoare <graydon@pobox.com>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/Sys/Tracer.hh>
#include <Prague/Sys/Signal.hh>
#include <Prague/Sys/Profiler.hh>
#include <Prague/Sys/Timer.hh>
#include <Prague/Sys/Path.hh>
#include <Prague/Sys/User.hh>
#include <Prague/Sys/Fork.hh>
#include <Prague/Sys/GetOpt.hh>
#include <Warsaw/config.hh>
#include <Warsaw/resolve.hh>
#include <Warsaw/LayoutKit.hh>
#include <Warsaw/ToolKit.hh>
#include <Warsaw/DrawingKit.hh>
#include <Berlin/RCManager.hh>
#include <Berlin/ScreenImpl.hh>
#include <Berlin/ScreenManager.hh>
#include <Berlin/ServerImpl.hh>
#include <Berlin/Console.hh>
#include <Berlin/Logger.hh>
#include <Berlin/DesktopImpl.hh>
#include <fstream>
#include <strstream>
#ifdef RC_PREFIX
const std::string prefix = RC_PREFIX;
#else
const std::string prefix = "";
#endif
#ifdef VERSION
const std::string version = VERSION;
#else
const std::string version = "unknown";
#endif
#ifdef JPROF
// probably need to change include path
#include "jprof.h"
#endif
using namespace Prague;
using namespace Warsaw;
struct Dump : Signal::Notifier
{
void notify(int signo)
{
switch (signo)
{
case Signal::usr2:
Console::activate_autoplay();
Console::wakeup();
return;
case Signal::hangup: Profiler::dump(cerr); break;
case Signal::abort:
case Signal::segv:
{
std::string output = "server.log";
std::ofstream ofs(output.c_str());
Logger::dump(ofs);
Tracer::dump(ofs);
std::cerr << "Something went wrong. '" << output << "' contains a debugging log.\n"
<< "Please mail this output to bugs@berlin-consortium.org\n\n";
exit(-1);
}
}
}
};
//. Execute a client using the command in 'value'. The process is stored in
//. client
void exec_child(Fork*& child, std::string& value)
{
// Fork to create child process to execute client in
child = new Fork(true, true);
if (child->child())
{
std::vector<char*> args;
// Split 'value' into command and arguments for execvp
int start = 0, index = 0;
value.push_back('\0');
while ( (index = value.find(' ', index)) != std::string::npos)
{
value[index] = '\0';
args.push_back(&*value.begin() + start);
start = index + 1;
}
args.push_back(&*value.begin() + start);
args.push_back(0);
// Execute command
execvp(args[0], &*args.begin());
// Should not get here
perror("client execvp");
exit(1);
}
// Attempt to kill client on these signals
child->suicide_on_signal(Signal::interrupt);
child->suicide_on_signal(Signal::quit);
child->suicide_on_signal(Signal::abort);
child->suicide_on_signal(Signal::segv);
}
int main(int argc, char **argv)
{
/*
* start with some administrative stuff...
*/
Dump *dump = new Dump;
Signal::set(Signal::usr2, dump);
Signal::set(Signal::abort, dump);
Signal::set(Signal::segv, dump);
Signal::set(Signal::hangup, dump);
if (~prefix.empty()) RCManager::read(prefix + "/share/berlin/berlinrc");
const char *rcfile = getenv("BERLINRC");
if (rcfile) RCManager::read(Prague::Path::expand_user(rcfile));
else RCManager::read(std::string(User().home()) + "/.berlin");
GetOpt getopt(argv[0], "a berlin display server");
getopt.add('h', "help", GetOpt::novalue, "help message");
getopt.add('v', "version", GetOpt::novalue, "version number");
getopt.add('l', "logger", GetOpt::optional, "switch logging on");
getopt.add('t', "tracer", GetOpt::novalue, "switch tracing on");
getopt.add('p', "profiler", GetOpt::novalue, "switch profiling on");
getopt.add('d', "drawing", GetOpt::mandatory, "the DrawingKit to choose");
getopt.add('r', "resource", GetOpt::mandatory, "the resource file to load (mandatory)");
getopt.add('e', "execute", GetOpt::mandatory, "the command to execute upon startup");
size_t argo = getopt.parse(argc, argv);
argc -= argo;
argv += argo;
if (getopt.is_set("version")) { cout << "version is " << version << endl; return 0;}
if (getopt.is_set("help")) { getopt.usage(); return 0;}
std::string value;
if (getopt.get("resource", &value))
RCManager::read(Prague::Path::expand_user(value));
else {
getopt.usage();
exit(1);
}
value = "";
if (getopt.get("logger", &value))
{
if (!value.empty())
{
std::istrstream iss(value.c_str());
std::string token;
while (iss >> token)
{
if (token == "corba") Logger::set(Logger::corba);
else if (token == "lifecycle") Logger::set(Logger::lifecycle);
else if (token == "focus") Logger::set(Logger::focus);
else if (token == "image") Logger::set(Logger::image);
else if (token == "loader") Logger::set(Logger::loader);
else if (token == "console") Logger::set(Logger::console);
else if (token == "subject") Logger::set(Logger::subject);
else if (token == "layout") Logger::set(Logger::layout);
else if (token == "picking") Logger::set(Logger::picking);
else if (token == "drawing") Logger::set(Logger::drawing);
else if (token == "traversal") Logger::set(Logger::traversal);
else if (token == "widget") Logger::set(Logger::widget);
else if (token == "text") Logger::set(Logger::text);
else if (token == "desktop") Logger::set(Logger::desktop);
}
}
else Logger::setall();
}
if (getopt.is_set("tracer")) Tracer::logging(true);
#ifdef JPROF
if (getopt.is_set("profiler")) setupProfilingStuff();
#endif
/*
* ...then start the ORB...
*/
omniORB::maxTcpConnectionPerServer = 10;
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
PortableServer::POA_var poa = resolve_init<PortableServer::POA>(orb, "RootPOA");
PortableServer::POAManager_var pman = poa->the_POAManager();
pman->activate();
Logger::log(Logger::corba) << "root POA is activated" << std::endl;
Console::open(argc, argv, poa);
Logger::log(Logger::console) << "console is initialized" << std::endl;
/*
* ...and finally construct the server.
*/
ServerImpl *server = ServerImpl::instance();
Prague::Path path = RCManager::get_path("modulepath");
for (Prague::Path::iterator i = path.begin(); i != path.end(); ++i)
server->scan(*i);
Logger::log(Logger::loader) << "modules are loaded" << std::endl;
Kit::PropertySeq props;
props.length(1);
props[0].name = CORBA::string_dup("implementation");
value = "";
getopt.get("drawing", &value);
if (!value.empty()) props[0].value = CORBA::string_dup(value.c_str());
else props[0].value = CORBA::string_dup("LibArtDrawingKit");
DrawingKit_var drawing = server->resolve<DrawingKit>("IDL:Warsaw/DrawingKit:1.0", props, poa);
if (CORBA::is_nil(drawing))
{
std::cerr << "unable to open " << "IDL:Warsaw/DrawingKit:1.0" << " with attribute "
<< props[0].name << '=' << props[0].value << std::endl;
return -1;
}
Logger::log(Logger::drawing) << "drawing system is built" << std::endl;
// make a Screen graphic to hold this server's scene graph
ScreenImpl *screen = new ScreenImpl();
EventManager *emanager = new EventManager(Controller_var(screen->_this()), screen->allocation());
ScreenManager *smanager = new ScreenManager(Graphic_var(screen->_this()), emanager, drawing);
screen->bind_managers(emanager, smanager);
props.length(0);
ToolKit_var tools = server->resolve<ToolKit>("IDL:Warsaw/ToolKit:1.0", props, poa);
LayoutKit_var layout = server->resolve<LayoutKit>("IDL:Warsaw/LayoutKit:1.0", props, poa);
Layout::Stage_var stage = layout->create_stage();
DesktopImpl *desktop = new DesktopImpl(stage);
screen->body(Desktop_var(desktop->_this()));
screen->append_controller(Desktop_var(desktop->_this()));
Logger::log(Logger::layout) << "desktop is created" << std::endl;
// initialize the client listener
server->set_singleton("IDL:Warsaw/Desktop:1.0", Desktop_var(desktop->_this()));
server->set_singleton("IDL:Warsaw/DrawingKit:1.0", drawing);
server->start();
Logger::log(Logger::layout) << "started server" << std::endl;
try {
bind_name(orb, Server_var(server->_this()), "IDL:Warsaw/Server:1.0");
} catch (CORBA::COMM_FAILURE) {
std::cerr << "CORBA communications failure finding Warsaw." << std::endl
<< "Are you sure the name service is running?" << std::endl;
return -1;
} catch (...) {
std::cerr << "Unknown exception finding Warsaw" << std::endl;
return -1;
}
Logger::log(Logger::corba) << "listening for clients" << std::endl;
// initialize the event distributor and draw thread
Logger::log(Logger::corba) << "event manager is constructed" << std::endl;
// Start client via --execute argument
Fork *child = NULL;
value = "";
getopt.get("execute", &value);
if (!value.empty())
exec_child(child, value);
try
{
smanager->run();
}
catch (CORBA::SystemException &se)
{
std::cout << "system exception " << std::endl;
}
catch(omniORB::fatalException &fe)
{
std::cerr << "fatal exception at " << fe.file() << " " << fe.line() << ":" << fe.errmsg() << std::endl;
}
catch (...)
{
std::cout << "unknown exception caught" << std::endl;
};
if (child) delete child;
orb->destroy();
return 0;
}
<|endoftext|> |
<commit_before>#include "hext/pattern/capture-pattern.h"
namespace hext {
capture_pattern::capture_pattern(
const std::string& result_name,
const std::string& regex
)
: name(result_name)
, rx(regex.empty() ? nullptr : make_unique<boost::regex>(regex))
{
}
capture_pattern::~capture_pattern()
{
}
std::string capture_pattern::regex_filter(const char * str) const
{
assert(this->rx);
if( !this->rx )
return str;
boost::match_results<const char *> mr;
if( boost::regex_search(str, str + strlen(str), mr, *(this->rx)) )
{
// If there are no captures, return whole string (mr[0]), if there are
// captures, then return the first one
if( mr.size() > 1 )
return mr[1];
else
return mr[0];
}
else
{
return "";
}
}
} // namespace hext
<commit_msg>add missing capture_pattern constructor implementation<commit_after>#include "hext/pattern/capture-pattern.h"
namespace hext {
capture_pattern::capture_pattern(const std::string& result_name)
: name(result_name)
, rx(nullptr)
{
}
capture_pattern::capture_pattern(
const std::string& result_name,
const std::string& regex
)
: name(result_name)
, rx(regex.empty() ? nullptr : make_unique<boost::regex>(regex))
{
}
capture_pattern::~capture_pattern()
{
}
std::string capture_pattern::regex_filter(const char * str) const
{
assert(this->rx);
if( !this->rx )
return str;
boost::match_results<const char *> mr;
if( boost::regex_search(str, str + strlen(str), mr, *(this->rx)) )
{
// If there are no captures, return whole string (mr[0]), if there are
// captures, then return the first one
if( mr.size() > 1 )
return mr[1];
else
return mr[0];
}
else
{
return "";
}
}
} // namespace hext
<|endoftext|> |
<commit_before>#include "./mouse_wheel_transition.h"
#include <QDebug>
MouseWheelTransition::MouseWheelTransition(QObject *object, QState *sourceState)
: QEventTransition(object, QEvent::Scroll, sourceState)
{
}
MouseWheelTransition::~MouseWheelTransition()
{
}
bool MouseWheelTransition::eventTest(QEvent *event)
{
qWarning() << "eventTest" << event->type();
return event->type() == QEvent::Scroll;
}
void MouseWheelTransition::onTransition(QEvent *event)
{
this->event = event;
}
<commit_msg>Use right event type Wheel instead of Scroll.<commit_after>#include "./mouse_wheel_transition.h"
#include <QDebug>
MouseWheelTransition::MouseWheelTransition(QObject *object, QState *sourceState)
: QEventTransition(object, QEvent::Wheel, sourceState)
{
}
MouseWheelTransition::~MouseWheelTransition()
{
}
bool MouseWheelTransition::eventTest(QEvent *event)
{
qWarning() << "eventTest" << event->type();
return event->type() == QEvent::Scroll;
}
void MouseWheelTransition::onTransition(QEvent *event)
{
this->event = event;
}
<|endoftext|> |
<commit_before>/**
* Copyright 2008 Matthew Graham
* 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 "shession_client.h"
#include <iostream>
#include <list>
#include <sstream>
#include <time.h>
void run_load( int n )
{
shession_client_c client;
if ( ! client.open( "127.0.0.1", 9000 ) ) {
std::cerr << "Error connecting socket.\n";
return;
}
// create session ids in memory
std::list< std::string > sessions;
for ( int i( 0 ); i<n; ++i ) {
std::ostringstream s;
s << "session" << i;
sessions.push_back( s.str() );
}
std::cerr << "begin load test\n";
// clock_t start_ticks( clock() );
time_t start_time( time( NULL ) );
std::list< std::string >::const_iterator it;
// check sessions and then create them
for ( it=sessions.begin(); it!=sessions.end(); ++it ) {
if ( client.live_session( *it ) ) {
std::cerr << "session is already live\n";
}
client.create_session( *it );
// std::cerr << "created session: " << *it << std::endl;
}
// check sessions now that they're there
for ( it=sessions.begin(); it!=sessions.end(); ++it ) {
if ( ! client.live_session( *it ) ) {
std::cerr << "session isn't alive\n";
}
client.kill_session( *it );
if ( client.live_session( *it ) ) {
std::cerr << "session is still alive\n";
}
// std::cerr << "killed session: " << *it << std::endl;
}
// clock_t stop_time( clock() );
// clock_t run_time( stop_time - start_time );
// clock_t run_ms( ( run_time * 1000 ) / CLOCKS_PER_SEC );
time_t run_time( time( NULL ) - start_time );
std::cerr << n << " sessions in " << run_time << " seconds\n";
}
int main( int argc, char **argv )
{
run_load( 80 );
return 0;
}
<commit_msg>added run_load_2 to the load tests. this runs for 12 seconds and finds number of status requests it can do in that time. appears to be about 9000/second<commit_after>/**
* Copyright 2008 Matthew Graham
* 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 "shession_client.h"
#include <iostream>
#include <list>
#include <sstream>
#include <time.h>
void run_load_1( int n )
{
shession_client_c client;
if ( ! client.open( "127.0.0.1", 9000 ) ) {
std::cerr << "Error connecting socket.\n";
return;
}
// create session ids in memory
std::list< std::string > sessions;
for ( int i( 0 ); i<n; ++i ) {
std::ostringstream s;
s << "session" << i;
sessions.push_back( s.str() );
}
std::cerr << "begin load test\n";
// clock_t start_ticks( clock() );
time_t start_time( time( NULL ) );
std::list< std::string >::const_iterator it;
// check sessions and then create them
for ( it=sessions.begin(); it!=sessions.end(); ++it ) {
if ( client.live_session( *it ) ) {
std::cerr << "session is already live\n";
}
client.create_session( *it );
// std::cerr << "created session: " << *it << std::endl;
}
// check sessions now that they're there
for ( it=sessions.begin(); it!=sessions.end(); ++it ) {
if ( ! client.live_session( *it ) ) {
std::cerr << "session isn't alive\n";
}
client.kill_session( *it );
if ( client.live_session( *it ) ) {
std::cerr << "session is still alive\n";
}
// std::cerr << "killed session: " << *it << std::endl;
}
// clock_t stop_time( clock() );
// clock_t run_time( stop_time - start_time );
// clock_t run_ms( ( run_time * 1000 ) / CLOCKS_PER_SEC );
time_t run_time( time( NULL ) - start_time );
std::cerr << n << " sessions in " << run_time << " seconds\n";
}
void run_load_2( int n )
{
shession_client_c client;
if ( ! client.open( "127.0.0.1", 9000 ) ) {
std::cerr << "Error connecting socket.\n";
return;
}
// create session ids in memory
std::list< std::string > sessions;
for ( int i( 0 ); i<n; ++i ) {
std::ostringstream s;
s << "load2_session_" << i;
sessions.push_back( s.str() );
}
std::cerr << "setup load test\n";
std::list< std::string >::const_iterator it;
// create all them
for ( it=sessions.begin(); it!=sessions.end(); ++it ) {
client.create_session( *it );
}
std::cerr << "begin load test\n";
time_t start_time( time( NULL ) );
// check sessions now that they're there
time_t stop_time( time( NULL ) + 12 );
it = sessions.begin();
int count( 0 );
while ( time( NULL ) < stop_time ) {
client.live_session( *it );
++count;
if ( ++it == sessions.end() ) {
it = sessions.begin();
}
}
std::cerr << count << " requests in 12 seconds\n";
std::cerr << 5 * count << " requests per minute\n";
std::cerr << count / 12 << " requests per second\n";
}
int main( int argc, char **argv )
{
run_load_2( 80 );
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <QtGui/QTabWidget>
#include <QtGui/QTextEdit>
#include <QtGui/QVBoxLayout>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QStyle>
#include <QtGui/QApplication>
#include "copasiui3window.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "listviews.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"
#include "function/CFunctionDB.h"
CQMessageBox::CQMessageBox(Icon icon, const QString &title, const QString &text,
QMessageBox::StandardButtons buttons, QWidget *parent,
Qt::WindowFlags f):
QMessageBox(icon, title, QString(), buttons, parent, f),
mpTabWidget(NULL),
mpPage1(NULL),
mpVerticalLayoutPage1(NULL),
mpText1(NULL),
mpPage2(NULL),
mpVerticalLayoutPage2(NULL),
mpText2(NULL)
{
if (CopasiUI3Window::getMainWindow() != NULL)
{
CopasiUI3Window::getMainWindow()->setMessageShown(true);
}
mpTabWidget = new QTabWidget(this);
mpTabWidget->setObjectName(QString::fromUtf8("mpTabWidget"));
mpTabWidget->setMinimumSize(QSize(400, 200));
mpPage1 = new QWidget();
mpPage1->setObjectName(QString::fromUtf8("mpPage1"));
mpVerticalLayoutPage1 = new QVBoxLayout(mpPage1);
mpVerticalLayoutPage1->setMargin(2);
mpVerticalLayoutPage1->setObjectName(QString::fromUtf8("mpVerticalLayoutPage1"));
mpText1 = new QTextEdit(mpPage1);
mpText1->setObjectName(QString::fromUtf8("mpText1"));
mpText1->setReadOnly(true);
mpText1->setText(text);
mpVerticalLayoutPage1->addWidget(mpText1);
mpTabWidget->addTab(mpPage1, QString("Messages"));
// The code below is derived from qt-4.4.3/src/gui/dialogs/qmessagebox.cpp
static_cast<QGridLayout *>(layout())->addWidget(mpTabWidget, 0, 1, 1, 1);
QLabel * pLabel = findChild<QLabel *>("qt_msgbox_label");
if (pLabel != NULL)
pLabel->hide();
}
CQMessageBox::~CQMessageBox()
{
if (CopasiUI3Window::getMainWindow() != NULL)
{
CopasiUI3Window::getMainWindow()->setMessageShown(false);
}
}
// static
QMessageBox::StandardButton CQMessageBox::information(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Information, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
QMessageBox::StandardButton CQMessageBox::question(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Question, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
// static
QMessageBox::StandardButton CQMessageBox::warning(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Warning, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
// static
QMessageBox::StandardButton CQMessageBox::critical(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Critical, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
// static
QMessageBox::StandardButton CQMessageBox::confirmDelete(QWidget *parent,
const QString &objectType, const QString &objects,
const std::set< const CCopasiObject * > & deletedObjects)
{
if (deletedObjects.size() == 0)
return QMessageBox::Ok;
std::set< const CCopasiObject * > DeletedObjects = deletedObjects;
// Determine the affected data model
const CCopasiDataModel * pDataModel = (*DeletedObjects.begin())->getObjectDataModel();
// Determine the affected function DB
CFunctionDB * pFunctionDB =
dynamic_cast< CFunctionDB * >((*DeletedObjects.begin())->getObjectAncestor("FunctionDB"));
if (pDataModel == NULL &&
pFunctionDB == NULL)
return QMessageBox::Ok;
if (pFunctionDB != NULL)
{
// TODO In case a function is deleted we need to loop through all data models
CCopasiDataModel* pDataModel = ListViews::dataModel(parent);
if (pDataModel == NULL) //Maybe should ensure a non-NULL, ListView-ancestor, parent is always set.
pDataModel = &CCopasiRootContainer::getDatamodelList()->operator[](0);
assert(pDataModel != NULL);
}
else
{
pFunctionDB = CCopasiRootContainer::getFunctionList();
}
QString msg =
QString("Do you want to delete the listed %1?\n %2\n").arg(objectType, objects);
std::set< const CCopasiObject * > Functions;
std::set< const CCopasiObject * > Reactions;
std::set< const CCopasiObject * > Metabolites;
std::set< const CCopasiObject * > Values;
std::set< const CCopasiObject * > Compartments;
std::set< const CCopasiObject * > Events;
std::set< const CCopasiObject * > Tasks;
bool Used = false;
if (pFunctionDB != NULL)
{
Used |= pFunctionDB->appendDependentFunctions(DeletedObjects, Functions);
if (Functions.size() > 0)
{
msg.append("Following functions(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Functions.begin();
std::set< const CCopasiObject * >::const_iterator end = Functions.end();
for (; it != end; ++it)
{
DeletedObjects.insert(*it);
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
}
const CModel * pModel = NULL;
if (pDataModel != NULL)
{
pModel = pDataModel->getModel();
// We need to check the tasks
Used |= pDataModel->appendDependentTasks(DeletedObjects, Tasks);
if (Tasks.size() > 0)
{
msg.append("Following task(s) reference above and will be modified:\n ");
std::set< const CCopasiObject * >::const_iterator it = Tasks.begin();
std::set< const CCopasiObject * >::const_iterator end = Tasks.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
}
if (pModel != NULL)
{
Used |= pModel->appendDependentModelObjects(DeletedObjects, Reactions, Metabolites,
Compartments, Values, Events);
if (Reactions.size() > 0)
{
msg.append("Following reactions(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Reactions.begin();
std::set< const CCopasiObject * >::const_iterator end = Reactions.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Metabolites.size() > 0)
{
msg.append("Following species reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Metabolites.begin();
std::set< const CCopasiObject * >::const_iterator end = Metabolites.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Values.size() > 0)
{
msg.append("Following global quantities reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Values.begin();
std::set< const CCopasiObject * >::const_iterator end = Values.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Compartments.size() > 0)
{
msg.append("Following compartment(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Compartments.begin();
std::set< const CCopasiObject * >::const_iterator end = Compartments.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Events.size() > 0)
{
msg.append("Following event(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Events.begin();
std::set< const CCopasiObject * >::const_iterator end = Events.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
}
StandardButton choice = QMessageBox::Ok;
if (Used)
{
choice = CQMessageBox::question(parent, "CONFIRM DELETE", msg,
QMessageBox::Ok | QMessageBox::Cancel,
QMessageBox::Cancel);
}
return choice;
}
void CQMessageBox::setText(const QString & text)
{
mpText1->setText(text);
}
void CQMessageBox::setFilteredText(const QString & text)
{
if (!text.isEmpty() && mpPage2 == NULL)
{
mpPage2 = new QWidget();
mpPage2->setObjectName(QString::fromUtf8("mpPage2"));
mpVerticalLayoutPage2 = new QVBoxLayout(mpPage2);
mpVerticalLayoutPage2->setMargin(2);
mpVerticalLayoutPage2->setObjectName(QString::fromUtf8("mpVerticalLayoutPage2"));
mpText2 = new QTextEdit(mpPage2);
mpText2->setObjectName(QString::fromUtf8("mpText2"));
mpText2->setReadOnly(true);
mpVerticalLayoutPage2->addWidget(mpText2);
mpTabWidget->addTab(mpPage2, QString("Minor Issues"));
}
mpText2->setText(text);
}
<commit_msg>Removed a fall-back CCopasiRootContainer::getDatamodelList()->operator[](0).<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
// Copyright (C) 2008 - 2009 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., EML Research, gGmbH, University of Heidelberg,
// and The University of Manchester.
// All rights reserved.
// Copyright (C) 2007 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.
#include <QtGui/QTabWidget>
#include <QtGui/QTextEdit>
#include <QtGui/QVBoxLayout>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>
#include <QtGui/QStyle>
#include <QtGui/QApplication>
#include "copasiui3window.h"
#include "CQMessageBox.h"
#include "qtUtilities.h"
#include "listviews.h"
#include "report/CCopasiRootContainer.h"
#include "model/CModel.h"
#include "function/CFunctionDB.h"
CQMessageBox::CQMessageBox(Icon icon, const QString &title, const QString &text,
QMessageBox::StandardButtons buttons, QWidget *parent,
Qt::WindowFlags f):
QMessageBox(icon, title, QString(), buttons, parent, f),
mpTabWidget(NULL),
mpPage1(NULL),
mpVerticalLayoutPage1(NULL),
mpText1(NULL),
mpPage2(NULL),
mpVerticalLayoutPage2(NULL),
mpText2(NULL)
{
if (CopasiUI3Window::getMainWindow() != NULL)
{
CopasiUI3Window::getMainWindow()->setMessageShown(true);
}
mpTabWidget = new QTabWidget(this);
mpTabWidget->setObjectName(QString::fromUtf8("mpTabWidget"));
mpTabWidget->setMinimumSize(QSize(400, 200));
mpPage1 = new QWidget();
mpPage1->setObjectName(QString::fromUtf8("mpPage1"));
mpVerticalLayoutPage1 = new QVBoxLayout(mpPage1);
mpVerticalLayoutPage1->setMargin(2);
mpVerticalLayoutPage1->setObjectName(QString::fromUtf8("mpVerticalLayoutPage1"));
mpText1 = new QTextEdit(mpPage1);
mpText1->setObjectName(QString::fromUtf8("mpText1"));
mpText1->setReadOnly(true);
mpText1->setText(text);
mpVerticalLayoutPage1->addWidget(mpText1);
mpTabWidget->addTab(mpPage1, QString("Messages"));
// The code below is derived from qt-4.4.3/src/gui/dialogs/qmessagebox.cpp
static_cast<QGridLayout *>(layout())->addWidget(mpTabWidget, 0, 1, 1, 1);
QLabel * pLabel = findChild<QLabel *>("qt_msgbox_label");
if (pLabel != NULL)
pLabel->hide();
}
CQMessageBox::~CQMessageBox()
{
if (CopasiUI3Window::getMainWindow() != NULL)
{
CopasiUI3Window::getMainWindow()->setMessageShown(false);
}
}
// static
QMessageBox::StandardButton CQMessageBox::information(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Information, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
QMessageBox::StandardButton CQMessageBox::question(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Question, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
// static
QMessageBox::StandardButton CQMessageBox::warning(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Warning, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
// static
QMessageBox::StandardButton CQMessageBox::critical(QWidget *parent, const QString &title,
const QString &text, QMessageBox::StandardButtons buttons,
QMessageBox::StandardButton defaultButton)
{
if (!CopasiUI3Window::isMainThread())
return defaultButton;
CQMessageBox * pMessageBox = new CQMessageBox(QMessageBox::Critical, title, text, buttons, parent);
pMessageBox->setDefaultButton(defaultButton);
StandardButton choice = (StandardButton) pMessageBox->exec();
delete pMessageBox;
return choice;
}
// static
QMessageBox::StandardButton CQMessageBox::confirmDelete(QWidget *parent,
const QString &objectType, const QString &objects,
const std::set< const CCopasiObject * > & deletedObjects)
{
if (deletedObjects.size() == 0)
return QMessageBox::Ok;
std::set< const CCopasiObject * > DeletedObjects = deletedObjects;
// Determine the affected data model
const CCopasiDataModel * pDataModel = (*DeletedObjects.begin())->getObjectDataModel();
// Determine the affected function DB
CFunctionDB * pFunctionDB =
dynamic_cast< CFunctionDB * >((*DeletedObjects.begin())->getObjectAncestor("FunctionDB"));
if (pDataModel == NULL &&
pFunctionDB == NULL)
return QMessageBox::Ok;
if (pFunctionDB != NULL)
{
// TODO In case a function is deleted we need to loop through all data models
CCopasiDataModel* pDataModel = ListViews::dataModel(parent);
assert(pDataModel != NULL);
}
else
{
pFunctionDB = CCopasiRootContainer::getFunctionList();
}
QString msg =
QString("Do you want to delete the listed %1?\n %2\n").arg(objectType, objects);
std::set< const CCopasiObject * > Functions;
std::set< const CCopasiObject * > Reactions;
std::set< const CCopasiObject * > Metabolites;
std::set< const CCopasiObject * > Values;
std::set< const CCopasiObject * > Compartments;
std::set< const CCopasiObject * > Events;
std::set< const CCopasiObject * > Tasks;
bool Used = false;
if (pFunctionDB != NULL)
{
Used |= pFunctionDB->appendDependentFunctions(DeletedObjects, Functions);
if (Functions.size() > 0)
{
msg.append("Following functions(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Functions.begin();
std::set< const CCopasiObject * >::const_iterator end = Functions.end();
for (; it != end; ++it)
{
DeletedObjects.insert(*it);
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
}
const CModel * pModel = NULL;
if (pDataModel != NULL)
{
pModel = pDataModel->getModel();
// We need to check the tasks
Used |= pDataModel->appendDependentTasks(DeletedObjects, Tasks);
if (Tasks.size() > 0)
{
msg.append("Following task(s) reference above and will be modified:\n ");
std::set< const CCopasiObject * >::const_iterator it = Tasks.begin();
std::set< const CCopasiObject * >::const_iterator end = Tasks.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
}
if (pModel != NULL)
{
Used |= pModel->appendDependentModelObjects(DeletedObjects, Reactions, Metabolites,
Compartments, Values, Events);
if (Reactions.size() > 0)
{
msg.append("Following reactions(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Reactions.begin();
std::set< const CCopasiObject * >::const_iterator end = Reactions.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Metabolites.size() > 0)
{
msg.append("Following species reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Metabolites.begin();
std::set< const CCopasiObject * >::const_iterator end = Metabolites.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Values.size() > 0)
{
msg.append("Following global quantities reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Values.begin();
std::set< const CCopasiObject * >::const_iterator end = Values.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Compartments.size() > 0)
{
msg.append("Following compartment(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Compartments.begin();
std::set< const CCopasiObject * >::const_iterator end = Compartments.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
if (Events.size() > 0)
{
msg.append("Following event(s) reference above and will be deleted:\n ");
std::set< const CCopasiObject * >::const_iterator it = Events.begin();
std::set< const CCopasiObject * >::const_iterator end = Events.end();
for (; it != end; ++it)
{
msg.append(FROM_UTF8((*it)->getObjectName()));
msg.append("\n ");
}
msg.remove(msg.length() - 2, 2);
}
}
StandardButton choice = QMessageBox::Ok;
if (Used)
{
choice = CQMessageBox::question(parent, "CONFIRM DELETE", msg,
QMessageBox::Ok | QMessageBox::Cancel,
QMessageBox::Cancel);
}
return choice;
}
void CQMessageBox::setText(const QString & text)
{
mpText1->setText(text);
}
void CQMessageBox::setFilteredText(const QString & text)
{
if (!text.isEmpty() && mpPage2 == NULL)
{
mpPage2 = new QWidget();
mpPage2->setObjectName(QString::fromUtf8("mpPage2"));
mpVerticalLayoutPage2 = new QVBoxLayout(mpPage2);
mpVerticalLayoutPage2->setMargin(2);
mpVerticalLayoutPage2->setObjectName(QString::fromUtf8("mpVerticalLayoutPage2"));
mpText2 = new QTextEdit(mpPage2);
mpText2->setObjectName(QString::fromUtf8("mpText2"));
mpText2->setReadOnly(true);
mpVerticalLayoutPage2->addWidget(mpText2);
mpTabWidget->addTab(mpPage2, QString("Minor Issues"));
}
mpText2->setText(text);
}
<|endoftext|> |
<commit_before>// Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <math.h>
#include <string.h>
#include <algorithm>
#include "copasi/utilities/CUnit.h"
#include "copasi/utilities/CUnitParser.h"
#include "copasi/model/CModel.h"
#include "copasi/xml/CCopasiXMLInterface.h"
#include "copasi/utilities/CUnitParser.h"
#include "CCopasiException.h"
// static
C_FLOAT64 CUnit::Avogadro(6.02214129e23); // http://physics.nist.gov/cgi-bin/cuu/Value?na (Wed Jan 29 18:33:36 EST 2014)
const char * CUnit::VolumeUnitNames[] =
{"dimensionless", "m\xc2\xb3", "l", "ml", "\xc2\xb5l", "nl", "pl", "fl", NULL};
const char * CUnit::AreaUnitNames[] =
{"dimensionless", "m\xc2\xb2", "dm\xc2\xb2", "cm\xc2\xb2", "mm\xc2\xb2", "\xc2\xb5m\xc2\xb2", "nm\xc2\xb2", "pm\xc2\xb2", "fm\xc2\xb2", NULL};
const char * CUnit::LengthUnitNames[] =
{"dimensionless", "m", "dm", "cm", "mm", "\xc2\xb5m", "nm", "pm", "fm", NULL};
const char * CUnit::TimeUnitNames[] =
{"dimensionless", "d", "h", "min", "s", "ms", "\xc2\xb5s", "ns", "ps", "fs", NULL};
// "mol" is the correct name, however in the COPASI XML files "Mol" is used
// up to build 18
const char * CUnit::QuantityUnitOldXMLNames[] =
{"dimensionless", "Mol", "mMol", "\xc2\xb5Mol", "nMol", "pMol", "fMol", "#", NULL};
const char * CUnit::QuantityUnitNames[] =
{"dimensionless", "mol", "mmol", "\xc2\xb5mol", "nmol", "pmol", "fmol", "#", NULL};
// static
std::string CUnit::replaceSymbol(const std::string & expression,
const std::string & oldSymbol,
const std::string & newSymbol)
{
if (oldSymbol == newSymbol)
return expression;
std::istringstream buffer(expression);
CUnitParser Parser(&buffer);
Parser.setAvogadro(CUnit::Avogadro);
Parser.replaceSymbol(oldSymbol, newSymbol);
return (Parser.yyparse() == 0) ? Parser.getReplacedExpression() : expression;
}
// constructors
// default
CUnit::CUnit():
mExpression(""),
mComponents(),
mUsedSymbols()
{
}
// kind
CUnit::CUnit(const CBaseUnit::Kind & kind):
mExpression(CBaseUnit::getSymbol(kind)),
mComponents(),
mUsedSymbols()
{
mComponents.insert(CUnitComponent(kind));
}
// copy constructor
CUnit::CUnit(const CUnit & src,
const C_FLOAT64 & avogadro):
mExpression(),
mComponents(),
mUsedSymbols()
{
setExpression(src.mExpression, avogadro);
}
CUnit::~CUnit()
{
}
void CUnit::fromEnum(VolumeUnit volEnum)
{
mComponents.clear();
mExpression = VolumeUnitNames[volEnum];
if (volEnum == CUnit::dimensionlessVolume)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
tmpComponent.setExponent(3);
switch (volEnum)
{
case CUnit::m3: //default scale = 0
break;
case CUnit::l:
tmpComponent.setScale(-3);
break;
case CUnit::ml:
tmpComponent.setScale(-6);
break;
case CUnit::microl:
tmpComponent.setScale(-9);
break;
case CUnit::nl:
tmpComponent.setScale(-12);
break;
case CUnit::pl:
tmpComponent.setScale(-15);
break;
case CUnit::fl:
tmpComponent.setScale(-18);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(AreaUnit areaEnum)
{
mComponents.clear();
mExpression = AreaUnitNames[areaEnum];
if (areaEnum == CUnit::dimensionlessArea)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
tmpComponent.setExponent(2);
switch (areaEnum)
{
case CUnit::m2: //default scale = 0
break;
case CUnit::dm2:
tmpComponent.setScale(-2);
break;
case CUnit::cm2:
tmpComponent.setScale(-4);
break;
case CUnit::mm2:
tmpComponent.setScale(-6);
break;
case CUnit::microm2:
tmpComponent.setScale(-12);
break;
case CUnit::nm2:
tmpComponent.setScale(-18);
break;
case CUnit::pm2:
tmpComponent.setScale(-24);
break;
case CUnit::fm2:
tmpComponent.setScale(-30);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(LengthUnit lengthEnum)
{
mComponents.clear();
mExpression = LengthUnitNames[lengthEnum];
if (lengthEnum == CUnit::dimensionlessLength)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
switch (lengthEnum)
{
case CUnit::m: //default scale = 0
break;
case CUnit::dm:
tmpComponent.setScale(-1);
break;
case CUnit::cm:
tmpComponent.setScale(-2);
break;
case CUnit::mm:
tmpComponent.setScale(-3);
break;
case CUnit::microm:
tmpComponent.setScale(-6);
break;
case CUnit::nm:
tmpComponent.setScale(-9);
break;
case CUnit::pm:
tmpComponent.setScale(-12);
break;
case CUnit::fm:
tmpComponent.setScale(-15);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(TimeUnit timeEnum)
{
mComponents.clear();
mExpression = TimeUnitNames[timeEnum];
if (timeEnum == CUnit::dimensionlessTime)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::second);
switch (timeEnum)
{
case CUnit::d:
tmpComponent.setMultiplier(60 * 60 * 24);
break;
case CUnit::h:
tmpComponent.setMultiplier(60 * 60);
break;
case CUnit::min:
case CUnit::OldMinute:
tmpComponent.setMultiplier(60);
break;
case CUnit::s: // defaults are appropriate
break;
case CUnit::micros:
tmpComponent.setScale(-6);
break;
case CUnit::ns:
tmpComponent.setScale(-9);
break;
case CUnit::ps:
tmpComponent.setScale(-12);
break;
case CUnit::fs:
tmpComponent.setScale(-15);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(QuantityUnit quantityEnum, C_FLOAT64 avogadro)
{
mComponents.clear();
mExpression = QuantityUnitNames[quantityEnum];
if (quantityEnum == CUnit::dimensionlessQuantity)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::item);
tmpComponent.setMultiplier(avogadro);
// enum QuantityUnit {dimensionlessQuantity = 0, Mol, mMol, microMol, nMol, pMol, fMol, number, OldXML};
switch (quantityEnum)
{
case CUnit::Mol:
break;
case CUnit::mMol:
tmpComponent.setScale(-3);
break;
case CUnit::microMol:
tmpComponent.setScale(-6);
break;
case CUnit::nMol:
tmpComponent.setScale(-9);
break;
case CUnit::pMol:
tmpComponent.setScale(-12);
break;
case CUnit::fMol:
tmpComponent.setScale(-15);
break;
case CUnit::number:
case CUnit::OldXML:
tmpComponent.setMultiplier(1);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
bool CUnit::setExpression(const std::string & expression,
const C_FLOAT64 & avogadro)
{
mExpression = expression;
if (expression.empty())
{
mComponents.clear();
return true;
}
return compile(avogadro);
}
bool CUnit::compile(const C_FLOAT64 & avogadro)
{
mComponents.clear();
mUsedSymbols.clear();
// parse the expression into a linked node tree
std::istringstream buffer(mExpression);
CUnitParser Parser(&buffer);
Parser.setAvogadro(avogadro);
bool success = (Parser.yyparse() == 0);
if (success)
{
mComponents = Parser.getComponents();
mUsedSymbols = Parser.getSymbols();
}
return success;
}
std::string CUnit::getExpression() const
{
return mExpression;
}
const std::set< std::string > & CUnit::getUsedSymbols() const
{
return mUsedSymbols;
}
// See if the component units cancel (divide to 1).
// The CUnitComponent::Kind enumerator uses only prime numbers.
// Multiplying all the components should give 1, if numerators and
// denominators have the same combination of units.
bool CUnit::isDimensionless() const
{
std::set< CUnitComponent >::const_iterator it = mComponents.begin();
double reduction = 1;
for (; it != mComponents.end(); it++)
{
reduction *= pow((double)(*it).getKind(), (*it).getExponent());
}
// If the vector is empty, it will loop 0 times, and the reduction
// will remain ==1 (i.e. dimensionless if no components)
return reduction == 1;
}
void CUnit::addComponent(const CUnitComponent & component)
{
std::set< CUnitComponent >::iterator it = mComponents.find(component);
if (it != mComponents.end())
{
CUnitComponent * pComponent = const_cast< CUnitComponent * >(&*it);
pComponent->setScale(pComponent->getScale() + component.getScale());
pComponent->setMultiplier(pComponent->getMultiplier() * component.getMultiplier());
if (pComponent->getKind() != CBaseUnit::dimensionless)
{
pComponent->setExponent(pComponent->getExponent() + component.getExponent());
}
}
else
{
mComponents.insert(component);
}
}
const std::set< CUnitComponent > & CUnit::getComponents() const
{
return mComponents;
}
CUnit & CUnit::exponentiate(double exp)
{
std::set< CUnitComponent >::iterator it = mComponents.begin();
for (; it != mComponents.end(); it++)
{
CUnitComponent * pComponent = const_cast< CUnitComponent * >(&*it);
pComponent->setMultiplier(pow(pComponent->getMultiplier(), exp));
pComponent->setScale(pComponent->getScale() * exp);
if (pComponent->getKind() != CBaseUnit::dimensionless)
{
pComponent->setExponent(pComponent->getExponent() * exp);
}
}
return *this;
}
// Putting units next to each other implies multiplying them.
CUnit CUnit::operator*(const CUnit & rhs) const
{
std::set< CUnitComponent >::const_iterator it = rhs.mComponents.begin();
std::set< CUnitComponent >::const_iterator end = rhs.mComponents.end();
CUnit combined_unit = *this; // Make a copy of the first CUnit
for (; it != end; ++it)
{
combined_unit.addComponent(*it);
}
return combined_unit; // The calling code might want to call simplifyComponents() on the returned unit.
}
bool CUnit::operator==(const CUnit & rhs) const
{
return (mExpression == rhs.mExpression);
}
bool CUnit::isEquivalent(const CUnit & rhs) const
{
if (mComponents.size() != rhs.mComponents.size())
{
return false;
}
std::set< CUnitComponent >::const_iterator it = mComponents.begin();
std::set< CUnitComponent >::const_iterator end = mComponents.end();
std::set< CUnitComponent >::const_iterator itRhs = rhs.mComponents.begin();
for (; it != end; ++it, ++itRhs)
{
if (*it == *itRhs)
{
continue;
}
else
return false;
}
return true;
}
// friend
std::ostream &operator<<(std::ostream &os, const CUnit & o)
{
os << "Expression: " << o.mExpression << ", ";
os << "Components: " << std::endl;
std::set< CUnitComponent >::const_iterator it = o.mComponents.begin();
std::set< CUnitComponent >::const_iterator end = o.mComponents.end();
for (; it != end; ++it)
{
os << *it;
}
return os;
}
<commit_msg>Updated Copasi default Avogadro "constant".<commit_after>// Copyright (C) 2014 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#include <math.h>
#include <string.h>
#include <algorithm>
#include "copasi/utilities/CUnit.h"
#include "copasi/utilities/CUnitParser.h"
#include "copasi/model/CModel.h"
#include "copasi/xml/CCopasiXMLInterface.h"
#include "copasi/utilities/CUnitParser.h"
#include "CCopasiException.h"
// static
C_FLOAT64 CUnit::Avogadro(6.022140857e23); // http://physics.nist.gov/cgi-bin/cuu/Value?na (Thu Feb 11 09:57:27 EST 2016)
const char * CUnit::VolumeUnitNames[] =
{"dimensionless", "m\xc2\xb3", "l", "ml", "\xc2\xb5l", "nl", "pl", "fl", NULL};
const char * CUnit::AreaUnitNames[] =
{"dimensionless", "m\xc2\xb2", "dm\xc2\xb2", "cm\xc2\xb2", "mm\xc2\xb2", "\xc2\xb5m\xc2\xb2", "nm\xc2\xb2", "pm\xc2\xb2", "fm\xc2\xb2", NULL};
const char * CUnit::LengthUnitNames[] =
{"dimensionless", "m", "dm", "cm", "mm", "\xc2\xb5m", "nm", "pm", "fm", NULL};
const char * CUnit::TimeUnitNames[] =
{"dimensionless", "d", "h", "min", "s", "ms", "\xc2\xb5s", "ns", "ps", "fs", NULL};
// "mol" is the correct name, however in the COPASI XML files "Mol" is used
// up to build 18
const char * CUnit::QuantityUnitOldXMLNames[] =
{"dimensionless", "Mol", "mMol", "\xc2\xb5Mol", "nMol", "pMol", "fMol", "#", NULL};
const char * CUnit::QuantityUnitNames[] =
{"dimensionless", "mol", "mmol", "\xc2\xb5mol", "nmol", "pmol", "fmol", "#", NULL};
// static
std::string CUnit::replaceSymbol(const std::string & expression,
const std::string & oldSymbol,
const std::string & newSymbol)
{
if (oldSymbol == newSymbol)
return expression;
std::istringstream buffer(expression);
CUnitParser Parser(&buffer);
Parser.setAvogadro(CUnit::Avogadro);
Parser.replaceSymbol(oldSymbol, newSymbol);
return (Parser.yyparse() == 0) ? Parser.getReplacedExpression() : expression;
}
// constructors
// default
CUnit::CUnit():
mExpression(""),
mComponents(),
mUsedSymbols()
{
}
// kind
CUnit::CUnit(const CBaseUnit::Kind & kind):
mExpression(CBaseUnit::getSymbol(kind)),
mComponents(),
mUsedSymbols()
{
mComponents.insert(CUnitComponent(kind));
}
// copy constructor
CUnit::CUnit(const CUnit & src,
const C_FLOAT64 & avogadro):
mExpression(),
mComponents(),
mUsedSymbols()
{
setExpression(src.mExpression, avogadro);
}
CUnit::~CUnit()
{
}
void CUnit::fromEnum(VolumeUnit volEnum)
{
mComponents.clear();
mExpression = VolumeUnitNames[volEnum];
if (volEnum == CUnit::dimensionlessVolume)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
tmpComponent.setExponent(3);
switch (volEnum)
{
case CUnit::m3: //default scale = 0
break;
case CUnit::l:
tmpComponent.setScale(-3);
break;
case CUnit::ml:
tmpComponent.setScale(-6);
break;
case CUnit::microl:
tmpComponent.setScale(-9);
break;
case CUnit::nl:
tmpComponent.setScale(-12);
break;
case CUnit::pl:
tmpComponent.setScale(-15);
break;
case CUnit::fl:
tmpComponent.setScale(-18);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(AreaUnit areaEnum)
{
mComponents.clear();
mExpression = AreaUnitNames[areaEnum];
if (areaEnum == CUnit::dimensionlessArea)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
tmpComponent.setExponent(2);
switch (areaEnum)
{
case CUnit::m2: //default scale = 0
break;
case CUnit::dm2:
tmpComponent.setScale(-2);
break;
case CUnit::cm2:
tmpComponent.setScale(-4);
break;
case CUnit::mm2:
tmpComponent.setScale(-6);
break;
case CUnit::microm2:
tmpComponent.setScale(-12);
break;
case CUnit::nm2:
tmpComponent.setScale(-18);
break;
case CUnit::pm2:
tmpComponent.setScale(-24);
break;
case CUnit::fm2:
tmpComponent.setScale(-30);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(LengthUnit lengthEnum)
{
mComponents.clear();
mExpression = LengthUnitNames[lengthEnum];
if (lengthEnum == CUnit::dimensionlessLength)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::meter);
switch (lengthEnum)
{
case CUnit::m: //default scale = 0
break;
case CUnit::dm:
tmpComponent.setScale(-1);
break;
case CUnit::cm:
tmpComponent.setScale(-2);
break;
case CUnit::mm:
tmpComponent.setScale(-3);
break;
case CUnit::microm:
tmpComponent.setScale(-6);
break;
case CUnit::nm:
tmpComponent.setScale(-9);
break;
case CUnit::pm:
tmpComponent.setScale(-12);
break;
case CUnit::fm:
tmpComponent.setScale(-15);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(TimeUnit timeEnum)
{
mComponents.clear();
mExpression = TimeUnitNames[timeEnum];
if (timeEnum == CUnit::dimensionlessTime)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::second);
switch (timeEnum)
{
case CUnit::d:
tmpComponent.setMultiplier(60 * 60 * 24);
break;
case CUnit::h:
tmpComponent.setMultiplier(60 * 60);
break;
case CUnit::min:
case CUnit::OldMinute:
tmpComponent.setMultiplier(60);
break;
case CUnit::s: // defaults are appropriate
break;
case CUnit::micros:
tmpComponent.setScale(-6);
break;
case CUnit::ns:
tmpComponent.setScale(-9);
break;
case CUnit::ps:
tmpComponent.setScale(-12);
break;
case CUnit::fs:
tmpComponent.setScale(-15);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
void CUnit::fromEnum(QuantityUnit quantityEnum, C_FLOAT64 avogadro)
{
mComponents.clear();
mExpression = QuantityUnitNames[quantityEnum];
if (quantityEnum == CUnit::dimensionlessQuantity)
return; // no need to add component
CUnitComponent tmpComponent = CUnitComponent(CBaseUnit::item);
tmpComponent.setMultiplier(avogadro);
// enum QuantityUnit {dimensionlessQuantity = 0, Mol, mMol, microMol, nMol, pMol, fMol, number, OldXML};
switch (quantityEnum)
{
case CUnit::Mol:
break;
case CUnit::mMol:
tmpComponent.setScale(-3);
break;
case CUnit::microMol:
tmpComponent.setScale(-6);
break;
case CUnit::nMol:
tmpComponent.setScale(-9);
break;
case CUnit::pMol:
tmpComponent.setScale(-12);
break;
case CUnit::fMol:
tmpComponent.setScale(-15);
break;
case CUnit::number:
case CUnit::OldXML:
tmpComponent.setMultiplier(1);
break;
default:
return; // just to silence compiler warning
}
addComponent(tmpComponent);
}
bool CUnit::setExpression(const std::string & expression,
const C_FLOAT64 & avogadro)
{
mExpression = expression;
if (expression.empty())
{
mComponents.clear();
return true;
}
return compile(avogadro);
}
bool CUnit::compile(const C_FLOAT64 & avogadro)
{
mComponents.clear();
mUsedSymbols.clear();
// parse the expression into a linked node tree
std::istringstream buffer(mExpression);
CUnitParser Parser(&buffer);
Parser.setAvogadro(avogadro);
bool success = (Parser.yyparse() == 0);
if (success)
{
mComponents = Parser.getComponents();
mUsedSymbols = Parser.getSymbols();
}
return success;
}
std::string CUnit::getExpression() const
{
return mExpression;
}
const std::set< std::string > & CUnit::getUsedSymbols() const
{
return mUsedSymbols;
}
// See if the component units cancel (divide to 1).
// The CUnitComponent::Kind enumerator uses only prime numbers.
// Multiplying all the components should give 1, if numerators and
// denominators have the same combination of units.
bool CUnit::isDimensionless() const
{
std::set< CUnitComponent >::const_iterator it = mComponents.begin();
double reduction = 1;
for (; it != mComponents.end(); it++)
{
reduction *= pow((double)(*it).getKind(), (*it).getExponent());
}
// If the vector is empty, it will loop 0 times, and the reduction
// will remain ==1 (i.e. dimensionless if no components)
return reduction == 1;
}
void CUnit::addComponent(const CUnitComponent & component)
{
std::set< CUnitComponent >::iterator it = mComponents.find(component);
if (it != mComponents.end())
{
CUnitComponent * pComponent = const_cast< CUnitComponent * >(&*it);
pComponent->setScale(pComponent->getScale() + component.getScale());
pComponent->setMultiplier(pComponent->getMultiplier() * component.getMultiplier());
if (pComponent->getKind() != CBaseUnit::dimensionless)
{
pComponent->setExponent(pComponent->getExponent() + component.getExponent());
}
}
else
{
mComponents.insert(component);
}
}
const std::set< CUnitComponent > & CUnit::getComponents() const
{
return mComponents;
}
CUnit & CUnit::exponentiate(double exp)
{
std::set< CUnitComponent >::iterator it = mComponents.begin();
for (; it != mComponents.end(); it++)
{
CUnitComponent * pComponent = const_cast< CUnitComponent * >(&*it);
pComponent->setMultiplier(pow(pComponent->getMultiplier(), exp));
pComponent->setScale(pComponent->getScale() * exp);
if (pComponent->getKind() != CBaseUnit::dimensionless)
{
pComponent->setExponent(pComponent->getExponent() * exp);
}
}
return *this;
}
// Putting units next to each other implies multiplying them.
CUnit CUnit::operator*(const CUnit & rhs) const
{
std::set< CUnitComponent >::const_iterator it = rhs.mComponents.begin();
std::set< CUnitComponent >::const_iterator end = rhs.mComponents.end();
CUnit combined_unit = *this; // Make a copy of the first CUnit
for (; it != end; ++it)
{
combined_unit.addComponent(*it);
}
return combined_unit; // The calling code might want to call simplifyComponents() on the returned unit.
}
bool CUnit::operator==(const CUnit & rhs) const
{
return (mExpression == rhs.mExpression);
}
bool CUnit::isEquivalent(const CUnit & rhs) const
{
if (mComponents.size() != rhs.mComponents.size())
{
return false;
}
std::set< CUnitComponent >::const_iterator it = mComponents.begin();
std::set< CUnitComponent >::const_iterator end = mComponents.end();
std::set< CUnitComponent >::const_iterator itRhs = rhs.mComponents.begin();
for (; it != end; ++it, ++itRhs)
{
if (*it == *itRhs)
{
continue;
}
else
return false;
}
return true;
}
// friend
std::ostream &operator<<(std::ostream &os, const CUnit & o)
{
os << "Expression: " << o.mExpression << ", ";
os << "Components: " << std::endl;
std::set< CUnitComponent >::const_iterator it = o.mComponents.begin();
std::set< CUnitComponent >::const_iterator end = o.mComponents.end();
for (; it != end; ++it)
{
os << *it;
}
return os;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: JDriver.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: oj $ $Date: 2000-11-22 14:44:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_DRIVER_HXX_
#include "java/sql/Driver.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_
#include "java/lang/Object.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_DRIVERMANAGER_HXX_
#include "java/sql/DriverManager.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_DRIVERPOPERTYINFO_HXX_
#include "java/sql/DriverPropertyInfo.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_
#include "java/sql/Connection.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
java_sql_Driver::java_sql_Driver(const Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
: java_lang_Object(_rxFactory)
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
// this object is not the right one
t.pEnv->DeleteGlobalRef( object );
object = 0;
}
// --------------------------------------------------------------------------------
jclass java_sql_Driver::theClass = 0;
// --------------------------------------------------------------------------------
java_sql_Driver::~java_sql_Driver()
{}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString java_sql_Driver::getImplementationName_Static( ) throw(RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.sdbc.JDriver");
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > java_sql_Driver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aSNS( 1 );
aSNS[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.Driver");
return aSNS;
}
//------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL connectivity::java_sql_Driver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
{
return *(new java_sql_Driver(_rxFactory));
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL java_sql_Driver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL java_sql_Driver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
for (sal_Int32 i=0; i<aSupported.getLength(); ++i, ++pSupported)
if (pSupported->equals(_rServiceName))
return sal_True;
return sal_False;
}
// --------------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL java_sql_Driver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
jclass java_sql_Driver::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass )
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Driver");
OSL_ENSHURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
// --------------------------------------------------------------------------------
void java_sql_Driver::saveClassRef( jclass pClass )
{
if( SDBThreadAttach::IsJavaErrorOccured() || pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
// -------------------------------------------------------------------------
Reference< XConnection > SAL_CALL java_sql_Driver::connect( const ::rtl::OUString& url, const
Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
Reference< XConnection > xRet;
// first try if the jdbc driver is alraedy registered at the driver manager
try
{
if(!object)
{
const PropertyValue* pBegin = info.getConstArray();
const PropertyValue* pEnd = pBegin + info.getLength();
for(jsize i=0;pBegin != pEnd;++pBegin)
{
if(!pBegin->Name.compareToAscii("JDBCDRV"))
{
// here I try to find the class for jdbc driver
java_sql_SQLException_BASE::getMyClass();
java_lang_Throwable::getMyClass();
::rtl::OUString aStr;
pBegin->Value >>= aStr;
// the driver manager holds the class of the driver for later use
// if forName didn't find the class it will throw an exception
java_lang_Class *pDrvClass = java_lang_Class::forName(aStr);
if(pDrvClass)
{
saveRef(t.pEnv, pDrvClass->newInstanceObject());
delete pDrvClass;
}
break;
}
}
}
}
catch(Exception&)
{
throw SQLException(::rtl::OUString::createFromAscii("The specified driver could not be loaded!"),*this,::rtl::OUString(),1000,Any());
}
jobject out(0);
if( t.pEnv )
{
jvalue args[2];
// Parameter konvertieren
args[0].l = convertwchar_tToJavaString(t.pEnv,url);
args[1].l = createStringPropertyArray(t.pEnv,info);
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;Ljava/util/Properties)Ljava/sql/Connection;";
char * cMethodName = "connect";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
{
out = t.pEnv->CallObjectMethodA( getMyClass(), mID, args );
} //mID
// und aufraeumen
t.pEnv->DeleteLocalRef((jstring)args[0].l);
t.pEnv->DeleteLocalRef((jstring)args[1].l);
ThrowSQLException(t.pEnv,*this);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
Reference< XConnection > xOut;
return out==0 ? 0 : new java_sql_Connection( t.pEnv, out,this );
// return xOut;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL java_sql_Driver::acceptsURL( const ::rtl::OUString& url ) throw(SQLException, RuntimeException)
{
// don't ask the real driver for the url
// I feel responsible for all jdbc url's
if(!url.compareTo(::rtl::OUString::createFromAscii("jdbc:"),5))
{
return sal_True;
}
return sal_False;
}
// -------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL java_sql_Driver::getPropertyInfo( const ::rtl::OUString& url,
const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if(!object)
object = java_sql_DriverManager::getDriver(url);
if(!object)
{
// one of these must throw an exception
ThrowSQLException(t.pEnv,*this);
throw SQLException(); // we need a object here
}
jobjectArray out(0);
if( t.pEnv )
{
jvalue args[2];
// Parameter konvertieren
args[0].l = convertwchar_tToJavaString(t.pEnv,url);
args[1].l = createStringPropertyArray(t.pEnv,info);
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;Ljava/util/Properties)[Ljava/sql/DriverPropertyInfo;";
char * cMethodName = "getPropertyInfo";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
{
out = (jobjectArray)t.pEnv->CallObjectMethodA( getMyClass(), mID, args );
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
t.pEnv->DeleteLocalRef((jstring)args[0].l);
t.pEnv->DeleteLocalRef((jstring)args[1].l);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return copyArrayAndDelete( t.pEnv, out, DriverPropertyInfo(),java_sql_DriverPropertyInfo(NULL,NULL));
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL java_sql_Driver::getMajorVersion( ) throw(RuntimeException)
{
if(!object)
throw RuntimeException();
jint out(0);
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()I";
char * cMethodName = "getMajorVersion";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
out = t.pEnv->CallIntMethod( object, mID);
ThrowSQLException(t.pEnv,*this);
} //t.pEnv
return out;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL java_sql_Driver::getMinorVersion( ) throw(RuntimeException)
{
if(!object)
throw RuntimeException();
jint out(0);
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()I";
char * cMethodName = "getMinorVersion";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
out = t.pEnv->CallIntMethod( object, mID);
ThrowSQLException(t.pEnv,*this);
} //t.pEnv
return out;
}
// -------------------------------------------------------------------------
<commit_msg>#80002# check for null of env<commit_after>/*************************************************************************
*
* $RCSfile: JDriver.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: oj $ $Date: 2000-11-27 09:25:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_DRIVER_HXX_
#include "java/sql/Driver.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_OBJECT_HXX_
#include "java/lang/Object.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_DRIVERMANAGER_HXX_
#include "java/sql/DriverManager.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_DRIVERPOPERTYINFO_HXX_
#include "java/sql/DriverPropertyInfo.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_CONNECTION_HXX_
#include "java/sql/Connection.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
// using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
// -------------------------------------------------------------------------
java_sql_Driver::java_sql_Driver(const Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
: java_lang_Object(_rxFactory)
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
// this object is not the right one
if(t.pEnv)
t.pEnv->DeleteGlobalRef( object );
object = 0;
}
// --------------------------------------------------------------------------------
jclass java_sql_Driver::theClass = 0;
// --------------------------------------------------------------------------------
java_sql_Driver::~java_sql_Driver()
{}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString java_sql_Driver::getImplementationName_Static( ) throw(RuntimeException)
{
return ::rtl::OUString::createFromAscii("com.sun.star.sdbc.JDriver");
}
//------------------------------------------------------------------------------
Sequence< ::rtl::OUString > java_sql_Driver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
Sequence< ::rtl::OUString > aSNS( 1 );
aSNS[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.Driver");
return aSNS;
}
//------------------------------------------------------------------
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL connectivity::java_sql_Driver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )
{
return *(new java_sql_Driver(_rxFactory));
}
// --------------------------------------------------------------------------------
::rtl::OUString SAL_CALL java_sql_Driver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL java_sql_Driver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
Sequence< ::rtl::OUString > aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
for (sal_Int32 i=0; i<aSupported.getLength(); ++i, ++pSupported)
if (pSupported->equals(_rServiceName))
return sal_True;
return sal_False;
}
// --------------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL java_sql_Driver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
jclass java_sql_Driver::getMyClass()
{
// die Klasse muss nur einmal geholt werden, daher statisch
if( !theClass )
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if( !t.pEnv ) return (jclass)0;
jclass tempClass = t.pEnv->FindClass("java/sql/Driver");
OSL_ENSHURE(tempClass,"Java : FindClass nicht erfolgreich!");
jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
t.pEnv->DeleteLocalRef( tempClass );
saveClassRef( globClass );
}
return theClass;
}
// --------------------------------------------------------------------------------
void java_sql_Driver::saveClassRef( jclass pClass )
{
if( SDBThreadAttach::IsJavaErrorOccured() || pClass==0 )
return;
// der uebergebe Klassen-Handle ist schon global, daher einfach speichern
theClass = pClass;
}
// -------------------------------------------------------------------------
Reference< XConnection > SAL_CALL java_sql_Driver::connect( const ::rtl::OUString& url, const
Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
Reference< XConnection > xRet;
// first try if the jdbc driver is alraedy registered at the driver manager
try
{
if(!object)
{
const PropertyValue* pBegin = info.getConstArray();
const PropertyValue* pEnd = pBegin + info.getLength();
for(jsize i=0;pBegin != pEnd;++pBegin)
{
if(!pBegin->Name.compareToAscii("JDBCDRV"))
{
// here I try to find the class for jdbc driver
java_sql_SQLException_BASE::getMyClass();
java_lang_Throwable::getMyClass();
::rtl::OUString aStr;
pBegin->Value >>= aStr;
// the driver manager holds the class of the driver for later use
// if forName didn't find the class it will throw an exception
java_lang_Class *pDrvClass = java_lang_Class::forName(aStr);
if(pDrvClass)
{
saveRef(t.pEnv, pDrvClass->newInstanceObject());
delete pDrvClass;
}
break;
}
}
}
}
catch(Exception&)
{
throw SQLException(::rtl::OUString::createFromAscii("The specified driver could not be loaded!"),*this,::rtl::OUString(),1000,Any());
}
jobject out(0);
if( t.pEnv )
{
jvalue args[2];
// Parameter konvertieren
args[0].l = convertwchar_tToJavaString(t.pEnv,url);
args[1].l = createStringPropertyArray(t.pEnv,info);
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;Ljava/util/Properties)Ljava/sql/Connection;";
char * cMethodName = "connect";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
{
out = t.pEnv->CallObjectMethodA( getMyClass(), mID, args );
} //mID
// und aufraeumen
t.pEnv->DeleteLocalRef((jstring)args[0].l);
t.pEnv->DeleteLocalRef((jstring)args[1].l);
ThrowSQLException(t.pEnv,*this);
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
Reference< XConnection > xOut;
return out==0 ? 0 : new java_sql_Connection( t.pEnv, out,this );
// return xOut;
}
// -------------------------------------------------------------------------
sal_Bool SAL_CALL java_sql_Driver::acceptsURL( const ::rtl::OUString& url ) throw(SQLException, RuntimeException)
{
// don't ask the real driver for the url
// I feel responsible for all jdbc url's
if(!url.compareTo(::rtl::OUString::createFromAscii("jdbc:"),5))
{
return sal_True;
}
return sal_False;
}
// -------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL java_sql_Driver::getPropertyInfo( const ::rtl::OUString& url,
const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if(!object)
object = java_sql_DriverManager::getDriver(url);
if(!object)
{
// one of these must throw an exception
ThrowSQLException(t.pEnv,*this);
throw SQLException(); // we need a object here
}
jobjectArray out(0);
if( t.pEnv )
{
jvalue args[2];
// Parameter konvertieren
args[0].l = convertwchar_tToJavaString(t.pEnv,url);
args[1].l = createStringPropertyArray(t.pEnv,info);
// temporaere Variable initialisieren
char * cSignature = "(Ljava/lang/String;Ljava/util/Properties)[Ljava/sql/DriverPropertyInfo;";
char * cMethodName = "getPropertyInfo";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
{
out = (jobjectArray)t.pEnv->CallObjectMethodA( getMyClass(), mID, args );
ThrowSQLException(t.pEnv,*this);
// und aufraeumen
t.pEnv->DeleteLocalRef((jstring)args[0].l);
t.pEnv->DeleteLocalRef((jstring)args[1].l);
} //mID
} //t.pEnv
// ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
return copyArrayAndDelete( t.pEnv, out, DriverPropertyInfo(),java_sql_DriverPropertyInfo(NULL,NULL));
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL java_sql_Driver::getMajorVersion( ) throw(RuntimeException)
{
if(!object)
throw RuntimeException();
jint out(0);
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()I";
char * cMethodName = "getMajorVersion";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
out = t.pEnv->CallIntMethod( object, mID);
ThrowSQLException(t.pEnv,*this);
} //t.pEnv
return out;
}
// -------------------------------------------------------------------------
sal_Int32 SAL_CALL java_sql_Driver::getMinorVersion( ) throw(RuntimeException)
{
if(!object)
throw RuntimeException();
jint out(0);
SDBThreadAttach t; OSL_ENSHURE(t.pEnv,"Java Enviroment gelscht worden!");
if( t.pEnv ){
// temporaere Variable initialisieren
char * cSignature = "()I";
char * cMethodName = "getMinorVersion";
// Java-Call absetzen
jmethodID mID = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
if( mID )
out = t.pEnv->CallIntMethod( object, mID);
ThrowSQLException(t.pEnv,*this);
} //t.pEnv
return out;
}
// -------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
* Copyright (C) 2011 Shantanu Tushar <jhahoneyk@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "directoryprovider.h"
#include <QtCore/QDir>
#include <QtGui/QDesktopServices>
#include <QtCore/QCoreApplication>
using namespace GluonCore;
GLUON_DEFINE_SINGLETON( DirectoryProvider )
DirectoryProvider::DirectoryProvider( QObject* parent )
{
m_userDataPath = QDesktopServices::storageLocation( QDesktopServices::DataLocation );
m_userDataPath.remove( QCoreApplication::applicationName() );
m_userDataPath.remove( QCoreApplication::organizationName() );
m_userDataPath.append( "/gluon/" );
//Define standard dirs Gluon recommends
m_userDirs["data"] = QDir::fromNativeSeparators( m_userDataPath + "/data" );
m_userDirs["games"] = QDir::fromNativeSeparators( m_userDataPath + "/games" );
//Create standard dirs Gluon recommends
QDir dir;
foreach( const QString& dirPath, m_userDirs.values() )
{
dir.mkpath( dirPath );
}
}
QString DirectoryProvider::installPrefix() const
{
return GLUON_INSTALL_PREFIX;
}
QString DirectoryProvider::dataDirectory() const
{
return GLUON_SHARE_INSTALL_DIR;
}
QString DirectoryProvider::libDirectory() const
{
return GLUON_LIB_INSTALL_DIR;
}
QString DirectoryProvider::userDirectory( const QString& name )
{
if( !m_userDirs.contains( name ) )
{
QString path = QDir::fromNativeSeparators( m_userDataPath + name );
m_userDirs[name] = path;
QDir dir;
dir.mkpath( path );
}
return m_userDirs[name];
}
#include "directoryprovider.moc"
<commit_msg>Core: Use hash/mapS without explicite values() method in foreach loops<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
* Copyright (C) 2011 Shantanu Tushar <jhahoneyk@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "directoryprovider.h"
#include <QtCore/QDir>
#include <QtGui/QDesktopServices>
#include <QtCore/QCoreApplication>
using namespace GluonCore;
GLUON_DEFINE_SINGLETON( DirectoryProvider )
DirectoryProvider::DirectoryProvider( QObject* parent )
{
m_userDataPath = QDesktopServices::storageLocation( QDesktopServices::DataLocation );
m_userDataPath.remove( QCoreApplication::applicationName() );
m_userDataPath.remove( QCoreApplication::organizationName() );
m_userDataPath.append( "/gluon/" );
//Define standard dirs Gluon recommends
m_userDirs["data"] = QDir::fromNativeSeparators( m_userDataPath + "/data" );
m_userDirs["games"] = QDir::fromNativeSeparators( m_userDataPath + "/games" );
//Create standard dirs Gluon recommends
QDir dir;
foreach( const QString& dirPath, m_userDirs )
{
dir.mkpath( dirPath );
}
}
QString DirectoryProvider::installPrefix() const
{
return GLUON_INSTALL_PREFIX;
}
QString DirectoryProvider::dataDirectory() const
{
return GLUON_SHARE_INSTALL_DIR;
}
QString DirectoryProvider::libDirectory() const
{
return GLUON_LIB_INSTALL_DIR;
}
QString DirectoryProvider::userDirectory( const QString& name )
{
if( !m_userDirs.contains( name ) )
{
QString path = QDir::fromNativeSeparators( m_userDataPath + name );
m_userDirs[name] = path;
QDir dir;
dir.mkpath( path );
}
return m_userDirs[name];
}
#include "directoryprovider.moc"
<|endoftext|> |
<commit_before>/*
* constrained_ik_plugin.cpp
*
* Created on: Sep 15, 2013
* Author: dsolomon
*/
/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2013, Southwest Research Institute
*
* 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 <constrained_ik/constrained_ik_plugin.h>
#include <ros/ros.h>
#include <kdl_parser/kdl_parser.hpp>
#include <tf_conversions/tf_kdl.h>
#include <eigen_conversions/eigen_kdl.h>
#include <pluginlib/class_list_macros.h>
//register PR2ArmKinematics as a KinematicsBase implementation
PLUGINLIB_EXPORT_CLASS(constrained_ik::ConstrainedIKPlugin, kinematics::KinematicsBase);
using namespace KDL;
using namespace tf;
using namespace std;
using namespace ros;
namespace constrained_ik
{
using basic_ik::Basic_IK;
ConstrainedIKPlugin::ConstrainedIKPlugin():active_(false), dimension_(0)
{
}
bool ConstrainedIKPlugin::isActive()
{
if(active_)
return true;
ROS_ERROR("kinematics not active");
return false;
}
bool ConstrainedIKPlugin::isActive() const
{
if(active_)
return true;
ROS_ERROR("kinematics not active");
return false;
}
bool ConstrainedIKPlugin::initialize(const std::string& robot_description,
const std::string& group_name,
const std::string& base_name,
const std::string& tip_name,
double search_discretization)
{
setValues(robot_description, group_name, base_name, tip_name, search_discretization);
//get robot data from parameter server
urdf::Model robot_model;
if (!robot_model.initParam(robot_description))
{
ROS_ERROR_STREAM("Could not load URDF model from " << robot_description);
active_ = false;
return false;
}
//initialize kinematic solver with robot info
if (!kin_.init(robot_model, base_frame_, tip_frame_))
{
ROS_ERROR("Could not load ik");
active_ = false;
}
else
{
dimension_ = kin_.numJoints();
kin_.getJointNames(joint_names_);
kin_.getLinkNames(link_names_);
active_ = true;
}
return active_;
}
bool ConstrainedIKPlugin::getPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
//check that solver is ready and properly configured
if(!active_)
{
ROS_ERROR("kinematics not active");
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
if(ik_seed_state.size() != dimension_)
{
ROS_ERROR("ik_seed_state does not have same dimension as solver");
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
//convert input parameters to required types
KDL::Frame pose_desired;
tf::poseMsgToKDL(ik_pose, pose_desired);
Eigen::Affine3d goal;
tf::transformKDLToEigen(pose_desired, goal);
Eigen::VectorXd seed(dimension_), joint_angles(dimension_);
for(size_t ii=0; ii < dimension_; ++ii)
{
seed(ii) = ik_seed_state[ii];
}
//create solver and initialize with kinematic model
Basic_IK solver;
solver.init(kin_);
//Do IK and report results
try { solver.calcInvKin(goal, seed, joint_angles); } //TODO throwing exception kills IK and moveit permanently freezes
catch (exception &e)
{
ROS_ERROR_STREAM("Caught exception from IK: " << e.what());
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
solution.resize(dimension_);
for(size_t ii=0; ii < dimension_; ++ii)
{
solution[ii] = joint_angles(ii);
}
error_code.val = error_code.SUCCESS;
return true;
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
static IKCallbackFn solution_callback = 0;
static std::vector<double> consistency_limits;
return searchPositionIK(ik_pose, ik_seed_state, timeout, consistency_limits, solution, solution_callback, error_code);
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
const std::vector<double> &consistency_limits,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
static IKCallbackFn solution_callback = 0;
return searchPositionIK(ik_pose, ik_seed_state, timeout, consistency_limits, solution, solution_callback, error_code);
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
static std::vector<double> consistency_limits;
return searchPositionIK(ik_pose, ik_seed_state, timeout, consistency_limits, solution, solution_callback, error_code);
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
const std::vector<double> &consistency_limits,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
if(!active_)
{
ROS_ERROR("kinematics not active");
error_code.val = error_code.FAILURE;
return false;
}
KDL::Frame pose_desired;
tf::poseMsgToKDL(ik_pose, pose_desired);
Eigen::Affine3d goal;
tf::transformKDLToEigen(pose_desired, goal);
Eigen::VectorXd seed(dimension_), joint_angles;
for(size_t ii=0; ii < dimension_; ii++)
{
seed(ii) = ik_seed_state[ii];
}
//Do the IK
Basic_IK solver;
solver.init(kin_);
try { solver.calcInvKin(goal, seed, joint_angles); } //TODO throwing exception kills IK and moveit permanently freezes
catch (exception &e)
{
ROS_ERROR_STREAM("Caught exception from IK: " << e.what());
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
solution.resize(dimension_);
for(size_t ii=0; ii < dimension_; ++ii)
{
solution[ii] = joint_angles(ii);
}
// If there is a solution callback registered, check before returning
if (solution_callback)
{
solution_callback(ik_pose, solution, error_code);
if(error_code.val != error_code.SUCCESS)
return false;
}
// Default: return successfully
error_code.val = error_code.SUCCESS;
return true;
}
bool ConstrainedIKPlugin::getPositionFK(const std::vector<std::string> &link_names,
const std::vector<double> &joint_angles,
std::vector<geometry_msgs::Pose> &poses) const
{
if(!active_)
{
ROS_ERROR("kinematics not active");
return false;
}
Eigen::VectorXd jnt_pos_in;
geometry_msgs::PoseStamped pose;
tf::Stamped<tf::Pose> tf_pose;
jnt_pos_in.resize(dimension_);
for(int i=0; i < dimension_; i++)
{
jnt_pos_in(i) = joint_angles[i];
// ROS_DEBUG("Joint angle: %d %f",i,joint_angles[i]);
}
poses.resize(link_names.size());
std::vector<KDL::Frame> kdl_poses;
bool valid = kin_.linkTransforms(jnt_pos_in, kdl_poses, link_names);
for(size_t ii=0; ii < kdl_poses.size(); ++ii)
{
tf::poseKDLToMsg(kdl_poses[ii],poses[ii]);
}
//TODO remove this printing
ROS_INFO_STREAM("poses: ");
for (size_t ii=0; ii<poses.size(); ++ii)
{
ROS_INFO_STREAM(poses[ii]);
}
return valid;
}
const std::vector<std::string>& ConstrainedIKPlugin::getJointNames() const
{
isActive();
return joint_names_;
}
const std::vector<std::string>& ConstrainedIKPlugin::getLinkNames() const
{
isActive();
return link_names_;
}
} //namespace constrained_ik_plugin
<commit_msg>removed TODO from corrected code<commit_after>/*
* constrained_ik_plugin.cpp
*
* Created on: Sep 15, 2013
* Author: dsolomon
*/
/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2013, Southwest Research Institute
*
* 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 <constrained_ik/constrained_ik_plugin.h>
#include <ros/ros.h>
#include <kdl_parser/kdl_parser.hpp>
#include <tf_conversions/tf_kdl.h>
#include <eigen_conversions/eigen_kdl.h>
#include <pluginlib/class_list_macros.h>
//register PR2ArmKinematics as a KinematicsBase implementation
PLUGINLIB_EXPORT_CLASS(constrained_ik::ConstrainedIKPlugin, kinematics::KinematicsBase);
using namespace KDL;
using namespace tf;
using namespace std;
using namespace ros;
namespace constrained_ik
{
using basic_ik::Basic_IK;
ConstrainedIKPlugin::ConstrainedIKPlugin():active_(false), dimension_(0)
{
}
bool ConstrainedIKPlugin::isActive()
{
if(active_)
return true;
ROS_ERROR("kinematics not active");
return false;
}
bool ConstrainedIKPlugin::isActive() const
{
if(active_)
return true;
ROS_ERROR("kinematics not active");
return false;
}
bool ConstrainedIKPlugin::initialize(const std::string& robot_description,
const std::string& group_name,
const std::string& base_name,
const std::string& tip_name,
double search_discretization)
{
setValues(robot_description, group_name, base_name, tip_name, search_discretization);
//get robot data from parameter server
urdf::Model robot_model;
if (!robot_model.initParam(robot_description))
{
ROS_ERROR_STREAM("Could not load URDF model from " << robot_description);
active_ = false;
return false;
}
//initialize kinematic solver with robot info
if (!kin_.init(robot_model, base_frame_, tip_frame_))
{
ROS_ERROR("Could not load ik");
active_ = false;
}
else
{
dimension_ = kin_.numJoints();
kin_.getJointNames(joint_names_);
kin_.getLinkNames(link_names_);
active_ = true;
}
return active_;
}
bool ConstrainedIKPlugin::getPositionIK(const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
//check that solver is ready and properly configured
if(!active_)
{
ROS_ERROR("kinematics not active");
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
if(ik_seed_state.size() != dimension_)
{
ROS_ERROR("ik_seed_state does not have same dimension as solver");
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
//convert input parameters to required types
KDL::Frame pose_desired;
tf::poseMsgToKDL(ik_pose, pose_desired);
Eigen::Affine3d goal;
tf::transformKDLToEigen(pose_desired, goal);
Eigen::VectorXd seed(dimension_), joint_angles(dimension_);
for(size_t ii=0; ii < dimension_; ++ii)
{
seed(ii) = ik_seed_state[ii];
}
//create solver and initialize with kinematic model
Basic_IK solver;
solver.init(kin_);
//Do IK and report results
try { solver.calcInvKin(goal, seed, joint_angles); }
catch (exception &e)
{
ROS_ERROR_STREAM("Caught exception from IK: " << e.what());
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
solution.resize(dimension_);
for(size_t ii=0; ii < dimension_; ++ii)
{
solution[ii] = joint_angles(ii);
}
error_code.val = error_code.SUCCESS;
return true;
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
static IKCallbackFn solution_callback = 0;
static std::vector<double> consistency_limits;
return searchPositionIK(ik_pose, ik_seed_state, timeout, consistency_limits, solution, solution_callback, error_code);
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
const std::vector<double> &consistency_limits,
std::vector<double> &solution,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
static IKCallbackFn solution_callback = 0;
return searchPositionIK(ik_pose, ik_seed_state, timeout, consistency_limits, solution, solution_callback, error_code);
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
static std::vector<double> consistency_limits;
return searchPositionIK(ik_pose, ik_seed_state, timeout, consistency_limits, solution, solution_callback, error_code);
}
bool ConstrainedIKPlugin::searchPositionIK( const geometry_msgs::Pose &ik_pose,
const std::vector<double> &ik_seed_state,
double timeout,
const std::vector<double> &consistency_limits,
std::vector<double> &solution,
const IKCallbackFn &solution_callback,
moveit_msgs::MoveItErrorCodes &error_code,
const kinematics::KinematicsQueryOptions &options) const
{
if(!active_)
{
ROS_ERROR("kinematics not active");
error_code.val = error_code.FAILURE;
return false;
}
KDL::Frame pose_desired;
tf::poseMsgToKDL(ik_pose, pose_desired);
Eigen::Affine3d goal;
tf::transformKDLToEigen(pose_desired, goal);
Eigen::VectorXd seed(dimension_), joint_angles;
for(size_t ii=0; ii < dimension_; ii++)
{
seed(ii) = ik_seed_state[ii];
}
//Do the IK
Basic_IK solver;
solver.init(kin_);
try { solver.calcInvKin(goal, seed, joint_angles); }
catch (exception &e)
{
ROS_ERROR_STREAM("Caught exception from IK: " << e.what());
error_code.val = error_code.NO_IK_SOLUTION;
return false;
}
solution.resize(dimension_);
for(size_t ii=0; ii < dimension_; ++ii)
{
solution[ii] = joint_angles(ii);
}
// If there is a solution callback registered, check before returning
if (solution_callback)
{
solution_callback(ik_pose, solution, error_code);
if(error_code.val != error_code.SUCCESS)
return false;
}
// Default: return successfully
error_code.val = error_code.SUCCESS;
return true;
}
bool ConstrainedIKPlugin::getPositionFK(const std::vector<std::string> &link_names,
const std::vector<double> &joint_angles,
std::vector<geometry_msgs::Pose> &poses) const
{
if(!active_)
{
ROS_ERROR("kinematics not active");
return false;
}
Eigen::VectorXd jnt_pos_in;
geometry_msgs::PoseStamped pose;
tf::Stamped<tf::Pose> tf_pose;
jnt_pos_in.resize(dimension_);
for(int i=0; i < dimension_; i++)
{
jnt_pos_in(i) = joint_angles[i];
// ROS_DEBUG("Joint angle: %d %f",i,joint_angles[i]);
}
poses.resize(link_names.size());
std::vector<KDL::Frame> kdl_poses;
bool valid = kin_.linkTransforms(jnt_pos_in, kdl_poses, link_names);
for(size_t ii=0; ii < kdl_poses.size(); ++ii)
{
tf::poseKDLToMsg(kdl_poses[ii],poses[ii]);
}
//TODO remove this printing
ROS_INFO_STREAM("poses: ");
for (size_t ii=0; ii<poses.size(); ++ii)
{
ROS_INFO_STREAM(poses[ii]);
}
return valid;
}
const std::vector<std::string>& ConstrainedIKPlugin::getJointNames() const
{
isActive();
return joint_names_;
}
const std::vector<std::string>& ConstrainedIKPlugin::getLinkNames() const
{
isActive();
return link_names_;
}
} //namespace constrained_ik_plugin
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// 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 "stdafx.h"
#include "Process.h"
#pragma warning(push, 4)
// Process::s_sysinfo
//
// Static SYSTEM_INFO information
Process::SystemInfo Process::s_sysinfo;
// Process::Create<ElfClass::x86>
//
// Explicit Instantiation of template function
template std::shared_ptr<Process> Process::Create<ElfClass::x86>(const std::shared_ptr<VirtualMachine>&,
const FileSystem::HandlePtr&, const uapi::char_t**, const uapi::char_t**, const tchar_t*, const tchar_t*);
#ifdef _M_X64
// Process::Create<ElfClass::x86_64>
//
// Explicit Instantiation of template function
template std::shared_ptr<Process> Process::Create<ElfClass::x86_64>(const std::shared_ptr<VirtualMachine>&,
const FileSystem::HandlePtr&, const uapi::char_t**, const uapi::char_t**, const tchar_t*, const tchar_t*);
#endif
//-----------------------------------------------------------------------------
// Process::AddHandle
//
// Adds a file system handle to the process
//
// Arguments:
//
// handle - Handle instance to be added to the process
int Process::AddHandle(const FileSystem::HandlePtr& handle)
{
// Allocate a new index (file descriptor) for the handle and insert it
int index = m_indexpool.Allocate();
if(m_handles.insert(std::make_pair(index, handle)).second) return index;
// Insertion failed, release the index back to the pool and throw
m_indexpool.Release(index);
throw LinuxException(LINUX_EBADFD);
}
//-----------------------------------------------------------------------------
// Process::GetHandle
//
// Accesses a file system handle referenced by the process
//
// Arguments:
//
// index - Index (file descriptor) of the target handle
FileSystem::HandlePtr Process::GetHandle(int index)
{
try { return m_handles.at(index); }
catch(...) { throw LinuxException(LINUX_EBADFD); }
}
//-----------------------------------------------------------------------------
// Process::RemoveHandle
//
// Removes a file system handle from the process
//
// Arguments:
//
// index - Index (file descriptor) of the target handle
void Process::RemoveHandle(int index)
{
// unsafe_erase *should* be OK to use here since values are shared_ptrs,
// but if problems start to happen, this is a good place to look at
if(m_handles.unsafe_erase(index) == 0) throw LinuxException(LINUX_EBADFD);
m_indexpool.Release(index);
}
//-----------------------------------------------------------------------------
// Process::CheckHostProcessClass<x86> (static, private)
//
// Verifies that the created host process is 32-bit
//
// Arguments:
//
// process - Handle to the created host process
template <> inline void Process::CheckHostProcessClass<ElfClass::x86>(HANDLE process)
{
BOOL result; // Result from IsWow64Process
// 32-bit systems can only create 32-bit processes; nothing to worry about
if(s_sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) return;
// 64-bit system; verify that the process is running under WOW64
if(!IsWow64Process(process, &result)) throw Win32Exception();
if(!result) throw Exception(E_PROCESSINVALIDX86HOST);
}
//-----------------------------------------------------------------------------
// Process::CheckHostProcessClass<x86_64> (static, private)
//
// Verifies that the created host process is 64-bit
//
// Arguments:
//
// process - Handle to the created host process
#ifdef _M_X64
template <> inline void Process::CheckHostProcessClass<ElfClass::x86_64>(HANDLE process)
{
BOOL result; // Result from IsWow64Process
// 64-bit system; verify that the process is not running under WOW64
if(!IsWow64Process(process, &result)) throw Win32Exception();
if(result) throw Exception(E_PROCESSINVALIDX64HOST);
}
#endif
//-----------------------------------------------------------------------------
// Process::Create (static)
//
// Constructs a new process instance from an ELF binary
//
// Arguments:
//
// vm - Reference to the VirtualMachine instance
// handle - Open FileSystem::Handle against the ELF binary to load
// argv - ELF command line arguments from caller
// envp - ELF environment variables from caller
// hostpath - Path to the external host to load
// hostargs - Command line arguments to pass to the host
template <ElfClass _class>
std::shared_ptr<Process> Process::Create(const std::shared_ptr<VirtualMachine>& vm, const FileSystem::HandlePtr& handle,
const uapi::char_t** argv, const uapi::char_t** envp, const tchar_t* hostpath, const tchar_t* hostargs)
{
using elf = elf_traits<_class>;
std::unique_ptr<ElfImage> executable; // The main ELF binary image to be loaded
std::unique_ptr<ElfImage> interpreter; // Optional interpreter image specified by executable
uint8_t random[16]; // 16-bytes of random data for AT_RANDOM auxvec
StartupInfo startinfo; // Hosted process startup information
// Create the external host process (suspended by default) and verify the class/architecture
// as this will all go south very quickly if it's not the expected architecture
// todo: need the handles to stuff that are to be inherited (signals, etc)
std::unique_ptr<Host> host = Host::Create(hostpath, hostargs, nullptr, 0);
CheckHostProcessClass<_class>(host->ProcessHandle);
try {
// Generate the AT_RANDOM data to be associated with this process
Random::Generate(random, 16);
// Attempt to load the binary image into the process, then check for an interpreter
executable = ElfImage::Load<_class>(handle, host->ProcessHandle);
if(executable->Interpreter) {
// Acquire a handle to the interpreter binary and attempt to load that into the process
FileSystem::HandlePtr interphandle = vm->OpenExecutable(executable->Interpreter);
interpreter = ElfImage::Load<_class>(interphandle, host->ProcessHandle);
}
// Construct the ELF arguments stack image for the hosted process
ElfArguments args(argv, envp);
(LINUX_AT_EXECFD); // 2 - TODO
if(executable->ProgramHeaders) {
args.AppendAuxiliaryVector(LINUX_AT_PHDR, executable->ProgramHeaders); // 3
args.AppendAuxiliaryVector(LINUX_AT_PHENT, sizeof(typename elf::progheader_t)); // 4
args.AppendAuxiliaryVector(LINUX_AT_PHNUM, executable->NumProgramHeaders); // 5
}
args.AppendAuxiliaryVector(LINUX_AT_PAGESZ, MemoryRegion::PageSize); // 6
if(interpreter) args.AppendAuxiliaryVector(LINUX_AT_BASE, interpreter->BaseAddress); // 7
args.AppendAuxiliaryVector(LINUX_AT_FLAGS, 0); // 8
args.AppendAuxiliaryVector(LINUX_AT_ENTRY, executable->EntryPoint); // 9
(LINUX_AT_NOTELF); // 10 - NOT IMPLEMENTED
(LINUX_AT_UID); // 11 - TODO
(LINUX_AT_EUID); // 12 - TODO
(LINUX_AT_GID); // 13 - TODO
(LINUX_AT_EGID); // 14 - TODO
args.AppendAuxiliaryVector(LINUX_AT_PLATFORM, elf::platform); // 15
(LINUX_AT_HWCAP); // 16 - TODO
(LINUX_AT_CLKTCK); // 17 - TODO
args.AppendAuxiliaryVector(LINUX_AT_SECURE, 0); // 23
(LINUX_AT_BASE_PLATFORM); // 24 - NOT IMPLEMENTED
args.AppendAuxiliaryVector(LINUX_AT_RANDOM, random, 16); // 25
(LINUX_AT_HWCAP2); // 26 - TODO
(LINUX_AT_EXECFN); // 31 - TODO WHICH PATH? ARGUMENT TO EXECVE() OR THE ACTUAL PATH?
(LINUX_AT_SYSINFO); // 32 - TODO MAY NOT IMPLEMENT?
//args.AppendAuxiliaryVector(LINUX_AT_SYSINFO_EHDR, vdso->BaseAddress); // 33 - TODO NEEDS VDSO
// Generate the stack image for the process in it's address space
ElfArguments::StackImage stackimg = args.GenerateStackImage<_class>(host->ProcessHandle);
// Load the StartupInfo structure with the necessary information to get the ELF binary running
startinfo.EntryPoint = (interpreter) ? interpreter->EntryPoint : executable->EntryPoint;
startinfo.ProgramBreak = executable->ProgramBreak;
startinfo.StackImage = stackimg.BaseAddress;
startinfo.StackImageLength = stackimg.Length;
// Create the Process object, transferring the host and startup information
return std::make_shared<Process>(std::move(host), std::move(startinfo));
}
// Terminate the host process on exception since it doesn't get killed by the Host destructor
// TODO: should be LinuxException wrapping the underlying one? Only case right now where
// that wouldn't be true is interpreter's OpenExec() call which should already throw LinuxExceptions
catch(...) { host->Terminate(E_FAIL); throw; }
}
//-----------------------------------------------------------------------------
#pragma warning(pop)
<commit_msg>Improper error code for Process file descriptor functions<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2014 Michael G. Brehm
//
// 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 "stdafx.h"
#include "Process.h"
#pragma warning(push, 4)
// Process::s_sysinfo
//
// Static SYSTEM_INFO information
Process::SystemInfo Process::s_sysinfo;
// Process::Create<ElfClass::x86>
//
// Explicit Instantiation of template function
template std::shared_ptr<Process> Process::Create<ElfClass::x86>(const std::shared_ptr<VirtualMachine>&,
const FileSystem::HandlePtr&, const uapi::char_t**, const uapi::char_t**, const tchar_t*, const tchar_t*);
#ifdef _M_X64
// Process::Create<ElfClass::x86_64>
//
// Explicit Instantiation of template function
template std::shared_ptr<Process> Process::Create<ElfClass::x86_64>(const std::shared_ptr<VirtualMachine>&,
const FileSystem::HandlePtr&, const uapi::char_t**, const uapi::char_t**, const tchar_t*, const tchar_t*);
#endif
//-----------------------------------------------------------------------------
// Process::AddHandle
//
// Adds a file system handle to the process
//
// Arguments:
//
// handle - Handle instance to be added to the process
int Process::AddHandle(const FileSystem::HandlePtr& handle)
{
// Allocate a new index (file descriptor) for the handle and insert it
int index = m_indexpool.Allocate();
if(m_handles.insert(std::make_pair(index, handle)).second) return index;
// Insertion failed, release the index back to the pool and throw
m_indexpool.Release(index);
throw LinuxException(LINUX_EBADF);
}
//-----------------------------------------------------------------------------
// Process::GetHandle
//
// Accesses a file system handle referenced by the process
//
// Arguments:
//
// index - Index (file descriptor) of the target handle
FileSystem::HandlePtr Process::GetHandle(int index)
{
try { return m_handles.at(index); }
catch(...) { throw LinuxException(LINUX_EBADF); }
}
//-----------------------------------------------------------------------------
// Process::RemoveHandle
//
// Removes a file system handle from the process
//
// Arguments:
//
// index - Index (file descriptor) of the target handle
void Process::RemoveHandle(int index)
{
// unsafe_erase *should* be OK to use here since values are shared_ptrs,
// but if problems start to happen, this is a good place to look at
if(m_handles.unsafe_erase(index) == 0) throw LinuxException(LINUX_EBADF);
m_indexpool.Release(index);
}
//-----------------------------------------------------------------------------
// Process::CheckHostProcessClass<x86> (static, private)
//
// Verifies that the created host process is 32-bit
//
// Arguments:
//
// process - Handle to the created host process
template <> inline void Process::CheckHostProcessClass<ElfClass::x86>(HANDLE process)
{
BOOL result; // Result from IsWow64Process
// 32-bit systems can only create 32-bit processes; nothing to worry about
if(s_sysinfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL) return;
// 64-bit system; verify that the process is running under WOW64
if(!IsWow64Process(process, &result)) throw Win32Exception();
if(!result) throw Exception(E_PROCESSINVALIDX86HOST);
}
//-----------------------------------------------------------------------------
// Process::CheckHostProcessClass<x86_64> (static, private)
//
// Verifies that the created host process is 64-bit
//
// Arguments:
//
// process - Handle to the created host process
#ifdef _M_X64
template <> inline void Process::CheckHostProcessClass<ElfClass::x86_64>(HANDLE process)
{
BOOL result; // Result from IsWow64Process
// 64-bit system; verify that the process is not running under WOW64
if(!IsWow64Process(process, &result)) throw Win32Exception();
if(result) throw Exception(E_PROCESSINVALIDX64HOST);
}
#endif
//-----------------------------------------------------------------------------
// Process::Create (static)
//
// Constructs a new process instance from an ELF binary
//
// Arguments:
//
// vm - Reference to the VirtualMachine instance
// handle - Open FileSystem::Handle against the ELF binary to load
// argv - ELF command line arguments from caller
// envp - ELF environment variables from caller
// hostpath - Path to the external host to load
// hostargs - Command line arguments to pass to the host
template <ElfClass _class>
std::shared_ptr<Process> Process::Create(const std::shared_ptr<VirtualMachine>& vm, const FileSystem::HandlePtr& handle,
const uapi::char_t** argv, const uapi::char_t** envp, const tchar_t* hostpath, const tchar_t* hostargs)
{
using elf = elf_traits<_class>;
std::unique_ptr<ElfImage> executable; // The main ELF binary image to be loaded
std::unique_ptr<ElfImage> interpreter; // Optional interpreter image specified by executable
uint8_t random[16]; // 16-bytes of random data for AT_RANDOM auxvec
StartupInfo startinfo; // Hosted process startup information
// Create the external host process (suspended by default) and verify the class/architecture
// as this will all go south very quickly if it's not the expected architecture
// todo: need the handles to stuff that are to be inherited (signals, etc)
std::unique_ptr<Host> host = Host::Create(hostpath, hostargs, nullptr, 0);
CheckHostProcessClass<_class>(host->ProcessHandle);
try {
// Generate the AT_RANDOM data to be associated with this process
Random::Generate(random, 16);
// Attempt to load the binary image into the process, then check for an interpreter
executable = ElfImage::Load<_class>(handle, host->ProcessHandle);
if(executable->Interpreter) {
// Acquire a handle to the interpreter binary and attempt to load that into the process
FileSystem::HandlePtr interphandle = vm->OpenExecutable(executable->Interpreter);
interpreter = ElfImage::Load<_class>(interphandle, host->ProcessHandle);
}
// Construct the ELF arguments stack image for the hosted process
ElfArguments args(argv, envp);
(LINUX_AT_EXECFD); // 2 - TODO
if(executable->ProgramHeaders) {
args.AppendAuxiliaryVector(LINUX_AT_PHDR, executable->ProgramHeaders); // 3
args.AppendAuxiliaryVector(LINUX_AT_PHENT, sizeof(typename elf::progheader_t)); // 4
args.AppendAuxiliaryVector(LINUX_AT_PHNUM, executable->NumProgramHeaders); // 5
}
args.AppendAuxiliaryVector(LINUX_AT_PAGESZ, MemoryRegion::PageSize); // 6
if(interpreter) args.AppendAuxiliaryVector(LINUX_AT_BASE, interpreter->BaseAddress); // 7
args.AppendAuxiliaryVector(LINUX_AT_FLAGS, 0); // 8
args.AppendAuxiliaryVector(LINUX_AT_ENTRY, executable->EntryPoint); // 9
(LINUX_AT_NOTELF); // 10 - NOT IMPLEMENTED
(LINUX_AT_UID); // 11 - TODO
(LINUX_AT_EUID); // 12 - TODO
(LINUX_AT_GID); // 13 - TODO
(LINUX_AT_EGID); // 14 - TODO
args.AppendAuxiliaryVector(LINUX_AT_PLATFORM, elf::platform); // 15
(LINUX_AT_HWCAP); // 16 - TODO
(LINUX_AT_CLKTCK); // 17 - TODO
args.AppendAuxiliaryVector(LINUX_AT_SECURE, 0); // 23
(LINUX_AT_BASE_PLATFORM); // 24 - NOT IMPLEMENTED
args.AppendAuxiliaryVector(LINUX_AT_RANDOM, random, 16); // 25
(LINUX_AT_HWCAP2); // 26 - TODO
(LINUX_AT_EXECFN); // 31 - TODO WHICH PATH? ARGUMENT TO EXECVE() OR THE ACTUAL PATH?
(LINUX_AT_SYSINFO); // 32 - TODO MAY NOT IMPLEMENT?
//args.AppendAuxiliaryVector(LINUX_AT_SYSINFO_EHDR, vdso->BaseAddress); // 33 - TODO NEEDS VDSO
// Generate the stack image for the process in it's address space
ElfArguments::StackImage stackimg = args.GenerateStackImage<_class>(host->ProcessHandle);
// Load the StartupInfo structure with the necessary information to get the ELF binary running
startinfo.EntryPoint = (interpreter) ? interpreter->EntryPoint : executable->EntryPoint;
startinfo.ProgramBreak = executable->ProgramBreak;
startinfo.StackImage = stackimg.BaseAddress;
startinfo.StackImageLength = stackimg.Length;
// Create the Process object, transferring the host and startup information
return std::make_shared<Process>(std::move(host), std::move(startinfo));
}
// Terminate the host process on exception since it doesn't get killed by the Host destructor
// TODO: should be LinuxException wrapping the underlying one? Only case right now where
// that wouldn't be true is interpreter's OpenExec() call which should already throw LinuxExceptions
catch(...) { host->Terminate(E_FAIL); throw; }
}
//-----------------------------------------------------------------------------
#pragma warning(pop)
<|endoftext|> |
<commit_before>//
// Created by monty on 21/02/16.
//
#include <algorithm>
#include <glm/glm.hpp>
#include "Trig.h"
Trig::Trig() {
cachedVertexData = nullptr;
cachedUVData = nullptr;
}
const float* Trig::getUVData() {
if ( cachedUVData == nullptr ) {
cachedUVData = new float[ 3 * 2 ];
cachedUVData[ 0 ] = t0.x;
cachedUVData[ 1 ] = t0.y;
cachedUVData[ 2 ] = t1.x;
cachedUVData[ 3 ] = t1.y;
cachedUVData[ 4 ] = t2.x;
cachedUVData[ 5 ] = t2.y;
}
return cachedVertexData;
}
const float* Trig::getVertexData() {
if ( cachedVertexData == nullptr ) {
cachedVertexData = new float[ 3 * 3 ];
cachedVertexData[ 0 ] = p0.x;
cachedVertexData[ 1 ] = p0.y;
cachedVertexData[ 2 ] = p0.z;
cachedVertexData[ 3 ] = p1.x;
cachedVertexData[ 4 ] = p1.y;
cachedVertexData[ 5 ] = p1.z;
cachedVertexData[ 6 ] = p2.x;
cachedVertexData[ 7 ] = p2.y;
cachedVertexData[ 8 ] = p2.z;
}
return cachedVertexData;
}
Trig::~Trig() {
delete cachedUVData;
delete cachedVertexData;
}
<commit_msg>Fix bug in UV coordinates on Lesson 10<commit_after>//
// Created by monty on 21/02/16.
//
#include <algorithm>
#include <glm/glm.hpp>
#include "Trig.h"
Trig::Trig() {
cachedVertexData = nullptr;
cachedUVData = nullptr;
}
const float* Trig::getUVData() {
if ( cachedUVData == nullptr ) {
cachedUVData = new float[ 3 * 2 ];
cachedUVData[ 0 ] = t0.x;
cachedUVData[ 1 ] = t0.y;
cachedUVData[ 2 ] = t1.x;
cachedUVData[ 3 ] = t1.y;
cachedUVData[ 4 ] = t2.x;
cachedUVData[ 5 ] = t2.y;
}
return cachedUVData;
}
const float* Trig::getVertexData() {
if ( cachedVertexData == nullptr ) {
cachedVertexData = new float[ 3 * 3 ];
cachedVertexData[ 0 ] = p0.x;
cachedVertexData[ 1 ] = p0.y;
cachedVertexData[ 2 ] = p0.z;
cachedVertexData[ 3 ] = p1.x;
cachedVertexData[ 4 ] = p1.y;
cachedVertexData[ 5 ] = p1.z;
cachedVertexData[ 6 ] = p2.x;
cachedVertexData[ 7 ] = p2.y;
cachedVertexData[ 8 ] = p2.z;
}
return cachedVertexData;
}
Trig::~Trig() {
delete cachedUVData;
delete cachedVertexData;
}
<|endoftext|> |
<commit_before>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
//
// 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 machine register scavenger. It can provide
// information such as unused register at any point in a machine basic block.
// It also provides a mechanism to make registers availbale by evicting them
// to spill slots.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reg-scavenging"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/STLExtras.h"
using namespace llvm;
void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
const MachineFunction &MF = *mbb->getParent();
const TargetMachine &TM = MF.getTarget();
TII = TM.getInstrInfo();
RegInfo = TM.getRegisterInfo();
assert((NumPhysRegs == 0 || NumPhysRegs == RegInfo->getNumRegs()) &&
"Target changed?");
if (!MBB) {
NumPhysRegs = RegInfo->getNumRegs();
RegsAvailable.resize(NumPhysRegs);
// Create reserved registers bitvector.
ReservedRegs = RegInfo->getReservedRegs(MF);
// Create callee-saved registers bitvector.
CalleeSavedRegs.resize(NumPhysRegs);
const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
if (CSRegs != NULL)
for (unsigned i = 0; CSRegs[i]; ++i)
CalleeSavedRegs.set(CSRegs[i]);
}
MBB = mbb;
ScavengedReg = 0;
ScavengedRC = NULL;
// All registers started out unused.
RegsAvailable.set();
// Reserved registers are always used.
RegsAvailable ^= ReservedRegs;
// Live-in registers are in use.
if (!MBB->livein_empty())
for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
E = MBB->livein_end(); I != E; ++I)
setUsed(*I);
Tracking = false;
}
void RegScavenger::restoreScavengedReg() {
if (!ScavengedReg)
return;
TII->loadRegFromStackSlot(*MBB, MBBI, ScavengedReg,
ScavengingFrameIndex, ScavengedRC);
MachineBasicBlock::iterator II = prior(MBBI);
RegInfo->eliminateFrameIndex(II, 0, this);
setUsed(ScavengedReg);
ScavengedReg = 0;
ScavengedRC = NULL;
}
void RegScavenger::forward() {
// Move ptr forward.
if (!Tracking) {
MBBI = MBB->begin();
Tracking = true;
} else {
assert(MBBI != MBB->end() && "Already at the end of the basic block!");
MBBI = next(MBBI);
}
MachineInstr *MI = MBBI;
const TargetInstrDesc &TID = MI->getDesc();
// Reaching a terminator instruction. Restore a scavenged register (which
// must be life out.
if (TID.isTerminator())
restoreScavengedReg();
// Process uses first.
BitVector ChangedRegs(NumPhysRegs);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isUse())
continue;
unsigned Reg = MO.getReg();
if (Reg == 0)
continue;
if (!isUsed(Reg)) {
// Register has been scavenged. Restore it!
if (Reg != ScavengedReg)
assert(false && "Using an undefined register!");
else
restoreScavengedReg();
}
if (MO.isKill() && !isReserved(Reg))
ChangedRegs.set(Reg);
}
// Change states of all registers after all the uses are processed to guard
// against multiple uses.
setUnused(ChangedRegs);
// Process defs.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isDef())
continue;
unsigned Reg = MO.getReg();
// If it's dead upon def, then it is now free.
if (MO.isDead()) {
setUnused(Reg);
continue;
}
// Skip two-address destination operand.
if (TID.findTiedToSrcOperand(i) != -1) {
assert(isUsed(Reg) && "Using an undefined register!");
continue;
}
assert((isUnused(Reg) || isReserved(Reg)) &&
"Re-defining a live register!");
setUsed(Reg);
}
}
void RegScavenger::backward() {
assert(Tracking && "Not tracking states!");
assert(MBBI != MBB->begin() && "Already at start of basic block!");
// Move ptr backward.
MBBI = prior(MBBI);
MachineInstr *MI = MBBI;
// Process defs first.
const TargetInstrDesc &TID = MI->getDesc();
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isDef())
continue;
// Skip two-address destination operand.
if (TID.findTiedToSrcOperand(i) != -1)
continue;
unsigned Reg = MO.getReg();
assert(isUsed(Reg));
if (!isReserved(Reg))
setUnused(Reg);
}
// Process uses.
BitVector ChangedRegs(NumPhysRegs);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isUse())
continue;
unsigned Reg = MO.getReg();
if (Reg == 0)
continue;
assert(isUnused(Reg) || isReserved(Reg));
ChangedRegs.set(Reg);
}
setUsed(ChangedRegs);
}
void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
if (includeReserved)
used = ~RegsAvailable;
else
used = ~RegsAvailable & ~ReservedRegs;
}
/// CreateRegClassMask - Set the bits that represent the registers in the
/// TargetRegisterClass.
static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
++I)
Mask.set(*I);
}
unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
const BitVector &Candidates) const {
// Mask off the registers which are not in the TargetRegisterClass.
BitVector RegsAvailableCopy(NumPhysRegs, false);
CreateRegClassMask(RegClass, RegsAvailableCopy);
RegsAvailableCopy &= RegsAvailable;
// Restrict the search to candidates.
RegsAvailableCopy &= Candidates;
// Returns the first unused (bit is set) register, or 0 is none is found.
int Reg = RegsAvailableCopy.find_first();
return (Reg == -1) ? 0 : Reg;
}
unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
bool ExCalleeSaved) const {
// Mask off the registers which are not in the TargetRegisterClass.
BitVector RegsAvailableCopy(NumPhysRegs, false);
CreateRegClassMask(RegClass, RegsAvailableCopy);
RegsAvailableCopy &= RegsAvailable;
// If looking for a non-callee-saved register, mask off all the callee-saved
// registers.
if (ExCalleeSaved)
RegsAvailableCopy &= ~CalleeSavedRegs;
// Returns the first unused (bit is set) register, or 0 is none is found.
int Reg = RegsAvailableCopy.find_first();
return (Reg == -1) ? 0 : Reg;
}
/// calcDistanceToUse - Calculate the distance to the first use of the
/// specified register.
static unsigned calcDistanceToUse(MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned Reg) {
unsigned Dist = 0;
I = next(I);
while (I != MBB->end()) {
Dist++;
if (I->findRegisterUseOperandIdx(Reg) != -1)
return Dist;
I = next(I);
}
return Dist + 1;
}
unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
MachineBasicBlock::iterator I,
int SPAdj) {
assert(ScavengingFrameIndex >= 0 &&
"Cannot scavenge a register without an emergency spill slot!");
// Mask off the registers which are not in the TargetRegisterClass.
BitVector Candidates(NumPhysRegs, false);
CreateRegClassMask(RC, Candidates);
Candidates ^= ReservedRegs; // Do not include reserved registers.
// Exclude all the registers being used by the instruction.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
MachineOperand &MO = I->getOperand(i);
if (MO.isRegister())
Candidates.reset(MO.getReg());
}
// Find the register whose use is furthest away.
unsigned SReg = 0;
unsigned MaxDist = 0;
int Reg = Candidates.find_first();
while (Reg != -1) {
unsigned Dist = calcDistanceToUse(MBB, I, Reg);
if (Dist >= MaxDist) {
MaxDist = Dist;
SReg = Reg;
}
Reg = Candidates.find_next(Reg);
}
if (ScavengedReg != 0) {
// First restore previously scavenged register.
TII->loadRegFromStackSlot(*MBB, I, ScavengedReg,
ScavengingFrameIndex, ScavengedRC);
MachineBasicBlock::iterator II = prior(I);
RegInfo->eliminateFrameIndex(II, SPAdj, this);
}
TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC);
MachineBasicBlock::iterator II = prior(I);
RegInfo->eliminateFrameIndex(II, SPAdj, this);
ScavengedReg = SReg;
ScavengedRC = RC;
return SReg;
}
<commit_msg>Make the register scavenger update the bookkeeping values for sub/super registers.<commit_after>//===-- RegisterScavenging.cpp - Machine register scavenging --------------===//
//
// 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 machine register scavenger. It can provide
// information such as unused register at any point in a machine basic block.
// It also provides a mechanism to make registers availbale by evicting them
// to spill slots.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "reg-scavenging"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/STLExtras.h"
using namespace llvm;
/// setUsed - Set the register and its sub-registers as being used.
void RegScavenger::setUsed(unsigned Reg) {
RegsAvailable.reset(Reg);
for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
unsigned SubReg = *SubRegs; ++SubRegs)
RegsAvailable.reset(SubReg);
}
/// setUnused - Set the register and its sub-registers as being unused.
void RegScavenger::setUnused(unsigned Reg) {
RegsAvailable.set(Reg);
for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
unsigned SubReg = *SubRegs; ++SubRegs)
RegsAvailable.set(SubReg);
}
void RegScavenger::enterBasicBlock(MachineBasicBlock *mbb) {
const MachineFunction &MF = *mbb->getParent();
const TargetMachine &TM = MF.getTarget();
TII = TM.getInstrInfo();
RegInfo = TM.getRegisterInfo();
assert((NumPhysRegs == 0 || NumPhysRegs == RegInfo->getNumRegs()) &&
"Target changed?");
if (!MBB) {
NumPhysRegs = RegInfo->getNumRegs();
RegsAvailable.resize(NumPhysRegs);
// Create reserved registers bitvector.
ReservedRegs = RegInfo->getReservedRegs(MF);
// Create callee-saved registers bitvector.
CalleeSavedRegs.resize(NumPhysRegs);
const unsigned *CSRegs = RegInfo->getCalleeSavedRegs();
if (CSRegs != NULL)
for (unsigned i = 0; CSRegs[i]; ++i)
CalleeSavedRegs.set(CSRegs[i]);
}
MBB = mbb;
ScavengedReg = 0;
ScavengedRC = NULL;
// All registers started out unused.
RegsAvailable.set();
// Reserved registers are always used.
RegsAvailable ^= ReservedRegs;
// Live-in registers are in use.
if (!MBB->livein_empty())
for (MachineBasicBlock::const_livein_iterator I = MBB->livein_begin(),
E = MBB->livein_end(); I != E; ++I)
setUsed(*I);
Tracking = false;
}
void RegScavenger::restoreScavengedReg() {
if (!ScavengedReg)
return;
TII->loadRegFromStackSlot(*MBB, MBBI, ScavengedReg,
ScavengingFrameIndex, ScavengedRC);
MachineBasicBlock::iterator II = prior(MBBI);
RegInfo->eliminateFrameIndex(II, 0, this);
setUsed(ScavengedReg);
ScavengedReg = 0;
ScavengedRC = NULL;
}
void RegScavenger::forward() {
// Move ptr forward.
if (!Tracking) {
MBBI = MBB->begin();
Tracking = true;
} else {
assert(MBBI != MBB->end() && "Already at the end of the basic block!");
MBBI = next(MBBI);
}
MachineInstr *MI = MBBI;
const TargetInstrDesc &TID = MI->getDesc();
// Reaching a terminator instruction. Restore a scavenged register (which
// must be life out.
if (TID.isTerminator())
restoreScavengedReg();
// Process uses first.
BitVector ChangedRegs(NumPhysRegs);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isUse())
continue;
unsigned Reg = MO.getReg();
if (Reg == 0) continue;
if (!isUsed(Reg)) {
// Register has been scavenged. Restore it!
if (Reg != ScavengedReg)
assert(false && "Using an undefined register!");
else
restoreScavengedReg();
}
if (MO.isKill() && !isReserved(Reg)) {
ChangedRegs.set(Reg);
for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
unsigned SubReg = *SubRegs; ++SubRegs)
ChangedRegs.set(SubReg);
}
}
// Change states of all registers after all the uses are processed to guard
// against multiple uses.
setUnused(ChangedRegs);
// Process defs.
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isDef())
continue;
unsigned Reg = MO.getReg();
// If it's dead upon def, then it is now free.
if (MO.isDead()) {
setUnused(Reg);
continue;
}
// Skip two-address destination operand.
if (TID.findTiedToSrcOperand(i) != -1) {
assert(isUsed(Reg) && "Using an undefined register!");
continue;
}
assert((isUnused(Reg) || isReserved(Reg)) &&
"Re-defining a live register!");
setUsed(Reg);
}
}
void RegScavenger::backward() {
assert(Tracking && "Not tracking states!");
assert(MBBI != MBB->begin() && "Already at start of basic block!");
// Move ptr backward.
MBBI = prior(MBBI);
MachineInstr *MI = MBBI;
// Process defs first.
const TargetInstrDesc &TID = MI->getDesc();
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isDef())
continue;
// Skip two-address destination operand.
if (TID.findTiedToSrcOperand(i) != -1)
continue;
unsigned Reg = MO.getReg();
assert(isUsed(Reg));
if (!isReserved(Reg))
setUnused(Reg);
}
// Process uses.
BitVector ChangedRegs(NumPhysRegs);
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
if (!MO.isRegister() || !MO.isUse())
continue;
unsigned Reg = MO.getReg();
if (Reg == 0)
continue;
assert(isUnused(Reg) || isReserved(Reg));
ChangedRegs.set(Reg);
// Set the sub-registers as "used".
for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
unsigned SubReg = *SubRegs; ++SubRegs)
ChangedRegs.set(SubReg);
}
setUsed(ChangedRegs);
}
void RegScavenger::getRegsUsed(BitVector &used, bool includeReserved) {
if (includeReserved)
used = ~RegsAvailable;
else
used = ~RegsAvailable & ~ReservedRegs;
}
/// CreateRegClassMask - Set the bits that represent the registers in the
/// TargetRegisterClass.
static void CreateRegClassMask(const TargetRegisterClass *RC, BitVector &Mask) {
for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I != E;
++I)
Mask.set(*I);
}
unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
const BitVector &Candidates) const {
// Mask off the registers which are not in the TargetRegisterClass.
BitVector RegsAvailableCopy(NumPhysRegs, false);
CreateRegClassMask(RegClass, RegsAvailableCopy);
RegsAvailableCopy &= RegsAvailable;
// Restrict the search to candidates.
RegsAvailableCopy &= Candidates;
// Returns the first unused (bit is set) register, or 0 is none is found.
int Reg = RegsAvailableCopy.find_first();
return (Reg == -1) ? 0 : Reg;
}
unsigned RegScavenger::FindUnusedReg(const TargetRegisterClass *RegClass,
bool ExCalleeSaved) const {
// Mask off the registers which are not in the TargetRegisterClass.
BitVector RegsAvailableCopy(NumPhysRegs, false);
CreateRegClassMask(RegClass, RegsAvailableCopy);
RegsAvailableCopy &= RegsAvailable;
// If looking for a non-callee-saved register, mask off all the callee-saved
// registers.
if (ExCalleeSaved)
RegsAvailableCopy &= ~CalleeSavedRegs;
// Returns the first unused (bit is set) register, or 0 is none is found.
int Reg = RegsAvailableCopy.find_first();
return (Reg == -1) ? 0 : Reg;
}
/// calcDistanceToUse - Calculate the distance to the first use of the
/// specified register.
static unsigned calcDistanceToUse(MachineBasicBlock *MBB,
MachineBasicBlock::iterator I, unsigned Reg) {
unsigned Dist = 0;
I = next(I);
while (I != MBB->end()) {
Dist++;
if (I->findRegisterUseOperandIdx(Reg) != -1)
return Dist;
I = next(I);
}
return Dist + 1;
}
unsigned RegScavenger::scavengeRegister(const TargetRegisterClass *RC,
MachineBasicBlock::iterator I,
int SPAdj) {
assert(ScavengingFrameIndex >= 0 &&
"Cannot scavenge a register without an emergency spill slot!");
// Mask off the registers which are not in the TargetRegisterClass.
BitVector Candidates(NumPhysRegs, false);
CreateRegClassMask(RC, Candidates);
Candidates ^= ReservedRegs; // Do not include reserved registers.
// Exclude all the registers being used by the instruction.
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
MachineOperand &MO = I->getOperand(i);
if (MO.isRegister())
Candidates.reset(MO.getReg());
}
// Find the register whose use is furthest away.
unsigned SReg = 0;
unsigned MaxDist = 0;
int Reg = Candidates.find_first();
while (Reg != -1) {
unsigned Dist = calcDistanceToUse(MBB, I, Reg);
if (Dist >= MaxDist) {
MaxDist = Dist;
SReg = Reg;
}
Reg = Candidates.find_next(Reg);
}
if (ScavengedReg != 0) {
// First restore previously scavenged register.
TII->loadRegFromStackSlot(*MBB, I, ScavengedReg,
ScavengingFrameIndex, ScavengedRC);
MachineBasicBlock::iterator II = prior(I);
RegInfo->eliminateFrameIndex(II, SPAdj, this);
}
TII->storeRegToStackSlot(*MBB, I, SReg, true, ScavengingFrameIndex, RC);
MachineBasicBlock::iterator II = prior(I);
RegInfo->eliminateFrameIndex(II, SPAdj, this);
ScavengedReg = SReg;
ScavengedRC = RC;
return SReg;
}
<|endoftext|> |
<commit_before>//===-- DWARFCompileUnit.cpp ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DWARFCompileUnit.h"
#include "DWARFContext.h"
#include "DWARFFormValue.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace dwarf;
DataExtractor DWARFCompileUnit::getDebugInfoExtractor() const {
return DataExtractor(Context.getInfoSection(),
Context.isLittleEndian(), getAddressByteSize());
}
bool DWARFCompileUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
clear();
Offset = *offset_ptr;
if (debug_info.isValidOffset(*offset_ptr)) {
uint64_t abbrOffset;
const DWARFDebugAbbrev *abbr = Context.getDebugAbbrev();
Length = debug_info.getU32(offset_ptr);
Version = debug_info.getU16(offset_ptr);
abbrOffset = debug_info.getU32(offset_ptr);
AddrSize = debug_info.getU8(offset_ptr);
bool lengthOK = debug_info.isValidOffset(getNextCompileUnitOffset()-1);
bool versionOK = DWARFContext::isSupportedVersion(Version);
bool abbrOffsetOK = Context.getAbbrevSection().size() > abbrOffset;
bool addrSizeOK = AddrSize == 4 || AddrSize == 8;
if (lengthOK && versionOK && addrSizeOK && abbrOffsetOK && abbr != NULL) {
Abbrevs = abbr->getAbbreviationDeclarationSet(abbrOffset);
return true;
}
// reset the offset to where we tried to parse from if anything went wrong
*offset_ptr = Offset;
}
return false;
}
uint32_t
DWARFCompileUnit::extract(uint32_t offset, DataExtractor debug_info_data,
const DWARFAbbreviationDeclarationSet *abbrevs) {
clear();
Offset = offset;
if (debug_info_data.isValidOffset(offset)) {
Length = debug_info_data.getU32(&offset);
Version = debug_info_data.getU16(&offset);
bool abbrevsOK = debug_info_data.getU32(&offset) == abbrevs->getOffset();
Abbrevs = abbrevs;
AddrSize = debug_info_data.getU8 (&offset);
bool versionOK = DWARFContext::isSupportedVersion(Version);
bool addrSizeOK = AddrSize == 4 || AddrSize == 8;
if (versionOK && addrSizeOK && abbrevsOK &&
debug_info_data.isValidOffset(offset))
return offset;
}
return 0;
}
void DWARFCompileUnit::clear() {
Offset = 0;
Length = 0;
Version = 0;
Abbrevs = 0;
AddrSize = 0;
BaseAddr = 0;
clearDIEs(false);
}
void DWARFCompileUnit::dump(raw_ostream &OS) {
OS << format("0x%08x", Offset) << ": Compile Unit:"
<< " length = " << format("0x%08x", Length)
<< " version = " << format("0x%04x", Version)
<< " abbr_offset = " << format("0x%04x", Abbrevs->getOffset())
<< " addr_size = " << format("0x%02x", AddrSize)
<< " (next CU at " << format("0x%08x", getNextCompileUnitOffset())
<< ")\n";
getCompileUnitDIE(false)->dump(OS, this, -1U);
}
const char *DWARFCompileUnit::getCompilationDir() {
extractDIEsIfNeeded(true);
if (DieArray.empty())
return 0;
return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, 0);
}
void DWARFCompileUnit::setDIERelations() {
if (DieArray.empty())
return;
DWARFDebugInfoEntryMinimal *die_array_begin = &DieArray.front();
DWARFDebugInfoEntryMinimal *die_array_end = &DieArray.back();
DWARFDebugInfoEntryMinimal *curr_die;
// We purposely are skipping the last element in the array in the loop below
// so that we can always have a valid next item
for (curr_die = die_array_begin; curr_die < die_array_end; ++curr_die) {
// Since our loop doesn't include the last element, we can always
// safely access the next die in the array.
DWARFDebugInfoEntryMinimal *next_die = curr_die + 1;
const DWARFAbbreviationDeclaration *curr_die_abbrev =
curr_die->getAbbreviationDeclarationPtr();
if (curr_die_abbrev) {
// Normal DIE
if (curr_die_abbrev->hasChildren())
next_die->setParent(curr_die);
else
curr_die->setSibling(next_die);
} else {
// NULL DIE that terminates a sibling chain
DWARFDebugInfoEntryMinimal *parent = curr_die->getParent();
if (parent)
parent->setSibling(next_die);
}
}
// Since we skipped the last element, we need to fix it up!
if (die_array_begin < die_array_end)
curr_die->setParent(die_array_begin);
}
size_t DWARFCompileUnit::extractDIEsIfNeeded(bool cu_die_only) {
const size_t initial_die_array_size = DieArray.size();
if ((cu_die_only && initial_die_array_size > 0) ||
initial_die_array_size > 1)
return 0; // Already parsed
// Set the offset to that of the first DIE and calculate the start of the
// next compilation unit header.
uint32_t offset = getFirstDIEOffset();
uint32_t next_cu_offset = getNextCompileUnitOffset();
DWARFDebugInfoEntryMinimal die;
// Keep a flat array of the DIE for binary lookup by DIE offset
uint32_t depth = 0;
// We are in our compile unit, parse starting at the offset
// we were told to parse
const uint8_t *fixed_form_sizes =
DWARFFormValue::getFixedFormSizesForAddressSize(getAddressByteSize());
while (offset < next_cu_offset &&
die.extractFast(this, fixed_form_sizes, &offset)) {
if (depth == 0) {
uint64_t base_addr =
die.getAttributeValueAsUnsigned(this, DW_AT_low_pc, -1U);
if (base_addr == -1U)
base_addr = die.getAttributeValueAsUnsigned(this, DW_AT_entry_pc, 0);
setBaseAddress(base_addr);
}
if (cu_die_only) {
addDIE(die);
return 1;
}
else if (depth == 0 && initial_die_array_size == 1) {
// Don't append the CU die as we already did that
} else {
addDIE (die);
}
const DWARFAbbreviationDeclaration *abbrDecl =
die.getAbbreviationDeclarationPtr();
if (abbrDecl) {
// Normal DIE
if (abbrDecl->hasChildren())
++depth;
} else {
// NULL DIE.
if (depth > 0)
--depth;
if (depth == 0)
break; // We are done with this compile unit!
}
}
// Give a little bit of info if we encounter corrupt DWARF (our offset
// should always terminate at or before the start of the next compilation
// unit header).
if (offset > next_cu_offset) {
fprintf (stderr, "warning: DWARF compile unit extends beyond its bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), offset);
}
setDIERelations();
return DieArray.size();
}
void DWARFCompileUnit::clearDIEs(bool keep_compile_unit_die) {
if (DieArray.size() > (unsigned)keep_compile_unit_die) {
// std::vectors never get any smaller when resized to a smaller size,
// or when clear() or erase() are called, the size will report that it
// is smaller, but the memory allocated remains intact (call capacity()
// to see this). So we need to create a temporary vector and swap the
// contents which will cause just the internal pointers to be swapped
// so that when "tmp_array" goes out of scope, it will destroy the
// contents.
// Save at least the compile unit DIE
std::vector<DWARFDebugInfoEntryMinimal> tmpArray;
DieArray.swap(tmpArray);
if (keep_compile_unit_die)
DieArray.push_back(tmpArray.front());
}
}
void
DWARFCompileUnit::buildAddressRangeTable(DWARFDebugAranges *debug_aranges,
bool clear_dies_if_already_not_parsed){
// This function is usually called if there in no .debug_aranges section
// in order to produce a compile unit level set of address ranges that
// is accurate. If the DIEs weren't parsed, then we don't want all dies for
// all compile units to stay loaded when they weren't needed. So we can end
// up parsing the DWARF and then throwing them all away to keep memory usage
// down.
const bool clear_dies = extractDIEsIfNeeded(false) > 1 &&
clear_dies_if_already_not_parsed;
DieArray[0].buildAddressRangeTable(this, debug_aranges);
// Keep memory down by clearing DIEs if this generate function
// caused them to be parsed.
if (clear_dies)
clearDIEs(true);
}
const DWARFDebugInfoEntryMinimal*
DWARFCompileUnit::getFunctionDIEForAddress(int64_t address) {
extractDIEsIfNeeded(false);
for (size_t i = 0, n = DieArray.size(); i != n; i++) {
if (DieArray[i].addressRangeContainsAddress(this, address))
return &DieArray[i];
}
return 0;
}
<commit_msg>Tidy.<commit_after>//===-- DWARFCompileUnit.cpp ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "DWARFCompileUnit.h"
#include "DWARFContext.h"
#include "DWARFFormValue.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace dwarf;
DataExtractor DWARFCompileUnit::getDebugInfoExtractor() const {
return DataExtractor(Context.getInfoSection(),
Context.isLittleEndian(), getAddressByteSize());
}
bool DWARFCompileUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
clear();
Offset = *offset_ptr;
if (debug_info.isValidOffset(*offset_ptr)) {
uint64_t abbrOffset;
const DWARFDebugAbbrev *abbr = Context.getDebugAbbrev();
Length = debug_info.getU32(offset_ptr);
Version = debug_info.getU16(offset_ptr);
abbrOffset = debug_info.getU32(offset_ptr);
AddrSize = debug_info.getU8(offset_ptr);
bool lengthOK = debug_info.isValidOffset(getNextCompileUnitOffset()-1);
bool versionOK = DWARFContext::isSupportedVersion(Version);
bool abbrOffsetOK = Context.getAbbrevSection().size() > abbrOffset;
bool addrSizeOK = AddrSize == 4 || AddrSize == 8;
if (lengthOK && versionOK && addrSizeOK && abbrOffsetOK && abbr != NULL) {
Abbrevs = abbr->getAbbreviationDeclarationSet(abbrOffset);
return true;
}
// reset the offset to where we tried to parse from if anything went wrong
*offset_ptr = Offset;
}
return false;
}
uint32_t
DWARFCompileUnit::extract(uint32_t offset, DataExtractor debug_info_data,
const DWARFAbbreviationDeclarationSet *abbrevs) {
clear();
Offset = offset;
if (debug_info_data.isValidOffset(offset)) {
Length = debug_info_data.getU32(&offset);
Version = debug_info_data.getU16(&offset);
bool abbrevsOK = debug_info_data.getU32(&offset) == abbrevs->getOffset();
Abbrevs = abbrevs;
AddrSize = debug_info_data.getU8 (&offset);
bool versionOK = DWARFContext::isSupportedVersion(Version);
bool addrSizeOK = AddrSize == 4 || AddrSize == 8;
if (versionOK && addrSizeOK && abbrevsOK &&
debug_info_data.isValidOffset(offset))
return offset;
}
return 0;
}
void DWARFCompileUnit::clear() {
Offset = 0;
Length = 0;
Version = 0;
Abbrevs = 0;
AddrSize = 0;
BaseAddr = 0;
clearDIEs(false);
}
void DWARFCompileUnit::dump(raw_ostream &OS) {
OS << format("0x%08x", Offset) << ": Compile Unit:"
<< " length = " << format("0x%08x", Length)
<< " version = " << format("0x%04x", Version)
<< " abbr_offset = " << format("0x%04x", Abbrevs->getOffset())
<< " addr_size = " << format("0x%02x", AddrSize)
<< " (next CU at " << format("0x%08x", getNextCompileUnitOffset())
<< ")\n";
getCompileUnitDIE(false)->dump(OS, this, -1U);
}
const char *DWARFCompileUnit::getCompilationDir() {
extractDIEsIfNeeded(true);
if (DieArray.empty())
return 0;
return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, 0);
}
void DWARFCompileUnit::setDIERelations() {
if (DieArray.empty())
return;
DWARFDebugInfoEntryMinimal *die_array_begin = &DieArray.front();
DWARFDebugInfoEntryMinimal *die_array_end = &DieArray.back();
DWARFDebugInfoEntryMinimal *curr_die;
// We purposely are skipping the last element in the array in the loop below
// so that we can always have a valid next item
for (curr_die = die_array_begin; curr_die < die_array_end; ++curr_die) {
// Since our loop doesn't include the last element, we can always
// safely access the next die in the array.
DWARFDebugInfoEntryMinimal *next_die = curr_die + 1;
const DWARFAbbreviationDeclaration *curr_die_abbrev =
curr_die->getAbbreviationDeclarationPtr();
if (curr_die_abbrev) {
// Normal DIE
if (curr_die_abbrev->hasChildren())
next_die->setParent(curr_die);
else
curr_die->setSibling(next_die);
} else {
// NULL DIE that terminates a sibling chain
DWARFDebugInfoEntryMinimal *parent = curr_die->getParent();
if (parent)
parent->setSibling(next_die);
}
}
// Since we skipped the last element, we need to fix it up!
if (die_array_begin < die_array_end)
curr_die->setParent(die_array_begin);
}
size_t DWARFCompileUnit::extractDIEsIfNeeded(bool cu_die_only) {
const size_t initial_die_array_size = DieArray.size();
if ((cu_die_only && initial_die_array_size > 0) ||
initial_die_array_size > 1)
return 0; // Already parsed
// Set the offset to that of the first DIE and calculate the start of the
// next compilation unit header.
uint32_t offset = getFirstDIEOffset();
uint32_t next_cu_offset = getNextCompileUnitOffset();
DWARFDebugInfoEntryMinimal die;
// Keep a flat array of the DIE for binary lookup by DIE offset
uint32_t depth = 0;
// We are in our compile unit, parse starting at the offset
// we were told to parse
const uint8_t *fixed_form_sizes =
DWARFFormValue::getFixedFormSizesForAddressSize(getAddressByteSize());
while (offset < next_cu_offset &&
die.extractFast(this, fixed_form_sizes, &offset)) {
if (depth == 0) {
uint64_t base_addr =
die.getAttributeValueAsUnsigned(this, DW_AT_low_pc, -1U);
if (base_addr == -1U)
base_addr = die.getAttributeValueAsUnsigned(this, DW_AT_entry_pc, 0);
setBaseAddress(base_addr);
}
if (cu_die_only) {
addDIE(die);
return 1;
}
else if (depth == 0 && initial_die_array_size == 1) {
// Don't append the CU die as we already did that
} else {
addDIE (die);
}
const DWARFAbbreviationDeclaration *abbrDecl =
die.getAbbreviationDeclarationPtr();
if (abbrDecl) {
// Normal DIE
if (abbrDecl->hasChildren())
++depth;
} else {
// NULL DIE.
if (depth > 0)
--depth;
if (depth == 0)
break; // We are done with this compile unit!
}
}
// Give a little bit of info if we encounter corrupt DWARF (our offset
// should always terminate at or before the start of the next compilation
// unit header).
if (offset > next_cu_offset)
fprintf (stderr, "warning: DWARF compile unit extends beyond its"
"bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), offset);
setDIERelations();
return DieArray.size();
}
void DWARFCompileUnit::clearDIEs(bool keep_compile_unit_die) {
if (DieArray.size() > (unsigned)keep_compile_unit_die) {
// std::vectors never get any smaller when resized to a smaller size,
// or when clear() or erase() are called, the size will report that it
// is smaller, but the memory allocated remains intact (call capacity()
// to see this). So we need to create a temporary vector and swap the
// contents which will cause just the internal pointers to be swapped
// so that when "tmp_array" goes out of scope, it will destroy the
// contents.
// Save at least the compile unit DIE
std::vector<DWARFDebugInfoEntryMinimal> tmpArray;
DieArray.swap(tmpArray);
if (keep_compile_unit_die)
DieArray.push_back(tmpArray.front());
}
}
void
DWARFCompileUnit::buildAddressRangeTable(DWARFDebugAranges *debug_aranges,
bool clear_dies_if_already_not_parsed){
// This function is usually called if there in no .debug_aranges section
// in order to produce a compile unit level set of address ranges that
// is accurate. If the DIEs weren't parsed, then we don't want all dies for
// all compile units to stay loaded when they weren't needed. So we can end
// up parsing the DWARF and then throwing them all away to keep memory usage
// down.
const bool clear_dies = extractDIEsIfNeeded(false) > 1 &&
clear_dies_if_already_not_parsed;
DieArray[0].buildAddressRangeTable(this, debug_aranges);
// Keep memory down by clearing DIEs if this generate function
// caused them to be parsed.
if (clear_dies)
clearDIEs(true);
}
const DWARFDebugInfoEntryMinimal*
DWARFCompileUnit::getFunctionDIEForAddress(int64_t address) {
extractDIEsIfNeeded(false);
for (size_t i = 0, n = DieArray.size(); i != n; i++) {
if (DieArray[i].addressRangeContainsAddress(this, address))
return &DieArray[i];
}
return 0;
}
<|endoftext|> |
<commit_before>//===- GsymCreator.cpp ----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/GSYM/GsymCreator.h"
#include "llvm/DebugInfo/GSYM/FileWriter.h"
#include "llvm/DebugInfo/GSYM/Header.h"
#include "llvm/DebugInfo/GSYM/LineTable.h"
#include "llvm/MC/StringTableBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
using namespace llvm;
using namespace gsym;
GsymCreator::GsymCreator() : StrTab(StringTableBuilder::ELF) {
insertFile(StringRef());
}
uint32_t GsymCreator::insertFile(StringRef Path,
llvm::sys::path::Style Style) {
llvm::StringRef directory = llvm::sys::path::parent_path(Path, Style);
llvm::StringRef filename = llvm::sys::path::filename(Path, Style);
FileEntry FE(insertString(directory), insertString(filename));
std::lock_guard<std::recursive_mutex> Guard(Mutex);
const auto NextIndex = Files.size();
// Find FE in hash map and insert if not present.
auto R = FileEntryToIndex.insert(std::make_pair(FE, NextIndex));
if (R.second)
Files.emplace_back(FE);
return R.first->second;
}
llvm::Error GsymCreator::save(StringRef Path,
llvm::support::endianness ByteOrder) const {
std::error_code EC;
raw_fd_ostream OutStrm(Path, EC);
if (EC)
return llvm::errorCodeToError(EC);
FileWriter O(OutStrm, ByteOrder);
return encode(O);
}
llvm::Error GsymCreator::encode(FileWriter &O) const {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
if (Funcs.empty())
return createStringError(std::errc::invalid_argument,
"no functions to encode");
if (!Finalized)
return createStringError(std::errc::invalid_argument,
"GsymCreator wasn't finalized prior to encoding");
if (Funcs.size() > UINT32_MAX)
return createStringError(std::errc::invalid_argument,
"too many FunctionInfos");
const uint64_t MinAddr = Funcs.front().startAddress();
const uint64_t MaxAddr = Funcs.back().startAddress();
const uint64_t AddrDelta = MaxAddr - MinAddr;
Header Hdr;
Hdr.Magic = GSYM_MAGIC;
Hdr.Version = GSYM_VERSION;
Hdr.AddrOffSize = 0;
Hdr.UUIDSize = static_cast<uint8_t>(UUID.size());
Hdr.BaseAddress = MinAddr;
Hdr.NumAddresses = static_cast<uint32_t>(Funcs.size());
Hdr.StrtabOffset = 0; // We will fix this up later.
Hdr.StrtabOffset = 0; // We will fix this up later.
bzero(Hdr.UUID, sizeof(Hdr.UUID));
if (UUID.size() > sizeof(Hdr.UUID))
return createStringError(std::errc::invalid_argument,
"invalid UUID size %u", (uint32_t)UUID.size());
// Set the address offset size correctly in the GSYM header.
if (AddrDelta <= UINT8_MAX)
Hdr.AddrOffSize = 1;
else if (AddrDelta <= UINT16_MAX)
Hdr.AddrOffSize = 2;
else if (AddrDelta <= UINT32_MAX)
Hdr.AddrOffSize = 4;
else
Hdr.AddrOffSize = 8;
// Copy the UUID value if we have one.
if (UUID.size() > 0)
memcpy(Hdr.UUID, UUID.data(), UUID.size());
// Write out the header.
llvm::Error Err = Hdr.encode(O);
if (Err)
return Err;
// Write out the address offsets.
O.alignTo(Hdr.AddrOffSize);
for (const auto &FuncInfo : Funcs) {
uint64_t AddrOffset = FuncInfo.startAddress() - Hdr.BaseAddress;
switch(Hdr.AddrOffSize) {
case 1: O.writeU8(static_cast<uint8_t>(AddrOffset)); break;
case 2: O.writeU16(static_cast<uint16_t>(AddrOffset)); break;
case 4: O.writeU32(static_cast<uint32_t>(AddrOffset)); break;
case 8: O.writeU64(AddrOffset); break;
}
}
// Write out all zeros for the AddrInfoOffsets.
O.alignTo(4);
const off_t AddrInfoOffsetsOffset = O.tell();
for (size_t i = 0, n = Funcs.size(); i < n; ++i)
O.writeU32(0);
// Write out the file table
O.alignTo(4);
assert(!Files.empty());
assert(Files[0].Dir == 0);
assert(Files[0].Base == 0);
size_t NumFiles = Files.size();
if (NumFiles > UINT32_MAX)
return createStringError(std::errc::invalid_argument,
"too many files");
O.writeU32(static_cast<uint32_t>(NumFiles));
for (auto File: Files) {
O.writeU32(File.Dir);
O.writeU32(File.Base);
}
// Write out the sting table.
const off_t StrtabOffset = O.tell();
StrTab.write(O.get_stream());
const off_t StrtabSize = O.tell() - StrtabOffset;
std::vector<uint32_t> AddrInfoOffsets;
// Write out the address infos for each function info.
for (const auto &FuncInfo : Funcs) {
if (Expected<uint64_t> OffsetOrErr = FuncInfo.encode(O))
AddrInfoOffsets.push_back(OffsetOrErr.get());
else
return OffsetOrErr.takeError();
}
// Fixup the string table offset and size in the header
O.fixup32((uint32_t)StrtabOffset, offsetof(Header, StrtabOffset));
O.fixup32((uint32_t)StrtabSize, offsetof(Header, StrtabSize));
// Fixup all address info offsets
uint64_t Offset = 0;
for (auto AddrInfoOffset: AddrInfoOffsets) {
O.fixup32(AddrInfoOffset, AddrInfoOffsetsOffset + Offset);
Offset += 4;
}
return ErrorSuccess();
}
llvm::Error GsymCreator::finalize(llvm::raw_ostream &OS) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
if (Finalized)
return createStringError(std::errc::invalid_argument,
"already finalized");
Finalized = true;
// Sort function infos so we can emit sorted functions.
llvm::sort(Funcs.begin(), Funcs.end());
// Don't let the string table indexes change by finalizing in order.
StrTab.finalizeInOrder();
// Remove duplicates function infos that have both entries from debug info
// (DWARF or Breakpad) and entries from the SymbolTable.
//
// Also handle overlapping function. Usually there shouldn't be any, but they
// can and do happen in some rare cases.
//
// (a) (b) (c)
// ^ ^ ^ ^
// |X |Y |X ^ |X
// | | | |Y | ^
// | | | v v |Y
// v v v v
//
// In (a) and (b), Y is ignored and X will be reported for the full range.
// In (c), both functions will be included in the result and lookups for an
// address in the intersection will return Y because of binary search.
//
// Note that in case of (b), we cannot include Y in the result because then
// we wouldn't find any function for range (end of Y, end of X)
// with binary search
auto NumBefore = Funcs.size();
auto Curr = Funcs.begin();
auto Prev = Funcs.end();
while (Curr != Funcs.end()) {
// Can't check for overlaps or same address ranges if we don't have a
// previous entry
if (Prev != Funcs.end()) {
if (Prev->Range.intersects(Curr->Range)) {
// Overlapping address ranges.
if (Prev->Range == Curr->Range) {
// Same address range. Check if one is from debug info and the other
// is from a symbol table. If so, then keep the one with debug info.
// Our sorting guarantees that entries with matching address ranges
// that have debug info are last in the sort.
if (*Prev == *Curr) {
// FunctionInfo entries match exactly (range, lines, inlines)
OS << "warning: duplicate function info entries, removing "
"duplicate:\n"
<< *Curr << '\n';
Curr = Funcs.erase(Prev);
} else {
if (!Prev->hasRichInfo() && Curr->hasRichInfo()) {
// Same address range, one with no debug info (symbol) and the
// next with debug info. Keep the latter.
Curr = Funcs.erase(Prev);
} else {
OS << "warning: same address range contains different debug "
<< "info. Removing:\n"
<< *Prev << "\nIn favor of this one:\n"
<< *Curr << "\n";
Curr = Funcs.erase(Prev);
}
}
} else {
// print warnings about overlaps
OS << "warning: function ranges overlap:\n"
<< *Prev << "\n"
<< *Curr << "\n";
}
} else if (Prev->Range.size() == 0 &&
Curr->Range.contains(Prev->Range.Start)) {
OS << "warning: removing symbol:\n"
<< *Prev << "\nKeeping:\n"
<< *Curr << "\n";
Curr = Funcs.erase(Prev);
}
}
if (Curr == Funcs.end())
break;
Prev = Curr++;
}
OS << "Pruned " << NumBefore - Funcs.size() << " functions, ended with "
<< Funcs.size() << " total\n";
return Error::success();
}
uint32_t GsymCreator::insertString(StringRef S) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
if (S.empty())
return 0;
return StrTab.add(S);
}
void GsymCreator::addFunctionInfo(FunctionInfo &&FI) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
Funcs.emplace_back(FI);
}
void GsymCreator::forEachFunctionInfo(
std::function<bool(FunctionInfo &)> const &Callback) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
for (auto &FI : Funcs) {
if (!Callback(FI))
break;
}
}
void GsymCreator::forEachFunctionInfo(
std::function<bool(const FunctionInfo &)> const &Callback) const {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
for (const auto &FI : Funcs) {
if (!Callback(FI))
break;
}
}
<commit_msg>Unbreak llvm-clang-lld-x86_64-scei-ps4-windows10pro-fast buildbot.<commit_after>//===- GsymCreator.cpp ----------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/GSYM/GsymCreator.h"
#include "llvm/DebugInfo/GSYM/FileWriter.h"
#include "llvm/DebugInfo/GSYM/Header.h"
#include "llvm/DebugInfo/GSYM/LineTable.h"
#include "llvm/MC/StringTableBuilder.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <strings.h>
using namespace llvm;
using namespace gsym;
GsymCreator::GsymCreator() : StrTab(StringTableBuilder::ELF) {
insertFile(StringRef());
}
uint32_t GsymCreator::insertFile(StringRef Path,
llvm::sys::path::Style Style) {
llvm::StringRef directory = llvm::sys::path::parent_path(Path, Style);
llvm::StringRef filename = llvm::sys::path::filename(Path, Style);
FileEntry FE(insertString(directory), insertString(filename));
std::lock_guard<std::recursive_mutex> Guard(Mutex);
const auto NextIndex = Files.size();
// Find FE in hash map and insert if not present.
auto R = FileEntryToIndex.insert(std::make_pair(FE, NextIndex));
if (R.second)
Files.emplace_back(FE);
return R.first->second;
}
llvm::Error GsymCreator::save(StringRef Path,
llvm::support::endianness ByteOrder) const {
std::error_code EC;
raw_fd_ostream OutStrm(Path, EC);
if (EC)
return llvm::errorCodeToError(EC);
FileWriter O(OutStrm, ByteOrder);
return encode(O);
}
llvm::Error GsymCreator::encode(FileWriter &O) const {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
if (Funcs.empty())
return createStringError(std::errc::invalid_argument,
"no functions to encode");
if (!Finalized)
return createStringError(std::errc::invalid_argument,
"GsymCreator wasn't finalized prior to encoding");
if (Funcs.size() > UINT32_MAX)
return createStringError(std::errc::invalid_argument,
"too many FunctionInfos");
const uint64_t MinAddr = Funcs.front().startAddress();
const uint64_t MaxAddr = Funcs.back().startAddress();
const uint64_t AddrDelta = MaxAddr - MinAddr;
Header Hdr;
Hdr.Magic = GSYM_MAGIC;
Hdr.Version = GSYM_VERSION;
Hdr.AddrOffSize = 0;
Hdr.UUIDSize = static_cast<uint8_t>(UUID.size());
Hdr.BaseAddress = MinAddr;
Hdr.NumAddresses = static_cast<uint32_t>(Funcs.size());
Hdr.StrtabOffset = 0; // We will fix this up later.
Hdr.StrtabOffset = 0; // We will fix this up later.
bzero(Hdr.UUID, sizeof(Hdr.UUID));
if (UUID.size() > sizeof(Hdr.UUID))
return createStringError(std::errc::invalid_argument,
"invalid UUID size %u", (uint32_t)UUID.size());
// Set the address offset size correctly in the GSYM header.
if (AddrDelta <= UINT8_MAX)
Hdr.AddrOffSize = 1;
else if (AddrDelta <= UINT16_MAX)
Hdr.AddrOffSize = 2;
else if (AddrDelta <= UINT32_MAX)
Hdr.AddrOffSize = 4;
else
Hdr.AddrOffSize = 8;
// Copy the UUID value if we have one.
if (UUID.size() > 0)
memcpy(Hdr.UUID, UUID.data(), UUID.size());
// Write out the header.
llvm::Error Err = Hdr.encode(O);
if (Err)
return Err;
// Write out the address offsets.
O.alignTo(Hdr.AddrOffSize);
for (const auto &FuncInfo : Funcs) {
uint64_t AddrOffset = FuncInfo.startAddress() - Hdr.BaseAddress;
switch(Hdr.AddrOffSize) {
case 1: O.writeU8(static_cast<uint8_t>(AddrOffset)); break;
case 2: O.writeU16(static_cast<uint16_t>(AddrOffset)); break;
case 4: O.writeU32(static_cast<uint32_t>(AddrOffset)); break;
case 8: O.writeU64(AddrOffset); break;
}
}
// Write out all zeros for the AddrInfoOffsets.
O.alignTo(4);
const off_t AddrInfoOffsetsOffset = O.tell();
for (size_t i = 0, n = Funcs.size(); i < n; ++i)
O.writeU32(0);
// Write out the file table
O.alignTo(4);
assert(!Files.empty());
assert(Files[0].Dir == 0);
assert(Files[0].Base == 0);
size_t NumFiles = Files.size();
if (NumFiles > UINT32_MAX)
return createStringError(std::errc::invalid_argument,
"too many files");
O.writeU32(static_cast<uint32_t>(NumFiles));
for (auto File: Files) {
O.writeU32(File.Dir);
O.writeU32(File.Base);
}
// Write out the sting table.
const off_t StrtabOffset = O.tell();
StrTab.write(O.get_stream());
const off_t StrtabSize = O.tell() - StrtabOffset;
std::vector<uint32_t> AddrInfoOffsets;
// Write out the address infos for each function info.
for (const auto &FuncInfo : Funcs) {
if (Expected<uint64_t> OffsetOrErr = FuncInfo.encode(O))
AddrInfoOffsets.push_back(OffsetOrErr.get());
else
return OffsetOrErr.takeError();
}
// Fixup the string table offset and size in the header
O.fixup32((uint32_t)StrtabOffset, offsetof(Header, StrtabOffset));
O.fixup32((uint32_t)StrtabSize, offsetof(Header, StrtabSize));
// Fixup all address info offsets
uint64_t Offset = 0;
for (auto AddrInfoOffset: AddrInfoOffsets) {
O.fixup32(AddrInfoOffset, AddrInfoOffsetsOffset + Offset);
Offset += 4;
}
return ErrorSuccess();
}
llvm::Error GsymCreator::finalize(llvm::raw_ostream &OS) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
if (Finalized)
return createStringError(std::errc::invalid_argument,
"already finalized");
Finalized = true;
// Sort function infos so we can emit sorted functions.
llvm::sort(Funcs.begin(), Funcs.end());
// Don't let the string table indexes change by finalizing in order.
StrTab.finalizeInOrder();
// Remove duplicates function infos that have both entries from debug info
// (DWARF or Breakpad) and entries from the SymbolTable.
//
// Also handle overlapping function. Usually there shouldn't be any, but they
// can and do happen in some rare cases.
//
// (a) (b) (c)
// ^ ^ ^ ^
// |X |Y |X ^ |X
// | | | |Y | ^
// | | | v v |Y
// v v v v
//
// In (a) and (b), Y is ignored and X will be reported for the full range.
// In (c), both functions will be included in the result and lookups for an
// address in the intersection will return Y because of binary search.
//
// Note that in case of (b), we cannot include Y in the result because then
// we wouldn't find any function for range (end of Y, end of X)
// with binary search
auto NumBefore = Funcs.size();
auto Curr = Funcs.begin();
auto Prev = Funcs.end();
while (Curr != Funcs.end()) {
// Can't check for overlaps or same address ranges if we don't have a
// previous entry
if (Prev != Funcs.end()) {
if (Prev->Range.intersects(Curr->Range)) {
// Overlapping address ranges.
if (Prev->Range == Curr->Range) {
// Same address range. Check if one is from debug info and the other
// is from a symbol table. If so, then keep the one with debug info.
// Our sorting guarantees that entries with matching address ranges
// that have debug info are last in the sort.
if (*Prev == *Curr) {
// FunctionInfo entries match exactly (range, lines, inlines)
OS << "warning: duplicate function info entries, removing "
"duplicate:\n"
<< *Curr << '\n';
Curr = Funcs.erase(Prev);
} else {
if (!Prev->hasRichInfo() && Curr->hasRichInfo()) {
// Same address range, one with no debug info (symbol) and the
// next with debug info. Keep the latter.
Curr = Funcs.erase(Prev);
} else {
OS << "warning: same address range contains different debug "
<< "info. Removing:\n"
<< *Prev << "\nIn favor of this one:\n"
<< *Curr << "\n";
Curr = Funcs.erase(Prev);
}
}
} else {
// print warnings about overlaps
OS << "warning: function ranges overlap:\n"
<< *Prev << "\n"
<< *Curr << "\n";
}
} else if (Prev->Range.size() == 0 &&
Curr->Range.contains(Prev->Range.Start)) {
OS << "warning: removing symbol:\n"
<< *Prev << "\nKeeping:\n"
<< *Curr << "\n";
Curr = Funcs.erase(Prev);
}
}
if (Curr == Funcs.end())
break;
Prev = Curr++;
}
OS << "Pruned " << NumBefore - Funcs.size() << " functions, ended with "
<< Funcs.size() << " total\n";
return Error::success();
}
uint32_t GsymCreator::insertString(StringRef S) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
if (S.empty())
return 0;
return StrTab.add(S);
}
void GsymCreator::addFunctionInfo(FunctionInfo &&FI) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
Funcs.emplace_back(FI);
}
void GsymCreator::forEachFunctionInfo(
std::function<bool(FunctionInfo &)> const &Callback) {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
for (auto &FI : Funcs) {
if (!Callback(FI))
break;
}
}
void GsymCreator::forEachFunctionInfo(
std::function<bool(const FunctionInfo &)> const &Callback) const {
std::lock_guard<std::recursive_mutex> Guard(Mutex);
for (const auto &FI : Funcs) {
if (!Callback(FI))
break;
}
}
<|endoftext|> |
<commit_before>/** \file add_author_synonyms.cc
* \brief Adds author synonyms to each record.
* \author Oliver Obenland
*/
/*
Copyright (C) 2016-2018, Library of the University of Tübingen
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 <iostream>
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
static unsigned modified_count(0);
static unsigned record_count(0);
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
std::string ExtractNameFromSubfields(const MARC::Record::Field &field, const std::string &subfield_codes) {
auto subfield_values(field.getSubfields().extractSubfields(subfield_codes));
if (subfield_values.empty())
return "";
std::sort(subfield_values.begin(), subfield_values.end());
return StringUtil::Join(subfield_values, ' ');
}
void ExtractSynonyms(MARC::Reader * const marc_reader,
std::unordered_map<std::string, std::unordered_set<std::string>> * const author_to_synonyms_map,
const std::string &field_list)
{
std::vector<std::string> tags_and_subfield_codes;
if (unlikely(StringUtil::Split(field_list, ':', &tags_and_subfield_codes) < 2))
LOG_ERROR("need at least two fields!");
unsigned count(0);
while (const MARC::Record record = marc_reader->read()) {
++count;
const auto primary_name_field(record.findTag(tags_and_subfield_codes[0].substr(0, MARC::Record::TAG_LENGTH)));
if (primary_name_field == record.end())
continue;
const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,
tags_and_subfield_codes[0].substr(3)));
if (unlikely(primary_name.empty()))
continue;
std::unordered_set<std::string> synonyms;
if (author_to_synonyms_map->find(primary_name) != author_to_synonyms_map->end())
continue;
for (const auto &tag_and_subfield_codes : tags_and_subfield_codes) {
const std::string tag(tag_and_subfield_codes.substr(0, MARC::Record::TAG_LENGTH));
const std::string secondary_field_subfield_codes(tag_and_subfield_codes.substr(MARC::Record::TAG_LENGTH));
for (auto secondary_name_field(record.findTag(tag));
secondary_name_field != record.end();
++secondary_name_field)
{
const std::string secondary_name(ExtractNameFromSubfields(*secondary_name_field,
secondary_field_subfield_codes));
if (not secondary_name.empty())
synonyms.emplace(secondary_name);
}
}
if (not synonyms.empty())
author_to_synonyms_map->emplace(primary_name, synonyms);
}
std::cout << "Found synonyms for " << author_to_synonyms_map->size() << " authors while processing " << count
<< " norm data records.\n";
}
const std::string SYNOMYM_FIELD("109"); // This must be an o/w unused field!
void ProcessRecord(MARC::Record * const record,
const std::unordered_map<std::string, std::unordered_set<std::string>> &author_to_synonyms_map,
const std::string &primary_author_field)
{
if (unlikely(record->findTag(SYNOMYM_FIELD) != record->end()))
LOG_ERROR("field " + SYNOMYM_FIELD + " is apparently already in use in at least some title records!");
const auto primary_name_field(record->findTag(primary_author_field.substr(0, 3)));
if (primary_name_field == record->end())
return;
const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,
primary_author_field.substr(3)));
if (unlikely(primary_name.empty()))
return;
const auto author_and_synonyms(author_to_synonyms_map.find(primary_name));
if (author_and_synonyms == author_to_synonyms_map.end())
return;
MARC::Subfields subfields;
size_t target_field_size(2); // 2 indicators
for (const auto &synonym : author_and_synonyms->second) {
if (target_field_size + 2 /* delimiter + subfield code */ + synonym.length() > MARC::Record::MAX_VARIABLE_FIELD_DATA_LENGTH) {
if (not record->insertField(SYNOMYM_FIELD, subfields)) {
LOG_WARNING("Not enough room to add a " + SYNOMYM_FIELD + " field! (Control number: "
+ record->getControlNumber() + ")");
return;
}
subfields.clear();
target_field_size = 2; // 2 indicators
}
subfields.addSubfield('a', synonym);
target_field_size += 2 /* delimiter + subfield code */ + synonym.length();
}
if (not subfields.empty() and not record->insertField(SYNOMYM_FIELD, subfields)) {
LOG_WARNING("Not enough room to add a " + SYNOMYM_FIELD + " field! (Control number: "
+ record->getControlNumber() + ")");
}
++modified_count;
}
void AddAuthorSynonyms(MARC::Reader * const marc_reader, MARC::Writer * marc_writer,
const std::unordered_map<std::string, std::unordered_set<std::string>> &author_to_synonyms_map,
const std::string &primary_author_field)
{
while (MARC::Record record = marc_reader->read()) {
ProcessRecord(&record, author_to_synonyms_map, primary_author_field);
marc_writer->write(record);
++record_count;
}
std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n";
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 4)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string authority_data_marc_input_filename(argv[2]);
const std::string marc_output_filename(argv[3]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Title input file name equals title output file name!");
if (unlikely(authority_data_marc_input_filename == marc_output_filename))
LOG_ERROR("Authority data input file name equals MARC output file name!");
auto marc_reader(MARC::Reader::Factory(marc_input_filename));
auto authority_reader(MARC::Reader::Factory(authority_data_marc_input_filename));
auto marc_writer(MARC::Writer::Factory(marc_output_filename));
try {
std::unordered_map<std::string, std::unordered_set<std::string>> author_to_synonyms_map;
ExtractSynonyms(authority_reader.get(), &author_to_synonyms_map, "100abcd:400abcd");
AddAuthorSynonyms(marc_reader.get(), marc_writer.get(), author_to_synonyms_map, "100abcd");
} catch (const std::exception &x) {
LOG_ERROR("caught exception: " + std::string(x.what()));
}
return EXIT_SUCCESS;
}
<commit_msg>Fix erroneous handling of secondary names<commit_after>/** \file add_author_synonyms.cc
* \brief Adds author synonyms to each record.
* \author Oliver Obenland
*/
/*
Copyright (C) 2016-2018, Library of the University of Tübingen
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 <iostream>
#include <unordered_map>
#include <vector>
#include <cstdlib>
#include "Compiler.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
static unsigned modified_count(0);
static unsigned record_count(0);
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " master_marc_input norm_data_marc_input marc_output\n";
std::exit(EXIT_FAILURE);
}
std::string ExtractNameFromSubfields(const MARC::Record::Field &field, const std::string &subfield_codes) {
auto subfield_values(field.getSubfields().extractSubfields(subfield_codes));
if (subfield_values.empty())
return "";
return StringUtil::Join(subfield_values, ' ');
}
void ExtractSynonyms(MARC::Reader * const marc_reader,
std::unordered_map<std::string, std::unordered_set<std::string>> * const author_to_synonyms_map,
const std::string &field_list)
{
std::vector<std::string> tags_and_subfield_codes;
if (unlikely(StringUtil::Split(field_list, ':', &tags_and_subfield_codes) < 2))
LOG_ERROR("need at least two fields!");
unsigned count(0);
while (const MARC::Record record = marc_reader->read()) {
++count;
const auto primary_name_field(record.findTag(tags_and_subfield_codes[0].substr(0, MARC::Record::TAG_LENGTH)));
if (primary_name_field == record.end())
continue;
const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,
tags_and_subfield_codes[0].substr(3)));
if (unlikely(primary_name.empty()))
continue;
std::unordered_set<std::string> synonyms;
if (author_to_synonyms_map->find(primary_name) != author_to_synonyms_map->end())
continue;
for (const auto &tag_and_subfield_codes : tags_and_subfield_codes) {
const std::string tag(tag_and_subfield_codes.substr(0, MARC::Record::TAG_LENGTH));
const std::string secondary_field_subfield_codes(tag_and_subfield_codes.substr(MARC::Record::TAG_LENGTH));
for (const auto secondary_name_field : record.getTagRange(tag)) {
const std::string secondary_name(ExtractNameFromSubfields(secondary_name_field,
secondary_field_subfield_codes));
if (not secondary_name.empty())
synonyms.emplace(secondary_name);
}
}
if (not synonyms.empty())
author_to_synonyms_map->emplace(primary_name, synonyms);
}
std::cout << "Found synonyms for " << author_to_synonyms_map->size() << " authors while processing " << count
<< " norm data records.\n";
}
const std::string SYNOMYM_FIELD("109"); // This must be an o/w unused field!
void ProcessRecord(MARC::Record * const record,
const std::unordered_map<std::string, std::unordered_set<std::string>> &author_to_synonyms_map,
const std::string &primary_author_field)
{
if (unlikely(record->findTag(SYNOMYM_FIELD) != record->end()))
LOG_ERROR("field " + SYNOMYM_FIELD + " is apparently already in use in at least some title records!");
const auto primary_name_field(record->findTag(primary_author_field.substr(0, 3)));
if (primary_name_field == record->end())
return;
const std::string primary_name(ExtractNameFromSubfields(*primary_name_field,
primary_author_field.substr(3)));
if (unlikely(primary_name.empty()))
return;
const auto author_and_synonyms(author_to_synonyms_map.find(primary_name));
if (author_and_synonyms == author_to_synonyms_map.end())
return;
MARC::Subfields subfields;
size_t target_field_size(2); // 2 indicators
for (const auto &synonym : author_and_synonyms->second) {
if (target_field_size + 2 /* delimiter + subfield code */ + synonym.length() > MARC::Record::MAX_VARIABLE_FIELD_DATA_LENGTH) {
if (not record->insertField(SYNOMYM_FIELD, subfields)) {
LOG_WARNING("Not enough room to add a " + SYNOMYM_FIELD + " field! (Control number: "
+ record->getControlNumber() + ")");
return;
}
subfields.clear();
target_field_size = 2; // 2 indicators
}
subfields.addSubfield('a', synonym);
target_field_size += 2 /* delimiter + subfield code */ + synonym.length();
}
if (not subfields.empty() and not record->insertField(SYNOMYM_FIELD, subfields)) {
LOG_WARNING("Not enough room to add a " + SYNOMYM_FIELD + " field! (Control number: "
+ record->getControlNumber() + ")");
}
++modified_count;
}
void AddAuthorSynonyms(MARC::Reader * const marc_reader, MARC::Writer * marc_writer,
const std::unordered_map<std::string, std::unordered_set<std::string>> &author_to_synonyms_map,
const std::string &primary_author_field)
{
while (MARC::Record record = marc_reader->read()) {
ProcessRecord(&record, author_to_synonyms_map, primary_author_field);
marc_writer->write(record);
++record_count;
}
std::cerr << "Modified " << modified_count << " of " << record_count << " record(s).\n";
}
} // unnamed namespace
int Main(int argc, char **argv) {
if (argc != 4)
Usage();
const std::string marc_input_filename(argv[1]);
const std::string authority_data_marc_input_filename(argv[2]);
const std::string marc_output_filename(argv[3]);
if (unlikely(marc_input_filename == marc_output_filename))
LOG_ERROR("Title input file name equals title output file name!");
if (unlikely(authority_data_marc_input_filename == marc_output_filename))
LOG_ERROR("Authority data input file name equals MARC output file name!");
auto marc_reader(MARC::Reader::Factory(marc_input_filename));
auto authority_reader(MARC::Reader::Factory(authority_data_marc_input_filename));
auto marc_writer(MARC::Writer::Factory(marc_output_filename));
try {
std::unordered_map<std::string, std::unordered_set<std::string>> author_to_synonyms_map;
ExtractSynonyms(authority_reader.get(), &author_to_synonyms_map, "100abcd:400abcd");
AddAuthorSynonyms(marc_reader.get(), marc_writer.get(), author_to_synonyms_map, "100abcd");
} catch (const std::exception &x) {
LOG_ERROR("caught exception: " + std::string(x.what()));
}
return EXIT_SUCCESS;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.