text stringlengths 54 60.6k |
|---|
<commit_before>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_DETAILS_TRAITS_HPP
#define DTK_DETAILS_TRAITS_HPP
#include <DTK_Box.hpp>
#include <DTK_Point.hpp>
#include <Kokkos_View.hpp>
namespace DataTransferKit
{
namespace Details
{
namespace Traits
{
template <typename T, typename Enable = void>
struct Access
{
};
template <typename View>
struct Access<View, typename std::enable_if<Kokkos::is_view<View>::value &&
View::rank == 1>::type>
{
// Returns a const reference
KOKKOS_FUNCTION static typename View::const_value_type &get( View const &v,
int i )
{
return v( i );
}
static typename View::size_type size( View const &v )
{
return v.extent( 0 );
}
using Tag = typename Tag<typename View::value_type>::type;
};
template <typename View>
struct Access<View, typename std::enable_if<Kokkos::is_view<View>::value &&
View::rank == 2>::type>
{
KOKKOS_FUNCTION static Point get( View const &v, int i )
{
return {v( i, 0 ), v( i, 1 ), v( i, 2 )};
}
static typename View::size_type size( View const &v )
{
return v.extent( 0 );
}
using Tag = PointTag;
};
} // namespace Traits
} // namespace Details
} // namespace DataTransferKit
#endif
<commit_msg>Comment that the access traits for view of rank-2 return a point by value<commit_after>/****************************************************************************
* Copyright (c) 2012-2018 by the DataTransferKit authors *
* All rights reserved. *
* *
* This file is part of the DataTransferKit library. DataTransferKit is *
* distributed under a BSD 3-clause license. For the licensing terms see *
* the LICENSE file in the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef DTK_DETAILS_TRAITS_HPP
#define DTK_DETAILS_TRAITS_HPP
#include <DTK_Box.hpp>
#include <DTK_Point.hpp>
#include <Kokkos_View.hpp>
namespace DataTransferKit
{
namespace Details
{
namespace Traits
{
template <typename T, typename Enable = void>
struct Access
{
};
template <typename View>
struct Access<View, typename std::enable_if<Kokkos::is_view<View>::value &&
View::rank == 1>::type>
{
// Returns a const reference
KOKKOS_FUNCTION static typename View::const_value_type &get( View const &v,
int i )
{
return v( i );
}
static typename View::size_type size( View const &v )
{
return v.extent( 0 );
}
using Tag = typename Tag<typename View::value_type>::type;
};
template <typename View>
struct Access<View, typename std::enable_if<Kokkos::is_view<View>::value &&
View::rank == 2>::type>
{
// Returns by value
KOKKOS_FUNCTION static Point get( View const &v, int i )
{
return {v( i, 0 ), v( i, 1 ), v( i, 2 )};
}
static typename View::size_type size( View const &v )
{
return v.extent( 0 );
}
using Tag = PointTag;
};
} // namespace Traits
} // namespace Details
} // namespace DataTransferKit
#endif
<|endoftext|> |
<commit_before>/*
* Copyright © 2012 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*
* Authors:
* Eric Anholt <eric@anholt.net>
*
*/
#include "brw_cfg.h"
#include "brw_fs_live_variables.h"
using namespace brw;
#define MAX_INSTRUCTION (1 << 30)
/** @file brw_fs_live_variables.cpp
*
* Support for calculating liveness information about virtual GRFs.
*
* This produces a live interval for each whole virtual GRF. We could
* choose to expose per-component live intervals for VGRFs of size > 1,
* but we currently do not. It is easier for the consumers of this
* information to work with whole VGRFs.
*
* However, we internally track use/def information at the per-component
* (reg_offset) level for greater accuracy. Large VGRFs may be accessed
* piecemeal over many (possibly non-adjacent) instructions. In this case,
* examining a single instruction is insufficient to decide whether a whole
* VGRF is ultimately used or defined. Tracking individual components
* allows us to easily assemble this information.
*
* See Muchnick's Advanced Compiler Design and Implementation, section
* 14.1 (p444).
*/
void
fs_live_variables::setup_one_read(bblock_t *block, fs_inst *inst,
int ip, fs_reg reg)
{
int var = var_from_vgrf[reg.reg] + reg.reg_offset;
/* In most cases, a register can be written over safely by the
* same instruction that is its last use. For a single
* instruction, the sources are dereferenced before writing of the
* destination starts (naturally). This gets more complicated for
* simd16, because the instruction:
*
* add(16) g4<1>F g4<8,8,1>F g6<8,8,1>F
*
* is actually decoded in hardware as:
*
* add(8) g4<1>F g4<8,8,1>F g6<8,8,1>F
* add(8) g5<1>F g5<8,8,1>F g7<8,8,1>F
*
* Which is safe. However, if we have uniform accesses
* happening, we get into trouble:
*
* add(8) g4<1>F g4<0,1,0>F g6<8,8,1>F
* add(8) g5<1>F g4<0,1,0>F g7<8,8,1>F
*
* Now our destination for the first instruction overwrote the
* second instruction's src0, and we get garbage for those 8
* pixels. There's a similar issue for the pre-gen6
* pixel_x/pixel_y, which are registers of 16-bit values and thus
* would get stomped by the first decode as well.
*/
int end_ip = ip;
if (v->dispatch_width == 16 && (reg.smear != -1 ||
(v->pixel_x.reg == reg.reg ||
v->pixel_y.reg == reg.reg))) {
end_ip++;
}
start[var] = MIN2(start[var], ip);
end[var] = MAX2(end[var], end_ip);
/* The use[] bitset marks when the block makes use of a variable (VGRF
* channel) without having completely defined that variable within the
* block.
*/
if (!BITSET_TEST(bd[block->block_num].def, var))
BITSET_SET(bd[block->block_num].use, var);
}
void
fs_live_variables::setup_one_write(bblock_t *block, fs_inst *inst,
int ip, fs_reg reg)
{
int var = var_from_vgrf[reg.reg] + reg.reg_offset;
start[var] = MIN2(start[var], ip);
end[var] = MAX2(end[var], ip);
/* The def[] bitset marks when an initialization in a block completely
* screens off previous updates of that variable (VGRF channel).
*/
if (inst->dst.file == GRF && !inst->is_partial_write()) {
if (!BITSET_TEST(bd[block->block_num].use, var))
BITSET_SET(bd[block->block_num].def, var);
}
}
/**
* Sets up the use[] and def[] bitsets.
*
* The basic-block-level live variable analysis needs to know which
* variables get used before they're completely defined, and which
* variables are completely defined before they're used.
*
* These are tracked at the per-component level, rather than whole VGRFs.
*/
void
fs_live_variables::setup_def_use()
{
int ip = 0;
for (int b = 0; b < cfg->num_blocks; b++) {
bblock_t *block = cfg->blocks[b];
assert(ip == block->start_ip);
if (b > 0)
assert(cfg->blocks[b - 1]->end_ip == ip - 1);
for (fs_inst *inst = (fs_inst *)block->start;
inst != block->end->next;
inst = (fs_inst *)inst->next) {
/* Set use[] for this instruction */
for (unsigned int i = 0; i < 3; i++) {
fs_reg reg = inst->src[i];
if (reg.file != GRF)
continue;
for (int j = 0; j < inst->regs_read(v, i); j++) {
setup_one_read(block, inst, ip, reg);
reg.reg_offset++;
}
}
/* Set def[] for this instruction */
if (inst->dst.file == GRF) {
fs_reg reg = inst->dst;
for (int j = 0; j < inst->regs_written; j++) {
setup_one_write(block, inst, ip, reg);
reg.reg_offset++;
}
}
ip++;
}
}
}
/**
* The algorithm incrementally sets bits in liveout and livein,
* propagating it through control flow. It will eventually terminate
* because it only ever adds bits, and stops when no bits are added in
* a pass.
*/
void
fs_live_variables::compute_live_variables()
{
bool cont = true;
while (cont) {
cont = false;
for (int b = 0; b < cfg->num_blocks; b++) {
/* Update livein */
for (int i = 0; i < bitset_words; i++) {
BITSET_WORD new_livein = (bd[b].use[i] |
(bd[b].liveout[i] & ~bd[b].def[i]));
if (new_livein & ~bd[b].livein[i]) {
bd[b].livein[i] |= new_livein;
cont = true;
}
}
/* Update liveout */
foreach_list(block_node, &cfg->blocks[b]->children) {
bblock_link *link = (bblock_link *)block_node;
bblock_t *block = link->block;
for (int i = 0; i < bitset_words; i++) {
BITSET_WORD new_liveout = (bd[block->block_num].livein[i] &
~bd[b].liveout[i]);
if (new_liveout) {
bd[b].liveout[i] |= new_liveout;
cont = true;
}
}
}
}
}
}
/**
* Extend the start/end ranges for each variable to account for the
* new information calculated from control flow.
*/
void
fs_live_variables::compute_start_end()
{
for (int b = 0; b < cfg->num_blocks; b++) {
for (int i = 0; i < num_vars; i++) {
if (BITSET_TEST(bd[b].livein, i)) {
start[i] = MIN2(start[i], cfg->blocks[b]->start_ip);
end[i] = MAX2(end[i], cfg->blocks[b]->start_ip);
}
if (BITSET_TEST(bd[b].liveout, i)) {
start[i] = MIN2(start[i], cfg->blocks[b]->end_ip);
end[i] = MAX2(end[i], cfg->blocks[b]->end_ip);
}
}
}
}
int
fs_live_variables::var_from_reg(fs_reg *reg)
{
return var_from_vgrf[reg->reg] + reg->reg_offset;
}
fs_live_variables::fs_live_variables(fs_visitor *v, cfg_t *cfg)
: v(v), cfg(cfg)
{
mem_ctx = ralloc_context(NULL);
num_vgrfs = v->virtual_grf_count;
num_vars = 0;
var_from_vgrf = rzalloc_array(mem_ctx, int, num_vgrfs);
for (int i = 0; i < num_vgrfs; i++) {
var_from_vgrf[i] = num_vars;
num_vars += v->virtual_grf_sizes[i];
}
vgrf_from_var = rzalloc_array(mem_ctx, int, num_vars);
for (int i = 0; i < num_vgrfs; i++) {
for (int j = 0; j < v->virtual_grf_sizes[i]; j++) {
vgrf_from_var[var_from_vgrf[i] + j] = i;
}
}
start = ralloc_array(mem_ctx, int, num_vars);
end = rzalloc_array(mem_ctx, int, num_vars);
for (int i = 0; i < num_vars; i++) {
start[i] = MAX_INSTRUCTION;
end[i] = -1;
}
bd = rzalloc_array(mem_ctx, struct block_data, cfg->num_blocks);
bitset_words = BITSET_WORDS(num_vars);
for (int i = 0; i < cfg->num_blocks; i++) {
bd[i].def = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
bd[i].use = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
bd[i].livein = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
bd[i].liveout = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
}
setup_def_use();
compute_live_variables();
compute_start_end();
}
fs_live_variables::~fs_live_variables()
{
ralloc_free(mem_ctx);
}
void
fs_visitor::invalidate_live_intervals()
{
ralloc_free(live_intervals);
live_intervals = NULL;
}
/**
* Compute the live intervals for each virtual GRF.
*
* This uses the per-component use/def data, but combines it to produce
* information about whole VGRFs.
*/
void
fs_visitor::calculate_live_intervals()
{
if (this->live_intervals)
return;
int num_vgrfs = this->virtual_grf_count;
ralloc_free(this->virtual_grf_start);
ralloc_free(this->virtual_grf_end);
virtual_grf_start = ralloc_array(mem_ctx, int, num_vgrfs);
virtual_grf_end = ralloc_array(mem_ctx, int, num_vgrfs);
for (int i = 0; i < num_vgrfs; i++) {
virtual_grf_start[i] = MAX_INSTRUCTION;
virtual_grf_end[i] = -1;
}
cfg_t cfg(&instructions);
this->live_intervals = new(mem_ctx) fs_live_variables(this, &cfg);
/* Merge the per-component live ranges to whole VGRF live ranges. */
for (int i = 0; i < live_intervals->num_vars; i++) {
int vgrf = live_intervals->vgrf_from_var[i];
virtual_grf_start[vgrf] = MIN2(virtual_grf_start[vgrf],
live_intervals->start[i]);
virtual_grf_end[vgrf] = MAX2(virtual_grf_end[vgrf],
live_intervals->end[i]);
}
}
bool
fs_live_variables::vars_interfere(int a, int b)
{
return !(end[b] <= start[a] ||
end[a] <= start[b]);
}
bool
fs_visitor::virtual_grf_interferes(int a, int b)
{
return !(virtual_grf_end[a] <= virtual_grf_start[b] ||
virtual_grf_end[b] <= virtual_grf_start[a]);
}
<commit_msg>i965/fs: Assert that var < num_vars.<commit_after>/*
* Copyright © 2012 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*
* Authors:
* Eric Anholt <eric@anholt.net>
*
*/
#include "brw_cfg.h"
#include "brw_fs_live_variables.h"
using namespace brw;
#define MAX_INSTRUCTION (1 << 30)
/** @file brw_fs_live_variables.cpp
*
* Support for calculating liveness information about virtual GRFs.
*
* This produces a live interval for each whole virtual GRF. We could
* choose to expose per-component live intervals for VGRFs of size > 1,
* but we currently do not. It is easier for the consumers of this
* information to work with whole VGRFs.
*
* However, we internally track use/def information at the per-component
* (reg_offset) level for greater accuracy. Large VGRFs may be accessed
* piecemeal over many (possibly non-adjacent) instructions. In this case,
* examining a single instruction is insufficient to decide whether a whole
* VGRF is ultimately used or defined. Tracking individual components
* allows us to easily assemble this information.
*
* See Muchnick's Advanced Compiler Design and Implementation, section
* 14.1 (p444).
*/
void
fs_live_variables::setup_one_read(bblock_t *block, fs_inst *inst,
int ip, fs_reg reg)
{
int var = var_from_vgrf[reg.reg] + reg.reg_offset;
assert(var < num_vars);
/* In most cases, a register can be written over safely by the
* same instruction that is its last use. For a single
* instruction, the sources are dereferenced before writing of the
* destination starts (naturally). This gets more complicated for
* simd16, because the instruction:
*
* add(16) g4<1>F g4<8,8,1>F g6<8,8,1>F
*
* is actually decoded in hardware as:
*
* add(8) g4<1>F g4<8,8,1>F g6<8,8,1>F
* add(8) g5<1>F g5<8,8,1>F g7<8,8,1>F
*
* Which is safe. However, if we have uniform accesses
* happening, we get into trouble:
*
* add(8) g4<1>F g4<0,1,0>F g6<8,8,1>F
* add(8) g5<1>F g4<0,1,0>F g7<8,8,1>F
*
* Now our destination for the first instruction overwrote the
* second instruction's src0, and we get garbage for those 8
* pixels. There's a similar issue for the pre-gen6
* pixel_x/pixel_y, which are registers of 16-bit values and thus
* would get stomped by the first decode as well.
*/
int end_ip = ip;
if (v->dispatch_width == 16 && (reg.smear != -1 ||
(v->pixel_x.reg == reg.reg ||
v->pixel_y.reg == reg.reg))) {
end_ip++;
}
start[var] = MIN2(start[var], ip);
end[var] = MAX2(end[var], end_ip);
/* The use[] bitset marks when the block makes use of a variable (VGRF
* channel) without having completely defined that variable within the
* block.
*/
if (!BITSET_TEST(bd[block->block_num].def, var))
BITSET_SET(bd[block->block_num].use, var);
}
void
fs_live_variables::setup_one_write(bblock_t *block, fs_inst *inst,
int ip, fs_reg reg)
{
int var = var_from_vgrf[reg.reg] + reg.reg_offset;
assert(var < num_vars);
start[var] = MIN2(start[var], ip);
end[var] = MAX2(end[var], ip);
/* The def[] bitset marks when an initialization in a block completely
* screens off previous updates of that variable (VGRF channel).
*/
if (inst->dst.file == GRF && !inst->is_partial_write()) {
if (!BITSET_TEST(bd[block->block_num].use, var))
BITSET_SET(bd[block->block_num].def, var);
}
}
/**
* Sets up the use[] and def[] bitsets.
*
* The basic-block-level live variable analysis needs to know which
* variables get used before they're completely defined, and which
* variables are completely defined before they're used.
*
* These are tracked at the per-component level, rather than whole VGRFs.
*/
void
fs_live_variables::setup_def_use()
{
int ip = 0;
for (int b = 0; b < cfg->num_blocks; b++) {
bblock_t *block = cfg->blocks[b];
assert(ip == block->start_ip);
if (b > 0)
assert(cfg->blocks[b - 1]->end_ip == ip - 1);
for (fs_inst *inst = (fs_inst *)block->start;
inst != block->end->next;
inst = (fs_inst *)inst->next) {
/* Set use[] for this instruction */
for (unsigned int i = 0; i < 3; i++) {
fs_reg reg = inst->src[i];
if (reg.file != GRF)
continue;
for (int j = 0; j < inst->regs_read(v, i); j++) {
setup_one_read(block, inst, ip, reg);
reg.reg_offset++;
}
}
/* Set def[] for this instruction */
if (inst->dst.file == GRF) {
fs_reg reg = inst->dst;
for (int j = 0; j < inst->regs_written; j++) {
setup_one_write(block, inst, ip, reg);
reg.reg_offset++;
}
}
ip++;
}
}
}
/**
* The algorithm incrementally sets bits in liveout and livein,
* propagating it through control flow. It will eventually terminate
* because it only ever adds bits, and stops when no bits are added in
* a pass.
*/
void
fs_live_variables::compute_live_variables()
{
bool cont = true;
while (cont) {
cont = false;
for (int b = 0; b < cfg->num_blocks; b++) {
/* Update livein */
for (int i = 0; i < bitset_words; i++) {
BITSET_WORD new_livein = (bd[b].use[i] |
(bd[b].liveout[i] & ~bd[b].def[i]));
if (new_livein & ~bd[b].livein[i]) {
bd[b].livein[i] |= new_livein;
cont = true;
}
}
/* Update liveout */
foreach_list(block_node, &cfg->blocks[b]->children) {
bblock_link *link = (bblock_link *)block_node;
bblock_t *block = link->block;
for (int i = 0; i < bitset_words; i++) {
BITSET_WORD new_liveout = (bd[block->block_num].livein[i] &
~bd[b].liveout[i]);
if (new_liveout) {
bd[b].liveout[i] |= new_liveout;
cont = true;
}
}
}
}
}
}
/**
* Extend the start/end ranges for each variable to account for the
* new information calculated from control flow.
*/
void
fs_live_variables::compute_start_end()
{
for (int b = 0; b < cfg->num_blocks; b++) {
for (int i = 0; i < num_vars; i++) {
if (BITSET_TEST(bd[b].livein, i)) {
start[i] = MIN2(start[i], cfg->blocks[b]->start_ip);
end[i] = MAX2(end[i], cfg->blocks[b]->start_ip);
}
if (BITSET_TEST(bd[b].liveout, i)) {
start[i] = MIN2(start[i], cfg->blocks[b]->end_ip);
end[i] = MAX2(end[i], cfg->blocks[b]->end_ip);
}
}
}
}
int
fs_live_variables::var_from_reg(fs_reg *reg)
{
return var_from_vgrf[reg->reg] + reg->reg_offset;
}
fs_live_variables::fs_live_variables(fs_visitor *v, cfg_t *cfg)
: v(v), cfg(cfg)
{
mem_ctx = ralloc_context(NULL);
num_vgrfs = v->virtual_grf_count;
num_vars = 0;
var_from_vgrf = rzalloc_array(mem_ctx, int, num_vgrfs);
for (int i = 0; i < num_vgrfs; i++) {
var_from_vgrf[i] = num_vars;
num_vars += v->virtual_grf_sizes[i];
}
vgrf_from_var = rzalloc_array(mem_ctx, int, num_vars);
for (int i = 0; i < num_vgrfs; i++) {
for (int j = 0; j < v->virtual_grf_sizes[i]; j++) {
vgrf_from_var[var_from_vgrf[i] + j] = i;
}
}
start = ralloc_array(mem_ctx, int, num_vars);
end = rzalloc_array(mem_ctx, int, num_vars);
for (int i = 0; i < num_vars; i++) {
start[i] = MAX_INSTRUCTION;
end[i] = -1;
}
bd = rzalloc_array(mem_ctx, struct block_data, cfg->num_blocks);
bitset_words = BITSET_WORDS(num_vars);
for (int i = 0; i < cfg->num_blocks; i++) {
bd[i].def = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
bd[i].use = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
bd[i].livein = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
bd[i].liveout = rzalloc_array(mem_ctx, BITSET_WORD, bitset_words);
}
setup_def_use();
compute_live_variables();
compute_start_end();
}
fs_live_variables::~fs_live_variables()
{
ralloc_free(mem_ctx);
}
void
fs_visitor::invalidate_live_intervals()
{
ralloc_free(live_intervals);
live_intervals = NULL;
}
/**
* Compute the live intervals for each virtual GRF.
*
* This uses the per-component use/def data, but combines it to produce
* information about whole VGRFs.
*/
void
fs_visitor::calculate_live_intervals()
{
if (this->live_intervals)
return;
int num_vgrfs = this->virtual_grf_count;
ralloc_free(this->virtual_grf_start);
ralloc_free(this->virtual_grf_end);
virtual_grf_start = ralloc_array(mem_ctx, int, num_vgrfs);
virtual_grf_end = ralloc_array(mem_ctx, int, num_vgrfs);
for (int i = 0; i < num_vgrfs; i++) {
virtual_grf_start[i] = MAX_INSTRUCTION;
virtual_grf_end[i] = -1;
}
cfg_t cfg(&instructions);
this->live_intervals = new(mem_ctx) fs_live_variables(this, &cfg);
/* Merge the per-component live ranges to whole VGRF live ranges. */
for (int i = 0; i < live_intervals->num_vars; i++) {
int vgrf = live_intervals->vgrf_from_var[i];
virtual_grf_start[vgrf] = MIN2(virtual_grf_start[vgrf],
live_intervals->start[i]);
virtual_grf_end[vgrf] = MAX2(virtual_grf_end[vgrf],
live_intervals->end[i]);
}
}
bool
fs_live_variables::vars_interfere(int a, int b)
{
return !(end[b] <= start[a] ||
end[a] <= start[b]);
}
bool
fs_visitor::virtual_grf_interferes(int a, int b)
{
return !(virtual_grf_end[a] <= virtual_grf_start[b] ||
virtual_grf_end[b] <= virtual_grf_start[a]);
}
<|endoftext|> |
<commit_before>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
private:
void compute_matrices_from_inputs();
void* world_species_pointer; // pointer to world species (used in collision detection).
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all textures using this shader.
void render();
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::World *world_pointer; // pointer to the world.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
void bind_to_world();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method renders all species using this texture.
void render();
// this method sets a species pointer.
void set_species_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_species_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
void switch_to_new_shader(model::Shader *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::Shader *shader_pointer; // pointer to the shader.
private:
void bind_to_shader();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `Shader::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_node_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_node_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
private:
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
bool is_world; // worlds currently do not rotate nor translate.
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
void bind_to_texture();
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
private:
void bind_to_species();
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<commit_msg>Muokattu välilyöntejä.<commit_after>#ifndef __MODEL_HPP_INCLUDED
#define __MODEL_HPP_INCLUDED
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h>
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp>
#endif
#include <iostream>
#include <queue> // std::queue
#include <string.h>
#include "globals.hpp"
#include "shader.hpp"
#include "heightmap_loader.hpp"
#include "objloader.hpp"
namespace model
{
class World
{
public:
// constructor.
World();
// destructor.
~World();
// this method renders the entire world, one shader at a time.
void render();
// this method sets a shader pointer.
void set_shader_pointer(GLuint shaderID, void* shader_pointer);
// this method gets a shader pointer.
void* get_shader_pointer(GLuint shaderID);
// this method gets a shader ID and removes it from the `free_shaderID_queue` if it was popped from the queue.
GLuint get_shaderID();
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
private:
void compute_matrices_from_inputs();
void* world_species_pointer; // pointer to world species (used in collision detection).
std::vector<void*> shader_pointer_vector;
std::queue<GLuint> free_shaderID_queue;
};
class Shader
{
public:
// constructor.
Shader(ShaderStruct shader_struct);
// destructor.
~Shader();
// this method renders all textures using this shader.
void render();
// this method sets a texture pointer.
void set_texture_pointer(GLuint textureID, void* texture_pointer);
// this method gets a texture pointer.
void* get_texture_pointer(GLuint textureID);
// this method gets a texture ID and removes it from the `free_textureID_queue` if it was popped from the queue.
GLuint get_textureID();
// this method sets pointer to this shader to NULL, sets `world_pointer` according to the input, and requests a new `shaderID` from the new world.
void switch_to_new_world(model::World *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::World *world_pointer; // pointer to the world.
GLuint programID; // shaders' programID, returned by `LoadShaders`.
private:
void bind_to_world();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint shaderID; // shader ID, returned by `model::World->get_shaderID()`.
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
std::vector<void*> texture_pointer_vector;
std::queue<GLuint> free_textureID_queue;
const char *char_vertex_shader;
const char *char_fragment_shader;
};
class Texture
{
public:
// constructor.
Texture(TextureStruct texture_struct);
// destructor.
~Texture();
// this method renders all species using this texture.
void render();
// this method sets a species pointer.
void set_species_pointer(GLuint speciesID, void* species_pointer);
// this method gets a species pointer.
void* get_species_pointer(GLuint speciesID);
// this method gets a species ID and removes it from the `free_speciesID_queue` if it was popped from the queue.
GLuint get_speciesID();
// this method sets pointer to this shader to NULL, sets `shader_pointer` according to the input, and requests a new `textureID` from the new shader.
void switch_to_new_shader(model::Shader *new_world_pointer);
// this method sets a world species pointer.
void set_world_species_pointer(void* world_species_pointer);
model::Shader *shader_pointer; // pointer to the shader.
private:
void bind_to_shader();
void* world_species_pointer; // pointer to world species (used in collision detection).
GLuint texture; // Texture, returned by `load_DDS_texture` or `load_BMP_texture`.
GLuint openGL_textureID; // texture ID, returned by `glGetUniformLocation(programID, "myTextureSampler");`.
std::vector<void*> species_pointer_vector;
std::queue<GLuint> free_speciesID_queue;
std::string texture_file_format; // type of the model file, eg. `"bmp"`.
std::string texture_filename; // filename of the model file.
GLuint textureID; // texture ID, returned by `Shader::get_textureID`.
const char *char_texture_file_format;
const char *char_texture_filename;
};
class Graph
{
public:
// constructor.
Graph();
// destructor.
~Graph();
// this method sets a node pointer.
void set_node_pointer(GLuint nodeID, void* node_pointer);
// this method gets a node pointer.
void* get_node_pointer(GLuint nodeID);
// this method gets a node ID and removes it from the `free_nodeID_queue` if it was popped from the queue.
GLuint get_nodeID();
private:
std::vector<void*> node_pointer_vector;
std::queue<GLuint> free_nodeID_queue;
};
// `Node` is not a subclass of `Graph` because if the graph splits, node may be transferred to an another graph.
// Transferring a node to a new graph naturally requires appropriate reindexing of `nodeID`s.
// The graph in which a node belongs is accessible through `void* graph_pointer` (must be cast to `model::Graph*`).
class Node
{
public:
// constructor.
Node(NodeStruct node_struct);
// destructor.
~Node();
// this method creates a bidirectional link.
// creating of bidirectional links is not possible before all nodes are created.
void create_bidirectional_link(GLuint nodeID);
// this method deletes a bidirectional link.
// deleting of links is not possible before all nodes are created.
void delete_bidirectional_link(GLuint nodeID);
// this method transfers this node to a new graph.
// links will not be changed.
// all nodes that are to be transferred must be transferred separately.
// before transfering any node to a new graph,
// all links to nodes that do not belong to the new graph of this node must be deleted with separate `delete_bidirectional_link` calls.
void transfer_to_new_graph(model::Graph *new_graph_pointer);
GLuint nodeID;
model::Graph *graph_pointer;
private:
// nodes do not keep pointers to neighbor nodes, because all pointer values are not known yet before all nodes are created.
std::vector<GLuint> neighbor_nodeIDs;
// this method creates an unidirectional link.
// in the constructor only unidirectional links can be created.
void create_unidirectional_link(GLuint nodeID);
// this method deletes an unidirectional link.
void delete_unidirectional_link(GLuint nodeID);
glm::vec3 coordinate_vector;
};
class Species
{
public:
// constructor.
Species(SpeciesStruct species_struct);
// destructor.
~Species();
// this method renders all objects of this species.
void render();
// this method sets a object pointer.
void set_object_pointer(GLuint objectID, void* object_pointer);
// this method gets a object pointer.
void* get_object_pointer(GLuint objectID);
// this method gets a object ID and removes it from the `free_objectID_queue` if it was popped from the queue.
GLuint get_objectID();
// this method sets pointer to this species to NULL, sets `texture_pointer` according to the input, and requests a new `speciesID` from the new texture.
void switch_to_new_texture(model::Texture *new_texture_pointer);
bool is_world; // worlds currently do not rotate nor translate.
std::string color_channel; // color channel in use: `"red"`, `"green"`, `"blue"`, `"mean"` or `"all"`.
std::vector<ObjectStruct> object_vector; // vector of individual objects of this species.
glm::vec3 lightPos; // light position.
// The rest fields are created in the constructor.
GLuint image_width;
GLuint image_height;
GLuint MatrixID;
GLuint ViewMatrixID;
GLuint ModelMatrixID;
GLuint vertexPosition_modelspaceID;
GLuint vertexUVID;
GLuint vertexNormal_modelspaceID;
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object.
std::vector<GLuint> indices; // the deleted vertices will be reused (though it is not required, if there's enough memory).
std::vector<glm::vec3> indexed_vertices;
std::vector<glm::vec2> indexed_UVs;
std::vector<glm::vec3> indexed_normals;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
GLuint elementbuffer;
glm::mat4 ProjectionMatrix;
glm::mat4 ViewMatrix;
private:
void bind_to_texture();
model::Texture *texture_pointer; // pointer to the texture.
std::string model_file_format; // type of the model file, eg. `"bmp"`.
std::string model_filename; // filename of the model file.
GLuint speciesID; // species ID, returned by `model::Texture->get_speciesID()`.
GLuint lightID; // light ID, returned by `glGetUniformLocation(programID, "LightPosition_worldspace");`.
const char *char_model_file_format;
const char *char_model_filename;
const char *char_color_channel;
std::vector<void*> object_pointer_vector;
std::queue<GLuint> free_objectID_queue;
};
class Object
{
public:
// constructor.
Object(ObjectStruct object_struct);
// destructor.
~Object();
// this method renders this object.
void render();
// this method sets pointer to this object to NULL, sets `species_pointer` according to the input, and requests a new `objectID` from the new species.
void switch_to_new_species(model::Species *new_species_pointer);
private:
void bind_to_species();
model::Species *species_pointer; // pointer to the species.
GLuint objectID; // object ID, returned by `model::Species->get_objectID()`.
bool has_entered;
glm::vec3 coordinate_vector; // rotate vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
// The rest fields are created in the constructor.
glm::mat4 model_matrix; // model matrix.
std::vector<glm::vec3> vertices; // vertices of the object.
std::vector<glm::vec2> UVs; // UVs of the object.
std::vector<glm::vec3> normals; // normals of the object. not used at the moment.
glm::mat4 MVP_matrix; // model view projection matrix.
};
}
#endif
<|endoftext|> |
<commit_before>#pragma once
#include <port.hpp>
template <class USI_t, class CSn>
class CC1101 {
public:
typedef USI_t USI;
enum ConfReg {
IOCFG2 = 0x00,
IOCFG1 = 0x01,
IOCFG0 = 0x02,
FIFOTHR = 0x03,
SYNC1 = 0x04,
SYNC0 = 0x05,
PKTLEN = 0x06,
PKTCTRL1 = 0x07,
PKTCTRL0 = 0x08,
ADDR = 0x09,
CHANNR = 0x0A,
FSCTRL1 = 0x0B,
FSCTRL0 = 0x0C,
FREQ2 = 0x0D,
FREQ1 = 0x0E,
FREQ0 = 0x0F,
MDMCFG4 = 0x10,
MDMCFG3 = 0x11,
MDMCFG2 = 0x12,
MDMCFG1 = 0x13,
MDMCFG0 = 0x14,
DEVIATN = 0x15,
MCSM2 = 0x16,
MCSM1 = 0x17,
MCSM0 = 0x18,
FOCCFG = 0x19,
BSCFG = 0x1A,
AGCCTRL2 = 0x1B,
AGCCTRL1 = 0x1C,
AGCCTRL0 = 0x1D,
WOREVT1 = 0x1E,
WOREVT0 = 0x1F,
WORCTRL = 0x20,
FREND1 = 0x21,
FREND0 = 0x22,
FSCAL3 = 0x23,
FSCAL2 = 0x24,
FSCAL1 = 0x25,
FSCAL0 = 0x26,
RCCTRL1 = 0x27,
RCCTRL0 = 0x28,
FSTEST = 0x29,
PTEST = 0x2A,
AGCTEST = 0x2B,
TEST2 = 0x2C,
TEST1 = 0x2D,
TEST0 = 0x2E,
PATABLE = 0x3E,
};
enum CommandStrobe {
SRES = 0x30,
SFSTXON = 0x31,
SXOFF = 0x32,
SCAL = 0x33,
SRX = 0x34,
STX = 0x35,
SIDLE = 0x36,
SWOR = 0x38,
SPWD = 0x39,
SFRX = 0x3A,
SFTX = 0x3B,
SWORRST = 0x3C,
SNOP = 0x3D,
};
enum StatusReg {
PARTNUM = 0x30,
VERSION = 0x31,
FREQEST = 0x32,
LQI = 0x33,
RSSI = 0x34,
MARCSTATE = 0x35,
WORTIME1 = 0x36,
WORTIME0 = 0x37,
PKTSTATUS = 0x38,
VCO_VC_DAC = 0x39,
TXBYTES = 0x3A,
RXBYTES = 0x3B,
RCCTRL1_STATUS = 0x3C,
RCCTRL0_STATUS = 0x3D,
};
static void setup() {
USI::setup();
CSn::mode(OUTPUT);
CSn::set();
}
template <ConfReg Reg>
static void set(unsigned char value) {
USI::xmit(Reg);
USI::xmit(value);
}
template <ConfReg Reg>
static unsigned char get() {
USI::xmit(Reg | 0x80);
return USI::xmit(0);
}
template <CommandStrobe Cmd>
static unsigned char rcmd() {
return USI::xmit(Cmd | 0x80);
}
template <CommandStrobe Cmd>
static unsigned char wcmd() {
return USI::xmit(Cmd);
}
template <StatusReg Reg>
static unsigned char status() {
USI::xmit(Reg | 0xc0);
return USI::xmit(0);
}
static bool select()
{
CSn::clear();
return USI::DI::loop_until_clear(200);
}
static void release()
{
CSn::set();
}
static void write_txfifo(unsigned char* values, int len) {
USI::xmit(0x7f);
while(len-- > 0) {
USI::xmit(*values++);
}
release();
}
static void read_rxfifo(unsigned char* values, int len) {
USI::xmit(0xff);
while(len-- > 0) {
*values++ = USI::xmit(0);
}
release();
}
static void reset() {
// reset
select();
wcmd<SRES>();
release();
select();
// disable GDOx pins
set<IOCFG2>(0x2f);
set<IOCFG1>(0x2f);
set<IOCFG0>(0x2f);
// max packet length
set<PKTLEN>(32);
// packet automation
set<PKTCTRL1>(0x0c);
set<PKTCTRL0>(0x44);
// frequency configuration
set<FREQ2>(0x10);
set<FREQ1>(0xa7);
set<FREQ0>(0x63);
// modem configuration
set<MDMCFG2>(0x12);
set<MDMCFG1>(0xa2);
// main radio control state machine configuration
set<MCSM1>(0x3c);
set<MCSM0>(0x34);
// frequency synthesizer calibration
set<FSCAL3>(0xea);
set<FSCAL2>(0x2a);
set<FSCAL1>(0x00);
set<FSCAL0>(0x1f);
// Various test settings
set<TEST2>(0x81);
set<TEST1>(0x35);
set<TEST0>(0x09);
wcmd<SCAL>();
release();
}
};
<commit_msg>Power-On-Timeout raised as per spec<commit_after>#pragma once
#include <port.hpp>
template <class USI_t, class CSn>
class CC1101 {
public:
typedef USI_t USI;
enum ConfReg {
IOCFG2 = 0x00,
IOCFG1 = 0x01,
IOCFG0 = 0x02,
FIFOTHR = 0x03,
SYNC1 = 0x04,
SYNC0 = 0x05,
PKTLEN = 0x06,
PKTCTRL1 = 0x07,
PKTCTRL0 = 0x08,
ADDR = 0x09,
CHANNR = 0x0A,
FSCTRL1 = 0x0B,
FSCTRL0 = 0x0C,
FREQ2 = 0x0D,
FREQ1 = 0x0E,
FREQ0 = 0x0F,
MDMCFG4 = 0x10,
MDMCFG3 = 0x11,
MDMCFG2 = 0x12,
MDMCFG1 = 0x13,
MDMCFG0 = 0x14,
DEVIATN = 0x15,
MCSM2 = 0x16,
MCSM1 = 0x17,
MCSM0 = 0x18,
FOCCFG = 0x19,
BSCFG = 0x1A,
AGCCTRL2 = 0x1B,
AGCCTRL1 = 0x1C,
AGCCTRL0 = 0x1D,
WOREVT1 = 0x1E,
WOREVT0 = 0x1F,
WORCTRL = 0x20,
FREND1 = 0x21,
FREND0 = 0x22,
FSCAL3 = 0x23,
FSCAL2 = 0x24,
FSCAL1 = 0x25,
FSCAL0 = 0x26,
RCCTRL1 = 0x27,
RCCTRL0 = 0x28,
FSTEST = 0x29,
PTEST = 0x2A,
AGCTEST = 0x2B,
TEST2 = 0x2C,
TEST1 = 0x2D,
TEST0 = 0x2E,
PATABLE = 0x3E,
};
enum CommandStrobe {
SRES = 0x30,
SFSTXON = 0x31,
SXOFF = 0x32,
SCAL = 0x33,
SRX = 0x34,
STX = 0x35,
SIDLE = 0x36,
SWOR = 0x38,
SPWD = 0x39,
SFRX = 0x3A,
SFTX = 0x3B,
SWORRST = 0x3C,
SNOP = 0x3D,
};
enum StatusReg {
PARTNUM = 0x30,
VERSION = 0x31,
FREQEST = 0x32,
LQI = 0x33,
RSSI = 0x34,
MARCSTATE = 0x35,
WORTIME1 = 0x36,
WORTIME0 = 0x37,
PKTSTATUS = 0x38,
VCO_VC_DAC = 0x39,
TXBYTES = 0x3A,
RXBYTES = 0x3B,
RCCTRL1_STATUS = 0x3C,
RCCTRL0_STATUS = 0x3D,
};
static void setup() {
USI::setup();
CSn::mode(OUTPUT);
CSn::set();
}
template <ConfReg Reg>
static void set(unsigned char value) {
USI::xmit(Reg);
USI::xmit(value);
}
template <ConfReg Reg>
static unsigned char get() {
USI::xmit(Reg | 0x80);
return USI::xmit(0);
}
template <CommandStrobe Cmd>
static unsigned char rcmd() {
return USI::xmit(Cmd | 0x80);
}
template <CommandStrobe Cmd>
static unsigned char wcmd() {
return USI::xmit(Cmd);
}
template <StatusReg Reg>
static unsigned char status() {
USI::xmit(Reg | 0xc0);
return USI::xmit(0);
}
static bool select()
{
CSn::clear();
return USI::DI::loop_until_clear(400);
}
static void release()
{
CSn::set();
}
static void write_txfifo(unsigned char* values, int len) {
USI::xmit(0x7f);
while(len-- > 0) {
USI::xmit(*values++);
}
release();
}
static void read_rxfifo(unsigned char* values, int len) {
USI::xmit(0xff);
while(len-- > 0) {
*values++ = USI::xmit(0);
}
release();
}
static void reset() {
// reset
select();
wcmd<SRES>();
release();
select();
// disable GDOx pins
set<IOCFG2>(0x2f);
set<IOCFG1>(0x2f);
set<IOCFG0>(0x2f);
// max packet length
set<PKTLEN>(32);
// packet automation
set<PKTCTRL1>(0x0c);
set<PKTCTRL0>(0x44);
// frequency configuration
set<FREQ2>(0x10);
set<FREQ1>(0xa7);
set<FREQ0>(0x63);
// modem configuration
set<MDMCFG2>(0x12);
set<MDMCFG1>(0xa2);
// main radio control state machine configuration
set<MCSM1>(0x3c);
set<MCSM0>(0x38);
// frequency synthesizer calibration
set<FSCAL3>(0xea);
set<FSCAL2>(0x2a);
set<FSCAL1>(0x00);
set<FSCAL0>(0x1f);
// Various test settings
set<TEST2>(0x81);
set<TEST1>(0x35);
set<TEST0>(0x09);
wcmd<SCAL>();
release();
}
};
<|endoftext|> |
<commit_before><commit_msg>Typo: constarined->constrained<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRungeKutta4.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkRungeKutta4.h"
#include "vtkObjectFactory.h"
vtkRungeKutta4::vtkRungeKutta4()
{
for(int i=0; i<3; i++)
{
this->NextDerivs[i] = 0;
}
}
vtkRungeKutta4::~vtkRungeKutta4()
{
for(int i=0; i<3; i++)
{
delete[] this->NextDerivs[i];
this->NextDerivs[i] = 0;
}
}
vtkRungeKutta4* vtkRungeKutta4::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkRungeKutta4");
if(ret)
{
return (vtkRungeKutta4*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkRungeKutta4;
}
void vtkRungeKutta4::Initialize()
{
this->vtkInitialValueProblemSolver::Initialize();
if (!this->Initialized)
{
return;
}
// Allocate memory for temporary derivatives array
for(int i=0; i<3; i++)
{
this->NextDerivs[i] =
new float[this->FunctionSet->GetNumberOfFunctions()];
}
}
// For a detailed description of Runge-Kutta methods,
// see, for example, Numerical Recipes in (C/Fortran/Pascal) by
// Press et al. (Cambridge University Press) or
// Applied Numerical Analysis by C. F. Gerald and P. O. Wheatley
// (Addison Wesley)
float vtkRungeKutta4::ComputeNextStep(float* xprev, float* dxprev,
float* xnext, float t, float delT)
{
int i, numDerivs, numVals;
if (!this->FunctionSet)
{
vtkErrorMacro("No derivative functions are provided!");
return -1;
}
if (!this->Initialized)
{
vtkErrorMacro("Integrator not initialized!");
return -1;
}
numDerivs = this->FunctionSet->GetNumberOfFunctions();
numVals = numDerivs + 1;
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i];
}
this->Vals[numVals-1] = t;
// 4th order
// 1
if (dxprev)
{
for(i=0; i<numDerivs; i++)
{
this->Derivs[i] = dxprev[i];
}
}
else if ( !this->FunctionSet->FunctionValues(this->Vals, this->Derivs) )
{
return -1;
}
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i] + delT/2.0*this->Derivs[i];
}
this->Vals[numVals-1] = t + delT/2.0;
// 2
if (!this->FunctionSet->FunctionValues(this->Vals, this->NextDerivs[0]))
{
return -1;
}
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i] + delT/2.0*this->NextDerivs[0][i];
}
this->Vals[numVals-1] = t + delT/2.0;
// 3
if (!this->FunctionSet->FunctionValues(this->Vals, this->NextDerivs[1]))
{
return -1;
}
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i] + delT*this->NextDerivs[0][i];
}
this->Vals[numVals-1] = t + delT;
// 4
if (!this->FunctionSet->FunctionValues(this->Vals, this->NextDerivs[2]))
{
return -1;
}
for(i=0; i<numDerivs; i++)
{
xnext[i] = xprev[i] + delT*(this->Derivs[i]/6.0 +
this->NextDerivs[0][i]/3.0 +
this->NextDerivs[1][i]/3.0 +
this->NextDerivs[2][i]/6.0);
}
// TO DO: Should return estimated error
return 0;
}
void vtkRungeKutta4::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkInitialValueProblemSolver::PrintSelf(os,indent);
os << indent << "Runge-Kutta 4 function derivatives: "
<< this->NextDerivs[0] << " " << this->NextDerivs[1] << " "
<< this->NextDerivs[2] << endl;
}
<commit_msg>ERR: Mistake in calculating k4<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRungeKutta4.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "vtkRungeKutta4.h"
#include "vtkObjectFactory.h"
vtkRungeKutta4::vtkRungeKutta4()
{
for(int i=0; i<3; i++)
{
this->NextDerivs[i] = 0;
}
}
vtkRungeKutta4::~vtkRungeKutta4()
{
for(int i=0; i<3; i++)
{
delete[] this->NextDerivs[i];
this->NextDerivs[i] = 0;
}
}
vtkRungeKutta4* vtkRungeKutta4::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkRungeKutta4");
if(ret)
{
return (vtkRungeKutta4*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkRungeKutta4;
}
void vtkRungeKutta4::Initialize()
{
this->vtkInitialValueProblemSolver::Initialize();
if (!this->Initialized)
{
return;
}
// Allocate memory for temporary derivatives array
for(int i=0; i<3; i++)
{
this->NextDerivs[i] =
new float[this->FunctionSet->GetNumberOfFunctions()];
}
}
// For a detailed description of Runge-Kutta methods,
// see, for example, Numerical Recipes in (C/Fortran/Pascal) by
// Press et al. (Cambridge University Press) or
// Applied Numerical Analysis by C. F. Gerald and P. O. Wheatley
// (Addison Wesley)
float vtkRungeKutta4::ComputeNextStep(float* xprev, float* dxprev,
float* xnext, float t, float delT)
{
int i, numDerivs, numVals;
if (!this->FunctionSet)
{
vtkErrorMacro("No derivative functions are provided!");
return -1;
}
if (!this->Initialized)
{
vtkErrorMacro("Integrator not initialized!");
return -1;
}
numDerivs = this->FunctionSet->GetNumberOfFunctions();
numVals = numDerivs + 1;
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i];
}
this->Vals[numVals-1] = t;
// 4th order
// 1
if (dxprev)
{
for(i=0; i<numDerivs; i++)
{
this->Derivs[i] = dxprev[i];
}
}
else if ( !this->FunctionSet->FunctionValues(this->Vals, this->Derivs) )
{
return -1;
}
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i] + delT/2.0*this->Derivs[i];
}
this->Vals[numVals-1] = t + delT/2.0;
// 2
if (!this->FunctionSet->FunctionValues(this->Vals, this->NextDerivs[0]))
{
return -1;
}
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i] + delT/2.0*this->NextDerivs[0][i];
}
this->Vals[numVals-1] = t + delT/2.0;
// 3
if (!this->FunctionSet->FunctionValues(this->Vals, this->NextDerivs[1]))
{
return -1;
}
for(i=0; i<numVals-1; i++)
{
this->Vals[i] = xprev[i] + delT*this->NextDerivs[1][i];
}
this->Vals[numVals-1] = t + delT;
// 4
if (!this->FunctionSet->FunctionValues(this->Vals, this->NextDerivs[2]))
{
return -1;
}
for(i=0; i<numDerivs; i++)
{
xnext[i] = xprev[i] + delT*(this->Derivs[i]/6.0 +
this->NextDerivs[0][i]/3.0 +
this->NextDerivs[1][i]/3.0 +
this->NextDerivs[2][i]/6.0);
}
// TO DO: Should return estimated error
return 0;
}
void vtkRungeKutta4::PrintSelf(ostream& os, vtkIndent indent)
{
this->vtkInitialValueProblemSolver::PrintSelf(os,indent);
os << indent << "Runge-Kutta 4 function derivatives: "
<< this->NextDerivs[0] << " " << this->NextDerivs[1] << " "
<< this->NextDerivs[2] << endl;
}
<|endoftext|> |
<commit_before>#include "HEALTH.H"
#include "DELTAPAK.H"
#include "DRAW.H"
#include "DRAWPHAS.H"
#include "GAMEFLOW.H"
#include "LARA.H"
#include "SPOTCAM.H"
#include <stdio.h>
#include "SPECIFIC.H"
#include "OBJECTS.H"
#include "NEWINV2.H"
int health_bar_timer = 0;
char PoisonFlag = 0;
struct DISPLAYPU pickups[8];
short PickupX = 0;
short PickupY = 0;
short PickupVel = 0;
short CurrentPickup = 0;
void AddDisplayPickup(short object_number)//3B6F4, ? (F)
{
struct DISPLAYPU* pu = &pickups[0];
long lp;
if (gfCurrentLevel == LVL5_SUBMARINE && object_number == PUZZLE_ITEM1 ||
gfCurrentLevel == LVL5_OLD_MILL && object_number == PUZZLE_ITEM3)
{
object_number = CROWBAR_ITEM;
}
for(lp = 0; lp < 8; lp++, pu++)
{
if (pu->life < 0)
{
pu->life = 45;
pu->object_number = object_number;
break;
}
}
DEL_picked_up_object(object_number);
}
void DrawPickups(int timed)// (F)
{
struct DISPLAYPU* pu = &pickups[CurrentPickup];
long lp;
if (pu->life > 0)
{
if (PickupX > 0)
{
PickupX += (-PickupX >> 3);
}
else
{
pu->life--;
}
}
else if (pu->life == 0)
{
if (PickupX < 128)
{
if (PickupVel < 16)
PickupX += ++PickupVel;
}
else
{
pu->life = -1;
PickupVel = 0;
}
}
else
{
for (lp = 0; lp < 8; lp++)
{
if (pickups[(CurrentPickup + lp) % 8].life > 0)
break;
}
if (lp == 8)
{
CurrentPickup = 0;
return;
}
CurrentPickup = (CurrentPickup + lp) % 8;
}
S_DrawPickup(pu->object_number);
}
void InitialisePickUpDisplay()//3B580, 3B9DC (F)
{
int i;
for (i = 7; i > -1; i--)
{
pickups[i].life = -1;
}
PickupY = 128;
PickupX = 128;
PickupVel = 0;
CurrentPickup = 0;
}
void DrawAirBar(int flash_state)
{
S_Warn("[DrawAirBar] - Unimplemented!\n");
}
void DrawHealthBar(int flash_state)
{
S_Warn("[DrawHealthBar] - Unimplemented!\n");
}
void DrawGameInfo(int timed)//3AD68(<), 3B268(!)
{
#if PC_VERSION
if (GLOBAL_playing_cutseq == 0 &&
!bDisableLaraControl &&
gfGameMode != 1)
{
int flash_state = FlashIt();
DrawHealthBar(flash_state);
DrawAirBar(flash_state);
DrawPickups(timed);
/*if (DashTimer < 120)
s_drawdas*/
}
#else
// line 2, offset 0x3ad68
int flash_state; // $s0
//{ // line 17, offset 0x3adac
char sbuf[80]; // stack offset -192
//} // line 19, offset 0x3adac
{ // line 53, offset 0x3af50
char buf[80]; // stack offset -112
int seconds; // $s3
} // line 77, offset 0x3b0a0
if (GLOBAL_playing_cutseq != 0 || bDisableLaraControl != 0)
{
return;
}
sprintf(sbuf, "Room:%d X:%d Y:%d Z:%d", lara_item->room_number, (lara_item->pos.x_pos - room[lara_item->room_number].x) / SECTOR(1), (lara_item->pos.y_pos - room[lara_item->room_number].minfloor) / CLICK, (lara_item->pos.z_pos - room[lara_item->room_number].z) / SECTOR(1));
PrintString(256, 24, 0, sbuf, 0);
//^Not verified for retail/internal split
if (gfGameMode == 1)
{
//loc_3B0A0
return;
}
flash_state = FlashIt();
DrawHealthBar(flash_state);
DrawAirBar(flash_state);
DrawPickups(timed);//Arg does not seem right imo
if (DashTimer < 120)
{
//TODO
}//loc_3AF14
return;
#endif
} // line 79, offset 0x3b0a0
int FlashIt()//3AD2C, 3B22C
{
static int flash_state;
static int flash_count;
if (--flash_count != 0)
{
flash_count = 5;
flash_state ^= 1;
}
return flash_state;
}
<commit_msg>Add AddDisplayPickup()<commit_after>#include "HEALTH.H"
#include "DELTAPAK.H"
#include "DRAW.H"
#include "DRAWPHAS.H"
#include "GAMEFLOW.H"
#include "LARA.H"
#include "NEWINV2.H"
#include "OBJECTS.H"
#include "SPECIFIC.H"
#include "SPOTCAM.H"
#include <stdio.h>
int health_bar_timer = 0;
char PoisonFlag = 0;
struct DISPLAYPU pickups[8];
short PickupX = 0;
short PickupY = 0;
short PickupVel = 0;
short CurrentPickup = 0;
void AddDisplayPickup(short object_number)//3B6F4, ? (F)
{
struct DISPLAYPU* pu = &pickups[0];
long lp;
if (gfCurrentLevel == LVL5_SUBMARINE && object_number == PUZZLE_ITEM1 ||
gfCurrentLevel == LVL5_OLD_MILL && object_number == PUZZLE_ITEM3)
{
object_number = CROWBAR_ITEM;
}
for(lp = 0; lp < 8; lp++, pu++)
{
if (pu->life < 0)
{
pu->life = 45;
pu->object_number = object_number;
break;
}
}
DEL_picked_up_object(object_number);
}
void DrawPickups(int timed)// (F)
{
struct DISPLAYPU* pu = &pickups[CurrentPickup];
long lp;
if (pu->life > 0)
{
if (PickupX > 0)
{
PickupX += (-PickupX >> 3);
}
else
{
pu->life--;
}
}
else if (pu->life == 0)
{
if (PickupX < 128)
{
if (PickupVel < 16)
PickupX += ++PickupVel;
}
else
{
pu->life = -1;
PickupVel = 0;
}
}
else
{
for (lp = 0; lp < 8; lp++)
{
if (pickups[(CurrentPickup + lp) % 8].life > 0)
break;
}
if (lp == 8)
{
CurrentPickup = 0;
return;
}
CurrentPickup = (CurrentPickup + lp) % 8;
}
S_DrawPickup(pu->object_number);
}
void InitialisePickUpDisplay()//3B580, 3B9DC (F)
{
int i;
for (i = 7; i > -1; i--)
{
pickups[i].life = -1;
}
PickupY = 128;
PickupX = 128;
PickupVel = 0;
CurrentPickup = 0;
}
void DrawAirBar(int flash_state)
{
S_Warn("[DrawAirBar] - Unimplemented!\n");
}
void DrawHealthBar(int flash_state)
{
S_Warn("[DrawHealthBar] - Unimplemented!\n");
}
void DrawGameInfo(int timed)//3AD68(<), 3B268(!)
{
#if PC_VERSION
if (GLOBAL_playing_cutseq == 0 &&
!bDisableLaraControl &&
gfGameMode != 1)
{
int flash_state = FlashIt();
DrawHealthBar(flash_state);
DrawAirBar(flash_state);
DrawPickups(timed);
/*if (DashTimer < 120)
s_drawdas*/
}
#else
// line 2, offset 0x3ad68
int flash_state; // $s0
//{ // line 17, offset 0x3adac
char sbuf[80]; // stack offset -192
//} // line 19, offset 0x3adac
{ // line 53, offset 0x3af50
char buf[80]; // stack offset -112
int seconds; // $s3
} // line 77, offset 0x3b0a0
if (GLOBAL_playing_cutseq != 0 || bDisableLaraControl != 0)
{
return;
}
sprintf(sbuf, "Room:%d X:%d Y:%d Z:%d", lara_item->room_number, (lara_item->pos.x_pos - room[lara_item->room_number].x) / SECTOR(1), (lara_item->pos.y_pos - room[lara_item->room_number].minfloor) / CLICK, (lara_item->pos.z_pos - room[lara_item->room_number].z) / SECTOR(1));
PrintString(256, 24, 0, sbuf, 0);
//^Not verified for retail/internal split
if (gfGameMode == 1)
{
//loc_3B0A0
return;
}
flash_state = FlashIt();
DrawHealthBar(flash_state);
DrawAirBar(flash_state);
DrawPickups(timed);//Arg does not seem right imo
if (DashTimer < 120)
{
//TODO
}//loc_3AF14
return;
#endif
} // line 79, offset 0x3b0a0
int FlashIt()//3AD2C, 3B22C
{
static int flash_state;
static int flash_count;
if (--flash_count != 0)
{
flash_count = 5;
flash_state ^= 1;
}
return flash_state;
}
void AddDisplayPickup(short object_number)//3B6F4(<), 3BB50(<) (F)
{
struct DISPLAYPU* pu = &pickups[0];
long lp = 0;
if (gfCurrentLevel == LVL5_SUBMARINE && object_number == PUZZLE_ITEM1)
{
object_number = CROWBAR_ITEM;
}
if (gfCurrentLevel == LVL5_OLD_MILL && object_number == PUZZLE_ITEM3)
{
object_number = CROWBAR_ITEM;
}
if (pu->life < 0)
{
pu->life = 45;
pu->object_number = object_number;
}
else
{
//loc_3B764
lp++;
//loc_3B768
do
{
if (lp > 7)
{
DEL_picked_up_object(object_number);
return;
}
} while (++pu->life >= 0, lp++);
pu->life = 45;
pu->object_number = object_number;
}
//loc_3B790
DEL_picked_up_object(object_number);
return;
}<|endoftext|> |
<commit_before>#include "SPHERE.H"
#include "LARA.H"
#include "SPECIFIC.H"
#if PSX_VERSION || PSXPC_VERSION
#include "SPHERES.H"
#endif
char GotLaraSpheres;
int NumLaraSpheres;
struct SPHERE LaraSpheres[15];
struct SPHERE Slist[34];
int TestCollision(struct ITEM_INFO* item, struct ITEM_INFO* laraitem)//55C3C(<), 560DC(<) (F)
{
int num1;
int num2;
int x1;
int y1;
int z1;
int r1;
int x;
int y;
int z;
int r;
int i;
int j;
unsigned long flags;
struct SPHERE* ptr1;
struct SPHERE* ptr2;
num1 = GetSpheres(item, &Slist[0], 1);
flags = 0;
if (laraitem != item)
{
GotLaraSpheres = 0;
}
//loc_55C8C
if (!GotLaraSpheres)
{
NumLaraSpheres = num2 = GetSpheres(laraitem, &LaraSpheres[0], 1);
if (laraitem == lara_item)
{
GotLaraSpheres = 1;
}
}
else
{
//loc_55CD0
num2 = NumLaraSpheres;
}
laraitem->touch_bits = 0;
//loc_55CD8
ptr1 = &Slist[0];
for (i = 0; i < num1; i++, ptr1++)
{
r1 = ptr1->r;
if (r1 > 0)
{
ptr2 = &LaraSpheres[0];
x1 = ptr1->x;
y1 = ptr1->y;
z1 = ptr1->z;
//loc_55D1C
for (j = 0; j < num2; j++, ptr2++)
{
r += r1;
if (ptr2->r > 0)
{
x = (ptr2->x - x1) * ptr2->x;
y = (ptr2->y - y1) * ptr2->y;
z = (ptr2->z - z1) * ptr2->z;
r *= r;
if (x + y + z < r)
{
flags |= (1 << i);
laraitem->touch_bits |= (1 << j);
}//loc_55D14
}//loc_55D14
}
}
}
//loc_55DBC
item->touch_bits = flags;
return flags;
}<commit_msg>fix include<commit_after>#include "SPHERE.H"
#include "LARA.H"
#include "SPECIFIC.H"
#include "SPHERES.H"
char GotLaraSpheres;
int NumLaraSpheres;
struct SPHERE LaraSpheres[15];
struct SPHERE Slist[34];
int TestCollision(struct ITEM_INFO* item, struct ITEM_INFO* laraitem)//55C3C(<), 560DC(<) (F)
{
int num1;
int num2;
int x1;
int y1;
int z1;
int r1;
int x;
int y;
int z;
int r;
int i;
int j;
unsigned long flags;
struct SPHERE* ptr1;
struct SPHERE* ptr2;
num1 = GetSpheres(item, &Slist[0], 1);
flags = 0;
if (laraitem != item)
{
GotLaraSpheres = 0;
}
//loc_55C8C
if (!GotLaraSpheres)
{
NumLaraSpheres = num2 = GetSpheres(laraitem, &LaraSpheres[0], 1);
if (laraitem == lara_item)
{
GotLaraSpheres = 1;
}
}
else
{
//loc_55CD0
num2 = NumLaraSpheres;
}
laraitem->touch_bits = 0;
//loc_55CD8
ptr1 = &Slist[0];
for (i = 0; i < num1; i++, ptr1++)
{
r1 = ptr1->r;
if (r1 > 0)
{
ptr2 = &LaraSpheres[0];
x1 = ptr1->x;
y1 = ptr1->y;
z1 = ptr1->z;
//loc_55D1C
for (j = 0; j < num2; j++, ptr2++)
{
r += r1;
if (ptr2->r > 0)
{
x = (ptr2->x - x1) * ptr2->x;
y = (ptr2->y - y1) * ptr2->y;
z = (ptr2->z - z1) * ptr2->z;
r *= r;
if (x + y + z < r)
{
flags |= (1 << i);
laraitem->touch_bits |= (1 << j);
}//loc_55D14
}//loc_55D14
}
}
}
//loc_55DBC
item->touch_bits = flags;
return flags;
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 SlimDX Group
*
* 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 <d3d10.h>
#include "../Utilities.h"
#include "BlendStateDescription.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;
namespace SlimDX
{
namespace Direct3D10
{
BlendStateDescription::BlendStateDescription( const D3D10_BLEND_DESC& native )
{
m_AlphaToCoverageEnable = native.AlphaToCoverageEnable ? true : false;
m_SrcBlend = static_cast<BlendOption>( native.SrcBlend );
m_DestBlend = static_cast<BlendOption>( native.DestBlend );
m_BlendOp = static_cast<Direct3D10::BlendOperation>( native.BlendOp );
m_SrcBlendAlpha = static_cast<BlendOption>( native.SrcBlendAlpha );
m_DestBlendAlpha = static_cast<BlendOption>( native.DestBlendAlpha );
m_BlendOpAlpha = static_cast<Direct3D10::BlendOperation>( native.BlendOpAlpha );
ConstructLazyProperties();
}
D3D10_BLEND_DESC BlendStateDescription::CreateNativeVersion()
{
D3D10_BLEND_DESC native;
native.AlphaToCoverageEnable = m_AlphaToCoverageEnable;
native.SrcBlend = static_cast<D3D10_BLEND>( m_SrcBlend );
native.DestBlend = static_cast<D3D10_BLEND>( m_DestBlend );
native.BlendOp = static_cast<D3D10_BLEND_OP>( m_BlendOp );
native.SrcBlendAlpha = static_cast<D3D10_BLEND>( m_SrcBlendAlpha );
native.DestBlendAlpha = static_cast<D3D10_BLEND>( m_DestBlendAlpha );
native.BlendOpAlpha = static_cast<D3D10_BLEND_OP>( m_BlendOpAlpha );
ConstructLazyProperties();
for(int index = 0; index < 8; ++index)
{
native.BlendEnable[ index ] = m_BlendEnable[ index ];
native.RenderTargetWriteMask[ index ] = static_cast<UINT8>( m_RenderTargetWriteMask[ index ] );
}
return native;
}
bool BlendStateDescription::IsAlphaToCoverageEnabled::get()
{
return m_AlphaToCoverageEnable;
}
void BlendStateDescription::IsAlphaToCoverageEnabled::set( bool value )
{
m_AlphaToCoverageEnable = value;
}
BlendOption BlendStateDescription::SourceBlend::get()
{
return m_SrcBlend;
}
void BlendStateDescription::SourceBlend::set( BlendOption value )
{
m_SrcBlend = value;
}
BlendOption BlendStateDescription::DestinationBlend::get()
{
return m_DestBlend;
}
void BlendStateDescription::DestinationBlend::set( BlendOption value )
{
m_DestBlend = value;
}
Direct3D10::BlendOperation BlendStateDescription::BlendOperation::get()
{
return m_BlendOp;
}
void BlendStateDescription::BlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOp = value;
}
BlendOption BlendStateDescription::SourceAlphaBlend::get()
{
return m_SrcBlendAlpha;
}
void BlendStateDescription::SourceAlphaBlend::set( BlendOption value )
{
m_SrcBlendAlpha = value;
}
BlendOption BlendStateDescription::DestinationAlphaBlend::get()
{
return m_DestBlendAlpha;
}
void BlendStateDescription::DestinationAlphaBlend::set( BlendOption value )
{
m_DestBlendAlpha = value;
}
Direct3D10::BlendOperation BlendStateDescription::AlphaBlendOperation::get()
{
return m_BlendOpAlpha;
}
void BlendStateDescription::AlphaBlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOpAlpha = value;
}
bool BlendStateDescription::GetBlendEnable( UInt32 index )
{
ConstructLazyProperties();
return m_BlendEnable[ index ];
}
void BlendStateDescription::SetBlendEnable( UInt32 index, bool value )
{
ConstructLazyProperties();
m_BlendEnable[ index ] = value;
}
ColorWriteMaskFlags BlendStateDescription::GetWriteMask( UInt32 index )
{
ConstructLazyProperties();
return m_RenderTargetWriteMask[ index ];
}
void BlendStateDescription::SetWriteMask( UInt32 index, ColorWriteMaskFlags value )
{
ConstructLazyProperties();
m_RenderTargetWriteMask[ index ] = value;
}
void BlendStateDescription::ConstructLazyProperties()
{
if( m_BlendEnable == nullptr )
{
m_BlendEnable = gcnew array<bool>(8);
m_RenderTargetWriteMask = gcnew array<ColorWriteMaskFlags>(8);
for(int index = 0; index < 8; ++index)
{
m_BlendEnable[ index ] = false;
m_RenderTargetWriteMask[ index ] = ColorWriteMaskFlags::All;
}
}
}
bool BlendStateDescription::operator == ( BlendStateDescription left, BlendStateDescription right )
{
return BlendStateDescription::Equals( left, right );
}
bool BlendStateDescription::operator != ( BlendStateDescription left, BlendStateDescription right )
{
return !BlendStateDescription::Equals( left, right );
}
int BlendStateDescription::GetHashCode()
{
return (
m_AlphaToCoverageEnable.GetHashCode() +
m_BlendEnable->GetHashCode() +
m_SrcBlend.GetHashCode() +
m_DestBlend.GetHashCode() +
m_BlendOp.GetHashCode() +
m_SrcBlendAlpha.GetHashCode() +
m_DestBlendAlpha.GetHashCode() +
m_BlendOpAlpha.GetHashCode() +
m_RenderTargetWriteMask->GetHashCode()
);
}
bool BlendStateDescription::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<BlendStateDescription>( value ) );
}
bool BlendStateDescription::Equals( BlendStateDescription value )
{
return (
m_AlphaToCoverageEnable == value.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( m_BlendEnable, value.m_BlendEnable ) &&
m_SrcBlend == value.m_SrcBlend &&
m_DestBlend == value.m_DestBlend &&
m_BlendOp == value.m_BlendOp &&
m_SrcBlendAlpha == value.m_SrcBlendAlpha &&
m_DestBlendAlpha == value.m_DestBlendAlpha &&
m_BlendOpAlpha == value.m_BlendOpAlpha &&
Utilities::CheckElementEquality( m_RenderTargetWriteMask, value.m_RenderTargetWriteMask )
);
}
bool BlendStateDescription::Equals( BlendStateDescription% value1, BlendStateDescription% value2 )
{
return (
value1.m_AlphaToCoverageEnable == value2.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( value1.m_BlendEnable, value2.m_BlendEnable ) &&
value1.m_SrcBlend == value2.m_SrcBlend &&
value1.m_DestBlend == value2.m_DestBlend &&
value1.m_BlendOp == value2.m_BlendOp &&
value1.m_SrcBlendAlpha == value2.m_SrcBlendAlpha &&
value1.m_DestBlendAlpha == value2.m_DestBlendAlpha &&
value1.m_BlendOpAlpha == value2.m_BlendOpAlpha &&
Utilities::CheckElementEquality( value1.m_RenderTargetWriteMask, value2.m_RenderTargetWriteMask )
);
}
}
}
<commit_msg>(issue #361) After constructing lazy property arrays, the BlendStateDescription internal constructor will copy values from the native struct's arrays.<commit_after>/*
* Copyright (c) 2007-2008 SlimDX Group
*
* 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 <d3d10.h>
#include "../Utilities.h"
#include "BlendStateDescription.h"
using namespace System;
using namespace System::Collections::Generic;
using namespace System::Collections::ObjectModel;
namespace SlimDX
{
namespace Direct3D10
{
BlendStateDescription::BlendStateDescription( const D3D10_BLEND_DESC& native )
{
m_AlphaToCoverageEnable = native.AlphaToCoverageEnable ? true : false;
m_SrcBlend = static_cast<BlendOption>( native.SrcBlend );
m_DestBlend = static_cast<BlendOption>( native.DestBlend );
m_BlendOp = static_cast<Direct3D10::BlendOperation>( native.BlendOp );
m_SrcBlendAlpha = static_cast<BlendOption>( native.SrcBlendAlpha );
m_DestBlendAlpha = static_cast<BlendOption>( native.DestBlendAlpha );
m_BlendOpAlpha = static_cast<Direct3D10::BlendOperation>( native.BlendOpAlpha );
ConstructLazyProperties();
for(int index = 0; index < 8; ++index)
{
m_BlendEnable[ index ] = native.BlendEnable[ index ];
m_RenderTargetWriteMask[ index ] = static_cast<ColorWriteMaskFlags>( native.RenderTargetWriteMask[ index ] );
}
}
D3D10_BLEND_DESC BlendStateDescription::CreateNativeVersion()
{
D3D10_BLEND_DESC native;
native.AlphaToCoverageEnable = m_AlphaToCoverageEnable;
native.SrcBlend = static_cast<D3D10_BLEND>( m_SrcBlend );
native.DestBlend = static_cast<D3D10_BLEND>( m_DestBlend );
native.BlendOp = static_cast<D3D10_BLEND_OP>( m_BlendOp );
native.SrcBlendAlpha = static_cast<D3D10_BLEND>( m_SrcBlendAlpha );
native.DestBlendAlpha = static_cast<D3D10_BLEND>( m_DestBlendAlpha );
native.BlendOpAlpha = static_cast<D3D10_BLEND_OP>( m_BlendOpAlpha );
ConstructLazyProperties();
for(int index = 0; index < 8; ++index)
{
native.BlendEnable[ index ] = m_BlendEnable[ index ];
native.RenderTargetWriteMask[ index ] = static_cast<UINT8>( m_RenderTargetWriteMask[ index ] );
}
return native;
}
bool BlendStateDescription::IsAlphaToCoverageEnabled::get()
{
return m_AlphaToCoverageEnable;
}
void BlendStateDescription::IsAlphaToCoverageEnabled::set( bool value )
{
m_AlphaToCoverageEnable = value;
}
BlendOption BlendStateDescription::SourceBlend::get()
{
return m_SrcBlend;
}
void BlendStateDescription::SourceBlend::set( BlendOption value )
{
m_SrcBlend = value;
}
BlendOption BlendStateDescription::DestinationBlend::get()
{
return m_DestBlend;
}
void BlendStateDescription::DestinationBlend::set( BlendOption value )
{
m_DestBlend = value;
}
Direct3D10::BlendOperation BlendStateDescription::BlendOperation::get()
{
return m_BlendOp;
}
void BlendStateDescription::BlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOp = value;
}
BlendOption BlendStateDescription::SourceAlphaBlend::get()
{
return m_SrcBlendAlpha;
}
void BlendStateDescription::SourceAlphaBlend::set( BlendOption value )
{
m_SrcBlendAlpha = value;
}
BlendOption BlendStateDescription::DestinationAlphaBlend::get()
{
return m_DestBlendAlpha;
}
void BlendStateDescription::DestinationAlphaBlend::set( BlendOption value )
{
m_DestBlendAlpha = value;
}
Direct3D10::BlendOperation BlendStateDescription::AlphaBlendOperation::get()
{
return m_BlendOpAlpha;
}
void BlendStateDescription::AlphaBlendOperation::set( Direct3D10::BlendOperation value )
{
m_BlendOpAlpha = value;
}
bool BlendStateDescription::GetBlendEnable( UInt32 index )
{
ConstructLazyProperties();
return m_BlendEnable[ index ];
}
void BlendStateDescription::SetBlendEnable( UInt32 index, bool value )
{
ConstructLazyProperties();
m_BlendEnable[ index ] = value;
}
ColorWriteMaskFlags BlendStateDescription::GetWriteMask( UInt32 index )
{
ConstructLazyProperties();
return m_RenderTargetWriteMask[ index ];
}
void BlendStateDescription::SetWriteMask( UInt32 index, ColorWriteMaskFlags value )
{
ConstructLazyProperties();
m_RenderTargetWriteMask[ index ] = value;
}
void BlendStateDescription::ConstructLazyProperties()
{
if( m_BlendEnable == nullptr )
{
m_BlendEnable = gcnew array<bool>(8);
m_RenderTargetWriteMask = gcnew array<ColorWriteMaskFlags>(8);
for(int index = 0; index < 8; ++index)
{
m_BlendEnable[ index ] = false;
m_RenderTargetWriteMask[ index ] = ColorWriteMaskFlags::All;
}
}
}
bool BlendStateDescription::operator == ( BlendStateDescription left, BlendStateDescription right )
{
return BlendStateDescription::Equals( left, right );
}
bool BlendStateDescription::operator != ( BlendStateDescription left, BlendStateDescription right )
{
return !BlendStateDescription::Equals( left, right );
}
int BlendStateDescription::GetHashCode()
{
return (
m_AlphaToCoverageEnable.GetHashCode() +
m_BlendEnable->GetHashCode() +
m_SrcBlend.GetHashCode() +
m_DestBlend.GetHashCode() +
m_BlendOp.GetHashCode() +
m_SrcBlendAlpha.GetHashCode() +
m_DestBlendAlpha.GetHashCode() +
m_BlendOpAlpha.GetHashCode() +
m_RenderTargetWriteMask->GetHashCode()
);
}
bool BlendStateDescription::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<BlendStateDescription>( value ) );
}
bool BlendStateDescription::Equals( BlendStateDescription value )
{
return (
m_AlphaToCoverageEnable == value.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( m_BlendEnable, value.m_BlendEnable ) &&
m_SrcBlend == value.m_SrcBlend &&
m_DestBlend == value.m_DestBlend &&
m_BlendOp == value.m_BlendOp &&
m_SrcBlendAlpha == value.m_SrcBlendAlpha &&
m_DestBlendAlpha == value.m_DestBlendAlpha &&
m_BlendOpAlpha == value.m_BlendOpAlpha &&
Utilities::CheckElementEquality( m_RenderTargetWriteMask, value.m_RenderTargetWriteMask )
);
}
bool BlendStateDescription::Equals( BlendStateDescription% value1, BlendStateDescription% value2 )
{
return (
value1.m_AlphaToCoverageEnable == value2.m_AlphaToCoverageEnable &&
Utilities::CheckElementEquality( value1.m_BlendEnable, value2.m_BlendEnable ) &&
value1.m_SrcBlend == value2.m_SrcBlend &&
value1.m_DestBlend == value2.m_DestBlend &&
value1.m_BlendOp == value2.m_BlendOp &&
value1.m_SrcBlendAlpha == value2.m_SrcBlendAlpha &&
value1.m_DestBlendAlpha == value2.m_DestBlendAlpha &&
value1.m_BlendOpAlpha == value2.m_BlendOpAlpha &&
Utilities::CheckElementEquality( value1.m_RenderTargetWriteMask, value2.m_RenderTargetWriteMask )
);
}
}
}
<|endoftext|> |
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Definitions for the FStream classes
*
* These classes are versions of ifstream and ofstream that accept platform independent
* (i.e. win32 or unix) utf-8 path specifiers for their constructor and open() methods.
*
* The native ifstream and ofstream classes on unix already accept UTF-8, but on win32,
* we must convert the utf-8 path to unicode and then pass it to the 'w' version of
* ifstream or ofstream
*/
#include "nta/utils/Log.hpp"
#include "nta/os/Path.hpp"
#include "nta/os/FStream.hpp"
#include "nta/os/Directory.hpp"
#include "nta/os/Env.hpp"
#include <fstream>
#include <cstdlib>
#ifdef WIN32
#include <fcntl.h>
#include <sys/stat.h>
#endif
#include <zlib.h>
using namespace nta;
//////////////////////////////////////////////////////////////////////////
/// Print out diagnostic information when a file open fails
/////////////////////////////////////////////////////////////////////////
void IFStream::diagnostics(const char* filename)
{
bool forceLog = false;
// We occasionally get error 116(ESTALE) "Stale NFS file handle" (TOO-402) when creating
// a file using OFStream::open() on a shared drive on unix systems. We found that
// if we perform a directory listing after encountering the error, that a retry
// immediately after is successful. So.... we log this information if we
// get errno==ESTALE OR if NTA_FILE_LOGGING is set.
#ifdef ESTALE
if (errno == ESTALE)
forceLog = true;
#endif
if (forceLog || ::getenv("NTA_FILE_LOGGING")) {
NTA_DEBUG << "FStream::open() failed opening file " << filename
<< "; errno = " << errno
<< "; errmsg = " << strerror(errno)
<< "; cwd = " << Directory::getCWD();
Directory::Iterator di(Directory::getCWD());
Directory::Entry e;
while (di.next(e)) {
NTA_DEBUG << "FStream::open() ls: " << e.path;
}
}
}
//////////////////////////////////////////////////////////////////////////
/// open the given file by name
/////////////////////////////////////////////////////////////////////////
void IFStream::open(const char * filename, ios_base::openmode mode)
{
#ifdef WIN32
std::wstring pathW = Path::utf8ToUnicode(filename);
std::ifstream::open(pathW.c_str(), mode);
#else
std::ifstream::open(filename, mode);
#endif
// Check for error
if (!is_open()) {
IFStream::diagnostics(filename);
// On unix, running nfs, we occasionally get errors opening a file on an nfs drive
// and it seems that simply doing a retry makes it successful
#ifndef WIN32
std::ifstream::clear();
std::ifstream::open(filename, mode);
#endif
}
}
//////////////////////////////////////////////////////////////////////////
/// open the given file by name
/////////////////////////////////////////////////////////////////////////
void OFStream::open(const char * filename, ios_base::openmode mode)
{
#ifdef WIN32
std::wstring pathW = Path::utf8ToUnicode(filename);
std::ofstream::open(pathW.c_str(), mode);
#else
std::ofstream::open(filename, mode);
#endif
// Check for error
if (!is_open()) {
IFStream::diagnostics(filename);
// On unix, running nfs, we occasionally get errors opening a file on an nfs drive
// and it seems that simply doing a retry makes it successful
#ifndef WIN32
std::ofstream::clear();
std::ofstream::open(filename, mode);
#endif
}
}
void *ZLib::fopen(const std::string &filename, const std::string &mode,
std::string *errorMessage)
{
if(mode.empty()) throw std::invalid_argument("Mode may not be empty.");
#ifdef WIN32
std::wstring wfilename(Path::utf8ToUnicode(filename));
int cflags = _O_BINARY;
int pflags = 0;
if(mode[0] == 'r') {
cflags |= _O_RDONLY;
}
else if(mode[0] == 'w') {
cflags |= _O_TRUNC | _O_CREAT | _O_WRONLY;
pflags |= _S_IREAD | _S_IWRITE;
}
else if(mode[0] == 'a') {
cflags |= _O_APPEND | _O_CREAT | _O_WRONLY;
pflags |= _S_IREAD | _S_IWRITE;
}
else { throw std::invalid_argument("Mode must start with 'r', 'w' or 'a'."); }
int fd = _wopen(wfilename.c_str(), cflags, pflags);
gzFile fs = gzdopen(fd, mode.c_str());
if(fs == 0) {
// TODO: Build an error message for Windows.
}
#else
gzFile fs = 0;
{ // zlib may not be thread-safe in its current compiled state.
int attempts = 0;
const int maxAttempts = 1;
int lastError = 0;
while(1) {
fs = gzopen(filename.c_str(), mode.c_str());
if(fs) break;
int error = errno;
if(error != lastError) {
std::string message("Unknown error.");
// lastError = error;
switch(error) {
case Z_STREAM_ERROR: message = "Zlib stream error."; break;
case Z_DATA_ERROR: message = "Zlib data error."; break;
case Z_MEM_ERROR: message = "Zlib memory error."; break;
case Z_BUF_ERROR: message = "Zlib buffer error."; break;
case Z_VERSION_ERROR: message = "Zlib version error."; break;
default:
char errbuf[256];
::strerror_r(error, errbuf, 256);
message = errbuf;
break;
}
if(errorMessage) {
*errorMessage = message;
}
else if(maxAttempts > 1) { // If we will try again, warn about failure.
std::cerr << "Warning: Failed to open file '"
<< filename << "': " << message << std::endl;
}
}
if((++attempts) >= maxAttempts) break;
::usleep(10000);
}
}
#endif
return fs;
}
<commit_msg>workaround strerror_r ignoring return value warning<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
/** @file
* Definitions for the FStream classes
*
* These classes are versions of ifstream and ofstream that accept platform independent
* (i.e. win32 or unix) utf-8 path specifiers for their constructor and open() methods.
*
* The native ifstream and ofstream classes on unix already accept UTF-8, but on win32,
* we must convert the utf-8 path to unicode and then pass it to the 'w' version of
* ifstream or ofstream
*/
#include "nta/utils/Log.hpp"
#include "nta/os/Path.hpp"
#include "nta/os/FStream.hpp"
#include "nta/os/Directory.hpp"
#include "nta/os/Env.hpp"
#include <fstream>
#include <cstdlib>
#ifdef WIN32
#include <fcntl.h>
#include <sys/stat.h>
#endif
#include <zlib.h>
using namespace nta;
//////////////////////////////////////////////////////////////////////////
/// Print out diagnostic information when a file open fails
/////////////////////////////////////////////////////////////////////////
void IFStream::diagnostics(const char* filename)
{
bool forceLog = false;
// We occasionally get error 116(ESTALE) "Stale NFS file handle" (TOO-402) when creating
// a file using OFStream::open() on a shared drive on unix systems. We found that
// if we perform a directory listing after encountering the error, that a retry
// immediately after is successful. So.... we log this information if we
// get errno==ESTALE OR if NTA_FILE_LOGGING is set.
#ifdef ESTALE
if (errno == ESTALE)
forceLog = true;
#endif
if (forceLog || ::getenv("NTA_FILE_LOGGING")) {
NTA_DEBUG << "FStream::open() failed opening file " << filename
<< "; errno = " << errno
<< "; errmsg = " << strerror(errno)
<< "; cwd = " << Directory::getCWD();
Directory::Iterator di(Directory::getCWD());
Directory::Entry e;
while (di.next(e)) {
NTA_DEBUG << "FStream::open() ls: " << e.path;
}
}
}
//////////////////////////////////////////////////////////////////////////
/// open the given file by name
/////////////////////////////////////////////////////////////////////////
void IFStream::open(const char * filename, ios_base::openmode mode)
{
#ifdef WIN32
std::wstring pathW = Path::utf8ToUnicode(filename);
std::ifstream::open(pathW.c_str(), mode);
#else
std::ifstream::open(filename, mode);
#endif
// Check for error
if (!is_open()) {
IFStream::diagnostics(filename);
// On unix, running nfs, we occasionally get errors opening a file on an nfs drive
// and it seems that simply doing a retry makes it successful
#ifndef WIN32
std::ifstream::clear();
std::ifstream::open(filename, mode);
#endif
}
}
//////////////////////////////////////////////////////////////////////////
/// open the given file by name
/////////////////////////////////////////////////////////////////////////
void OFStream::open(const char * filename, ios_base::openmode mode)
{
#ifdef WIN32
std::wstring pathW = Path::utf8ToUnicode(filename);
std::ofstream::open(pathW.c_str(), mode);
#else
std::ofstream::open(filename, mode);
#endif
// Check for error
if (!is_open()) {
IFStream::diagnostics(filename);
// On unix, running nfs, we occasionally get errors opening a file on an nfs drive
// and it seems that simply doing a retry makes it successful
#ifndef WIN32
std::ofstream::clear();
std::ofstream::open(filename, mode);
#endif
}
}
void *ZLib::fopen(const std::string &filename, const std::string &mode,
std::string *errorMessage)
{
if(mode.empty()) throw std::invalid_argument("Mode may not be empty.");
#ifdef WIN32
std::wstring wfilename(Path::utf8ToUnicode(filename));
int cflags = _O_BINARY;
int pflags = 0;
if(mode[0] == 'r') {
cflags |= _O_RDONLY;
}
else if(mode[0] == 'w') {
cflags |= _O_TRUNC | _O_CREAT | _O_WRONLY;
pflags |= _S_IREAD | _S_IWRITE;
}
else if(mode[0] == 'a') {
cflags |= _O_APPEND | _O_CREAT | _O_WRONLY;
pflags |= _S_IREAD | _S_IWRITE;
}
else { throw std::invalid_argument("Mode must start with 'r', 'w' or 'a'."); }
int fd = _wopen(wfilename.c_str(), cflags, pflags);
gzFile fs = gzdopen(fd, mode.c_str());
if(fs == 0) {
// TODO: Build an error message for Windows.
}
#else
gzFile fs = 0;
{ // zlib may not be thread-safe in its current compiled state.
int attempts = 0;
const int maxAttempts = 1;
int lastError = 0;
while(1) {
fs = gzopen(filename.c_str(), mode.c_str());
if(fs) break;
int error = errno;
if(error != lastError) {
std::string message("Unknown error.");
// lastError = error;
switch(error) {
case Z_STREAM_ERROR: message = "Zlib stream error."; break;
case Z_DATA_ERROR: message = "Zlib data error."; break;
case Z_MEM_ERROR: message = "Zlib memory error."; break;
case Z_BUF_ERROR: message = "Zlib buffer error."; break;
case Z_VERSION_ERROR: message = "Zlib version error."; break;
default:
char errbuf[256];
char* retval = ::strerror_r(error, errbuf, 256);
if(retval != NULL) {
//empty code to silence -Werror=unused-variable warning
}
message = errbuf;
break;
}
if(errorMessage) {
*errorMessage = message;
}
else if(maxAttempts > 1) { // If we will try again, warn about failure.
std::cerr << "Warning: Failed to open file '"
<< filename << "': " << message << std::endl;
}
}
if((++attempts) >= maxAttempts) break;
::usleep(10000);
}
}
#endif
return fs;
}
<|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/login_manager_view.h"
#include <signal.h>
#include <sys/types.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/image_background.h"
#include "chrome/browser/chromeos/login_library.h"
#include "chrome/browser/chromeos/network_library.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/label.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
#include "views/window/window_gtk.h"
using views::Background;
using views::Label;
using views::Textfield;
using views::View;
using views::Widget;
const int kUsernameY = 386;
const int kPanelSpacing = 36;
const int kVersionPad = 4;
const int kTextfieldWidth = 286;
const SkColor kVersionColor = 0xFF7691DA;
const SkColor kErrorColor = 0xFF8F384F;
const char *kDefaultDomain = "@gmail.com";
namespace browser {
// Acts as a frame view with no UI.
class LoginManagerNonClientFrameView : public views::NonClientFrameView {
public:
explicit LoginManagerNonClientFrameView() : views::NonClientFrameView() {}
// Returns just the bounds of the window.
virtual gfx::Rect GetBoundsForClientView() const { return bounds(); }
// Doesn't add any size to the client bounds.
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
// There is no system menu.
virtual gfx::Point GetSystemMenuPoint() const { return gfx::Point(); }
// There is no non client area.
virtual int NonClientHitTest(const gfx::Point& point) { return 0; }
// There is no non client area.
virtual void GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {}
virtual void EnableClose(bool enable) {}
virtual void ResetWindowControls() {}
DISALLOW_COPY_AND_ASSIGN(LoginManagerNonClientFrameView);
};
// Subclass of WindowGtk, for use as the top level login window.
class LoginManagerWindow : public views::WindowGtk {
public:
static LoginManagerWindow* CreateLoginManagerWindow() {
LoginManagerWindow* login_manager_window =
new LoginManagerWindow();
login_manager_window->GetNonClientView()->SetFrameView(
new LoginManagerNonClientFrameView());
login_manager_window->Init(NULL, gfx::Rect());
return login_manager_window;
}
private:
LoginManagerWindow() : views::WindowGtk(new LoginManagerView) {
}
DISALLOW_COPY_AND_ASSIGN(LoginManagerWindow);
};
// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginManager() {
// if we can't load the library, we'll tell the user in LoginManagerView.
views::WindowGtk* window =
LoginManagerWindow::CreateLoginManagerWindow();
window->Show();
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->EmitLoginPromptReady();
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
} // namespace browser
LoginManagerView::LoginManagerView() {
Init();
}
LoginManagerView::~LoginManagerView() {
MessageLoop::current()->Quit();
}
void LoginManagerView::Init() {
username_field_ = new views::Textfield;
username_field_->RemoveBorder();
password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD);
password_field_->RemoveBorder();
os_version_label_ = new views::Label();
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_ = new views::Label();
error_label_->SetColor(kErrorColor);
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Creates the main window
BuildWindow();
// Controller to handle events from textfields
username_field_->SetController(this);
password_field_->SetController(this);
if (chromeos::LoginLibrary::EnsureLoaded()) {
loader_.GetVersion(
&consumer_, NewCallback(this, &LoginManagerView::OnOSVersion));
}
}
gfx::Size LoginManagerView::GetPreferredSize() {
return dialog_dimensions_;
}
void LoginManagerView::BuildWindow() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
panel_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_PANEL);
background_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_BACKGROUND);
// --------------------- Get attributes of images -----------------------
dialog_dimensions_.SetSize(gdk_pixbuf_get_width(background_pixbuf_),
gdk_pixbuf_get_height(background_pixbuf_));
int panel_height = gdk_pixbuf_get_height(panel_pixbuf_);
int panel_width = gdk_pixbuf_get_width(panel_pixbuf_);
// ---------------------- Set up root View ------------------------------
set_background(new views::ImageBackground(background_pixbuf_));
View* login_prompt = new View();
login_prompt->set_background(new views::ImageBackground(panel_pixbuf_));
login_prompt->SetBounds(0, 0, panel_width, panel_height);
int x = (panel_width - kTextfieldWidth) / 2;
int y = kUsernameY;
username_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
password_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
os_version_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
os_version_label_->GetPreferredSize().height());
y += kPanelSpacing;
error_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
error_label_->GetPreferredSize().height());
login_prompt->AddChildView(username_field_);
login_prompt->AddChildView(password_field_);
login_prompt->AddChildView(os_version_label_);
login_prompt->AddChildView(error_label_);
AddChildView(login_prompt);
if (!chromeos::LoginLibrary::EnsureLoaded()) {
username_field_->SetText(
l10n_util::GetStringUTF16(IDS_LOGIN_DISABLED_NO_LIBCROS));
username_field_->SetReadOnly(true);
password_field_->SetReadOnly(true);
}
return;
}
views::View* LoginManagerView::GetContentsView() {
return this;
}
bool LoginManagerView::Authenticate(const std::string& username,
const std::string& password) {
base::ProcessHandle handle;
std::vector<std::string> argv;
// TODO(cmasone): we'll want this to be configurable.
argv.push_back("/opt/google/chrome/session");
argv.push_back(username);
argv.push_back(password);
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
base::LaunchApp(argv, no_env, no_files, false, &handle);
int child_exit_code;
return base::WaitForExitCode(handle, &child_exit_code) &&
child_exit_code == 0;
}
void LoginManagerView::SetupSession(const std::string& username) {
if (window()) {
window()->Close();
}
if (username.find("@google.com") != std::string::npos) {
// This isn't thread-safe. However, the login window is specifically
// supposed to be run in a blocking fashion, before any other threads are
// created by the initial browser process.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAutoSSLClientAuth);
}
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->StartSession(username, "");
}
bool LoginManagerView::HandleKeystroke(views::Textfield* s,
const views::Textfield::Keystroke& keystroke) {
if (!chromeos::LoginLibrary::EnsureLoaded())
return false;
if (keystroke.GetKeyboardCode() == base::VKEY_TAB) {
if (username_field_->text().length() != 0) {
std::string username = UTF16ToUTF8(username_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
return false;
}
} else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) {
// Disallow 0 size username.
if (username_field_->text().length() == 0) {
// Return true so that processing ends
return true;
} else {
chromeos::NetworkLibrary* network = chromeos::NetworkLibrary::Get();
if (!network || !network->EnsureLoaded()) {
error_label_->SetText(
l10n_util::GetString(IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY));
return true;
}
if (!network->Connected()) {
error_label_->SetText(
l10n_util::GetString(IDS_LOGIN_ERROR_NETWORK_NOT_CONNECTED));
return true;
}
std::string username = UTF16ToUTF8(username_field_->text());
// todo(cmasone) Need to sanitize memory used to store password.
std::string password = UTF16ToUTF8(password_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
// Set up credentials to prepare for authentication.
if (!Authenticate(username, password)) {
error_label_->SetText(
l10n_util::GetString(IDS_LOGIN_ERROR_AUTHENTICATING));
return true;
}
// TODO(cmasone): something sensible if errors occur.
SetupSession(username);
// Return true so that processing ends
return true;
}
}
// Return false so that processing does not end
return false;
}
void LoginManagerView::OnOSVersion(
chromeos::VersionLoader::Handle handle,
std::string version) {
os_version_label_->SetText(ASCIIToWide(version));
}
<commit_msg>allow login without network This allows locally cached logins and admin logins to work.<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/login_manager_view.h"
#include <signal.h>
#include <sys/types.h>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/file_path.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/chromeos/image_background.h"
#include "chrome/browser/chromeos/login_library.h"
#include "chrome/browser/chromeos/network_library.h"
#include "chrome/common/chrome_switches.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/label.h"
#include "views/widget/widget.h"
#include "views/window/non_client_view.h"
#include "views/window/window.h"
#include "views/window/window_gtk.h"
using views::Background;
using views::Label;
using views::Textfield;
using views::View;
using views::Widget;
const int kUsernameY = 386;
const int kPanelSpacing = 36;
const int kVersionPad = 4;
const int kTextfieldWidth = 286;
const SkColor kVersionColor = 0xFF7691DA;
const SkColor kErrorColor = 0xFF8F384F;
const char *kDefaultDomain = "@gmail.com";
namespace browser {
// Acts as a frame view with no UI.
class LoginManagerNonClientFrameView : public views::NonClientFrameView {
public:
explicit LoginManagerNonClientFrameView() : views::NonClientFrameView() {}
// Returns just the bounds of the window.
virtual gfx::Rect GetBoundsForClientView() const { return bounds(); }
// Doesn't add any size to the client bounds.
virtual gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const {
return client_bounds;
}
// There is no system menu.
virtual gfx::Point GetSystemMenuPoint() const { return gfx::Point(); }
// There is no non client area.
virtual int NonClientHitTest(const gfx::Point& point) { return 0; }
// There is no non client area.
virtual void GetWindowMask(const gfx::Size& size,
gfx::Path* window_mask) {}
virtual void EnableClose(bool enable) {}
virtual void ResetWindowControls() {}
DISALLOW_COPY_AND_ASSIGN(LoginManagerNonClientFrameView);
};
// Subclass of WindowGtk, for use as the top level login window.
class LoginManagerWindow : public views::WindowGtk {
public:
static LoginManagerWindow* CreateLoginManagerWindow() {
LoginManagerWindow* login_manager_window =
new LoginManagerWindow();
login_manager_window->GetNonClientView()->SetFrameView(
new LoginManagerNonClientFrameView());
login_manager_window->Init(NULL, gfx::Rect());
return login_manager_window;
}
private:
LoginManagerWindow() : views::WindowGtk(new LoginManagerView) {
}
DISALLOW_COPY_AND_ASSIGN(LoginManagerWindow);
};
// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowLoginManager() {
// if we can't load the library, we'll tell the user in LoginManagerView.
views::WindowGtk* window =
LoginManagerWindow::CreateLoginManagerWindow();
window->Show();
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->EmitLoginPromptReady();
bool old_state = MessageLoop::current()->NestableTasksAllowed();
MessageLoop::current()->SetNestableTasksAllowed(true);
MessageLoop::current()->Run();
MessageLoop::current()->SetNestableTasksAllowed(old_state);
}
} // namespace browser
LoginManagerView::LoginManagerView() {
Init();
}
LoginManagerView::~LoginManagerView() {
MessageLoop::current()->Quit();
}
void LoginManagerView::Init() {
username_field_ = new views::Textfield;
username_field_->RemoveBorder();
password_field_ = new views::Textfield(views::Textfield::STYLE_PASSWORD);
password_field_->RemoveBorder();
os_version_label_ = new views::Label();
os_version_label_->SetColor(kVersionColor);
os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
error_label_ = new views::Label();
error_label_->SetColor(kErrorColor);
error_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
// Creates the main window
BuildWindow();
// Controller to handle events from textfields
username_field_->SetController(this);
password_field_->SetController(this);
if (chromeos::LoginLibrary::EnsureLoaded()) {
loader_.GetVersion(
&consumer_, NewCallback(this, &LoginManagerView::OnOSVersion));
}
}
gfx::Size LoginManagerView::GetPreferredSize() {
return dialog_dimensions_;
}
void LoginManagerView::BuildWindow() {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
panel_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_PANEL);
background_pixbuf_ = rb.GetPixbufNamed(IDR_LOGIN_BACKGROUND);
// --------------------- Get attributes of images -----------------------
dialog_dimensions_.SetSize(gdk_pixbuf_get_width(background_pixbuf_),
gdk_pixbuf_get_height(background_pixbuf_));
int panel_height = gdk_pixbuf_get_height(panel_pixbuf_);
int panel_width = gdk_pixbuf_get_width(panel_pixbuf_);
// ---------------------- Set up root View ------------------------------
set_background(new views::ImageBackground(background_pixbuf_));
View* login_prompt = new View();
login_prompt->set_background(new views::ImageBackground(panel_pixbuf_));
login_prompt->SetBounds(0, 0, panel_width, panel_height);
int x = (panel_width - kTextfieldWidth) / 2;
int y = kUsernameY;
username_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
password_field_->SetBounds(x, y, kTextfieldWidth, kPanelSpacing);
y += 2 * kPanelSpacing;
os_version_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
os_version_label_->GetPreferredSize().height());
y += kPanelSpacing;
error_label_->SetBounds(
x,
y,
panel_width - (x + kVersionPad),
error_label_->GetPreferredSize().height());
login_prompt->AddChildView(username_field_);
login_prompt->AddChildView(password_field_);
login_prompt->AddChildView(os_version_label_);
login_prompt->AddChildView(error_label_);
AddChildView(login_prompt);
if (!chromeos::LoginLibrary::EnsureLoaded()) {
error_label->SetText(
l10n_util::GetStringUTF16(IDS_LOGIN_DISABLED_NO_LIBCROS));
username_field_->SetReadOnly(true);
password_field_->SetReadOnly(true);
}
return;
}
views::View* LoginManagerView::GetContentsView() {
return this;
}
bool LoginManagerView::Authenticate(const std::string& username,
const std::string& password) {
base::ProcessHandle handle;
std::vector<std::string> argv;
// TODO(cmasone): we'll want this to be configurable.
argv.push_back("/opt/google/chrome/session");
argv.push_back(username);
argv.push_back(password);
base::environment_vector no_env;
base::file_handle_mapping_vector no_files;
base::LaunchApp(argv, no_env, no_files, false, &handle);
int child_exit_code;
return base::WaitForExitCode(handle, &child_exit_code) &&
child_exit_code == 0;
}
void LoginManagerView::SetupSession(const std::string& username) {
if (window()) {
window()->Close();
}
if (username.find("@google.com") != std::string::npos) {
// This isn't thread-safe. However, the login window is specifically
// supposed to be run in a blocking fashion, before any other threads are
// created by the initial browser process.
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAutoSSLClientAuth);
}
if (chromeos::LoginLibrary::EnsureLoaded())
chromeos::LoginLibrary::Get()->StartSession(username, "");
}
bool LoginManagerView::HandleKeystroke(views::Textfield* s,
const views::Textfield::Keystroke& keystroke) {
if (!chromeos::LoginLibrary::EnsureLoaded())
return false;
if (keystroke.GetKeyboardCode() == base::VKEY_TAB) {
if (username_field_->text().length() != 0) {
std::string username = UTF16ToUTF8(username_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
return false;
}
} else if (keystroke.GetKeyboardCode() == base::VKEY_RETURN) {
// Disallow 0 size username.
if (username_field_->text().length() == 0) {
// Return true so that processing ends
return true;
} else {
std::string username = UTF16ToUTF8(username_field_->text());
// todo(cmasone) Need to sanitize memory used to store password.
std::string password = UTF16ToUTF8(password_field_->text());
if (username.find('@') == std::string::npos) {
username += kDefaultDomain;
username_field_->SetText(UTF8ToUTF16(username));
}
// Set up credentials to prepare for authentication.
if (!Authenticate(username, password)) {
chromeos::NetworkLibrary* network = chromeos::NetworkLibrary::Get();
int errorID;
// Check networking after trying to login in case user is
// cached locally or the local admin account.
if (!network || !network->EnsureLoaded())
errorID = IDS_LOGIN_ERROR_NO_NETWORK_LIBRARY;
else if (!network->Connected())
errorID = IDS_LOGIN_ERROR_NETWORK_NOT_CONNECTED;
else
errorID = IDS_LOGIN_ERROR_AUTHENTICATING;
error_label_->SetText(l10n_util::GetString(errorID));
return true;
}
// TODO(cmasone): something sensible if errors occur.
SetupSession(username);
// Return true so that processing ends
return true;
}
}
// Return false so that processing does not end
return false;
}
void LoginManagerView::OnOSVersion(
chromeos::VersionLoader::Handle handle,
std::string version) {
os_version_label_->SetText(ASCIIToWide(version));
}
<|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/usb_mount_observer.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
namespace chromeos {
const char* kFilebrowseURLHash = "chrome://filebrowse#";
const char* kFilebrowseScanning = "scanningdevice";
const int kPopupLeft = 0;
const int kPopupTop = 0;
const int kPopupWidth = 250;
const int kPopupHeight = 300;
void USBMountObserver::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::BROWSER_CLOSED);
for (BrowserIterator i = browsers_.begin(); i != browsers_.end();
++i) {
if (Source<Browser>(source).ptr() == i->browser) {
i->browser = NULL;
registrar_.Remove(this,
NotificationType::BROWSER_CLOSED,
source);
return;
}
}
}
void USBMountObserver::ScanForDevices(chromeos::MountLibrary* obj) {
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
chromeos::MountLibrary::Disk disk = disks[i];
if (!disk.is_parent && !disk.device_path.empty()) {
obj->MountPath(disk.device_path.c_str());
}
}
}
void USBMountObserver::OpenFileBrowse(const std::string& url,
const std::string& device_path,
bool small) {
Browser* browser;
Profile* profile;
profile = BrowserList::GetLastActive()->profile();
if (small) {
browser = FileBrowseUI::OpenPopup(profile,
url,
FileBrowseUI::kSmallPopupWidth,
FileBrowseUI::kSmallPopupHeight);
} else {
browser = FileBrowseUI::OpenPopup(profile,
url,
FileBrowseUI::kPopupWidth,
FileBrowseUI::kPopupHeight);
}
registrar_.Add(this,
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
BrowserIterator iter = FindBrowserForPath(device_path);
if (iter == browsers_.end()) {
BrowserWithPath new_browser;
new_browser.browser = browser;
new_browser.device_path = device_path;
browsers_.push_back(new_browser);
} else {
iter->browser = browser;
}
}
void USBMountObserver::MountChanged(chromeos::MountLibrary* obj,
chromeos::MountEventType evt,
const std::string& path) {
if (evt == chromeos::DISK_ADDED) {
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
chromeos::MountLibrary::Disk disk = disks[i];
if (disk.device_path == path) {
if (disk.is_parent) {
if (!disk.has_media) {
RemoveBrowserFromVector(disk.system_path);
}
} else if (!obj->MountPath(path.c_str())) {
RemoveBrowserFromVector(disk.system_path);
}
}
}
LOG(INFO) << "Got added mount:" << path;
} else if (evt == chromeos::DISK_REMOVED ||
evt == chromeos::DEVICE_REMOVED) {
RemoveBrowserFromVector(path);
} else if (evt == chromeos::DISK_CHANGED) {
BrowserIterator iter = FindBrowserForPath(path);
LOG(INFO) << "Got changed mount:" << path;
if (iter == browsers_.end()) {
// We don't currently have this one, so it must have been
// mounted
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
if (disks[i].device_path == path) {
if (!disks[i].mount_path.empty()) {
// Doing second search to see if the current disk has already
// been popped up due to its parent device being plugged in.
iter = FindBrowserForPath(disks[i].system_path);
if (iter != browsers_.end() && iter->browser) {
std::string url = kFilebrowseURLHash;
url += disks[i].mount_path;
TabContents* tab = iter->browser->GetSelectedTabContents();
iter->browser->window()->SetBounds(gfx::Rect(
0, 0, FileBrowseUI::kPopupWidth, FileBrowseUI::kPopupHeight));
tab->OpenURL(GURL(url), GURL(), CURRENT_TAB,
PageTransition::LINK);
tab->NavigateToPendingEntry(NavigationController::RELOAD);
iter->device_path = path;
} else {
OpenFileBrowse(disks[i].mount_path, disks[i].device_path, false);
}
}
return;
}
}
}
} else if (evt == chromeos::DEVICE_ADDED) {
LOG(INFO) << "Got device added" << path;
OpenFileBrowse(kFilebrowseScanning, path, true);
} else if (evt == chromeos::DEVICE_SCANNED) {
LOG(INFO) << "Got device scanned:" << path;
}
}
USBMountObserver::BrowserIterator USBMountObserver::FindBrowserForPath(
const std::string& path) {
for (BrowserIterator i = browsers_.begin();i != browsers_.end();
++i) {
// Doing a substring match so that we find if this new one is a subdevice
// of another already inserted device.
if (path.find(i->device_path) != std::string::npos) {
return i;
}
}
return browsers_.end();
}
void USBMountObserver::RemoveBrowserFromVector(const std::string& path) {
BrowserIterator i = FindBrowserForPath(path);
std::string mount_path;
if (i != browsers_.end()) {
registrar_.Remove(this,
NotificationType::BROWSER_CLOSED,
Source<Browser>(i->browser));
mount_path = i->mount_path;
browsers_.erase(i);
}
std::vector<Browser*> close_these;
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
if (*it && (*it)->GetTabContentsAt((*it)->selected_index())) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIFileBrowseHost &&
url.ref().find(mount_path) != std::string::npos) {
close_these.push_back(*it);
}
}
}
}
for (size_t x = 0; x < close_these.size(); x++) {
if (close_these[x]->window()) {
close_these[x]->window()->Close();
}
}
}
} // namespace chromeos
<commit_msg>Fixing system so that it only closes open file browsers that currently point at the directories on that device.<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/usb_mount_observer.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/dom_ui/filebrowse_ui.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
namespace chromeos {
const char* kFilebrowseURLHash = "chrome://filebrowse#";
const char* kFilebrowseScanning = "scanningdevice";
const int kPopupLeft = 0;
const int kPopupTop = 0;
const int kPopupWidth = 250;
const int kPopupHeight = 300;
void USBMountObserver::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type == NotificationType::BROWSER_CLOSED);
for (BrowserIterator i = browsers_.begin(); i != browsers_.end();
++i) {
if (Source<Browser>(source).ptr() == i->browser) {
i->browser = NULL;
registrar_.Remove(this,
NotificationType::BROWSER_CLOSED,
source);
return;
}
}
}
void USBMountObserver::ScanForDevices(chromeos::MountLibrary* obj) {
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
chromeos::MountLibrary::Disk disk = disks[i];
if (!disk.is_parent && !disk.device_path.empty()) {
obj->MountPath(disk.device_path.c_str());
}
}
}
void USBMountObserver::OpenFileBrowse(const std::string& url,
const std::string& device_path,
bool small) {
Browser* browser;
Profile* profile;
profile = BrowserList::GetLastActive()->profile();
if (small) {
browser = FileBrowseUI::OpenPopup(profile,
url,
FileBrowseUI::kSmallPopupWidth,
FileBrowseUI::kSmallPopupHeight);
} else {
browser = FileBrowseUI::OpenPopup(profile,
url,
FileBrowseUI::kPopupWidth,
FileBrowseUI::kPopupHeight);
}
registrar_.Add(this,
NotificationType::BROWSER_CLOSED,
Source<Browser>(browser));
BrowserIterator iter = FindBrowserForPath(device_path);
if (iter == browsers_.end()) {
BrowserWithPath new_browser;
new_browser.browser = browser;
new_browser.device_path = device_path;
browsers_.push_back(new_browser);
} else {
iter->browser = browser;
}
}
void USBMountObserver::MountChanged(chromeos::MountLibrary* obj,
chromeos::MountEventType evt,
const std::string& path) {
if (evt == chromeos::DISK_ADDED) {
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
chromeos::MountLibrary::Disk disk = disks[i];
if (disk.device_path == path) {
if (disk.is_parent) {
if (!disk.has_media) {
RemoveBrowserFromVector(disk.system_path);
}
} else if (!obj->MountPath(path.c_str())) {
RemoveBrowserFromVector(disk.system_path);
}
}
}
LOG(INFO) << "Got added mount:" << path;
} else if (evt == chromeos::DISK_REMOVED ||
evt == chromeos::DEVICE_REMOVED) {
RemoveBrowserFromVector(path);
} else if (evt == chromeos::DISK_CHANGED) {
BrowserIterator iter = FindBrowserForPath(path);
LOG(INFO) << "Got changed mount:" << path;
if (iter == browsers_.end()) {
// We don't currently have this one, so it must have been
// mounted
const chromeos::MountLibrary::DiskVector& disks = obj->disks();
for (size_t i = 0; i < disks.size(); ++i) {
if (disks[i].device_path == path) {
if (!disks[i].mount_path.empty()) {
// Doing second search to see if the current disk has already
// been popped up due to its parent device being plugged in.
iter = FindBrowserForPath(disks[i].system_path);
if (iter != browsers_.end() && iter->browser) {
std::string url = kFilebrowseURLHash;
url += disks[i].mount_path;
TabContents* tab = iter->browser->GetSelectedTabContents();
iter->browser->window()->SetBounds(gfx::Rect(
0, 0, FileBrowseUI::kPopupWidth, FileBrowseUI::kPopupHeight));
tab->OpenURL(GURL(url), GURL(), CURRENT_TAB,
PageTransition::LINK);
tab->NavigateToPendingEntry(NavigationController::RELOAD);
iter->device_path = path;
iter->mount_path = disks[i].mount_path;
} else {
OpenFileBrowse(disks[i].mount_path, disks[i].device_path, false);
}
}
return;
}
}
}
} else if (evt == chromeos::DEVICE_ADDED) {
LOG(INFO) << "Got device added" << path;
OpenFileBrowse(kFilebrowseScanning, path, true);
} else if (evt == chromeos::DEVICE_SCANNED) {
LOG(INFO) << "Got device scanned:" << path;
}
}
USBMountObserver::BrowserIterator USBMountObserver::FindBrowserForPath(
const std::string& path) {
for (BrowserIterator i = browsers_.begin();i != browsers_.end();
++i) {
// Doing a substring match so that we find if this new one is a subdevice
// of another already inserted device.
if (path.find(i->device_path) != std::string::npos) {
return i;
}
}
return browsers_.end();
}
void USBMountObserver::RemoveBrowserFromVector(const std::string& path) {
BrowserIterator i = FindBrowserForPath(path);
std::string mount_path;
if (i != browsers_.end()) {
registrar_.Remove(this,
NotificationType::BROWSER_CLOSED,
Source<Browser>(i->browser));
mount_path = i->mount_path;
browsers_.erase(i);
}
std::vector<Browser*> close_these;
for (BrowserList::const_iterator it = BrowserList::begin();
it != BrowserList::end(); ++it) {
if ((*it)->type() == Browser::TYPE_POPUP) {
if (*it && (*it)->GetTabContentsAt((*it)->selected_index())) {
const GURL& url =
(*it)->GetTabContentsAt((*it)->selected_index())->GetURL();
if (url.SchemeIs(chrome::kChromeUIScheme) &&
url.host() == chrome::kChromeUIFileBrowseHost &&
url.ref().find(mount_path) != std::string::npos &&
!mount_path.empty()) {
close_these.push_back(*it);
}
}
}
}
for (size_t x = 0; x < close_these.size(); x++) {
if (close_these[x]->window()) {
close_these[x]->window()->Close();
}
}
}
} // namespace chromeos
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "xdgdirs.h"
#include <stdlib.h>
#include <QDir>
#include <QStringBuilder> // for the % operator
#include <QDebug>
#include <QStandardPaths>
static const QString userDirectoryString[8] =
{
"Desktop",
"Download",
"Templates",
"Publicshare",
"Documents",
"Music",
"Pictures",
"Videos"
};
// Helper functions prototypes
void fixBashShortcuts(QString &s);
void removeEndingSlash(QString &s);
QString createDirectory(const QString &dir);
void cleanAndAddPostfix(QStringList &dirs, const QString& postfix);
QString userDirFallback(XdgDirs::UserDirectory dir);
/************************************************
Helper func.
************************************************/
void fixBashShortcuts(QString &s)
{
if (s.startsWith(QLatin1Char('~')))
s = QString(getenv("HOME")) + (s).mid(1);
}
void removeEndingSlash(QString &s)
{
// We don't check for empty strings. Caller must check it.
// Remove the ending slash, except for root dirs.
if (s.length() > 1 && s.endsWith(QLatin1Char('/')))
s.chop(1);
}
QString createDirectory(const QString &dir)
{
QDir d(dir);
if (!d.exists())
{
if (!d.mkpath("."))
{
qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath());
}
}
QString r = d.absolutePath();
removeEndingSlash(r);
return r;
}
void cleanAndAddPostfix(QStringList &dirs, const QString& postfix)
{
const int N = dirs.count();
for(int i = 0; i < N; ++i)
{
fixBashShortcuts(dirs[i]);
removeEndingSlash(dirs[i]);
dirs[i].append(postfix);
}
}
QString userDirFallback(XdgDirs::UserDirectory dir)
{
QString fallback;
if (getenv("HOME") == NULL)
return QString("/tmp");
else if (dir == XdgDirs::Desktop)
fallback = QString("%1/%2").arg(getenv("HOME")).arg("Desktop");
else
fallback = QString(getenv("HOME"));
return fallback;
}
QString XdgDirs::userDirDefault(XdgDirs::UserDirectory dir)
{
// possible values for UserDirectory
if (dir < XdgDirs::Desktop || dir > XdgDirs::Videos)
return QString();
return userDirFallback(dir);
}
QString XdgDirs::userDir(XdgDirs::UserDirectory dir)
{
// possible values for UserDirectory
if (dir < 0 || dir > 7)
return QString();
QString folderName = userDirectoryString[dir];
const QString fallback = userDirFallback(dir);
QString configDir(configHome());
QFile configFile(configDir + "/user-dirs.dirs");
if (!configFile.exists())
return fallback;
if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text))
return fallback;
QString userDirVar("XDG_" + folderName.toUpper() + "_DIR");
QTextStream in(&configFile);
QString line;
while (!in.atEnd())
{
line = in.readLine();
if (line.contains(userDirVar))
{
configFile.close();
// get path between quotes
line = line.section(QLatin1Char('"'), 1, 1);
if (line.isEmpty())
return fallback;
line.replace(QLatin1String("$HOME"), QLatin1String("~"));
fixBashShortcuts(line);
return line;
}
}
configFile.close();
return fallback;
}
bool XdgDirs::setUserDir(XdgDirs::UserDirectory dir, const QString& value, bool createDir)
{
// possible values for UserDirectory
if (dir < 0 || dir > 7)
return false;
if (!(value.startsWith(QLatin1String("$HOME"))
|| value.startsWith(QLatin1String("~/"))
|| value.startsWith(QString(getenv("HOME")))))
return false;
QString folderName = userDirectoryString[dir];
QString configDir(configHome());
QFile configFile(configDir % QLatin1String("/user-dirs.dirs"));
// create the file if doesn't exist and opens it
if (!configFile.open(QIODevice::ReadWrite | QIODevice::Text))
return false;
QTextStream stream(&configFile);
QVector<QString> lines;
QString line;
bool foundVar = false;
while (!stream.atEnd())
{
line = stream.readLine();
if (line.indexOf(QLatin1String("XDG_") + folderName.toUpper() + QLatin1String("_DIR")) == 0)
{
foundVar = true;
QString path = line.section(QLatin1Char('"'), 1, 1);
line.replace(path, value);
lines.append(line);
}
else if (line.indexOf(QLatin1String("XDG_")) == 0)
{
lines.append(line);
}
}
stream.reset();
configFile.resize(0);
if (!foundVar)
stream << QString("XDG_%1_DIR=\"%2\"\n").arg(folderName.toUpper()).arg(value);
for (QVector<QString>::iterator i = lines.begin(); i != lines.end(); ++i)
stream << *i << "\n";
configFile.close();
if (createDir) {
QString path = QString(value).replace(QLatin1String("$HOME"), QLatin1String("~"));
fixBashShortcuts(path);
QDir().mkpath(path);
}
return true;
}
QString XdgDirs::dataHome(bool createDir)
{
QString s = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
removeEndingSlash(s);
return s;
}
QString XdgDirs::configHome(bool createDir)
{
QString s = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
removeEndingSlash(s);
return s;
}
QStringList XdgDirs::dataDirs(const QString &postfix)
{
QString d = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
QStringList dirs = d.split(QLatin1Char(':'), QString::SkipEmptyParts);
if (dirs.isEmpty()) {
dirs.append(QString::fromLatin1("/usr/local/share"));
dirs.append(QString::fromLatin1("/usr/share"));
} else {
QMutableListIterator<QString> it(dirs);
while (it.hasNext()) {
const QString dir = it.next();
if (!dir.startsWith(QLatin1Char('/')))
it.remove();
}
}
dirs.removeDuplicates();
cleanAndAddPostfix(dirs, postfix);
return dirs;
}
QStringList XdgDirs::configDirs(const QString &postfix)
{
QStringList dirs;
const QString env = QFile::decodeName(qgetenv("XDG_CONFIG_DIRS"));
if (env.isEmpty())
dirs.append(QString::fromLatin1("/etc/xdg"));
else
dirs = env.split(QLatin1Char(':'), QString::SkipEmptyParts);
cleanAndAddPostfix(dirs, postfix);
return dirs;
}
QString XdgDirs::cacheHome(bool createDir)
{
QString s = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
removeEndingSlash(s);
return s;
}
QString XdgDirs::runtimeDir()
{
QString result = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
fixBashShortcuts(result);
removeEndingSlash(result);
return result;
}
QString XdgDirs::autostartHome(bool createDir)
{
QString s = QString("%1/autostart").arg(configHome(createDir));
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
QDir d(s);
QString r = d.absolutePath();
removeEndingSlash(r);
return r;
}
QStringList XdgDirs::autostartDirs(const QString &postfix)
{
QStringList dirs;
QStringList s = configDirs();
foreach(QString dir, s)
dirs << QString("%1/autostart").arg(dir) + postfix;
return dirs;
}
<commit_msg>XdgDirs: Use XdgDirs::UserDirectory enum instead of int<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or 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
*
* END_COMMON_COPYRIGHT_HEADER */
#include "xdgdirs.h"
#include <stdlib.h>
#include <QDir>
#include <QStringBuilder> // for the % operator
#include <QDebug>
#include <QStandardPaths>
static const QString userDirectoryString[8] =
{
"Desktop",
"Download",
"Templates",
"Publicshare",
"Documents",
"Music",
"Pictures",
"Videos"
};
// Helper functions prototypes
void fixBashShortcuts(QString &s);
void removeEndingSlash(QString &s);
QString createDirectory(const QString &dir);
void cleanAndAddPostfix(QStringList &dirs, const QString& postfix);
QString userDirFallback(XdgDirs::UserDirectory dir);
/************************************************
Helper func.
************************************************/
void fixBashShortcuts(QString &s)
{
if (s.startsWith(QLatin1Char('~')))
s = QString(getenv("HOME")) + (s).mid(1);
}
void removeEndingSlash(QString &s)
{
// We don't check for empty strings. Caller must check it.
// Remove the ending slash, except for root dirs.
if (s.length() > 1 && s.endsWith(QLatin1Char('/')))
s.chop(1);
}
QString createDirectory(const QString &dir)
{
QDir d(dir);
if (!d.exists())
{
if (!d.mkpath("."))
{
qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath());
}
}
QString r = d.absolutePath();
removeEndingSlash(r);
return r;
}
void cleanAndAddPostfix(QStringList &dirs, const QString& postfix)
{
const int N = dirs.count();
for(int i = 0; i < N; ++i)
{
fixBashShortcuts(dirs[i]);
removeEndingSlash(dirs[i]);
dirs[i].append(postfix);
}
}
QString userDirFallback(XdgDirs::UserDirectory dir)
{
QString fallback;
if (getenv("HOME") == NULL)
return QString("/tmp");
else if (dir == XdgDirs::Desktop)
fallback = QString("%1/%2").arg(getenv("HOME")).arg("Desktop");
else
fallback = QString(getenv("HOME"));
return fallback;
}
QString XdgDirs::userDirDefault(XdgDirs::UserDirectory dir)
{
// possible values for UserDirectory
if (dir < XdgDirs::Desktop || dir > XdgDirs::Videos)
return QString();
return userDirFallback(dir);
}
QString XdgDirs::userDir(XdgDirs::UserDirectory dir)
{
// possible values for UserDirectory
if (dir < XdgDirs::Desktop || dir > XdgDirs::Videos)
return QString();
QString folderName = userDirectoryString[dir];
const QString fallback = userDirFallback(dir);
QString configDir(configHome());
QFile configFile(configDir + "/user-dirs.dirs");
if (!configFile.exists())
return fallback;
if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text))
return fallback;
QString userDirVar("XDG_" + folderName.toUpper() + "_DIR");
QTextStream in(&configFile);
QString line;
while (!in.atEnd())
{
line = in.readLine();
if (line.contains(userDirVar))
{
configFile.close();
// get path between quotes
line = line.section(QLatin1Char('"'), 1, 1);
if (line.isEmpty())
return fallback;
line.replace(QLatin1String("$HOME"), QLatin1String("~"));
fixBashShortcuts(line);
return line;
}
}
configFile.close();
return fallback;
}
bool XdgDirs::setUserDir(XdgDirs::UserDirectory dir, const QString& value, bool createDir)
{
// possible values for UserDirectory
if (dir < XdgDirs::Desktop || dir > XdgDirs::Videos)
return false;
if (!(value.startsWith(QLatin1String("$HOME"))
|| value.startsWith(QLatin1String("~/"))
|| value.startsWith(QString(getenv("HOME")))))
return false;
QString folderName = userDirectoryString[dir];
QString configDir(configHome());
QFile configFile(configDir % QLatin1String("/user-dirs.dirs"));
// create the file if doesn't exist and opens it
if (!configFile.open(QIODevice::ReadWrite | QIODevice::Text))
return false;
QTextStream stream(&configFile);
QVector<QString> lines;
QString line;
bool foundVar = false;
while (!stream.atEnd())
{
line = stream.readLine();
if (line.indexOf(QLatin1String("XDG_") + folderName.toUpper() + QLatin1String("_DIR")) == 0)
{
foundVar = true;
QString path = line.section(QLatin1Char('"'), 1, 1);
line.replace(path, value);
lines.append(line);
}
else if (line.indexOf(QLatin1String("XDG_")) == 0)
{
lines.append(line);
}
}
stream.reset();
configFile.resize(0);
if (!foundVar)
stream << QString("XDG_%1_DIR=\"%2\"\n").arg(folderName.toUpper()).arg(value);
for (QVector<QString>::iterator i = lines.begin(); i != lines.end(); ++i)
stream << *i << "\n";
configFile.close();
if (createDir) {
QString path = QString(value).replace(QLatin1String("$HOME"), QLatin1String("~"));
fixBashShortcuts(path);
QDir().mkpath(path);
}
return true;
}
QString XdgDirs::dataHome(bool createDir)
{
QString s = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
removeEndingSlash(s);
return s;
}
QString XdgDirs::configHome(bool createDir)
{
QString s = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
removeEndingSlash(s);
return s;
}
QStringList XdgDirs::dataDirs(const QString &postfix)
{
QString d = QFile::decodeName(qgetenv("XDG_DATA_DIRS"));
QStringList dirs = d.split(QLatin1Char(':'), QString::SkipEmptyParts);
if (dirs.isEmpty()) {
dirs.append(QString::fromLatin1("/usr/local/share"));
dirs.append(QString::fromLatin1("/usr/share"));
} else {
QMutableListIterator<QString> it(dirs);
while (it.hasNext()) {
const QString dir = it.next();
if (!dir.startsWith(QLatin1Char('/')))
it.remove();
}
}
dirs.removeDuplicates();
cleanAndAddPostfix(dirs, postfix);
return dirs;
}
QStringList XdgDirs::configDirs(const QString &postfix)
{
QStringList dirs;
const QString env = QFile::decodeName(qgetenv("XDG_CONFIG_DIRS"));
if (env.isEmpty())
dirs.append(QString::fromLatin1("/etc/xdg"));
else
dirs = env.split(QLatin1Char(':'), QString::SkipEmptyParts);
cleanAndAddPostfix(dirs, postfix);
return dirs;
}
QString XdgDirs::cacheHome(bool createDir)
{
QString s = QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation);
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
removeEndingSlash(s);
return s;
}
QString XdgDirs::runtimeDir()
{
QString result = QStandardPaths::writableLocation(QStandardPaths::RuntimeLocation);
fixBashShortcuts(result);
removeEndingSlash(result);
return result;
}
QString XdgDirs::autostartHome(bool createDir)
{
QString s = QString("%1/autostart").arg(configHome(createDir));
fixBashShortcuts(s);
if (createDir)
return createDirectory(s);
QDir d(s);
QString r = d.absolutePath();
removeEndingSlash(r);
return r;
}
QStringList XdgDirs::autostartDirs(const QString &postfix)
{
QStringList dirs;
QStringList s = configDirs();
foreach(QString dir, s)
dirs << QString("%1/autostart").arg(dir) + postfix;
return dirs;
}
<|endoftext|> |
<commit_before>class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double maxAvg = INT_MIN, tmp = 0;
for (int start = nums.size() - k; start >= 0; start--) {
tmp = 0;
for (int i = 0; i < k; i++) {
tmp += nums[start+i];
}
maxAvg = max(maxAvg, (double)tmp/k);
}
return maxAvg;
}
};<commit_msg>leetcode 643 with sliding window<commit_after>class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double maxAvg = INT_MIN, tmp = 0;
for (int start = nums.size() - k; start >= 0; start--) {
tmp = 0;
for (int i = 0; i < k; i++) {
tmp += nums[start+i];
}
maxAvg = max(maxAvg, (double)tmp/k);
}
return maxAvg;
}
double findMaxAverage(vector<int>& nums, int k) {
double window;
for (int i = 0; i < k; i++) window += nums[i];
double tmp = window;
for (int i = 1; i <= nums.size() - k; i++) {
std::cout<<nums[i-1]<<":"<<nums[i+k-1]<<":"<<tmp<<endl;
tmp = nums[i+k-1] - nums[i-1] + window;
window = max(tmp, window);
}
return (double)window/k;
}
};<|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.
===================================================================*/
// semantic relations UI module
#include "QmitkPatientTableModel.h"
#include "QmitkPatientTableHeaderView.h"
#include "QmitkSemanticRelationsUIHelper.h"
// semantic relations module
#include <mitkControlPointManager.h>
#include <mitkNodePredicates.h>
#include <mitkSemanticRelationException.h>
#include <mitkSemanticRelationsInference.h>
#include <mitkRelationStorage.h>
#include <QmitkCustomVariants.h>
#include <QmitkEnums.h>
// qt
#include <QColor>
// c++
#include <iostream>
#include <string>
QmitkPatientTableModel::QmitkPatientTableModel(QObject* parent /*= nullptr*/)
: QmitkAbstractSemanticRelationsStorageModel(parent)
, m_SelectedNodeType("Image")
{
m_HeaderModel = new QStandardItemModel(this);
}
QmitkPatientTableModel::~QmitkPatientTableModel()
{
// nothing here
}
QModelIndex QmitkPatientTableModel::index(int row, int column, const QModelIndex& parent/* = QModelIndex()*/) const
{
if (hasIndex(row, column, parent))
{
return createIndex(row, column);
}
return QModelIndex();
}
QModelIndex QmitkPatientTableModel::parent(const QModelIndex& /*child*/) const
{
return QModelIndex();
}
int QmitkPatientTableModel::rowCount(const QModelIndex& parent/* = QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return m_InformationTypes.size();
}
int QmitkPatientTableModel::columnCount(const QModelIndex& parent/* = QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return m_ExaminationPeriods.size();
}
QVariant QmitkPatientTableModel::data(const QModelIndex& index, int role/* = Qt::DisplayRole*/) const
{
// special role for returning the horizontal header
if (QmitkPatientTableHeaderView::HorizontalHeaderDataRole == role)
{
return QVariant::fromValue<QStandardItemModel*>(m_HeaderModel);
}
if (!index.isValid())
{
return QVariant();
}
if (index.row() < 0 || index.row() >= static_cast<int>(m_InformationTypes.size())
|| index.column() < 0 || index.column() >= static_cast<int>(m_ExaminationPeriods.size()))
{
return QVariant();
}
mitk::DataNode* dataNode = GetCurrentDataNode(index);
if (Qt::DecorationRole == role)
{
auto it = m_PixmapMap.find(dataNode);
if (it != m_PixmapMap.end())
{
return QVariant(it->second);
}
auto emptyPixmap = QPixmap(120, 120);
emptyPixmap.fill(Qt::darkGray);
return emptyPixmap;
}
if (Qt::BackgroundColorRole == role)
{
auto it = m_LesionPresence.find(dataNode);
if (it != m_LesionPresence.end())
{
return it->second ? QVariant(QColor(Qt::darkGreen)) : QVariant(QColor(Qt::transparent));
}
return QVariant(QColor(Qt::transparent));
}
if (QmitkDataNodeRole == role)
{
return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode));
}
if (QmitkDataNodeRawPointerRole == role)
{
return QVariant::fromValue<mitk::DataNode*>(dataNode);
}
return QVariant();
}
QVariant QmitkPatientTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (Qt::Vertical == orientation && Qt::DisplayRole == role)
{
if (static_cast<int>(m_InformationTypes.size()) > section)
{
mitk::SemanticTypes::InformationType currentInformationType = m_InformationTypes.at(section);
return QVariant(QString::fromStdString(currentInformationType));
}
}
return QVariant();
}
Qt::ItemFlags QmitkPatientTableModel::flags(const QModelIndex& index) const
{
Qt::ItemFlags flags;
mitk::DataNode* dataNode = GetCurrentDataNode(index);
if (nullptr != dataNode)
{
flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
return flags;
}
void QmitkPatientTableModel::SetNodeType(const std::string& nodeType)
{
m_SelectedNodeType = nodeType;
UpdateModelData();
}
void QmitkPatientTableModel::NodePredicateChanged()
{
UpdateModelData();
}
void QmitkPatientTableModel::SetData()
{
// get all examination periods of current case
m_ExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(m_CaseID);
// sort all examination periods for the timeline
mitk::SortAllExaminationPeriods(m_CaseID, m_ExaminationPeriods);
// rename examination periods according to their new order
std::string examinationPeriodName = "Baseline";
for (int i = 0; i < m_ExaminationPeriods.size(); ++i)
{
auto& examinationPeriod = m_ExaminationPeriods.at(i);
examinationPeriod.name = examinationPeriodName;
mitk::RelationStorage::RenameExaminationPeriod(m_CaseID, examinationPeriod);
examinationPeriodName = "Follow-up " + std::to_string(i);
}
// get all information types points of current case
m_InformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(m_CaseID);
if ("Image" == m_SelectedNodeType)
{
m_CurrentDataNodes = m_SemanticRelationsDataStorageAccess->GetAllImagesOfCase(m_CaseID);
}
else if ("Segmentation" == m_SelectedNodeType)
{
m_CurrentDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSegmentationsOfCase(m_CaseID);
}
SetHeaderModel();
SetPixmaps();
SetLesionPresences();
}
void QmitkPatientTableModel::SetHeaderModel()
{
m_HeaderModel->clear();
QStandardItem* rootItem = new QStandardItem("Timeline");
QList<QStandardItem*> standardItems;
for (const auto& examinationPeriod : m_ExaminationPeriods)
{
QStandardItem* examinationPeriodItem = new QStandardItem(QString::fromStdString(examinationPeriod.name));
standardItems.push_back(examinationPeriodItem);
rootItem->appendColumn(standardItems);
standardItems.clear();
}
m_HeaderModel->setItem(0, 0, rootItem);
}
void QmitkPatientTableModel::SetPixmaps()
{
m_PixmapMap.clear();
for (const auto& dataNode : m_CurrentDataNodes)
{
// set the pixmap for the current node
QPixmap pixmapFromImage = QmitkSemanticRelationsUIHelper::GetPixmapFromImageNode(dataNode);
SetPixmapOfNode(dataNode, &pixmapFromImage);
}
}
void QmitkPatientTableModel::SetPixmapOfNode(const mitk::DataNode* dataNode, QPixmap* pixmapFromImage)
{
if (nullptr == dataNode)
{
return;
}
std::map<mitk::DataNode::ConstPointer, QPixmap>::iterator iter = m_PixmapMap.find(dataNode);
if (iter != m_PixmapMap.end())
{
// key already existing
if (nullptr != pixmapFromImage)
{
// overwrite already stored pixmap
iter->second = pixmapFromImage->scaled(120, 120, Qt::IgnoreAspectRatio);
}
else
{
// remove key if no pixmap is given
m_PixmapMap.erase(iter);
}
}
else
{
m_PixmapMap.insert(std::make_pair(dataNode, pixmapFromImage->scaled(120, 120, Qt::IgnoreAspectRatio)));
}
}
void QmitkPatientTableModel::SetLesionPresences()
{
m_LesionPresence.clear();
if (!mitk::SemanticRelationsInference::InstanceExists(m_CaseID, m_Lesion))
{
return;
}
for (const auto& dataNode : m_CurrentDataNodes)
{
if (!mitk::SemanticRelationsInference::InstanceExists(dataNode))
{
continue;
}
// set the lesion presence for the current node
bool lesionPresence = mitk::SemanticRelationsInference::IsLesionPresent(m_Lesion, dataNode);
SetLesionPresenceOfNode(dataNode, lesionPresence);
}
}
void QmitkPatientTableModel::SetLesionPresenceOfNode(const mitk::DataNode* dataNode, bool lesionPresence)
{
std::map<mitk::DataNode::ConstPointer, bool>::iterator iter = m_LesionPresence.find(dataNode);
if (iter != m_LesionPresence.end())
{
// key already existing, overwrite already stored bool value
iter->second = lesionPresence;
}
else
{
m_LesionPresence.insert(std::make_pair(dataNode, lesionPresence));
}
}
mitk::DataNode* QmitkPatientTableModel::GetCurrentDataNode(const QModelIndex& index) const
{
if (!index.isValid())
{
return nullptr;
}
auto examinationPeriod = m_ExaminationPeriods.at(index.column());
auto currentInformationType = m_InformationTypes.at(index.row());
auto controlPointsOfExaminationPeriod = examinationPeriod.controlPointUIDs;
for (const auto& controlPointUID : controlPointsOfExaminationPeriod)
{
auto currentControlPoint = mitk::GetControlPointByUID(m_CaseID, controlPointUID);
try
{
std::vector<mitk::DataNode::Pointer> filteredDataNodes;
if ("Image" == m_SelectedNodeType)
{
filteredDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSpecificImages(m_CaseID, currentControlPoint, currentInformationType);
}
else if ("Segmentation" == m_SelectedNodeType)
{
filteredDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSpecificSegmentations(m_CaseID, currentControlPoint, currentInformationType);
}
if (filteredDataNodes.empty())
{
// try next control point
continue;
}
else
{
// found a specific image
return filteredDataNodes.front();
}
}
catch (const mitk::SemanticRelationException&)
{
return nullptr;
}
}
// could not find a specif image
return nullptr;
}
<commit_msg>Make empty place holder pixmap transparent<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.
===================================================================*/
// semantic relations UI module
#include "QmitkPatientTableModel.h"
#include "QmitkPatientTableHeaderView.h"
#include "QmitkSemanticRelationsUIHelper.h"
// semantic relations module
#include <mitkControlPointManager.h>
#include <mitkNodePredicates.h>
#include <mitkSemanticRelationException.h>
#include <mitkSemanticRelationsInference.h>
#include <mitkRelationStorage.h>
#include <QmitkCustomVariants.h>
#include <QmitkEnums.h>
// qt
#include <QColor>
// c++
#include <iostream>
#include <string>
QmitkPatientTableModel::QmitkPatientTableModel(QObject* parent /*= nullptr*/)
: QmitkAbstractSemanticRelationsStorageModel(parent)
, m_SelectedNodeType("Image")
{
m_HeaderModel = new QStandardItemModel(this);
}
QmitkPatientTableModel::~QmitkPatientTableModel()
{
// nothing here
}
QModelIndex QmitkPatientTableModel::index(int row, int column, const QModelIndex& parent/* = QModelIndex()*/) const
{
if (hasIndex(row, column, parent))
{
return createIndex(row, column);
}
return QModelIndex();
}
QModelIndex QmitkPatientTableModel::parent(const QModelIndex& /*child*/) const
{
return QModelIndex();
}
int QmitkPatientTableModel::rowCount(const QModelIndex& parent/* = QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return m_InformationTypes.size();
}
int QmitkPatientTableModel::columnCount(const QModelIndex& parent/* = QModelIndex()*/) const
{
if (parent.isValid())
{
return 0;
}
return m_ExaminationPeriods.size();
}
QVariant QmitkPatientTableModel::data(const QModelIndex& index, int role/* = Qt::DisplayRole*/) const
{
// special role for returning the horizontal header
if (QmitkPatientTableHeaderView::HorizontalHeaderDataRole == role)
{
return QVariant::fromValue<QStandardItemModel*>(m_HeaderModel);
}
if (!index.isValid())
{
return QVariant();
}
if (index.row() < 0 || index.row() >= static_cast<int>(m_InformationTypes.size())
|| index.column() < 0 || index.column() >= static_cast<int>(m_ExaminationPeriods.size()))
{
return QVariant();
}
mitk::DataNode* dataNode = GetCurrentDataNode(index);
if (Qt::DecorationRole == role)
{
auto it = m_PixmapMap.find(dataNode);
if (it != m_PixmapMap.end())
{
return QVariant(it->second);
}
auto emptyPixmap = QPixmap(120, 120);
emptyPixmap.fill(Qt::transparent);
return emptyPixmap;
}
if (Qt::BackgroundColorRole == role)
{
auto it = m_LesionPresence.find(dataNode);
if (it != m_LesionPresence.end())
{
return it->second ? QVariant(QColor(Qt::darkGreen)) : QVariant(QColor(Qt::transparent));
}
return QVariant(QColor(Qt::transparent));
}
if (QmitkDataNodeRole == role)
{
return QVariant::fromValue<mitk::DataNode::Pointer>(mitk::DataNode::Pointer(dataNode));
}
if (QmitkDataNodeRawPointerRole == role)
{
return QVariant::fromValue<mitk::DataNode*>(dataNode);
}
return QVariant();
}
QVariant QmitkPatientTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (Qt::Vertical == orientation && Qt::DisplayRole == role)
{
if (static_cast<int>(m_InformationTypes.size()) > section)
{
mitk::SemanticTypes::InformationType currentInformationType = m_InformationTypes.at(section);
return QVariant(QString::fromStdString(currentInformationType));
}
}
return QVariant();
}
Qt::ItemFlags QmitkPatientTableModel::flags(const QModelIndex& index) const
{
Qt::ItemFlags flags;
mitk::DataNode* dataNode = GetCurrentDataNode(index);
if (nullptr != dataNode)
{
flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
return flags;
}
void QmitkPatientTableModel::SetNodeType(const std::string& nodeType)
{
m_SelectedNodeType = nodeType;
UpdateModelData();
}
void QmitkPatientTableModel::NodePredicateChanged()
{
UpdateModelData();
}
void QmitkPatientTableModel::SetData()
{
// get all examination periods of current case
m_ExaminationPeriods = mitk::RelationStorage::GetAllExaminationPeriodsOfCase(m_CaseID);
// sort all examination periods for the timeline
mitk::SortAllExaminationPeriods(m_CaseID, m_ExaminationPeriods);
// rename examination periods according to their new order
std::string examinationPeriodName = "Baseline";
for (int i = 0; i < m_ExaminationPeriods.size(); ++i)
{
auto& examinationPeriod = m_ExaminationPeriods.at(i);
examinationPeriod.name = examinationPeriodName;
mitk::RelationStorage::RenameExaminationPeriod(m_CaseID, examinationPeriod);
examinationPeriodName = "Follow-up " + std::to_string(i);
}
// get all information types points of current case
m_InformationTypes = mitk::RelationStorage::GetAllInformationTypesOfCase(m_CaseID);
if ("Image" == m_SelectedNodeType)
{
m_CurrentDataNodes = m_SemanticRelationsDataStorageAccess->GetAllImagesOfCase(m_CaseID);
}
else if ("Segmentation" == m_SelectedNodeType)
{
m_CurrentDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSegmentationsOfCase(m_CaseID);
}
SetHeaderModel();
SetPixmaps();
SetLesionPresences();
}
void QmitkPatientTableModel::SetHeaderModel()
{
m_HeaderModel->clear();
QStandardItem* rootItem = new QStandardItem("Timeline");
QList<QStandardItem*> standardItems;
for (const auto& examinationPeriod : m_ExaminationPeriods)
{
QStandardItem* examinationPeriodItem = new QStandardItem(QString::fromStdString(examinationPeriod.name));
standardItems.push_back(examinationPeriodItem);
rootItem->appendColumn(standardItems);
standardItems.clear();
}
m_HeaderModel->setItem(0, 0, rootItem);
}
void QmitkPatientTableModel::SetPixmaps()
{
m_PixmapMap.clear();
for (const auto& dataNode : m_CurrentDataNodes)
{
// set the pixmap for the current node
QPixmap pixmapFromImage = QmitkSemanticRelationsUIHelper::GetPixmapFromImageNode(dataNode);
SetPixmapOfNode(dataNode, &pixmapFromImage);
}
}
void QmitkPatientTableModel::SetPixmapOfNode(const mitk::DataNode* dataNode, QPixmap* pixmapFromImage)
{
if (nullptr == dataNode)
{
return;
}
std::map<mitk::DataNode::ConstPointer, QPixmap>::iterator iter = m_PixmapMap.find(dataNode);
if (iter != m_PixmapMap.end())
{
// key already existing
if (nullptr != pixmapFromImage)
{
// overwrite already stored pixmap
iter->second = pixmapFromImage->scaled(120, 120, Qt::IgnoreAspectRatio);
}
else
{
// remove key if no pixmap is given
m_PixmapMap.erase(iter);
}
}
else
{
m_PixmapMap.insert(std::make_pair(dataNode, pixmapFromImage->scaled(120, 120, Qt::IgnoreAspectRatio)));
}
}
void QmitkPatientTableModel::SetLesionPresences()
{
m_LesionPresence.clear();
if (!mitk::SemanticRelationsInference::InstanceExists(m_CaseID, m_Lesion))
{
return;
}
for (const auto& dataNode : m_CurrentDataNodes)
{
if (!mitk::SemanticRelationsInference::InstanceExists(dataNode))
{
continue;
}
// set the lesion presence for the current node
bool lesionPresence = mitk::SemanticRelationsInference::IsLesionPresent(m_Lesion, dataNode);
SetLesionPresenceOfNode(dataNode, lesionPresence);
}
}
void QmitkPatientTableModel::SetLesionPresenceOfNode(const mitk::DataNode* dataNode, bool lesionPresence)
{
std::map<mitk::DataNode::ConstPointer, bool>::iterator iter = m_LesionPresence.find(dataNode);
if (iter != m_LesionPresence.end())
{
// key already existing, overwrite already stored bool value
iter->second = lesionPresence;
}
else
{
m_LesionPresence.insert(std::make_pair(dataNode, lesionPresence));
}
}
mitk::DataNode* QmitkPatientTableModel::GetCurrentDataNode(const QModelIndex& index) const
{
if (!index.isValid())
{
return nullptr;
}
auto examinationPeriod = m_ExaminationPeriods.at(index.column());
auto currentInformationType = m_InformationTypes.at(index.row());
auto controlPointsOfExaminationPeriod = examinationPeriod.controlPointUIDs;
for (const auto& controlPointUID : controlPointsOfExaminationPeriod)
{
auto currentControlPoint = mitk::GetControlPointByUID(m_CaseID, controlPointUID);
try
{
std::vector<mitk::DataNode::Pointer> filteredDataNodes;
if ("Image" == m_SelectedNodeType)
{
filteredDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSpecificImages(m_CaseID, currentControlPoint, currentInformationType);
}
else if ("Segmentation" == m_SelectedNodeType)
{
filteredDataNodes = m_SemanticRelationsDataStorageAccess->GetAllSpecificSegmentations(m_CaseID, currentControlPoint, currentInformationType);
}
if (filteredDataNodes.empty())
{
// try next control point
continue;
}
else
{
// found a specific image
return filteredDataNodes.front();
}
}
catch (const mitk::SemanticRelationException&)
{
return nullptr;
}
}
// could not find a specif image
return nullptr;
}
<|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 Qt Creator.
**
** 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.
**
****************************************************************************/
#include "abstractprocessstep.h"
#include "buildconfiguration.h"
#include "buildstep.h"
#include "ioutputparser.h"
#include "project.h"
#include "target.h"
#include "task.h"
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QEventLoop>
#include <QTimer>
#include <QDir>
using namespace ProjectExplorer;
/*!
\class ProjectExplorer::AbstractProcessStep
\brief A convenience class, which can be used as a base class instead of BuildStep.
It should be used as a base class if your buildstep just needs to run a process.
Usage:
\list
\li Use processParameters() to configure the process you want to run
(you need to do that before calling AbstractProcessStep::init()).
\li Inside YourBuildStep::init() call AbstractProcessStep::init().
\li Inside YourBuildStep::run() call AbstractProcessStep::run(), which automatically starts the process
and by default adds the output on stdOut and stdErr to the OutputWindow.
\li If you need to process the process output override stdOut() and/or stdErr.
\endlist
The two functions processStarted() and processFinished() are called after starting/finishing the process.
By default they add a message to the output window.
Use setEnabled() to control whether the BuildStep needs to run. (A disabled BuildStep immediately returns true,
from the run function.)
\sa ProjectExplorer::ProcessParameters
*/
/*!
\fn void ProjectExplorer::AbstractProcessStep::setEnabled(bool b)
\brief Enables or disables a BuildStep.
Disabled BuildSteps immediately return true from their run method.
Should be called from init()
*/
/*!
\fn ProcessParameters *ProjectExplorer::AbstractProcessStep::processParameters()
\brief Obtain a reference to the parameters for the actual process to run.
Should be used in init()
*/
AbstractProcessStep::AbstractProcessStep(BuildStepList *bsl, const Core::Id id) :
BuildStep(bsl, id), m_timer(0), m_futureInterface(0),
m_ignoreReturnValue(false), m_process(0),
m_eventLoop(0), m_outputParserChain(0)
{
}
AbstractProcessStep::AbstractProcessStep(BuildStepList *bsl,
AbstractProcessStep *bs) :
BuildStep(bsl, bs), m_timer(0), m_futureInterface(0),
m_ignoreReturnValue(bs->m_ignoreReturnValue),
m_process(0), m_eventLoop(0), m_outputParserChain(0)
{
}
AbstractProcessStep::~AbstractProcessStep()
{
delete m_process;
delete m_timer;
// do not delete m_futureInterface, we do not own it.
delete m_outputParserChain;
}
/*!
\brief Delete all existing output parsers and start a new chain with the
given parser.
Derived classes need to call this function.
*/
void AbstractProcessStep::setOutputParser(ProjectExplorer::IOutputParser *parser)
{
delete m_outputParserChain;
m_outputParserChain = parser;
if (m_outputParserChain) {
connect(parser, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)),
this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat)));
connect(parser, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)));
}
}
/*!
\brief Append the given output parser to the existing chain of parsers.
*/
void AbstractProcessStep::appendOutputParser(ProjectExplorer::IOutputParser *parser)
{
if (!parser)
return;
QTC_ASSERT(m_outputParserChain, return);
m_outputParserChain->appendOutputParser(parser);
return;
}
ProjectExplorer::IOutputParser *AbstractProcessStep::outputParser() const
{
return m_outputParserChain;
}
bool AbstractProcessStep::ignoreReturnValue()
{
return m_ignoreReturnValue;
}
/*!
\brief If ignoreReturnValue is set to true, then the abstractprocess step will
return success even if the return value indicates otherwise.
Should be called from init.
*/
void AbstractProcessStep::setIgnoreReturnValue(bool b)
{
m_ignoreReturnValue = b;
}
/*!
\brief Reimplemented from BuildStep::init(). You need to call this from
YourBuildStep::init()
*/
bool AbstractProcessStep::init()
{
return true;
}
/*!
\brief Reimplemented from BuildStep::init(). You need to call this from YourBuildStep::run()
*/
void AbstractProcessStep::run(QFutureInterface<bool> &fi)
{
m_futureInterface = &fi;
QDir wd(m_param.effectiveWorkingDirectory());
if (!wd.exists())
wd.mkpath(wd.absolutePath());
m_process = new Utils::QtcProcess();
#ifdef Q_OS_WIN
m_process->setUseCtrlCStub(true);
#endif
m_process->setWorkingDirectory(wd.absolutePath());
m_process->setEnvironment(m_param.environment());
connect(m_process, SIGNAL(readyReadStandardOutput()),
this, SLOT(processReadyReadStdOutput()),
Qt::DirectConnection);
connect(m_process, SIGNAL(readyReadStandardError()),
this, SLOT(processReadyReadStdError()),
Qt::DirectConnection);
connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
this, SLOT(slotProcessFinished(int,QProcess::ExitStatus)),
Qt::DirectConnection);
m_process->setCommand(m_param.effectiveCommand(), m_param.effectiveArguments());
m_process->start();
if (!m_process->waitForStarted()) {
processStartupFailed();
delete m_process;
m_process = 0;
fi.reportResult(false);
return;
}
processStarted();
m_timer = new QTimer();
connect(m_timer, SIGNAL(timeout()), this, SLOT(checkForCancel()), Qt::DirectConnection);
m_timer->start(500);
m_eventLoop = new QEventLoop;
m_eventLoop->exec();
m_timer->stop();
delete m_timer;
m_timer = 0;
// The process has finished, leftover data is read in processFinished
processFinished(m_process->exitCode(), m_process->exitStatus());
bool returnValue = processSucceeded(m_process->exitCode(), m_process->exitStatus()) || m_ignoreReturnValue;
// Clean up output parsers
if (m_outputParserChain) {
delete m_outputParserChain;
m_outputParserChain = 0;
}
delete m_process;
m_process = 0;
delete m_eventLoop;
m_eventLoop = 0;
fi.reportResult(returnValue);
m_futureInterface = 0;
return;
}
/*!
\brief Called after the process is started.
The default implementation adds a process started message to the output message
*/
void AbstractProcessStep::processStarted()
{
emit addOutput(tr("Starting: \"%1\" %2")
.arg(QDir::toNativeSeparators(m_param.effectiveCommand()),
m_param.prettyArguments()),
BuildStep::MessageOutput);
}
/*!
\brief Called after the process Finished.
The default implementation adds a line to the output window
*/
void AbstractProcessStep::processFinished(int exitCode, QProcess::ExitStatus status)
{
QString command = QDir::toNativeSeparators(m_param.effectiveCommand());
if (status == QProcess::NormalExit && exitCode == 0) {
emit addOutput(tr("The process \"%1\" exited normally.").arg(command),
BuildStep::MessageOutput);
} else if (status == QProcess::NormalExit) {
emit addOutput(tr("The process \"%1\" exited with code %2.")
.arg(command, QString::number(m_process->exitCode())),
BuildStep::ErrorMessageOutput);
} else {
emit addOutput(tr("The process \"%1\" crashed.").arg(command), BuildStep::ErrorMessageOutput);
}
}
/*!
\brief Called if the process could not be started.
By default adds a message to the output window.
*/
void AbstractProcessStep::processStartupFailed()
{
emit addOutput(tr("Could not start process \"%1\" %2")
.arg(QDir::toNativeSeparators(m_param.effectiveCommand()),
m_param.prettyArguments()),
BuildStep::ErrorMessageOutput);
}
/*!
\brief Called to test whether a prcess succeeded or not.
*/
bool AbstractProcessStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
{
return exitCode == 0 && status == QProcess::NormalExit;
}
void AbstractProcessStep::processReadyReadStdOutput()
{
m_process->setReadChannel(QProcess::StandardOutput);
while (m_process->canReadLine()) {
QString line = QString::fromLocal8Bit(m_process->readLine());
stdOutput(line);
}
}
/*!
\brief Called for each line of output on stdOut().
The default implementation adds the line to the application output window.
*/
void AbstractProcessStep::stdOutput(const QString &line)
{
if (m_outputParserChain)
m_outputParserChain->stdOutput(line);
emit addOutput(line, BuildStep::NormalOutput, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::processReadyReadStdError()
{
m_process->setReadChannel(QProcess::StandardError);
while (m_process->canReadLine()) {
QString line = QString::fromLocal8Bit(m_process->readLine());
stdError(line);
}
}
/*!
\brief Called for each line of output on StdErrror().
The default implementation adds the line to the application output window
*/
void AbstractProcessStep::stdError(const QString &line)
{
if (m_outputParserChain)
m_outputParserChain->stdError(line);
emit addOutput(line, BuildStep::ErrorOutput, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::checkForCancel()
{
if (m_futureInterface->isCanceled() && m_timer->isActive()) {
m_timer->stop();
m_process->terminate();
m_process->waitForFinished(5000);
m_process->kill();
}
}
void AbstractProcessStep::taskAdded(const ProjectExplorer::Task &task)
{
// Do not bother to report issues if we do not care about the results of
// the buildstep anyway:
if (m_ignoreReturnValue)
return;
Task editable(task);
QString filePath = task.file.toString();
if (!filePath.isEmpty() && !QDir::isAbsolutePath(filePath)) {
// We have no save way to decide which file in which subfolder
// is meant. Therefore we apply following heuristics:
// 1. Check if file is unique in whole project
// 2. Otherwise try again without any ../
// 3. give up.
QList<QFileInfo> possibleFiles;
QString fileName = QFileInfo(filePath).fileName();
foreach (const QString &file, project()->files(ProjectExplorer::Project::AllFiles)) {
QFileInfo candidate(file);
if (candidate.fileName() == fileName)
possibleFiles << candidate;
}
if (possibleFiles.count() == 1) {
editable.file = Utils::FileName(possibleFiles.first());
} else {
// More then one filename, so do a better compare
// Chop of any "../"
while (filePath.startsWith(QLatin1String("../")))
filePath.remove(0, 3);
int count = 0;
QString possibleFilePath;
foreach (const QFileInfo &fi, possibleFiles) {
if (fi.filePath().endsWith(filePath)) {
possibleFilePath = fi.filePath();
++count;
}
}
if (count == 1)
editable.file = Utils::FileName::fromString(possibleFilePath);
else
qWarning() << "Could not find absolute location of file " << filePath;
}
}
emit addTask(editable);
}
void AbstractProcessStep::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format)
{
emit addOutput(string, format, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::slotProcessFinished(int, QProcess::ExitStatus)
{
QString line = QString::fromLocal8Bit(m_process->readAllStandardError());
if (!line.isEmpty())
stdError(line);
line = QString::fromLocal8Bit(m_process->readAllStandardOutput());
if (!line.isEmpty())
stdOutput(line);
m_eventLoop->exit(0);
}
<commit_msg>OutputParser: Use AnsiFilterParser<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
****************************************************************************/
#include "abstractprocessstep.h"
#include "ansifilterparser.h"
#include "buildconfiguration.h"
#include "buildstep.h"
#include "ioutputparser.h"
#include "project.h"
#include "target.h"
#include "task.h"
#include <utils/qtcassert.h>
#include <utils/qtcprocess.h>
#include <QEventLoop>
#include <QTimer>
#include <QDir>
using namespace ProjectExplorer;
/*!
\class ProjectExplorer::AbstractProcessStep
\brief A convenience class, which can be used as a base class instead of BuildStep.
It should be used as a base class if your buildstep just needs to run a process.
Usage:
\list
\li Use processParameters() to configure the process you want to run
(you need to do that before calling AbstractProcessStep::init()).
\li Inside YourBuildStep::init() call AbstractProcessStep::init().
\li Inside YourBuildStep::run() call AbstractProcessStep::run(), which automatically starts the process
and by default adds the output on stdOut and stdErr to the OutputWindow.
\li If you need to process the process output override stdOut() and/or stdErr.
\endlist
The two functions processStarted() and processFinished() are called after starting/finishing the process.
By default they add a message to the output window.
Use setEnabled() to control whether the BuildStep needs to run. (A disabled BuildStep immediately returns true,
from the run function.)
\sa ProjectExplorer::ProcessParameters
*/
/*!
\fn void ProjectExplorer::AbstractProcessStep::setEnabled(bool b)
\brief Enables or disables a BuildStep.
Disabled BuildSteps immediately return true from their run method.
Should be called from init()
*/
/*!
\fn ProcessParameters *ProjectExplorer::AbstractProcessStep::processParameters()
\brief Obtain a reference to the parameters for the actual process to run.
Should be used in init()
*/
AbstractProcessStep::AbstractProcessStep(BuildStepList *bsl, const Core::Id id) :
BuildStep(bsl, id), m_timer(0), m_futureInterface(0),
m_ignoreReturnValue(false), m_process(0),
m_eventLoop(0), m_outputParserChain(0)
{
}
AbstractProcessStep::AbstractProcessStep(BuildStepList *bsl,
AbstractProcessStep *bs) :
BuildStep(bsl, bs), m_timer(0), m_futureInterface(0),
m_ignoreReturnValue(bs->m_ignoreReturnValue),
m_process(0), m_eventLoop(0), m_outputParserChain(0)
{
}
AbstractProcessStep::~AbstractProcessStep()
{
delete m_process;
delete m_timer;
// do not delete m_futureInterface, we do not own it.
delete m_outputParserChain;
}
/*!
\brief Delete all existing output parsers and start a new chain with the
given parser.
Derived classes need to call this function.
*/
void AbstractProcessStep::setOutputParser(ProjectExplorer::IOutputParser *parser)
{
delete m_outputParserChain;
m_outputParserChain = new AnsiFilterParser;
m_outputParserChain->appendOutputParser(parser);
if (m_outputParserChain) {
connect(m_outputParserChain, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat)),
this, SLOT(outputAdded(QString,ProjectExplorer::BuildStep::OutputFormat)));
connect(m_outputParserChain, SIGNAL(addTask(ProjectExplorer::Task)),
this, SLOT(taskAdded(ProjectExplorer::Task)));
}
}
/*!
\brief Append the given output parser to the existing chain of parsers.
*/
void AbstractProcessStep::appendOutputParser(ProjectExplorer::IOutputParser *parser)
{
if (!parser)
return;
QTC_ASSERT(m_outputParserChain, return);
m_outputParserChain->appendOutputParser(parser);
return;
}
ProjectExplorer::IOutputParser *AbstractProcessStep::outputParser() const
{
return m_outputParserChain;
}
bool AbstractProcessStep::ignoreReturnValue()
{
return m_ignoreReturnValue;
}
/*!
\brief If ignoreReturnValue is set to true, then the abstractprocess step will
return success even if the return value indicates otherwise.
Should be called from init.
*/
void AbstractProcessStep::setIgnoreReturnValue(bool b)
{
m_ignoreReturnValue = b;
}
/*!
\brief Reimplemented from BuildStep::init(). You need to call this from
YourBuildStep::init()
*/
bool AbstractProcessStep::init()
{
return true;
}
/*!
\brief Reimplemented from BuildStep::init(). You need to call this from YourBuildStep::run()
*/
void AbstractProcessStep::run(QFutureInterface<bool> &fi)
{
m_futureInterface = &fi;
QDir wd(m_param.effectiveWorkingDirectory());
if (!wd.exists())
wd.mkpath(wd.absolutePath());
m_process = new Utils::QtcProcess();
#ifdef Q_OS_WIN
m_process->setUseCtrlCStub(true);
#endif
m_process->setWorkingDirectory(wd.absolutePath());
m_process->setEnvironment(m_param.environment());
connect(m_process, SIGNAL(readyReadStandardOutput()),
this, SLOT(processReadyReadStdOutput()),
Qt::DirectConnection);
connect(m_process, SIGNAL(readyReadStandardError()),
this, SLOT(processReadyReadStdError()),
Qt::DirectConnection);
connect(m_process, SIGNAL(finished(int,QProcess::ExitStatus)),
this, SLOT(slotProcessFinished(int,QProcess::ExitStatus)),
Qt::DirectConnection);
m_process->setCommand(m_param.effectiveCommand(), m_param.effectiveArguments());
m_process->start();
if (!m_process->waitForStarted()) {
processStartupFailed();
delete m_process;
m_process = 0;
fi.reportResult(false);
return;
}
processStarted();
m_timer = new QTimer();
connect(m_timer, SIGNAL(timeout()), this, SLOT(checkForCancel()), Qt::DirectConnection);
m_timer->start(500);
m_eventLoop = new QEventLoop;
m_eventLoop->exec();
m_timer->stop();
delete m_timer;
m_timer = 0;
// The process has finished, leftover data is read in processFinished
processFinished(m_process->exitCode(), m_process->exitStatus());
bool returnValue = processSucceeded(m_process->exitCode(), m_process->exitStatus()) || m_ignoreReturnValue;
// Clean up output parsers
if (m_outputParserChain) {
delete m_outputParserChain;
m_outputParserChain = 0;
}
delete m_process;
m_process = 0;
delete m_eventLoop;
m_eventLoop = 0;
fi.reportResult(returnValue);
m_futureInterface = 0;
return;
}
/*!
\brief Called after the process is started.
The default implementation adds a process started message to the output message
*/
void AbstractProcessStep::processStarted()
{
emit addOutput(tr("Starting: \"%1\" %2")
.arg(QDir::toNativeSeparators(m_param.effectiveCommand()),
m_param.prettyArguments()),
BuildStep::MessageOutput);
}
/*!
\brief Called after the process Finished.
The default implementation adds a line to the output window
*/
void AbstractProcessStep::processFinished(int exitCode, QProcess::ExitStatus status)
{
QString command = QDir::toNativeSeparators(m_param.effectiveCommand());
if (status == QProcess::NormalExit && exitCode == 0) {
emit addOutput(tr("The process \"%1\" exited normally.").arg(command),
BuildStep::MessageOutput);
} else if (status == QProcess::NormalExit) {
emit addOutput(tr("The process \"%1\" exited with code %2.")
.arg(command, QString::number(m_process->exitCode())),
BuildStep::ErrorMessageOutput);
} else {
emit addOutput(tr("The process \"%1\" crashed.").arg(command), BuildStep::ErrorMessageOutput);
}
}
/*!
\brief Called if the process could not be started.
By default adds a message to the output window.
*/
void AbstractProcessStep::processStartupFailed()
{
emit addOutput(tr("Could not start process \"%1\" %2")
.arg(QDir::toNativeSeparators(m_param.effectiveCommand()),
m_param.prettyArguments()),
BuildStep::ErrorMessageOutput);
}
/*!
\brief Called to test whether a prcess succeeded or not.
*/
bool AbstractProcessStep::processSucceeded(int exitCode, QProcess::ExitStatus status)
{
return exitCode == 0 && status == QProcess::NormalExit;
}
void AbstractProcessStep::processReadyReadStdOutput()
{
m_process->setReadChannel(QProcess::StandardOutput);
while (m_process->canReadLine()) {
QString line = QString::fromLocal8Bit(m_process->readLine());
stdOutput(line);
}
}
/*!
\brief Called for each line of output on stdOut().
The default implementation adds the line to the application output window.
*/
void AbstractProcessStep::stdOutput(const QString &line)
{
if (m_outputParserChain)
m_outputParserChain->stdOutput(line);
emit addOutput(line, BuildStep::NormalOutput, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::processReadyReadStdError()
{
m_process->setReadChannel(QProcess::StandardError);
while (m_process->canReadLine()) {
QString line = QString::fromLocal8Bit(m_process->readLine());
stdError(line);
}
}
/*!
\brief Called for each line of output on StdErrror().
The default implementation adds the line to the application output window
*/
void AbstractProcessStep::stdError(const QString &line)
{
if (m_outputParserChain)
m_outputParserChain->stdError(line);
emit addOutput(line, BuildStep::ErrorOutput, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::checkForCancel()
{
if (m_futureInterface->isCanceled() && m_timer->isActive()) {
m_timer->stop();
m_process->terminate();
m_process->waitForFinished(5000);
m_process->kill();
}
}
void AbstractProcessStep::taskAdded(const ProjectExplorer::Task &task)
{
// Do not bother to report issues if we do not care about the results of
// the buildstep anyway:
if (m_ignoreReturnValue)
return;
Task editable(task);
QString filePath = task.file.toString();
if (!filePath.isEmpty() && !QDir::isAbsolutePath(filePath)) {
// We have no save way to decide which file in which subfolder
// is meant. Therefore we apply following heuristics:
// 1. Check if file is unique in whole project
// 2. Otherwise try again without any ../
// 3. give up.
QList<QFileInfo> possibleFiles;
QString fileName = QFileInfo(filePath).fileName();
foreach (const QString &file, project()->files(ProjectExplorer::Project::AllFiles)) {
QFileInfo candidate(file);
if (candidate.fileName() == fileName)
possibleFiles << candidate;
}
if (possibleFiles.count() == 1) {
editable.file = Utils::FileName(possibleFiles.first());
} else {
// More then one filename, so do a better compare
// Chop of any "../"
while (filePath.startsWith(QLatin1String("../")))
filePath.remove(0, 3);
int count = 0;
QString possibleFilePath;
foreach (const QFileInfo &fi, possibleFiles) {
if (fi.filePath().endsWith(filePath)) {
possibleFilePath = fi.filePath();
++count;
}
}
if (count == 1)
editable.file = Utils::FileName::fromString(possibleFilePath);
else
qWarning() << "Could not find absolute location of file " << filePath;
}
}
emit addTask(editable);
}
void AbstractProcessStep::outputAdded(const QString &string, ProjectExplorer::BuildStep::OutputFormat format)
{
emit addOutput(string, format, BuildStep::DontAppendNewline);
}
void AbstractProcessStep::slotProcessFinished(int, QProcess::ExitStatus)
{
QString line = QString::fromLocal8Bit(m_process->readAllStandardError());
if (!line.isEmpty())
stdError(line);
line = QString::fromLocal8Bit(m_process->readAllStandardOutput());
if (!line.isEmpty())
stdOutput(line);
m_eventLoop->exit(0);
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "targetsettingspanel.h"
#include "addtargetdialog.h"
#include "buildsettingspropertiespage.h"
#include "project.h"
#include "projectwindow.h"
#include "runsettingspropertiespage.h"
#include "target.h"
#include "targetsettingswidget.h"
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QCoreApplication>
#include <QtGui/QLabel>
#include <QtGui/QMessageBox>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// TargetSettingsWidget
///
TargetSettingsPanelWidget::TargetSettingsPanelWidget(Project *project) :
m_currentTarget(0),
m_project(project),
m_selector(0),
m_centralWidget(0)
{
Q_ASSERT(m_project);
m_panelWidgets[0] = 0;
m_panelWidgets[1] = 0;
setupUi();
connect(m_project, SIGNAL(addedTarget(ProjectExplorer::Target*)),
this, SLOT(targetAdded(ProjectExplorer::Target*)));
connect(m_project, SIGNAL(removedTarget(ProjectExplorer::Target*)),
this, SLOT(removedTarget(ProjectExplorer::Target*)));
connect(m_project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
this, SLOT(activeTargetChanged(ProjectExplorer::Target*)));
connect(m_project, SIGNAL(supportedTargetIdsChanged()),
this, SLOT(updateTargetAddAndRemoveButtons()));
}
TargetSettingsPanelWidget::~TargetSettingsPanelWidget()
{
}
void TargetSettingsPanelWidget::setupUi()
{
QVBoxLayout *viewLayout = new QVBoxLayout(this);
viewLayout->setMargin(0);
viewLayout->setSpacing(0);
m_selector = new TargetSettingsWidget(this);
viewLayout->addWidget(m_selector);
// Setup our container for the contents:
m_centralWidget = new QStackedWidget(this);
m_selector->setCentralWidget(m_centralWidget);
// no projects label:
m_noTargetLabel = new QWidget;
QVBoxLayout *noTargetLayout = new QVBoxLayout;
noTargetLayout->setMargin(0);
QLabel *label = new QLabel(m_noTargetLabel);
label->setText(tr("No target defined."));
{
QFont f = label->font();
f.setPointSizeF(f.pointSizeF() * 1.4);
f.setBold(true);
label->setFont(f);
}
label->setMargin(10);
label->setAlignment(Qt::AlignTop);
noTargetLayout->addWidget(label);
noTargetLayout->addStretch(10);
m_centralWidget->addWidget(m_noTargetLabel);
connect(m_selector, SIGNAL(currentChanged(int,int)),
this, SLOT(currentTargetChanged(int,int)));
// Save active target now as it will change when targets are added:
Target *activeTarget = m_project->activeTarget();
foreach (Target *t, m_project->targets())
targetAdded(t);
connect(m_selector, SIGNAL(addButtonClicked()),
this, SLOT(addTarget()));
connect(m_selector, SIGNAL(removeButtonClicked()),
this, SLOT(removeTarget()));
updateTargetAddAndRemoveButtons();
// Restore target originally set:
m_project->setActiveTarget(activeTarget);
}
void TargetSettingsPanelWidget::currentTargetChanged(int targetIndex, int subIndex)
{
if (targetIndex < -1 || targetIndex >= m_targets.count())
return;
if (subIndex < -1 || subIndex >= 2)
return;
if (targetIndex == -1 || subIndex == -1) { // no more targets!
delete m_panelWidgets[0];
m_panelWidgets[0] = 0;
delete m_panelWidgets[1];
m_panelWidgets[1] = 0;
m_centralWidget->setCurrentWidget(m_noTargetLabel);
return;
}
Target *target = m_targets.at(targetIndex);
// Target was not actually changed:
if (m_currentTarget == target) {
if (m_panelWidgets[subIndex])
m_centralWidget->setCurrentWidget(m_panelWidgets[subIndex]);
else
m_centralWidget->setCurrentWidget(m_noTargetLabel);
return;
}
// Target has changed:
m_currentTarget = target;
PanelsWidget *buildPanel = new PanelsWidget(m_centralWidget);
PanelsWidget *runPanel = new PanelsWidget(m_centralWidget);
foreach (ITargetPanelFactory *panelFactory, ExtensionSystem::PluginManager::instance()->getObjects<ITargetPanelFactory>()) {
if (panelFactory->id() == QLatin1String(BUILDSETTINGS_PANEL_ID)) {
IPropertiesPanel *panel = panelFactory->createPanel(target);
buildPanel->addPropertiesPanel(panel);
continue;
}
if (panelFactory->id() == QLatin1String(RUNSETTINGS_PANEL_ID)) {
IPropertiesPanel *panel = panelFactory->createPanel(target);
runPanel->addPropertiesPanel(panel);
continue;
}
}
m_centralWidget->addWidget(buildPanel);
m_centralWidget->addWidget(runPanel);
m_centralWidget->setCurrentWidget(subIndex == 0 ? buildPanel : runPanel);
delete m_panelWidgets[0];
m_panelWidgets[0] = buildPanel;
delete m_panelWidgets[1];
m_panelWidgets[1] = runPanel;
m_project->setActiveTarget(target);
}
void TargetSettingsPanelWidget::addTarget()
{
AddTargetDialog dialog(m_project);
dialog.exec();
}
void TargetSettingsPanelWidget::removeTarget()
{
int index = m_selector->currentIndex();
Target *t = m_targets.at(index);
int ret = QMessageBox::warning(this, tr("Qt Creator"),
tr("Do you really want to remove the\n"
"\"%1\" target?").arg(t->displayName()),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret == QMessageBox::Yes)
m_project->removeTarget(t);
}
void TargetSettingsPanelWidget::targetAdded(ProjectExplorer::Target *target)
{
Q_ASSERT(m_project == target->project());
Q_ASSERT(m_selector);
for (int pos = 0; pos <= m_targets.count(); ++pos) {
if (m_targets.count() == pos ||
m_targets.at(pos)->displayName() > target->displayName()) {
m_targets.insert(pos, target);
m_selector->insertTarget(pos, target->displayName());
break;
}
}
updateTargetAddAndRemoveButtons();
}
void TargetSettingsPanelWidget::removedTarget(ProjectExplorer::Target *target)
{
Q_ASSERT(m_project == target->project());
Q_ASSERT(m_selector);
int index(m_targets.indexOf(target));
if (index < 0)
return;
m_targets.removeAt(index);
m_selector->removeTarget(index);
updateTargetAddAndRemoveButtons();
}
void TargetSettingsPanelWidget::activeTargetChanged(ProjectExplorer::Target *target)
{
Q_ASSERT(m_project == target->project());
Q_ASSERT(m_selector);
int index = m_targets.indexOf(target);
m_selector->setCurrentIndex(index);
}
void TargetSettingsPanelWidget::updateTargetAddAndRemoveButtons()
{
if (!m_selector)
return;
m_selector->setAddButtonEnabled(m_project->possibleTargetIds().count() > 0);
m_selector->setRemoveButtonEnabled(m_project->targets().count() > 1);
}
<commit_msg>Target selection in projects pane doesn't match active target at startup.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "targetsettingspanel.h"
#include "addtargetdialog.h"
#include "buildsettingspropertiespage.h"
#include "project.h"
#include "projectwindow.h"
#include "runsettingspropertiespage.h"
#include "target.h"
#include "targetsettingswidget.h"
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QCoreApplication>
#include <QtGui/QLabel>
#include <QtGui/QMessageBox>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// TargetSettingsWidget
///
TargetSettingsPanelWidget::TargetSettingsPanelWidget(Project *project) :
m_currentTarget(0),
m_project(project),
m_selector(0),
m_centralWidget(0)
{
Q_ASSERT(m_project);
m_panelWidgets[0] = 0;
m_panelWidgets[1] = 0;
setupUi();
connect(m_project, SIGNAL(addedTarget(ProjectExplorer::Target*)),
this, SLOT(targetAdded(ProjectExplorer::Target*)));
connect(m_project, SIGNAL(removedTarget(ProjectExplorer::Target*)),
this, SLOT(removedTarget(ProjectExplorer::Target*)));
connect(m_project, SIGNAL(activeTargetChanged(ProjectExplorer::Target*)),
this, SLOT(activeTargetChanged(ProjectExplorer::Target*)));
connect(m_project, SIGNAL(supportedTargetIdsChanged()),
this, SLOT(updateTargetAddAndRemoveButtons()));
}
TargetSettingsPanelWidget::~TargetSettingsPanelWidget()
{
}
void TargetSettingsPanelWidget::setupUi()
{
QVBoxLayout *viewLayout = new QVBoxLayout(this);
viewLayout->setMargin(0);
viewLayout->setSpacing(0);
m_selector = new TargetSettingsWidget(this);
viewLayout->addWidget(m_selector);
// Setup our container for the contents:
m_centralWidget = new QStackedWidget(this);
m_selector->setCentralWidget(m_centralWidget);
// no projects label:
m_noTargetLabel = new QWidget;
QVBoxLayout *noTargetLayout = new QVBoxLayout;
noTargetLayout->setMargin(0);
QLabel *label = new QLabel(m_noTargetLabel);
label->setText(tr("No target defined."));
{
QFont f = label->font();
f.setPointSizeF(f.pointSizeF() * 1.4);
f.setBold(true);
label->setFont(f);
}
label->setMargin(10);
label->setAlignment(Qt::AlignTop);
noTargetLayout->addWidget(label);
noTargetLayout->addStretch(10);
m_centralWidget->addWidget(m_noTargetLabel);
connect(m_selector, SIGNAL(currentChanged(int,int)),
this, SLOT(currentTargetChanged(int,int)));
// Save active target now as it will change when targets are added:
Target *activeTarget = m_project->activeTarget();
foreach (Target *t, m_project->targets())
targetAdded(t);
connect(m_selector, SIGNAL(addButtonClicked()),
this, SLOT(addTarget()));
connect(m_selector, SIGNAL(removeButtonClicked()),
this, SLOT(removeTarget()));
updateTargetAddAndRemoveButtons();
activeTargetChanged(activeTarget);
}
void TargetSettingsPanelWidget::currentTargetChanged(int targetIndex, int subIndex)
{
if (targetIndex < -1 || targetIndex >= m_targets.count())
return;
if (subIndex < -1 || subIndex >= 2)
return;
if (targetIndex == -1 || subIndex == -1) { // no more targets!
delete m_panelWidgets[0];
m_panelWidgets[0] = 0;
delete m_panelWidgets[1];
m_panelWidgets[1] = 0;
m_centralWidget->setCurrentWidget(m_noTargetLabel);
return;
}
Target *target = m_targets.at(targetIndex);
// Target was not actually changed:
if (m_currentTarget == target) {
if (m_panelWidgets[subIndex])
m_centralWidget->setCurrentWidget(m_panelWidgets[subIndex]);
else
m_centralWidget->setCurrentWidget(m_noTargetLabel);
return;
}
// Target has changed:
m_currentTarget = target;
PanelsWidget *buildPanel = new PanelsWidget(m_centralWidget);
PanelsWidget *runPanel = new PanelsWidget(m_centralWidget);
foreach (ITargetPanelFactory *panelFactory, ExtensionSystem::PluginManager::instance()->getObjects<ITargetPanelFactory>()) {
if (panelFactory->id() == QLatin1String(BUILDSETTINGS_PANEL_ID)) {
IPropertiesPanel *panel = panelFactory->createPanel(target);
buildPanel->addPropertiesPanel(panel);
continue;
}
if (panelFactory->id() == QLatin1String(RUNSETTINGS_PANEL_ID)) {
IPropertiesPanel *panel = panelFactory->createPanel(target);
runPanel->addPropertiesPanel(panel);
continue;
}
}
m_centralWidget->addWidget(buildPanel);
m_centralWidget->addWidget(runPanel);
m_centralWidget->setCurrentWidget(subIndex == 0 ? buildPanel : runPanel);
delete m_panelWidgets[0];
m_panelWidgets[0] = buildPanel;
delete m_panelWidgets[1];
m_panelWidgets[1] = runPanel;
m_project->setActiveTarget(target);
}
void TargetSettingsPanelWidget::addTarget()
{
AddTargetDialog dialog(m_project);
dialog.exec();
}
void TargetSettingsPanelWidget::removeTarget()
{
int index = m_selector->currentIndex();
Target *t = m_targets.at(index);
int ret = QMessageBox::warning(this, tr("Qt Creator"),
tr("Do you really want to remove the\n"
"\"%1\" target?").arg(t->displayName()),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (ret == QMessageBox::Yes)
m_project->removeTarget(t);
}
void TargetSettingsPanelWidget::targetAdded(ProjectExplorer::Target *target)
{
Q_ASSERT(m_project == target->project());
Q_ASSERT(m_selector);
for (int pos = 0; pos <= m_targets.count(); ++pos) {
if (m_targets.count() == pos ||
m_targets.at(pos)->displayName() > target->displayName()) {
m_targets.insert(pos, target);
m_selector->insertTarget(pos, target->displayName());
break;
}
}
updateTargetAddAndRemoveButtons();
}
void TargetSettingsPanelWidget::removedTarget(ProjectExplorer::Target *target)
{
Q_ASSERT(m_project == target->project());
Q_ASSERT(m_selector);
int index(m_targets.indexOf(target));
if (index < 0)
return;
m_targets.removeAt(index);
m_selector->removeTarget(index);
updateTargetAddAndRemoveButtons();
}
void TargetSettingsPanelWidget::activeTargetChanged(ProjectExplorer::Target *target)
{
Q_ASSERT(m_project == target->project());
Q_ASSERT(m_selector);
int index = m_targets.indexOf(target);
m_selector->setCurrentIndex(index);
}
void TargetSettingsPanelWidget::updateTargetAddAndRemoveButtons()
{
if (!m_selector)
return;
m_selector->setAddButtonEnabled(m_project->possibleTargetIds().count() > 0);
m_selector->setRemoveButtonEnabled(m_project->targets().count() > 1);
}
<|endoftext|> |
<commit_before>
#include "util/thread.hpp"
#include "gc/managed.hpp"
namespace rubinius {
class WorldState {
thread::Mutex mutex_;
thread::Condition waiting_to_stop_;
thread::Condition waiting_to_run_;
int pending_threads_;
bool should_stop_;
atomic::integer time_waiting_;
public:
WorldState()
: pending_threads_(0)
, should_stop_(false)
, time_waiting_(0)
{}
uint64_t time_waiting() {
return time_waiting_.read();
}
/**
* Called after a fork(), when we know we're alone again, to get
* everything back in the proper order.
*/
void reinit() {
mutex_.init();
waiting_to_stop_.init();
waiting_to_run_.init();
pending_threads_ = 0;
should_stop_ = false;
}
/**
* If called when the GC is waiting to run, wait until the GC tells us its
* OK to continue. Always decrements pending_threads_ at the end.
*/
void become_independent(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
switch(state->run_state()) {
case ManagedThread::eAlone:
// Running alone, ignore.
return;
case ManagedThread::eIndependent:
// Already independent, ignore.
return;
case ManagedThread::eSuspended:
// This is sort of bad. We're already suspended
// and want to go independent. Abort on this.
rubinius::bug("Trying to make a suspended thread independent");
break;
case ManagedThread::eRunning:
// If someone is waiting on us to stop, stop now.
if(should_stop_) wait_to_run(state);
// We're now independent.
state->run_state_ = ManagedThread::eIndependent;
pending_threads_--;
break;
}
}
void become_dependent(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
switch(state->run_state()) {
case ManagedThread::eAlone:
// Running alone, ignore.
return;
case ManagedThread::eRunning:
// Ignore this, a running thread is already dependent.
return;
case ManagedThread::eSuspended:
// Again, bad, don't allow this.
rubinius::bug("Trying to make a suspended thread dependent");
break;
case ManagedThread::eIndependent:
// If the GC is running, wait here...
while(should_stop_) {
waiting_to_run_.wait(mutex_);
}
// Ok, we're running again.
state->run_state_ = ManagedThread::eRunning;
pending_threads_++;
}
}
bool wait_til_alone(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
if(should_stop_) {
if(cDebugThreading) {
std::cerr << "[" << VM::current()
<< " WORLD detected concurrent stop request, returning false]\n";
}
return false;
}
should_stop_ = true;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waiting until alone]\n";
}
if(state->run_state_ != ManagedThread::eRunning) {
rubinius::bug("A non-running thread is trying to wait till alone");
}
// For ourself..
pending_threads_--;
timer::Running<> timer(time_waiting_);
while(pending_threads_ > 0) {
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waiting on condvar: "
<< pending_threads_ << "]\n";
}
waiting_to_stop_.wait(mutex_);
}
state->run_state_ = ManagedThread::eAlone;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD o/~ I think we're alone now.. o/~]\n";
}
return true;
}
void stop_threads_externally() {
thread::Mutex::LockGuard guard(mutex_);
if(should_stop_) {
if(cDebugThreading) {
std::cerr << "[WORLD waiting to stopping all threads (as external event)]\n";
}
// Wait around on the run condition variable until whoever is currently
// working independently is done and sets should_stop_ to false.
while(should_stop_) {
waiting_to_run_.wait(mutex_);
}
// Ok, now we can stop all the threads for ourself.
}
should_stop_ = true;
if(cDebugThreading) {
std::cerr << "[WORLD stopping all threads (as external event)]\n";
}
while(pending_threads_ > 0) {
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waiting on condvar: "
<< pending_threads_ << "]\n";
}
waiting_to_stop_.wait(mutex_);
}
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD o/~ I think we're alone now.. o/~]\n";
}
}
void wake_all_waiters(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
should_stop_ = false;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waking all threads]\n";
}
if(state->run_state_ != ManagedThread::eAlone) {
rubinius::bug("A non-alone thread is trying to wake all");
}
// For ourself..
pending_threads_++;
waiting_to_run_.broadcast();
state->run_state_ = ManagedThread::eRunning;
}
void restart_threads_externally() {
thread::Mutex::LockGuard guard(mutex_);
should_stop_ = false;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waking all threads (externally)]\n";
}
waiting_to_run_.broadcast();
}
bool should_stop() {
thread::Mutex::LockGuard guard(mutex_);
return should_stop_;
}
bool checkpoint(THREAD) {
// Test should_stop_ without the lock, because we do this a lot.
if(should_stop_) {
thread::Mutex::LockGuard guard(mutex_);
// If the thread is set to alone, then ignore checkpointing
if(state->run_state() == ManagedThread::eAlone) return false;
if(should_stop_) wait_to_run(state);
return true;
}
return false;
}
private:
void wait_to_run(THREAD) {
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD stopping, waiting to be restarted]\n";
}
if(state->run_state_ != ManagedThread::eRunning) {
rubinius::bug("Suspending a non running thread!");
}
state->run_state_ = ManagedThread::eSuspended;
pending_threads_--;
waiting_to_stop_.signal();
while(should_stop_) {
waiting_to_run_.wait(mutex_);
}
pending_threads_++;
state->run_state_ = ManagedThread::eRunning;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD restarted]\n";
}
}
};
}
<commit_msg>Simplify signaling logic when going independent<commit_after>
#include "util/thread.hpp"
#include "gc/managed.hpp"
namespace rubinius {
class WorldState {
thread::Mutex mutex_;
thread::Condition waiting_to_stop_;
thread::Condition waiting_to_run_;
int pending_threads_;
bool should_stop_;
atomic::integer time_waiting_;
public:
WorldState()
: pending_threads_(0)
, should_stop_(false)
, time_waiting_(0)
{}
uint64_t time_waiting() {
return time_waiting_.read();
}
/**
* Called after a fork(), when we know we're alone again, to get
* everything back in the proper order.
*/
void reinit() {
mutex_.init();
waiting_to_stop_.init();
waiting_to_run_.init();
pending_threads_ = 0;
should_stop_ = false;
}
/**
* If called when the GC is waiting to run, wait until the GC tells us its
* OK to continue. Always decrements pending_threads_ at the end.
*/
void become_independent(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
switch(state->run_state()) {
case ManagedThread::eAlone:
// Running alone, ignore.
return;
case ManagedThread::eIndependent:
// Already independent, ignore.
return;
case ManagedThread::eSuspended:
// This is sort of bad. We're already suspended
// and want to go independent. Abort on this.
rubinius::bug("Trying to make a suspended thread independent");
break;
case ManagedThread::eRunning:
// We're now independent.
state->run_state_ = ManagedThread::eIndependent;
pending_threads_--;
// If someone is waiting on us to stop, signal them
// because we have gone independent and they don't have to wait
// for us.
if(should_stop_) {
waiting_to_stop_.signal();
}
break;
}
}
void become_dependent(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
switch(state->run_state()) {
case ManagedThread::eAlone:
// Running alone, ignore.
return;
case ManagedThread::eRunning:
// Ignore this, a running thread is already dependent.
return;
case ManagedThread::eSuspended:
// Again, bad, don't allow this.
rubinius::bug("Trying to make a suspended thread dependent");
break;
case ManagedThread::eIndependent:
// If the GC is running, wait here...
while(should_stop_) {
waiting_to_run_.wait(mutex_);
}
// Ok, we're running again.
state->run_state_ = ManagedThread::eRunning;
pending_threads_++;
}
}
bool wait_til_alone(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
if(should_stop_) {
if(cDebugThreading) {
std::cerr << "[" << VM::current()
<< " WORLD detected concurrent stop request, returning false]\n";
}
return false;
}
should_stop_ = true;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waiting until alone]\n";
}
if(state->run_state_ != ManagedThread::eRunning) {
rubinius::bug("A non-running thread is trying to wait till alone");
}
// For ourself..
pending_threads_--;
timer::Running<> timer(time_waiting_);
while(pending_threads_ > 0) {
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waiting on condvar: "
<< pending_threads_ << "]\n";
}
waiting_to_stop_.wait(mutex_);
}
state->run_state_ = ManagedThread::eAlone;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD o/~ I think we're alone now.. o/~]\n";
}
return true;
}
void stop_threads_externally() {
thread::Mutex::LockGuard guard(mutex_);
if(should_stop_) {
if(cDebugThreading) {
std::cerr << "[WORLD waiting to stopping all threads (as external event)]\n";
}
// Wait around on the run condition variable until whoever is currently
// working independently is done and sets should_stop_ to false.
while(should_stop_) {
waiting_to_run_.wait(mutex_);
}
// Ok, now we can stop all the threads for ourself.
}
should_stop_ = true;
if(cDebugThreading) {
std::cerr << "[WORLD stopping all threads (as external event)]\n";
}
while(pending_threads_ > 0) {
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waiting on condvar: "
<< pending_threads_ << "]\n";
}
waiting_to_stop_.wait(mutex_);
}
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD o/~ I think we're alone now.. o/~]\n";
}
}
void wake_all_waiters(THREAD) {
thread::Mutex::LockGuard guard(mutex_);
should_stop_ = false;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waking all threads]\n";
}
if(state->run_state_ != ManagedThread::eAlone) {
rubinius::bug("A non-alone thread is trying to wake all");
}
// For ourself..
pending_threads_++;
waiting_to_run_.broadcast();
state->run_state_ = ManagedThread::eRunning;
}
void restart_threads_externally() {
thread::Mutex::LockGuard guard(mutex_);
should_stop_ = false;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD waking all threads (externally)]\n";
}
waiting_to_run_.broadcast();
}
bool should_stop() {
thread::Mutex::LockGuard guard(mutex_);
return should_stop_;
}
bool checkpoint(THREAD) {
// Test should_stop_ without the lock, because we do this a lot.
if(should_stop_) {
thread::Mutex::LockGuard guard(mutex_);
// If the thread is set to alone, then ignore checkpointing
if(state->run_state() == ManagedThread::eAlone) return false;
if(should_stop_) wait_to_run(state);
return true;
}
return false;
}
private:
void wait_to_run(THREAD) {
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD stopping, waiting to be restarted]\n";
}
if(state->run_state_ != ManagedThread::eRunning) {
rubinius::bug("Suspending a non running thread!");
}
state->run_state_ = ManagedThread::eSuspended;
pending_threads_--;
waiting_to_stop_.signal();
while(should_stop_) {
waiting_to_run_.wait(mutex_);
}
pending_threads_++;
state->run_state_ = ManagedThread::eRunning;
if(cDebugThreading) {
std::cerr << "[" << VM::current() << " WORLD restarted]\n";
}
}
};
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxExtension report utility functions
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/extension/configdlg.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/log.h>
#include <wx/extension/report/report.h>
#include <wx/extension/report/dir.h>
bool wxExCompareFile(const wxFileName& file1, const wxFileName& file2)
{
if (wxConfigBase::Get()->Read(_("Comparator")).empty())
{
return false;
}
const wxString arguments =
(file1.GetModificationTime() < file2.GetModificationTime()) ?
"\"" + file1.GetFullPath() + "\" \"" + file2.GetFullPath() + "\"":
"\"" + file2.GetFullPath() + "\" \"" + file1.GetFullPath() + "\"";
if (wxExecute(wxConfigBase::Get()->Read(_("Comparator")) + " " + arguments) == 0)
{
return false;
}
const wxString msg = _("Compared") + ": " + arguments;
wxExLog::Get()->Log(msg);
#if wxUSE_STATUSBAR
wxExFrame::StatusText(msg);
#endif
return true;
}
size_t wxExFindInFiles(bool replace)
{
if (wxExDir::GetIsBusy())
{
wxExDir::Cancel();
#if wxUSE_STATUSBAR
wxExFrame::StatusText(_("Cancelled previous find files"));
#endif
}
std::vector<wxExConfigItem> v;
v.push_back(
wxExConfigItem(wxExFindReplaceData::Get()->GetTextFindWhat(),
CONFIG_COMBOBOX,
wxEmptyString,
true));
if (replace)
{
v.push_back(wxExConfigItem(
wxExFindReplaceData::Get()->GetTextReplaceWith(),
CONFIG_COMBOBOX));
}
const wxString in_files = _("In files");
const wxString in_folder = _("In folder");
v.push_back(wxExConfigItem(in_files, CONFIG_COMBOBOX, wxEmptyString, true));
v.push_back(wxExConfigItem(in_folder, CONFIG_COMBOBOXDIR, wxEmptyString, true));
v.push_back(wxExConfigItem());
v.push_back(wxExConfigItem(wxExFindReplaceData::Get()->GetInfo()));
if (wxExConfigDialog(NULL,
v,
(replace ? _("Replace In Files"): _("Find In Files"))).ShowModal() == wxID_CANCEL)
{
return;
}
const wxExTool tool =
(replace ?
ID_TOOL_REPORT_REPLACE:
ID_TOOL_REPORT_FIND);
if (!wxExTextFileWithListView::SetupTool(tool))
{
return 0;
}
wxExLog::Get()->Log(wxExFindReplaceData::Get()->GetText(replace));
wxExDirWithListView dir(
tool,
wxExConfigFirstOf(in_folder),
wxExConfigFirstOf(in_files));
const size_t result = dir.FindFiles();
dir.GetStatistics().Log(tool);
return result;
}
bool wxExFindOtherFileName(
const wxFileName& filename,
wxExListViewFile* listview,
wxFileName* lastfile)
{
/* Add the base version if present. E.g.
fullpath: F:\CCIS\v990308\com\atis\atis-ctrl\atis-ctrl.cc
base: F:\CCIS\
append: \com\atis\atis-ctrl\atis-ctrl.cc
*/
const wxString fullpath = filename.GetFullPath();
wxRegEx reg("[/|\\][a-z-]*[0-9]+\\.?[0-9]*\\.?[0-9]*\\.?[0-9]*");
if (!reg.Matches(fullpath.Lower()))
{
#if wxUSE_STATUSBAR
wxExFrame::StatusText(_("No version information found"));
#endif
return false;
}
size_t start, len;
if (!reg.GetMatch(&start, &len))
{
wxFAIL;
return false;
}
wxString base = fullpath.substr(0, start);
if (!wxEndsWithPathSeparator(base))
{
base += wxFileName::GetPathSeparator();
}
wxDir dir(base);
if (!dir.IsOpened())
{
wxFAIL;
return false;
}
wxString filename_string;
bool cont = dir.GetFirst(&filename_string, wxEmptyString, wxDIR_DIRS); // only get dirs
wxDateTime lastmodtime((time_t)0);
const wxString append = fullpath.substr(start + len);
bool found = false;
// Readme: Maybe use a thread for this.
while (cont)
{
wxFileName fn(base + filename_string + append);
if (fn.FileExists() &&
fn.GetPath().CmpNoCase(filename.GetPath()) != 0 &&
fn.GetModificationTime() != filename.GetModificationTime())
{
found = true;
if (listview == NULL && lastfile == NULL)
{
// We are only interested in return value, so speed it up.
return true;
}
if (listview != NULL)
{
wxExListItemWithFileName item(listview, fn.GetFullPath());
item.Insert();
}
if (lastfile != NULL)
{
if (fn.GetModificationTime() > lastmodtime)
{
lastmodtime = fn.GetModificationTime();
*lastfile = fn;
}
}
}
cont = dir.GetNext(&filename_string);
if (wxTheApp != NULL)
{
wxTheApp->Yield();
}
}
if (!found && (listview != NULL || lastfile != NULL))
{
#if wxUSE_STATUSBAR
wxExFrame::StatusText(_("No files found"));
#endif
}
return found;
}
bool wxExForEach(wxAuiNotebook* notebook, int id, const wxFont& font)
{
for (
int page = notebook->GetPageCount() - 1;
page >= 0;
page--)
{
wxExListViewWithFrame* lv = (wxExListViewWithFrame*)notebook->GetPage(page);
if (lv == NULL)
{
wxFAIL;
return false;
}
if (id >= wxID_VIEW_DETAILS && id <= wxID_VIEW_LIST)
{
lv->SetStyle(id);
}
else
{
switch (id)
{
case ID_LIST_ALL_ITEMS:
{
if (font.IsOk())
{
lv->SetFont(font);
}
lv->ItemsUpdate();
}
break;
case ID_LIST_ALL_CLOSE:
{
wxExFileDialog dlg(notebook, lv);
if (!dlg.Continue()) return false;
if (!notebook->DeletePage(page)) return false;
}
break;
default: wxFAIL;
}
}
}
return true;
}
bool wxExMake(wxExFrameWithHistory* frame, const wxFileName& makefile)
{
const wxString cwd = wxGetCwd();
wxSetWorkingDirectory(makefile.GetPath());
const bool ret = frame->ProcessRun(
wxConfigBase::Get()->Read("Make", "make") + " " +
wxConfigBase::Get()->Read("MakeSwitch", "-f") + " " +
makefile.GetFullPath());
wxSetWorkingDirectory(cwd);
return ret;
}
void wxExOpenFiles(
wxExFrameWithHistory* frame,
const wxArrayString& files,
long file_flags,
int dir_flags)
{
for (size_t i = 0; i < files.GetCount(); i++)
{
wxString file = files[i]; // cannot be const because of file = later on
if (file.Contains("*") || file.Contains("?"))
{
wxExDirWithListView dir(frame, wxGetCwd(), file, file_flags, dir_flags);
dir.FindFiles();
}
else
{
int line = 0;
if (file.Contains(":"))
{
line = atoi(files[i].AfterFirst(':').c_str());
if (line != 0) // this indicates an error in the number
{
file = file.BeforeFirst(':');
}
}
frame->OpenFile(file, line, wxEmptyString, file_flags);
}
}
}
void wxExOpenFilesDialog(
wxExFrameWithHistory* frame,
long style,
const wxString& wildcards,
bool ask_for_continue)
{
wxExSTC* stc = frame->GetSTC();
wxArrayString files;
if (stc != NULL)
{
wxExFileDialog dlg(frame,
stc,
_("Select Files"),
wxFileSelectorDefaultWildcardStr,
style);
if (dlg.ShowModal(ask_for_continue) == wxID_CANCEL) return;
dlg.GetPaths(files);
}
else
{
wxFileDialog dlg(frame,
_("Select Files"),
wxEmptyString,
wxEmptyString,
wildcards,
style);
if (dlg.ShowModal() == wxID_CANCEL) return;
dlg.GetPaths(files);
}
wxExOpenFiles(frame, files);
}
<commit_msg>fixed error<commit_after>/******************************************************************************\
* File: util.cpp
* Purpose: Implementation of wxExtension report utility functions
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/extension/configdlg.h>
#include <wx/extension/filedlg.h>
#include <wx/extension/log.h>
#include <wx/extension/report/report.h>
#include <wx/extension/report/dir.h>
bool wxExCompareFile(const wxFileName& file1, const wxFileName& file2)
{
if (wxConfigBase::Get()->Read(_("Comparator")).empty())
{
return false;
}
const wxString arguments =
(file1.GetModificationTime() < file2.GetModificationTime()) ?
"\"" + file1.GetFullPath() + "\" \"" + file2.GetFullPath() + "\"":
"\"" + file2.GetFullPath() + "\" \"" + file1.GetFullPath() + "\"";
if (wxExecute(wxConfigBase::Get()->Read(_("Comparator")) + " " + arguments) == 0)
{
return false;
}
const wxString msg = _("Compared") + ": " + arguments;
wxExLog::Get()->Log(msg);
#if wxUSE_STATUSBAR
wxExFrame::StatusText(msg);
#endif
return true;
}
size_t wxExFindInFiles(bool replace)
{
if (wxExDir::GetIsBusy())
{
wxExDir::Cancel();
#if wxUSE_STATUSBAR
wxExFrame::StatusText(_("Cancelled previous find files"));
#endif
}
std::vector<wxExConfigItem> v;
v.push_back(
wxExConfigItem(wxExFindReplaceData::Get()->GetTextFindWhat(),
CONFIG_COMBOBOX,
wxEmptyString,
true));
if (replace)
{
v.push_back(wxExConfigItem(
wxExFindReplaceData::Get()->GetTextReplaceWith(),
CONFIG_COMBOBOX));
}
const wxString in_files = _("In files");
const wxString in_folder = _("In folder");
v.push_back(wxExConfigItem(in_files, CONFIG_COMBOBOX, wxEmptyString, true));
v.push_back(wxExConfigItem(in_folder, CONFIG_COMBOBOXDIR, wxEmptyString, true));
v.push_back(wxExConfigItem());
v.push_back(wxExConfigItem(wxExFindReplaceData::Get()->GetInfo()));
if (wxExConfigDialog(NULL,
v,
(replace ? _("Replace In Files"): _("Find In Files"))).ShowModal() == wxID_CANCEL)
{
return 0;
}
const wxExTool tool =
(replace ?
ID_TOOL_REPORT_REPLACE:
ID_TOOL_REPORT_FIND);
if (!wxExTextFileWithListView::SetupTool(tool))
{
return 0;
}
wxExLog::Get()->Log(wxExFindReplaceData::Get()->GetText(replace));
wxExDirWithListView dir(
tool,
wxExConfigFirstOf(in_folder),
wxExConfigFirstOf(in_files));
const size_t result = dir.FindFiles();
dir.GetStatistics().Log(tool);
return result;
}
bool wxExFindOtherFileName(
const wxFileName& filename,
wxExListViewFile* listview,
wxFileName* lastfile)
{
/* Add the base version if present. E.g.
fullpath: F:\CCIS\v990308\com\atis\atis-ctrl\atis-ctrl.cc
base: F:\CCIS\
append: \com\atis\atis-ctrl\atis-ctrl.cc
*/
const wxString fullpath = filename.GetFullPath();
wxRegEx reg("[/|\\][a-z-]*[0-9]+\\.?[0-9]*\\.?[0-9]*\\.?[0-9]*");
if (!reg.Matches(fullpath.Lower()))
{
#if wxUSE_STATUSBAR
wxExFrame::StatusText(_("No version information found"));
#endif
return false;
}
size_t start, len;
if (!reg.GetMatch(&start, &len))
{
wxFAIL;
return false;
}
wxString base = fullpath.substr(0, start);
if (!wxEndsWithPathSeparator(base))
{
base += wxFileName::GetPathSeparator();
}
wxDir dir(base);
if (!dir.IsOpened())
{
wxFAIL;
return false;
}
wxString filename_string;
bool cont = dir.GetFirst(&filename_string, wxEmptyString, wxDIR_DIRS); // only get dirs
wxDateTime lastmodtime((time_t)0);
const wxString append = fullpath.substr(start + len);
bool found = false;
// Readme: Maybe use a thread for this.
while (cont)
{
wxFileName fn(base + filename_string + append);
if (fn.FileExists() &&
fn.GetPath().CmpNoCase(filename.GetPath()) != 0 &&
fn.GetModificationTime() != filename.GetModificationTime())
{
found = true;
if (listview == NULL && lastfile == NULL)
{
// We are only interested in return value, so speed it up.
return true;
}
if (listview != NULL)
{
wxExListItemWithFileName item(listview, fn.GetFullPath());
item.Insert();
}
if (lastfile != NULL)
{
if (fn.GetModificationTime() > lastmodtime)
{
lastmodtime = fn.GetModificationTime();
*lastfile = fn;
}
}
}
cont = dir.GetNext(&filename_string);
if (wxTheApp != NULL)
{
wxTheApp->Yield();
}
}
if (!found && (listview != NULL || lastfile != NULL))
{
#if wxUSE_STATUSBAR
wxExFrame::StatusText(_("No files found"));
#endif
}
return found;
}
bool wxExForEach(wxAuiNotebook* notebook, int id, const wxFont& font)
{
for (
int page = notebook->GetPageCount() - 1;
page >= 0;
page--)
{
wxExListViewWithFrame* lv = (wxExListViewWithFrame*)notebook->GetPage(page);
if (lv == NULL)
{
wxFAIL;
return false;
}
if (id >= wxID_VIEW_DETAILS && id <= wxID_VIEW_LIST)
{
lv->SetStyle(id);
}
else
{
switch (id)
{
case ID_LIST_ALL_ITEMS:
{
if (font.IsOk())
{
lv->SetFont(font);
}
lv->ItemsUpdate();
}
break;
case ID_LIST_ALL_CLOSE:
{
wxExFileDialog dlg(notebook, lv);
if (!dlg.Continue()) return false;
if (!notebook->DeletePage(page)) return false;
}
break;
default: wxFAIL;
}
}
}
return true;
}
bool wxExMake(wxExFrameWithHistory* frame, const wxFileName& makefile)
{
const wxString cwd = wxGetCwd();
wxSetWorkingDirectory(makefile.GetPath());
const bool ret = frame->ProcessRun(
wxConfigBase::Get()->Read("Make", "make") + " " +
wxConfigBase::Get()->Read("MakeSwitch", "-f") + " " +
makefile.GetFullPath());
wxSetWorkingDirectory(cwd);
return ret;
}
void wxExOpenFiles(
wxExFrameWithHistory* frame,
const wxArrayString& files,
long file_flags,
int dir_flags)
{
for (size_t i = 0; i < files.GetCount(); i++)
{
wxString file = files[i]; // cannot be const because of file = later on
if (file.Contains("*") || file.Contains("?"))
{
wxExDirWithListView dir(frame, wxGetCwd(), file, file_flags, dir_flags);
dir.FindFiles();
}
else
{
int line = 0;
if (file.Contains(":"))
{
line = atoi(files[i].AfterFirst(':').c_str());
if (line != 0) // this indicates an error in the number
{
file = file.BeforeFirst(':');
}
}
frame->OpenFile(file, line, wxEmptyString, file_flags);
}
}
}
void wxExOpenFilesDialog(
wxExFrameWithHistory* frame,
long style,
const wxString& wildcards,
bool ask_for_continue)
{
wxExSTC* stc = frame->GetSTC();
wxArrayString files;
if (stc != NULL)
{
wxExFileDialog dlg(frame,
stc,
_("Select Files"),
wxFileSelectorDefaultWildcardStr,
style);
if (dlg.ShowModal(ask_for_continue) == wxID_CANCEL) return;
dlg.GetPaths(files);
}
else
{
wxFileDialog dlg(frame,
_("Select Files"),
wxEmptyString,
wxEmptyString,
wildcards,
style);
if (dlg.ShowModal() == wxID_CANCEL) return;
dlg.GetPaths(files);
}
wxExOpenFiles(frame, files);
}
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
//#include "atexit.h"
//#include "thread_private.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <sstream>
#include "xstring.h"
#define NO_ALLOC_MACRO_OVERRIDE
#include "mem_tracker.h"
using namespace std;
/** actually define the global (extern-ed) variables here
* and do some initialization directly at the beginning of main() */
unsigned long long CALL_COUNT_NEW;
unsigned long long CALL_COUNT_DELETE;
unsigned long long MEMORY_COUNT_NEW;
unsigned long long MEMORY_COUNT_DELETE;
/** this flag activates the tracking */
bool USE_MEM_TRACKER;
/** temporary save variables provided during "delete" call " */
const char* ____DELETE_FILENAME____;
size_t ____DELETE_LINE____;
/** the two main "databases" for the pointers */
tPtrDataStorage ALLOCATED_PTRS;
tPtrDataList ARCHIVED_PTRS;
/** no args ctor */
PtrData::PtrData()
: p(nullptr), size(0), allocated(false), deleted(false),
new_call(), delete_call() { }
/** copy ctor */
PtrData::PtrData(const PtrData& obj)
: p(obj.p), size(obj.size), allocated(obj.allocated), deleted(obj.deleted),
new_call(obj.new_call), delete_call(obj.delete_call) { }
/** keeps all the data for one pointer */
PtrData::PtrData(void* ptr, const size_t& len)
: p(ptr), size(len), allocated(true), deleted(false),
new_call(), delete_call() { }
/** handle new-call */
void* __handle_new_request(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
if(USE_MEM_TRACKER) {
CALL_COUNT_NEW++;
MEMORY_COUNT_NEW += size;
}
void* out = malloc(size);
if(USE_MEM_TRACKER) {
USE_MEM_TRACKER = false;
ALLOCATED_PTRS[out] = PtrData(out, size);
ALLOCATED_PTRS[out].new_call = make_pair(string(fn), line);
USE_MEM_TRACKER = true;
}
return out;
}
/** save meta-data (filename, lineno) into tmp-vars for __handle_delete_request */
void __handle_delete_meta_data(const char* fn, const size_t& line) {
____DELETE_FILENAME____ = fn;
____DELETE_LINE____ = line;
}
/** handle delete-call */
void __handle_delete_request(void* ptr) {
if(USE_MEM_TRACKER) {
tPtrDataStorageIter i = ALLOCATED_PTRS.find(ptr);
if(i != ALLOCATED_PTRS.end()) {
USE_MEM_TRACKER = false;
// move PtrData instance from ALLOCATED to ARCHIVED
ARCHIVED_PTRS.push_back(ALLOCATED_PTRS[ptr]);
ALLOCATED_PTRS.erase(ptr);
ARCHIVED_PTRS.back().deleted = true;
ARCHIVED_PTRS.back().delete_call = \
make_pair(string(____DELETE_FILENAME____), ____DELETE_LINE____);
CALL_COUNT_DELETE++;
MEMORY_COUNT_DELETE += ARCHIVED_PTRS.back().size;
USE_MEM_TRACKER = true;
}
}
free(ptr);
}
/** Global "new" operator overload */
void* operator new(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
void* operator new[](size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
/** Global "delete" operator overload */
void operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
void operator delete[](void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
/** return delete or new statistics */
string __print_memory_details(bool delete_mode, bool verbose) {
stringstream ss;
tOpPtrDataMap pos2ptr;
tPtrDataList data;
// generate reverse table
if(!delete_mode) {
for(tPtrDataStorage::value_type& i : ALLOCATED_PTRS) {
pos2ptr[i.second.new_call].push_back(i.second);
data.push_back(i.second);
}
} else {
for(PtrData& i : ARCHIVED_PTRS) {
pos2ptr[i.delete_call].push_back(i);
data.push_back(i);
}
}
// directly return, if no details are available
if(data.size() == 0)
return "";
// find PtrData instance allocating most bytes
tPtrDataIter max_iter = std::max_element(data.begin(), data.end(), \
[](const PtrData& a, const PtrData& b) \
{ return (a.size <= b.size); } \
);
// calc/set formatting vars
size_t max_size = max_iter->size;
size_t max_width = 0;
size_t max_cols = 6;
while(max_size) {
max_size /= 10.0;
max_width++;
}
// go over generated map and gen. results
for(tOpPtrDataIter i=pos2ptr.begin(); i!=pos2ptr.end(); ++i) {
// calculate sum of bytes alloced/deleted
unsigned long long sum = 0;
std::for_each(i->second.begin(), i->second.end(), \
[&](const PtrData& x) {
sum += x.size;
}
);
ss << "[i] " << setw(5) << i->first.first << setw(10) <<
" line: " << setw(6) << i->first.second << setw(10) <<
"#calls: " << setw(8) << i->second.size() << setw(10) <<
" bytes: " << setw(16) << sum << endl;
// print: ptr-addr[size] x (max_cols) each line
size_t col = 0;
if(verbose) {
ss << "[E] ";
for(tPtrDataIter p=i->second.begin(); p!=i->second.end(); ++p, col++) {
ss << p->p << "[" << setw(max_width) << p->size << "]";
ss << (((p+1) != i->second.end()) ? ", " : "\n");
if((col % max_cols) == (max_cols - 1))
ss << endl << " ";
}
}
}
return ss.str();
}
/** show some results and hints to search the leaks */
string get_memory_tracker_results(bool verbose) {
long m_diff = (MEMORY_COUNT_NEW - MEMORY_COUNT_DELETE);
long ptr_diff = CALL_COUNT_NEW - CALL_COUNT_DELETE;
stringstream ss;
ss << endl;
ss << "[STATS] Memory tracking overview:" << endl;
ss << endl;
string sep = " | ";
size_t pad = 14;
size_t loff = 8;
size_t hline = 82;
ss << setw(pad+loff) << "tracked" << sep << setw(pad) << "tracked" << sep <<
setw(pad) << "leaked" << sep << setw(pad) << "leaked" << sep << endl;
ss << setw(pad+loff) << "calls" << sep << setw(pad) << "bytes" << sep <<
setw(pad) << "calls" << sep << setw(pad) << "bytes" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "NEW" << setw(pad) << CALL_COUNT_NEW << sep <<
setw(pad) << MEMORY_COUNT_NEW << sep << setw(pad) << "n/a" << sep <<
setw(pad) << "n/a" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "DELETE" << setw(pad) << CALL_COUNT_DELETE << sep <<
setw(pad) << MEMORY_COUNT_DELETE << sep << setw(pad) << ptr_diff << sep <<
setw(pad) << m_diff << sep << endl;
if(m_diff > 0) {
ss << endl;
ss << "[LEAK DATA] showing not deleted (bad) calls:" << endl;
ss << __print_memory_details(false, verbose);
} else
cout << "[+] no leaks found!" << endl;
ss << endl;
if(verbose) {
if(CALL_COUNT_DELETE > 0) {
ss << "[DELETE DATA] showing deleted (good) calls:" << endl;
ss << __print_memory_details(true, verbose);
ss << endl;
} else
cout << "[i] no delete calls tracked..." << endl;
}
return ss.str();
}
// saving pointer to original ::exit() function call
auto original_exit = &::exit;
/** To avoid a segfault on exit, if MEM_TRACKER is used.
* (Segfault due to the automated cleanup of MemTracker datastructures on leaving scope) */
void exit(int status) throw() {
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
// calling "real" exit()
original_exit(status);
}
/** initilize the memory tracker variables */
void init_memory_tracker() {
CALL_COUNT_NEW = 0;
CALL_COUNT_DELETE = 0;
MEMORY_COUNT_NEW = 0;
MEMORY_COUNT_DELETE = 0;
____DELETE_FILENAME____ = "";
____DELETE_LINE____ = 0;
// set to true to start tracking!
USE_MEM_TRACKER = false;
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
}
<commit_msg>exit still not working good<commit_after>#include <sys/types.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
//#include "atexit.h"
//#include "thread_private.h"
#include <iostream>
#include <vector>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <sstream>
#include "xstring.h"
#define NO_ALLOC_MACRO_OVERRIDE
// NEED TWO MEM_TRACKER header files
// one for this .cc file
// another one for the target source files
#include "mem_tracker.h"
using namespace std;
/** actually define the global (extern-ed) variables here
* and do some initialization directly at the beginning of main() */
unsigned long long CALL_COUNT_NEW;
unsigned long long CALL_COUNT_DELETE;
unsigned long long MEMORY_COUNT_NEW;
unsigned long long MEMORY_COUNT_DELETE;
/** this flag activates the tracking */
bool USE_MEM_TRACKER;
/** temporary save variables provided during "delete" call " */
const char* ____DELETE_FILENAME____;
size_t ____DELETE_LINE____;
/** the two main "databases" for the pointers */
tPtrDataStorage ALLOCATED_PTRS;
tPtrDataList ARCHIVED_PTRS;
/** no args ctor */
PtrData::PtrData()
: p(nullptr), size(0), allocated(false), deleted(false),
new_call(), delete_call() { }
/** copy ctor */
PtrData::PtrData(const PtrData& obj)
: p(obj.p), size(obj.size), allocated(obj.allocated), deleted(obj.deleted),
new_call(obj.new_call), delete_call(obj.delete_call) { }
/** keeps all the data for one pointer */
PtrData::PtrData(void* ptr, const size_t& len)
: p(ptr), size(len), allocated(true), deleted(false),
new_call(), delete_call() { }
/** handle new-call */
void* __handle_new_request(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
if(USE_MEM_TRACKER) {
CALL_COUNT_NEW++;
MEMORY_COUNT_NEW += size;
}
void* out = malloc(size);
if(USE_MEM_TRACKER) {
USE_MEM_TRACKER = false;
ALLOCATED_PTRS[out] = PtrData(out, size);
ALLOCATED_PTRS[out].new_call = make_pair(string(fn), line);
USE_MEM_TRACKER = true;
}
return out;
}
/** save meta-data (filename, lineno) into tmp-vars for __handle_delete_request */
void __handle_delete_meta_data(const char* fn, const size_t& line) {
____DELETE_FILENAME____ = fn;
____DELETE_LINE____ = line;
}
/** handle delete-call */
void __handle_delete_request(void* ptr) {
if(USE_MEM_TRACKER) {
tPtrDataStorageIter i = ALLOCATED_PTRS.find(ptr);
if(i != ALLOCATED_PTRS.end()) {
USE_MEM_TRACKER = false;
// move PtrData instance from ALLOCATED to ARCHIVED
ARCHIVED_PTRS.push_back(ALLOCATED_PTRS[ptr]);
ALLOCATED_PTRS.erase(ptr);
ARCHIVED_PTRS.back().deleted = true;
ARCHIVED_PTRS.back().delete_call = \
make_pair(string(____DELETE_FILENAME____), ____DELETE_LINE____);
CALL_COUNT_DELETE++;
MEMORY_COUNT_DELETE += ARCHIVED_PTRS.back().size;
USE_MEM_TRACKER = true;
}
}
free(ptr);
}
/** Global "new" operator overload */
void* operator new(size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
void* operator new[](size_t size, const char* fn, size_t line) _GLIBCXX_THROW(std::bad_alloc) {
return __handle_new_request(size, fn, line);
}
/** Global "delete" operator overload */
void operator delete(void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
void operator delete[](void* ptr) _GLIBCXX_USE_NOEXCEPT {
__handle_delete_request(ptr);
}
/** return delete or new statistics */
string __print_memory_details(bool delete_mode, bool verbose) {
stringstream ss;
tOpPtrDataMap pos2ptr;
tPtrDataList data;
// generate reverse table
if(!delete_mode) {
for(tPtrDataStorage::value_type& i : ALLOCATED_PTRS) {
pos2ptr[i.second.new_call].push_back(i.second);
data.push_back(i.second);
}
} else {
for(PtrData& i : ARCHIVED_PTRS) {
pos2ptr[i.delete_call].push_back(i);
data.push_back(i);
}
}
// directly return, if no details are available
if(data.size() == 0)
return "";
// find PtrData instance allocating most bytes
tPtrDataIter max_iter = std::max_element(data.begin(), data.end(), \
[](const PtrData& a, const PtrData& b) \
{ return (a.size <= b.size); } \
);
// calc/set formatting vars
size_t max_size = max_iter->size;
size_t max_width = 0;
size_t max_cols = 6;
while(max_size) {
max_size /= 10.0;
max_width++;
}
// go over generated map and gen. results
for(tOpPtrDataIter i=pos2ptr.begin(); i!=pos2ptr.end(); ++i) {
// calculate sum of bytes alloced/deleted
unsigned long long sum = 0;
std::for_each(i->second.begin(), i->second.end(), \
[&](const PtrData& x) {
sum += x.size;
}
);
ss << "[i] " << setw(5) << i->first.first << setw(10) <<
" line: " << setw(6) << i->first.second << setw(10) <<
"#calls: " << setw(8) << i->second.size() << setw(10) <<
" bytes: " << setw(16) << sum << endl;
// print: ptr-addr[size] x (max_cols) each line
size_t col = 0;
if(verbose) {
ss << "[E] ";
for(tPtrDataIter p=i->second.begin(); p!=i->second.end(); ++p, col++) {
ss << p->p << "[" << setw(max_width) << p->size << "]";
ss << (((p+1) != i->second.end()) ? ", " : "\n");
if((col % max_cols) == (max_cols - 1))
ss << endl << " ";
}
}
}
return ss.str();
}
/** show some results and hints to search the leaks */
string get_memory_tracker_results(bool verbose) {
long m_diff = (MEMORY_COUNT_NEW - MEMORY_COUNT_DELETE);
long ptr_diff = CALL_COUNT_NEW - CALL_COUNT_DELETE;
stringstream ss;
ss << endl;
ss << "[STATS] Memory tracking overview:" << endl;
ss << endl;
string sep = " | ";
size_t pad = 14;
size_t loff = 8;
size_t hline = 82;
ss << setw(pad+loff) << "tracked" << sep << setw(pad) << "tracked" << sep <<
setw(pad) << "leaked" << sep << setw(pad) << "leaked" << sep << endl;
ss << setw(pad+loff) << "calls" << sep << setw(pad) << "bytes" << sep <<
setw(pad) << "calls" << sep << setw(pad) << "bytes" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "NEW" << setw(pad) << CALL_COUNT_NEW << sep <<
setw(pad) << MEMORY_COUNT_NEW << sep << setw(pad) << "n/a" << sep <<
setw(pad) << "n/a" << sep << endl;
ss << setw(hline) << setfill('-') << "" << setfill(' ') << endl;
ss << setw(loff) << "DELETE" << setw(pad) << CALL_COUNT_DELETE << sep <<
setw(pad) << MEMORY_COUNT_DELETE << sep << setw(pad) << ptr_diff << sep <<
setw(pad) << m_diff << sep << endl;
if(m_diff > 0) {
ss << endl;
ss << "[LEAK DATA] showing not deleted (bad) calls:" << endl;
ss << __print_memory_details(false, verbose);
} else
cout << "[+] no leaks found!" << endl;
ss << endl;
if(verbose) {
if(CALL_COUNT_DELETE > 0) {
ss << "[DELETE DATA] showing deleted (good) calls:" << endl;
ss << __print_memory_details(true, verbose);
ss << endl;
} else
cout << "[i] no delete calls tracked..." << endl;
}
return ss.str();
}
// saving pointer to original ::exit() function call
auto original_exit = &::exit;
/** To avoid a segfault on exit, if MEM_TRACKER is used.
* (Segfault due to the automated cleanup of MemTracker datastructures on leaving scope) */
void exit(int status) throw() {
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
// calling "real" exit()
original_exit(status);
}
/** initilize the memory tracker variables */
void init_memory_tracker() {
CALL_COUNT_NEW = 0;
CALL_COUNT_DELETE = 0;
MEMORY_COUNT_NEW = 0;
MEMORY_COUNT_DELETE = 0;
____DELETE_FILENAME____ = "";
____DELETE_LINE____ = 0;
// set to true to start tracking!
USE_MEM_TRACKER = false;
ALLOCATED_PTRS.clear();
ARCHIVED_PTRS.clear();
}
<|endoftext|> |
<commit_before>// $Id$
//
// Copyright (C) 2005-2008 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include "RDLog.h"
#if 1
#include <iomanip>
#include <string>
#include <time.h>
boost::logging::rdLogger *rdAppLog=0;
boost::logging::rdLogger *rdDebugLog=0;
boost::logging::rdLogger *rdInfoLog=0;
boost::logging::rdLogger *rdErrorLog=0;
boost::logging::rdLogger *rdWarningLog=0;
boost::logging::rdLogger *rdStatusLog=0;
namespace boost {
namespace logging {
void enable_logs(const char *arg) { enable_logs(std::string(arg));};
void enable_logs(const std::string &arg) {
// Yes... this is extremely crude
if(arg=="rdApp.debug"||arg=="rdApp.*"){
if(rdDebugLog) rdDebugLog->df_enabled=true;
}
if(arg=="rdApp.info"||arg=="rdApp.*"){
if(rdInfoLog) rdInfoLog->df_enabled=true;
}
if(arg=="rdApp.warning"||arg=="rdApp.*"){
if(rdWarningLog) rdWarningLog->df_enabled=true;
}
if(arg=="rdApp.error"||arg=="rdApp.*"){
if(rdErrorLog) rdErrorLog->df_enabled=true;
}
};
void disable_logs(const char *arg) {disable_logs(std::string(arg));};
void disable_logs(const std::string &arg) {
// Yes... this is extremely crude
if(arg=="rdApp.debug"||arg=="rdApp.*"){
if(rdDebugLog) rdDebugLog->df_enabled=false;
}
if(arg=="rdApp.info"||arg=="rdApp.*"){
if(rdInfoLog) rdInfoLog->df_enabled=false;
}
if(arg=="rdApp.warning"||arg=="rdApp.*"){
if(rdWarningLog) rdWarningLog->df_enabled=false;
}
if(arg=="rdApp.error"||arg=="rdApp.*"){
if(rdErrorLog) rdErrorLog->df_enabled=false;
}
};
}
}
namespace RDLog {
void InitLogs(){
rdDebugLog=new boost::logging::rdLogger(&std::cerr);
rdInfoLog=new boost::logging::rdLogger(&std::cout);
rdWarningLog=new boost::logging::rdLogger(&std::cerr);
rdErrorLog=new boost::logging::rdLogger(&std::cerr);
}
std::ostream &toStream(std::ostream &logstrm) {
time_t t = time(0);
tm details = *localtime( &t);
logstrm << "["<<std::setw(2)<<std::setfill('0')<<details.tm_hour<<":"<<std::setw(2)<<std::setfill('0')<<details.tm_min<<":"<<std::setw(2)<<std::setfill('0')<<int(details.tm_sec)<<"] ";
return logstrm;
}
}
#else
#include <boost/log/functions.hpp>
#if defined(BOOST_HAS_THREADS2)
#include <boost/log/extra/functions_ts.hpp>
#endif
#include <iostream>
namespace logging = boost::logging;
BOOST_DEFINE_LOG(rdAppLog,"rdApp")
BOOST_DEFINE_LOG(rdDebugLog,"rdApp.debug")
BOOST_DEFINE_LOG(rdInfoLog,"rdApp.info")
BOOST_DEFINE_LOG(rdErrorLog,"rdApp.error")
BOOST_DEFINE_LOG(rdWarningLog,"rdApp.warning")
BOOST_DEFINE_LOG(rdStatusLog,"rdApp.status")
namespace RDLog {
void write_to_cout(const std::string &, const std::string &msg) {
std::cout << msg; std::cout.flush();
}
void write_to_cerr(const std::string &, const std::string &msg) {
std::cerr << msg; std::cerr.flush();
}
void InitLogs(){
static bool callOnce=true;
if(!callOnce) return;
callOnce=false;
// turn off caching:
logging::set_log_caching(false);
logging::manipulate_logs("rdApp.*")
.add_modifier(logging::prepend_time("[$hh:$mm:$ss] "),
logging::DEFAULT_INDEX-10);
logging::manipulate_logs("rdApp.info")
.add_appender(write_to_cout,
logging::DEFAULT_INDEX+1);
#if defined(BOOST_HAS_THREADS2)
logging::manipulate_logs("rdApp.error")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.warning")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.status")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.debug")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
#else
logging::manipulate_logs("rdApp.error")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.warning")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.status")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.debug")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
#endif
// start with the debug log disabled:
logging::disable_logs("rdApp.debug");
};
}
#endif
<commit_msg>add a hack to get the console stuff working on windows. this needs to be tested on lin and mac<commit_after>// $Id$
//
// Copyright (C) 2005-2010 Greg Landrum and Rational Discovery LLC
//
// @@ All Rights Reserved @@
//
#include "RDLog.h"
#if 1
#include <iomanip>
#include <string>
#include <time.h>
namespace {
// this is a "bit" of a hack to work around shared/static library problems
// on windows
boost::logging::rdLogger cerrLogger(&std::cerr);
boost::logging::rdLogger coutLogger(&std::cout);
}
boost::logging::rdLogger *rdAppLog=0;
boost::logging::rdLogger *rdDebugLog=0;
boost::logging::rdLogger *rdInfoLog=&coutLogger;
boost::logging::rdLogger *rdErrorLog=&cerrLogger;
boost::logging::rdLogger *rdWarningLog=&cerrLogger;
boost::logging::rdLogger *rdStatusLog=0;
namespace boost {
namespace logging {
void enable_logs(const char *arg) { enable_logs(std::string(arg));};
void enable_logs(const std::string &arg) {
// Yes... this is extremely crude
if(arg=="rdApp.debug"||arg=="rdApp.*"){
if(rdDebugLog) rdDebugLog->df_enabled=true;
}
if(arg=="rdApp.info"||arg=="rdApp.*"){
if(rdInfoLog) rdInfoLog->df_enabled=true;
}
if(arg=="rdApp.warning"||arg=="rdApp.*"){
if(rdWarningLog) rdWarningLog->df_enabled=true;
}
if(arg=="rdApp.error"||arg=="rdApp.*"){
if(rdErrorLog) rdErrorLog->df_enabled=true;
}
};
void disable_logs(const char *arg) {disable_logs(std::string(arg));};
void disable_logs(const std::string &arg) {
// Yes... this is extremely crude
if(arg=="rdApp.debug"||arg=="rdApp.*"){
if(rdDebugLog) rdDebugLog->df_enabled=false;
}
if(arg=="rdApp.info"||arg=="rdApp.*"){
if(rdInfoLog) rdInfoLog->df_enabled=false;
}
if(arg=="rdApp.warning"||arg=="rdApp.*"){
if(rdWarningLog) rdWarningLog->df_enabled=false;
}
if(arg=="rdApp.error"||arg=="rdApp.*"){
if(rdErrorLog) rdErrorLog->df_enabled=false;
}
};
}
}
namespace RDLog {
void InitLogs(){
rdDebugLog=new boost::logging::rdLogger(&std::cerr);
rdInfoLog=new boost::logging::rdLogger(&std::cout);
rdWarningLog=new boost::logging::rdLogger(&std::cerr);
rdErrorLog=new boost::logging::rdLogger(&std::cerr);
}
std::ostream &toStream(std::ostream &logstrm) {
time_t t = time(0);
tm details = *localtime( &t);
logstrm << "["<<std::setw(2)<<std::setfill('0')<<details.tm_hour<<":"<<std::setw(2)<<std::setfill('0')<<details.tm_min<<":"<<std::setw(2)<<std::setfill('0')<<int(details.tm_sec)<<"] ";
return logstrm;
}
}
#else
#include <boost/log/functions.hpp>
#if defined(BOOST_HAS_THREADS2)
#include <boost/log/extra/functions_ts.hpp>
#endif
#include <iostream>
namespace logging = boost::logging;
BOOST_DEFINE_LOG(rdAppLog,"rdApp")
BOOST_DEFINE_LOG(rdDebugLog,"rdApp.debug")
BOOST_DEFINE_LOG(rdInfoLog,"rdApp.info")
BOOST_DEFINE_LOG(rdErrorLog,"rdApp.error")
BOOST_DEFINE_LOG(rdWarningLog,"rdApp.warning")
BOOST_DEFINE_LOG(rdStatusLog,"rdApp.status")
namespace RDLog {
void write_to_cout(const std::string &, const std::string &msg) {
std::cout << msg; std::cout.flush();
}
void write_to_cerr(const std::string &, const std::string &msg) {
std::cerr << msg; std::cerr.flush();
}
void InitLogs(){
static bool callOnce=true;
if(!callOnce) return;
callOnce=false;
// turn off caching:
logging::set_log_caching(false);
logging::manipulate_logs("rdApp.*")
.add_modifier(logging::prepend_time("[$hh:$mm:$ss] "),
logging::DEFAULT_INDEX-10);
logging::manipulate_logs("rdApp.info")
.add_appender(write_to_cout,
logging::DEFAULT_INDEX+1);
#if defined(BOOST_HAS_THREADS2)
logging::manipulate_logs("rdApp.error")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.warning")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.status")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.debug")
.add_appender(logging::ts_appender(write_to_cerr,100),
logging::DEFAULT_INDEX+1);
#else
logging::manipulate_logs("rdApp.error")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.warning")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.status")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
logging::manipulate_logs("rdApp.debug")
.add_appender(write_to_cerr,
logging::DEFAULT_INDEX+1);
#endif
// start with the debug log disabled:
logging::disable_logs("rdApp.debug");
};
}
#endif
<|endoftext|> |
<commit_before>//===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that handles AST -> LLVM type lowering.
//
//===----------------------------------------------------------------------===//
#include "CodeGenTypes.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/AST/AST.h"
#include "llvm/DerivedTypes.h"
using namespace clang;
using namespace CodeGen;
CodeGenTypes::CodeGenTypes(ASTContext &Ctx)
: Context(Ctx), Target(Ctx.Target) {
}
/// ConvertType - Convert the specified type to its LLVM form.
const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
// FIXME: Cache these, move the CodeGenModule, expand, etc.
const clang::Type &Ty = *T.getCanonicalType();
switch (Ty.getTypeClass()) {
case Type::Builtin: {
switch (cast<BuiltinType>(Ty).getKind()) {
case BuiltinType::Void:
// LLVM void type can only be used as the result of a function call. Just
// map to the same as char.
return llvm::IntegerType::get(8);
case BuiltinType::Bool:
// FIXME: This is very strange. We want scalars to be i1, but in memory
// they can be i1 or i32. Should the codegen handle this issue?
return llvm::Type::Int1Ty;
case BuiltinType::Char_S:
case BuiltinType::Char_U:
case BuiltinType::SChar:
case BuiltinType::UChar:
case BuiltinType::Short:
case BuiltinType::UShort:
case BuiltinType::Int:
case BuiltinType::UInt:
case BuiltinType::Long:
case BuiltinType::ULong:
case BuiltinType::LongLong:
case BuiltinType::ULongLong:
return llvm::IntegerType::get(Context.getTypeSize(T, SourceLocation()));
case BuiltinType::Float: return llvm::Type::FloatTy;
case BuiltinType::Double: return llvm::Type::DoubleTy;
case BuiltinType::LongDouble:
// FIXME: mapping long double onto double.
return llvm::Type::DoubleTy;
}
break;
}
case Type::Complex: {
std::vector<const llvm::Type*> Elts;
Elts.push_back(ConvertType(cast<ComplexType>(Ty).getElementType()));
Elts.push_back(Elts[0]);
return llvm::StructType::get(Elts);
}
case Type::Pointer: {
const PointerType &P = cast<PointerType>(Ty);
return llvm::PointerType::get(ConvertType(P.getPointeeType()));
}
case Type::Reference: {
const ReferenceType &R = cast<ReferenceType>(Ty);
return llvm::PointerType::get(ConvertType(R.getReferenceeType()));
}
case Type::Array: {
const ArrayType &A = cast<ArrayType>(Ty);
assert(A.getSizeModifier() == ArrayType::Normal &&
A.getIndexTypeQualifier() == 0 &&
"FIXME: We only handle trivial array types so far!");
llvm::APSInt Size(32);
if (A.getSizeExpr() &&
A.getSizeExpr()->isIntegerConstantExpr(Size, Context)) {
const llvm::Type *EltTy = ConvertType(A.getElementType());
return llvm::ArrayType::get(EltTy, Size.getZExtValue());
} else {
assert(0 && "FIXME: VLAs not implemented yet!");
}
}
case Type::Vector: {
const VectorType &VT = cast<VectorType>(Ty);
return llvm::VectorType::get(ConvertType(VT.getElementType()),
VT.getNumElements());
}
case Type::FunctionNoProto:
case Type::FunctionProto: {
const FunctionType &FP = cast<FunctionType>(Ty);
const llvm::Type *ResultType;
if (FP.getResultType()->isVoidType())
ResultType = llvm::Type::VoidTy; // Result of function uses llvm void.
else
ResultType = ConvertType(FP.getResultType());
// FIXME: Convert argument types.
bool isVarArg;
std::vector<const llvm::Type*> ArgTys;
// Struct return passes the struct byref.
if (!ResultType->isFirstClassType() && ResultType != llvm::Type::VoidTy) {
ArgTys.push_back(llvm::PointerType::get(ResultType));
ResultType = llvm::Type::VoidTy;
}
if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(&FP)) {
DecodeArgumentTypes(*FTP, ArgTys);
isVarArg = FTP->isVariadic();
} else {
isVarArg = true;
}
return llvm::FunctionType::get(ResultType, ArgTys, isVarArg, 0);
}
case Type::TypeName:
case Type::Tagged:
break;
}
// FIXME: implement.
return llvm::OpaqueType::get();
}
void CodeGenTypes::DecodeArgumentTypes(const FunctionTypeProto &FTP,
std::vector<const llvm::Type*> &ArgTys) {
for (unsigned i = 0, e = FTP.getNumArgs(); i != e; ++i) {
const llvm::Type *Ty = ConvertType(FTP.getArgType(i));
if (Ty->isFirstClassType())
ArgTys.push_back(Ty);
else
ArgTys.push_back(llvm::PointerType::get(Ty));
}
}
<commit_msg>silence a warning by treating ocuvectors the same as vectors.<commit_after>//===--- CodeGenTypes.cpp - Type translation for LLVM CodeGen -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Chris Lattner and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is the code that handles AST -> LLVM type lowering.
//
//===----------------------------------------------------------------------===//
#include "CodeGenTypes.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/AST/AST.h"
#include "llvm/DerivedTypes.h"
using namespace clang;
using namespace CodeGen;
CodeGenTypes::CodeGenTypes(ASTContext &Ctx)
: Context(Ctx), Target(Ctx.Target) {
}
/// ConvertType - Convert the specified type to its LLVM form.
const llvm::Type *CodeGenTypes::ConvertType(QualType T) {
// FIXME: Cache these, move the CodeGenModule, expand, etc.
const clang::Type &Ty = *T.getCanonicalType();
switch (Ty.getTypeClass()) {
case Type::Builtin: {
switch (cast<BuiltinType>(Ty).getKind()) {
case BuiltinType::Void:
// LLVM void type can only be used as the result of a function call. Just
// map to the same as char.
return llvm::IntegerType::get(8);
case BuiltinType::Bool:
// FIXME: This is very strange. We want scalars to be i1, but in memory
// they can be i1 or i32. Should the codegen handle this issue?
return llvm::Type::Int1Ty;
case BuiltinType::Char_S:
case BuiltinType::Char_U:
case BuiltinType::SChar:
case BuiltinType::UChar:
case BuiltinType::Short:
case BuiltinType::UShort:
case BuiltinType::Int:
case BuiltinType::UInt:
case BuiltinType::Long:
case BuiltinType::ULong:
case BuiltinType::LongLong:
case BuiltinType::ULongLong:
return llvm::IntegerType::get(Context.getTypeSize(T, SourceLocation()));
case BuiltinType::Float: return llvm::Type::FloatTy;
case BuiltinType::Double: return llvm::Type::DoubleTy;
case BuiltinType::LongDouble:
// FIXME: mapping long double onto double.
return llvm::Type::DoubleTy;
}
break;
}
case Type::Complex: {
std::vector<const llvm::Type*> Elts;
Elts.push_back(ConvertType(cast<ComplexType>(Ty).getElementType()));
Elts.push_back(Elts[0]);
return llvm::StructType::get(Elts);
}
case Type::Pointer: {
const PointerType &P = cast<PointerType>(Ty);
return llvm::PointerType::get(ConvertType(P.getPointeeType()));
}
case Type::Reference: {
const ReferenceType &R = cast<ReferenceType>(Ty);
return llvm::PointerType::get(ConvertType(R.getReferenceeType()));
}
case Type::Array: {
const ArrayType &A = cast<ArrayType>(Ty);
assert(A.getSizeModifier() == ArrayType::Normal &&
A.getIndexTypeQualifier() == 0 &&
"FIXME: We only handle trivial array types so far!");
llvm::APSInt Size(32);
if (A.getSizeExpr() &&
A.getSizeExpr()->isIntegerConstantExpr(Size, Context)) {
const llvm::Type *EltTy = ConvertType(A.getElementType());
return llvm::ArrayType::get(EltTy, Size.getZExtValue());
} else {
assert(0 && "FIXME: VLAs not implemented yet!");
}
}
case Type::OCUVector:
case Type::Vector: {
const VectorType &VT = cast<VectorType>(Ty);
return llvm::VectorType::get(ConvertType(VT.getElementType()),
VT.getNumElements());
}
case Type::FunctionNoProto:
case Type::FunctionProto: {
const FunctionType &FP = cast<FunctionType>(Ty);
const llvm::Type *ResultType;
if (FP.getResultType()->isVoidType())
ResultType = llvm::Type::VoidTy; // Result of function uses llvm void.
else
ResultType = ConvertType(FP.getResultType());
// FIXME: Convert argument types.
bool isVarArg;
std::vector<const llvm::Type*> ArgTys;
// Struct return passes the struct byref.
if (!ResultType->isFirstClassType() && ResultType != llvm::Type::VoidTy) {
ArgTys.push_back(llvm::PointerType::get(ResultType));
ResultType = llvm::Type::VoidTy;
}
if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(&FP)) {
DecodeArgumentTypes(*FTP, ArgTys);
isVarArg = FTP->isVariadic();
} else {
isVarArg = true;
}
return llvm::FunctionType::get(ResultType, ArgTys, isVarArg, 0);
}
case Type::TypeName:
case Type::Tagged:
break;
}
// FIXME: implement.
return llvm::OpaqueType::get();
}
void CodeGenTypes::DecodeArgumentTypes(const FunctionTypeProto &FTP,
std::vector<const llvm::Type*> &ArgTys) {
for (unsigned i = 0, e = FTP.getNumArgs(); i != e; ++i) {
const llvm::Type *Ty = ConvertType(FTP.getArgType(i));
if (Ty->isFirstClassType())
ArgTys.push_back(Ty);
else
ArgTys.push_back(llvm::PointerType::get(Ty));
}
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, const char* _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, "abi") || argToStdout(_args, "natspec-user") || argToStdout(_args, "natspec-dev") ||
argToStdout(_args, "asm") || argToStdout(_args, "opcodes") || argToStdout(_args, "binary");
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBytecode(string const& _argName,
string const& _title,
string const& _contract,
string const& _suffix)
{
if (m_args.count(_argName))
{
auto choice = m_args[_argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << _title << endl;
if (_suffix == "opcodes")
;
// TODO: Figure out why after moving to own class ostream operator does not work for vector of bytes
// cout << m_compiler.getBytecode(_contract) << endl;
else
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + _suffix);
if (_suffix == "opcodes")
;
// TODO: Figure out why after moving to own class ostream operator does not work for vector of bytes
// outFile << m_compiler.getBytecode(_contract);
else
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = "abi";
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "natspec-user";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = "natspec-dev";
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
("ast", po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
("asm", po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
("opcodes", po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
("binary", po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
("abi", po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
("natspec-user", po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
("natspec-dev", po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
m_sourceCodes[infile] = asString(dev::contents(infile));
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count("ast"))
{
auto choice = m_args["ast"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count("asm"))
{
auto choice = m_args["asm"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode("opcodes", "Opcodes:", contract, ".opcodes");
handleBytecode("binary", "Binary:", contract, ".binary");
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<commit_msg>Explicitly calling dev::operator<<() on two occassions due to mixup with boost<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Lefteris <lefteris@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include "CommandLineInterface.h"
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>
#include "BuildInfo.h"
#include <libdevcore/Common.h>
#include <libdevcore/CommonData.h>
#include <libdevcore/CommonIO.h>
#include <libevmcore/Instruction.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/ASTPrinter.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Exceptions.h>
#include <libsolidity/CompilerStack.h>
#include <libsolidity/SourceReferenceFormatter.h>
using namespace std;
namespace po = boost::program_options;
namespace dev
{
namespace solidity
{
static void version()
{
cout << "solc, the solidity complier commandline interface " << dev::Version << endl
<< " by Christian <c@ethdev.com> and Lefteris <lefteris@ethdev.com>, (c) 2014." << endl
<< "Build: " << DEV_QUOTED(ETH_BUILD_PLATFORM) << "/" << DEV_QUOTED(ETH_BUILD_TYPE) << endl;
exit(0);
}
static inline bool argToStdout(po::variables_map const& _args, const char* _name)
{
return _args.count(_name) && _args[_name].as<OutputType>() != OutputType::FILE;
}
static bool needStdout(po::variables_map const& _args)
{
return argToStdout(_args, "abi") || argToStdout(_args, "natspec-user") || argToStdout(_args, "natspec-dev") ||
argToStdout(_args, "asm") || argToStdout(_args, "opcodes") || argToStdout(_args, "binary");
}
static inline bool outputToFile(OutputType type)
{
return type == OutputType::FILE || type == OutputType::BOTH;
}
static inline bool outputToStdout(OutputType type)
{
return type == OutputType::STDOUT || type == OutputType::BOTH;
}
static std::istream& operator>>(std::istream& _in, OutputType& io_output)
{
std::string token;
_in >> token;
if (token == "stdout")
io_output = OutputType::STDOUT;
else if (token == "file")
io_output = OutputType::FILE;
else if (token == "both")
io_output = OutputType::BOTH;
else
throw boost::program_options::invalid_option_value(token);
return _in;
}
void CommandLineInterface::handleBytecode(string const& _argName,
string const& _title,
string const& _contract,
string const& _suffix)
{
if (m_args.count(_argName))
{
auto choice = m_args[_argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << _title << endl;
if (_suffix == "opcodes")
{
// TODO: Figure out why the wrong operator << (from boost) is used here
dev::operator<<(cout, m_compiler.getBytecode(_contract));
cout << endl;
}
else
cout << toHex(m_compiler.getBytecode(_contract)) << endl;
}
if (outputToFile(choice))
{
ofstream outFile(_contract + _suffix);
if (_suffix == "opcodes")
// TODO: Figure out why the wrong operator << (from boost) is used here
dev::operator<<(outFile, m_compiler.getBytecode(_contract));
else
outFile << toHex(m_compiler.getBytecode(_contract));
outFile.close();
}
}
}
void CommandLineInterface::handleJson(DocumentationType _type,
string const& _contract)
{
std::string argName;
std::string suffix;
std::string title;
switch(_type)
{
case DocumentationType::ABI_INTERFACE:
argName = "abi";
suffix = ".abi";
title = "Contract ABI";
break;
case DocumentationType::NATSPEC_USER:
argName = "natspec-user";
suffix = ".docuser";
title = "User Documentation";
break;
case DocumentationType::NATSPEC_DEV:
argName = "natspec-dev";
suffix = ".docdev";
title = "Developer Documentation";
break;
default:
// should never happen
BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Unknown documentation _type"));
}
if (m_args.count(argName))
{
auto choice = m_args[argName].as<OutputType>();
if (outputToStdout(choice))
{
cout << title << endl;
cout << m_compiler.getJsonDocumentation(_contract, _type);
}
if (outputToFile(choice))
{
ofstream outFile(_contract + suffix);
outFile << m_compiler.getJsonDocumentation(_contract, _type);
outFile.close();
}
}
}
bool CommandLineInterface::parseArguments(int argc, char** argv)
{
#define OUTPUT_TYPE_STR "Legal values:\n" \
"\tstdout: Print it to standard output\n" \
"\tfile: Print it to a file with same name\n" \
"\tboth: Print both to a file and the stdout\n"
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
("help", "Show help message and exit")
("version", "Show version and exit")
("optimize", po::value<bool>()->default_value(false), "Optimize bytecode for size")
("input-file", po::value<vector<string>>(), "input file")
("ast", po::value<OutputType>(),
"Request to output the AST of the contract. " OUTPUT_TYPE_STR)
("asm", po::value<OutputType>(),
"Request to output the EVM assembly of the contract. " OUTPUT_TYPE_STR)
("opcodes", po::value<OutputType>(),
"Request to output the Opcodes of the contract. " OUTPUT_TYPE_STR)
("binary", po::value<OutputType>(),
"Request to output the contract in binary (hexadecimal). " OUTPUT_TYPE_STR)
("abi", po::value<OutputType>(),
"Request to output the contract's ABI interface. " OUTPUT_TYPE_STR)
("natspec-user", po::value<OutputType>(),
"Request to output the contract's Natspec user documentation. " OUTPUT_TYPE_STR)
("natspec-dev", po::value<OutputType>(),
"Request to output the contract's Natspec developer documentation. " OUTPUT_TYPE_STR);
#undef OUTPUT_TYPE_STR
// All positional options should be interpreted as input files
po::positional_options_description p;
p.add("input-file", -1);
// parse the compiler arguments
try
{
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).allow_unregistered().run(), m_args);
}
catch (po::error const& exception)
{
cout << exception.what() << endl;
return false;
}
po::notify(m_args);
if (m_args.count("help"))
{
cout << desc;
return false;
}
if (m_args.count("version"))
{
version();
return false;
}
return true;
}
bool CommandLineInterface::processInput()
{
if (!m_args.count("input-file"))
{
string s;
while (!cin.eof())
{
getline(cin, s);
m_sourceCodes["<stdin>"].append(s);
}
}
else
for (string const& infile: m_args["input-file"].as<vector<string>>())
m_sourceCodes[infile] = asString(dev::contents(infile));
try
{
for (auto const& sourceCode: m_sourceCodes)
m_compiler.addSource(sourceCode.first, sourceCode.second);
// TODO: Perhaps we should not compile unless requested
m_compiler.compile(m_args["optimize"].as<bool>());
}
catch (ParserError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Parser error", m_compiler);
return false;
}
catch (DeclarationError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Declaration error", m_compiler);
return false;
}
catch (TypeError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Type error", m_compiler);
return false;
}
catch (CompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Compiler error", m_compiler);
return false;
}
catch (InternalCompilerError const& exception)
{
SourceReferenceFormatter::printExceptionInformation(cerr, exception, "Internal compiler error", m_compiler);
return false;
}
catch (Exception const& exception)
{
cerr << "Exception during compilation: " << boost::diagnostic_information(exception) << endl;
return false;
}
catch (...)
{
cerr << "Unknown exception during compilation." << endl;
return false;
}
return true;
}
void CommandLineInterface::actOnInput()
{
// do we need AST output?
if (m_args.count("ast"))
{
auto choice = m_args["ast"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "Syntax trees:" << endl << endl;
for (auto const& sourceCode: m_sourceCodes)
{
cout << endl << "======= " << sourceCode.first << " =======" << endl;
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(cout);
}
}
if (outputToFile(choice))
{
for (auto const& sourceCode: m_sourceCodes)
{
boost::filesystem::path p(sourceCode.first);
ofstream outFile(p.stem().string() + ".ast");
ASTPrinter printer(m_compiler.getAST(sourceCode.first), sourceCode.second);
printer.print(outFile);
outFile.close();
}
}
}
vector<string> contracts = m_compiler.getContractNames();
for (string const& contract: contracts)
{
if (needStdout(m_args))
cout << endl << "======= " << contract << " =======" << endl;
// do we need EVM assembly?
if (m_args.count("asm"))
{
auto choice = m_args["asm"].as<OutputType>();
if (outputToStdout(choice))
{
cout << "EVM assembly:" << endl;
m_compiler.streamAssembly(cout, contract);
}
if (outputToFile(choice))
{
ofstream outFile(contract + ".evm");
m_compiler.streamAssembly(outFile, contract);
outFile.close();
}
}
handleBytecode("opcodes", "Opcodes:", contract, ".opcodes");
handleBytecode("binary", "Binary:", contract, ".binary");
handleJson(DocumentationType::ABI_INTERFACE, contract);
handleJson(DocumentationType::NATSPEC_DEV, contract);
handleJson(DocumentationType::NATSPEC_USER, contract);
} // end of contracts iteration
}
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "EmbeddedPython.h"
#include "ModsLocation.h"
#include "ExceptionFetcher.h"
#include "ResourceLoader.h"
#include <iostream>
#include "resource.h"
#include "Logger.h"
#include "SQFReader.h"
#include "SQFWriter.h"
#define THROW_PYEXCEPTION(_msg_) throw std::runtime_error(_msg_ + std::string(": ") + PyExceptionFetcher().getError());
//#define EXTENSION_DEVELOPMENT 1
EmbeddedPython *python = nullptr;
std::string pythonInitializationError = "";
namespace
{
class PyObjectGuard final
{
public:
PyObjectGuard(PyObject* source) : ptr(source)
{
}
~PyObjectGuard()
{
if (ptr != nullptr)
{
Py_DECREF(ptr);
}
}
PyObject* get() const
{
return ptr;
}
explicit operator bool() const
{
return ptr != nullptr;
}
/// Release ownership
PyObject* transfer()
{
PyObject* tmp = ptr;
ptr = nullptr;
return tmp;
}
private:
PyObjectGuard(const PyObjectGuard&) = delete;
void operator=(const PyObjectGuard&) = delete;
private:
PyObject *ptr;
};
}
EmbeddedPython::EmbeddedPython(HMODULE moduleHandle): dllModuleHandle(moduleHandle)
{
Py_Initialize();
PyEval_InitThreads(); // Initialize and acquire GIL
initialize();
leavePythonThread();
}
void EmbeddedPython::enterPythonThread()
{
PyEval_RestoreThread(pThreadState);
}
void EmbeddedPython::leavePythonThread()
{
pThreadState = PyEval_SaveThread();
}
void EmbeddedPython::initialize()
{
#ifdef EXTENSION_DEVELOPMENT
PyObjectGuard mainModuleName(PyUnicode_DecodeFSDefault("python.Adapter"));
if (!mainModuleName)
{
THROW_PYEXCEPTION("Failed to create unicode module name");
}
PyObjectGuard moduleOriginal(PyImport_Import(mainModuleName.get()));
if (!moduleOriginal)
{
THROW_PYEXCEPTION("Failed to import adapter module");
}
// Reload the module to force re-reading the file
PyObjectGuard module(PyImport_ReloadModule(moduleOriginal.get()));
if (!module)
{
THROW_PYEXCEPTION("Failed to reload adapter module");
}
#else
std::string text_resource = ResourceLoader::loadTextResource(dllModuleHandle, PYTHON_ADAPTER, TEXT("PYTHON")).c_str();
PyObject *compiledString = Py_CompileString(
text_resource.c_str(),
"python-adapter.py",
Py_file_input);
PyObjectGuard pCompiledContents(compiledString);
if (!pCompiledContents)
{
THROW_PYEXCEPTION("Failed to compile embedded python module");
}
PyObjectGuard module(PyImport_ExecCodeModule("adapter", pCompiledContents.get()));
if (!module)
{
THROW_PYEXCEPTION("Failed to add compiled module");
}
#endif
PyObjectGuard function(PyObject_GetAttrString(module.get(), "python_adapter"));
if (!function || !PyCallable_Check(function.get()))
{
THROW_PYEXCEPTION("Failed to reference python function 'python_adapter'");
}
pModule = module.transfer();
pFunc = function.transfer();
}
void EmbeddedPython::initModules(modules_t mods)
{
/**
Initialize python sources for modules.
The sources passed here will be used to import `pythia.modulename`.
*/
if (!pModule)
{
THROW_PYEXCEPTION("Pythia adapter not loaded correctly. Not initializing python modules.")
}
PyObjectGuard pDict(PyDict_New());
if (!pDict)
{
THROW_PYEXCEPTION("Could not create a new python dict.")
}
// Fill the dict with the items in the unordered_map
for (const auto& entry: mods)
{
PyObjectGuard pString(PyUnicode_FromWideChar(entry.second.c_str(), -1));
if (!pString)
{
continue;
}
int retval = PyDict_SetItemString(pDict.get(), entry.first.c_str(), pString.get());
if (retval == -1)
{
THROW_PYEXCEPTION("Error while running PyDict_SetItemString.")
}
}
// Perform the call adding the mods sources
PyObjectGuard function(PyObject_GetAttrString(pModule, "init_modules"));
if (!function || !PyCallable_Check(function.get()))
{
THROW_PYEXCEPTION("Failed to reference python function 'init_modules'");
}
PyObjectGuard pResult(PyObject_CallFunctionObjArgs(function.get(), pDict.get(), NULL));
if (pResult)
{
return; // Yay!
}
else
{
THROW_PYEXCEPTION("Failed to execute python init_modules function");
}
}
void EmbeddedPython::deinitialize()
{
Py_CLEAR(pFunc);
Py_CLEAR(pModule);
}
void EmbeddedPython::reload()
{
deinitialize();
try
{
initialize();
LOG_INFO("Python extension successfully reloaded");
}
catch (const std::exception& ex)
{
LOG_ERROR("Caught error when reloading the extension: " << ex.what());
pythonInitializationError = ex.what();
}
}
EmbeddedPython::~EmbeddedPython()
{
enterPythonThread();
deinitialize();
Py_Finalize();
}
unsigned long multipartCounter = 0;
typedef std::vector<std::string> multipartEntry_t;
std::unordered_map<unsigned long long int, multipartEntry_t> multiparts;
std::vector<std::string> splitString(const std::string str, int splitLength)
{
size_t NumSubstrings = str.length() / splitLength;
std::vector<std::string> ret;
for (auto i = 0; i < NumSubstrings; i++)
{
ret.push_back(str.substr(i * splitLength, splitLength));
}
// If there are leftover characters, create a shorter item at the end.
if (str.length() % splitLength != 0)
{
ret.push_back(str.substr(splitLength * NumSubstrings));
}
return ret;
}
std::string handleMultipart(const std::string originalResponse)
{
const int maxLen = 1000;
if (originalResponse.length() <= maxLen)
{
return originalResponse;
}
// Need to handle multipart here
auto entry = splitString(originalResponse, maxLen);
multiparts[multipartCounter] = entry;
//["m", MULTIPART_COUNTER, len(response_split)]
char buff[100];
snprintf(buff, sizeof(buff), "[\"m\", %lu, %lu]", multipartCounter++, (unsigned long)entry.size());
return buff;
}
std::string returnMultipart(unsigned long multipartID)
{
try
{
auto &entry = multiparts.at(multipartID);
auto retval = entry.front();
// TODO: Make this more efficient!
entry.erase(entry.begin());
if (entry.size() == 0)
{
multiparts.erase(multipartID);
}
return retval;
}
catch (std::out_of_range)
{
return "";
}
}
std::string EmbeddedPython::execute(const char * input)
{
#ifdef EXTENSION_DEVELOPMENT
reload();
#endif
if (!pFunc)
{
throw std::runtime_error("No bootstrapping function. Additional error: " + pythonInitializationError);
}
PyObjectGuard pArgs(SQFReader::decode(input));
/*PyObjectGuard pArgs(PyUnicode_FromString(input));
if (!pArgs)
{
throw std::runtime_error("Failed to transform given input to unicode");
}*/
PyObjectGuard pTuple(PyTuple_Pack(1, pArgs.get()));
if (!pTuple)
{
throw std::runtime_error("Failed to convert argument string to tuple");
}
// TODO: Discover multipart request
PyObject* PyFunction = PyList_GetItem(pArgs.get(), 0); // Borrows reference
if (PyFunction)
{
// TODO: Do a Python string comparison
if (PyUnicode_CompareWithASCIIString(PyFunction, "pythia.multipart") == 0)
{
PyObject* PyMultipartID = PyList_GetItem(pArgs.get(), 1); // Borrows reference
if (PyMultipartID)
{
int overflow;
long multipartID = PyLong_AsLongAndOverflow(PyMultipartID, &overflow);
if (overflow == 0 && multipartID >= 0)
{
return returnMultipart(multipartID);
}
else
{
throw std::runtime_error("TODO: Error3");
}
}
else
{
throw std::runtime_error("TODO: Error2");
}
}
}
else
{
throw std::runtime_error("TODO: Error1");
}
PyObjectGuard pResult(PyObject_CallObject(pFunc, pTuple.get()));
if (pResult)
{
return handleMultipart(SQFWriter::encode(pResult.get()));
// Hopefully RVO applies here
//return std::string(PyUnicode_AsUTF8(pResult.get()));
}
else
{
THROW_PYEXCEPTION("Failed to execute python extension");
}
}
<commit_msg>Fixed signed/unsigned mismatch<commit_after>#include "stdafx.h"
#include "EmbeddedPython.h"
#include "ModsLocation.h"
#include "ExceptionFetcher.h"
#include "ResourceLoader.h"
#include <iostream>
#include "resource.h"
#include "Logger.h"
#include "SQFReader.h"
#include "SQFWriter.h"
#define THROW_PYEXCEPTION(_msg_) throw std::runtime_error(_msg_ + std::string(": ") + PyExceptionFetcher().getError());
//#define EXTENSION_DEVELOPMENT 1
EmbeddedPython *python = nullptr;
std::string pythonInitializationError = "";
namespace
{
class PyObjectGuard final
{
public:
PyObjectGuard(PyObject* source) : ptr(source)
{
}
~PyObjectGuard()
{
if (ptr != nullptr)
{
Py_DECREF(ptr);
}
}
PyObject* get() const
{
return ptr;
}
explicit operator bool() const
{
return ptr != nullptr;
}
/// Release ownership
PyObject* transfer()
{
PyObject* tmp = ptr;
ptr = nullptr;
return tmp;
}
private:
PyObjectGuard(const PyObjectGuard&) = delete;
void operator=(const PyObjectGuard&) = delete;
private:
PyObject *ptr;
};
}
EmbeddedPython::EmbeddedPython(HMODULE moduleHandle): dllModuleHandle(moduleHandle)
{
Py_Initialize();
PyEval_InitThreads(); // Initialize and acquire GIL
initialize();
leavePythonThread();
}
void EmbeddedPython::enterPythonThread()
{
PyEval_RestoreThread(pThreadState);
}
void EmbeddedPython::leavePythonThread()
{
pThreadState = PyEval_SaveThread();
}
void EmbeddedPython::initialize()
{
#ifdef EXTENSION_DEVELOPMENT
PyObjectGuard mainModuleName(PyUnicode_DecodeFSDefault("python.Adapter"));
if (!mainModuleName)
{
THROW_PYEXCEPTION("Failed to create unicode module name");
}
PyObjectGuard moduleOriginal(PyImport_Import(mainModuleName.get()));
if (!moduleOriginal)
{
THROW_PYEXCEPTION("Failed to import adapter module");
}
// Reload the module to force re-reading the file
PyObjectGuard module(PyImport_ReloadModule(moduleOriginal.get()));
if (!module)
{
THROW_PYEXCEPTION("Failed to reload adapter module");
}
#else
std::string text_resource = ResourceLoader::loadTextResource(dllModuleHandle, PYTHON_ADAPTER, TEXT("PYTHON")).c_str();
PyObject *compiledString = Py_CompileString(
text_resource.c_str(),
"python-adapter.py",
Py_file_input);
PyObjectGuard pCompiledContents(compiledString);
if (!pCompiledContents)
{
THROW_PYEXCEPTION("Failed to compile embedded python module");
}
PyObjectGuard module(PyImport_ExecCodeModule("adapter", pCompiledContents.get()));
if (!module)
{
THROW_PYEXCEPTION("Failed to add compiled module");
}
#endif
PyObjectGuard function(PyObject_GetAttrString(module.get(), "python_adapter"));
if (!function || !PyCallable_Check(function.get()))
{
THROW_PYEXCEPTION("Failed to reference python function 'python_adapter'");
}
pModule = module.transfer();
pFunc = function.transfer();
}
void EmbeddedPython::initModules(modules_t mods)
{
/**
Initialize python sources for modules.
The sources passed here will be used to import `pythia.modulename`.
*/
if (!pModule)
{
THROW_PYEXCEPTION("Pythia adapter not loaded correctly. Not initializing python modules.")
}
PyObjectGuard pDict(PyDict_New());
if (!pDict)
{
THROW_PYEXCEPTION("Could not create a new python dict.")
}
// Fill the dict with the items in the unordered_map
for (const auto& entry: mods)
{
PyObjectGuard pString(PyUnicode_FromWideChar(entry.second.c_str(), -1));
if (!pString)
{
continue;
}
int retval = PyDict_SetItemString(pDict.get(), entry.first.c_str(), pString.get());
if (retval == -1)
{
THROW_PYEXCEPTION("Error while running PyDict_SetItemString.")
}
}
// Perform the call adding the mods sources
PyObjectGuard function(PyObject_GetAttrString(pModule, "init_modules"));
if (!function || !PyCallable_Check(function.get()))
{
THROW_PYEXCEPTION("Failed to reference python function 'init_modules'");
}
PyObjectGuard pResult(PyObject_CallFunctionObjArgs(function.get(), pDict.get(), NULL));
if (pResult)
{
return; // Yay!
}
else
{
THROW_PYEXCEPTION("Failed to execute python init_modules function");
}
}
void EmbeddedPython::deinitialize()
{
Py_CLEAR(pFunc);
Py_CLEAR(pModule);
}
void EmbeddedPython::reload()
{
deinitialize();
try
{
initialize();
LOG_INFO("Python extension successfully reloaded");
}
catch (const std::exception& ex)
{
LOG_ERROR("Caught error when reloading the extension: " << ex.what());
pythonInitializationError = ex.what();
}
}
EmbeddedPython::~EmbeddedPython()
{
enterPythonThread();
deinitialize();
Py_Finalize();
}
unsigned long multipartCounter = 0;
typedef std::vector<std::string> multipartEntry_t;
std::unordered_map<unsigned long long int, multipartEntry_t> multiparts;
std::vector<std::string> splitString(const std::string str, int splitLength)
{
size_t NumSubstrings = str.length() / splitLength;
std::vector<std::string> ret;
for (size_t i = 0; i < NumSubstrings; i++)
{
ret.push_back(str.substr(i * splitLength, splitLength));
}
// If there are leftover characters, create a shorter item at the end.
if (str.length() % splitLength != 0)
{
ret.push_back(str.substr(splitLength * NumSubstrings));
}
return ret;
}
std::string handleMultipart(const std::string originalResponse)
{
const int maxLen = 1000;
if (originalResponse.length() <= maxLen)
{
return originalResponse;
}
// Need to handle multipart here
auto entry = splitString(originalResponse, maxLen);
multiparts[multipartCounter] = entry;
//["m", MULTIPART_COUNTER, len(response_split)]
char buff[100];
snprintf(buff, sizeof(buff), "[\"m\", %lu, %lu]", multipartCounter++, (unsigned long)entry.size());
return buff;
}
std::string returnMultipart(unsigned long multipartID)
{
try
{
auto &entry = multiparts.at(multipartID);
auto retval = entry.front();
// TODO: Make this more efficient!
entry.erase(entry.begin());
if (entry.size() == 0)
{
multiparts.erase(multipartID);
}
return retval;
}
catch (std::out_of_range)
{
return "";
}
}
std::string EmbeddedPython::execute(const char * input)
{
#ifdef EXTENSION_DEVELOPMENT
reload();
#endif
if (!pFunc)
{
throw std::runtime_error("No bootstrapping function. Additional error: " + pythonInitializationError);
}
PyObjectGuard pArgs(SQFReader::decode(input));
/*PyObjectGuard pArgs(PyUnicode_FromString(input));
if (!pArgs)
{
throw std::runtime_error("Failed to transform given input to unicode");
}*/
PyObjectGuard pTuple(PyTuple_Pack(1, pArgs.get()));
if (!pTuple)
{
throw std::runtime_error("Failed to convert argument string to tuple");
}
// TODO: Discover multipart request
PyObject* PyFunction = PyList_GetItem(pArgs.get(), 0); // Borrows reference
if (PyFunction)
{
// TODO: Do a Python string comparison
if (PyUnicode_CompareWithASCIIString(PyFunction, "pythia.multipart") == 0)
{
PyObject* PyMultipartID = PyList_GetItem(pArgs.get(), 1); // Borrows reference
if (PyMultipartID)
{
int overflow;
long multipartID = PyLong_AsLongAndOverflow(PyMultipartID, &overflow);
if (overflow == 0 && multipartID >= 0)
{
return returnMultipart(multipartID);
}
else
{
throw std::runtime_error("TODO: Error3");
}
}
else
{
throw std::runtime_error("TODO: Error2");
}
}
}
else
{
throw std::runtime_error("TODO: Error1");
}
PyObjectGuard pResult(PyObject_CallObject(pFunc, pTuple.get()));
if (pResult)
{
return handleMultipart(SQFWriter::encode(pResult.get()));
// Hopefully RVO applies here
//return std::string(PyUnicode_AsUTF8(pResult.get()));
}
else
{
THROW_PYEXCEPTION("Failed to execute python extension");
}
}
<|endoftext|> |
<commit_before>/**
* @file ExecuteProcess.cpp
* ExecuteProcess class implementation
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TimeUtil.h"
#include "ExecuteProcess.h"
#include "ProcessContext.h"
#include "ProcessSession.h"
const std::string ExecuteProcess::ProcessorName("ExecuteProcess");
Property ExecuteProcess::Command("Command", "Specifies the command to be executed; if just the name of an executable is provided, it must be in the user's environment PATH.", "");
Property ExecuteProcess::CommandArguments("Command Arguments",
"The arguments to supply to the executable delimited by white space. White space can be escaped by enclosing it in double-quotes.", "");
Property ExecuteProcess::WorkingDir("Working Directory",
"The directory to use as the current working directory when executing the command", "");
Property ExecuteProcess::BatchDuration("Batch Duration",
"If the process is expected to be long-running and produce textual output, a batch duration can be specified.", "0");
Property ExecuteProcess::RedirectErrorStream("Redirect Error Stream",
"If true will redirect any error stream output of the process to the output stream.", "false");
Relationship ExecuteProcess::Success("success", "All created FlowFiles are routed to this relationship.");
void ExecuteProcess::initialize()
{
//! Set the supported properties
std::set<Property> properties;
properties.insert(Command);
properties.insert(CommandArguments);
properties.insert(WorkingDir);
properties.insert(BatchDuration);
properties.insert(RedirectErrorStream);
setSupportedProperties(properties);
//! Set the supported relationships
std::set<Relationship> relationships;
relationships.insert(Success);
setSupportedRelationships(relationships);
}
void ExecuteProcess::onTrigger(ProcessContext *context, ProcessSession *session)
{
std::string value;
if (context->getProperty(Command.getName(), value))
{
this->_command = value;
}
if (context->getProperty(CommandArguments.getName(), value))
{
this->_commandArgument = value;
}
if (context->getProperty(WorkingDir.getName(), value))
{
this->_workingDir = value;
}
if (context->getProperty(BatchDuration.getName(), value))
{
TimeUnit unit;
if (Property::StringToTime(value, _batchDuration, unit) &&
Property::ConvertTimeUnitToMS(_batchDuration, unit, _batchDuration))
{
}
}
if (context->getProperty(RedirectErrorStream.getName(), value))
{
Property::StringToBool(value, _redirectErrorStream);
}
this->_fullCommand = _command + " " + _commandArgument;
if (_fullCommand.length() == 0)
{
yield();
return;
}
if (_workingDir.length() > 0 && _workingDir != ".")
{
// change to working directory
if (chdir(_workingDir.c_str()) != 0)
{
_logger->log_error("Execute Command can not chdir %s", _workingDir.c_str());
yield();
return;
}
}
_logger->log_info("Execute Command %s", _fullCommand.c_str());
// split the command into array
char cstr[_fullCommand.length()+1];
std::strcpy(cstr, _fullCommand.c_str());
char *p = std::strtok (cstr, " ");
int argc = 0;
char *argv[64];
while (p != 0 && argc < 64)
{
argv[argc] = p;
p = std::strtok(NULL, " ");
argc++;
}
argv[argc] = NULL;
int status, died;
if (!_processRunning)
{
_processRunning = true;
// if the process has not launched yet
// create the pipe
if (pipe(_pipefd) == -1)
{
_processRunning = false;
yield();
return;
}
switch (_pid = fork())
{
case -1:
_logger->log_error("Execute Process fork failed");
_processRunning = false;
close(_pipefd[0]);
close(_pipefd[1]);
yield();
break;
case 0 : // this is the code the child runs
close(1); // close stdout
dup(_pipefd[1]); // points pipefd at file descriptor
if (_redirectErrorStream)
// redirect stderr
dup2(_pipefd[1], 2);
close(_pipefd[0]);
execvp(argv[0], argv);
exit(1);
break;
default: // this is the code the parent runs
// the parent isn't going to write to the pipe
close(_pipefd[1]);
if (_batchDuration > 0)
{
while (1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(_batchDuration));
char buffer[4096];
int numRead = read(_pipefd[0], buffer, sizeof(buffer));
if (numRead <= 0)
break;
_logger->log_info("Execute Command Respond %d", numRead);
ExecuteProcess::WriteCallback callback(buffer, numRead);
FlowFileRecord *flowFile = session->create();
if (!flowFile)
continue;
session->write(flowFile, &callback);
session->transfer(flowFile, Success);
session->commit();
}
}
else
{
char buffer[4096];
char *bufPtr = buffer;
int totalRead = 0;
FlowFileRecord *flowFile = NULL;
while (1)
{
int numRead = read(_pipefd[0], bufPtr, (sizeof(buffer) - totalRead));
if (numRead <= 0)
{
if (totalRead > 0)
{
_logger->log_info("Execute Command Respond %d", totalRead);
// child exits and close the pipe
ExecuteProcess::WriteCallback callback(buffer, totalRead);
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
break;
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
session->transfer(flowFile, Success);
}
break;
}
else
{
if (numRead == (sizeof(buffer) - totalRead))
{
// we reach the max buffer size
_logger->log_info("Execute Command Max Respond %d", sizeof(buffer));
ExecuteProcess::WriteCallback callback(buffer, sizeof(buffer));
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
continue;
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
// Rewind
totalRead = 0;
bufPtr = buffer;
}
else
{
totalRead += numRead;
bufPtr += numRead;
}
}
}
}
died= wait(&status);
if (WIFEXITED(status))
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WEXITSTATUS(status), _pid);
}
else
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WTERMSIG(status), _pid);
}
close(_pipefd[0]);
_processRunning = false;
break;
}
}
}
<commit_msg>MINIFI-111 Providing explicit inclusion of cstring in ExecuteProcess needed by gcc environments.<commit_after>/**
* @file ExecuteProcess.cpp
* ExecuteProcess class implementation
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TimeUtil.h"
#include "ExecuteProcess.h"
#include "ProcessContext.h"
#include "ProcessSession.h"
#include <cstring>
const std::string ExecuteProcess::ProcessorName("ExecuteProcess");
Property ExecuteProcess::Command("Command", "Specifies the command to be executed; if just the name of an executable is provided, it must be in the user's environment PATH.", "");
Property ExecuteProcess::CommandArguments("Command Arguments",
"The arguments to supply to the executable delimited by white space. White space can be escaped by enclosing it in double-quotes.", "");
Property ExecuteProcess::WorkingDir("Working Directory",
"The directory to use as the current working directory when executing the command", "");
Property ExecuteProcess::BatchDuration("Batch Duration",
"If the process is expected to be long-running and produce textual output, a batch duration can be specified.", "0");
Property ExecuteProcess::RedirectErrorStream("Redirect Error Stream",
"If true will redirect any error stream output of the process to the output stream.", "false");
Relationship ExecuteProcess::Success("success", "All created FlowFiles are routed to this relationship.");
void ExecuteProcess::initialize()
{
//! Set the supported properties
std::set<Property> properties;
properties.insert(Command);
properties.insert(CommandArguments);
properties.insert(WorkingDir);
properties.insert(BatchDuration);
properties.insert(RedirectErrorStream);
setSupportedProperties(properties);
//! Set the supported relationships
std::set<Relationship> relationships;
relationships.insert(Success);
setSupportedRelationships(relationships);
}
void ExecuteProcess::onTrigger(ProcessContext *context, ProcessSession *session)
{
std::string value;
if (context->getProperty(Command.getName(), value))
{
this->_command = value;
}
if (context->getProperty(CommandArguments.getName(), value))
{
this->_commandArgument = value;
}
if (context->getProperty(WorkingDir.getName(), value))
{
this->_workingDir = value;
}
if (context->getProperty(BatchDuration.getName(), value))
{
TimeUnit unit;
if (Property::StringToTime(value, _batchDuration, unit) &&
Property::ConvertTimeUnitToMS(_batchDuration, unit, _batchDuration))
{
}
}
if (context->getProperty(RedirectErrorStream.getName(), value))
{
Property::StringToBool(value, _redirectErrorStream);
}
this->_fullCommand = _command + " " + _commandArgument;
if (_fullCommand.length() == 0)
{
yield();
return;
}
if (_workingDir.length() > 0 && _workingDir != ".")
{
// change to working directory
if (chdir(_workingDir.c_str()) != 0)
{
_logger->log_error("Execute Command can not chdir %s", _workingDir.c_str());
yield();
return;
}
}
_logger->log_info("Execute Command %s", _fullCommand.c_str());
// split the command into array
char cstr[_fullCommand.length()+1];
std::strcpy(cstr, _fullCommand.c_str());
char *p = std::strtok (cstr, " ");
int argc = 0;
char *argv[64];
while (p != 0 && argc < 64)
{
argv[argc] = p;
p = std::strtok(NULL, " ");
argc++;
}
argv[argc] = NULL;
int status, died;
if (!_processRunning)
{
_processRunning = true;
// if the process has not launched yet
// create the pipe
if (pipe(_pipefd) == -1)
{
_processRunning = false;
yield();
return;
}
switch (_pid = fork())
{
case -1:
_logger->log_error("Execute Process fork failed");
_processRunning = false;
close(_pipefd[0]);
close(_pipefd[1]);
yield();
break;
case 0 : // this is the code the child runs
close(1); // close stdout
dup(_pipefd[1]); // points pipefd at file descriptor
if (_redirectErrorStream)
// redirect stderr
dup2(_pipefd[1], 2);
close(_pipefd[0]);
execvp(argv[0], argv);
exit(1);
break;
default: // this is the code the parent runs
// the parent isn't going to write to the pipe
close(_pipefd[1]);
if (_batchDuration > 0)
{
while (1)
{
std::this_thread::sleep_for(std::chrono::milliseconds(_batchDuration));
char buffer[4096];
int numRead = read(_pipefd[0], buffer, sizeof(buffer));
if (numRead <= 0)
break;
_logger->log_info("Execute Command Respond %d", numRead);
ExecuteProcess::WriteCallback callback(buffer, numRead);
FlowFileRecord *flowFile = session->create();
if (!flowFile)
continue;
session->write(flowFile, &callback);
session->transfer(flowFile, Success);
session->commit();
}
}
else
{
char buffer[4096];
char *bufPtr = buffer;
int totalRead = 0;
FlowFileRecord *flowFile = NULL;
while (1)
{
int numRead = read(_pipefd[0], bufPtr, (sizeof(buffer) - totalRead));
if (numRead <= 0)
{
if (totalRead > 0)
{
_logger->log_info("Execute Command Respond %d", totalRead);
// child exits and close the pipe
ExecuteProcess::WriteCallback callback(buffer, totalRead);
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
break;
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
session->transfer(flowFile, Success);
}
break;
}
else
{
if (numRead == (sizeof(buffer) - totalRead))
{
// we reach the max buffer size
_logger->log_info("Execute Command Max Respond %d", sizeof(buffer));
ExecuteProcess::WriteCallback callback(buffer, sizeof(buffer));
if (!flowFile)
{
flowFile = session->create();
if (!flowFile)
continue;
session->write(flowFile, &callback);
}
else
{
session->append(flowFile, &callback);
}
// Rewind
totalRead = 0;
bufPtr = buffer;
}
else
{
totalRead += numRead;
bufPtr += numRead;
}
}
}
}
died= wait(&status);
if (WIFEXITED(status))
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WEXITSTATUS(status), _pid);
}
else
{
_logger->log_info("Execute Command Complete %s status %d pid %d", _fullCommand.c_str(), WTERMSIG(status), _pid);
}
close(_pipefd[0]);
_processRunning = false;
break;
}
}
}
<|endoftext|> |
<commit_before>#include "FTTextureGlyph.h"
#include "FTGL.h"
FTTextureGlyph::FTTextureGlyph( FT_Glyph glyph, int id, unsigned char* data, GLsizei stride, GLsizei height, float u, float v)
: FTGlyph(),
destWidth(0),
destHeight(0),
numGreys(0),
glTextureID(id)
{
// This function will always fail if the glyph's format isn't scalable????
err = FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1);
if( err || glyph->format != ft_glyph_format_bitmap)
{
return;
}
FT_BitmapGlyph bitmap = ( FT_BitmapGlyph)glyph;
FT_Bitmap* source = &bitmap->bitmap;
//check the pixel mode
//ft_pixel_mode_grays
int srcWidth = source->width;
int srcHeight = source->rows;
int srcPitch = source->pitch;
numGreys = source->num_grays;
advance = glyph->advance.x >> 16;
pos.x = bitmap->left;
pos.y = bitmap->top;
destWidth = srcWidth;
destHeight = srcHeight;
for(int y = 0; y < srcHeight; ++y)
{
for(int x = 0; x < srcWidth; ++x)
{
*( data + ( y * stride + x)) = *( source->buffer + ( y * srcPitch) + x);
}
}
// 0
// +----+
// | |
// | |
// | |
// +----+
// 1
uv[0].x = u;
uv[0].y = v;
uv[1].x = uv[0].x + ( (float)destWidth / (float)stride);
uv[1].y = uv[0].y + ( (float)destHeight / (float)height);
// discard glyph image (bitmap or not)
// Is this the right place to do this?
FT_Done_Glyph( glyph);
}
FTTextureGlyph::~FTTextureGlyph()
{
}
float FTTextureGlyph::Render( const FT_Vector& pen)
{
glGetIntegerv( GL_TEXTURE_2D_BINDING_EXT, &activeTextureID);
if( activeTextureID != glTextureID)
{
glBindTexture( GL_TEXTURE_2D, (GLuint)glTextureID);
}
glBegin( GL_QUADS);
glTexCoord2f( uv[0].x, uv[0].y); glVertex2f( pen.x + pos.x, pen.y + pos.y);
glTexCoord2f( uv[1].x, uv[0].y); glVertex2f( pen.x + destWidth + pos.x, pen.y + pos.y);
glTexCoord2f( uv[1].x, uv[1].y); glVertex2f( pen.x + destWidth + pos.x, pen.y + pos.y - destHeight);
glTexCoord2f( uv[0].x, uv[1].y); glVertex2f( pen.x + pos.x, pen.y + pos.y - destHeight);
glEnd();
return advance;
}
<commit_msg>Set the bounding box
Tidied up some code<commit_after>#include "FTTextureGlyph.h"
#include "FTGL.h"
FTTextureGlyph::FTTextureGlyph( FT_Glyph glyph, int id, unsigned char* data, GLsizei stride, GLsizei height, float u, float v)
: FTGlyph(),
destWidth(0),
destHeight(0),
numGreys(0),
glTextureID(id)
{
// This function will always fail if the glyph's format isn't scalable????
err = FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1);
if( err || glyph->format != ft_glyph_format_bitmap)
{
return;
}
FT_BitmapGlyph bitmap = ( FT_BitmapGlyph)glyph;
FT_Bitmap* source = &bitmap->bitmap;
//check the pixel mode
//ft_pixel_mode_grays
int srcWidth = source->width;
int srcHeight = source->rows;
int srcPitch = source->pitch;
destWidth = srcWidth;
destHeight = srcHeight;
for(int y = 0; y < srcHeight; ++y)
{
for(int x = 0; x < srcWidth; ++x)
{
*( data + ( y * stride + x)) = *( source->buffer + ( y * srcPitch) + x);
}
}
// 0
// +----+
// | |
// | |
// | |
// +----+
// 1
uv[0].x = u;
uv[0].y = v;
uv[1].x = uv[0].x + ( (float)destWidth / (float)stride);
uv[1].y = uv[0].y + ( (float)destHeight / (float)height);
bBox = FTBBox( glyph);
numGreys = source->num_grays;
advance = glyph->advance.x >> 16;
pos.x = bitmap->left;
pos.y = bitmap->top;
// discard glyph image (bitmap or not)
// Is this the right place to do this?
FT_Done_Glyph( glyph);
}
FTTextureGlyph::~FTTextureGlyph()
{
}
float FTTextureGlyph::Render( const FT_Vector& pen)
{
glGetIntegerv( GL_TEXTURE_2D_BINDING_EXT, &activeTextureID);
if( activeTextureID != glTextureID)
{
glBindTexture( GL_TEXTURE_2D, (GLuint)glTextureID);
}
glBegin( GL_QUADS);
glTexCoord2f( uv[0].x, uv[0].y);
glVertex2f( pen.x + pos.x, pen.y + pos.y);
glTexCoord2f( uv[0].x, uv[1].y);
glVertex2f( pen.x + pos.x, pen.y + pos.y - destHeight);
glTexCoord2f( uv[1].x, uv[1].y);
glVertex2f( pen.x + destWidth + pos.x, pen.y + pos.y - destHeight);
glTexCoord2f( uv[1].x, uv[0].y);
glVertex2f( pen.x + destWidth + pos.x, pen.y + pos.y);
glEnd();
return advance;
}
<|endoftext|> |
<commit_before>#include "midiplayer.h"
// Copyright 2017 by LE Ferguson, LLC, licensed under Apache 2.0
#define DELETE_LOG(X) if(X != NULL) { qDebug() << "Freeing " #X; delete X; }
midiPlayer::midiPlayer(QWidget *parent, QString midiFile) : QWidget(parent)
{
qDebug() << "Entered";
setWindowTitle("Midi Player");
errorEncountered = ""; // Once set this cannot be unset in this routine - close and open again
this->setWindowFlags(Qt::Window|Qt::Dialog);
_midiFile = midiFile;
doPlayingLayout(); // This is needed even if not playing to show error
openAndLoadFile();
updateVolume(MUSICALPI_INITIAL_VELOCITY_SCALE);
updateTempo(MUSICALPI_INITIAL_TIME_SCALE);
updateSliders(); // This is really only needed for error conditions since the above won't update then
}
midiPlayer::~midiPlayer()
{
DELETE_LOG(transport);
DELETE_LOG(sch);
DELETE_LOG(msf);
DELETE_LOG(metronome);
DELETE_LOG(song);
DELETE_LOG(mfi);
}
void midiPlayer::openAndLoadFile()
{
canPlay = false;
// Open and see if we can find key information for file
int bar, beat, pulse; // Used to find where measures start/end
int newBar, newBeat, newPulse; // Used to fill in bars
lastBar = 0;
QString step;
try
{
step = "Importing file";
mfi = new TSE3::MidiFileImport(_midiFile.toStdString().c_str(), 1);
step = "Loading song";
song = mfi->load();
step = "Creating time sig track";
tst = song->timeSigTrack(); // used to get timing below
step = "Searching for tracks and parts and bars, track = none yet.";
for (unsigned int trk=0; trk < song->size(); trk++)
{
TSE3::Track *Tk = (*song)[trk];
step = "Searching for tracks and parts and bars, trk = " + QString(trk);
for (unsigned int prt=0; prt < Tk->size(); prt++)
{
TSE3::Part *Pt = (*Tk)[prt];
step = "Searching for tracks and parts and bars, trk = " + QString(trk) + ", part = " + QString(prt);
tst->barBeatPulse(Pt->lastClock(), bar, beat, pulse); // This gives the end, but we need to iterate to see where each measure is for go-to function
lastBar = std::max(bar,lastBar);
for (unsigned int mCnt=0; mCnt < Pt->phrase()->size(); mCnt++)
{
TSE3::MidiEvent me = (*(Pt->phrase()))[mCnt]; // Part contains phrase which contains [] MidiEvents
tst->barBeatPulse(me.time, newBar, newBeat, newPulse);
tst->barBeatPulse(barsClock[newBar],bar, beat, pulse); // This is current setting (may be zero if not set)
if (bar < newBar || (bar == newBar && beat > newBeat) || (bar == newBar && beat == newBeat && pulse > newPulse ) ) barsClock[newBar] = TSE3::Clock(me.time); // We want the first event in the bar
}
}
}
qDebug() << "Last measure = " << lastBar;
step = "Creating metronome";
metronome = new TSE3::Metronome();
step = "Setting preferred scheduler";
TSE3::Plt::UnixMidiSchedulerFactory::setPreferredPlatform(TSE3::Plt::UnixMidiSchedulerFactory::UnixPlatform_Alsa);
step = "Creating factory";
msf = new TSE3::MidiSchedulerFactory();
step = "Creating scheduler";
sch = msf->createScheduler();
step = "Creating transport";
transport = new TSE3::Transport(metronome, sch);
step = "Setting port";
transport->filter()->setPort(MUSICALPI_MIDI_PORT);
step = "Setting panic";
setPanic(transport->startPanic());
setPanic(transport->endPanic());
}
catch (const TSE3::Error &e)
{
qDebug() << "Error=" << TSE3::errString(e.reason());
errorEncountered = "Failure loading and processing song, step = " + step + ", error = " + TSE3::errString(e.reason());
return;
}
catch (...)
{
qDebug() << "Got an error we didn't catch with TSE3::error";
}
qDebug() << "Transport all set, ready to play";
canPlay = true;
}
void midiPlayer::doPlayingLayout()
{
outLayout = new QVBoxLayout(this);
outLayout->setSpacing(15);
gridLayout = new QGridLayout();
gridLayout->setVerticalSpacing(15);
qDebug() << "Layouts created";
outLayout->addLayout(gridLayout);
measureGo = new QPushButton("???",this);
measureGo->setStyleSheet("padding: 2px;");
connect(measureGo,&QPushButton::clicked, this, &midiPlayer::go);
measureInLabel = new QLabel(this);
measureInLabel->setText("Go to measure#: ");
measureIn = new QLineEdit("1",this); // Leave default as blank so we can tell if value entered
measureInRange = new QLabel(this);
gridLayout->addWidget(measureGo,0,0,1,1);
gridLayout->addWidget(measureInLabel,0,1,1,1);
gridLayout->addWidget(measureIn,0,2,1,1);
gridLayout->addWidget(measureInRange,0,3,1,1);
tempoLabel = new QLabel("Tempo %: ",this);
tempoSlider = new QSlider(Qt::Horizontal,this);
tempoSlider->setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 white, stop:1 Grey);");
tempoSlider->setMaximum(500); // I can't find a variable for this
tempoSlider->setMinimum(1);
connect(tempoSlider,SIGNAL(valueChanged(int)),this,SLOT(updateTempo(int)));
tempoValueLabel = new QLabel("???",this);
gridLayout->addWidget(tempoLabel,1,1,1,1);
gridLayout->addWidget(tempoSlider,1,2,1,1);
gridLayout->addWidget(tempoValueLabel,1,3,1,1);
volumeLabel = new QLabel("Volume %", this);
volumeSlider = new QSlider(Qt::Horizontal,this);
volumeSlider->setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 white, stop:1 Grey); ");
volumeValueLabel = new QLabel("???",this);
volumeSlider->setMaximum(200);
volumeSlider->setMinimum(1);
connect(volumeSlider,SIGNAL(valueChanged(int)),this,SLOT(updateVolume(int)));
gridLayout->addWidget(volumeLabel,2,1,1,1);
gridLayout->addWidget(volumeSlider,2,2,1,1);
gridLayout->addWidget(volumeValueLabel,2,3,1,1);
qDebug() << "Volume Slider setup done";
songLabel = new QLabel(_midiFile,this);
outLayout->addWidget(songLabel);
errorLabel = new QLabel("",this);
outLayout->addWidget(errorLabel);
}
void midiPlayer::updateSliders()
{
int bar, beat, pulse;
if(canPlay)
{
qDebug() << "Updating sliders while can play";
playStatus = transport->status();
if(playStatus == TSE3::Transport::Playing) transport->poll(); // Must call this frequently to keep data going, only if playing
// Don't update the slider unnecessarily as it causes the change routine to fire even if not changed
if(tempoSlider->value() != transport->filter()->timeScale()) tempoSlider->setValue(transport->filter()->timeScale());
tempoValueLabel->setText(QString::number(tempoSlider->value()) + " %");
if(volumeSlider->value() != transport->filter()->velocityScale()) volumeSlider->setValue(transport->filter()->velocityScale());
volumeValueLabel->setText(QString::number(volumeSlider->value()) + " %");
// use error slot but not highlighted for status
switch(playStatus)
{
case TSE3::Transport::Resting:
errorLabel->setText("Song is resting (done or not started)");
measureGo->setText(" Play ");
tempoSlider->setEnabled(true);
volumeSlider->setEnabled(true);
break;
case TSE3::Transport::Playing:
errorLabel->setText("Song is playing");
measureGo->setText(" Stop ");
tempoSlider->setDisabled(true);
volumeSlider->setDisabled(true);
tst->barBeatPulse(sch->clock(), bar, beat, pulse);
measureIn->setText(QString::number(bar));
break;
case TSE3::Transport::Recording:
errorLabel->setText("Song is recording (never should get here!!)");
break;
case TSE3::Transport::SynchroPlaying:
errorLabel->setText("Song is Synchro-playing (never should get here!!)");
break;
case TSE3::Transport::SynchroRecording:
errorLabel->setText("Song is Synchro-Recording (never should get here!!)");
break;
default:
errorLabel->setText("Received invalid status from transport - bug");
}
}
else
{
qDebug() << "Updating sliders but can't play";
// Disable controls
tempoSlider->setDisabled(true);
volumeSlider->setDisabled(true);
measureGo->setDisabled(true);
measureGo->setText("Error");
// Highlight and show error
errorLabel->setText(errorEncountered);
errorLabel->setStyleSheet("color: red;");
}
}
void midiPlayer::updateVolume(int newVolume)
{
qDebug() << "Entered";
if(!canPlay) return; // Shouldn't get here but just in case
transport->filter()->setVelocityScale(newVolume);
updateSliders(); // hasten reflection of new info
}
void midiPlayer::updateTempo(int newTempo)
{
qDebug() << "Entered";
if(!canPlay) return; // Shouldn't get here but just in case
transport->filter()->setTimeScale(newTempo);
updateSliders(); // hasten reflection of new info
}
void midiPlayer::go()
{
if(canPlay && playStatus == TSE3::Transport::Resting) // Hitting play from here uses measure or starts over if blank
{
qDebug() << "Entered Go and resting, switching to playing";
TSE3::Clock newClock(0);
if(measureIn->text() != "" )
{
int newBar = measureIn->text().toInt();
newBar = std::max(1,std::min(lastBar,newBar));
newClock = barsClock[newBar];
qDebug() << "Picked new bar " << newBar;
}
transport->play(song,newClock);
if(timer==NULL)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateSliders()));
timer->start(1000);
qDebug() << "First time through, starting timer";
}
measureGo->setText("Stop");
}
else if (canPlay && playStatus == TSE3::Transport::Playing) // Hitting stop ends play entirely but updates measure to where we were
{
qDebug() << "Playing, so changing to stopped";
sch->stop();
measureGo->setText("Play");
}
else if (!canPlay)
{
qDebug() << "Can't play so doing nothing in go -- shouldn't be able to get here";
measureGo->setDisabled(true); // Shouldn't get here but if we do we can't play
}
else qDebug() << "Bad logic in Go, fell through status = " << playStatus;
}
void midiPlayer::closeEvent(QCloseEvent *event)
{
event->ignore(); // We ignore it here and signal the caller to delete us, but do stop any playing
if(canPlay && playStatus == TSE3::Transport::Playing) transport->play(0,0);
emit requestToClose();
}
void midiPlayer::setPanic(TSE3::Panic *panic)
{
panic->setMidiReset(true);
panic->setGmReset(true);
panic->setGsReset(true);
panic->setXgReset(true);
}
<commit_msg>More start/stop work<commit_after>#include "midiplayer.h"
// Copyright 2017 by LE Ferguson, LLC, licensed under Apache 2.0
#define DELETE_LOG(X) if(X != NULL) { qDebug() << "Freeing " #X; delete X; }
midiPlayer::midiPlayer(QWidget *parent, QString midiFile) : QWidget(parent)
{
qDebug() << "Entered";
setWindowTitle("Midi Player");
errorEncountered = ""; // Once set this cannot be unset in this routine - close and open again
this->setWindowFlags(Qt::Window|Qt::Dialog);
_midiFile = midiFile;
doPlayingLayout(); // This is needed even if not playing to show error
openAndLoadFile();
updateVolume(MUSICALPI_INITIAL_VELOCITY_SCALE);
updateTempo(MUSICALPI_INITIAL_TIME_SCALE);
updateSliders(); // This is really only needed for error conditions since the above won't update then
}
midiPlayer::~midiPlayer()
{
DELETE_LOG(transport);
DELETE_LOG(sch);
DELETE_LOG(msf);
DELETE_LOG(metronome);
DELETE_LOG(song);
DELETE_LOG(mfi);
}
void midiPlayer::openAndLoadFile()
{
canPlay = false;
// Open and see if we can find key information for file
int bar, beat, pulse; // Used to find where measures start/end
int newBar, newBeat, newPulse; // Used to fill in bars
lastBar = 0;
QString step;
try
{
step = "Importing file";
mfi = new TSE3::MidiFileImport(_midiFile.toStdString().c_str(), 1);
step = "Loading song";
song = mfi->load();
step = "Creating time sig track";
tst = song->timeSigTrack(); // used to get timing below
step = "Searching for tracks and parts and bars, track = none yet.";
for (unsigned int trk=0; trk < song->size(); trk++)
{
TSE3::Track *Tk = (*song)[trk];
step = "Searching for tracks and parts and bars, trk = " + QString(trk);
for (unsigned int prt=0; prt < Tk->size(); prt++)
{
TSE3::Part *Pt = (*Tk)[prt];
step = "Searching for tracks and parts and bars, trk = " + QString(trk) + ", part = " + QString(prt);
tst->barBeatPulse(Pt->lastClock(), bar, beat, pulse); // This gives the end, but we need to iterate to see where each measure is for go-to function
lastBar = std::max(bar,lastBar);
for (unsigned int mCnt=0; mCnt < Pt->phrase()->size(); mCnt++)
{
TSE3::MidiEvent me = (*(Pt->phrase()))[mCnt]; // Part contains phrase which contains [] MidiEvents
tst->barBeatPulse(me.time, newBar, newBeat, newPulse);
tst->barBeatPulse(barsClock[newBar],bar, beat, pulse); // This is current setting (may be zero if not set)
if (bar < newBar || (bar == newBar && beat > newBeat) || (bar == newBar && beat == newBeat && pulse > newPulse ) ) barsClock[newBar] = TSE3::Clock(me.time); // We want the first event in the bar
}
}
}
qDebug() << "Last measure = " << lastBar;
step = "Creating metronome";
metronome = new TSE3::Metronome();
step = "Setting preferred scheduler";
TSE3::Plt::UnixMidiSchedulerFactory::setPreferredPlatform(TSE3::Plt::UnixMidiSchedulerFactory::UnixPlatform_Alsa);
step = "Creating factory";
msf = new TSE3::MidiSchedulerFactory();
step = "Creating scheduler";
sch = msf->createScheduler();
step = "Creating transport";
transport = new TSE3::Transport(metronome, sch);
step = "Setting port";
transport->filter()->setPort(MUSICALPI_MIDI_PORT);
step = "Setting panic";
setPanic(transport->startPanic());
setPanic(transport->endPanic());
qDebug() << "Adaptive lookahead is " << transport->adaptiveLookAhead() << " (setting to true).";
transport->setAdaptiveLookAhead(true);
qDebug() << "Lookahead = " << transport->lookAhead();
}
catch (const TSE3::Error &e)
{
qDebug() << "Error=" << TSE3::errString(e.reason());
errorEncountered = "Failure loading and processing song, step = " + step + ", error = " + TSE3::errString(e.reason());
return;
}
catch (...)
{
qDebug() << "Got an error we didn't catch with TSE3::error";
}
qDebug() << "Transport all set, ready to play";
canPlay = true;
}
void midiPlayer::doPlayingLayout()
{
outLayout = new QVBoxLayout(this);
outLayout->setSpacing(15);
gridLayout = new QGridLayout();
gridLayout->setVerticalSpacing(15);
qDebug() << "Layouts created";
outLayout->addLayout(gridLayout);
measureGo = new QPushButton("???",this);
measureGo->setStyleSheet("padding: 2px;");
connect(measureGo,&QPushButton::clicked, this, &midiPlayer::go);
measureInLabel = new QLabel(this);
measureInLabel->setText("Go to measure#: ");
measureIn = new QLineEdit("1",this); // Leave default as blank so we can tell if value entered
measureInRange = new QLabel(this);
gridLayout->addWidget(measureGo,0,0,1,1);
gridLayout->addWidget(measureInLabel,0,1,1,1);
gridLayout->addWidget(measureIn,0,2,1,1);
gridLayout->addWidget(measureInRange,0,3,1,1);
tempoLabel = new QLabel("Tempo %: ",this);
tempoSlider = new QSlider(Qt::Horizontal,this);
tempoSlider->setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 white, stop:1 Grey);");
tempoSlider->setMaximum(500); // I can't find a variable for this
tempoSlider->setMinimum(1);
connect(tempoSlider,SIGNAL(valueChanged(int)),this,SLOT(updateTempo(int)));
tempoValueLabel = new QLabel("???",this);
gridLayout->addWidget(tempoLabel,1,1,1,1);
gridLayout->addWidget(tempoSlider,1,2,1,1);
gridLayout->addWidget(tempoValueLabel,1,3,1,1);
volumeLabel = new QLabel("Volume %", this);
volumeSlider = new QSlider(Qt::Horizontal,this);
volumeSlider->setStyleSheet("background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 white, stop:1 Grey); ");
volumeValueLabel = new QLabel("???",this);
volumeSlider->setMaximum(200);
volumeSlider->setMinimum(1);
connect(volumeSlider,SIGNAL(valueChanged(int)),this,SLOT(updateVolume(int)));
gridLayout->addWidget(volumeLabel,2,1,1,1);
gridLayout->addWidget(volumeSlider,2,2,1,1);
gridLayout->addWidget(volumeValueLabel,2,3,1,1);
qDebug() << "Volume Slider setup done";
songLabel = new QLabel(_midiFile,this);
outLayout->addWidget(songLabel);
errorLabel = new QLabel("",this);
outLayout->addWidget(errorLabel);
}
void midiPlayer::updateSliders()
{
int bar, beat, pulse;
if(canPlay)
{
qDebug() << "Updating sliders while can play";
playStatus = transport->status();
if(playStatus == TSE3::Transport::Playing) transport->poll(); // Must call this frequently to keep data going, only if playing
// Don't update the slider unnecessarily as it causes the change routine to fire even if not changed
if(tempoSlider->value() != transport->filter()->timeScale()) tempoSlider->setValue(transport->filter()->timeScale());
tempoValueLabel->setText(QString::number(tempoSlider->value()) + " %");
if(volumeSlider->value() != transport->filter()->velocityScale()) volumeSlider->setValue(transport->filter()->velocityScale());
volumeValueLabel->setText(QString::number(volumeSlider->value()) + " %");
// use error slot but not highlighted for status
switch(playStatus)
{
case TSE3::Transport::Resting:
errorLabel->setText("Song is resting (done or not started)");
measureGo->setText(" Play ");
tempoSlider->setEnabled(true);
volumeSlider->setEnabled(true);
break;
case TSE3::Transport::Playing:
errorLabel->setText("Song is playing");
measureGo->setText(" Stop ");
tempoSlider->setDisabled(true);
volumeSlider->setDisabled(true);
tst->barBeatPulse(sch->clock(), bar, beat, pulse);
measureIn->setText(QString::number(bar));
break;
case TSE3::Transport::Recording:
errorLabel->setText("Song is recording (never should get here!!)");
break;
case TSE3::Transport::SynchroPlaying:
errorLabel->setText("Song is Synchro-playing (never should get here!!)");
break;
case TSE3::Transport::SynchroRecording:
errorLabel->setText("Song is Synchro-Recording (never should get here!!)");
break;
default:
errorLabel->setText("Received invalid status from transport - bug");
}
}
else
{
qDebug() << "Updating sliders but can't play";
// Disable controls
tempoSlider->setDisabled(true);
volumeSlider->setDisabled(true);
measureGo->setDisabled(true);
measureGo->setText("Error");
// Highlight and show error
errorLabel->setText(errorEncountered);
errorLabel->setStyleSheet("color: red;");
}
}
void midiPlayer::updateVolume(int newVolume)
{
qDebug() << "Entered";
if(!canPlay) return; // Shouldn't get here but just in case
transport->filter()->setVelocityScale(newVolume);
updateSliders(); // hasten reflection of new info
}
void midiPlayer::updateTempo(int newTempo)
{
qDebug() << "Entered";
if(!canPlay) return; // Shouldn't get here but just in case
transport->filter()->setTimeScale(newTempo);
updateSliders(); // hasten reflection of new info
}
void midiPlayer::go()
{
if(canPlay && playStatus == TSE3::Transport::Resting) // Hitting play from here uses measure or starts over if blank
{
qDebug() << "Entered Go and resting, switching to playing";
TSE3::Clock newClock(0);
if(measureIn->text() != "" )
{
int newBar = measureIn->text().toInt();
newBar = std::max(1,std::min(lastBar,newBar));
newClock = barsClock[newBar - 1]; // I do not know but I seem to have to start a measure ahead (and can't seem to start on the first)
qDebug() << "Picked new bar " << newBar;
}
transport->play(song,newClock);
if(timer==NULL)
{
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateSliders()));
timer->start(1000);
qDebug() << "First time through, starting timer";
}
measureGo->setText("Stop");
}
else if (canPlay && playStatus == TSE3::Transport::Playing) // Hitting stop ends play entirely but updates measure to where we were
{
qDebug() << "Playing, so changing to stopped";
sch->stop();
transport->play(0,0);
measureGo->setText("Play");
}
else if (!canPlay)
{
qDebug() << "Can't play so doing nothing in go -- shouldn't be able to get here";
measureGo->setDisabled(true); // Shouldn't get here but if we do we can't play
}
else qDebug() << "Bad logic in Go, fell through status = " << playStatus;
}
void midiPlayer::closeEvent(QCloseEvent *event)
{
event->ignore(); // We ignore it here and signal the caller to delete us, but do stop any playing
if(canPlay && playStatus == TSE3::Transport::Playing) transport->play(0,0);
emit requestToClose();
}
void midiPlayer::setPanic(TSE3::Panic *panic)
{
panic->setMidiReset(true);
panic->setGmReset(true);
panic->setGsReset(true);
panic->setXgReset(true);
}
<|endoftext|> |
<commit_before>// Copyright (C) 2014 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include "theia/sfm/nonlinear_reconstruction_estimator.h"
#include <Eigen/Core>
#include "theia/util/random.h"
#include "theia/util/timer.h"
#include "theia/sfm/bundle_adjustment/bundle_adjustment.h"
#include "theia/sfm/estimate_track.h"
#include "theia/sfm/filter_view_pairs_from_cycles.h"
#include "theia/sfm/filter_view_pairs_from_orientation.h"
#include "theia/sfm/filter_view_pairs_from_relative_translation.h"
#include "theia/sfm/reconstruction.h"
#include "theia/sfm/reconstruction_estimator_options.h"
#include "theia/sfm/reconstruction_estimator_utils.h"
#include "theia/sfm/pose/estimate_positions_nonlinear.h"
#include "theia/sfm/pose/estimate_rotations_robust.h"
#include "theia/sfm/view_graph/orientations_from_view_graph.h"
#include "theia/sfm/twoview_info.h"
#include "theia/sfm/view_graph/remove_disconnected_view_pairs.h"
#include "theia/sfm/view_graph/view_graph.h"
#include "theia/solvers/sample_consensus_estimator.h"
namespace theia {
using Eigen::Vector3d;
namespace {
FilterViewPairsFromRelativeTranslationOptions
SetRelativeTranslationFilteringOptions(
const ReconstructionEstimatorOptions& options) {
FilterViewPairsFromRelativeTranslationOptions fvpfrt_options;
fvpfrt_options.num_threads = options.num_threads;
fvpfrt_options.num_iterations = options.translation_filtering_num_iterations;
fvpfrt_options.translation_projection_tolerance =
options.translation_filtering_projection_tolerance;
return fvpfrt_options;
}
// Sets the nonlinear position estimation options from the reconstruction
// estimator options.
NonlinearPositionEstimatorOptions SetNonlinearPositionEstimatorOptions(
const ReconstructionEstimatorOptions& options) {
NonlinearPositionEstimatorOptions npe_options;
npe_options.num_threads = options.num_threads;
npe_options.robust_loss_width =
options.position_estimation_robust_loss_scale;
npe_options.min_num_points_per_view =
options.position_estimation_min_num_tracks_per_view;
npe_options.point_to_camera_weight =
options.position_estimation_point_to_camera_weight;
npe_options.max_num_reweighted_iterations =
options.position_estimation_max_reweighted_iterations;
return npe_options;
}
ViewId RandomViewId(const ViewGraph& view_graph) {
const auto& view_pairs = view_graph.GetAllEdges();
// Collect all view ids.
std::unordered_set<ViewId> views;
for (const auto& view_pair : view_pairs) {
views.insert(view_pair.first.first);
views.insert(view_pair.first.second);
}
// Find a random view id. TODO(cmsweeney): Choose the "best" random view by
// some criterion such as highest connectivity.
InitRandomGenerator();
const int num_advances = RandInt(0, views.size() - 1);
auto it = views.begin();
std::advance(it, num_advances);
return *it;
}
void SetUnderconstrainedAsUnestimated(Reconstruction* reconstruction) {
int num_underconstrained_views = -1;
int num_underconstrained_tracks = -1;
while (num_underconstrained_views != 0 && num_underconstrained_tracks != 0) {
num_underconstrained_views =
SetUnderconstrainedViewsToUnestimated(reconstruction);
num_underconstrained_tracks =
SetUnderconstrainedTracksToUnestimated(reconstruction);
}
}
} // namespace
NonlinearReconstructionEstimator::NonlinearReconstructionEstimator(
const ReconstructionEstimatorOptions& options) {
options_ = options;
translation_filter_options_ = SetRelativeTranslationFilteringOptions(options);
position_estimator_options_ = SetNonlinearPositionEstimatorOptions(options);
ransac_params_ = SetRansacParameters(options);
}
// The pipeline for estimating camera poses and structure is as follows:
// 1) Filter potentially bad pairwise geometries by enforcing a loop
// constaint on rotations that form a triplet.
// 2) Initialize focal lengths.
// 3) Estimate the global rotation for each camera.
// 4) Remove any pairwise geometries where the relative rotation is not
// consistent with the global rotation.
// 5) Optimize the relative translation given the known rotations.
// 6) Filter potentially bad relative translations with 1D SfM.
// 7) Estimate positions.
// 8) Estimate structure.
// 9) Bundle adjustment.
// 10) TODO: localize any unestimated cameras, retriangulate, and bundle
// adjust.
//
// After each filtering step we remove any views which are no longer connected
// to the largest connected component in the view graph.
ReconstructionEstimatorSummary NonlinearReconstructionEstimator::Estimate(
ViewGraph* view_graph, Reconstruction* reconstruction) {
CHECK_NOTNULL(reconstruction);
reconstruction_ = reconstruction;
view_graph_ = view_graph;
orientations_.clear();
positions_.clear();
ReconstructionEstimatorSummary summary;
Timer timer;
LOG(INFO) << "Computing a reconstruction from " << view_graph_->NumEdges()
<< " initial view pairs.";
// Step 1. Filter the initial view graph and remove any bad two view
// geometries.
LOG(INFO) << "Filtering the intial view graph.";
timer.Reset();
if (!FilterInitialViewGraph()) {
LOG(INFO) << "Insufficient view pairs to perform estimation.";
return summary;
}
summary.initial_view_graph_filtering_time = timer.ElapsedTimeInSeconds();
// Step 2. Calibrate any uncalibrated cameras.
LOG(INFO) << "Calibrating any uncalibrated cameras.";
timer.Reset();
CalibrateCameras();
summary.camera_intrinsics_calibration_time = timer.ElapsedTimeInSeconds();
// Step 3. Estimate global rotations.
LOG(INFO) << "Estimating the global rotations of all cameras.";
timer.Reset();
EstimateGlobalRotations();
summary.rotation_estimation_time = timer.ElapsedTimeInSeconds();
// Step 4. Filter bad rotations.
LOG(INFO) << "Filtering any bad rotation estimations.";
timer.Reset();
FilterRotations();
summary.rotation_filtering_time = timer.ElapsedTimeInSeconds();
// Step 5. Optimize relative translations.
LOG(INFO) << "Optimizing the pairwise translation estimations.";
timer.Reset();
OptimizePairwiseTranslations();
summary.relative_translation_optimization_time = timer.ElapsedTimeInSeconds();
// Step 6. Filter bad relative translations.
LOG(INFO) << "Filtering any bad relative translations.";
timer.Reset();
FilterRelativeTranslation();
summary.relative_translation_filtering_time = timer.ElapsedTimeInSeconds();
// Step 7. Estimate global positions.
LOG(INFO) << "Estimating the positions of all cameras.";
timer.Reset();
EstimatePosition();
summary.position_estimation_time = timer.ElapsedTimeInSeconds();
// Set the poses in the reconstruction object.
SetReconstructionFromEstimatedPoses(orientations_,
positions_,
reconstruction_);
// Step 8. Triangulate features.
LOG(INFO) << "Triangulating all features.";
timer.Reset();
EstimateStructure();
summary.triangulation_time = timer.ElapsedTimeInSeconds();
// Step 9. Bundle Adjustment.
LOG(INFO) << "Performing bundle adjustment.";
timer.Reset();
BundleAdjustment();
summary.bundle_adjustment_time = timer.ElapsedTimeInSeconds();
for (int i = 0; i < options_.num_retriangulation_iterations; i++) {
const int num_features_removed = RemoveOutlierFeatures(
options_.max_reprojection_error_in_pixels, reconstruction_);
LOG(INFO) << num_features_removed << " outlier features were removed.";
SetUnderconstrainedAsUnestimated(reconstruction_);
// Step 8. Triangulate features.
LOG(INFO) << "Triangulating all features again.";
timer.Reset();
EstimateStructure();
summary.triangulation_time += timer.ElapsedTimeInSeconds();
// Step 9. Bundle Adjustment.
LOG(INFO) << "Performing bundle adjustment again.";
timer.Reset();
BundleAdjustment();
summary.bundle_adjustment_time += timer.ElapsedTimeInSeconds();
}
// Set the output parameters.
GetEstimatedViewsFromReconstruction(*reconstruction_,
&summary.estimated_views);
GetEstimatedTracksFromReconstruction(*reconstruction_,
&summary.estimated_tracks);
summary.success = true;
return summary;
}
bool NonlinearReconstructionEstimator::FilterInitialViewGraph() {
// Remove any view pairs that do not have a sufficient number of inliers.
std::unordered_set<ViewIdPair> view_pairs_to_remove;
const auto& view_pairs = view_graph_->GetAllEdges();
for (const auto& view_pair : view_pairs) {
if (view_pair.second.num_verified_matches <
options_.min_num_two_view_inliers) {
view_pairs_to_remove.insert(view_pair.first);
}
}
for (const ViewIdPair view_id_pair : view_pairs_to_remove) {
view_graph_->RemoveEdge(view_id_pair.first, view_id_pair.second);
}
// Only reconstruct the largest connected component.
RemoveDisconnectedViewPairs(view_graph_);
return view_graph_->NumEdges() >= 2;
}
void NonlinearReconstructionEstimator::CalibrateCameras() {
if (options_.initialize_focal_lengths_from_median_estimate) {
InitializeFocalLengthsFromMedian(*view_graph_, reconstruction_);
} else {
InitializeFocalLengthsFromImageSize(reconstruction_);
}
}
void NonlinearReconstructionEstimator::EstimateGlobalRotations() {
const ViewId random_starting_view = RandomViewId(*view_graph_);
OrientationsFromViewGraph(*view_graph_, random_starting_view, &orientations_);
const auto& relative_rotations = RelativeRotationsFromViewGraph(*view_graph_);
RobustRotationEstimator::Options rotation_estimator_options;
RobustRotationEstimator rotation_estimator(rotation_estimator_options,
relative_rotations);
CHECK(rotation_estimator.EstimateRotations(&orientations_))
<< "Could not estimate rotations.";
}
void NonlinearReconstructionEstimator::FilterRotations() {
// Filter view pairs based on the relative rotation and the estimated global
// orientations.
FilterViewPairsFromOrientation(
orientations_,
options_.rotation_filtering_max_difference_degrees,
view_graph_);
RemoveDisconnectedViewPairs(view_graph_);
}
void NonlinearReconstructionEstimator::OptimizePairwiseTranslations() {
if (options_.refine_relative_translations_after_rotation_estimation) {
RefineRelativeTranslationsWithKnownRotations(*reconstruction_,
orientations_,
options_.num_threads,
view_graph_);
}
}
void NonlinearReconstructionEstimator::FilterRelativeTranslation() {
// Filter potentially bad relative translations.
FilterViewPairsFromRelativeTranslation(translation_filter_options_,
orientations_,
view_graph_);
RemoveDisconnectedViewPairs(view_graph_);
}
void NonlinearReconstructionEstimator::EstimatePosition() {
// Estimate position.
const auto& view_pairs = view_graph_->GetAllEdges();
NonlinearPositionEstimator position_estimator(position_estimator_options_,
*reconstruction_,
view_pairs);
CHECK(position_estimator.EstimatePositions(orientations_, &positions_))
<< "Position estimation failed!";
LOG(INFO) << positions_.size()
<< " camera positions were estimated successfully.";
}
void NonlinearReconstructionEstimator::EstimateStructure() {
// Estimate all tracks.
EstimateTrackOptions triangulation_options;
triangulation_options.max_acceptable_reprojection_error_pixels =
options_.triangulation_max_reprojection_error_in_pixels;
triangulation_options.min_triangulation_angle_degrees =
options_.min_triangulation_angle_degrees;
triangulation_options.bundle_adjustment = options_.bundle_adjust_tracks;
EstimateAllTracks(triangulation_options,
options_.num_threads,
reconstruction_);
}
void NonlinearReconstructionEstimator::BundleAdjustment() {
// Bundle adjustment.
bundle_adjustment_options_ =
SetBundleAdjustmentOptions(options_, positions_.size());
const auto& bundle_adjustment_summary =
BundleAdjustReconstruction(bundle_adjustment_options_, reconstruction_);
CHECK(bundle_adjustment_summary.success) << "Could not perform BA.";
}
} // namespace theia
<commit_msg>Fixed incorrect include line.<commit_after>// Copyright (C) 2014 The Regents of the University of California (Regents).
// 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 Regents or University of California 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 HOLDERS 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.
//
// Please contact the author of this library if you have any questions.
// Author: Chris Sweeney (cmsweeney@cs.ucsb.edu)
#include "theia/sfm/nonlinear_reconstruction_estimator.h"
#include <Eigen/Core>
#include "theia/util/random.h"
#include "theia/util/timer.h"
#include "theia/sfm/bundle_adjustment/bundle_adjustment.h"
#include "theia/sfm/estimate_track.h"
#include "theia/sfm/filter_view_graph_cycles_by_rotation.h"
#include "theia/sfm/filter_view_pairs_from_orientation.h"
#include "theia/sfm/filter_view_pairs_from_relative_translation.h"
#include "theia/sfm/reconstruction.h"
#include "theia/sfm/reconstruction_estimator_options.h"
#include "theia/sfm/reconstruction_estimator_utils.h"
#include "theia/sfm/pose/estimate_positions_nonlinear.h"
#include "theia/sfm/pose/estimate_rotations_robust.h"
#include "theia/sfm/view_graph/orientations_from_view_graph.h"
#include "theia/sfm/twoview_info.h"
#include "theia/sfm/view_graph/remove_disconnected_view_pairs.h"
#include "theia/sfm/view_graph/view_graph.h"
#include "theia/solvers/sample_consensus_estimator.h"
namespace theia {
using Eigen::Vector3d;
namespace {
FilterViewPairsFromRelativeTranslationOptions
SetRelativeTranslationFilteringOptions(
const ReconstructionEstimatorOptions& options) {
FilterViewPairsFromRelativeTranslationOptions fvpfrt_options;
fvpfrt_options.num_threads = options.num_threads;
fvpfrt_options.num_iterations = options.translation_filtering_num_iterations;
fvpfrt_options.translation_projection_tolerance =
options.translation_filtering_projection_tolerance;
return fvpfrt_options;
}
// Sets the nonlinear position estimation options from the reconstruction
// estimator options.
NonlinearPositionEstimatorOptions SetNonlinearPositionEstimatorOptions(
const ReconstructionEstimatorOptions& options) {
NonlinearPositionEstimatorOptions npe_options;
npe_options.num_threads = options.num_threads;
npe_options.robust_loss_width =
options.position_estimation_robust_loss_scale;
npe_options.min_num_points_per_view =
options.position_estimation_min_num_tracks_per_view;
npe_options.point_to_camera_weight =
options.position_estimation_point_to_camera_weight;
npe_options.max_num_reweighted_iterations =
options.position_estimation_max_reweighted_iterations;
return npe_options;
}
ViewId RandomViewId(const ViewGraph& view_graph) {
const auto& view_pairs = view_graph.GetAllEdges();
// Collect all view ids.
std::unordered_set<ViewId> views;
for (const auto& view_pair : view_pairs) {
views.insert(view_pair.first.first);
views.insert(view_pair.first.second);
}
// Find a random view id. TODO(cmsweeney): Choose the "best" random view by
// some criterion such as highest connectivity.
InitRandomGenerator();
const int num_advances = RandInt(0, views.size() - 1);
auto it = views.begin();
std::advance(it, num_advances);
return *it;
}
void SetUnderconstrainedAsUnestimated(Reconstruction* reconstruction) {
int num_underconstrained_views = -1;
int num_underconstrained_tracks = -1;
while (num_underconstrained_views != 0 && num_underconstrained_tracks != 0) {
num_underconstrained_views =
SetUnderconstrainedViewsToUnestimated(reconstruction);
num_underconstrained_tracks =
SetUnderconstrainedTracksToUnestimated(reconstruction);
}
}
} // namespace
NonlinearReconstructionEstimator::NonlinearReconstructionEstimator(
const ReconstructionEstimatorOptions& options) {
options_ = options;
translation_filter_options_ = SetRelativeTranslationFilteringOptions(options);
position_estimator_options_ = SetNonlinearPositionEstimatorOptions(options);
ransac_params_ = SetRansacParameters(options);
}
// The pipeline for estimating camera poses and structure is as follows:
// 1) Filter potentially bad pairwise geometries by enforcing a loop
// constaint on rotations that form a triplet.
// 2) Initialize focal lengths.
// 3) Estimate the global rotation for each camera.
// 4) Remove any pairwise geometries where the relative rotation is not
// consistent with the global rotation.
// 5) Optimize the relative translation given the known rotations.
// 6) Filter potentially bad relative translations with 1D SfM.
// 7) Estimate positions.
// 8) Estimate structure.
// 9) Bundle adjustment.
// 10) TODO: localize any unestimated cameras, retriangulate, and bundle
// adjust.
//
// After each filtering step we remove any views which are no longer connected
// to the largest connected component in the view graph.
ReconstructionEstimatorSummary NonlinearReconstructionEstimator::Estimate(
ViewGraph* view_graph, Reconstruction* reconstruction) {
CHECK_NOTNULL(reconstruction);
reconstruction_ = reconstruction;
view_graph_ = view_graph;
orientations_.clear();
positions_.clear();
ReconstructionEstimatorSummary summary;
Timer timer;
LOG(INFO) << "Computing a reconstruction from " << view_graph_->NumEdges()
<< " initial view pairs.";
// Step 1. Filter the initial view graph and remove any bad two view
// geometries.
LOG(INFO) << "Filtering the intial view graph.";
timer.Reset();
if (!FilterInitialViewGraph()) {
LOG(INFO) << "Insufficient view pairs to perform estimation.";
return summary;
}
summary.initial_view_graph_filtering_time = timer.ElapsedTimeInSeconds();
// Step 2. Calibrate any uncalibrated cameras.
LOG(INFO) << "Calibrating any uncalibrated cameras.";
timer.Reset();
CalibrateCameras();
summary.camera_intrinsics_calibration_time = timer.ElapsedTimeInSeconds();
// Step 3. Estimate global rotations.
LOG(INFO) << "Estimating the global rotations of all cameras.";
timer.Reset();
EstimateGlobalRotations();
summary.rotation_estimation_time = timer.ElapsedTimeInSeconds();
// Step 4. Filter bad rotations.
LOG(INFO) << "Filtering any bad rotation estimations.";
timer.Reset();
FilterRotations();
summary.rotation_filtering_time = timer.ElapsedTimeInSeconds();
// Step 5. Optimize relative translations.
LOG(INFO) << "Optimizing the pairwise translation estimations.";
timer.Reset();
OptimizePairwiseTranslations();
summary.relative_translation_optimization_time = timer.ElapsedTimeInSeconds();
// Step 6. Filter bad relative translations.
LOG(INFO) << "Filtering any bad relative translations.";
timer.Reset();
FilterRelativeTranslation();
summary.relative_translation_filtering_time = timer.ElapsedTimeInSeconds();
// Step 7. Estimate global positions.
LOG(INFO) << "Estimating the positions of all cameras.";
timer.Reset();
EstimatePosition();
summary.position_estimation_time = timer.ElapsedTimeInSeconds();
// Set the poses in the reconstruction object.
SetReconstructionFromEstimatedPoses(orientations_,
positions_,
reconstruction_);
// Step 8. Triangulate features.
LOG(INFO) << "Triangulating all features.";
timer.Reset();
EstimateStructure();
summary.triangulation_time = timer.ElapsedTimeInSeconds();
// Step 9. Bundle Adjustment.
LOG(INFO) << "Performing bundle adjustment.";
timer.Reset();
BundleAdjustment();
summary.bundle_adjustment_time = timer.ElapsedTimeInSeconds();
for (int i = 0; i < options_.num_retriangulation_iterations; i++) {
const int num_features_removed = RemoveOutlierFeatures(
options_.max_reprojection_error_in_pixels, reconstruction_);
LOG(INFO) << num_features_removed << " outlier features were removed.";
SetUnderconstrainedAsUnestimated(reconstruction_);
// Step 8. Triangulate features.
LOG(INFO) << "Triangulating all features again.";
timer.Reset();
EstimateStructure();
summary.triangulation_time += timer.ElapsedTimeInSeconds();
// Step 9. Bundle Adjustment.
LOG(INFO) << "Performing bundle adjustment again.";
timer.Reset();
BundleAdjustment();
summary.bundle_adjustment_time += timer.ElapsedTimeInSeconds();
}
// Set the output parameters.
GetEstimatedViewsFromReconstruction(*reconstruction_,
&summary.estimated_views);
GetEstimatedTracksFromReconstruction(*reconstruction_,
&summary.estimated_tracks);
summary.success = true;
return summary;
}
bool NonlinearReconstructionEstimator::FilterInitialViewGraph() {
// Remove any view pairs that do not have a sufficient number of inliers.
std::unordered_set<ViewIdPair> view_pairs_to_remove;
const auto& view_pairs = view_graph_->GetAllEdges();
for (const auto& view_pair : view_pairs) {
if (view_pair.second.num_verified_matches <
options_.min_num_two_view_inliers) {
view_pairs_to_remove.insert(view_pair.first);
}
}
for (const ViewIdPair view_id_pair : view_pairs_to_remove) {
view_graph_->RemoveEdge(view_id_pair.first, view_id_pair.second);
}
// Only reconstruct the largest connected component.
RemoveDisconnectedViewPairs(view_graph_);
return view_graph_->NumEdges() >= 2;
}
void NonlinearReconstructionEstimator::CalibrateCameras() {
if (options_.initialize_focal_lengths_from_median_estimate) {
InitializeFocalLengthsFromMedian(*view_graph_, reconstruction_);
} else {
InitializeFocalLengthsFromImageSize(reconstruction_);
}
}
void NonlinearReconstructionEstimator::EstimateGlobalRotations() {
const ViewId random_starting_view = RandomViewId(*view_graph_);
OrientationsFromViewGraph(*view_graph_, random_starting_view, &orientations_);
const auto& relative_rotations = RelativeRotationsFromViewGraph(*view_graph_);
RobustRotationEstimator::Options rotation_estimator_options;
RobustRotationEstimator rotation_estimator(rotation_estimator_options,
relative_rotations);
CHECK(rotation_estimator.EstimateRotations(&orientations_))
<< "Could not estimate rotations.";
}
void NonlinearReconstructionEstimator::FilterRotations() {
// Filter view pairs based on the relative rotation and the estimated global
// orientations.
FilterViewPairsFromOrientation(
orientations_,
options_.rotation_filtering_max_difference_degrees,
view_graph_);
RemoveDisconnectedViewPairs(view_graph_);
}
void NonlinearReconstructionEstimator::OptimizePairwiseTranslations() {
if (options_.refine_relative_translations_after_rotation_estimation) {
RefineRelativeTranslationsWithKnownRotations(*reconstruction_,
orientations_,
options_.num_threads,
view_graph_);
}
}
void NonlinearReconstructionEstimator::FilterRelativeTranslation() {
// Filter potentially bad relative translations.
FilterViewPairsFromRelativeTranslation(translation_filter_options_,
orientations_,
view_graph_);
RemoveDisconnectedViewPairs(view_graph_);
}
void NonlinearReconstructionEstimator::EstimatePosition() {
// Estimate position.
const auto& view_pairs = view_graph_->GetAllEdges();
NonlinearPositionEstimator position_estimator(position_estimator_options_,
*reconstruction_,
view_pairs);
CHECK(position_estimator.EstimatePositions(orientations_, &positions_))
<< "Position estimation failed!";
LOG(INFO) << positions_.size()
<< " camera positions were estimated successfully.";
}
void NonlinearReconstructionEstimator::EstimateStructure() {
// Estimate all tracks.
EstimateTrackOptions triangulation_options;
triangulation_options.max_acceptable_reprojection_error_pixels =
options_.triangulation_max_reprojection_error_in_pixels;
triangulation_options.min_triangulation_angle_degrees =
options_.min_triangulation_angle_degrees;
triangulation_options.bundle_adjustment = options_.bundle_adjust_tracks;
EstimateAllTracks(triangulation_options,
options_.num_threads,
reconstruction_);
}
void NonlinearReconstructionEstimator::BundleAdjustment() {
// Bundle adjustment.
bundle_adjustment_options_ =
SetBundleAdjustmentOptions(options_, positions_.size());
const auto& bundle_adjustment_summary =
BundleAdjustReconstruction(bundle_adjustment_options_, reconstruction_);
CHECK(bundle_adjustment_summary.success) << "Could not perform BA.";
}
} // namespace theia
<|endoftext|> |
<commit_before>#include "dreal/util/box.h"
#include <iostream>
#include <limits>
#include <type_traits>
#include <vector>
#include <gtest/gtest.h>
#include "dreal/symbolic/symbolic.h"
using std::cout;
using std::endl;
using std::numeric_limits;
using std::vector;
namespace dreal {
// TODO(soonho): Add more tests.
namespace {
GTEST_TEST(BoxTest, InplaceUnion) {
const Variable x{"x"};
const Variable y{"y"};
Box b1{{x, y}};
b1[x] = Box::Interval(0, 1);
b1[y] = Box::Interval(0, 1);
Box b2{{x, y}};
b2[x] = Box::Interval(2, 3);
b2[y] = Box::Interval(3, 4);
b1.InplaceUnion(b2);
EXPECT_EQ(b1[x], Box::Interval(0, 3));
EXPECT_EQ(b1[y], Box::Interval(0, 4));
// No changes on b2.
EXPECT_EQ(b2[x], Box::Interval(2, 3));
EXPECT_EQ(b2[y], Box::Interval(3, 4));
}
GTEST_TEST(BoxTest, BisectInt) {
const Variable x{"x", Variable::Type::INTEGER};
const Variable y{"y", Variable::Type::INTEGER};
Box b;
b.Add(x);
b.Add(y);
b[x] = Box::Interval(-numeric_limits<double>::infinity(),
numeric_limits<double>::infinity());
b[y] = Box::Interval(-numeric_limits<double>::infinity(),
numeric_limits<double>::infinity());
const std::pair<Box, Box> p{b.bisect(x)};
EXPECT_FALSE(p.first.empty());
EXPECT_FALSE(p.second.empty());
}
GTEST_TEST(BoxTest, is_nothrow_move_constructible) {
static_assert(std::is_nothrow_move_constructible<Box::Interval>::value,
"Box::Interval should be nothrow_move_constructible.");
static_assert(std::is_nothrow_move_constructible<Box::IntervalVector>::value,
"Box::IntervalVector should be nothrow_move_constructible.");
static_assert(std::is_nothrow_move_constructible<Box>::value,
"Box should be nothrow_move_constructible.");
}
} // namespace
} // namespace dreal
<commit_msg>test(dreal/util): add more tests to box_test<commit_after>#include "dreal/util/box.h"
#include <iostream>
#include <limits>
#include <type_traits>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "dreal/symbolic/symbolic.h"
using std::cout;
using std::endl;
using std::is_nothrow_move_constructible;
using std::numeric_limits;
using std::pair;
using std::vector;
namespace dreal {
namespace {
class BoxTest : public ::testing::Test {
protected:
// Real Variables.
const Variable x_{"x"};
const Variable y_{"y"};
const Variable z_{"z"};
const Variable w_{"w"};
// Integer Variables.
const Variable i_{"i", Variable::Type::INTEGER};
const Variable j_{"j", Variable::Type::INTEGER};
// Binary Variables.
const Variable b1_{"i", Variable::Type::BINARY};
const Variable b2_{"j", Variable::Type::BINARY};
const double inf_{numeric_limits<double>::infinity()};
};
TEST_F(BoxTest, Add) {
Box b1{{x_}};
EXPECT_EQ(b1[x_].lb(), -inf_);
EXPECT_EQ(b1[x_].ub(), inf_);
b1.Add(y_);
EXPECT_EQ(b1[y_].lb(), -inf_);
EXPECT_EQ(b1[y_].ub(), inf_);
b1.Add(z_, -5, 10);
EXPECT_EQ(b1[z_].lb(), -5);
EXPECT_EQ(b1[z_].ub(), 10);
}
TEST_F(BoxTest, Empty) {
Box b1{{x_}};
EXPECT_FALSE(b1.empty());
b1.set_empty();
EXPECT_TRUE(b1.empty());
}
TEST_F(BoxTest, IndexOperator) {
Box b1;
b1.Add(x_, 3, 5);
b1.Add(y_, 6, 10);
EXPECT_EQ(b1[0], b1[x_]);
EXPECT_EQ(b1[1], b1[y_]);
const Box b2{b1};
EXPECT_EQ(b2[0], b2[x_]);
EXPECT_EQ(b2[1], b2[y_]);
EXPECT_EQ(b1[0], b2[x_]);
EXPECT_EQ(b1[1], b2[y_]);
}
TEST_F(BoxTest, IntervalVector) {
Box b1;
b1.Add(x_, 3, 5);
b1.Add(y_, 6, 10);
EXPECT_EQ(b1.interval_vector()[0], b1[x_]);
// Update
b1.get_mutable_interval_vector()[0] = Box::Interval(0, 1);
EXPECT_EQ(b1[x_].lb(), 0);
EXPECT_EQ(b1[x_].ub(), 1);
const Box b2{b1};
EXPECT_EQ(b2.interval_vector()[0].lb(), 0);
EXPECT_EQ(b2.interval_vector()[0].ub(), 1);
}
TEST_F(BoxTest, VariableVariables) {
const Box b1{{x_, y_, z_}};
vector<Variable> variables{x_, y_, z_};
const vector<Variable>& variables_in_b1{b1.variables()};
EXPECT_EQ(variables_in_b1.size(), 3);
EXPECT_EQ(variables_in_b1[0], x_);
EXPECT_EQ(variables_in_b1[1], y_);
EXPECT_EQ(variables_in_b1[2], z_);
}
TEST_F(BoxTest, Index) {
const Box b1{{x_, y_, z_}};
EXPECT_EQ(b1.index(x_), 0);
EXPECT_EQ(b1.index(y_), 1);
EXPECT_EQ(b1.index(z_), 2);
}
TEST_F(BoxTest, MaxDiam) {
Box b1;
b1.Add(x_, -10, 10);
b1.Add(y_, 5, 5);
b1.Add(z_, -1, 1);
const pair<double, int> maxdiam_result{b1.MaxDiam()};
EXPECT_EQ(maxdiam_result.first, 20.0);
EXPECT_EQ(b1.variable(maxdiam_result.second), x_);
}
TEST_F(BoxTest, Sharing) {
Box b1{{x_, y_}};
// b1 is not shared yet, so we should just update its internal
// states.
b1.Add(z_);
// Now, b1 and b2 are shared.
Box b2{b1};
// Internal structure of b2 should be cloned before updated. It makes sure
// that b1 is not affected.
b2.Add(w_);
EXPECT_EQ(b1.size(), 3 /* x, y, z */);
EXPECT_EQ(b2.size(), 4 /* x, y, z, w_ */);
}
TEST_F(BoxTest, InplaceUnion) {
Box b1{{x_, y_}};
b1[x_] = Box::Interval(0, 1);
b1[y_] = Box::Interval(0, 1);
Box b2{{x_, y_}};
b2[x_] = Box::Interval(2, 3);
b2[y_] = Box::Interval(3, 4);
b1.InplaceUnion(b2);
EXPECT_EQ(b1[x_], Box::Interval(0, 3));
EXPECT_EQ(b1[y_], Box::Interval(0, 4));
// No changes on b2.
EXPECT_EQ(b2[x_], Box::Interval(2, 3));
EXPECT_EQ(b2[y_], Box::Interval(3, 4));
}
TEST_F(BoxTest, BisectReal) {
Box box;
box.Add(x_, -10, 10);
box.Add(i_, -5, 5);
box.Add(b1_, 0, 1);
const pair<Box, Box> p{box.bisect(x_)};
const Box& box1{p.first};
const Box& box2{p.second};
EXPECT_EQ(box1[x_].lb(), box[x_].lb());
EXPECT_EQ(box1[x_].ub(), 0.0);
EXPECT_EQ(box1[i_], box[i_]);
EXPECT_EQ(box1[b1_], box[b1_]);
EXPECT_EQ(box2[x_].lb(), box1[x_].ub());
EXPECT_EQ(box2[x_].ub(), box[x_].ub());
EXPECT_EQ(box2[i_], box[i_]);
EXPECT_EQ(box2[b1_], box[b1_]);
}
TEST_F(BoxTest, BisectInteger) {
Box box;
box.Add(x_, -10, 10);
box.Add(i_, -5, 5);
box.Add(b1_, 0, 1);
const pair<Box, Box> p{box.bisect(i_)};
const Box& box1{p.first};
const Box& box2{p.second};
EXPECT_EQ(box1[i_].lb(), box[i_].lb());
EXPECT_EQ(box1[i_].ub(), 0.0);
EXPECT_EQ(box1[x_], box[x_]);
EXPECT_EQ(box1[b1_], box[b1_]);
EXPECT_EQ(box2[i_].lb(), box1[i_].ub() + 1);
EXPECT_EQ(box2[i_].ub(), box[i_].ub());
EXPECT_EQ(box2[x_], box[x_]);
EXPECT_EQ(box2[b1_], box[b1_]);
}
TEST_F(BoxTest, BisectBinary) {
Box box;
box.Add(x_, -10, 10);
box.Add(i_, -5, 5);
box.Add(b1_, 0, 1);
const pair<Box, Box> p{box.bisect(b1_)};
const Box& box1{p.first};
const Box& box2{p.second};
EXPECT_EQ(box1[b1_].lb(), box[b1_].lb());
EXPECT_EQ(box1[b1_].ub(), 0.0);
EXPECT_EQ(box1[x_], box[x_]);
EXPECT_EQ(box1[i_], box[i_]);
EXPECT_EQ(box2[b1_].lb(), box1[b1_].ub() + 1);
EXPECT_EQ(box2[b1_].ub(), box[b1_].ub());
EXPECT_EQ(box2[x_], box[x_]);
EXPECT_EQ(box2[i_], box[i_]);
}
TEST_F(BoxTest, NotBisectable) {
Box box;
// x = [10, 10 + ε]
box.Add(x_, 10, std::nextafter(10, 11));
// [10, 10 + ε] is not bisectable.
EXPECT_THROW(box.bisect(x_), std::runtime_error);
// y is not in the box -> non-bisectable.
EXPECT_THROW(box.bisect(y_), std::runtime_error);
}
TEST_F(BoxTest, Equality) {
Box b1;
b1.Add(x_, -10, 10);
b1.Add(y_, -5, 5);
Box b2{b1};
EXPECT_TRUE(b1 == b2);
EXPECT_FALSE(b1 != b2);
b2.Add(z_, -1, 1);
EXPECT_FALSE(b1 == b2);
EXPECT_TRUE(b1 != b2);
Box b3{b1};
EXPECT_TRUE(b1 == b3);
EXPECT_FALSE(b1 != b3);
b3[y_] = Box::Interval(-5, 6);
EXPECT_FALSE(b1 == b3);
EXPECT_TRUE(b1 != b3);
}
// Checks types in Box are nothrow move-constructible so that the
// vectors including them can be processed efficiently.
TEST_F(BoxTest, is_nothrow_move_constructible) {
static_assert(is_nothrow_move_constructible<Box::Interval>::value,
"Box::Interval should be nothrow_move_constructible.");
static_assert(is_nothrow_move_constructible<Box::IntervalVector>::value,
"Box::IntervalVector should be nothrow_move_constructible.");
static_assert(is_nothrow_move_constructible<Box>::value,
"Box should be nothrow_move_constructible.");
}
} // namespace
} // namespace dreal
<|endoftext|> |
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/lineBasedFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);
parpars.registerParameter("i_dcd", "input dcd-file or", INFILE, false);
//TODO offer the alternatives in a more elegant way!
parpars.registerParameter("i_transformations", "input transformation file for rigid rmsd clustering ", INFILE, false);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output dcd-file name for first solution ", STRING, true, "", true);
parpars.registerParameter("o_id", "output id ", STRING, true, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution ", STRING, true, "", true);
parpars.registerParameter("o_dcd", "output directory for the reduced cluster set (one structure per final cluster) ", STRING, false, "", true);
// register String parameter for supplying minimal rmsd between clusters
parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);
// choice of cluster algorithm
parpars.registerParameter("alg", "algorithm used for clustering (CLINK_DEFAYS, NEAREST_NEIGHBOR_CHAIN_WARD, SLINK_SIBSON, TRIVIAL_COMPLETE_LINKAGE) ", STRING, false, "CLINK_DEFAYS");
list<String> cluster_algs;
cluster_algs.push_back("CLINK_DEFAYS");
cluster_algs.push_back("TRIVIAL_COMPLETE_LINKAGE");
cluster_algs.push_back("NEAREST_NEIGHBOR_CHAIN_WARD");
cluster_algs.push_back("SLINK_SIBSON");
parpars.setParameterRestrictions("alg", cluster_algs);
// choice of atom rmsd scope
parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
list<String> rmsd_levels;
rmsd_levels.push_back("C_ALPHA");
//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
rmsd_levels.push_back("BACKBONE");
rmsd_levels.push_back("ALL_ATOMS");
parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);
// choice of rmsd type
parpars.registerParameter("rmsd_type", "rmsd type used for clustering (SNAPSHOT_RMSD, RIGID_RMSD, CENTER_OF_MASS_DISTANCE) ", STRING, false, "SNAPSHOT_RMSD");
list<String> rmsd_types;
rmsd_types.push_back("SNAPSHOT_RMSD");
rmsd_types.push_back("RIGID_RMSD");
rmsd_types.push_back("CENTER_OF_MASS_DISTANCE");
parpars.setParameterRestrictions("rmsd_type", rmsd_types);
// register bool parameter for using pre-clustering
parpars.registerFlag("use_refinement", "Apply a second clustering run with different options");
// refinement algorithm
parpars.registerParameter("refine_alg", "algorithm used for second clustering run (CLINK_DEFAYS, NEAREST_NEIGHBOR_CHAIN_WARD, SLINK_SIBSON, TRIVIAL_COMPLETE_LINKAGE) ", STRING, false, "CLINK_DEFAYS");
parpars.setParameterRestrictions("refine_alg", cluster_algs);
// refinment rmsd type
parpars.registerParameter("refine_rmsd_type", "rmsd type used for second clustering run (SNAPSHOT_RMSD, RIGID_RMSD, CENTER_OF_MASS_DISTANCE) ", STRING, false, "SNAPSHOT_RMSD");
parpars.setParameterRestrictions("refine_rmsd_type", rmsd_types);
// refinement rmsd scope
parpars.registerParameter("refine_rmsd_scope", "atoms to be considered for rmsd score in second clustering run (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
parpars.setParameterRestrictions("refine_rmsd_scope", rmsd_levels);
// the manual
String man = "This tool computes clusters of docking poses given as conformation set using a CLINK or SLINK algorithm.\n\nParameters are the input ConformationSet (-i_dcd), one corresponding pdb file (-i_pdb), and a naming schema for the results (-o). Optional parameters are the algorithm (-alg), the minimal rmsd between the final clusters (-rmsd_cutoff), the rmsd type, and the scope/level of detail of the rmsd computation (-rmsd_scope). The optional parameter -o_dcd set the output directory for the reduced cluster set.\n\nOutput of this tool is a dcd file containing the reduced cluster ConformationSet.";
parpars.setToolManual(man);
// here we set the types of I/O files
parpars.setSupportedFormats("i_dcd","dcd");
parpars.setSupportedFormats("i_pdb","pdb");
parpars.setSupportedFormats("i_transformations","txt");
parpars.setSupportedFormats("o","dcd");
parpars.setSupportedFormats("o_dcd","dcd");
parpars.parse(argc, argv);
//////////////////////////////////////////////////
// read the input
PDBFile pdb;
pdb.open(parpars.get("i_pdb"));
System sys;
pdb.read(sys);
ConformationSet cs;
cs.setup(sys);
if (parpars.has("i_dcd"))
{
/*
//TODO fix, when solution found for the "dcd or transformation alternativ" problem
if (parpars.has("rmsd_type") && (parpars.get("rmsd_type") == "RIGID_RMSD"))
{
Log << "Trajectory input file cannot be used with rmsd_type 'RIGID_RMSD'. Abort!" << endl;
//TODO Implement an automatic conversion from dcd to transformation file format!
return 0;
}
*/
cs.readDCDFile(parpars.get("i_dcd"));
}
cs.resetScoring();
PoseClustering pc;
if (parpars.has("i_transformations"))
{
if (parpars.has("rmsd_type"))
{
if (parpars.get("rmsd_type") != "RIGID_RMSD")
{
Log << "Transformation input file can only be used with rmsd_type 'RIGID_RMSD'. Abort!" << endl;
return 0;
}
}
else
{
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
}
pc.setBaseSystemAndTransformations(sys, parpars.get("i_transformations"));
}
if (parpars.has("rmsd_cutoff"))
{
float rmsd = parpars.get("rmsd_cutoff").toInt();
pc.options.setReal(PoseClustering::Option::DISTANCE_THRESHOLD, rmsd);
}
if (parpars.has("rmsd_scope"))
{
String scope = parpars.get("rmsd_scope");
if (scope == "C_ALPHA")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA);
else if (scope == "BACKBONE")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE);
else if (scope == "ALL_ATOMS")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS);
else
Log.info() << "Unknown value " << scope << " for option rmsd_scope." << endl;
}
if (parpars.has("alg"))
{
String alg = parpars.get("alg");
if (alg == "CLINK_DEFAYS")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::CLINK_DEFAYS);
else if (alg == "SLINK_SIBSON")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::SLINK_SIBSON);
else if (alg == "TRIVIAL_COMPLETE_LINKAGE")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::TRIVIAL_COMPLETE_LINKAGE);
else if (alg == " NEAREST_NEIGHBOR_CHAIN_WARD")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::NEAREST_NEIGHBOR_CHAIN_WARD);
else
Log.info() << "Unknown value " << alg << " for option alg." << endl;
}
if (parpars.has("rmsd_type"))
{
String type = parpars.get("rmsd_type");
if (type == "SNAPSHOT_RMSD")
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::SNAPSHOT_RMSD);
else if (type == "RIGID_RMSD")
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
else if (type == "CENTER_OF_MASS_DISTANCE")
{
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::CENTER_OF_MASS_DISTANCE);
Log << "Parameter rmsd_scope will be ignored!" << endl;
}
else
Log.info() << "Unknown value " << type << " for option rmsd_type." << endl;
}
pc.setConformationSet(&cs);
pc.compute();
// do we need a second clustering run?
if (parpars.has("use_refinement"))
{
// get the options
Options refine_options = pc.options;
if (parpars.has("refine_rmsd_scope"))
{
String scope = parpars.get("refine_rmsd_scope");
if (scope == "C_ALPHA")
refine_options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA);
else if (scope == "BACKBONE")
refine_options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE);
else if (scope == "ALL_ATOMS")
refine_options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS);
else
Log.info() << "Unknown value " << scope << " for option refine_rmsd_scope." << endl;
}
if (parpars.has("refine_alg"))
{
String alg = parpars.get("refine_alg");
if (alg == "CLINK_DEFAYS")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::CLINK_DEFAYS);
else if (alg == "SLINK_SIBSON")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::SLINK_SIBSON);
else if (alg == "TRIVIAL_COMPLETE_LINKAGE")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::TRIVIAL_COMPLETE_LINKAGE);
else if (alg == " NEAREST_NEIGHBOR_CHAIN_WARD")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::NEAREST_NEIGHBOR_CHAIN_WARD);
else
Log.info() << "Unknown value " << alg << " for option refine_alg." << endl;
}
if (parpars.has("refine_rmsd_type"))
{
String type = parpars.get("refine_rmsd_type");
if (type == "SNAPSHOT_RMSD")
refine_options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::SNAPSHOT_RMSD);
else if (type == "RIGID_RMSD")
refine_options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
else if (type == "CENTER_OF_MASS_DISTANCE")
{
refine_options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::CENTER_OF_MASS_DISTANCE);
Log << "Parameter rmsd_scope will be ignored!" << endl;
}
else
Log.info() << "Unknown value " << type << " for option refine_rmsd_type." << endl;
}
pc.refineClustering(refine_options);
}
Size num_clusters = pc.getNumberOfClusters();
Log << "Computed " << num_clusters << " clusters, start writing..." << endl;
for (Size i = 0; i < num_clusters; i++)
{
Log << " Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;
if (parpars.has("rmsd_type") && parpars.get("rmsd_type") != "RIGID_RMSD")
{
boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_cluster" + String(i)
+ "_visible_dcd";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
new_cs->writeDCDFile(outfile_name);
}
}
// print
pc.printClusters();
pc.printClusterRMSDs();
if (parpars.has("o_dcd"))
{
String outfile_name = String(parpars.get("o_dcd"));
boost::shared_ptr<ConformationSet> cs = pc.getReducedConformationSet();
cs->writeDCDFile(outfile_name);
}
Log << "done." << endl;
return 0;
}
<commit_msg>DockPoseClustering: more options for output of clusters.<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
#include <BALL/DOCKING/COMMON/poseClustering.h>
#include <BALL/FORMAT/DCDFile.h>
#include <BALL/FORMAT/PDBFile.h>
#include <BALL/FORMAT/lineBasedFile.h>
#include <BALL/DOCKING/COMMON/conformationSet.h>
#include <BALL/FORMAT/commandlineParser.h>
#include <iostream>
#include "version.h"
using namespace std;
using namespace BALL;
int main (int argc, char **argv)
{
// instantiate CommandlineParser object supplying
// - tool name
// - short description
// - version string
// - build date
// - category
CommandlineParser parpars("DockPoseClustering", "clusters docking poses ", VERSION, String(__DATE__), "Docking");
// we register an input file parameter
// - CLI switch
// - description
// - Inputfile
parpars.registerParameter("i_pdb", "input pdb-file", INFILE, true);
parpars.registerParameter("i_dcd", "input dcd-file or", INFILE, false);
//TODO offer the alternatives in a more elegant way!
parpars.registerParameter("i_transformations", "input transformation file for rigid rmsd clustering ", INFILE, false);
// we register an output file parameter
// - description
// - Outputfile
// - required
parpars.registerParameter("o", "output dcd-file name for first solution ", STRING, true, "", true);
parpars.registerParameter("o_type", "output type (dcd, index_list, or rmsd_matrix) ", STRING, false, "dcd");
list<String> output_types;
output_types.push_back("dcd");
output_types.push_back("index_list");
output_types.push_back("rmsd_matrix");
parpars.setParameterRestrictions("o_type", output_types);
parpars.registerParameter("o_id", "output id ", STRING, false, "", true);
parpars.registerParameter("o_dir", "output directory for 2nd to last solution ", STRING, false, "", true);
parpars.registerParameter("o_dcd", "output directory for the reduced cluster set (one structure per final cluster) ", STRING, false, "", true);
// register String parameter for supplying minimal rmsd between clusters
parpars.registerParameter("rmsd_cutoff", "minimal rmsd between the final clusters (default 5.0) ", DOUBLE, false, 5.0);
parpars.setParameterRestrictions("rmsd_cutoff", 0, 100);
// choice of cluster algorithm
parpars.registerParameter("alg", "algorithm used for clustering (CLINK_DEFAYS, NEAREST_NEIGHBOR_CHAIN_WARD, SLINK_SIBSON, TRIVIAL_COMPLETE_LINKAGE) ", STRING, false, "CLINK_DEFAYS");
list<String> cluster_algs;
cluster_algs.push_back("CLINK_DEFAYS");
cluster_algs.push_back("TRIVIAL_COMPLETE_LINKAGE");
cluster_algs.push_back("NEAREST_NEIGHBOR_CHAIN_WARD");
cluster_algs.push_back("SLINK_SIBSON");
parpars.setParameterRestrictions("alg", cluster_algs);
// choice of atom rmsd scope
parpars.registerParameter("rmsd_scope", "atoms to be considered for rmsd score (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
list<String> rmsd_levels;
rmsd_levels.push_back("C_ALPHA");
//rmsd_levels.push_back("HEAVY_ATOMS"); //TODO
rmsd_levels.push_back("BACKBONE");
rmsd_levels.push_back("ALL_ATOMS");
parpars.setParameterRestrictions("rmsd_scope", rmsd_levels);
// choice of rmsd type
parpars.registerParameter("rmsd_type", "rmsd type used for clustering (SNAPSHOT_RMSD, RIGID_RMSD, CENTER_OF_MASS_DISTANCE) ", STRING, false, "SNAPSHOT_RMSD");
list<String> rmsd_types;
rmsd_types.push_back("SNAPSHOT_RMSD");
rmsd_types.push_back("RIGID_RMSD");
rmsd_types.push_back("CENTER_OF_MASS_DISTANCE");
parpars.setParameterRestrictions("rmsd_type", rmsd_types);
// register bool parameter for using pre-clustering
parpars.registerFlag("use_refinement", "Apply a second clustering run with different options (-refine_alg <string>, -refine_rmsd_type <string>, and -refine_rmsd_scope <string>)");
// refinement algorithm
parpars.registerParameter("refine_alg", "algorithm used for second clustering run (CLINK_DEFAYS, NEAREST_NEIGHBOR_CHAIN_WARD, SLINK_SIBSON, TRIVIAL_COMPLETE_LINKAGE) ", STRING, false, "CLINK_DEFAYS");
parpars.setParameterRestrictions("refine_alg", cluster_algs);
// refinment rmsd type
parpars.registerParameter("refine_rmsd_type", "rmsd type used for second clustering run (SNAPSHOT_RMSD, RIGID_RMSD, CENTER_OF_MASS_DISTANCE) ", STRING, false, "SNAPSHOT_RMSD");
parpars.setParameterRestrictions("refine_rmsd_type", rmsd_types);
// refinement rmsd scope
parpars.registerParameter("refine_rmsd_scope", "atoms to be considered for rmsd score in second clustering run (C_ALPHA, BACKBONE, ALL_ATOMS) ", STRING, false, "C_ALPHA");
parpars.setParameterRestrictions("refine_rmsd_scope", rmsd_levels);
// the manual
String man = "This tool computes clusters of docking poses given as conformation set or a list of rigid transformations.\n\nParameters are either the input ConformationSet (-i_dcd) and one corresponding pdb file (-i_pdb), or a transformation file (-i_transformations), and a naming schema for the results (-o). Optional parameters are the algorithm (-alg), the minimal rmsd between the final clusters (-rmsd_cutoff), the rmsd type (-rmsd_type), and the scope/level of detail of the rmsd computation (-rmsd_scope). The optional parameter -o_dcd sets the output directory for the reduced cluster set.\n\nOutput of this tool is a dcd file containing the reduced cluster ConformationSet.";
parpars.setToolManual(man);
// here we set the types of I/O files
parpars.setSupportedFormats("i_dcd","dcd");
parpars.setSupportedFormats("i_pdb","pdb");
parpars.setSupportedFormats("i_transformations","txt");
parpars.setSupportedFormats("o","dcd");
parpars.setSupportedFormats("o_dcd","dcd");
parpars.parse(argc, argv);
//////////////////////////////////////////////////
// first, a little sanity check
if (parpars.get("o_type") == "dcd")
{
if (!parpars.has("o_dir") || !parpars.has("o_id"))
{
Log << "Output type \"dcd\" requires setting the options \"o_dir\" \"o_id\"! Abort!" << endl;
return 1;
}
}
// read the input
PDBFile pdb;
pdb.open(parpars.get("i_pdb"));
System sys;
pdb.read(sys);
ConformationSet cs;
cs.setup(sys);
if (parpars.has("i_dcd"))
{
cs.readDCDFile(parpars.get("i_dcd"));
}
cs.resetScoring();
PoseClustering pc;
if (parpars.has("i_transformations"))
{
if (parpars.has("rmsd_type"))
{
if (parpars.get("rmsd_type") != "RIGID_RMSD")
{
Log << "Transformation input file can only be used with rmsd_type 'RIGID_RMSD'. Abort!" << endl;
return 0;
}
}
else
{
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
}
pc.setBaseSystemAndTransformations(sys, parpars.get("i_transformations"));
}
if (parpars.has("rmsd_cutoff"))
{
float rmsd = parpars.get("rmsd_cutoff").toInt();
pc.options.setReal(PoseClustering::Option::DISTANCE_THRESHOLD, rmsd);
}
if (parpars.has("rmsd_scope"))
{
String scope = parpars.get("rmsd_scope");
if (scope == "C_ALPHA")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA);
else if (scope == "BACKBONE")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE);
else if (scope == "ALL_ATOMS")
pc.options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS);
else
Log.info() << "Unknown value " << scope << " for option rmsd_scope." << endl;
}
if (parpars.has("alg"))
{
String alg = parpars.get("alg");
if (alg == "CLINK_DEFAYS")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::CLINK_DEFAYS);
else if (alg == "SLINK_SIBSON")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::SLINK_SIBSON);
else if (alg == "TRIVIAL_COMPLETE_LINKAGE")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::TRIVIAL_COMPLETE_LINKAGE);
else if (alg == " NEAREST_NEIGHBOR_CHAIN_WARD")
pc.options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::NEAREST_NEIGHBOR_CHAIN_WARD);
else
Log.info() << "Unknown value " << alg << " for option alg." << endl;
}
if (parpars.has("rmsd_type"))
{
String type = parpars.get("rmsd_type");
if (type == "SNAPSHOT_RMSD")
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::SNAPSHOT_RMSD);
else if (type == "RIGID_RMSD")
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
else if (type == "CENTER_OF_MASS_DISTANCE")
{
pc.options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::CENTER_OF_MASS_DISTANCE);
Log << "Parameter rmsd_scope will be ignored!" << endl;
}
else
Log.info() << "Unknown value " << type << " for option rmsd_type." << endl;
}
if (parpars.has("-i_dcd"))
{
pc.setConformationSet(&cs);
}
pc.compute();
// do we need a second clustering run?
if (parpars.has("use_refinement"))
{
// get the options
Options refine_options = pc.options;
if (parpars.has("refine_rmsd_scope"))
{
String scope = parpars.get("refine_rmsd_scope");
if (scope == "C_ALPHA")
refine_options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::C_ALPHA);
else if (scope == "BACKBONE")
refine_options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::BACKBONE);
else if (scope == "ALL_ATOMS")
refine_options.set(PoseClustering::Option::RMSD_LEVEL_OF_DETAIL, PoseClustering::ALL_ATOMS);
else
Log.info() << "Unknown value " << scope << " for option refine_rmsd_scope." << endl;
}
if (parpars.has("refine_alg"))
{
String alg = parpars.get("refine_alg");
if (alg == "CLINK_DEFAYS")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::CLINK_DEFAYS);
else if (alg == "SLINK_SIBSON")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::SLINK_SIBSON);
else if (alg == "TRIVIAL_COMPLETE_LINKAGE")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::TRIVIAL_COMPLETE_LINKAGE);
else if (alg == " NEAREST_NEIGHBOR_CHAIN_WARD")
refine_options.set(PoseClustering::Option::CLUSTER_METHOD, PoseClustering::NEAREST_NEIGHBOR_CHAIN_WARD);
else
Log.info() << "Unknown value " << alg << " for option refine_alg." << endl;
}
if (parpars.has("refine_rmsd_type"))
{
String type = parpars.get("refine_rmsd_type");
if (type == "SNAPSHOT_RMSD")
refine_options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::SNAPSHOT_RMSD);
else if (type == "RIGID_RMSD")
refine_options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::RIGID_RMSD);
else if (type == "CENTER_OF_MASS_DISTANCE")
{
refine_options.set(PoseClustering::Option::RMSD_TYPE, PoseClustering::CENTER_OF_MASS_DISTANCE);
Log << "Parameter rmsd_scope will be ignored!" << endl;
}
else
Log.info() << "Unknown value " << type << " for option refine_rmsd_type." << endl;
}
pc.refineClustering(refine_options);
}
Size num_clusters = pc.getNumberOfClusters();
Log << "Computed " << num_clusters << " clusters, start writing..." << endl;
if (parpars.get("o_type") == "dcd")
{
for (Size i = 0; i < num_clusters; i++)
{
Log << " Cluster " << i << " has " << pc.getClusterSize(i) << " members." << endl;
boost::shared_ptr<ConformationSet> new_cs = pc.getClusterConformationSet(i);
String outfile_name = (i == 0) ? String(parpars.get("o"))
: String(parpars.get("o_dir")) + "/primary_"
+ String(parpars.get("o_id")) + "_cluster" + String(i)
+ "_visible.dcd";
//Log << " Writing solution " << String(i) << " as " << outfile_name << endl;
new_cs->writeDCDFile(outfile_name);
}
}
else
{
String outfile_name = String(parpars.get("o"));
File cluster_outfile(outfile_name, std::ios::out);
if (parpars.get("o_type") == "index_list")
{
pc.printClusters(cluster_outfile);
}
else
{
pc.printClusterRMSDs(cluster_outfile);
}
}
// print
pc.printClusters();
pc.printClusterRMSDs();
if (parpars.has("o_dcd"))
{
String outfile_name = String(parpars.get("o_dcd"));
boost::shared_ptr<ConformationSet> cs = pc.getReducedConformationSet();
cs->writeDCDFile(outfile_name);
}
Log << "done." << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#ifdef _WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#endif
#include "reductions.h"
#include "simple_label.h"
#include "gd.h"
#include "rand48.h"
using namespace std;
using namespace LEARNER;
namespace MF {
struct mf {
vector<string> pairs;
uint32_t rank;
uint32_t increment;
// array to cache w*x, (l^k * x_l) and (r^k * x_r)
// [ w*(1,x_l,x_r) , l^1*x_l, r^1*x_r, l^2*x_l, r^2*x_2, ... ]
v_array<float> sub_predictions;
// array for temp storage of indices during prediction
v_array<unsigned char> predict_indices;
// array for temp storage of indices
v_array<unsigned char> indices;
// array for temp storage of features
v_array<feature> temp_features;
vw* all;
};
template <bool cache_sub_predictions>
void predict(mf& data, learner& base, example& ec) {
vw* all = data.all;
float prediction = 0;
if (cache_sub_predictions)
data.sub_predictions.resize(2*data.rank+1, true);
// predict from linear terms
base.predict(ec);
// store linear prediction
if (cache_sub_predictions)
data.sub_predictions[0] = ec.partial_prediction;
prediction += ec.partial_prediction;
// store namespace indices
copy_array(data.predict_indices, ec.indices);
// erase indices
ec.indices.erase();
ec.indices.push_back(0);
// add interaction terms to prediction
for (vector<string>::iterator i = data.pairs.begin(); i != data.pairs.end(); i++) {
int left_ns = (int) (*i)[0];
int right_ns = (int) (*i)[1];
if (ec.atomics[left_ns].size() > 0 && ec.atomics[right_ns].size() > 0) {
for (size_t k = 1; k <= data.rank; k++) {
ec.indices[0] = left_ns;
// compute l^k * x_l using base learner
base.predict(ec, k);
float x_dot_l = ec.partial_prediction;
if (cache_sub_predictions)
data.sub_predictions[2*k-1] = x_dot_l;
// set example to right namespace only
ec.indices[0] = right_ns;
// compute r^k * x_r using base learner
base.predict(ec, k + data.rank);
float x_dot_r = ec.partial_prediction;
if (cache_sub_predictions)
data.sub_predictions[2*k] = x_dot_r;
// accumulate prediction
prediction += (x_dot_l * x_dot_r);
}
}
}
// restore namespace indices and label
copy_array(ec.indices, data.predict_indices);
// finalize prediction
ec.partial_prediction = prediction;
ec.l.simple.prediction = GD::finalize_prediction(data.all->sd, ec.partial_prediction);
}
void learn(mf& data, learner& base, example& ec) {
vw* all = data.all;
// predict with current weights
predict<true>(data, base, ec);
float predicted = ec.l.simple.prediction;
// update linear weights
base.update(ec);
ec.l.simple.prediction = ec.updated_prediction;
// store namespace indices
copy_array(data.indices, ec.indices);
// erase indices
ec.indices.erase();
ec.indices.push_back(0);
// update interaction terms
// looping over all pairs of non-empty namespaces
for (vector<string>::iterator i = data.pairs.begin(); i != data.pairs.end(); i++) {
int left_ns = (int) (*i)[0];
int right_ns = (int) (*i)[1];
if (ec.atomics[left_ns].size() > 0 && ec.atomics[right_ns].size() > 0) {
// set example to left namespace only
ec.indices[0] = left_ns;
// store feature values in left namespace
copy_array(data.temp_features, ec.atomics[left_ns]);
for (size_t k = 1; k <= data.rank; k++) {
// multiply features in left namespace by r^k * x_r
for (feature* f = ec.atomics[left_ns].begin; f != ec.atomics[left_ns].end; f++)
f->x *= data.sub_predictions[2*k];
// update l^k using base learner
base.update(ec, k);
// restore left namespace features (undoing multiply)
copy_array(ec.atomics[left_ns], data.temp_features);
// compute new l_k * x_l scaling factors
// base.predict(ec, k);
// data.sub_predictions[2*k-1] = ec.partial_prediction;
// ec.l.simple.prediction = ec.updated_prediction;
}
// set example to right namespace only
ec.indices[0] = right_ns;
// store feature values for right namespace
copy_array(data.temp_features, ec.atomics[right_ns]);
for (size_t k = 1; k <= data.rank; k++) {
// multiply features in right namespace by l^k * x_l
for (feature* f = ec.atomics[right_ns].begin; f != ec.atomics[right_ns].end; f++)
f->x *= data.sub_predictions[2*k-1];
// update r^k using base learner
base.update(ec, k + data.rank);
ec.l.simple.prediction = ec.updated_prediction;
// restore right namespace features
copy_array(ec.atomics[right_ns], data.temp_features);
}
}
}
// restore namespace indices
copy_array(ec.indices, data.indices);
// restore original prediction
ec.l.simple.prediction = predicted;
}
void finish(mf& o) {
// restore global pairs
o.all->pairs = o.pairs;
// clean up local v_arrays
o.indices.delete_v();
o.sub_predictions.delete_v();
}
learner* setup(vw& all, po::variables_map& vm) {
mf* data = new mf;
// copy global data locally
data->all = &all;
data->rank = (uint32_t)vm["new_mf"].as<size_t>();
// store global pairs in local data structure and clear global pairs
// for eventual calls to base learner
data->pairs = all.pairs;
all.pairs.clear();
all.random_positive_weights = true;
learner* l = new learner(data, all.l, 2*data->rank+1);
l->set_learn<mf, learn>();
l->set_predict<mf, predict<false> >();
l->set_finish<mf,finish>();
return l;
}
}
<commit_msg>no warning: unused variable 'all'<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved. Released under a BSD (revised)
license as described in the file LICENSE.
*/
#ifdef _WIN32
#include <winsock2.h>
#else
#include <netdb.h>
#endif
#include "reductions.h"
#include "simple_label.h"
#include "gd.h"
#include "rand48.h"
using namespace std;
using namespace LEARNER;
namespace MF {
struct mf {
vector<string> pairs;
uint32_t rank;
uint32_t increment;
// array to cache w*x, (l^k * x_l) and (r^k * x_r)
// [ w*(1,x_l,x_r) , l^1*x_l, r^1*x_r, l^2*x_l, r^2*x_2, ... ]
v_array<float> sub_predictions;
// array for temp storage of indices during prediction
v_array<unsigned char> predict_indices;
// array for temp storage of indices
v_array<unsigned char> indices;
// array for temp storage of features
v_array<feature> temp_features;
vw* all;
};
template <bool cache_sub_predictions>
void predict(mf& data, learner& base, example& ec) {
float prediction = 0;
if (cache_sub_predictions)
data.sub_predictions.resize(2*data.rank+1, true);
// predict from linear terms
base.predict(ec);
// store linear prediction
if (cache_sub_predictions)
data.sub_predictions[0] = ec.partial_prediction;
prediction += ec.partial_prediction;
// store namespace indices
copy_array(data.predict_indices, ec.indices);
// erase indices
ec.indices.erase();
ec.indices.push_back(0);
// add interaction terms to prediction
for (vector<string>::iterator i = data.pairs.begin(); i != data.pairs.end(); i++) {
int left_ns = (int) (*i)[0];
int right_ns = (int) (*i)[1];
if (ec.atomics[left_ns].size() > 0 && ec.atomics[right_ns].size() > 0) {
for (size_t k = 1; k <= data.rank; k++) {
ec.indices[0] = left_ns;
// compute l^k * x_l using base learner
base.predict(ec, k);
float x_dot_l = ec.partial_prediction;
if (cache_sub_predictions)
data.sub_predictions[2*k-1] = x_dot_l;
// set example to right namespace only
ec.indices[0] = right_ns;
// compute r^k * x_r using base learner
base.predict(ec, k + data.rank);
float x_dot_r = ec.partial_prediction;
if (cache_sub_predictions)
data.sub_predictions[2*k] = x_dot_r;
// accumulate prediction
prediction += (x_dot_l * x_dot_r);
}
}
}
// restore namespace indices and label
copy_array(ec.indices, data.predict_indices);
// finalize prediction
ec.partial_prediction = prediction;
ec.l.simple.prediction = GD::finalize_prediction(data.all->sd, ec.partial_prediction);
}
void learn(mf& data, learner& base, example& ec) {
// predict with current weights
predict<true>(data, base, ec);
float predicted = ec.l.simple.prediction;
// update linear weights
base.update(ec);
ec.l.simple.prediction = ec.updated_prediction;
// store namespace indices
copy_array(data.indices, ec.indices);
// erase indices
ec.indices.erase();
ec.indices.push_back(0);
// update interaction terms
// looping over all pairs of non-empty namespaces
for (vector<string>::iterator i = data.pairs.begin(); i != data.pairs.end(); i++) {
int left_ns = (int) (*i)[0];
int right_ns = (int) (*i)[1];
if (ec.atomics[left_ns].size() > 0 && ec.atomics[right_ns].size() > 0) {
// set example to left namespace only
ec.indices[0] = left_ns;
// store feature values in left namespace
copy_array(data.temp_features, ec.atomics[left_ns]);
for (size_t k = 1; k <= data.rank; k++) {
// multiply features in left namespace by r^k * x_r
for (feature* f = ec.atomics[left_ns].begin; f != ec.atomics[left_ns].end; f++)
f->x *= data.sub_predictions[2*k];
// update l^k using base learner
base.update(ec, k);
// restore left namespace features (undoing multiply)
copy_array(ec.atomics[left_ns], data.temp_features);
// compute new l_k * x_l scaling factors
// base.predict(ec, k);
// data.sub_predictions[2*k-1] = ec.partial_prediction;
// ec.l.simple.prediction = ec.updated_prediction;
}
// set example to right namespace only
ec.indices[0] = right_ns;
// store feature values for right namespace
copy_array(data.temp_features, ec.atomics[right_ns]);
for (size_t k = 1; k <= data.rank; k++) {
// multiply features in right namespace by l^k * x_l
for (feature* f = ec.atomics[right_ns].begin; f != ec.atomics[right_ns].end; f++)
f->x *= data.sub_predictions[2*k-1];
// update r^k using base learner
base.update(ec, k + data.rank);
ec.l.simple.prediction = ec.updated_prediction;
// restore right namespace features
copy_array(ec.atomics[right_ns], data.temp_features);
}
}
}
// restore namespace indices
copy_array(ec.indices, data.indices);
// restore original prediction
ec.l.simple.prediction = predicted;
}
void finish(mf& o) {
// restore global pairs
o.all->pairs = o.pairs;
// clean up local v_arrays
o.indices.delete_v();
o.sub_predictions.delete_v();
}
learner* setup(vw& all, po::variables_map& vm) {
mf* data = new mf;
// copy global data locally
data->all = &all;
data->rank = (uint32_t)vm["new_mf"].as<size_t>();
// store global pairs in local data structure and clear global pairs
// for eventual calls to base learner
data->pairs = all.pairs;
all.pairs.clear();
all.random_positive_weights = true;
learner* l = new learner(data, all.l, 2*data->rank+1);
l->set_learn<mf, learn>();
l->set_predict<mf, predict<false> >();
l->set_finish<mf,finish>();
return l;
}
}
<|endoftext|> |
<commit_before>#include "photoeffects.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/core/internal.hpp>
using namespace cv;
class VignetteInvoker
{
private:
const Mat& imgSrc;
Mat& imgDst;
float centerRow, centerCol, aSquare, bSquare, radiusMax;
VignetteInvoker& operator=(const VignetteInvoker&);
public:
VignetteInvoker(const Mat& src, Mat& dst, Size rect):
imgSrc(src),
imgDst(dst)
{
centerRow = imgSrc.rows / 2.0f;
centerCol = imgSrc.cols / 2.0f;
aSquare = rect.height * rect.height / 4.0f;
bSquare = rect.width * rect.width / 4.0f;
radiusMax = centerRow * centerRow / aSquare + centerCol * centerCol / bSquare - 1.0f;
}
void operator()(const BlockedRange& rows) const
{
Mat srcStripe = imgSrc.rowRange(rows.begin(), rows.end());
Mat dstStripe = imgDst.rowRange(rows.begin(), rows.end());
srcStripe.copyTo(dstStripe);
int stripeWidth = srcStripe.rows;
for (int i = rows.begin(); i < rows.end(); i++)
{
Vec3b* srcRow = (Vec3b*)srcStripe.row(i - rows.begin()).data;
Vec3b* dstRow = (Vec3b*)dstStripe.row(i - rows.begin()).data;
for (int j = 0; j < imgSrc.cols; j++)
{
float dist = (i - centerRow) * (i - centerRow) / aSquare +
(j - centerCol) * (j - centerCol) / bSquare;
float coefficient = 1.0f;
if (dist > 1.0f)
{
coefficient = 1.0f - (dist - 1.0f) / radiusMax;
}
dstRow[j] *= coefficient;
}
}
}
};
int vignette(InputArray src, OutputArray dst, Size rect)
{
CV_Assert(src.type() == CV_8UC3 && rect.height != 0 && rect.width != 0);
Mat imgSrc = src.getMat();
CV_Assert(imgSrc.data);
dst.create(imgSrc.size(), CV_8UC3);
Mat imgDst = dst.getMat();
parallel_for(BlockedRange(0, imgSrc.rows), VignetteInvoker(imgSrc, imgDst, rect));
return 0;
}<commit_msg>Vec3b replaced on uchar operations<commit_after>#include "photoeffects.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/core/internal.hpp>
using namespace cv;
class VignetteInvoker
{
private:
const Mat& imgSrc;
Mat& imgDst;
float centerRow, centerCol, aSquare, bSquare, radiusMax;
VignetteInvoker& operator=(const VignetteInvoker&);
public:
VignetteInvoker(const Mat& src, Mat& dst, Size rect):
imgSrc(src),
imgDst(dst)
{
centerRow = imgSrc.rows / 2.0f;
centerCol = imgSrc.cols / 2.0f;
aSquare = rect.height * rect.height / 4.0f;
bSquare = rect.width * rect.width / 4.0f;
radiusMax = centerRow * centerRow / aSquare + centerCol * centerCol / bSquare - 1.0f;
}
void operator()(const BlockedRange& rows) const
{
Mat srcStripe = imgSrc.rowRange(rows.begin(), rows.end());
Mat dstStripe = imgDst.rowRange(rows.begin(), rows.end());
srcStripe.copyTo(dstStripe);
int stripeWidth = srcStripe.rows;
for (int i = rows.begin(); i < rows.end(); i++)
{
uchar* srcRow = (uchar*)srcStripe.row(i - rows.begin()).data;
uchar* dstRow = (uchar*)dstStripe.row(i - rows.begin()).data;
for (int j = 0; j < imgSrc.cols; j++)
{
float dist = (i - centerRow) * (i - centerRow) / aSquare +
(j - centerCol) * (j - centerCol) / bSquare;
float coefficient = 1.0f;
if (dist > 1.0f)
{
coefficient = 1.0f - (dist - 1.0f) / radiusMax;
}
dstRow[3 * j] *= coefficient;
dstRow[3 * j + 1] *= coefficient;
dstRow[3 * j + 2] *= coefficient;
}
}
}
};
int vignette(InputArray src, OutputArray dst, Size rect)
{
CV_Assert(src.type() == CV_8UC3 && rect.height != 0 && rect.width != 0);
Mat imgSrc = src.getMat();
CV_Assert(imgSrc.data);
dst.create(imgSrc.size(), CV_8UC3);
Mat imgDst = dst.getMat();
parallel_for(BlockedRange(0, imgSrc.rows), VignetteInvoker(imgSrc, imgDst, rect));
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#ifdef NEBLIO_REST
#define CLIENT_VERSION_SUFFIX "-REST-Enabled"
#else
#define CLIENT_VERSION_SUFFIX ""
#endif
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 0
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID ""
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<commit_msg>Add RC1 suffix tag and begin updating infrastructure nodes to Tachyon<commit_after>// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#ifdef NEBLIO_REST
#define CLIENT_VERSION_SUFFIX "-REST-Enabled"
#else
#define CLIENT_VERSION_SUFFIX "-RC1"
#endif
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 0
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID ""
# define GIT_COMMIT_DATE "$Format:%cD"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
<|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*********************************************************************************/
#include <modules/base/processors/tfselector.h>
#include <inviwo/core/util/utilities.h>
#include <inviwo/core/network/networklock.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo TFSelector::processorInfo_{
"org.inviwo.TFSelector", // Class identifier
"Transfer Function Selector", // Display name
"Transfer Function", // Category
CodeState::Stable, // Code state
"Transfer Function, TF, Presets, UI", // Tags
};
const ProcessorInfo TFSelector::getProcessorInfo() const { return processorInfo_; }
TFSelector::TFSelector()
: Processor()
, inport_("inport")
, outport_("outport")
, tfOut_("tfOut", "TF Out", TransferFunction{})
, selectedTF_("selectedTF", "Selected")
, cycle_("cycle", "Cycle TFs")
, tfPresets_("presets", "Presets",
std::make_unique<TransferFunctionProperty>("tfPreset1", "TF 1"))
, interactions_("interactions", "Interactions")
, nextTF_("nextTF", "Next TF",
[this](Event* e) {
size_t next = selectedTF_.getSelectedIndex() + 1;
if (cycle_.get()) {
next = next % selectedTF_.size();
}
selectedTF_.setSelectedIndex(next);
e->markAsUsed();
},
IvwKey::Period, KeyState::Press)
, previousTF_("previousTF", "Previous TF",
[this](Event* e) {
if (auto index = selectedTF_.getSelectedIndex()) {
selectedTF_.setSelectedIndex(index - 1);
} else if (cycle_.get()) {
selectedTF_.setSelectedIndex(selectedTF_.size() - 1);
}
e->markAsUsed();
},
IvwKey::Comma, KeyState::Press) {
addPort(inport_);
addPort(outport_);
tfOut_.setReadOnly(true);
tfOut_.setCurrentStateAsDefault();
addProperty(tfOut_);
addProperty(selectedTF_);
addProperty(cycle_);
addProperty(tfPresets_);
interactions_.addProperty(nextTF_);
interactions_.addProperty(previousTF_);
addProperty(interactions_);
interactions_.setCollapsed(true);
selectedTF_.onChange([this]() {
for (auto p : tfPresets_.getProperties()) {
p->onChange([]() {});
}
if (tfPresets_.size() > 0 && selectedTF_.size() > 0) {
auto p = static_cast<TransferFunctionProperty*>(
tfPresets_.getPropertyByIdentifier(selectedTF_.getSelectedIdentifier()));
tfOut_.set(p->get());
// ensure that if the TF is modified, the output is in sync
p->onChange([this, p]() { tfOut_.set(p->get()); });
}
});
tfPresets_.PropertyOwnerObservable::addObserver(this);
}
void TFSelector::process() { outport_.setData(inport_.getData()); }
void TFSelector::deserialize(Deserializer& d) {
Processor::deserialize(d);
// ensure that option property is up to date
updateOptions();
// make processor aware of changes in display names of TFs
for (auto p : tfPresets_.getProperties()) {
p->Property::addObserver(this);
}
}
void TFSelector::onSetDisplayName(Property*, const std::string&) { updateOptions(); }
void TFSelector::onDidAddProperty(Property* property, size_t) {
updateOptions();
property->Property::addObserver(this);
}
void TFSelector::onDidRemoveProperty(Property*, size_t) { updateOptions(); }
void TFSelector::updateOptions() {
// update option property
NetworkLock lock(&selectedTF_);
if (tfPresets_.size()) {
std::vector<OptionPropertyStringOption> tfOptions;
for (auto p : tfPresets_.getProperties()) {
tfOptions.emplace_back(p->getIdentifier(), p->getDisplayName());
}
selectedTF_.replaceOptions(tfOptions);
} else {
selectedTF_.clearOptions();
tfOut_.resetToDefaultState();
}
}
} // namespace inviwo
<commit_msg>Base: Clang formatting<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018-2019 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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.
*
*********************************************************************************/
#include <modules/base/processors/tfselector.h>
#include <inviwo/core/util/utilities.h>
#include <inviwo/core/network/networklock.h>
namespace inviwo {
// The Class Identifier has to be globally unique. Use a reverse DNS naming scheme
const ProcessorInfo TFSelector::processorInfo_{
"org.inviwo.TFSelector", // Class identifier
"Transfer Function Selector", // Display name
"Transfer Function", // Category
CodeState::Stable, // Code state
"Transfer Function, TF, Presets, UI", // Tags
};
const ProcessorInfo TFSelector::getProcessorInfo() const { return processorInfo_; }
TFSelector::TFSelector()
: Processor()
, inport_("inport")
, outport_("outport")
, tfOut_("tfOut", "TF Out", TransferFunction{})
, selectedTF_("selectedTF", "Selected")
, cycle_("cycle", "Cycle TFs")
, tfPresets_("presets", "Presets",
std::make_unique<TransferFunctionProperty>("tfPreset1", "TF 1"))
, interactions_("interactions", "Interactions")
, nextTF_(
"nextTF", "Next TF",
[this](Event* e) {
size_t next = selectedTF_.getSelectedIndex() + 1;
if (cycle_.get()) {
next = next % selectedTF_.size();
}
selectedTF_.setSelectedIndex(next);
e->markAsUsed();
},
IvwKey::Period, KeyState::Press)
, previousTF_(
"previousTF", "Previous TF",
[this](Event* e) {
if (auto index = selectedTF_.getSelectedIndex()) {
selectedTF_.setSelectedIndex(index - 1);
} else if (cycle_.get()) {
selectedTF_.setSelectedIndex(selectedTF_.size() - 1);
}
e->markAsUsed();
},
IvwKey::Comma, KeyState::Press) {
addPort(inport_);
addPort(outport_);
tfOut_.setReadOnly(true);
tfOut_.setCurrentStateAsDefault();
addProperty(tfOut_);
addProperty(selectedTF_);
addProperty(cycle_);
addProperty(tfPresets_);
interactions_.addProperty(nextTF_);
interactions_.addProperty(previousTF_);
addProperty(interactions_);
interactions_.setCollapsed(true);
selectedTF_.onChange([this]() {
for (auto p : tfPresets_.getProperties()) {
p->onChange([]() {});
}
if (tfPresets_.size() > 0 && selectedTF_.size() > 0) {
auto p = static_cast<TransferFunctionProperty*>(
tfPresets_.getPropertyByIdentifier(selectedTF_.getSelectedIdentifier()));
tfOut_.set(p->get());
// ensure that if the TF is modified, the output is in sync
p->onChange([this, p]() { tfOut_.set(p->get()); });
}
});
tfPresets_.PropertyOwnerObservable::addObserver(this);
}
void TFSelector::process() { outport_.setData(inport_.getData()); }
void TFSelector::deserialize(Deserializer& d) {
Processor::deserialize(d);
// ensure that option property is up to date
updateOptions();
// make processor aware of changes in display names of TFs
for (auto p : tfPresets_.getProperties()) {
p->Property::addObserver(this);
}
}
void TFSelector::onSetDisplayName(Property*, const std::string&) { updateOptions(); }
void TFSelector::onDidAddProperty(Property* property, size_t) {
updateOptions();
property->Property::addObserver(this);
}
void TFSelector::onDidRemoveProperty(Property*, size_t) { updateOptions(); }
void TFSelector::updateOptions() {
// update option property
NetworkLock lock(&selectedTF_);
if (tfPresets_.size()) {
std::vector<OptionPropertyStringOption> tfOptions;
for (auto p : tfPresets_.getProperties()) {
tfOptions.emplace_back(p->getIdentifier(), p->getDisplayName());
}
selectedTF_.replaceOptions(tfOptions);
} else {
selectedTF_.clearOptions();
tfOut_.resetToDefaultState();
}
}
} // namespace inviwo
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@gmail.com>
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "application_p.h"
#include "config.h"
#include "common.h"
#include "context_p.h"
#include "request.h"
#include "request_p.h"
#include "controller.h"
#include "controller_p.h"
#include "response.h"
#include "response_p.h"
#include "dispatchtype.h"
#include "view.h"
#include "stats.h"
#include "utils.h"
#include "Actions/actionrest.h"
#include "Actions/roleacl.h"
#include "Actions/renderview.h"
#include <QDir>
#include <QStringList>
#include <QStringBuilder>
Q_LOGGING_CATEGORY(CUTELYST_DISPATCHER, "cutelyst.dispatcher")
Q_LOGGING_CATEGORY(CUTELYST_DISPATCHER_CHAINED, "cutelyst.dispatcher.chained")
Q_LOGGING_CATEGORY(CUTELYST_CONTROLLER, "cutelyst.controller")
Q_LOGGING_CATEGORY(CUTELYST_CORE, "cutelyst.core")
Q_LOGGING_CATEGORY(CUTELYST_ENGINE, "cutelyst.engine")
Q_LOGGING_CATEGORY(CUTELYST_UPLOAD, "cutelyst.upload")
Q_LOGGING_CATEGORY(CUTELYST_MULTIPART, "cutelyst.multipart")
Q_LOGGING_CATEGORY(CUTELYST_VIEW, "cutelyst.view")
Q_LOGGING_CATEGORY(CUTELYST_REQUEST, "cutelyst.request")
Q_LOGGING_CATEGORY(CUTELYST_RESPONSE, "cutelyst.response")
Q_LOGGING_CATEGORY(CUTELYST_STATS, "cutelyst.stats")
Q_LOGGING_CATEGORY(CUTELYST_COMPONENT, "cutelyst.component")
using namespace Cutelyst;
Application::Application(QObject *parent) :
QObject(parent),
d_ptr(new ApplicationPrivate)
{
Q_D(Application);
d->headers.setHeader(QStringLiteral("X-Cutelyst"), QStringLiteral(VERSION));
qRegisterMetaType<ParamsMultiMap>();
qRegisterMetaType<ActionREST *>();
qRegisterMetaType<RoleACL *>();
qRegisterMetaType<RenderView *>();
d->dispatcher = new Dispatcher(this);
}
Application::~Application()
{
delete d_ptr;
}
bool Application::init()
{
qCDebug(CUTELYST_CORE) << "Default Application::init called on pid:" << QCoreApplication::applicationPid();
return true;
}
bool Application::postFork()
{
qCDebug(CUTELYST_CORE) << "Default Application::postFork called on pid:" << QCoreApplication::applicationPid();
return true;
}
Headers &Application::defaultHeaders()
{
Q_D(Application);
return d->headers;
}
bool Application::registerPlugin(Cutelyst::Plugin *plugin)
{
Q_D(Application);
d->plugins.append(plugin);
return true;
}
bool Application::registerController(Controller *controller)
{
Q_D(Application);
if (d->init) {
qCWarning(CUTELYST_CORE) << "Tryied to register Controller after the Application was initted, ignoring"
<< controller->metaObject()->className();
return false;
}
d->controllers.append(controller);
return true;
}
QList<Controller *> Application::controllers() const
{
Q_D(const Application);
return d->controllers;
}
bool Application::registerView(View *view, const QString &name)
{
Q_D(Application);
if (d->views.contains(name)) {
qCWarning(CUTELYST_CORE) << "Not registering View. There is already a view with this name:" << name;
return false;
}
d->views.insert(name, view);
return true;
}
View *Application::view(const QString &name) const
{
Q_D(const Application);
return d->views.value(name);
}
void Application::registerDispatcher(DispatchType *dispatcher)
{
Q_D(const Application);
dispatcher->setParent(this);
d->dispatcher->registerDispatchType(dispatcher);
}
QVariant Application::config(const QString &key, const QVariant &defaultValue) const
{
Q_D(const Application);
QVariantHash::const_iterator it = d->config.constFind(key);
if (it != d->config.constEnd()) {
return it.value();
}
return defaultValue;
}
Dispatcher *Application::dispatcher() const
{
Q_D(const Application);
return d->dispatcher;
}
QList<DispatchType *> Application::dispatchers() const
{
Q_D(const Application);
return d->dispatcher->dispatchers();
}
QVariantHash Application::config() const
{
Q_D(const Application);
return d->config;
}
QString Cutelyst::Application::pathTo(const QStringList &path) const
{
QDir home = config(QStringLiteral("home")).toString();
return home.absoluteFilePath(path.join(QDir::separator()));
}
bool Cutelyst::Application::inited() const
{
Q_D(const Application);
return d->init;
}
Cutelyst::Engine *Cutelyst::Application::engine() const
{
Q_D(const Application);
return d->engine;
}
void Application::setConfig(const QString &key, const QVariant &value)
{
Q_D(Application);
d->config.insert(key, value);
}
bool Application::setup(Engine *engine)
{
Q_D(Application);
if (d->init) {
return true;
}
d->useStats = CUTELYST_STATS().isDebugEnabled();
d->engine = engine;
d->config = engine->config(QStringLiteral("Cutelyst"));
d->setupHome();
// Call the virtual application init
// to setup Controllers plugins stuff
if (init()) {
QString appName = QCoreApplication::applicationName();
QList<QStringList> tablePlugins;
Q_FOREACH (Plugin *plugin, d->plugins) {
QString className = QString::fromLatin1(plugin->metaObject()->className());
tablePlugins.append({ className });
// Configure plugins
plugin->setup(this);
}
qCDebug(CUTELYST_CORE) << Utils::buildTable(tablePlugins, QStringList(),
QStringLiteral("Loaded plugins:")).data();
QList<QStringList> tableDataHandlers;
tableDataHandlers.append({ QLatin1String("application/x-www-form-urlencoded") });
tableDataHandlers.append({ QLatin1String("application/json") });
tableDataHandlers.append({ QLatin1String("multipart/form-data") });
qCDebug(CUTELYST_CORE) << Utils::buildTable(tableDataHandlers, QStringList(),
QStringLiteral("Loaded Request Data Handlers:")).data();
qCDebug(CUTELYST_CORE) << "Loaded dispatcher" << QString::fromLatin1(d->dispatcher->metaObject()->className());
qCDebug(CUTELYST_CORE) << "Using engine" << QString::fromLatin1(d->engine->metaObject()->className());
QString home = d->config.value("home").toString();
if (home.isEmpty()) {
qCDebug(CUTELYST_CORE) << "Couldn't find home";
} else {
QFileInfo homeInfo = home;
if (homeInfo.isDir()) {
qCDebug(CUTELYST_CORE) << "Found home" << home;
} else {
qCDebug(CUTELYST_CORE) << "Home" << home << "doesn't exist";
}
}
QList<QStringList> table;
Q_FOREACH (Controller *controller, d->controllers) {
QString className = QString::fromLatin1(controller->metaObject()->className());
if (!className.startsWith(QLatin1String("Cutelyst"))) {
className = appName % QLatin1String("::Controller::") % className;
}
table.append({ className, QStringLiteral("instance")});
}
Q_FOREACH (View *view, d->views) {
QString className = QString::fromLatin1(view->metaObject()->className());
if (!className.startsWith(QLatin1String("Cutelyst"))) {
className = appName % QLatin1String("::View::") % className;
}
table.append({ className, QStringLiteral("instance")});
}
qCDebug(CUTELYST_CORE) << Utils::buildTable(table, {
QStringLiteral("Class"), QStringLiteral("Type")
},
QStringLiteral("Loaded components:")).data();
Q_FOREACH (Controller *controller, d->controllers) {
controller->d_ptr->init(this, d->dispatcher);
}
d->dispatcher->setupActions(d->controllers);
d->init = true;
qCDebug(CUTELYST_CORE) << QString("%1 powered by Cutelyst %2")
.arg(QCoreApplication::applicationName())
.arg(VERSION).toLatin1().data();
return true;
}
return false;
}
void Application::handleRequest(Request *req)
{
Q_D(Application);
ContextPrivate *priv = new ContextPrivate;
priv->app = this;
priv->engine = d->engine;
priv->dispatcher = d->dispatcher;
priv->request = req;
priv->plugins = d->plugins;
priv->requestPtr = req->d_ptr->requestPtr;
Context *c = new Context(priv);
priv->response = new Response(c);
ResponsePrivate *resPriv = priv->response->d_ptr;
resPriv->engine = d->engine;
resPriv->headers = d->headers;
if (d->useStats) {
priv->stats = new Stats(this);
}
// Process request
bool skipMethod = false;
Q_EMIT beforePrepareAction(c, &skipMethod);
if (!skipMethod) {
if (CUTELYST_REQUEST().isEnabled(QtDebugMsg)) {
d->logRequest(req);
}
d->dispatcher->prepareAction(c);
Q_EMIT beforeDispatch(c);
d->dispatcher->dispatch(c);
Q_EMIT afterDispatch(c);
}
d->engine->finalize(c);
if (priv->stats) {
qCDebug(CUTELYST_STATS, "Response Code: %d; Content-Type: %s; Content-Length: %s",
c->response()->status(),
c->response()->headers().header(QStringLiteral("Content-Type"), QStringLiteral("unknown")).toLatin1().data(),
c->response()->headers().header(QStringLiteral("Content-Length"), QStringLiteral("unknown")).toLatin1().data());
RequestPrivate *reqPriv = req->d_ptr;
reqPriv->endOfRequest = d->engine->time();
double enlapsed = (reqPriv->endOfRequest - reqPriv->startOfRequest) / 1000000.0;
QString average;
if (enlapsed == 0.0) {
average = QStringLiteral("??");
} else {
average = QString::number(1.0 / enlapsed, 'f');
average.truncate(average.size() - 3);
}
qCDebug(CUTELYST_STATS) << QString("Request took: %1s (%2/s)\n%3")
.arg(QString::number(enlapsed, 'f'))
.arg(average)
.arg(priv->stats->report())
.toLatin1().data();
delete priv->stats;
}
delete c;
}
bool Application::enginePostFork()
{
Q_D(Application);
if (!postFork()) {
return false;
}
Q_FOREACH (Controller *controller, d->controllers) {
if (!controller->postFork(this)) {
return false;
}
}
return true;
}
void Cutelyst::ApplicationPrivate::setupHome()
{
// Hook the current directory in config if "home" is not set
if (!config.contains("home")) {
config.insert("home", QDir::currentPath());
}
if (!config.contains("root")) {
QDir home = config.value("home").toString();
config.insert("root", home.absoluteFilePath("root"));
}
}
void Cutelyst::ApplicationPrivate::logRequest(Request *req)
{
QString path = req->path();
if (path.isEmpty()) {
path = QStringLiteral("/");
}
qCDebug(CUTELYST_REQUEST) << req->method() << "request for" << path << "from" << req->address().toString();
ParamsMultiMap params = req->queryParameters();
if (!params.isEmpty()) {
logRequestParameters(params, QStringLiteral("Query Parameters are:"));
}
params = req->bodyParameters();
if (!params.isEmpty()) {
logRequestParameters(params, QStringLiteral("Body Parameters are:"));
}
QMap<QString, Cutelyst::Upload *> uploads = req->uploads();
if (!uploads.isEmpty()) {
logRequestUploads(uploads);
}
}
void Cutelyst::ApplicationPrivate::logRequestParameters(const ParamsMultiMap ¶ms, const QString &title)
{
QList<QStringList> table;
ParamsMultiMap::ConstIterator it = params.constBegin();
while (it != params.constEnd()) {
table.append({ it.key(), it.value() });
++it;
}
qCDebug(CUTELYST_REQUEST) << Utils::buildTable(table, {
QStringLiteral("Parameter"),
QStringLiteral("Value"),
},
title).data();
}
void Cutelyst::ApplicationPrivate::logRequestUploads(const QMap<QString, Cutelyst::Upload *> &uploads)
{
QList<QStringList> table;
QMap<QString, Cutelyst::Upload *>::ConstIterator it = uploads.constBegin();
while (it != uploads.constEnd()) {
Upload *upload = it.value();
table.append({ it.key(),
upload->filename(),
upload->contentType(),
QString::number(upload->size())
});
++it;
}
qCDebug(CUTELYST_REQUEST) << Utils::buildTable(table, {
QStringLiteral("Parameter"),
QStringLiteral("Filename"),
QStringLiteral("Type"),
QStringLiteral("Size"),
},
QStringLiteral("File Uploads are:")).data();
}
<commit_msg>Don't print empty tables and show Qt version powering the app<commit_after>/*
* Copyright (C) 2013-2015 Daniel Nicoletti <dantti12@gmail.com>
*
* 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; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "application_p.h"
#include "config.h"
#include "common.h"
#include "context_p.h"
#include "request.h"
#include "request_p.h"
#include "controller.h"
#include "controller_p.h"
#include "response.h"
#include "response_p.h"
#include "dispatchtype.h"
#include "view.h"
#include "stats.h"
#include "utils.h"
#include "Actions/actionrest.h"
#include "Actions/roleacl.h"
#include "Actions/renderview.h"
#include <QDir>
#include <QStringList>
#include <QStringBuilder>
Q_LOGGING_CATEGORY(CUTELYST_DISPATCHER, "cutelyst.dispatcher")
Q_LOGGING_CATEGORY(CUTELYST_DISPATCHER_CHAINED, "cutelyst.dispatcher.chained")
Q_LOGGING_CATEGORY(CUTELYST_CONTROLLER, "cutelyst.controller")
Q_LOGGING_CATEGORY(CUTELYST_CORE, "cutelyst.core")
Q_LOGGING_CATEGORY(CUTELYST_ENGINE, "cutelyst.engine")
Q_LOGGING_CATEGORY(CUTELYST_UPLOAD, "cutelyst.upload")
Q_LOGGING_CATEGORY(CUTELYST_MULTIPART, "cutelyst.multipart")
Q_LOGGING_CATEGORY(CUTELYST_VIEW, "cutelyst.view")
Q_LOGGING_CATEGORY(CUTELYST_REQUEST, "cutelyst.request")
Q_LOGGING_CATEGORY(CUTELYST_RESPONSE, "cutelyst.response")
Q_LOGGING_CATEGORY(CUTELYST_STATS, "cutelyst.stats")
Q_LOGGING_CATEGORY(CUTELYST_COMPONENT, "cutelyst.component")
using namespace Cutelyst;
Application::Application(QObject *parent) :
QObject(parent),
d_ptr(new ApplicationPrivate)
{
Q_D(Application);
d->headers.setHeader(QStringLiteral("X-Cutelyst"), QStringLiteral(VERSION));
qRegisterMetaType<ParamsMultiMap>();
qRegisterMetaType<ActionREST *>();
qRegisterMetaType<RoleACL *>();
qRegisterMetaType<RenderView *>();
d->dispatcher = new Dispatcher(this);
}
Application::~Application()
{
delete d_ptr;
}
bool Application::init()
{
qCDebug(CUTELYST_CORE) << "Default Application::init called on pid:" << QCoreApplication::applicationPid();
return true;
}
bool Application::postFork()
{
qCDebug(CUTELYST_CORE) << "Default Application::postFork called on pid:" << QCoreApplication::applicationPid();
return true;
}
Headers &Application::defaultHeaders()
{
Q_D(Application);
return d->headers;
}
bool Application::registerPlugin(Cutelyst::Plugin *plugin)
{
Q_D(Application);
d->plugins.append(plugin);
return true;
}
bool Application::registerController(Controller *controller)
{
Q_D(Application);
if (d->init) {
qCWarning(CUTELYST_CORE) << "Tryied to register Controller after the Application was initted, ignoring"
<< controller->metaObject()->className();
return false;
}
d->controllers.append(controller);
return true;
}
QList<Controller *> Application::controllers() const
{
Q_D(const Application);
return d->controllers;
}
bool Application::registerView(View *view, const QString &name)
{
Q_D(Application);
if (d->views.contains(name)) {
qCWarning(CUTELYST_CORE) << "Not registering View. There is already a view with this name:" << name;
return false;
}
d->views.insert(name, view);
return true;
}
View *Application::view(const QString &name) const
{
Q_D(const Application);
return d->views.value(name);
}
void Application::registerDispatcher(DispatchType *dispatcher)
{
Q_D(const Application);
dispatcher->setParent(this);
d->dispatcher->registerDispatchType(dispatcher);
}
QVariant Application::config(const QString &key, const QVariant &defaultValue) const
{
Q_D(const Application);
QVariantHash::const_iterator it = d->config.constFind(key);
if (it != d->config.constEnd()) {
return it.value();
}
return defaultValue;
}
Dispatcher *Application::dispatcher() const
{
Q_D(const Application);
return d->dispatcher;
}
QList<DispatchType *> Application::dispatchers() const
{
Q_D(const Application);
return d->dispatcher->dispatchers();
}
QVariantHash Application::config() const
{
Q_D(const Application);
return d->config;
}
QString Cutelyst::Application::pathTo(const QStringList &path) const
{
QDir home = config(QStringLiteral("home")).toString();
return home.absoluteFilePath(path.join(QDir::separator()));
}
bool Cutelyst::Application::inited() const
{
Q_D(const Application);
return d->init;
}
Cutelyst::Engine *Cutelyst::Application::engine() const
{
Q_D(const Application);
return d->engine;
}
void Application::setConfig(const QString &key, const QVariant &value)
{
Q_D(Application);
d->config.insert(key, value);
}
bool Application::setup(Engine *engine)
{
Q_D(Application);
if (d->init) {
return true;
}
d->useStats = CUTELYST_STATS().isDebugEnabled();
d->engine = engine;
d->config = engine->config(QStringLiteral("Cutelyst"));
d->setupHome();
// Call the virtual application init
// to setup Controllers plugins stuff
if (init()) {
QString appName = QCoreApplication::applicationName();
QList<QStringList> tablePlugins;
Q_FOREACH (Plugin *plugin, d->plugins) {
QString className = QString::fromLatin1(plugin->metaObject()->className());
tablePlugins.append({ className });
// Configure plugins
plugin->setup(this);
}
if (!tablePlugins.isEmpty()) {
qCDebug(CUTELYST_CORE) << Utils::buildTable(tablePlugins, QStringList(),
QStringLiteral("Loaded plugins:")).data();
}
QList<QStringList> tableDataHandlers;
tableDataHandlers.append({ QLatin1String("application/x-www-form-urlencoded") });
tableDataHandlers.append({ QLatin1String("application/json") });
tableDataHandlers.append({ QLatin1String("multipart/form-data") });
qCDebug(CUTELYST_CORE) << Utils::buildTable(tableDataHandlers, QStringList(),
QStringLiteral("Loaded Request Data Handlers:")).data();
qCDebug(CUTELYST_CORE) << "Loaded dispatcher" << QString::fromLatin1(d->dispatcher->metaObject()->className());
qCDebug(CUTELYST_CORE) << "Using engine" << QString::fromLatin1(d->engine->metaObject()->className());
QString home = d->config.value("home").toString();
if (home.isEmpty()) {
qCDebug(CUTELYST_CORE) << "Couldn't find home";
} else {
QFileInfo homeInfo = home;
if (homeInfo.isDir()) {
qCDebug(CUTELYST_CORE) << "Found home" << home;
} else {
qCDebug(CUTELYST_CORE) << "Home" << home << "doesn't exist";
}
}
QList<QStringList> table;
Q_FOREACH (Controller *controller, d->controllers) {
QString className = QString::fromLatin1(controller->metaObject()->className());
if (!className.startsWith(QLatin1String("Cutelyst"))) {
className = appName % QLatin1String("::Controller::") % className;
}
table.append({ className, QStringLiteral("instance")});
}
Q_FOREACH (View *view, d->views) {
QString className = QString::fromLatin1(view->metaObject()->className());
if (!className.startsWith(QLatin1String("Cutelyst"))) {
className = appName % QLatin1String("::View::") % className;
}
table.append({ className, QStringLiteral("instance")});
}
if (!table.isEmpty()) {
qCDebug(CUTELYST_CORE) << Utils::buildTable(table, {
QStringLiteral("Class"), QStringLiteral("Type")
},
QStringLiteral("Loaded components:")).data();
}
Q_FOREACH (Controller *controller, d->controllers) {
controller->d_ptr->init(this, d->dispatcher);
}
d->dispatcher->setupActions(d->controllers);
d->init = true;
qCDebug(CUTELYST_CORE) << QString("%1 powered by Cutelyst %2, Qt %3.")
.arg(QCoreApplication::applicationName())
.arg(VERSION)
.arg(qVersion())
.toLatin1().data();
return true;
}
return false;
}
void Application::handleRequest(Request *req)
{
Q_D(Application);
ContextPrivate *priv = new ContextPrivate;
priv->app = this;
priv->engine = d->engine;
priv->dispatcher = d->dispatcher;
priv->request = req;
priv->plugins = d->plugins;
priv->requestPtr = req->d_ptr->requestPtr;
Context *c = new Context(priv);
priv->response = new Response(c);
ResponsePrivate *resPriv = priv->response->d_ptr;
resPriv->engine = d->engine;
resPriv->headers = d->headers;
if (d->useStats) {
priv->stats = new Stats(this);
}
// Process request
bool skipMethod = false;
Q_EMIT beforePrepareAction(c, &skipMethod);
if (!skipMethod) {
if (CUTELYST_REQUEST().isEnabled(QtDebugMsg)) {
d->logRequest(req);
}
d->dispatcher->prepareAction(c);
Q_EMIT beforeDispatch(c);
d->dispatcher->dispatch(c);
Q_EMIT afterDispatch(c);
}
d->engine->finalize(c);
if (priv->stats) {
qCDebug(CUTELYST_STATS, "Response Code: %d; Content-Type: %s; Content-Length: %s",
c->response()->status(),
c->response()->headers().header(QStringLiteral("Content-Type"), QStringLiteral("unknown")).toLatin1().data(),
c->response()->headers().header(QStringLiteral("Content-Length"), QStringLiteral("unknown")).toLatin1().data());
RequestPrivate *reqPriv = req->d_ptr;
reqPriv->endOfRequest = d->engine->time();
double enlapsed = (reqPriv->endOfRequest - reqPriv->startOfRequest) / 1000000.0;
QString average;
if (enlapsed == 0.0) {
average = QStringLiteral("??");
} else {
average = QString::number(1.0 / enlapsed, 'f');
average.truncate(average.size() - 3);
}
qCDebug(CUTELYST_STATS) << QString("Request took: %1s (%2/s)\n%3")
.arg(QString::number(enlapsed, 'f'))
.arg(average)
.arg(priv->stats->report())
.toLatin1().data();
delete priv->stats;
}
delete c;
}
bool Application::enginePostFork()
{
Q_D(Application);
if (!postFork()) {
return false;
}
Q_FOREACH (Controller *controller, d->controllers) {
if (!controller->postFork(this)) {
return false;
}
}
return true;
}
void Cutelyst::ApplicationPrivate::setupHome()
{
// Hook the current directory in config if "home" is not set
if (!config.contains("home")) {
config.insert("home", QDir::currentPath());
}
if (!config.contains("root")) {
QDir home = config.value("home").toString();
config.insert("root", home.absoluteFilePath("root"));
}
}
void Cutelyst::ApplicationPrivate::logRequest(Request *req)
{
QString path = req->path();
if (path.isEmpty()) {
path = QStringLiteral("/");
}
qCDebug(CUTELYST_REQUEST) << req->method() << "request for" << path << "from" << req->address().toString();
ParamsMultiMap params = req->queryParameters();
if (!params.isEmpty()) {
logRequestParameters(params, QStringLiteral("Query Parameters are:"));
}
params = req->bodyParameters();
if (!params.isEmpty()) {
logRequestParameters(params, QStringLiteral("Body Parameters are:"));
}
QMap<QString, Cutelyst::Upload *> uploads = req->uploads();
if (!uploads.isEmpty()) {
logRequestUploads(uploads);
}
}
void Cutelyst::ApplicationPrivate::logRequestParameters(const ParamsMultiMap ¶ms, const QString &title)
{
QList<QStringList> table;
ParamsMultiMap::ConstIterator it = params.constBegin();
while (it != params.constEnd()) {
table.append({ it.key(), it.value() });
++it;
}
qCDebug(CUTELYST_REQUEST) << Utils::buildTable(table, {
QStringLiteral("Parameter"),
QStringLiteral("Value"),
},
title).data();
}
void Cutelyst::ApplicationPrivate::logRequestUploads(const QMap<QString, Cutelyst::Upload *> &uploads)
{
QList<QStringList> table;
QMap<QString, Cutelyst::Upload *>::ConstIterator it = uploads.constBegin();
while (it != uploads.constEnd()) {
Upload *upload = it.value();
table.append({ it.key(),
upload->filename(),
upload->contentType(),
QString::number(upload->size())
});
++it;
}
qCDebug(CUTELYST_REQUEST) << Utils::buildTable(table, {
QStringLiteral("Parameter"),
QStringLiteral("Filename"),
QStringLiteral("Type"),
QStringLiteral("Size"),
},
QStringLiteral("File Uploads are:")).data();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/source/timing.h"
#include "webrtc/modules/video_coding/main/source/internal_defines.h"
#include "webrtc/modules/video_coding/main/source/jitter_buffer_common.h"
#include "webrtc/modules/video_coding/main/source/timestamp_extrapolator.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
VCMTiming::VCMTiming(Clock* clock,
int32_t vcm_id,
int32_t timing_id,
VCMTiming* master_timing)
: crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
vcm_id_(vcm_id),
clock_(clock),
timing_id_(timing_id),
master_(false),
ts_extrapolator_(),
codec_timer_(),
render_delay_ms_(kDefaultRenderDelayMs),
min_playout_delay_ms_(0),
jitter_delay_ms_(0),
current_delay_ms_(0),
prev_frame_timestamp_(0) {
if (master_timing == NULL) {
master_ = true;
ts_extrapolator_ = new VCMTimestampExtrapolator(clock_, vcm_id, timing_id);
} else {
ts_extrapolator_ = master_timing->ts_extrapolator_;
}
}
VCMTiming::~VCMTiming() {
if (master_) {
delete ts_extrapolator_;
}
delete crit_sect_;
}
void VCMTiming::Reset() {
CriticalSectionScoped cs(crit_sect_);
ts_extrapolator_->Reset();
codec_timer_.Reset();
render_delay_ms_ = kDefaultRenderDelayMs;
min_playout_delay_ms_ = 0;
jitter_delay_ms_ = 0;
current_delay_ms_ = 0;
prev_frame_timestamp_ = 0;
}
void VCMTiming::ResetDecodeTime() {
codec_timer_.Reset();
}
void VCMTiming::set_render_delay(uint32_t render_delay_ms) {
CriticalSectionScoped cs(crit_sect_);
render_delay_ms_ = render_delay_ms;
}
void VCMTiming::set_min_playout_delay(uint32_t min_playout_delay_ms) {
CriticalSectionScoped cs(crit_sect_);
min_playout_delay_ms_ = min_playout_delay_ms;
}
void VCMTiming::SetJitterDelay(uint32_t jitter_delay_ms) {
CriticalSectionScoped cs(crit_sect_);
if (jitter_delay_ms != jitter_delay_ms_) {
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding,
VCMId(vcm_id_, timing_id_),
"Desired jitter buffer level: %u ms", jitter_delay_ms);
}
jitter_delay_ms_ = jitter_delay_ms;
// When in initial state, set current delay to minimum delay.
if (current_delay_ms_ == 0) {
current_delay_ms_ = jitter_delay_ms_;
}
}
}
void VCMTiming::UpdateCurrentDelay(uint32_t frame_timestamp) {
CriticalSectionScoped cs(crit_sect_);
uint32_t target_delay_ms = TargetDelayInternal();
if (current_delay_ms_ == 0) {
// Not initialized, set current delay to target.
current_delay_ms_ = target_delay_ms;
} else if (target_delay_ms != current_delay_ms_) {
int64_t delay_diff_ms = static_cast<int64_t>(target_delay_ms) -
current_delay_ms_;
// Never change the delay with more than 100 ms every second. If we're
// changing the delay in too large steps we will get noticeable freezes. By
// limiting the change we can increase the delay in smaller steps, which
// will be experienced as the video is played in slow motion. When lowering
// the delay the video will be played at a faster pace.
int64_t max_change_ms = 0;
if (frame_timestamp < 0x0000ffff && prev_frame_timestamp_ > 0xffff0000) {
// wrap
max_change_ms = kDelayMaxChangeMsPerS * (frame_timestamp +
(static_cast<int64_t>(1) << 32) - prev_frame_timestamp_) / 90000;
} else {
max_change_ms = kDelayMaxChangeMsPerS *
(frame_timestamp - prev_frame_timestamp_) / 90000;
}
if (max_change_ms <= 0) {
// Any changes less than 1 ms are truncated and
// will be postponed. Negative change will be due
// to reordering and should be ignored.
return;
}
delay_diff_ms = std::max(delay_diff_ms, -max_change_ms);
delay_diff_ms = std::min(delay_diff_ms, max_change_ms);
current_delay_ms_ = current_delay_ms_ + static_cast<int32_t>(delay_diff_ms);
}
prev_frame_timestamp_ = frame_timestamp;
}
void VCMTiming::UpdateCurrentDelay(int64_t render_time_ms,
int64_t actual_decode_time_ms) {
CriticalSectionScoped cs(crit_sect_);
uint32_t target_delay_ms = TargetDelayInternal();
int64_t delayed_ms = actual_decode_time_ms -
(render_time_ms - MaxDecodeTimeMs() - render_delay_ms_);
if (delayed_ms < 0) {
return;
}
if (current_delay_ms_ + delayed_ms <= target_delay_ms) {
current_delay_ms_ += static_cast<uint32_t>(delayed_ms);
} else {
current_delay_ms_ = target_delay_ms;
}
}
int32_t VCMTiming::StopDecodeTimer(uint32_t time_stamp,
int64_t start_time_ms,
int64_t now_ms) {
CriticalSectionScoped cs(crit_sect_);
const int32_t max_dec_time = MaxDecodeTimeMs();
int32_t time_diff_ms = codec_timer_.StopTimer(start_time_ms, now_ms);
if (time_diff_ms < 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_), "Codec timer error: %d", time_diff_ms);
assert(false);
}
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_),
"Frame decoded: time_stamp=%u dec_time=%d max_dec_time=%u, at %u",
time_stamp, time_diff_ms, max_dec_time, MaskWord64ToUWord32(now_ms));
}
return 0;
}
void VCMTiming::IncomingTimestamp(uint32_t time_stamp, int64_t now_ms) {
CriticalSectionScoped cs(crit_sect_);
ts_extrapolator_->Update(now_ms, time_stamp, master_);
}
int64_t VCMTiming::RenderTimeMs(uint32_t frame_timestamp, int64_t now_ms)
const {
CriticalSectionScoped cs(crit_sect_);
const int64_t render_time_ms = RenderTimeMsInternal(frame_timestamp, now_ms);
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_), "Render frame %u at %u. Render delay %u",
"jitter delay %u, max decode time %u, playout delay %u",
frame_timestamp, MaskWord64ToUWord32(render_time_ms), render_delay_ms_,
jitter_delay_ms_, MaxDecodeTimeMs(), min_playout_delay_ms_);
}
return render_time_ms;
}
int64_t VCMTiming::RenderTimeMsInternal(uint32_t frame_timestamp,
int64_t now_ms) const {
int64_t estimated_complete_time_ms =
ts_extrapolator_->ExtrapolateLocalTime(frame_timestamp);
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding,
VCMId(vcm_id_, timing_id_), "ExtrapolateLocalTime(%u)=%u ms",
frame_timestamp, MaskWord64ToUWord32(estimated_complete_time_ms));
}
if (estimated_complete_time_ms == -1) {
estimated_complete_time_ms = now_ms;
}
// Make sure that we have at least the playout delay.
uint32_t actual_delay = std::max(current_delay_ms_, min_playout_delay_ms_);
return estimated_complete_time_ms + actual_delay;
}
// Must be called from inside a critical section.
int32_t VCMTiming::MaxDecodeTimeMs(FrameType frame_type /*= kVideoFrameDelta*/)
const {
const int32_t decode_time_ms = codec_timer_.RequiredDecodeTimeMs(frame_type);
if (decode_time_ms < 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_), "Negative maximum decode time: %d", decode_time_ms);
return -1;
}
return decode_time_ms;
}
uint32_t VCMTiming::MaxWaitingTime(int64_t render_time_ms, int64_t now_ms)
const {
CriticalSectionScoped cs(crit_sect_);
const int64_t max_wait_time_ms = render_time_ms - now_ms -
MaxDecodeTimeMs() - render_delay_ms_;
if (max_wait_time_ms < 0) {
return 0;
}
return static_cast<uint32_t>(max_wait_time_ms);
}
bool VCMTiming::EnoughTimeToDecode(uint32_t available_processing_time_ms)
const {
CriticalSectionScoped cs(crit_sect_);
int32_t max_decode_time_ms = MaxDecodeTimeMs();
if (max_decode_time_ms < 0) {
// Haven't decoded any frames yet, try decoding one to get an estimate
// of the decode time.
return true;
} else if (max_decode_time_ms == 0) {
// Decode time is less than 1, set to 1 for now since
// we don't have any better precision. Count ticks later?
max_decode_time_ms = 1;
}
return static_cast<int32_t>(available_processing_time_ms) -
max_decode_time_ms > 0;
}
uint32_t VCMTiming::TargetVideoDelay() const {
CriticalSectionScoped cs(crit_sect_);
return TargetDelayInternal();
}
uint32_t VCMTiming::TargetDelayInternal() const {
return std::max(min_playout_delay_ms_,
jitter_delay_ms_ + MaxDecodeTimeMs() + render_delay_ms_);
}
} // namespace webrtc
<commit_msg>Add a log message to see video delay break down<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/source/timing.h"
#include "webrtc/modules/video_coding/main/source/internal_defines.h"
#include "webrtc/modules/video_coding/main/source/jitter_buffer_common.h"
#include "webrtc/modules/video_coding/main/source/timestamp_extrapolator.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
VCMTiming::VCMTiming(Clock* clock,
int32_t vcm_id,
int32_t timing_id,
VCMTiming* master_timing)
: crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
vcm_id_(vcm_id),
clock_(clock),
timing_id_(timing_id),
master_(false),
ts_extrapolator_(),
codec_timer_(),
render_delay_ms_(kDefaultRenderDelayMs),
min_playout_delay_ms_(0),
jitter_delay_ms_(0),
current_delay_ms_(0),
prev_frame_timestamp_(0) {
if (master_timing == NULL) {
master_ = true;
ts_extrapolator_ = new VCMTimestampExtrapolator(clock_, vcm_id, timing_id);
} else {
ts_extrapolator_ = master_timing->ts_extrapolator_;
}
}
VCMTiming::~VCMTiming() {
if (master_) {
delete ts_extrapolator_;
}
delete crit_sect_;
}
void VCMTiming::Reset() {
CriticalSectionScoped cs(crit_sect_);
ts_extrapolator_->Reset();
codec_timer_.Reset();
render_delay_ms_ = kDefaultRenderDelayMs;
min_playout_delay_ms_ = 0;
jitter_delay_ms_ = 0;
current_delay_ms_ = 0;
prev_frame_timestamp_ = 0;
}
void VCMTiming::ResetDecodeTime() {
codec_timer_.Reset();
}
void VCMTiming::set_render_delay(uint32_t render_delay_ms) {
CriticalSectionScoped cs(crit_sect_);
render_delay_ms_ = render_delay_ms;
}
void VCMTiming::set_min_playout_delay(uint32_t min_playout_delay_ms) {
CriticalSectionScoped cs(crit_sect_);
min_playout_delay_ms_ = min_playout_delay_ms;
}
void VCMTiming::SetJitterDelay(uint32_t jitter_delay_ms) {
CriticalSectionScoped cs(crit_sect_);
if (jitter_delay_ms != jitter_delay_ms_) {
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding,
VCMId(vcm_id_, timing_id_),
"Desired jitter buffer level: %u ms", jitter_delay_ms);
}
jitter_delay_ms_ = jitter_delay_ms;
// When in initial state, set current delay to minimum delay.
if (current_delay_ms_ == 0) {
current_delay_ms_ = jitter_delay_ms_;
}
}
}
void VCMTiming::UpdateCurrentDelay(uint32_t frame_timestamp) {
CriticalSectionScoped cs(crit_sect_);
uint32_t target_delay_ms = TargetDelayInternal();
if (current_delay_ms_ == 0) {
// Not initialized, set current delay to target.
current_delay_ms_ = target_delay_ms;
} else if (target_delay_ms != current_delay_ms_) {
int64_t delay_diff_ms = static_cast<int64_t>(target_delay_ms) -
current_delay_ms_;
// Never change the delay with more than 100 ms every second. If we're
// changing the delay in too large steps we will get noticeable freezes. By
// limiting the change we can increase the delay in smaller steps, which
// will be experienced as the video is played in slow motion. When lowering
// the delay the video will be played at a faster pace.
int64_t max_change_ms = 0;
if (frame_timestamp < 0x0000ffff && prev_frame_timestamp_ > 0xffff0000) {
// wrap
max_change_ms = kDelayMaxChangeMsPerS * (frame_timestamp +
(static_cast<int64_t>(1) << 32) - prev_frame_timestamp_) / 90000;
} else {
max_change_ms = kDelayMaxChangeMsPerS *
(frame_timestamp - prev_frame_timestamp_) / 90000;
}
if (max_change_ms <= 0) {
// Any changes less than 1 ms are truncated and
// will be postponed. Negative change will be due
// to reordering and should be ignored.
return;
}
delay_diff_ms = std::max(delay_diff_ms, -max_change_ms);
delay_diff_ms = std::min(delay_diff_ms, max_change_ms);
current_delay_ms_ = current_delay_ms_ + static_cast<int32_t>(delay_diff_ms);
}
prev_frame_timestamp_ = frame_timestamp;
}
void VCMTiming::UpdateCurrentDelay(int64_t render_time_ms,
int64_t actual_decode_time_ms) {
CriticalSectionScoped cs(crit_sect_);
uint32_t target_delay_ms = TargetDelayInternal();
int64_t delayed_ms = actual_decode_time_ms -
(render_time_ms - MaxDecodeTimeMs() - render_delay_ms_);
if (delayed_ms < 0) {
return;
}
if (current_delay_ms_ + delayed_ms <= target_delay_ms) {
current_delay_ms_ += static_cast<uint32_t>(delayed_ms);
} else {
current_delay_ms_ = target_delay_ms;
}
}
int32_t VCMTiming::StopDecodeTimer(uint32_t time_stamp,
int64_t start_time_ms,
int64_t now_ms) {
CriticalSectionScoped cs(crit_sect_);
const int32_t max_dec_time = MaxDecodeTimeMs();
int32_t time_diff_ms = codec_timer_.StopTimer(start_time_ms, now_ms);
if (time_diff_ms < 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_), "Codec timer error: %d", time_diff_ms);
assert(false);
}
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_),
"Frame decoded: time_stamp=%u dec_time=%d max_dec_time=%u, at %u",
time_stamp, time_diff_ms, max_dec_time, MaskWord64ToUWord32(now_ms));
}
return 0;
}
void VCMTiming::IncomingTimestamp(uint32_t time_stamp, int64_t now_ms) {
CriticalSectionScoped cs(crit_sect_);
ts_extrapolator_->Update(now_ms, time_stamp, master_);
}
int64_t VCMTiming::RenderTimeMs(uint32_t frame_timestamp, int64_t now_ms)
const {
CriticalSectionScoped cs(crit_sect_);
const int64_t render_time_ms = RenderTimeMsInternal(frame_timestamp, now_ms);
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_), "Render frame %u at %u. Render delay %u",
"jitter delay %u, max decode time %u, playout delay %u",
frame_timestamp, MaskWord64ToUWord32(render_time_ms), render_delay_ms_,
jitter_delay_ms_, MaxDecodeTimeMs(), min_playout_delay_ms_);
}
return render_time_ms;
}
int64_t VCMTiming::RenderTimeMsInternal(uint32_t frame_timestamp,
int64_t now_ms) const {
int64_t estimated_complete_time_ms =
ts_extrapolator_->ExtrapolateLocalTime(frame_timestamp);
if (master_) {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding,
VCMId(vcm_id_, timing_id_), "ExtrapolateLocalTime(%u)=%u ms",
frame_timestamp, MaskWord64ToUWord32(estimated_complete_time_ms));
}
if (estimated_complete_time_ms == -1) {
estimated_complete_time_ms = now_ms;
}
// Make sure that we have at least the playout delay.
uint32_t actual_delay = std::max(current_delay_ms_, min_playout_delay_ms_);
return estimated_complete_time_ms + actual_delay;
}
// Must be called from inside a critical section.
int32_t VCMTiming::MaxDecodeTimeMs(FrameType frame_type /*= kVideoFrameDelta*/)
const {
const int32_t decode_time_ms = codec_timer_.RequiredDecodeTimeMs(frame_type);
if (decode_time_ms < 0) {
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(vcm_id_,
timing_id_), "Negative maximum decode time: %d", decode_time_ms);
return -1;
}
return decode_time_ms;
}
uint32_t VCMTiming::MaxWaitingTime(int64_t render_time_ms, int64_t now_ms)
const {
CriticalSectionScoped cs(crit_sect_);
const int64_t max_wait_time_ms = render_time_ms - now_ms -
MaxDecodeTimeMs() - render_delay_ms_;
if (max_wait_time_ms < 0) {
return 0;
}
return static_cast<uint32_t>(max_wait_time_ms);
}
bool VCMTiming::EnoughTimeToDecode(uint32_t available_processing_time_ms)
const {
CriticalSectionScoped cs(crit_sect_);
int32_t max_decode_time_ms = MaxDecodeTimeMs();
if (max_decode_time_ms < 0) {
// Haven't decoded any frames yet, try decoding one to get an estimate
// of the decode time.
return true;
} else if (max_decode_time_ms == 0) {
// Decode time is less than 1, set to 1 for now since
// we don't have any better precision. Count ticks later?
max_decode_time_ms = 1;
}
return static_cast<int32_t>(available_processing_time_ms) -
max_decode_time_ms > 0;
}
uint32_t VCMTiming::TargetVideoDelay() const {
CriticalSectionScoped cs(crit_sect_);
return TargetDelayInternal();
}
uint32_t VCMTiming::TargetDelayInternal() const {
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding,
VCMId(vcm_id_, timing_id_),
"Delay: min_playout=%u jitter=%u max_decode=%u render=%u",
min_playout_delay_ms_, jitter_delay_ms_, MaxDecodeTimeMs(),
render_delay_ms_);
return std::max(min_playout_delay_ms_,
jitter_delay_ms_ + MaxDecodeTimeMs() + render_delay_ms_);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>#include <ir/index_manager/store/FSIndexInput.h>
#include <ir/index_manager/utility/Utilities.h>
using namespace izenelib::ir::indexmanager;
FSIndexInput::FSIndexInput(const char* filename)
{
fileHandle_ = fopen(filename, "rb");
setbuf(fileHandle_,NULL);
if (fileHandle_ == NULL)
{
perror("error when opening file");
string sFileName = filename;
SF1V5_THROW(ERROR_FILEIO,"Open file error: " + sFileName);
}
fseek(fileHandle_, 0, SEEK_END);
length_ = ftell(fileHandle_);
rewind(fileHandle_);
filename_ = filename;
}
FSIndexInput::FSIndexInput(const char* filename,size_t buffsize)
:IndexInput(buffsize)
{
fileHandle_ = fopen(filename, "rb");
setbuf(fileHandle_,NULL);
if (fileHandle_ == NULL)
{
perror("error when opening file");
string sFileName = filename;
SF1V5_THROW(ERROR_FILEIO,"Open file error: " + sFileName);
}
fseek(fileHandle_, 0, SEEK_END);
length_ = ftell(fileHandle_);
rewind(fileHandle_);
filename_ = filename;
}
FSIndexInput::~FSIndexInput()
{
close();
}
void FSIndexInput::readInternal(char* b,size_t length,bool bCheck/* = true*/)
{
if (bCheck)
{
int64_t position = getFilePointer();
if (0 != fseek(fileHandle_, 0, SEEK_CUR))
{
if (0 != fseek(fileHandle_, position, SEEK_SET))
SF1V5_THROW(ERROR_FILEIO,"FSIndexInput::readInternal():file IO seek error: " + filename_);
}
}
int ret = fread(b, 1, length, fileHandle_);
if (ret != (int)length)
if (!feof(fileHandle_))
SF1V5_THROW(ERROR_FILEIO,"FSIndexInput::readInternal():file IO read error:" + filename_);
}
void FSIndexInput::close()
{
boost::mutex::scoped_lock lock(this->mutex_);
if (fileHandle_ )
{
fclose(fileHandle_);
fileHandle_ = NULL;
}
}
IndexInput* FSIndexInput::clone()
{
FSIndexInput* pClone = new FSIndexInput(filename_.c_str(),bufferSize_);
return pClone;
}
void FSIndexInput::seekInternal(int64_t position)
{
if (0 != fseek(fileHandle_, position, SEEK_SET))
{
cout<<"error "<<position<<" "<<filename_<<endl;
SF1V5_THROW(ERROR_FILEIO,"FSIndexInput::seekInternal():file IO seek error: " + filename_);
}
}
<commit_msg>Do not use setbuf(NULL) for file read in indexmanager<commit_after>#include <ir/index_manager/store/FSIndexInput.h>
#include <ir/index_manager/utility/Utilities.h>
using namespace izenelib::ir::indexmanager;
FSIndexInput::FSIndexInput(const char* filename)
{
fileHandle_ = fopen(filename, "rb");
//setbuf(fileHandle_,NULL);
if (fileHandle_ == NULL)
{
perror("error when opening file");
string sFileName = filename;
SF1V5_THROW(ERROR_FILEIO,"Open file error: " + sFileName);
}
fseek(fileHandle_, 0, SEEK_END);
length_ = ftell(fileHandle_);
rewind(fileHandle_);
filename_ = filename;
}
FSIndexInput::FSIndexInput(const char* filename,size_t buffsize)
:IndexInput(buffsize)
{
fileHandle_ = fopen(filename, "rb");
//setbuf(fileHandle_,NULL);
if (fileHandle_ == NULL)
{
perror("error when opening file");
string sFileName = filename;
SF1V5_THROW(ERROR_FILEIO,"Open file error: " + sFileName);
}
fseek(fileHandle_, 0, SEEK_END);
length_ = ftell(fileHandle_);
rewind(fileHandle_);
filename_ = filename;
}
FSIndexInput::~FSIndexInput()
{
close();
}
void FSIndexInput::readInternal(char* b,size_t length,bool bCheck/* = true*/)
{
if (bCheck)
{
int64_t position = getFilePointer();
if (0 != fseek(fileHandle_, 0, SEEK_CUR))
{
if (0 != fseek(fileHandle_, position, SEEK_SET))
SF1V5_THROW(ERROR_FILEIO,"FSIndexInput::readInternal():file IO seek error: " + filename_);
}
}
int ret = fread(b, 1, length, fileHandle_);
if (ret != (int)length)
if (!feof(fileHandle_))
SF1V5_THROW(ERROR_FILEIO,"FSIndexInput::readInternal():file IO read error:" + filename_);
}
void FSIndexInput::close()
{
boost::mutex::scoped_lock lock(this->mutex_);
if (fileHandle_ )
{
fclose(fileHandle_);
fileHandle_ = NULL;
}
}
IndexInput* FSIndexInput::clone()
{
FSIndexInput* pClone = new FSIndexInput(filename_.c_str(),bufferSize_);
return pClone;
}
void FSIndexInput::seekInternal(int64_t position)
{
if (0 != fseek(fileHandle_, position, SEEK_SET))
{
cout<<"error "<<position<<" "<<filename_<<endl;
SF1V5_THROW(ERROR_FILEIO,"FSIndexInput::seekInternal():file IO seek error: " + filename_);
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <SFML/Graphics.hpp>
#include "game.h"
Game::Game():
playing(true),
screen(),
map(nullptr)
//map_camera(nullptr),
//unitRepository(nullptr)
{
sf::ContextSettings settings;
settings.antialiasingLevel = 8;
screen.create(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close, settings);
screen.setFramerateLimit(IDEAL_FPS);
screen.setMouseCursorVisible(false);
if (!init()){
std::cerr << "Failed to initialized game.";
playing = false;
}
}
int Game::execute() {
sf::Clock clock;
while(playing) {
sf::Event event;
actionMap.clearEvents();
sf::Time dt = clock.restart();
while(screen.pollEvent(event)) {
onEvent(event);
actionMap.pushEvent(event);
}
updateState(dt);
render();
}
return 0;
}
bool Game::init() {
if (!terrain.loadFromFile("graphics/terrain.png")) {
std::cout << "Failed to read graphics/terrain.png data" << std::endl;
return false;
}
sf::Image temp;
if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
return false;
}
temp.createMaskFromColor(sf::Color(255, 0, 255));
shroud_edges.loadFromImage(temp);
map.reset(new Map(terrain, shroud_edges));
map->load("maps/4PL_Mountains.ini");
camera.reset({0,0,800,600});
screen.setView(camera);
//init a trike
sf::Image trikeImage;
trikeImage.loadFromFile("graphics/Unit_Trike.bmp");
trikeImage.createMaskFromColor(sf::Color(0,0,0));
sf::Texture* trikeTexture = new sf::Texture; //yes we are leaking! Player should own this
trikeTexture->loadFromImage(trikeImage);
sf::Image trikeShadowImage;
trikeShadowImage.loadFromFile("graphics/Unit_Trike_s.bmp");
trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));
sf::Texture* trikeShadowTexture = new sf::Texture;
trikeShadowTexture->loadFromImage(trikeShadowImage);
sf::Image selectedImage;
selectedImage.loadFromFile("graphics/selected.bmp");
selectedImage.createMaskFromColor(sf::Color(255, 0, 255));
sf::Texture* selectedTexture = new sf::Texture; //more leaks!
selectedTexture->loadFromImage(selectedImage);
units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));
//remove shroud here
map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);
//shroud_edges_shadow = Surface::load("graphics/shroud_edges_shadow.bmp");
//if (shroud_edges_shadow == NULL) {
//cout << "Failed to read graphics/shroud_edges_shadow.bmp data" << endl;
//return false;
//}
//mouse.init(screen);
//map_camera.reset(new MapCamera(0, 0, screen, &map));
//map.load("maps/4PL_Mountains.ini");
//unitRepository.reset(new UnitRepository(&map));
////init two players
//int idCount = 0;
//players.emplace_back(House::Sardaukar, idCount++);
//players.emplace_back(House::Harkonnen, idCount++);
//units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));
//units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));
//// soldiers
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));
thor::Action leftClick(sf::Mouse::Left, thor::Action::PressOnce);
thor::Action leftHold(sf::Mouse::Left, thor::Action::Hold);
actionMap["leftClick"] = leftClick;
actionMap["leftHold"] = leftHold;
return true;
}
void Game::onEvent(sf::Event event) {
switch (event.type){
case sf::Event::Closed:
playing = false; break;
case sf::Event::KeyPressed:
switch (event.key.code) {
case sf::Keyboard::Q:
playing = false; break;
default:
break;
}
break;
case sf::Event::MouseButtonPressed:
switch (event.mouseButton.button){
case sf::Mouse::Left:{
sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));
box.setTopLeft(toSet);
break;
}
default:
break;
}
break;
case sf::Event::MouseButtonReleased:
switch (event.mouseButton.button){
case sf::Mouse::Left:
for (auto& unit : units){
if (box.intersects(unit->getBounds())){
selectUnit(*unit);
mouse.setType(Mouse::Type::Move); //at least one unit selected...
}
}
box.clear();
break;
case sf::Mouse::Right:
//deselect all units
for (auto& unit : units){
unit->unselect();
mouse.setType(Mouse::Type::Default);
}
default:
break;
}
default:
break;
}
//mouse.onEvent(event);
//keyboard.onEvent(event);
//map_camera->onEvent(event);
//if (event->type == SDL_USEREVENT) {
//if (event->user.code == D2TM_SELECT) {
//std::unique_ptr<D2TMSelectStruct> s(static_cast<D2TMSelectStruct*>(event->user.data1));
//Point p = map_camera->toWorldCoordinates(s->screen_position);
//if (mouse.is_pointing()) {
//Unit* selected_unit = NULL;
//for (auto& unit : units){
//if (unit->is_point_within(p)){
//selected_unit = unit.get();
//break;
//}
//}
//if (selected_unit != NULL) {
//deselectAllUnits();
//selected_unit->select();
//mouse.state_order_move();
//}
//}
//} else if (event->user.code == D2TM_DESELECT) {
//mouse.state_pointing();
//deselectAllUnits();
//} else if (event->user.code == D2TM_BOX_SELECT) {
//std::unique_ptr<D2TMBoxSelectStruct> s(static_cast<D2TMBoxSelectStruct*>(event->user.data1));
//Rectangle rectangle = map_camera->toWorldCoordinates(s->rectangle);
//if (mouse.is_pointing()) {
//mouse.state_pointing();
//deselectAllUnits();
//for (auto& unit : units){
//if (unit->is_within(rectangle)){
//unit->select();
//mouse.state_order_move();
//}
//}
//}
//} else if (event->user.code == D2TM_MOVE_UNIT) {
//std::unique_ptr<D2TMMoveUnitStruct> s(static_cast<D2TMMoveUnitStruct*>(event->user.data1));
//Point p = map_camera->toWorldCoordinates(s->screen_position);
//for (auto& unit : units){
//if (unit->is_selected())
//unit->order_move(p);
//}
//}
//}
}
void Game::render() {
screen.clear();
screen.draw(*map);
for (const auto& unit : units)
screen.draw(*unit);
map->drawShrouded(screen, sf::RenderStates::Default);
screen.draw(box);
screen.draw(fpsCounter);
screen.draw(mouse);
screen.display();
}
void Game::updateState(sf::Time dt) {
actionMap.invokeCallbacks(system, &screen);
static const float cameraSpeed = 1.f;
float vec_x = 0.f, vec_y = 0.f;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) vec_y -= cameraSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) vec_y += cameraSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) vec_x -= cameraSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) vec_x += cameraSpeed;
camera.move(vec_x, vec_y);
screen.setView(camera);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));
mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));
//keyboard.updateState();
//mouse.updateState();
//map_camera->updateState();
for (auto& unit: units){
unit->updateState();
}
fpsCounter.update(dt);
map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));
}
//void Game::deselectAllUnits() {
//for (auto& unit : units)
//unit->unselect();
//}
//bool Game::playerHasUnits(const Player &player) const
//{
//for (const auto& unit : units){
//if (unit->getOwner()==player)
//return true; //unit belonging to player found
//}
//return false;
//}
void Game::selectUnit(Unit &unit)
{
unit.select();
system.connect("leftClick", [this](thor::ActionContext<std::string> context){
units[0]->order_move(screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y)));
});
}
<commit_msg>Q and Close event actions work<commit_after>#include <iostream>
#include <SFML/Graphics.hpp>
#include "game.h"
Game::Game():
playing(true),
screen(),
map(nullptr)
//map_camera(nullptr),
//unitRepository(nullptr)
{
sf::ContextSettings settings;
settings.antialiasingLevel = 8;
screen.create(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close, settings);
screen.setFramerateLimit(IDEAL_FPS);
screen.setMouseCursorVisible(false);
if (!init()){
std::cerr << "Failed to initialized game.";
playing = false;
}
}
int Game::execute() {
sf::Clock clock;
while(playing) {
sf::Event event;
actionMap.clearEvents();
sf::Time dt = clock.restart();
while(screen.pollEvent(event)) {
onEvent(event);
actionMap.pushEvent(event);
}
updateState(dt);
render();
}
return 0;
}
bool Game::init() {
if (!terrain.loadFromFile("graphics/terrain.png")) {
std::cout << "Failed to read graphics/terrain.png data" << std::endl;
return false;
}
sf::Image temp;
if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
return false;
}
temp.createMaskFromColor(sf::Color(255, 0, 255));
shroud_edges.loadFromImage(temp);
map.reset(new Map(terrain, shroud_edges));
map->load("maps/4PL_Mountains.ini");
camera.reset({0,0,800,600});
screen.setView(camera);
//init a trike
sf::Image trikeImage;
trikeImage.loadFromFile("graphics/Unit_Trike.bmp");
trikeImage.createMaskFromColor(sf::Color(0,0,0));
sf::Texture* trikeTexture = new sf::Texture; //yes we are leaking! Player should own this
trikeTexture->loadFromImage(trikeImage);
sf::Image trikeShadowImage;
trikeShadowImage.loadFromFile("graphics/Unit_Trike_s.bmp");
trikeShadowImage.createMaskFromColor(sf::Color(255,0,255));
sf::Texture* trikeShadowTexture = new sf::Texture;
trikeShadowTexture->loadFromImage(trikeShadowImage);
sf::Image selectedImage;
selectedImage.loadFromFile("graphics/selected.bmp");
selectedImage.createMaskFromColor(sf::Color(255, 0, 255));
sf::Texture* selectedTexture = new sf::Texture; //more leaks!
selectedTexture->loadFromImage(selectedImage);
units.emplace_back(new Unit(*trikeTexture, *trikeShadowTexture, *selectedTexture, 256, 256, 0));
//remove shroud here
map->removeShroud(static_cast<sf::Vector2i>(units[0]->getPosition()), 10);
//shroud_edges_shadow = Surface::load("graphics/shroud_edges_shadow.bmp");
//if (shroud_edges_shadow == NULL) {
//cout << "Failed to read graphics/shroud_edges_shadow.bmp data" << endl;
//return false;
//}
//mouse.init(screen);
//map_camera.reset(new MapCamera(0, 0, screen, &map));
//map.load("maps/4PL_Mountains.ini");
//unitRepository.reset(new UnitRepository(&map));
////init two players
//int idCount = 0;
//players.emplace_back(House::Sardaukar, idCount++);
//players.emplace_back(House::Harkonnen, idCount++);
//units.emplace_back(unitRepository->create(UNIT_FRIGATE, House::Sardaukar, 3, 3, 10, SUBCELL_CENTER, players[0]));
//units.emplace_back(unitRepository->create(UNIT_TRIKE, House::Sardaukar, 8, 8, 3, SUBCELL_CENTER, players[0]));
//// soldiers
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_CENTER, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPLEFT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_UPRIGHT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNLEFT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Sardaukar, 14, 14, 3, SUBCELL_DOWNRIGHT, players[0]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_CENTER, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPLEFT, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_UPRIGHT, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNLEFT, players[1]));
//units.emplace_back(unitRepository->create(UNIT_SOLDIER, House::Harkonnen, 18, 8, 3, SUBCELL_DOWNRIGHT, players[1]));
thor::Action leftClick(sf::Mouse::Left, thor::Action::PressOnce);
thor::Action leftHold(sf::Mouse::Left, thor::Action::Hold);
thor::Action eventClosed(sf::Event::Closed);
thor::Action Qclicked(sf::Keyboard::Q, thor::Action::PressOnce);
actionMap["leftClick"] = leftClick;
actionMap["leftHold"] = leftHold;
actionMap["close"] = eventClosed || Qclicked;
system.connect("close", [this](thor::ActionContext<std::string>){playing = false;});
return true;
}
void Game::onEvent(sf::Event event) {
switch (event.type){
case sf::Event::MouseButtonPressed:
switch (event.mouseButton.button){
case sf::Mouse::Left:{
sf::Vector2f toSet = screen.mapPixelToCoords(sf::Vector2i(event.mouseButton.x, event.mouseButton.y));
box.setTopLeft(toSet);
break;
}
default:
break;
}
break;
case sf::Event::MouseButtonReleased:
switch (event.mouseButton.button){
case sf::Mouse::Left:
for (auto& unit : units){
if (box.intersects(unit->getBounds())){
selectUnit(*unit);
mouse.setType(Mouse::Type::Move); //at least one unit selected...
}
}
box.clear();
break;
case sf::Mouse::Right:
//deselect all units
for (auto& unit : units){
unit->unselect();
mouse.setType(Mouse::Type::Default);
}
default:
break;
}
default:
break;
}
//mouse.onEvent(event);
//keyboard.onEvent(event);
//map_camera->onEvent(event);
//if (event->type == SDL_USEREVENT) {
//if (event->user.code == D2TM_SELECT) {
//std::unique_ptr<D2TMSelectStruct> s(static_cast<D2TMSelectStruct*>(event->user.data1));
//Point p = map_camera->toWorldCoordinates(s->screen_position);
//if (mouse.is_pointing()) {
//Unit* selected_unit = NULL;
//for (auto& unit : units){
//if (unit->is_point_within(p)){
//selected_unit = unit.get();
//break;
//}
//}
//if (selected_unit != NULL) {
//deselectAllUnits();
//selected_unit->select();
//mouse.state_order_move();
//}
//}
//} else if (event->user.code == D2TM_DESELECT) {
//mouse.state_pointing();
//deselectAllUnits();
//} else if (event->user.code == D2TM_BOX_SELECT) {
//std::unique_ptr<D2TMBoxSelectStruct> s(static_cast<D2TMBoxSelectStruct*>(event->user.data1));
//Rectangle rectangle = map_camera->toWorldCoordinates(s->rectangle);
//if (mouse.is_pointing()) {
//mouse.state_pointing();
//deselectAllUnits();
//for (auto& unit : units){
//if (unit->is_within(rectangle)){
//unit->select();
//mouse.state_order_move();
//}
//}
//}
//} else if (event->user.code == D2TM_MOVE_UNIT) {
//std::unique_ptr<D2TMMoveUnitStruct> s(static_cast<D2TMMoveUnitStruct*>(event->user.data1));
//Point p = map_camera->toWorldCoordinates(s->screen_position);
//for (auto& unit : units){
//if (unit->is_selected())
//unit->order_move(p);
//}
//}
//}
}
void Game::render() {
screen.clear();
screen.draw(*map);
for (const auto& unit : units)
screen.draw(*unit);
map->drawShrouded(screen, sf::RenderStates::Default);
screen.draw(box);
screen.draw(fpsCounter);
screen.draw(mouse);
screen.display();
}
void Game::updateState(sf::Time dt) {
actionMap.invokeCallbacks(system, &screen);
static const float cameraSpeed = 1.f;
float vec_x = 0.f, vec_y = 0.f;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) vec_y -= cameraSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) vec_y += cameraSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) vec_x -= cameraSpeed;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) vec_x += cameraSpeed;
camera.move(vec_x, vec_y);
screen.setView(camera);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));
mouse.setPosition(screen.mapPixelToCoords(sf::Mouse::getPosition(screen)));
//keyboard.updateState();
//mouse.updateState();
//map_camera->updateState();
for (auto& unit: units){
unit->updateState();
}
fpsCounter.update(dt);
map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));
}
//void Game::deselectAllUnits() {
//for (auto& unit : units)
//unit->unselect();
//}
//bool Game::playerHasUnits(const Player &player) const
//{
//for (const auto& unit : units){
//if (unit->getOwner()==player)
//return true; //unit belonging to player found
//}
//return false;
//}
void Game::selectUnit(Unit &unit)
{
unit.select();
system.connect("leftClick", [this](thor::ActionContext<std::string> context){
units[0]->order_move(screen.mapPixelToCoords(sf::Vector2i(context.event->mouseButton.x, context.event->mouseButton.y)));
});
}
<|endoftext|> |
<commit_before>#ifndef GAME_HPP_INCLUDED
#define GAME_HPP_INCLUDED
#include <SFML/Graphics.hpp>
#include <TGUI/TGUI.hpp>
#include "config.hpp"
#include "eoclient.hpp"
#include "eodata.hpp"
#include <memory>
using std::shared_ptr;
class Game
{
public:
Config config;
EOClient eoclient;
shared_ptr<EMF> emf;
shared_ptr<EIF> eif;
shared_ptr<ENF> enf;
shared_ptr<ESF> esf;
shared_ptr<ECF> ecf;
bool loaded;
Game();
void Load(std::string filename);
void Tick();
void Reset();
};
#endif // GAME_HPP_INCLUDED
<commit_msg>Delete game.hpp<commit_after><|endoftext|> |
<commit_before>#include "mmsapt.h"
#include <boost/foreach.hpp>
#include <boost/format.hpp>
#include <boost/tokenizer.hpp>
#include <boost/shared_ptr.hpp>
#include <algorithm>
#include <iostream>
using namespace Moses;
using namespace bitext;
using namespace std;
using namespace boost;
vector<FactorType> fo(1,FactorType(0));
class SimplePhrase : public Moses::Phrase
{
vector<FactorType> const m_fo; // factor order
public:
SimplePhrase(): m_fo(1,FactorType(0)) {}
void init(string const& s)
{
istringstream buf(s); string w;
while (buf >> w)
{
Word wrd;
this->AddWord().CreateFromString(Input,m_fo,StringPiece(w),false,false);
}
}
};
class TargetPhraseIndexSorter
{
TargetPhraseCollection const& my_tpc;
CompareTargetPhrase cmp;
public:
TargetPhraseIndexSorter(TargetPhraseCollection const& tpc) : my_tpc(tpc) {}
bool operator()(size_t a, size_t b) const
{
return cmp(*my_tpc[a], *my_tpc[b]);
}
};
int main(int argc, char* argv[])
{
Parameter params;
if (!params.LoadParam(argc,argv) || !StaticData::LoadDataStatic(¶ms, argv[0]))
exit(1);
Mmsapt* PT = NULL;
BOOST_FOREACH(PhraseDictionary* pd, PhraseDictionary::GetColl())
if ((PT = dynamic_cast<Mmsapt*>(pd))) break;
vector<string> const& fname = PT->GetFeatureNames();
// vector<FeatureFunction*> const& ffs = FeatureFunction::GetFeatureFunctions();
string line;
while (getline(cin,line))
{
SimplePhrase p; p.init(line);
cout << p << endl;
TargetPhraseCollection const* trg = PT->GetTargetPhraseCollectionLEGACY(p);
if (!trg) continue;
vector<size_t> order(trg->GetSize());
for (size_t i = 0; i < order.size(); ++i) order[i] = i;
sort(order.begin(),order.end(),TargetPhraseIndexSorter(*trg));
size_t k = 0;
// size_t precision =
cout.precision(2);
BOOST_FOREACH(size_t i, order)
{
Phrase const& phr = static_cast<Phrase const&>(*(*trg)[i]);
cout << setw(3) << ++k << " " << phr << endl;
ScoreComponentCollection const& scc = (*trg)[i]->GetScoreBreakdown();
ScoreComponentCollection::IndexPair idx = scc.GetIndexes(PT);
FVector const& scores = scc.GetScoresVector();
cout << " ";
for (size_t k = idx.first; k < idx.second; ++k)
cout << " " << format("%10.10s") % fname[k-idx.first];
cout << endl;
cout << " ";
for (size_t k = idx.first; k < idx.second; ++k)
{
if (fname[k-idx.first].substr(0,3) == "log")
{
if(scores[k] < 0)
cout << " " << format("%10d") % round(exp(-scores[k]));
else
cout << " " << format("%10d") % round(exp(scores[k]));
}
else
cout << " " << format("%10.8f") % exp(scores[k]);
}
cout << endl;
}
PT->Release(trg);
}
exit(0);
}
<commit_msg>Renamed lookup_mmsapt.cc to ptable-lookup.cc.<commit_after><|endoftext|> |
<commit_before>/*!
\file named_condition_variable.cpp
\brief Named condition variable synchronization primitive implementation
\author Ivan Shynkarenka
\date 04.10.2016
\copyright MIT License
*/
#include "threads/named_condition_variable.h"
#include "errors/exceptions.h"
#include "errors/fatal.h"
#include <algorithm>
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include "system/shared_type.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include "system/shared_type.h"
#include <windows.h>
#undef max
#undef min
#endif
namespace CppCommon {
//! @cond INTERNALS
class NamedConditionVariable::Impl
{
public:
Impl(const std::string& name) : _name(name)
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
, _shared(name)
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
, _shared(name)
#endif
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Only the owner should initializate a named condition variable
if (_shared.owner())
{
pthread_mutexattr_t mutex_attribute;
int result = pthread_mutexattr_init(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex attribute for the named condition variable!", result);
result = pthread_mutexattr_setpshared(&mutex_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a mutex process shared attribute for the named condition variable!", result);
result = pthread_mutex_init(&_shared->mutex, &mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex for the named condition variable!", result);
result = pthread_mutexattr_destroy(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a mutex attribute for the named condition variable!", result);
pthread_condattr_t cond_attribute;
result = pthread_condattr_init(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable attribute for the named condition variable!", result);
result = pthread_condattr_setpshared(&cond_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a conditional variable process shared attribute for the named condition variable!", result);
result = pthread_cond_init(&_shared->cond, &cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable for the named condition variable!", result);
result = pthread_condattr_destroy(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a conditional variable attribute for the named condition variable!", result);
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Owner of the condition variable should initialize its value
if (_shared.owner())
*_shared = 0;
_mutex = CreateMutexA(nullptr, FALSE, (name + "-mutex").c_str());
if (_mutex == nullptr)
throwex SystemException("Failed to create or open a named mutex for the named condition variable!");
_semaphore = CreateSemaphoreA(nullptr, 0, std::numeric_limits<LONG>::max(), (name + "-semaphore").c_str());
if (_semaphore == nullptr)
throwex SystemException("Failed to create or open a named semaphore for the named condition variable!");
#endif
}
~Impl()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Only the owner should destroy a named condition variable
if (_shared.owner())
{
int result = pthread_mutex_destroy(&_shared->mutex);
if (result != 0)
fatality(SystemException("Failed to destroy a mutex for the named condition variable!", result));
result = pthread_cond_destroy(&_shared->cond);
if (result != 0)
fatality(SystemException("Failed to destroy a conditional variable for the named condition variable!", result));
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
if (!CloseHandle(_mutex))
fatality(SystemException("Failed to close a named mutex for the named condition variable!"));
if (!CloseHandle(_semaphore))
fatality(SystemException("Failed to close a named semaphore for the named condition variable!"));
#endif
}
const std::string& name() const
{
return _name;
}
void NotifyOne()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_signal(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to signal a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Decrement shared waiters count
--(*_shared);
// Signal one waiter
if (!ReleaseSemaphore(_semaphore, 1, nullptr))
throwex SystemException("Failed to release one semaphore waiter for the named condition variable!");
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void NotifyAll()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_broadcast(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to broadcast a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Signal all waiters
if (!ReleaseSemaphore(_semaphore, *_shared, nullptr))
throwex SystemException("Failed to release all semaphore waiters for the named condition variable!");
// Clear all shared waiters
*_shared = 0;
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void Wait()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_wait(&_shared->cond, &_shared->mutex);
if (result != 0)
throwex SystemException("Failed to waiting a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to wait a named condition variable!");
#endif
}
bool TryWaitFor(const Timespan& timespan)
{
if (timespan < 0)
return false;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
struct timespec timeout;
timeout.tv_sec = timespan.seconds();
timeout.tv_nsec = timespan.nanoseconds() % 1000000000;
int result = pthread_cond_timedwait(&_shared->cond, &_shared->mutex, &timeout);
if ((result != 0) && (result != ETIMEDOUT))
throwex SystemException("Failed to waiting a named condition variable for the given timeout!", result);
return (result == 0);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, (DWORD)std::max(0ll, timespan.milliseconds()));
if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT))
throwex SystemException("Failed to try lock a named condition variable for the given timeout!");
return (result == WAIT_OBJECT_0);
#endif
}
private:
std::string _name;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Shared condition variable structure
struct CondVar
{
pthread_mutex_t mutex;
pthread_cond_t cond;
};
// Shared condition variable structure wrapper
SharedType<CondVar> _shared;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
HANDLE _mutex;
HANDLE _semaphore;
SharedType<LONG> _shared;
#endif
};
//! @endcond
NamedConditionVariable::NamedConditionVariable(const std::string& name) : _pimpl(std::make_unique<Impl>(name))
{
}
NamedConditionVariable::NamedConditionVariable(NamedConditionVariable&& cv) noexcept : _pimpl(std::move(cv._pimpl))
{
}
NamedConditionVariable::~NamedConditionVariable()
{
}
NamedConditionVariable& NamedConditionVariable::operator=(NamedConditionVariable&& cv) noexcept
{
_pimpl = std::move(cv._pimpl);
return *this;
}
const std::string& NamedConditionVariable::name() const
{
return _pimpl->name();
}
void NamedConditionVariable::NotifyOne()
{
_pimpl->NotifyOne();
}
void NamedConditionVariable::NotifyAll()
{
_pimpl->NotifyAll();
}
void NamedConditionVariable::Wait()
{
_pimpl->Wait();
}
bool NamedConditionVariable::TryWaitFor(const Timespan& timespan)
{
return _pimpl->TryWaitFor(timespan);
}
} // namespace CppCommon
<commit_msg>Fix Cygwin build<commit_after>/*!
\file named_condition_variable.cpp
\brief Named condition variable synchronization primitive implementation
\author Ivan Shynkarenka
\date 04.10.2016
\copyright MIT License
*/
#include "threads/named_condition_variable.h"
#include "errors/exceptions.h"
#include "errors/fatal.h"
#include <algorithm>
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
#include "system/shared_type.h"
#include <pthread.h>
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
#include "system/shared_type.h"
#include <windows.h>
#undef max
#undef min
#endif
namespace CppCommon {
//! @cond INTERNALS
class NamedConditionVariable::Impl
{
public:
Impl(const std::string& name) : _name(name)
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
, _shared(name)
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
, _shared(name)
#endif
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Only the owner should initializate a named condition variable
if (_shared.owner())
{
pthread_mutexattr_t mutex_attribute;
int result = pthread_mutexattr_init(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex attribute for the named condition variable!", result);
result = pthread_mutexattr_setpshared(&mutex_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a mutex process shared attribute for the named condition variable!", result);
result = pthread_mutex_init(&_shared->mutex, &mutex_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a mutex for the named condition variable!", result);
result = pthread_mutexattr_destroy(&mutex_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a mutex attribute for the named condition variable!", result);
pthread_condattr_t cond_attribute;
result = pthread_condattr_init(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable attribute for the named condition variable!", result);
result = pthread_condattr_setpshared(&cond_attribute, PTHREAD_PROCESS_SHARED);
if (result != 0)
throwex SystemException("Failed to set a conditional variable process shared attribute for the named condition variable!", result);
result = pthread_cond_init(&_shared->cond, &cond_attribute);
if (result != 0)
throwex SystemException("Failed to initialize a conditional variable for the named condition variable!", result);
result = pthread_condattr_destroy(&cond_attribute);
if (result != 0)
throwex SystemException("Failed to destroy a conditional variable attribute for the named condition variable!", result);
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Owner of the condition variable should initialize its value
if (_shared.owner())
*_shared = 0;
_mutex = CreateMutexA(nullptr, FALSE, (name + "-mutex").c_str());
if (_mutex == nullptr)
throwex SystemException("Failed to create or open a named mutex for the named condition variable!");
_semaphore = CreateSemaphoreA(nullptr, 0, std::numeric_limits<LONG>::max(), (name + "-semaphore").c_str());
if (_semaphore == nullptr)
throwex SystemException("Failed to create or open a named semaphore for the named condition variable!");
#endif
}
~Impl()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Only the owner should destroy a named condition variable
if (_shared.owner())
{
int result = pthread_mutex_destroy(&_shared->mutex);
if (result != 0)
fatality(SystemException("Failed to destroy a mutex for the named condition variable!", result));
result = pthread_cond_destroy(&_shared->cond);
if (result != 0)
fatality(SystemException("Failed to destroy a conditional variable for the named condition variable!", result));
}
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
if (!CloseHandle(_mutex))
fatality(SystemException("Failed to close a named mutex for the named condition variable!"));
if (!CloseHandle(_semaphore))
fatality(SystemException("Failed to close a named semaphore for the named condition variable!"));
#endif
}
const std::string& name() const
{
return _name;
}
void NotifyOne()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_signal(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to signal a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Decrement shared waiters count
--(*_shared);
// Signal one waiter
if (!ReleaseSemaphore(_semaphore, 1, nullptr))
throwex SystemException("Failed to release one semaphore waiter for the named condition variable!");
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void NotifyAll()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_broadcast(&_shared->cond);
if (result != 0)
throwex SystemException("Failed to broadcast a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Signal all waiters
if (!ReleaseSemaphore(_semaphore, *_shared, nullptr))
throwex SystemException("Failed to release all semaphore waiters for the named condition variable!");
// Clear all shared waiters
*_shared = 0;
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
#endif
}
void Wait()
{
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
int result = pthread_cond_wait(&_shared->cond, &_shared->mutex);
if (result != 0)
throwex SystemException("Failed to waiting a named condition variable!", result);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to wait a named condition variable!");
#endif
}
bool TryWaitFor(const Timespan& timespan)
{
if (timespan < 0)
return false;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
struct timespec timeout;
timeout.tv_sec = timespan.seconds();
timeout.tv_nsec = timespan.nanoseconds() % 1000000000;
int result = pthread_cond_timedwait(&_shared->cond, &_shared->mutex, &timeout);
if ((result != 0) && (result != ETIMEDOUT))
throwex SystemException("Failed to waiting a named condition variable for the given timeout!", result);
return (result == 0);
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
// Lock the named mutex
DWORD result = WaitForSingleObject(_mutex, INFINITE);
if (result != WAIT_OBJECT_0)
throwex SystemException("Failed to lock a named mutex for the named condition variable!");
// Increment shared waiters count
++(*_shared);
// Unlock the named mutex
if (!ReleaseMutex(_mutex))
throwex SystemException("Failed to unlock a named mutex for the named condition variable!");
// Wait for the named condition variable
result = WaitForSingleObject(_semaphore, (DWORD)std::max(0, timespan.milliseconds()));
if ((result != WAIT_OBJECT_0) && (result != WAIT_TIMEOUT))
throwex SystemException("Failed to try lock a named condition variable for the given timeout!");
return (result == WAIT_OBJECT_0);
#endif
}
private:
std::string _name;
#if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__)
// Shared condition variable structure
struct CondVar
{
pthread_mutex_t mutex;
pthread_cond_t cond;
};
// Shared condition variable structure wrapper
SharedType<CondVar> _shared;
#elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
HANDLE _mutex;
HANDLE _semaphore;
SharedType<LONG> _shared;
#endif
};
//! @endcond
NamedConditionVariable::NamedConditionVariable(const std::string& name) : _pimpl(std::make_unique<Impl>(name))
{
}
NamedConditionVariable::NamedConditionVariable(NamedConditionVariable&& cv) noexcept : _pimpl(std::move(cv._pimpl))
{
}
NamedConditionVariable::~NamedConditionVariable()
{
}
NamedConditionVariable& NamedConditionVariable::operator=(NamedConditionVariable&& cv) noexcept
{
_pimpl = std::move(cv._pimpl);
return *this;
}
const std::string& NamedConditionVariable::name() const
{
return _pimpl->name();
}
void NamedConditionVariable::NotifyOne()
{
_pimpl->NotifyOne();
}
void NamedConditionVariable::NotifyAll()
{
_pimpl->NotifyAll();
}
void NamedConditionVariable::Wait()
{
_pimpl->Wait();
}
bool NamedConditionVariable::TryWaitFor(const Timespan& timespan)
{
return _pimpl->TryWaitFor(timespan);
}
} // namespace CppCommon
<|endoftext|> |
<commit_before>#include "functions.hpp"
///data base
#include <Socket/client/Client.hpp>
#define SERVER_HOST 1
#define SERVER_PORT 2
int main(int argc,char* argv[])
{
if(argc < SERVER_PORT+1)
{
std::cout<<"Usage are: "<<argv[0]<<" <server-host> <server-port>"<<std::endl;
return 1;
}
ntw::Socket::init();
ntw::cli::Client client;
if(client.connect(argv[SERVER_HOST],atoi(argv[SERVER_PORT])) != NTW_ERROR_CONNEXION)
{
test::sendNewFile(client);
}
ntw::cli::Client client2;
if(client2.connect(argv[SERVER_HOST],atoi(argv[SERVER_PORT])) != NTW_ERROR_CONNEXION)
{
test::sendNewFile(client2);
}
ntw::Socket::close();
return 0;
}
<commit_msg>maj on example<commit_after>#include "functions.hpp"
///data base
#include <Socket/client/Client.hpp>
#define SERVER_HOST 1
#define SERVER_PORT 2
int main(int argc,char* argv[])
{
if(argc < SERVER_PORT+1)
{
std::cout<<"Usage are: "<<argv[0]<<" <server-host> <server-port>"<<std::endl;
return 1;
}
ntw::Socket::init();
ntw::cli::Client client;
if(client.connect(argv[SERVER_HOST],atoi(argv[SERVER_PORT])) != NTW_ERROR_CONNEXION)
{
test::sendNewFile(client);
}
ntw::Socket::close();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP
#define STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP
#include <stan/math/rev/core/vari.hpp>
#include <stan/math/rev/core/chainable_alloc.hpp>
#include <stan/math/rev/core/chainablestack.hpp>
namespace stan {
namespace math {
/**
* Reset all adjoint values in the top nested portion of the stack
* to zero.
*/
static void set_zero_all_adjoints_nested() {
if (empty_nested())
throw std::logic_error("empty_nested() must be false before calling"
" set_zero_all_adjoints_nested()");
size_t start1 = ChainableStack::nested_var_stack_sizes_.back();
for (size_t i = start1 - 1; i < ChainableStack::var_stack_.size(); ++i)
ChainableStack::var_stack_[i]->set_zero_adjoint();
size_t start2 = ChainableStack::nested_var_nochain_stack_sizes_.back();
for (size_t i = start2 - 1;
i < ChainableStack::var_nochain_stack_.size(); ++i)
ChainableStack::var_nochain_stack_[i]->set_zero_adjoint();
}
}
}
#endif
<commit_msg>Added missing include<commit_after>#ifndef STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP
#define STAN_MATH_REV_CORE_SET_ZERO_ALL_ADJOINTS_NESTED_HPP
#include <stan/math/rev/core/vari.hpp>
#include <stan/math/rev/core/chainable_alloc.hpp>
#include <stan/math/rev/core/chainablestack.hpp>
#include <stan/math/rev/core/empty_nested.hpp>
namespace stan {
namespace math {
/**
* Reset all adjoint values in the top nested portion of the stack
* to zero.
*/
static void set_zero_all_adjoints_nested() {
if (empty_nested())
throw std::logic_error("empty_nested() must be false before calling"
" set_zero_all_adjoints_nested()");
size_t start1 = ChainableStack::nested_var_stack_sizes_.back();
for (size_t i = start1 - 1; i < ChainableStack::var_stack_.size(); ++i)
ChainableStack::var_stack_[i]->set_zero_adjoint();
size_t start2 = ChainableStack::nested_var_nochain_stack_sizes_.back();
for (size_t i = start2 - 1;
i < ChainableStack::var_nochain_stack_.size(); ++i)
ChainableStack::var_nochain_stack_[i]->set_zero_adjoint();
}
}
}
#endif
<|endoftext|> |
<commit_before>// $Header$
void alieve_init(const Text_t* path=".", Int_t event=0,
Bool_t use_runloader=kTRUE, Bool_t use_esd=kTRUE,
Bool_t avoid_exceptions_on_open=kTRUE)
{
// Set-up environment, load libraries.
Reve::SetupEnvironment();
// alieve executable linked against ALICE nad EVE shared libraries.
// Reve::AssertMacro("alieve_loadlibs.C");
// Put macros in the list of browsables, spawn a browser.
TString macdir("$(REVESYS)/alice-macros");
gSystem->ExpandPathName(macdir);
TFolder* f = gReve->GetMacroFolder();
void* dirhandle = gSystem->OpenDirectory(macdir.Data());
if(dirhandle != 0) {
char* filename;
TPRegexp re("\.C$");
while((filename = gSystem->GetDirEntry(dirhandle)) != 0) {
if(re.Match(filename)) {
printf("Adding macro '%s'\n", filename);
//PH The line below is replaced waiting for a fix in Root
//PH which permits to use variable siza arguments in CINT
//PH on some platforms (alphalinuxgcc, solariscc5, etc.)
// f->Add(new Reve::RMacro(Form("%s/%s", macdir.Data(), filename)));
char fullName[1000];
sprintf(fullName,"%s/%s", macdir.Data(), filename);
f->Add(new Reve::RMacro(fullName));
}
}
}
gSystem->FreeDirectory(dirhandle);
gROOT->GetListOfBrowsables()->Add
// (new TSystemDirectory("alice-macros", macdir.Data())); // !!!! this spits blood, but then works
(new TSystemDirectory(macdir.Data(), macdir.Data()));
new TBrowser;
Reve::AssertMacro("region_marker.C");
// Open event
if(path != 0) {
Alieve::Event::Initialize(use_runloader, use_esd, avoid_exceptions_on_open);
printf("Opening event %d from '%s' ...", event, path); fflush(stdout);
Alieve::gEvent = new Alieve::Event(path, event);
printf(" done.\n");
gReve->AddEvent(Alieve::gEvent);
}
}
<commit_msg>Allow override of CDB storage.<commit_after>// $Header$
void alieve_init(const Text_t* path = ".", Int_t event=0,
const Text_t* cdburi = 0,
Bool_t use_runloader=kTRUE, Bool_t use_esd=kTRUE,
Bool_t avoid_exceptions_on_open=kTRUE)
{
// Set-up environment, load libraries.
Reve::SetupEnvironment();
// alieve executable linked against ALICE nad EVE shared libraries.
// Reve::AssertMacro("alieve_loadlibs.C");
// Put macros in the list of browsables, spawn a browser.
TString macdir("$(REVESYS)/alice-macros");
gSystem->ExpandPathName(macdir);
TFolder* f = gReve->GetMacroFolder();
void* dirhandle = gSystem->OpenDirectory(macdir.Data());
if(dirhandle != 0) {
char* filename;
TPRegexp re("\.C$");
while((filename = gSystem->GetDirEntry(dirhandle)) != 0) {
if(re.Match(filename)) {
printf("Adding macro '%s'\n", filename);
//PH The line below is replaced waiting for a fix in Root
//PH which permits to use variable siza arguments in CINT
//PH on some platforms (alphalinuxgcc, solariscc5, etc.)
// f->Add(new Reve::RMacro(Form("%s/%s", macdir.Data(), filename)));
char fullName[1000];
sprintf(fullName,"%s/%s", macdir.Data(), filename);
f->Add(new Reve::RMacro(fullName));
}
}
}
gSystem->FreeDirectory(dirhandle);
gROOT->GetListOfBrowsables()->Add
// (new TSystemDirectory("alice-macros", macdir.Data())); // !!!! this spits blood, but then works
(new TSystemDirectory(macdir.Data(), macdir.Data()));
new TBrowser;
Reve::AssertMacro("region_marker.C");
// Open event
if(path != 0) {
Alieve::Event::Initialize(use_runloader, use_esd, avoid_exceptions_on_open);
Alieve::Event::SetCdbUri(cdburi);
printf("Opening event %d from '%s' ...", event, path); fflush(stdout);
Alieve::gEvent = new Alieve::Event(path, event);
printf(" done.\n");
gReve->AddEvent(Alieve::gEvent);
}
}
<|endoftext|> |
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_WORLD_CONSTANTS_HPP__
#define LASERCAKE_WORLD_CONSTANTS_HPP__
#include "utils.hpp"
#include "units.hpp"
// fine_distance_units: Fine as opposed to coarse, that is.
// time_units: Choose a number that makes lots of frames-per-second values multiply in evenly.
// TODO if we use this more and want a different representation, that would be fine too.
// TODO where it doesn't already, code should refer to some kind of time unit more,
// rather than implicitly relying on frames being a fixed duration.
typedef units<dim::ratio<10>, dim::meter<1>> tile_widths_t;
typedef units<dim::ratio< 2>, dim::meter<1>> tile_heights_t;
typedef units<dim::ratio< 1, 200>, dim::meter<1>> fine_distance_units_t;
typedef typename units_prod<fine_distance_units_t, dim::ratio<1, 30>>::type tile_physics_sub_tile_units_t;
typedef units<dim::ratio<1, (2*2*2*2 * 3*3*3 * 5*5 * 7 * 11)>, dim::second<1>> time_units_t;
typedef typename units_prod<fine_distance_units_t, hertz_t>::type velocity_units_t;
typedef typename units_prod<milli_t, grams_t, units_pow<meters_t, (-3)>>::type density_units_t;
typedef pascals_t pressure_units_t;
// This is a stupid unit but it exists currently:
typedef typename units_prod<time_units_t, dim::ratio<30>>::type fixed_frame_lengths_t;
//typedef typename units_prod<kilograms_t, fine_distance_units_t::pow<(-3)>>::type density_units_t;
//constexpr auto velocity_units = fine_units / /* units_factor<30>() / ? */ seconds;
//constexpr auto tile_physics_sub_tile_units = fine_units / units_factor<30>();
constexpr auto tile_widths = tile_widths_t();
constexpr auto tile_heights = tile_heights_t();
constexpr auto fine_distance_units = fine_distance_units_t();
constexpr auto tile_physics_sub_tile_units = tile_physics_sub_tile_units_t();
constexpr auto time_units = time_units_t();
constexpr auto velocity_units = velocity_units_t();
constexpr auto density_units = density_units_t();
constexpr auto pressure_units = pressure_units_t();
constexpr auto fixed_frame_lengths = fixed_frame_lengths_t();
// Rationale for the 64 bit types:
// A lot of computations in Lasercake require more than 32 bits.
//
// Rationale for the 32 bit types:
// We can fit it within 32 bits, so we might as well have faster math
// (on 32bit, and possibly 64bit platform multiply/divides) and smaller storage.
typedef physical_quantity<int64_t, fine_distance_units_t> distance;
typedef physical_quantity<int32_t, tile_physics_sub_tile_units_t> sub_tile_distance;
typedef physical_quantity<int64_t, tile_physics_sub_tile_units_t> large_sub_tile_distance;
typedef physical_quantity<int64_t, time_units_t> time_unit;
typedef distance fine_scalar; // TODO replace fine_scalar->distance.
typedef fine_distance_units_t fine_units_t; // TODO
constexpr auto fine_units = fine_units_t(); // TODO
//ok...
const fine_scalar tile_width = 1 * tile_widths * identity(fine_units / tile_widths);
const fine_scalar tile_height = 1 * tile_heights * identity(fine_units / tile_heights);
const vector3<fine_scalar> tile_size(tile_width, tile_width, tile_height);
#if 0
const time_unit time_units_per_second = 2*2*2*2 * 3*3*3 * 5*5 * 7 * 11;
// delete these if we make frames variable length:
const time_unit fixed_frames_per_second = 30;
const time_unit time_units_per_fixed_frame = time_units_per_second / fixed_frames_per_second;
const fine_scalar tile_width = 2000;
const fine_scalar tile_height = 400;
const vector3<fine_scalar> tile_size(tile_width, tile_width, tile_height);
// Velocity is currently in units of (fine_unit / second). We might change this.
const fine_scalar velocity_scale_factor = fixed_frames_per_second;
const sub_tile_distance min_convincing_speed = velocity_scale_factor * tile_width / 50;
const sub_tile_distance gravity_acceleration_magnitude = velocity_scale_factor * tile_width / 200;
const vector3<sub_tile_distance> gravity_acceleration(0, 0, -gravity_acceleration_magnitude); // in mini-units per frame squared
const sub_tile_distance friction_amount = velocity_scale_factor * tile_width / 1800;
// TODO: Get some of these constants out of the header that everyone includes
const sub_tile_distance pressure_per_depth_in_tile_heights = gravity_acceleration_magnitude * tile_height * velocity_scale_factor;
// I believe this value makes it so that the terminal velocity of falling fluid is "half a vertical tile per frame".
const sub_tile_distance air_resistance_constant = tile_height * tile_height * velocity_scale_factor * velocity_scale_factor / gravity_acceleration_magnitude / 2;
const sub_tile_distance idle_progress_reduction_rate = 20 * velocity_scale_factor;
const vector3<sub_tile_distance> inactive_fluid_velocity(0, 0, -min_convincing_speed);
const fine_scalar max_object_speed_through_water = tile_width * velocity_scale_factor / 16;
#endif
#endif
<commit_msg>created acceleration units type; simplified things<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Lasercake 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 Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LASERCAKE_WORLD_CONSTANTS_HPP__
#define LASERCAKE_WORLD_CONSTANTS_HPP__
#include "utils.hpp"
#include "units.hpp"
// fine_distance_units: Fine as opposed to coarse, that is.
// time_units: Choose a number that makes lots of frames-per-second values multiply in evenly.
// TODO if we use this more and want a different representation, that would be fine too.
// TODO where it doesn't already, code should refer to some kind of time unit more,
// rather than implicitly relying on frames being a fixed duration.
typedef units<dim::ratio<10>, dim::meter<1>> tile_widths_t;
typedef units<dim::ratio< 2>, dim::meter<1>> tile_heights_t;
typedef units<dim::ratio< 1, 200>, dim::meter<1>> fine_distance_units_t;
typedef typename units_prod<fine_distance_units_t, dim::ratio<1, 30>>::type tile_physics_sub_tile_units_t;
typedef units<dim::ratio<1, (2*2*2*2 * 3*3*3 * 5*5 * 7 * 11)>, dim::second<1>> time_units_t;
typedef typename units_prod<fine_distance_units_t, dim::second<(-1)>>::type velocity_units_t;
typedef typename units_prod<fine_distance_units_t, dim::second<(-2)>>::type acceleration_units_t;
typedef typename units_prod<milli_t, grams_t, dim::meter<(-3)>>::type density_units_t;
typedef pascals_t pressure_units_t;
// This is a stupid unit but it exists currently:
typedef typename units_prod<time_units_t, dim::ratio<30>>::type fixed_frame_lengths_t;
//typedef typename units_prod<kilograms_t, fine_distance_units_t::pow<(-3)>>::type density_units_t;
//constexpr auto velocity_units = fine_units / /* units_factor<30>() / ? */ seconds;
//constexpr auto tile_physics_sub_tile_units = fine_units / units_factor<30>();
constexpr auto tile_widths = tile_widths_t();
constexpr auto tile_heights = tile_heights_t();
constexpr auto fine_distance_units = fine_distance_units_t();
constexpr auto tile_physics_sub_tile_units = tile_physics_sub_tile_units_t();
constexpr auto time_units = time_units_t();
constexpr auto velocity_units = velocity_units_t();
constexpr auto acceleration_units = acceleration_units_t();
constexpr auto density_units = density_units_t();
constexpr auto pressure_units = pressure_units_t();
constexpr auto fixed_frame_lengths = fixed_frame_lengths_t();
// Rationale for the 64 bit types:
// A lot of computations in Lasercake require more than 32 bits.
//
// Rationale for the 32 bit types:
// We can fit it within 32 bits, so we might as well have faster math
// (on 32bit, and possibly 64bit platform multiply/divides) and smaller storage.
typedef physical_quantity<int64_t, fine_distance_units_t> distance;
typedef physical_quantity<int32_t, tile_physics_sub_tile_units_t> sub_tile_distance;
typedef physical_quantity<int64_t, tile_physics_sub_tile_units_t> large_sub_tile_distance;
typedef physical_quantity<int64_t, time_units_t> time_unit;
typedef distance fine_scalar; // TODO replace fine_scalar->distance.
typedef fine_distance_units_t fine_units_t; // TODO
constexpr auto fine_units = fine_units_t(); // TODO
//ok...
const fine_scalar tile_width = 1 * tile_widths * identity(fine_units / tile_widths);
const fine_scalar tile_height = 1 * tile_heights * identity(fine_units / tile_heights);
const vector3<fine_scalar> tile_size(tile_width, tile_width, tile_height);
#if 0
const time_unit time_units_per_second = 2*2*2*2 * 3*3*3 * 5*5 * 7 * 11;
// delete these if we make frames variable length:
const time_unit fixed_frames_per_second = 30;
const time_unit time_units_per_fixed_frame = time_units_per_second / fixed_frames_per_second;
const fine_scalar tile_width = 2000;
const fine_scalar tile_height = 400;
const vector3<fine_scalar> tile_size(tile_width, tile_width, tile_height);
// Velocity is currently in units of (fine_unit / second). We might change this.
const fine_scalar velocity_scale_factor = fixed_frames_per_second;
const sub_tile_distance min_convincing_speed = velocity_scale_factor * tile_width / 50;
const sub_tile_distance gravity_acceleration_magnitude = velocity_scale_factor * tile_width / 200;
const vector3<sub_tile_distance> gravity_acceleration(0, 0, -gravity_acceleration_magnitude); // in mini-units per frame squared
const sub_tile_distance friction_amount = velocity_scale_factor * tile_width / 1800;
// TODO: Get some of these constants out of the header that everyone includes
const sub_tile_distance pressure_per_depth_in_tile_heights = gravity_acceleration_magnitude * tile_height * velocity_scale_factor;
// I believe this value makes it so that the terminal velocity of falling fluid is "half a vertical tile per frame".
const sub_tile_distance air_resistance_constant = tile_height * tile_height * velocity_scale_factor * velocity_scale_factor / gravity_acceleration_magnitude / 2;
const sub_tile_distance idle_progress_reduction_rate = 20 * velocity_scale_factor;
const vector3<sub_tile_distance> inactive_fluid_velocity(0, 0, -min_convincing_speed);
const fine_scalar max_object_speed_through_water = tile_width * velocity_scale_factor / 16;
#endif
#endif
<|endoftext|> |
<commit_before>/**
* @file collision_check.cpp
* @brief This defines a cost function for collision checking.
*
* @author Jorge Nicho
* @date March 30, 2016
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 <ros/console.h>
#include <pluginlib/class_list_macros.h>
#include <moveit/robot_state/conversions.h>
#include "stomp_moveit/cost_functions/collision_check.h"
PLUGINLIB_EXPORT_CLASS(stomp_moveit::cost_functions::CollisionCheck,stomp_moveit::cost_functions::StompCostFunction)
static const int MIN_KERNEL_WINDOW_SIZE = 3;
/**
* @brief Convenience method that propagates the cost value at center to the window to the adjacent points.
* @param window_size Size of the kernel, must be less than the size of the 'data' array.
* @param data The original data vector
* @param smoothed The smoothed data after applying the kernel.
*/
static void applyKernelSmoothing(std::size_t window_size, const Eigen::VectorXd& data, Eigen::VectorXd& smoothed)
{
using namespace Eigen;
// allocation
window_size = 2*(window_size/2) + 1;// forcing it into an odd number
smoothed.setZero(data.size());
VectorXd x_nneighbors = VectorXd::Zero(window_size);
VectorXd y_nneighbors = VectorXd::Zero(window_size);
VectorXd kernel_weights = VectorXd::Zero(window_size);
// indexing
int index_left, index_right;
std::size_t window_index_middle = window_size/2;
// kernel function
//Epanechnikov(x,neighbors,lambda)
auto epanechnikov_function = [](double x_m,const VectorXd& neighbors,double lambda, VectorXd& weights )
{
double t = 0;
for(int i = 0; i < neighbors.size(); i++)
{
t = std::abs(x_m - neighbors(i))/lambda;
if(t < 1)
{
weights(i) = 0.75f*(1 - std::pow(t,2));
}
else
{
weights(i) = 0;
}
}
};
for(int i = 0; i < data.size(); i++)
{
// middle term
x_nneighbors(window_index_middle) = i;
y_nneighbors(window_index_middle) = data(i);
// grabbing neighbors
for(int j = 1; j <= window_size/2; j++)
{
index_left = i - j;
index_right = i + j;
if(index_left < 0)
{
x_nneighbors(window_index_middle - j) = 0;
y_nneighbors(window_index_middle - j) = data(0);
}
else
{
x_nneighbors(window_index_middle - j) = index_left;
y_nneighbors(window_index_middle - j) = data(index_left);
}
if(index_right > data.rows()-1)
{
x_nneighbors(window_index_middle + j) = data.rows()-1;
y_nneighbors(window_index_middle + j) = data(data.rows() - 1);
}
else
{
x_nneighbors(window_index_middle + j) = index_right;
y_nneighbors(window_index_middle + j) = data(index_right);
}
}
epanechnikov_function(i,x_nneighbors,window_size,kernel_weights);
smoothed(i) = (y_nneighbors.array()*kernel_weights.array()).sum()/kernel_weights.sum();
}
}
namespace stomp_moveit
{
namespace cost_functions
{
CollisionCheck::CollisionCheck():
name_("CollisionCheckPlugin"),
robot_state_(),
collision_penalty_(0.0)
{
// TODO Auto-generated constructor stub
}
CollisionCheck::~CollisionCheck()
{
// TODO Auto-generated destructor stub
}
bool CollisionCheck::initialize(moveit::core::RobotModelConstPtr robot_model_ptr,
const std::string& group_name,XmlRpc::XmlRpcValue& config)
{
robot_model_ptr_ = robot_model_ptr;
group_name_ = group_name;
return configure(config);
}
bool CollisionCheck::setMotionPlanRequest(const planning_scene::PlanningSceneConstPtr& planning_scene,
const moveit_msgs::MotionPlanRequest &req,
const stomp_core::StompConfiguration &config,
moveit_msgs::MoveItErrorCodes& error_code)
{
using namespace moveit::core;
planning_scene_ = planning_scene;
plan_request_ = req;
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
// initialize collision request
collision_request_.group_name = group_name_;
collision_request_.cost = false;
collision_request_.distance = false;
collision_request_.max_contacts = 1;
collision_request_.max_contacts_per_pair = 1;
collision_request_.contacts = true;
collision_request_.verbose = false;
collision_robot_ = planning_scene->getCollisionRobot();
collision_world_ = planning_scene->getCollisionWorld();
// storing robot state
robot_state_.reset(new RobotState(robot_model_ptr_));
if(!robotStateMsgToRobotState(req.start_state,*robot_state_,true))
{
ROS_ERROR("%s Failed to get current robot state from request",getName().c_str());
return false;
}
// copying into intermediate robot states
for(auto& rs : intermediate_coll_states_)
{
rs.reset(new RobotState(*robot_state_));
}
// allocating arrays
raw_costs_ = Eigen::VectorXd::Zero(config.num_timesteps);
return true;
}
bool CollisionCheck::computeCosts(const Eigen::MatrixXd& parameters,
std::size_t start_timestep,
std::size_t num_timesteps,
int iteration_number,
int rollout_number,
Eigen::VectorXd& costs,
bool& validity)
{
using namespace moveit::core;
using namespace Eigen;
if(!robot_state_)
{
ROS_ERROR("%s Robot State has not been updated",getName().c_str());
return false;
}
typedef collision_detection::CollisionResult::ContactMap ContactMap;
typedef ContactMap::iterator ContactMapIterator;
typedef std::vector<collision_detection::Contact> ContactArray;
// initializing result array
costs = Eigen::VectorXd::Zero(num_timesteps);
// resetting array
raw_costs_.setZero();
// collision
collision_detection::CollisionRequest request = collision_request_;
collision_detection::CollisionResult result_world_collision, result_robot_collision;
std::vector<collision_detection::CollisionResult> results(2);
validity = true;
// planning groups
const JointModelGroup* joint_group = robot_model_ptr_->getJointModelGroup(group_name_);
if(parameters.cols()< (start_timestep + num_timesteps))
{
ROS_ERROR_STREAM("Size in the 'parameters' matrix is less than required");
return false;
}
// check for collisions at each state
bool skip_next_check = false;
for (auto t=start_timestep; t<start_timestep + num_timesteps; ++t)
{
if(!skip_next_check)
{
robot_state_->setJointGroupPositions(joint_group,parameters.col(t));
robot_state_->update();
// checking robot vs world (attached objects, octomap, not in urdf) collisions
result_world_collision.distance = std::numeric_limits<double>::max();
collision_world_->checkRobotCollision(request,
result_world_collision,
*collision_robot_,
*robot_state_,
planning_scene_->getAllowedCollisionMatrix());
collision_robot_->checkSelfCollision(request,
result_robot_collision,
*robot_state_,
planning_scene_->getAllowedCollisionMatrix());
results[0]= result_world_collision;
results[1] = result_robot_collision;
for(std::vector<collision_detection::CollisionResult>::iterator i = results.begin(); i != results.end(); i++)
{
collision_detection::CollisionResult& result = *i;
if(result.collision)
{
raw_costs_(t) = collision_penalty_;
validity = false;
break;
}
}
}
// check intermediate poses to the next position (skip the last one)
if(t < start_timestep + num_timesteps - 1)
{
if(!checkIntermediateCollisions(parameters.col(t),parameters.col(t+1),longest_valid_joint_move_))
{
raw_costs_(t) = 1.0;
raw_costs_(t+1) = 1.0;
validity = false;
skip_next_check = true;
}
else
{
skip_next_check = false;
}
}
}
// applying kernel smoothing
if(!validity)
{
if(kernel_window_percentage_> 1e-6)
{
int window_size = num_timesteps*kernel_window_percentage_;
window_size = window_size < MIN_KERNEL_WINDOW_SIZE ? MIN_KERNEL_WINDOW_SIZE : window_size;
// adding minimum cost
intermediate_costs_slots_ = (raw_costs_.array() < collision_penalty_).cast<double>();
raw_costs_ += (raw_costs_.sum()/raw_costs_.size())*(intermediate_costs_slots_.matrix());
// smoothing
applyKernelSmoothing(window_size,raw_costs_,costs);
}
else
{
costs = raw_costs_;
}
}
return true;
}
bool CollisionCheck::checkIntermediateCollisions(const Eigen::VectorXd& start,
const Eigen::VectorXd& end,double longest_valid_joint_move)
{
Eigen::VectorXd diff = end - start;
int num_intermediate = std::ceil(((diff.cwiseAbs())/longest_valid_joint_move).maxCoeff()) - 1;
if(num_intermediate < 1.0)
{
// no interpolation needed
return true;
}
// grabbing states
auto& start_state = intermediate_coll_states_[0];
auto& mid_state = intermediate_coll_states_[1];
auto& end_state = intermediate_coll_states_[2];
if(!start_state || !mid_state || !end_state)
{
ROS_ERROR("%s intermediate states not initialized",getName().c_str());
return false;
}
// setting up collision
auto req = collision_request_;
req.distance = false;
collision_detection::CollisionResult res;
const moveit::core::JointModelGroup* joint_group = robot_model_ptr_->getJointModelGroup(group_name_);
start_state->setJointGroupPositions(joint_group,start);
end_state->setJointGroupPositions(joint_group,end);
// checking intermediate states
double dt = 1.0/static_cast<double>(num_intermediate);
double interval = 0.0;
for(std::size_t i = 1; i < num_intermediate;i++)
{
interval = i*dt;
start_state->interpolate(*end_state,interval,*mid_state) ;
if(planning_scene_->isStateColliding(*mid_state))
{
return false;
}
}
return true;
}
bool CollisionCheck::configure(const XmlRpc::XmlRpcValue& config)
{
// check parameter presence
auto members = {"cost_weight","collision_penalty","kernel_window_percentage"};
for(auto& m : members)
{
if(!config.hasMember(m))
{
ROS_ERROR("%s failed to find one or more required parameters",getName().c_str());
return false;
}
}
try
{
// check parameter presence
auto members = {"cost_weight","collision_penalty","kernel_window_percentage", "longest_valid_joint_move"};
for(auto& m : members)
{
if(!config.hasMember(m))
{
ROS_ERROR("%s failed to find '%s' parameter",getName().c_str(),m);
return false;
}
}
XmlRpc::XmlRpcValue c = config;
cost_weight_ = static_cast<double>(c["cost_weight"]);
collision_penalty_ = static_cast<double>(c["collision_penalty"]);
kernel_window_percentage_ = static_cast<double>(c["kernel_window_percentage"]);
longest_valid_joint_move_ = static_cast<double>(c["longest_valid_joint_move"]);
}
catch(XmlRpc::XmlRpcException& e)
{
ROS_ERROR("%s failed to parse configuration parameters",name_.c_str());
return false;
}
return true;
}
void CollisionCheck::done(bool success,int total_iterations,double final_cost,const Eigen::MatrixXd& parameters)
{
robot_state_.reset();
}
} /* namespace cost_functions */
} /* namespace stomp_moveit */
<commit_msg>The current state is not needed here at all.<commit_after>/**
* @file collision_check.cpp
* @brief This defines a cost function for collision checking.
*
* @author Jorge Nicho
* @date March 30, 2016
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2016, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 <ros/console.h>
#include <pluginlib/class_list_macros.h>
#include <moveit/robot_state/conversions.h>
#include "stomp_moveit/cost_functions/collision_check.h"
PLUGINLIB_EXPORT_CLASS(stomp_moveit::cost_functions::CollisionCheck,stomp_moveit::cost_functions::StompCostFunction)
static const int MIN_KERNEL_WINDOW_SIZE = 3;
/**
* @brief Convenience method that propagates the cost value at center to the window to the adjacent points.
* @param window_size Size of the kernel, must be less than the size of the 'data' array.
* @param data The original data vector
* @param smoothed The smoothed data after applying the kernel.
*/
static void applyKernelSmoothing(std::size_t window_size, const Eigen::VectorXd& data, Eigen::VectorXd& smoothed)
{
using namespace Eigen;
// allocation
window_size = 2*(window_size/2) + 1;// forcing it into an odd number
smoothed.setZero(data.size());
VectorXd x_nneighbors = VectorXd::Zero(window_size);
VectorXd y_nneighbors = VectorXd::Zero(window_size);
VectorXd kernel_weights = VectorXd::Zero(window_size);
// indexing
int index_left, index_right;
std::size_t window_index_middle = window_size/2;
// kernel function
//Epanechnikov(x,neighbors,lambda)
auto epanechnikov_function = [](double x_m,const VectorXd& neighbors,double lambda, VectorXd& weights )
{
double t = 0;
for(int i = 0; i < neighbors.size(); i++)
{
t = std::abs(x_m - neighbors(i))/lambda;
if(t < 1)
{
weights(i) = 0.75f*(1 - std::pow(t,2));
}
else
{
weights(i) = 0;
}
}
};
for(int i = 0; i < data.size(); i++)
{
// middle term
x_nneighbors(window_index_middle) = i;
y_nneighbors(window_index_middle) = data(i);
// grabbing neighbors
for(int j = 1; j <= window_size/2; j++)
{
index_left = i - j;
index_right = i + j;
if(index_left < 0)
{
x_nneighbors(window_index_middle - j) = 0;
y_nneighbors(window_index_middle - j) = data(0);
}
else
{
x_nneighbors(window_index_middle - j) = index_left;
y_nneighbors(window_index_middle - j) = data(index_left);
}
if(index_right > data.rows()-1)
{
x_nneighbors(window_index_middle + j) = data.rows()-1;
y_nneighbors(window_index_middle + j) = data(data.rows() - 1);
}
else
{
x_nneighbors(window_index_middle + j) = index_right;
y_nneighbors(window_index_middle + j) = data(index_right);
}
}
epanechnikov_function(i,x_nneighbors,window_size,kernel_weights);
smoothed(i) = (y_nneighbors.array()*kernel_weights.array()).sum()/kernel_weights.sum();
}
}
namespace stomp_moveit
{
namespace cost_functions
{
CollisionCheck::CollisionCheck():
name_("CollisionCheckPlugin"),
robot_state_(),
collision_penalty_(0.0)
{
// TODO Auto-generated constructor stub
}
CollisionCheck::~CollisionCheck()
{
// TODO Auto-generated destructor stub
}
bool CollisionCheck::initialize(moveit::core::RobotModelConstPtr robot_model_ptr,
const std::string& group_name,XmlRpc::XmlRpcValue& config)
{
robot_model_ptr_ = robot_model_ptr;
group_name_ = group_name;
return configure(config);
}
bool CollisionCheck::setMotionPlanRequest(const planning_scene::PlanningSceneConstPtr& planning_scene,
const moveit_msgs::MotionPlanRequest &req,
const stomp_core::StompConfiguration &config,
moveit_msgs::MoveItErrorCodes& error_code)
{
using namespace moveit::core;
planning_scene_ = planning_scene;
plan_request_ = req;
error_code.val = moveit_msgs::MoveItErrorCodes::SUCCESS;
// initialize collision request
collision_request_.group_name = group_name_;
collision_request_.cost = false;
collision_request_.distance = false;
collision_request_.max_contacts = 1;
collision_request_.max_contacts_per_pair = 1;
collision_request_.contacts = true;
collision_request_.verbose = false;
collision_robot_ = planning_scene->getCollisionRobot();
collision_world_ = planning_scene->getCollisionWorld();
// storing robot state
robot_state_.reset(new RobotState(robot_model_ptr_));
// if(!robotStateMsgToRobotState(req.start_state,*robot_state_,true))
// {
// ROS_ERROR("%s Failed to get current robot state from request",getName().c_str());
// return false;
// }
// copying into intermediate robot states
for(auto& rs : intermediate_coll_states_)
{
rs.reset(new RobotState(*robot_state_));
}
// allocating arrays
raw_costs_ = Eigen::VectorXd::Zero(config.num_timesteps);
return true;
}
bool CollisionCheck::computeCosts(const Eigen::MatrixXd& parameters,
std::size_t start_timestep,
std::size_t num_timesteps,
int iteration_number,
int rollout_number,
Eigen::VectorXd& costs,
bool& validity)
{
using namespace moveit::core;
using namespace Eigen;
if(!robot_state_)
{
ROS_ERROR("%s Robot State has not been updated",getName().c_str());
return false;
}
typedef collision_detection::CollisionResult::ContactMap ContactMap;
typedef ContactMap::iterator ContactMapIterator;
typedef std::vector<collision_detection::Contact> ContactArray;
// initializing result array
costs = Eigen::VectorXd::Zero(num_timesteps);
// resetting array
raw_costs_.setZero();
// collision
collision_detection::CollisionRequest request = collision_request_;
collision_detection::CollisionResult result_world_collision, result_robot_collision;
std::vector<collision_detection::CollisionResult> results(2);
validity = true;
// planning groups
const JointModelGroup* joint_group = robot_model_ptr_->getJointModelGroup(group_name_);
if(parameters.cols()< (start_timestep + num_timesteps))
{
ROS_ERROR_STREAM("Size in the 'parameters' matrix is less than required");
return false;
}
// check for collisions at each state
bool skip_next_check = false;
for (auto t=start_timestep; t<start_timestep + num_timesteps; ++t)
{
if(!skip_next_check)
{
robot_state_->setJointGroupPositions(joint_group,parameters.col(t));
robot_state_->update();
// checking robot vs world (attached objects, octomap, not in urdf) collisions
result_world_collision.distance = std::numeric_limits<double>::max();
collision_world_->checkRobotCollision(request,
result_world_collision,
*collision_robot_,
*robot_state_,
planning_scene_->getAllowedCollisionMatrix());
collision_robot_->checkSelfCollision(request,
result_robot_collision,
*robot_state_,
planning_scene_->getAllowedCollisionMatrix());
results[0]= result_world_collision;
results[1] = result_robot_collision;
for(std::vector<collision_detection::CollisionResult>::iterator i = results.begin(); i != results.end(); i++)
{
collision_detection::CollisionResult& result = *i;
if(result.collision)
{
raw_costs_(t) = collision_penalty_;
validity = false;
break;
}
}
}
// check intermediate poses to the next position (skip the last one)
if(t < start_timestep + num_timesteps - 1)
{
if(!checkIntermediateCollisions(parameters.col(t),parameters.col(t+1),longest_valid_joint_move_))
{
raw_costs_(t) = 1.0;
raw_costs_(t+1) = 1.0;
validity = false;
skip_next_check = true;
}
else
{
skip_next_check = false;
}
}
}
// applying kernel smoothing
if(!validity)
{
if(kernel_window_percentage_> 1e-6)
{
int window_size = num_timesteps*kernel_window_percentage_;
window_size = window_size < MIN_KERNEL_WINDOW_SIZE ? MIN_KERNEL_WINDOW_SIZE : window_size;
// adding minimum cost
intermediate_costs_slots_ = (raw_costs_.array() < collision_penalty_).cast<double>();
raw_costs_ += (raw_costs_.sum()/raw_costs_.size())*(intermediate_costs_slots_.matrix());
// smoothing
applyKernelSmoothing(window_size,raw_costs_,costs);
}
else
{
costs = raw_costs_;
}
}
return true;
}
bool CollisionCheck::checkIntermediateCollisions(const Eigen::VectorXd& start,
const Eigen::VectorXd& end,double longest_valid_joint_move)
{
Eigen::VectorXd diff = end - start;
int num_intermediate = std::ceil(((diff.cwiseAbs())/longest_valid_joint_move).maxCoeff()) - 1;
if(num_intermediate < 1.0)
{
// no interpolation needed
return true;
}
// grabbing states
auto& start_state = intermediate_coll_states_[0];
auto& mid_state = intermediate_coll_states_[1];
auto& end_state = intermediate_coll_states_[2];
if(!start_state || !mid_state || !end_state)
{
ROS_ERROR("%s intermediate states not initialized",getName().c_str());
return false;
}
// setting up collision
auto req = collision_request_;
req.distance = false;
collision_detection::CollisionResult res;
const moveit::core::JointModelGroup* joint_group = robot_model_ptr_->getJointModelGroup(group_name_);
start_state->setJointGroupPositions(joint_group,start);
end_state->setJointGroupPositions(joint_group,end);
// checking intermediate states
double dt = 1.0/static_cast<double>(num_intermediate);
double interval = 0.0;
for(std::size_t i = 1; i < num_intermediate;i++)
{
interval = i*dt;
start_state->interpolate(*end_state,interval,*mid_state) ;
if(planning_scene_->isStateColliding(*mid_state))
{
return false;
}
}
return true;
}
bool CollisionCheck::configure(const XmlRpc::XmlRpcValue& config)
{
// check parameter presence
auto members = {"cost_weight","collision_penalty","kernel_window_percentage"};
for(auto& m : members)
{
if(!config.hasMember(m))
{
ROS_ERROR("%s failed to find one or more required parameters",getName().c_str());
return false;
}
}
try
{
// check parameter presence
auto members = {"cost_weight","collision_penalty","kernel_window_percentage", "longest_valid_joint_move"};
for(auto& m : members)
{
if(!config.hasMember(m))
{
ROS_ERROR("%s failed to find '%s' parameter",getName().c_str(),m);
return false;
}
}
XmlRpc::XmlRpcValue c = config;
cost_weight_ = static_cast<double>(c["cost_weight"]);
collision_penalty_ = static_cast<double>(c["collision_penalty"]);
kernel_window_percentage_ = static_cast<double>(c["kernel_window_percentage"]);
longest_valid_joint_move_ = static_cast<double>(c["longest_valid_joint_move"]);
}
catch(XmlRpc::XmlRpcException& e)
{
ROS_ERROR("%s failed to parse configuration parameters",name_.c_str());
return false;
}
return true;
}
void CollisionCheck::done(bool success,int total_iterations,double final_cost,const Eigen::MatrixXd& parameters)
{
robot_state_.reset();
}
} /* namespace cost_functions */
} /* namespace stomp_moveit */
<|endoftext|> |
<commit_before><commit_msg>Cleanup SW stream backfill tests<commit_after><|endoftext|> |
<commit_before>#include "cuteengine.h"
#include "protocolhttp.h"
#include "tcpserver.h"
#include <Cutelyst/Context>
#include <Cutelyst/Response>
#include <Cutelyst/Request>
#include <Cutelyst/Application>
#include <QTcpServer>
#include <QTcpSocket>
#include <QLocalServer>
#include <QLocalSocket>
CuteEngine::CuteEngine(const QVariantMap &opts, QObject *parent) : Engine(opts)
{
m_proto = new ProtocolHttp(this);
m_app = qobject_cast<Application*>(parent);
}
int CuteEngine::workerId() const
{
return m_workerId;
}
int CuteEngine::workerCore() const
{
return m_workerCore;
}
void CuteEngine::setTcpSockets(const QVector<QTcpServer *> sockets)
{
m_sockets = sockets;
}
void CuteEngine::forked()
{
if (workerCore() > 0) {
m_app = qobject_cast<Application *>(m_app->metaObject()->newInstance());
if (!m_app) {
qFatal("*** FATAL *** Could not create a NEW instance of your Cutelyst::Application, "
"make sure your constructor has Q_INVOKABLE macro or disable threaded mode.\n");
return;
}
// Move the application and it's children to this thread
m_app->moveToThread(thread());
// We can now set a parent
m_app->setParent(this);
// init and postfork
if (!initApplication(m_app, true)) {
qCritical() << "Failed to init application on a different thread than main. Are you sure threaded mode is supported in this application?";
return;
}
} else {
postForkApplication();
}
for (QTcpServer *socket : m_sockets) {
auto server = new TcpServer(this);
server->setSocketDescriptor(socket->socketDescriptor());
connect(server, &TcpServer::newConnection, this, &CuteEngine::newconnectionTcp);
}
}
bool CuteEngine::finalizeHeaders(Context *ctx)
{
// qDebug() << Q_FUNC_INFO;
// qDebug() << ctx->request()->engineData();
// qDebug() << static_cast<QObject*>(ctx->request()->engineData());
QIODevice *conn = static_cast<QIODevice*>(ctx->request()->engineData());
Response *res = ctx->res();
QByteArray status = QByteArrayLiteral("HTTP/1.1 ");
QByteArray code = statusCode(res->status());
status.reserve(code.size() + 9);
status.append(code);
if (conn->write(status) != status.size()) {
return false;
}
if (!Engine::finalizeHeaders(ctx)) {
return false;
}
const auto headers = res->headers().map();
auto it = headers.constBegin();
auto endIt = headers.constEnd();
while (it != endIt) {
QByteArray key = it.key().toLatin1();
camelCaseByteArrayHeader(key);
QByteArray value = it.value().toLatin1();
QByteArray buf;
buf.reserve(key.size() + 2 + value.size() + 2);
buf.append("\r\n", 2);
buf.append(key);
buf.append(": ", 2);
buf.append(value);
// conn->write("\r\n", 2);
// conn->write(key);
// conn->write(": ", 2);
// conn->write(value);
conn->write(buf);
++it;
}
conn->write("\r\n\r\n", 4);
return true;
}
qint64 CuteEngine::doWrite(Context *c, const char *data, qint64 len, void *engineData)
{
QIODevice *conn = static_cast<QIODevice*>(engineData);
// qDebug() << Q_FUNC_INFO << QByteArray(data,len);
conn->write(data, len);
// conn->waitForBytesWritten(200);
}
bool CuteEngine::init()
{
return true;
}
void CuteEngine::newconnectionTcp()
{
auto server = qobject_cast<QTcpServer*>(sender());
QTcpSocket *conn = server->nextPendingConnection();
if (conn) {
connect(conn, &QTcpSocket::disconnected, conn, &QTcpSocket::deleteLater);
TcpSocket *sock = qobject_cast<TcpSocket*>(conn);
sock->engine = this;
static QString serverAddress = server->serverAddress().toString();
sock->serverAddress = serverAddress;
connect(conn, &QIODevice::readyRead, m_proto, &Protocol::readyRead);
}
}
void CuteEngine::newconnectionLocalSocket()
{
// auto server = qobject_cast<QLocalServer*>(sender());
// QLocalSocket *conn = server->nextPendingConnection();
// if (conn) {
// }
}
<commit_msg>Fix return warning<commit_after>#include "cuteengine.h"
#include "protocolhttp.h"
#include "tcpserver.h"
#include <Cutelyst/Context>
#include <Cutelyst/Response>
#include <Cutelyst/Request>
#include <Cutelyst/Application>
#include <QTcpServer>
#include <QTcpSocket>
#include <QLocalServer>
#include <QLocalSocket>
CuteEngine::CuteEngine(const QVariantMap &opts, QObject *parent) : Engine(opts)
{
m_proto = new ProtocolHttp(this);
m_app = qobject_cast<Application*>(parent);
}
int CuteEngine::workerId() const
{
return m_workerId;
}
int CuteEngine::workerCore() const
{
return m_workerCore;
}
void CuteEngine::setTcpSockets(const QVector<QTcpServer *> sockets)
{
m_sockets = sockets;
}
void CuteEngine::forked()
{
if (workerCore() > 0) {
m_app = qobject_cast<Application *>(m_app->metaObject()->newInstance());
if (!m_app) {
qFatal("*** FATAL *** Could not create a NEW instance of your Cutelyst::Application, "
"make sure your constructor has Q_INVOKABLE macro or disable threaded mode.\n");
return;
}
// Move the application and it's children to this thread
m_app->moveToThread(thread());
// We can now set a parent
m_app->setParent(this);
// init and postfork
if (!initApplication(m_app, true)) {
qCritical() << "Failed to init application on a different thread than main. Are you sure threaded mode is supported in this application?";
return;
}
} else {
postForkApplication();
}
for (QTcpServer *socket : m_sockets) {
auto server = new TcpServer(this);
server->setSocketDescriptor(socket->socketDescriptor());
connect(server, &TcpServer::newConnection, this, &CuteEngine::newconnectionTcp);
}
}
bool CuteEngine::finalizeHeaders(Context *ctx)
{
// qDebug() << Q_FUNC_INFO;
// qDebug() << ctx->request()->engineData();
// qDebug() << static_cast<QObject*>(ctx->request()->engineData());
QIODevice *conn = static_cast<QIODevice*>(ctx->request()->engineData());
Response *res = ctx->res();
QByteArray status = QByteArrayLiteral("HTTP/1.1 ");
QByteArray code = statusCode(res->status());
status.reserve(code.size() + 9);
status.append(code);
if (conn->write(status) != status.size()) {
return false;
}
if (!Engine::finalizeHeaders(ctx)) {
return false;
}
const auto headers = res->headers().map();
auto it = headers.constBegin();
auto endIt = headers.constEnd();
while (it != endIt) {
QByteArray key = it.key().toLatin1();
camelCaseByteArrayHeader(key);
QByteArray value = it.value().toLatin1();
QByteArray buf;
buf.reserve(key.size() + 2 + value.size() + 2);
buf.append("\r\n", 2);
buf.append(key);
buf.append(": ", 2);
buf.append(value);
// conn->write("\r\n", 2);
// conn->write(key);
// conn->write(": ", 2);
// conn->write(value);
conn->write(buf);
++it;
}
conn->write("\r\n\r\n", 4);
return true;
}
qint64 CuteEngine::doWrite(Context *c, const char *data, qint64 len, void *engineData)
{
auto conn = static_cast<QIODevice*>(engineData);
// qDebug() << Q_FUNC_INFO << QByteArray(data,len);
qint64 ret = conn->write(data, len);
// conn->waitForBytesWritten(200);
return ret;
}
bool CuteEngine::init()
{
return true;
}
void CuteEngine::newconnectionTcp()
{
auto server = qobject_cast<QTcpServer*>(sender());
QTcpSocket *conn = server->nextPendingConnection();
if (conn) {
connect(conn, &QTcpSocket::disconnected, conn, &QTcpSocket::deleteLater);
TcpSocket *sock = qobject_cast<TcpSocket*>(conn);
sock->engine = this;
static QString serverAddress = server->serverAddress().toString();
sock->serverAddress = serverAddress;
connect(conn, &QIODevice::readyRead, m_proto, &Protocol::readyRead);
}
}
void CuteEngine::newconnectionLocalSocket()
{
// auto server = qobject_cast<QLocalServer*>(sender());
// QLocalSocket *conn = server->nextPendingConnection();
// if (conn) {
// }
}
<|endoftext|> |
<commit_before>//Simple wrapper file to conditionally include the real CATCH for if we're doing a build with tests enabled.
//in the future, replace CATCH macros with dummies if tests are to be disabled.
//#warning "including catch.hpp"
//#define CATCH_CONFIG_PREFIX_ALL
#ifndef PRINTIPI_CATCH_HPP
#define PRINTIPI_CATCH_HPP
#include "compileflags.h"
#if DO_TESTS
#include "catch/catch.hpp"
/*#include <mutex>
class ThreadSafeJunitReporter : public Catch::JunitReporter {
public:
ThreadSafeJunitReporter(Catch::ReporterConfig const& _config) :
Catch::JunitReporter(_config) { }
static std::string getDescription() {
return "Reports test results in an XML format that looks like Ant's junitreport target.\n"
"\tThis reporter can be used in a multi-threaded environment";
}
inline virtual bool assertionEnded(Catch::AssertionStats const& assertionStats) override {
std::lock_guard<std::mutex> lock(m_mutex);
return Catch::JunitReporter::assertionEnded(assertionStats);
}
private:
std::mutex m_mutex;
};
INTERNAL_CATCH_REGISTER_REPORTER("junit-thread-safe", ThreadSafeJunitReporter);*/
#else
//Taken from catch.hpp to generate unique variable/function names:
#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
#define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
//reimplement public catch functions as nop's:
#define TEST_CASE(...) static void INTERNAL_CATCH_UNIQUE_NAME(__DEAD_TEST_CODE)()
#define SECTION(...) if (false)
#define REQUIRE(...) do {} while (false);
#define Approx(...) 0
#endif
#endif<commit_msg>Silence unused function warning<commit_after>//Simple wrapper file to conditionally include the real CATCH for if we're doing a build with tests enabled.
//in the future, replace CATCH macros with dummies if tests are to be disabled.
//#warning "including catch.hpp"
//#define CATCH_CONFIG_PREFIX_ALL
#ifndef PRINTIPI_CATCH_HPP
#define PRINTIPI_CATCH_HPP
#include "compileflags.h"
#if DO_TESTS
#include "catch/catch.hpp"
/*#include <mutex>
class ThreadSafeJunitReporter : public Catch::JunitReporter {
public:
ThreadSafeJunitReporter(Catch::ReporterConfig const& _config) :
Catch::JunitReporter(_config) { }
static std::string getDescription() {
return "Reports test results in an XML format that looks like Ant's junitreport target.\n"
"\tThis reporter can be used in a multi-threaded environment";
}
inline virtual bool assertionEnded(Catch::AssertionStats const& assertionStats) override {
std::lock_guard<std::mutex> lock(m_mutex);
return Catch::JunitReporter::assertionEnded(assertionStats);
}
private:
std::mutex m_mutex;
};
INTERNAL_CATCH_REGISTER_REPORTER("junit-thread-safe", ThreadSafeJunitReporter);*/
#else
//Taken from catch.hpp to generate unique variable/function names:
#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
#define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
//reimplement public catch functions as nop's:
#define TEST_CASE(...) static inline void INTERNAL_CATCH_UNIQUE_NAME(__DEAD_TEST_CODE)()
#define SECTION(...) if (false)
#define REQUIRE(...) do {} while (false);
#define Approx(...) 0
#endif
#endif<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "PropertyPythonObject.h"
#include "DocumentObjectPy.h"
#include "DocumentObject.h"
#include <Base/Base64.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <iostream>
#include <boost/regex.hpp>
using namespace App;
TYPESYSTEM_SOURCE(App::PropertyPythonObject , App::Property);
PropertyPythonObject::PropertyPythonObject()
{
}
PropertyPythonObject::~PropertyPythonObject()
{
// this is needed because the release of the pickled object may need the
// GIL. Thus, we grab the GIL and replace the pickled with an empty object
Base::PyGILStateLocker lock;
this->object = Py::Object();
}
void PropertyPythonObject::setValue(Py::Object o)
{
aboutToSetValue();
this->object = o;
hasSetValue();
}
Py::Object PropertyPythonObject::getValue() const
{
return object;
}
PyObject *PropertyPythonObject::getPyObject(void)
{
return Py::new_reference_to(this->object);
}
void PropertyPythonObject::setPyObject(PyObject * obj)
{
aboutToSetValue();
this->object = obj;
hasSetValue();
}
std::string PropertyPythonObject::toString() const
{
std::string repr;
Base::PyGILStateLocker lock;
try {
Py::Module pickle(PyImport_ImportModule("json"),true);
Py::Callable method(pickle.getAttr(std::string("dumps")));
Py::Object dump;
if (this->object.hasAttr("__getstate__")) {
Py::Tuple args(0);
Py::Callable state(this->object.getAttr("__getstate__"));
dump = state.apply(args);
}
else if (this->object.hasAttr("__dict__")) {
dump = this->object.getAttr("__dict__");
}
Py::Tuple args(1);
args.setItem(0, dump);
Py::Object res = method.apply(args);
Py::String str(res);
repr = str.as_std_string();
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::toString: %s\n", e.what());
}
return repr;
}
void PropertyPythonObject::fromString(const std::string& repr)
{
Base::PyGILStateLocker lock;
try {
Py::Module pickle(PyImport_ImportModule("json"),true);
Py::Callable method(pickle.getAttr(std::string("loads")));
Py::Tuple args(1);
args.setItem(0, Py::String(repr));
Py::Object res = method.apply(args);
if (this->object.hasAttr("__setstate__")) {
Py::Tuple args(1);
args.setItem(0, res);
Py::Callable state(this->object.getAttr("__setstate__"));
state.apply(args);
}
else {
this->object.setAttr("__dict__", res);
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::fromString: %s\n", e.what());
}
}
void PropertyPythonObject::loadPickle(const std::string& str)
{
// find the custom attributes and restore them
try {
std::string buffer = str;
boost::regex pickle("S'(\\w+)'.+S'(\\w+)'\\n");
boost::match_results<std::string::const_iterator> what;
std::string::const_iterator start, end;
start = buffer.begin();
end = buffer.end();
while (boost::regex_search(start, end, what, pickle)) {
std::string key = std::string(what[1].first, what[1].second);
std::string val = std::string(what[2].first, what[2].second);
this->object.setAttr(key, Py::String(val));
buffer = std::string(what[2].second, end);
start = buffer.begin();
end = buffer.end();
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::loadPickle: %s\n", e.what());
}
}
std::string PropertyPythonObject::encodeValue(const std::string& str) const
{
std::string tmp;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
if (*it == '<')
tmp += "<";
else if (*it == '"')
tmp += """;
else if (*it == '&')
tmp += "&";
else if (*it == '>')
tmp += ">";
else if (*it == '\n')
tmp += "\\n";
else
tmp += *it;
}
return tmp;
}
std::string PropertyPythonObject::decodeValue(const std::string& str) const
{
std::string tmp;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
if (*it == '\\') {
++it;
if (it != str.end() && *it == 'n') {
tmp += '\n';
}
}
else
tmp += *it;
}
return tmp;
}
void PropertyPythonObject::saveObject(Base::Writer &writer) const
{
Base::PyGILStateLocker lock;
try {
PropertyContainer* parent = this->getContainer();
if (parent->isDerivedFrom(Base::Type::fromName("App::DocumentObject"))) {
if (this->object.hasAttr("__object__")) {
writer.Stream() << " object=\"yes\"";
}
}
if (parent->isDerivedFrom(Base::Type::fromName("Gui::ViewProvider"))) {
if (this->object.hasAttr("__vobject__")) {
writer.Stream() << " vobject=\"yes\"";
}
}
}
catch (Py::Exception& e) {
e.clear();
}
}
void PropertyPythonObject::restoreObject(Base::XMLReader &reader)
{
Base::PyGILStateLocker lock;
try {
PropertyContainer* parent = this->getContainer();
if (reader.hasAttribute("object")) {
if (strcmp(reader.getAttribute("object"),"yes") == 0) {
Py::Object obj = Py::asObject(parent->getPyObject());
this->object.setAttr("__object__", obj);
}
}
if (reader.hasAttribute("vobject")) {
if (strcmp(reader.getAttribute("vobject"),"yes") == 0) {
Py::Object obj = Py::asObject(parent->getPyObject());
this->object.setAttr("__vobject__", obj);
}
}
}
catch (Py::Exception& e) {
e.clear();
}
catch (const Base::Exception& e) {
Base::Console().Error("%s\n",e.what());
}
catch (...) {
Base::Console().Error("Critical error in PropertyPythonObject::restoreObject\n");
}
}
void PropertyPythonObject::Save (Base::Writer &writer) const
{
//if (writer.isForceXML()) {
std::string repr = this->toString();
repr = Base::base64_encode((const unsigned char*)repr.c_str(), repr.size());
std::string val = /*encodeValue*/(repr);
writer.Stream() << writer.ind() << "<Python value=\"" << val
<< "\" encoded=\"yes\"";
try {
if (this->object.hasAttr("__module__") && this->object.hasAttr("__class__")) {
Py::String mod(this->object.getAttr("__module__"));
Py::Object cls(this->object.getAttr("__class__"));
if (cls.hasAttr("__name__")) {
Py::String name(cls.getAttr("__name__"));
writer.Stream() << " module=\"" << (std::string)mod << "\""
<< " class=\"" << (std::string)name << "\"";
}
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::Save: %s\n", e.what());
}
saveObject(writer);
writer.Stream() << "/>" << std::endl;
//}
//else {
// writer.Stream() << writer.ind() << "<Python file=\"" <<
// writer.addFile("pickle", this) << "\"/>" << std::endl;
//}
}
void PropertyPythonObject::Restore(Base::XMLReader &reader)
{
reader.readElement("Python");
if (reader.hasAttribute("file")) {
std::string file(reader.getAttribute("file"));
reader.addFile(file.c_str(),this);
}
else {
bool load_json=false;
bool load_pickle=false;
std::string buffer = reader.getAttribute("value");
if (reader.hasAttribute("encoded") &&
strcmp(reader.getAttribute("encoded"),"yes") == 0) {
buffer = Base::base64_decode(buffer);
}
else {
buffer = decodeValue(buffer);
}
try {
boost::regex pickle("^\\(i(\\w+)\\n(\\w+)\\n");
boost::match_results<std::string::const_iterator> what;
std::string::const_iterator start, end;
start = buffer.begin();
end = buffer.end();
if (reader.hasAttribute("module") && reader.hasAttribute("class")) {
Py::Module mod(PyImport_ImportModule(reader.getAttribute("module")),true);
this->object = PyInstance_NewRaw(mod.getAttr(reader.getAttribute("class")).ptr(), 0);
load_json = true;
}
else if (boost::regex_search(start, end, what, pickle)) {
std::string nam = std::string(what[1].first, what[1].second);
std::string cls = std::string(what[2].first, what[2].second);
Py::Module mod(PyImport_ImportModule(nam.c_str()),true);
this->object = PyInstance_NewRaw(mod.getAttr(cls).ptr(), 0);
load_pickle = true;
buffer = std::string(what[2].second, end);
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::Restore: %s\n", e.what());
}
aboutToSetValue();
if (load_json)
this->fromString(buffer);
else if (load_pickle)
this->loadPickle(buffer);
else
Base::Console().Warning("PropertyPythonObject::Restore: unsupported serialisation: %s\n", buffer);
restoreObject(reader);
hasSetValue();
}
}
void PropertyPythonObject::SaveDocFile (Base::Writer &writer) const
{
std::string buffer = this->toString();
for (std::string::iterator it = buffer.begin(); it != buffer.end(); ++it)
writer.Stream().put(*it);
}
void PropertyPythonObject::RestoreDocFile(Base::Reader &reader)
{
aboutToSetValue();
std::string buffer;
char c;
while (reader.get(c)) {
buffer.push_back(c);
}
this->fromString(buffer);
hasSetValue();
}
unsigned int PropertyPythonObject::getMemSize (void) const
{
return sizeof(Py::Object);
}
Property *PropertyPythonObject::Copy(void) const
{
PropertyPythonObject *p = new PropertyPythonObject();
p->object = this->object;
return p;
}
void PropertyPythonObject::Paste(const Property &from)
{
if (from.getTypeId() == PropertyPythonObject::getClassTypeId()) {
aboutToSetValue();
this->object = static_cast<const PropertyPythonObject&>(from).object;
hasSetValue();
}
}
<commit_msg>0000774: merge project with these files instantly crashes FreeCAD<commit_after>/***************************************************************************
* Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include "PropertyPythonObject.h"
#include "DocumentObjectPy.h"
#include "DocumentObject.h"
#include <Base/Base64.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <iostream>
#include <boost/regex.hpp>
using namespace App;
TYPESYSTEM_SOURCE(App::PropertyPythonObject , App::Property);
PropertyPythonObject::PropertyPythonObject()
{
}
PropertyPythonObject::~PropertyPythonObject()
{
// this is needed because the release of the pickled object may need the
// GIL. Thus, we grab the GIL and replace the pickled with an empty object
Base::PyGILStateLocker lock;
this->object = Py::Object();
}
void PropertyPythonObject::setValue(Py::Object o)
{
aboutToSetValue();
this->object = o;
hasSetValue();
}
Py::Object PropertyPythonObject::getValue() const
{
return object;
}
PyObject *PropertyPythonObject::getPyObject(void)
{
return Py::new_reference_to(this->object);
}
void PropertyPythonObject::setPyObject(PyObject * obj)
{
aboutToSetValue();
this->object = obj;
hasSetValue();
}
std::string PropertyPythonObject::toString() const
{
std::string repr;
Base::PyGILStateLocker lock;
try {
Py::Module pickle(PyImport_ImportModule("json"),true);
Py::Callable method(pickle.getAttr(std::string("dumps")));
Py::Object dump;
if (this->object.hasAttr("__getstate__")) {
Py::Tuple args(0);
Py::Callable state(this->object.getAttr("__getstate__"));
dump = state.apply(args);
}
else if (this->object.hasAttr("__dict__")) {
dump = this->object.getAttr("__dict__");
}
Py::Tuple args(1);
args.setItem(0, dump);
Py::Object res = method.apply(args);
Py::String str(res);
repr = str.as_std_string();
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::toString: %s\n", e.what());
}
return repr;
}
void PropertyPythonObject::fromString(const std::string& repr)
{
Base::PyGILStateLocker lock;
try {
Py::Module pickle(PyImport_ImportModule("json"),true);
Py::Callable method(pickle.getAttr(std::string("loads")));
Py::Tuple args(1);
args.setItem(0, Py::String(repr));
Py::Object res = method.apply(args);
if (this->object.hasAttr("__setstate__")) {
Py::Tuple args(1);
args.setItem(0, res);
Py::Callable state(this->object.getAttr("__setstate__"));
state.apply(args);
}
else {
this->object.setAttr("__dict__", res);
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::fromString: %s\n", e.what());
}
}
void PropertyPythonObject::loadPickle(const std::string& str)
{
// find the custom attributes and restore them
Base::PyGILStateLocker lock;
try {
std::string buffer = str;
boost::regex pickle("S'(\\w+)'.+S'(\\w+)'\\n");
boost::match_results<std::string::const_iterator> what;
std::string::const_iterator start, end;
start = buffer.begin();
end = buffer.end();
while (boost::regex_search(start, end, what, pickle)) {
std::string key = std::string(what[1].first, what[1].second);
std::string val = std::string(what[2].first, what[2].second);
this->object.setAttr(key, Py::String(val));
buffer = std::string(what[2].second, end);
start = buffer.begin();
end = buffer.end();
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::loadPickle: %s\n", e.what());
}
}
std::string PropertyPythonObject::encodeValue(const std::string& str) const
{
std::string tmp;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
if (*it == '<')
tmp += "<";
else if (*it == '"')
tmp += """;
else if (*it == '&')
tmp += "&";
else if (*it == '>')
tmp += ">";
else if (*it == '\n')
tmp += "\\n";
else
tmp += *it;
}
return tmp;
}
std::string PropertyPythonObject::decodeValue(const std::string& str) const
{
std::string tmp;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
if (*it == '\\') {
++it;
if (it != str.end() && *it == 'n') {
tmp += '\n';
}
}
else
tmp += *it;
}
return tmp;
}
void PropertyPythonObject::saveObject(Base::Writer &writer) const
{
Base::PyGILStateLocker lock;
try {
PropertyContainer* parent = this->getContainer();
if (parent->isDerivedFrom(Base::Type::fromName("App::DocumentObject"))) {
if (this->object.hasAttr("__object__")) {
writer.Stream() << " object=\"yes\"";
}
}
if (parent->isDerivedFrom(Base::Type::fromName("Gui::ViewProvider"))) {
if (this->object.hasAttr("__vobject__")) {
writer.Stream() << " vobject=\"yes\"";
}
}
}
catch (Py::Exception& e) {
e.clear();
}
}
void PropertyPythonObject::restoreObject(Base::XMLReader &reader)
{
Base::PyGILStateLocker lock;
try {
PropertyContainer* parent = this->getContainer();
if (reader.hasAttribute("object")) {
if (strcmp(reader.getAttribute("object"),"yes") == 0) {
Py::Object obj = Py::asObject(parent->getPyObject());
this->object.setAttr("__object__", obj);
}
}
if (reader.hasAttribute("vobject")) {
if (strcmp(reader.getAttribute("vobject"),"yes") == 0) {
Py::Object obj = Py::asObject(parent->getPyObject());
this->object.setAttr("__vobject__", obj);
}
}
}
catch (Py::Exception& e) {
e.clear();
}
catch (const Base::Exception& e) {
Base::Console().Error("%s\n",e.what());
}
catch (...) {
Base::Console().Error("Critical error in PropertyPythonObject::restoreObject\n");
}
}
void PropertyPythonObject::Save (Base::Writer &writer) const
{
//if (writer.isForceXML()) {
std::string repr = this->toString();
repr = Base::base64_encode((const unsigned char*)repr.c_str(), repr.size());
std::string val = /*encodeValue*/(repr);
writer.Stream() << writer.ind() << "<Python value=\"" << val
<< "\" encoded=\"yes\"";
Base::PyGILStateLocker lock;
try {
if (this->object.hasAttr("__module__") && this->object.hasAttr("__class__")) {
Py::String mod(this->object.getAttr("__module__"));
Py::Object cls(this->object.getAttr("__class__"));
if (cls.hasAttr("__name__")) {
Py::String name(cls.getAttr("__name__"));
writer.Stream() << " module=\"" << (std::string)mod << "\""
<< " class=\"" << (std::string)name << "\"";
}
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::Save: %s\n", e.what());
}
saveObject(writer);
writer.Stream() << "/>" << std::endl;
//}
//else {
// writer.Stream() << writer.ind() << "<Python file=\"" <<
// writer.addFile("pickle", this) << "\"/>" << std::endl;
//}
}
void PropertyPythonObject::Restore(Base::XMLReader &reader)
{
reader.readElement("Python");
if (reader.hasAttribute("file")) {
std::string file(reader.getAttribute("file"));
reader.addFile(file.c_str(),this);
}
else {
bool load_json=false;
bool load_pickle=false;
std::string buffer = reader.getAttribute("value");
if (reader.hasAttribute("encoded") &&
strcmp(reader.getAttribute("encoded"),"yes") == 0) {
buffer = Base::base64_decode(buffer);
}
else {
buffer = decodeValue(buffer);
}
Base::PyGILStateLocker lock;
try {
boost::regex pickle("^\\(i(\\w+)\\n(\\w+)\\n");
boost::match_results<std::string::const_iterator> what;
std::string::const_iterator start, end;
start = buffer.begin();
end = buffer.end();
if (reader.hasAttribute("module") && reader.hasAttribute("class")) {
Py::Module mod(PyImport_ImportModule(reader.getAttribute("module")),true);
this->object = PyInstance_NewRaw(mod.getAttr(reader.getAttribute("class")).ptr(), 0);
load_json = true;
}
else if (boost::regex_search(start, end, what, pickle)) {
std::string nam = std::string(what[1].first, what[1].second);
std::string cls = std::string(what[2].first, what[2].second);
Py::Module mod(PyImport_ImportModule(nam.c_str()),true);
this->object = PyInstance_NewRaw(mod.getAttr(cls).ptr(), 0);
load_pickle = true;
buffer = std::string(what[2].second, end);
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
Base::Console().Warning("PropertyPythonObject::Restore: %s\n", e.what());
}
aboutToSetValue();
if (load_json)
this->fromString(buffer);
else if (load_pickle)
this->loadPickle(buffer);
else
Base::Console().Warning("PropertyPythonObject::Restore: unsupported serialisation: %s\n", buffer);
restoreObject(reader);
hasSetValue();
}
}
void PropertyPythonObject::SaveDocFile (Base::Writer &writer) const
{
std::string buffer = this->toString();
for (std::string::iterator it = buffer.begin(); it != buffer.end(); ++it)
writer.Stream().put(*it);
}
void PropertyPythonObject::RestoreDocFile(Base::Reader &reader)
{
aboutToSetValue();
std::string buffer;
char c;
while (reader.get(c)) {
buffer.push_back(c);
}
this->fromString(buffer);
hasSetValue();
}
unsigned int PropertyPythonObject::getMemSize (void) const
{
return sizeof(Py::Object);
}
Property *PropertyPythonObject::Copy(void) const
{
PropertyPythonObject *p = new PropertyPythonObject();
p->object = this->object;
return p;
}
void PropertyPythonObject::Paste(const Property &from)
{
if (from.getTypeId() == PropertyPythonObject::getClassTypeId()) {
aboutToSetValue();
this->object = static_cast<const PropertyPythonObject&>(from).object;
hasSetValue();
}
}
<|endoftext|> |
<commit_before>#include "3RVX.h"
#include "Controllers\Volume\IVolume.h"
#include "Controllers\Volume\CoreAudio.h"
#include "VolumeOSD.h"
#include <Wtsapi32.h>
#include "Logger.h"
int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow) {
hInst = hInstance;
using namespace Gdiplus;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
#ifdef _DEBUG
Logger::OpenConsole();
#endif
QCLOG(L" _____ ______ ____ _______ ");
QCLOG(L" |___ /| _ \\ \\ / /\\ \\/ /___ / ");
QCLOG(L" |_ \\| |_) \\ \\ / / \\ / |_ \\ ");
QCLOG(L" ___) | _ < \\ V / / \\ ___) |");
QCLOG(L" |____/|_| \\_\\ \\_/ /_/\\_\\____/ ");
QCLOG(L"");
QCLOG(L"Starting up...");
mainWnd = CreateMainWnd(hInstance);
if (mainWnd == NULL) {
CLOG(L"Could not create main window");
return EXIT_FAILURE;
}
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (hr != S_OK) {
CLOG(L"Failed to initialize the COM library.");
return EXIT_FAILURE;
}
/* Tell the program to initialize */
PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
/* Start the event loop */
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
void Init() {
CLOG(L"Initializing...");
ca = new CoreAudio(mainWnd);
ca->Init();
float v = ca->Volume();
// Meter *m = new HorizontalEndcap(L"meter.png", 71, 29, 28);
// mW = new MeterWnd(hInst, L"testtest", L"what what");
// mW->AddMeter(m);
// std::wstring bgbmp(L"bg.png");
// mW->SetBackgroundImage(Gdiplus::Bitmap::FromFile(bgbmp.c_str(), true));
// mW->MeterLevels(v);
// mW->Update();
// mW->Show();
vOsd = new VolumeOSD(hInst);
vOsd->LoadSkin(L"Ignition");
vOsd->MeterLevels(v);
WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);
HotkeyManager *hkManager = HotkeyManager::Instance();
hkManager->Register(mainWnd, HKM_MOD_WIN + VK_BACK);
hkManager->Register(mainWnd, HKM_MOD_WIN + HKM_MOUSE_WHUP);
}
HWND CreateMainWnd(HINSTANCE hInstance) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = NULL;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = NULL;
wcex.cbWndExtra = NULL;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"3RVX";
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
return NULL;
}
HWND hWnd = CreateWindowEx(
NULL,
L"3RVX", L"3RVX",
NULL, NULL, NULL, //your boat, gently down the stream
NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);
return hWnd;
}
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case MSG_VOLCHNG: {
float v = ca->Volume();
QCLOG(L"Volume level: %.0f", v * 100.0f);
vOsd->MeterLevels(v);
break;
}
case MSG_DEVCHNG:
CLOG(L"Device change detected.");
ca->ReattachDefaultDevice();
break;
case WM_HOTKEY:
CLOG(L"Hotkey: %d", (int) wParam);
break;
case WM_WTSSESSION_CHANGE:
CLOG(L"Detected session change");
break;
}
if (message == WM_3RVX_CONTROL) {
switch (wParam) {
case MSG_LOAD:
Init();
break;
case 101:
printf("%x\n", lParam);
break;
}
}
if (message == WM_HOTKEY) {
printf("Hotkey: %d\n", (int) wParam);
}
if (message == WM_WTSSESSION_CHANGE) {
printf("session change\n");
}
return DefWindowProc(hWnd, message, wParam, lParam);
}<commit_msg>Initial settings tests<commit_after>#include "3RVX.h"
#include "Controllers\Volume\IVolume.h"
#include "Controllers\Volume\CoreAudio.h"
#include "VolumeOSD.h"
#include <Wtsapi32.h>
#include "Logger.h"
#include "Settings.h"
int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow) {
hInst = hInstance;
using namespace Gdiplus;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
#ifdef _DEBUG
Logger::OpenConsole();
#endif
QCLOG(L" _____ ______ ____ _______ ");
QCLOG(L" |___ /| _ \\ \\ / /\\ \\/ /___ / ");
QCLOG(L" |_ \\| |_) \\ \\ / / \\ / |_ \\ ");
QCLOG(L" ___) | _ < \\ V / / \\ ___) |");
QCLOG(L" |____/|_| \\_\\ \\_/ /_/\\_\\____/ ");
QCLOG(L"");
QCLOG(L"Starting up...");
mainWnd = CreateMainWnd(hInstance);
if (mainWnd == NULL) {
CLOG(L"Could not create main window");
return EXIT_FAILURE;
}
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (hr != S_OK) {
CLOG(L"Failed to initialize the COM library.");
return EXIT_FAILURE;
}
/* Tell the program to initialize */
PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
/* Start the event loop */
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return (int)msg.wParam;
}
void Init() {
CLOG(L"Initializing...");
ca = new CoreAudio(mainWnd);
ca->Init();
float v = ca->Volume();
// Meter *m = new HorizontalEndcap(L"meter.png", 71, 29, 28);
// mW = new MeterWnd(hInst, L"testtest", L"what what");
// mW->AddMeter(m);
// std::wstring bgbmp(L"bg.png");
// mW->SetBackgroundImage(Gdiplus::Bitmap::FromFile(bgbmp.c_str(), true));
// mW->MeterLevels(v);
// mW->Update();
// mW->Show();
Settings s(L"Settings.xml");
vOsd = new VolumeOSD(hInst);
vOsd->LoadSkin(s.SkinName());
vOsd->MeterLevels(v);
WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);
HotkeyManager *hkManager = HotkeyManager::Instance();
hkManager->Register(mainWnd, HKM_MOD_WIN + VK_BACK);
hkManager->Register(mainWnd, HKM_MOD_WIN + HKM_MOUSE_WHUP);
CLOG(L"%d", HKM_MOD_WIN + VK_UP);
}
HWND CreateMainWnd(HINSTANCE hInstance) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = NULL;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = NULL;
wcex.cbWndExtra = NULL;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = L"3RVX";
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
return NULL;
}
HWND hWnd = CreateWindowEx(
NULL,
L"3RVX", L"3RVX",
NULL, NULL, NULL, //your boat, gently down the stream
NULL, NULL, HWND_MESSAGE, NULL, hInstance, NULL);
return hWnd;
}
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case MSG_VOLCHNG: {
float v = ca->Volume();
QCLOG(L"Volume level: %.0f", v * 100.0f);
vOsd->MeterLevels(v);
break;
}
case MSG_DEVCHNG:
CLOG(L"Device change detected.");
ca->ReattachDefaultDevice();
break;
case WM_HOTKEY:
CLOG(L"Hotkey: %d", (int) wParam);
break;
case WM_WTSSESSION_CHANGE:
CLOG(L"Detected session change");
break;
}
if (message == WM_3RVX_CONTROL) {
switch (wParam) {
case MSG_LOAD:
Init();
break;
case 101:
printf("%x\n", lParam);
break;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}<|endoftext|> |
<commit_before>#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
#include <iostream>
#include <string>
#include <unordered_map>
#include <Wtsapi32.h>
#include "3RVX.h"
#include "OSD\EjectOSD.h"
#include "OSD\VolumeOSD.h"
#include "HotkeyInfo.h"
#include "HotkeyManager.h"
#include "Logger.h"
#include "Settings.h"
#include "Skin.h"
HANDLE mutex;
HINSTANCE hInst;
ULONG_PTR gdiplusToken;
HWND mainWnd;
VolumeOSD *vOSD;
EjectOSD *eOSD;
VolumeSlider *vSlide;
HotkeyManager *hkManager;
std::unordered_map<int, HotkeyInfo> hotkeys;
void init();
HWND CreateMainWnd(HINSTANCE hInstance);
void ProcessHotkeys(HotkeyInfo &hki);
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow) {
hInst = hInstance;
#ifdef _DEBUG
Logger::OpenConsole();
#endif
QCLOG(L" _____ ______ ____ _______ ");
QCLOG(L" |___ /| _ \\ \\ / /\\ \\/ /___ / ");
QCLOG(L" |_ \\| |_) \\ \\ / / \\ / |_ \\ ");
QCLOG(L" ___) | _ < \\ V / / \\ ___) |");
QCLOG(L" |____/|_| \\_\\ \\_/ /_/\\_\\____/ ");
QCLOG(L"");
QCLOG(L"Starting up...");
mutex = CreateMutex(NULL, FALSE, L"Local\\3RVX");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
if (mutex) {
ReleaseMutex(mutex);
}
HWND masterWnd = FindWindow(CLASS_3RVX, CLASS_3RVX);
CLOG(L"A previous instance of the program is already running.\n"
L"Requesting Settings dialog from window: %d", (int) masterWnd);
SendMessage(masterWnd, WM_3RVX_CONTROL, MSG_SETTINGS, NULL);
#ifdef _DEBUG
CLOG(L"Press [enter] to terminate");
std::cin.get();
#endif
return EXIT_SUCCESS;
}
CLOG(L"App directory: %s", Settings::AppDir().c_str());
using namespace Gdiplus;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
mainWnd = CreateMainWnd(hInstance);
if (mainWnd == NULL) {
CLOG(L"Could not create main window");
return EXIT_FAILURE;
}
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (hr != S_OK) {
CLOG(L"Failed to initialize the COM library.");
return EXIT_FAILURE;
}
/* Tell the program to initialize */
PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
/* Start the event loop */
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return (int) msg.wParam;
}
void init() {
CLOG(L"Initializing...");
delete vOSD;
delete eOSD;
vOSD = new VolumeOSD();
eOSD = new EjectOSD();
if (hkManager != NULL) {
hkManager->Shutdown();
}
hkManager = HotkeyManager::Instance(mainWnd);
hotkeys = Settings::Instance()->Hotkeys();
for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {
int combination = it->first;
hkManager->Register(combination);
}
WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);
}
HWND CreateMainWnd(HINSTANCE hInstance) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = NULL;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = NULL;
wcex.cbWndExtra = NULL;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = CLASS_3RVX;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
return NULL;
}
HWND hWnd = CreateWindowEx(
NULL,
CLASS_3RVX, CLASS_3RVX,
NULL, NULL, NULL, //your boat, gently down the stream
NULL, NULL, NULL, NULL, hInstance, NULL);
return hWnd;
}
void ProcessHotkeys(HotkeyInfo &hki) {
switch (hki.action) {
case HotkeyInfo::IncreaseVolume:
case HotkeyInfo::DecreaseVolume:
case HotkeyInfo::Mute:
vOSD->ProcessHotkeys(hki);
break;
case HotkeyInfo::Settings:
ShellExecute(NULL, L"open",
Settings::SettingsApp().c_str(), NULL, NULL, SW_SHOWNORMAL);
break;
case HotkeyInfo::Exit:
SendMessage(mainWnd, WM_CLOSE, NULL, NULL);
break;
}
}
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_HOTKEY: {
CLOG(L"Hotkey: %d", (int) wParam);
HotkeyInfo hki = hotkeys[(int) wParam];
ProcessHotkeys(hki);
break;
}
case WM_WTSSESSION_CHANGE: {
CLOG(L"Detected session change");
break;
}
case WM_CLOSE: {
CLOG(L"Shutting down");
HotkeyManager::Instance()->Shutdown();
vOSD->HideIcon();
DestroyWindow(mainWnd);
break;
}
case WM_DESTROY: {
PostQuitMessage(0);
break;
}
}
if (message == WM_3RVX_CONTROL) {
switch (wParam) {
case MSG_LOAD:
init();
break;
case MSG_SETTINGS:
Settings::LaunchSettingsApp();
break;
case MSG_HIDEOSD:
int except = (OSDType) lParam;
switch (except) {
case Volume:
if (eOSD) {
eOSD->Hide();
}
break;
case Eject:
if (vOSD) {
vOSD->Hide();
}
break;
}
break;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}<commit_msg>Reorder deletes/creates<commit_after>#include <Windows.h>
#include <gdiplus.h>
#pragma comment(lib, "gdiplus.lib")
#include <iostream>
#include <string>
#include <unordered_map>
#include <Wtsapi32.h>
#include "3RVX.h"
#include "OSD\EjectOSD.h"
#include "OSD\VolumeOSD.h"
#include "HotkeyInfo.h"
#include "HotkeyManager.h"
#include "Logger.h"
#include "Settings.h"
#include "Skin.h"
HANDLE mutex;
HINSTANCE hInst;
ULONG_PTR gdiplusToken;
HWND mainWnd;
VolumeOSD *vOSD;
EjectOSD *eOSD;
VolumeSlider *vSlide;
HotkeyManager *hkManager;
std::unordered_map<int, HotkeyInfo> hotkeys;
void init();
HWND CreateMainWnd(HINSTANCE hInstance);
void ProcessHotkeys(HotkeyInfo &hki);
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
int APIENTRY
wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow) {
hInst = hInstance;
#ifdef _DEBUG
Logger::OpenConsole();
#endif
QCLOG(L" _____ ______ ____ _______ ");
QCLOG(L" |___ /| _ \\ \\ / /\\ \\/ /___ / ");
QCLOG(L" |_ \\| |_) \\ \\ / / \\ / |_ \\ ");
QCLOG(L" ___) | _ < \\ V / / \\ ___) |");
QCLOG(L" |____/|_| \\_\\ \\_/ /_/\\_\\____/ ");
QCLOG(L"");
QCLOG(L"Starting up...");
mutex = CreateMutex(NULL, FALSE, L"Local\\3RVX");
if (GetLastError() == ERROR_ALREADY_EXISTS) {
if (mutex) {
ReleaseMutex(mutex);
}
HWND masterWnd = FindWindow(CLASS_3RVX, CLASS_3RVX);
CLOG(L"A previous instance of the program is already running.\n"
L"Requesting Settings dialog from window: %d", (int) masterWnd);
SendMessage(masterWnd, WM_3RVX_CONTROL, MSG_SETTINGS, NULL);
#ifdef _DEBUG
CLOG(L"Press [enter] to terminate");
std::cin.get();
#endif
return EXIT_SUCCESS;
}
CLOG(L"App directory: %s", Settings::AppDir().c_str());
using namespace Gdiplus;
GdiplusStartupInput gdiplusStartupInput;
GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
mainWnd = CreateMainWnd(hInstance);
if (mainWnd == NULL) {
CLOG(L"Could not create main window");
return EXIT_FAILURE;
}
HRESULT hr = CoInitializeEx(NULL,
COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if (hr != S_OK) {
CLOG(L"Failed to initialize the COM library.");
return EXIT_FAILURE;
}
/* Tell the program to initialize */
PostMessage(mainWnd, WM_3RVX_CONTROL, MSG_LOAD, NULL);
/* Start the event loop */
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
GdiplusShutdown(gdiplusToken);
return (int) msg.wParam;
}
void init() {
CLOG(L"Initializing...");
delete vOSD;
delete eOSD;
Settings::Instance()->Reload();
eOSD = new EjectOSD();
vOSD = new VolumeOSD();
if (hkManager != NULL) {
hkManager->Shutdown();
}
hkManager = HotkeyManager::Instance(mainWnd);
hotkeys = Settings::Instance()->Hotkeys();
for (auto it = hotkeys.begin(); it != hotkeys.end(); ++it) {
int combination = it->first;
hkManager->Register(combination);
}
WTSRegisterSessionNotification(mainWnd, NOTIFY_FOR_THIS_SESSION);
}
HWND CreateMainWnd(HINSTANCE hInstance) {
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = NULL;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = NULL;
wcex.cbWndExtra = NULL;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = CLASS_3RVX;
wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION);
if (!RegisterClassEx(&wcex)) {
return NULL;
}
HWND hWnd = CreateWindowEx(
NULL,
CLASS_3RVX, CLASS_3RVX,
NULL, NULL, NULL, //your boat, gently down the stream
NULL, NULL, NULL, NULL, hInstance, NULL);
return hWnd;
}
void ProcessHotkeys(HotkeyInfo &hki) {
switch (hki.action) {
case HotkeyInfo::IncreaseVolume:
case HotkeyInfo::DecreaseVolume:
case HotkeyInfo::Mute:
vOSD->ProcessHotkeys(hki);
break;
case HotkeyInfo::Settings:
ShellExecute(NULL, L"open",
Settings::SettingsApp().c_str(), NULL, NULL, SW_SHOWNORMAL);
break;
case HotkeyInfo::Exit:
SendMessage(mainWnd, WM_CLOSE, NULL, NULL);
break;
}
}
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_HOTKEY: {
CLOG(L"Hotkey: %d", (int) wParam);
HotkeyInfo hki = hotkeys[(int) wParam];
ProcessHotkeys(hki);
break;
}
case WM_WTSSESSION_CHANGE: {
CLOG(L"Detected session change");
break;
}
case WM_CLOSE: {
CLOG(L"Shutting down");
HotkeyManager::Instance()->Shutdown();
vOSD->HideIcon();
DestroyWindow(mainWnd);
break;
}
case WM_DESTROY: {
PostQuitMessage(0);
break;
}
}
if (message == WM_3RVX_CONTROL) {
switch (wParam) {
case MSG_LOAD:
init();
break;
case MSG_SETTINGS:
Settings::LaunchSettingsApp();
break;
case MSG_HIDEOSD:
int except = (OSDType) lParam;
switch (except) {
case Volume:
if (eOSD) {
eOSD->Hide();
}
break;
case Eject:
if (vOSD) {
vOSD->Hide();
}
break;
}
break;
}
}
return DefWindowProc(hWnd, message, wParam, lParam);
}<|endoftext|> |
<commit_before>#include <map>
#include <string>
#include <utility>
#define PAM_SM_AUTH
#include <security/pam_modules.h>
#include <security/pam_ext.h>
#define LDAP_DEPRECATED 1
#include <ldap.h>
typedef std::map<std::string, std::string> ArgMap;
static bool verify(const char* host, const char* binddn, const char* pw)
{
LDAP* ld;
if (ldap_initialize(&ld, host)) {
return false;
}
int rc = ldap_simple_bind_s(ld, binddn, pw);
return rc == LDAP_SUCCESS;
}
static ArgMap get_args(int argc,
const char** argv)
{
ArgMap arguments;
for (int i = 0; i < argc; i++) {
std::string arg(argv[i]);
std::string::size_type pos = arg.find("=");
if (pos != std::string::npos) {
std::string key = arg.substr(0, pos);
std::string value = "";
if (arg.length() > pos+1) {
value = arg.substr(pos+1);
}
arguments.insert(std::make_pair(key, value));
}
}
return arguments;
}
PAM_EXTERN int pam_sm_authenticate(pam_handle_t* pamh,
int flags,
int argc,
const char** argv)
{
const char* user;
const char* pass;
ArgMap arguments = get_args(argc, argv);
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) {
return PAM_AUTH_ERR;
}
if (pam_get_authtok(pamh, PAM_AUTHTOK, &pass, NULL) != PAM_SUCCESS) {
return PAM_AUTH_ERR;
}
// ensure uri and binddn PAM parameters were specified
if (arguments.find("uri") == arguments.end() ||
arguments.find("binddn") == arguments.end()) {
return PAM_AUTH_ERR;
}
std::string binddn = arguments["binddn"];
// replace %s with user
std::string::size_type pos = binddn.find("%s");
if (pos != std::string::npos) {
binddn = binddn.replace(pos, 2, user);
}
// check against ldap database
if (verify(arguments["uri"].c_str(), binddn.c_str(), pass)) {
return PAM_SUCCESS;
} else {
return PAM_AUTH_ERR;
}
}
PAM_EXTERN int pam_sm_setcred(pam_handle_t* pamh,
int flags,
int argc,
const char** argv)
{
return PAM_SUCCESS;
}
<commit_msg>write a proper string replace_all function<commit_after>#include <map>
#include <string>
#include <utility>
#define PAM_SM_AUTH
#include <security/pam_modules.h>
#include <security/pam_ext.h>
#define LDAP_DEPRECATED 1
#include <ldap.h>
typedef std::map<std::string, std::string> ArgMap;
static bool verify(const char* host,
const char* binddn,
const char* pw)
{
LDAP* ld;
if (ldap_initialize(&ld, host)) {
return false;
}
int rc = ldap_simple_bind_s(ld, binddn, pw);
return rc == LDAP_SUCCESS;
}
static ArgMap get_args(int argc,
const char** argv)
{
ArgMap arguments;
for (int i = 0; i < argc; i++) {
std::string arg(argv[i]);
std::string::size_type pos = arg.find("=");
if (pos != std::string::npos) {
std::string key = arg.substr(0, pos);
std::string value = "";
if (arg.length() > pos+1) {
value = arg.substr(pos+1);
}
arguments.insert(std::make_pair(key, value));
}
}
return arguments;
}
static void replace_all(std::string& s,
const std::string& search_s,
const std::string& replace_s)
{
std::string::size_type last_pos = 0;
while ((last_pos = s.find(search_s, last_pos)) != std::string::npos) {
s.replace(last_pos, search_s.length(), replace_s);
}
}
PAM_EXTERN int pam_sm_authenticate(pam_handle_t* pamh,
int flags,
int argc,
const char** argv)
{
const char* user;
const char* pass;
ArgMap arguments = get_args(argc, argv);
if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS) {
return PAM_AUTH_ERR;
}
if (pam_get_authtok(pamh, PAM_AUTHTOK, &pass, NULL) != PAM_SUCCESS) {
return PAM_AUTH_ERR;
}
// ensure uri and binddn PAM parameters were specified
if (arguments.find("uri") == arguments.end() ||
arguments.find("binddn") == arguments.end()) {
return PAM_AUTH_ERR;
}
std::string binddn = arguments["binddn"];
replace_all(binddn, "%s", user);
// check against ldap database
if (verify(arguments["uri"].c_str(), binddn.c_str(), pass)) {
return PAM_SUCCESS;
} else {
return PAM_AUTH_ERR;
}
}
PAM_EXTERN int pam_sm_setcred(pam_handle_t* pamh,
int flags,
int argc,
const char** argv)
{
return PAM_SUCCESS;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "virtual_allocator.hpp"
#include "paging.hpp"
namespace {
size_t next_virtual_address = 0;
size_t allocated_pages = 0;
} //end of anonymous namespace
void virtual_allocator::init(){
auto start = paging::virtual_paging_start;
start += paging::physical_memory_pages * paging::PAGE_SIZE;
if(start % 0x100000 == 0){
next_virtual_address = start;
} else {
next_virtual_address = (start / 0x100000 + 1) * 0x100000;
}
allocated_pages = next_virtual_address / paging::PAGE_SIZE;
}
size_t virtual_allocator::allocate(size_t pages){
allocated_pages += pages;
auto address = next_virtual_address;
next_virtual_address += pages * paging::PAGE_SIZE;
return address;
}
size_t virtual_allocator::available(){
return kernel_virtual_size;
}
size_t virtual_allocator::allocated(){
return allocated_pages * paging::PAGE_SIZE;
}
size_t virtual_allocator::free(){
return available() - allocated();
}
<commit_msg>Compute as much as possible as compile-time<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include "virtual_allocator.hpp"
#include "paging.hpp"
namespace {
constexpr const size_t virtual_start = paging::virtual_paging_start + (paging::physical_memory_pages * paging::PAGE_SIZE);
constexpr const size_t first_virtual_address = virtual_start % 0x100000 == 0 ? virtual_start : (virtual_start / 0x100000 + 1) * 0x100000;
size_t next_virtual_address = first_virtual_address;
size_t allocated_pages = first_virtual_address / paging::PAGE_SIZE;
} //end of anonymous namespace
void virtual_allocator::init(){
}
size_t virtual_allocator::allocate(size_t pages){
allocated_pages += pages;
auto address = next_virtual_address;
next_virtual_address += pages * paging::PAGE_SIZE;
return address;
}
size_t virtual_allocator::available(){
return kernel_virtual_size;
}
size_t virtual_allocator::allocated(){
return allocated_pages * paging::PAGE_SIZE;
}
size_t virtual_allocator::free(){
return available() - allocated();
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include <Poco/Logger.h>
#include <Poco/LoggingFactory.h>
#include <Poco/FormattingChannel.h>
#include <Poco/SplitterChannel.h>
#include <Poco/LocalDateTime.h>
#include "Foundation.h"
namespace Foundation
{
Framework::Framework() : exit_signal_(false)
{
platform_ = PlatformPtr(new Platform(this));
config_.DeclareSetting(Framework::ConfigurationGroup(), "application_name", "realXtend");
platform_->PrepareApplicationDataDirectory(); // depends on config
CreateLoggingSystem(); // depends on config and platform
// create managers
module_manager_ = ModuleManagerPtr(new ModuleManager(this));
component_manager_ = ComponentManagerPtr(new ComponentManager(this));
service_manager_ = ServiceManagerPtr(new ServiceManager(this));
}
Framework::~Framework()
{
Poco::Logger::shutdown();
for (size_t i=0 ; i<log_channels_.size() ; ++i)
log_channels_[i]->release();
log_channels_.clear();
log_formatter_->release();
}
void Framework::CreateLoggingSystem()
{
Poco::LoggingFactory *loggingfactory = new Poco::LoggingFactory();
Poco::Channel *consolechannel = loggingfactory->createChannel("ConsoleChannel");
Poco::Channel *filechannel = loggingfactory->createChannel("FileChannel");
std::string logfilepath = platform_->GetUserDocumentsDirectory();
logfilepath += "/" + config_.GetString(Framework::ConfigurationGroup(), "application_name") + ".log";
std::fstream log(logfilepath.c_str(), std::ios::app | std::ios::out);
log << std::endl;
log << std::endl;
log.close();
filechannel->setProperty("path",logfilepath);
filechannel->setProperty("rotation","3M");
filechannel->setProperty("archive","number");
filechannel->setProperty("compress","false");
Poco::SplitterChannel *splitterchannel = new Poco::SplitterChannel();
splitterchannel->addChannel(consolechannel);
splitterchannel->addChannel(filechannel);
log_formatter_ = loggingfactory->createFormatter("PatternFormatter");
log_formatter_->setProperty("pattern","%H:%M:%S [%s] %t");
log_formatter_->setProperty("times","local");
Poco::Channel *formatchannel = new Poco::FormattingChannel(log_formatter_,splitterchannel);
try
{
Poco::Logger::create("",formatchannel,Poco::Message::PRIO_TRACE);
Poco::Logger::create("Foundation",Poco::Logger::root().getChannel() ,Poco::Message::PRIO_TRACE);
} catch (Poco::ExistsException)
{
assert (false && "Somewhere, a message is pushed to log before the logger is initialized.");
}
Poco::LocalDateTime *currenttime = new Poco::LocalDateTime();
std::string timestring = boost::lexical_cast<std::string>(currenttime->day()) + "/";
timestring.append(boost::lexical_cast<std::string>(currenttime->month()) + "/");
timestring.append(boost::lexical_cast<std::string>(currenttime->year()) + " ");
timestring.append(boost::lexical_cast<std::string>(currenttime->hour()) + ":");
timestring.append(boost::lexical_cast<std::string>(currenttime->minute()) + ":");
timestring.append(boost::lexical_cast<std::string>(currenttime->second()));
Foundation::RootLogInfo("Log file opened on " + timestring);
log_channels_.push_back(consolechannel);
log_channels_.push_back(filechannel);
log_channels_.push_back(splitterchannel);
log_channels_.push_back(formatchannel);
delete currenttime;
delete loggingfactory;
}
void Framework::Go()
{
LoadModules();
// main loop
while (exit_signal_ == false)
{
// do synchronized update for modules
module_manager_->UpdateModules();
// call asynchronous update on modules / do parallel tasks
// synchronize shared data across modules
//mChangeManager->_propagateChanges();
}
UnloadModules();
}
void Framework::LoadModules()
{
module_manager_->LoadAvailableModules();
module_manager_->InitializeModules();
}
void Framework::UnloadModules()
{
module_manager_->UninitializeModules();
module_manager_->UnloadModules();
}
}
<commit_msg>PoCo bug: cannot handle scandic letters (äöå) in folder/filenames. Catches Poco::OpenFileException when creating the log file.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include <Poco/Logger.h>
#include <Poco/LoggingFactory.h>
#include <Poco/FormattingChannel.h>
#include <Poco/SplitterChannel.h>
#include <Poco/LocalDateTime.h>
#include "Foundation.h"
namespace Foundation
{
Framework::Framework() : exit_signal_(false)
{
platform_ = PlatformPtr(new Platform(this));
config_.DeclareSetting(Framework::ConfigurationGroup(), "application_name", "realXtend");
platform_->PrepareApplicationDataDirectory(); // depends on config
CreateLoggingSystem(); // depends on config and platform
// create managers
module_manager_ = ModuleManagerPtr(new ModuleManager(this));
component_manager_ = ComponentManagerPtr(new ComponentManager(this));
service_manager_ = ServiceManagerPtr(new ServiceManager(this));
}
Framework::~Framework()
{
Poco::Logger::shutdown();
for (size_t i=0 ; i<log_channels_.size() ; ++i)
log_channels_[i]->release();
log_channels_.clear();
log_formatter_->release();
}
void Framework::CreateLoggingSystem()
{
Poco::LoggingFactory *loggingfactory = new Poco::LoggingFactory();
Poco::Channel *consolechannel = loggingfactory->createChannel("ConsoleChannel");
Poco::Channel *filechannel = loggingfactory->createChannel("FileChannel");
std::string logfilepath = platform_->GetUserDocumentsDirectory();
logfilepath += "/" + config_.GetString(Framework::ConfigurationGroup(), "application_name") + ".log";
std::fstream log(logfilepath.c_str(), std::ios::app | std::ios::out);
log << std::endl;
log << std::endl;
log.close();
filechannel->setProperty("path",logfilepath);
filechannel->setProperty("rotation","3M");
filechannel->setProperty("archive","number");
filechannel->setProperty("compress","false");
Poco::SplitterChannel *splitterchannel = new Poco::SplitterChannel();
splitterchannel->addChannel(consolechannel);
splitterchannel->addChannel(filechannel);
log_formatter_ = loggingfactory->createFormatter("PatternFormatter");
log_formatter_->setProperty("pattern","%H:%M:%S [%s] %t");
log_formatter_->setProperty("times","local");
Poco::Channel *formatchannel = new Poco::FormattingChannel(log_formatter_,splitterchannel);
try
{
Poco::Logger::create("",formatchannel,Poco::Message::PRIO_TRACE);
Poco::Logger::create("Foundation",Poco::Logger::root().getChannel() ,Poco::Message::PRIO_TRACE);
} catch (Poco::ExistsException)
{
assert (false && "Somewhere, a message is pushed to log before the logger is initialized.");
}
Poco::LocalDateTime *currenttime = new Poco::LocalDateTime();
std::string timestring = boost::lexical_cast<std::string>(currenttime->day()) + "/";
timestring.append(boost::lexical_cast<std::string>(currenttime->month()) + "/");
timestring.append(boost::lexical_cast<std::string>(currenttime->year()) + " ");
timestring.append(boost::lexical_cast<std::string>(currenttime->hour()) + ":");
timestring.append(boost::lexical_cast<std::string>(currenttime->minute()) + ":");
timestring.append(boost::lexical_cast<std::string>(currenttime->second()));
///\todo FIXME PoCo bug. Cannot handle scandic letters.
try
{
Foundation::RootLogInfo("Log file opened on " + timestring);
} catch(Poco::OpenFileException)
{
// Do not create the log file.
splitterchannel->removeChannel(filechannel);
Foundation::RootLogInfo("Poco::OpenFileException. Log file not created.");
}
log_channels_.push_back(consolechannel);
log_channels_.push_back(filechannel);
log_channels_.push_back(splitterchannel);
log_channels_.push_back(formatchannel);
delete currenttime;
delete loggingfactory;
}
void Framework::Go()
{
LoadModules();
// main loop
while (exit_signal_ == false)
{
// do synchronized update for modules
module_manager_->UpdateModules();
// call asynchronous update on modules / do parallel tasks
// synchronize shared data across modules
//mChangeManager->_propagateChanges();
}
UnloadModules();
}
void Framework::LoadModules()
{
module_manager_->LoadAvailableModules();
module_manager_->InitializeModules();
}
void Framework::UnloadModules()
{
module_manager_->UninitializeModules();
module_manager_->UnloadModules();
}
}
<|endoftext|> |
<commit_before>#include "VRManager.hpp"
#include "Utility/Log.hpp"
#include "../Component/VRDevice.hpp"
VRManager::VRManager() : scale(1.f) {
// Check if VR runtime is installed.
if (!vr::VR_IsRuntimeInstalled()) {
vrSystem = nullptr;
Log() << "VR runtime not installed. Playing without VR.\n";
return;
}
// Load VR Runtime.
vr::EVRInitError eError = vr::VRInitError_None;
vrSystem = vr::VR_Init(&eError, vr::VRApplication_Scene);
if (eError != vr::VRInitError_None) {
vrSystem = nullptr;
Log() << "Unable to init VR runtime: " << vr::VR_GetVRInitErrorAsEnglishDescription(eError) << "\n";
return;
}
// Get focus.
vr::VRCompositor()->WaitGetPoses(NULL, 0, NULL, 0);
}
VRManager::~VRManager() {
if (vrSystem == nullptr)
return;
vr::VR_Shutdown();
vrSystem = nullptr;
}
bool VRManager::Active() const {
return vrSystem != nullptr;
}
void VRManager::Sync() {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return;
}
// Get VR device pose(s).
vr::VRCompositor()->WaitGetPoses(tracedDevicePoseArray, vr::k_unMaxTrackedDeviceCount, NULL, 0);
vr::ETrackedControllerRole role;
// Convert to glm format.
for (int nDevice = 0; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice)
if (tracedDevicePoseArray[nDevice].bPoseIsValid)
deviceTransforms[nDevice] = ConvertMatrix(tracedDevicePoseArray[nDevice].mDeviceToAbsoluteTracking);
}
void VRManager::Update() {
if (vrSystem == nullptr)
return;
// Update VR devices.
for (Component::VRDevice* vrDevice : vrDevices.GetAll()) {
if (vrDevice->IsKilled() || !vrDevice->entity->enabled)
continue;
Entity* entity = vrDevice->entity;
if (vrDevice->type == Component::VRDevice::CONTROLLER) {
glm::mat4 transform = GetControllerPoseMatrix(vrDevice->controllerID);
// Update position based on controller position.
glm::vec3 position = glm::vec3(transform[3][0], transform[3][1], transform[3][2]);
entity->position = position * GetScale();
// Update rotation based on controller rotation.
entity->rotation.x = atan2(transform[1][0], transform[0][0]);
entity->rotation.y = atan2(-transform[2][0], sqrt(transform[2][1] * transform[2][1] + transform[2][2] * transform[2][2]));
entity->rotation.z = atan2(transform[2][1], transform[2][2]);
} else if (vrDevice->type == Component::VRDevice::HEADSET) {
/// @todo Update headset transformation.
}
}
}
glm::vec2 VRManager::GetRecommendedRenderTargetSize() const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::vec2();
}
std::uint32_t width, height;
vrSystem->GetRecommendedRenderTargetSize(&width, &height);
return glm::vec2(width, height);
}
glm::mat4 VRManager::GetHMDPoseMatrix() const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
return glm::inverse(deviceTransforms[vr::k_unTrackedDeviceIndex_Hmd]);
}
glm::mat4 VRManager::GetControllerPoseMatrix(int controlID) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
for (vr::TrackedDeviceIndex_t untrackedDevice = 0; untrackedDevice < vr::k_unMaxTrackedDeviceCount; untrackedDevice++) {
// Skip current VR device if it's not connected
if (!vrSystem->IsTrackedDeviceConnected(untrackedDevice))
continue;
// Skip current device if it's not a controller
else if (vrSystem->GetTrackedDeviceClass(untrackedDevice) != vr::TrackedDeviceClass_Controller)
continue;
// Skip current controller if it's not in a valid position
else if (!tracedDevicePoseArray[untrackedDevice].bPoseIsValid)
continue;
// Find out if current controller is the left or right one.
vr::ETrackedControllerRole role = vrSystem->GetControllerRoleForTrackedDeviceIndex(untrackedDevice);
// If we want to differentiate between left and right controller.
if (role == vr::ETrackedControllerRole::TrackedControllerRole_Invalid)
continue;
else if (role == vr::ETrackedControllerRole::TrackedControllerRole_LeftHand && controlID == 1) {
return deviceTransforms[untrackedDevice];
}
else if (role == vr::ETrackedControllerRole::TrackedControllerRole_RightHand && controlID == 2) {
return deviceTransforms[untrackedDevice];
}
}
return glm::mat4();
}
glm::mat4 VRManager::GetHMDEyeToHeadMatrix(vr::Hmd_Eye eye) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
return glm::inverse(ConvertMatrix(vrSystem->GetEyeToHeadTransform(eye)));
}
glm::mat4 VRManager::GetHandleTransformation(int controlID, Entity* entity) {
glm::mat4 ctrlTransform = GetControllerPoseMatrix(controlID);
glm::vec3 ctrlRight = glm::vec3(ctrlTransform[0][0], ctrlTransform[1][0], ctrlTransform[2][0]);
glm::vec3 ctrlUp = glm::vec3(ctrlTransform[0][1], ctrlTransform[1][1], ctrlTransform[2][1]);
glm::vec3 ctrlForward = glm::vec3(ctrlTransform[0][2], ctrlTransform[1][2], ctrlTransform[2][2]);
glm::vec3 ctrlPosition = glm::vec3(-ctrlTransform[3][0], -ctrlTransform[3][1], -ctrlTransform[3][2]);
glm::mat4 ctrlOrientation = glm::mat4(
glm::vec4(ctrlRight, 0.0f),
glm::vec4(ctrlUp, 0.0f),
glm::vec4(ctrlForward, 0.0f),
glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)
);
glm::vec3 localPosition = ctrlPosition * GetScale();
glm::mat4 localTranslationMatrix = glm::translate(glm::mat4(), localPosition);
glm::mat4 globalTranslationMatrix = entity->GetModelMatrix() * (ctrlOrientation * localTranslationMatrix);
return globalTranslationMatrix;
}
glm::mat4 VRManager::GetHMDProjectionMatrix(vr::Hmd_Eye eye, float zNear, float zFar) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
return ConvertMatrix(vrSystem->GetProjectionMatrix(eye, zNear, zFar));
}
void VRManager::Submit(vr::Hmd_Eye eye, vr::Texture_t* texture) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return;
}
const vr::EVRCompositorError eError = vr::VRCompositor()->Submit(eye, texture);
if (eError != vr::VRCompositorError_None)
Log() << "Unable to submit texture to hmd: " << eError << "\n";
}
glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix34_t& mat) {
glm::mat4 glmMat(
mat.m[0][0], mat.m[1][0], mat.m[2][0], 0.0,
mat.m[0][1], mat.m[1][1], mat.m[2][1], 0.0,
mat.m[0][2], mat.m[1][2], mat.m[2][2], 0.0,
mat.m[0][3], mat.m[1][3], mat.m[2][3], 1.0f
);
return glmMat;
}
glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix44_t& mat) {
glm::mat4 glmMat(
mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0],
mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1],
mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2],
mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3]
);
return glmMat;
}
float VRManager::GetScale() const {
return scale;
}
void VRManager::SetScale(float scale) {
this->scale = scale;
}
bool VRManager::GetInput(vr::EVRButtonId buttonID) {
for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) {
vr::VRControllerState_t controllerState;
if (vrSystem->GetControllerState(unDevice, &controllerState, sizeof(controllerState))) {
pressedTrackedDevice[unDevice] = controllerState.ulButtonPressed == 0;
if (controllerState.ulButtonPressed & vr::ButtonMaskFromId(buttonID))
return true;
}
}
return false;
}
Component::VRDevice* VRManager::CreateVRDevice() {
return vrDevices.Create();
}
Component::VRDevice* VRManager::CreateVRDevice(const Json::Value& node) {
Component::VRDevice* vrDevice = vrDevices.Create();
// Load values from Json node.
std::string type = node.get("type", "controller").asString();
if (type == "controller")
vrDevice->type = Component::VRDevice::CONTROLLER;
else if (type == "headset")
vrDevice->type = Component::VRDevice::HEADSET;
vrDevice->controllerID = node.get("controllerID", 1).asInt();
return vrDevice;
}
const std::vector<Component::VRDevice*>& VRManager::GetVRDevices() const {
return vrDevices.GetAll();
}
void VRManager::ClearKilledComponents() {
vrDevices.ClearKilled();
}
<commit_msg>Convert rotation to degrees<commit_after>#include "VRManager.hpp"
#include "Utility/Log.hpp"
#include "../Component/VRDevice.hpp"
VRManager::VRManager() : scale(1.f) {
// Check if VR runtime is installed.
if (!vr::VR_IsRuntimeInstalled()) {
vrSystem = nullptr;
Log() << "VR runtime not installed. Playing without VR.\n";
return;
}
// Load VR Runtime.
vr::EVRInitError eError = vr::VRInitError_None;
vrSystem = vr::VR_Init(&eError, vr::VRApplication_Scene);
if (eError != vr::VRInitError_None) {
vrSystem = nullptr;
Log() << "Unable to init VR runtime: " << vr::VR_GetVRInitErrorAsEnglishDescription(eError) << "\n";
return;
}
// Get focus.
vr::VRCompositor()->WaitGetPoses(NULL, 0, NULL, 0);
}
VRManager::~VRManager() {
if (vrSystem == nullptr)
return;
vr::VR_Shutdown();
vrSystem = nullptr;
}
bool VRManager::Active() const {
return vrSystem != nullptr;
}
void VRManager::Sync() {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return;
}
// Get VR device pose(s).
vr::VRCompositor()->WaitGetPoses(tracedDevicePoseArray, vr::k_unMaxTrackedDeviceCount, NULL, 0);
vr::ETrackedControllerRole role;
// Convert to glm format.
for (int nDevice = 0; nDevice < vr::k_unMaxTrackedDeviceCount; ++nDevice)
if (tracedDevicePoseArray[nDevice].bPoseIsValid)
deviceTransforms[nDevice] = ConvertMatrix(tracedDevicePoseArray[nDevice].mDeviceToAbsoluteTracking);
}
void VRManager::Update() {
if (vrSystem == nullptr)
return;
// Update VR devices.
for (Component::VRDevice* vrDevice : vrDevices.GetAll()) {
if (vrDevice->IsKilled() || !vrDevice->entity->enabled)
continue;
Entity* entity = vrDevice->entity;
if (vrDevice->type == Component::VRDevice::CONTROLLER) {
glm::mat4 transform = GetControllerPoseMatrix(vrDevice->controllerID);
// Update position based on controller position.
glm::vec3 position = glm::vec3(transform[3][0], transform[3][1], transform[3][2]);
entity->position = position * GetScale();
// Update rotation based on controller rotation.
entity->rotation.x = glm::degrees(atan2(transform[1][0], transform[0][0]));
entity->rotation.y = glm::degrees(atan2(-transform[2][0], sqrt(transform[2][1] * transform[2][1] + transform[2][2] * transform[2][2])));
entity->rotation.z = glm::degrees(atan2(transform[2][1], transform[2][2]));
} else if (vrDevice->type == Component::VRDevice::HEADSET) {
/// @todo Update headset transformation.
}
}
}
glm::vec2 VRManager::GetRecommendedRenderTargetSize() const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::vec2();
}
std::uint32_t width, height;
vrSystem->GetRecommendedRenderTargetSize(&width, &height);
return glm::vec2(width, height);
}
glm::mat4 VRManager::GetHMDPoseMatrix() const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
return glm::inverse(deviceTransforms[vr::k_unTrackedDeviceIndex_Hmd]);
}
glm::mat4 VRManager::GetControllerPoseMatrix(int controlID) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
for (vr::TrackedDeviceIndex_t untrackedDevice = 0; untrackedDevice < vr::k_unMaxTrackedDeviceCount; untrackedDevice++) {
// Skip current VR device if it's not connected
if (!vrSystem->IsTrackedDeviceConnected(untrackedDevice))
continue;
// Skip current device if it's not a controller
else if (vrSystem->GetTrackedDeviceClass(untrackedDevice) != vr::TrackedDeviceClass_Controller)
continue;
// Skip current controller if it's not in a valid position
else if (!tracedDevicePoseArray[untrackedDevice].bPoseIsValid)
continue;
// Find out if current controller is the left or right one.
vr::ETrackedControllerRole role = vrSystem->GetControllerRoleForTrackedDeviceIndex(untrackedDevice);
// If we want to differentiate between left and right controller.
if (role == vr::ETrackedControllerRole::TrackedControllerRole_Invalid)
continue;
else if (role == vr::ETrackedControllerRole::TrackedControllerRole_LeftHand && controlID == 1) {
return deviceTransforms[untrackedDevice];
}
else if (role == vr::ETrackedControllerRole::TrackedControllerRole_RightHand && controlID == 2) {
return deviceTransforms[untrackedDevice];
}
}
return glm::mat4();
}
glm::mat4 VRManager::GetHMDEyeToHeadMatrix(vr::Hmd_Eye eye) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
return glm::inverse(ConvertMatrix(vrSystem->GetEyeToHeadTransform(eye)));
}
glm::mat4 VRManager::GetHandleTransformation(int controlID, Entity* entity) {
glm::mat4 ctrlTransform = GetControllerPoseMatrix(controlID);
glm::vec3 ctrlRight = glm::vec3(ctrlTransform[0][0], ctrlTransform[1][0], ctrlTransform[2][0]);
glm::vec3 ctrlUp = glm::vec3(ctrlTransform[0][1], ctrlTransform[1][1], ctrlTransform[2][1]);
glm::vec3 ctrlForward = glm::vec3(ctrlTransform[0][2], ctrlTransform[1][2], ctrlTransform[2][2]);
glm::vec3 ctrlPosition = glm::vec3(-ctrlTransform[3][0], -ctrlTransform[3][1], -ctrlTransform[3][2]);
glm::mat4 ctrlOrientation = glm::mat4(
glm::vec4(ctrlRight, 0.0f),
glm::vec4(ctrlUp, 0.0f),
glm::vec4(ctrlForward, 0.0f),
glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)
);
glm::vec3 localPosition = ctrlPosition * GetScale();
glm::mat4 localTranslationMatrix = glm::translate(glm::mat4(), localPosition);
glm::mat4 globalTranslationMatrix = entity->GetModelMatrix() * (ctrlOrientation * localTranslationMatrix);
return globalTranslationMatrix;
}
glm::mat4 VRManager::GetHMDProjectionMatrix(vr::Hmd_Eye eye, float zNear, float zFar) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return glm::mat4();
}
return ConvertMatrix(vrSystem->GetProjectionMatrix(eye, zNear, zFar));
}
void VRManager::Submit(vr::Hmd_Eye eye, vr::Texture_t* texture) const {
if (vrSystem == nullptr) {
Log() << "No initialized VR device.\n";
return;
}
const vr::EVRCompositorError eError = vr::VRCompositor()->Submit(eye, texture);
if (eError != vr::VRCompositorError_None)
Log() << "Unable to submit texture to hmd: " << eError << "\n";
}
glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix34_t& mat) {
glm::mat4 glmMat(
mat.m[0][0], mat.m[1][0], mat.m[2][0], 0.0,
mat.m[0][1], mat.m[1][1], mat.m[2][1], 0.0,
mat.m[0][2], mat.m[1][2], mat.m[2][2], 0.0,
mat.m[0][3], mat.m[1][3], mat.m[2][3], 1.0f
);
return glmMat;
}
glm::mat4 VRManager::ConvertMatrix(const vr::HmdMatrix44_t& mat) {
glm::mat4 glmMat(
mat.m[0][0], mat.m[1][0], mat.m[2][0], mat.m[3][0],
mat.m[0][1], mat.m[1][1], mat.m[2][1], mat.m[3][1],
mat.m[0][2], mat.m[1][2], mat.m[2][2], mat.m[3][2],
mat.m[0][3], mat.m[1][3], mat.m[2][3], mat.m[3][3]
);
return glmMat;
}
float VRManager::GetScale() const {
return scale;
}
void VRManager::SetScale(float scale) {
this->scale = scale;
}
bool VRManager::GetInput(vr::EVRButtonId buttonID) {
for (vr::TrackedDeviceIndex_t unDevice = 0; unDevice < vr::k_unMaxTrackedDeviceCount; unDevice++) {
vr::VRControllerState_t controllerState;
if (vrSystem->GetControllerState(unDevice, &controllerState, sizeof(controllerState))) {
pressedTrackedDevice[unDevice] = controllerState.ulButtonPressed == 0;
if (controllerState.ulButtonPressed & vr::ButtonMaskFromId(buttonID))
return true;
}
}
return false;
}
Component::VRDevice* VRManager::CreateVRDevice() {
return vrDevices.Create();
}
Component::VRDevice* VRManager::CreateVRDevice(const Json::Value& node) {
Component::VRDevice* vrDevice = vrDevices.Create();
// Load values from Json node.
std::string type = node.get("type", "controller").asString();
if (type == "controller")
vrDevice->type = Component::VRDevice::CONTROLLER;
else if (type == "headset")
vrDevice->type = Component::VRDevice::HEADSET;
vrDevice->controllerID = node.get("controllerID", 1).asInt();
return vrDevice;
}
const std::vector<Component::VRDevice*>& VRManager::GetVRDevices() const {
return vrDevices.GetAll();
}
void VRManager::ClearKilledComponents() {
vrDevices.ClearKilled();
}
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "XSLTProcessorEnvSupportDefault.hpp"
#include <algorithm>
#include <xercesc/sax/EntityResolver.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/URISupport.hpp>
#include <XPath/ElementPrefixResolverProxy.hpp>
#include <XPath/XPathExecutionContext.hpp>
#include <XMLSupport/XMLParserLiaison.hpp>
#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"
XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(XSLTProcessor* theProcessor) :
XSLTProcessorEnvSupport(),
m_defaultSupport(),
m_processor(theProcessor)
{
}
XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
reset();
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
m_defaultSupport.installExternalFunctionLocal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
m_defaultSupport.reset();
}
XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
if (m_processor == 0)
{
return m_defaultSupport.parseXML(urlString, base);
}
else
{
typedef URISupport::URLAutoPtrType URLAutoPtrType;
// $$$ ToDo: we should re-work this code to only use
// XMLRUL when necessary.
const URLAutoPtrType xslURL =
URISupport::getURLFromString(urlString, base);
// $$$ ToDo: Explicit XalanDOMString constructor
const XalanDOMString urlText(XalanDOMString(xslURL->getURLText()));
// First see if it's already been parsed...
XalanDocument* theDocument =
getSourceDocument(urlText);
if (theDocument == 0)
{
XMLParserLiaison& parserLiaison =
m_processor->getXMLParserLiaison();
XSLTInputSource inputSource(c_wstr(urlText));
EntityResolver* const theResolver =
parserLiaison.getEntityResolver();
if (theResolver == 0)
{
const XSLTInputSource inputSource(c_wstr(urlText));
theDocument = parserLiaison.parseXMLStream(inputSource);
}
else
{
const XalanAutoPtr<InputSource> resolverInputSource =
theResolver->resolveEntity(0, c_wstr(urlText));
if (resolverInputSource.get() != 0)
{
theDocument = parserLiaison.parseXMLStream(*resolverInputSource.get());
}
else
{
const XSLTInputSource inputSource(c_wstr(urlText));
theDocument = parserLiaison.parseXMLStream(inputSource);
}
}
if (theDocument != 0)
{
setSourceDocument(urlText, theDocument);
}
}
return theDocument;
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
return m_defaultSupport.getSourceDocument(theURI);
}
void
XSLTProcessorEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_defaultSupport.setSourceDocument(theURI, theDocument);
}
XalanDOMString
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
return m_defaultSupport.findURIFromDoc(owner);
}
bool
XSLTProcessorEnvSupportDefault::elementAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.elementAvailable(theNamespace,
functionName);
}
bool
XSLTProcessorEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.functionAvailable(theNamespace,
functionName);
}
XObjectPtr
XSLTProcessorEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const Locator* locator) const
{
return m_defaultSupport.extFunction(
executionContext,
theNamespace,
functionName,
context,
argVec,
locator);
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const XalanNode* styleNode,
const XalanNode* sourceNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
styleNode,
sourceNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
styleNode,
sourceNode);
return false;
}
else
{
m_processor->message(
msg,
styleNode,
sourceNode);
return false;
}
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const PrefixResolver* /* resolver */,
const XalanNode* sourceNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
0,
sourceNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
0,
sourceNode);
return false;
}
else
{
m_processor->message(
msg,
0,
sourceNode);
return false;
}
}
<commit_msg>Removed unnecessary string copy.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "XSLTProcessorEnvSupportDefault.hpp"
#include <algorithm>
#include <xercesc/sax/EntityResolver.hpp>
#include <xercesc/util/XMLURL.hpp>
#include <Include/STLHelper.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/URISupport.hpp>
#include <XPath/ElementPrefixResolverProxy.hpp>
#include <XPath/XPathExecutionContext.hpp>
#include <XMLSupport/XMLParserLiaison.hpp>
#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"
XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(XSLTProcessor* theProcessor) :
XSLTProcessorEnvSupport(),
m_defaultSupport(),
m_processor(theProcessor)
{
}
XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
reset();
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
const Function& function)
{
m_defaultSupport.installExternalFunctionLocal(theNamespace, functionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName)
{
m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, functionName);
}
void
XSLTProcessorEnvSupportDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
m_defaultSupport.reset();
}
XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
if (m_processor == 0)
{
return m_defaultSupport.parseXML(urlString, base);
}
else
{
typedef URISupport::URLAutoPtrType URLAutoPtrType;
// $$$ ToDo: we should re-work this code to only use
// XMLRUL when necessary.
const URLAutoPtrType xslURL =
URISupport::getURLFromString(urlString, base);
// $$$ ToDo: Explicit XalanDOMString constructor
const XalanDOMString urlText(xslURL->getURLText());
// First see if it's already been parsed...
XalanDocument* theDocument =
getSourceDocument(urlText);
if (theDocument == 0)
{
XMLParserLiaison& parserLiaison =
m_processor->getXMLParserLiaison();
XSLTInputSource inputSource(c_wstr(urlText));
EntityResolver* const theResolver =
parserLiaison.getEntityResolver();
if (theResolver == 0)
{
const XSLTInputSource inputSource(c_wstr(urlText));
theDocument = parserLiaison.parseXMLStream(inputSource);
}
else
{
const XalanAutoPtr<InputSource> resolverInputSource =
theResolver->resolveEntity(0, c_wstr(urlText));
if (resolverInputSource.get() != 0)
{
theDocument = parserLiaison.parseXMLStream(*resolverInputSource.get());
}
else
{
const XSLTInputSource inputSource(c_wstr(urlText));
theDocument = parserLiaison.parseXMLStream(inputSource);
}
}
if (theDocument != 0)
{
setSourceDocument(urlText, theDocument);
}
}
return theDocument;
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
return m_defaultSupport.getSourceDocument(theURI);
}
void
XSLTProcessorEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_defaultSupport.setSourceDocument(theURI, theDocument);
}
XalanDOMString
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
return m_defaultSupport.findURIFromDoc(owner);
}
bool
XSLTProcessorEnvSupportDefault::elementAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.elementAvailable(theNamespace,
functionName);
}
bool
XSLTProcessorEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& functionName) const
{
return m_defaultSupport.functionAvailable(theNamespace,
functionName);
}
XObjectPtr
XSLTProcessorEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& functionName,
XalanNode* context,
const XObjectArgVectorType& argVec,
const Locator* locator) const
{
return m_defaultSupport.extFunction(
executionContext,
theNamespace,
functionName,
context,
argVec,
locator);
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const XalanNode* styleNode,
const XalanNode* sourceNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
styleNode,
sourceNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
styleNode,
sourceNode);
return false;
}
else
{
m_processor->message(
msg,
styleNode,
sourceNode);
return false;
}
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource /* where */,
eClassification classification,
const PrefixResolver* /* resolver */,
const XalanNode* sourceNode,
const XalanDOMString& msg,
const XalanDOMChar* /* uri */,
int /* lineNo */,
int /* charOffset */) const
{
if (classification == XPathEnvSupport::eError)
{
m_processor->error(
msg,
0,
sourceNode);
return true;
}
else if (classification == XPathEnvSupport::eWarning)
{
m_processor->warn(
msg,
0,
sourceNode);
return false;
}
else
{
m_processor->message(
msg,
0,
sourceNode);
return false;
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/agg_pattern_source.hpp>
#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/line_pattern_symbolizer.hpp>
#include <mapnik/vertex_converters.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/parse_path.hpp>
// agg
#include "agg_basics.h"
#include "agg_pixfmt_rgba.h"
#include "agg_color_rgba.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_outline.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_pattern_filters_rgba.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_renderer_outline_image.h"
#include "agg_conv_clip_polyline.h"
// boost
#include <boost/foreach.hpp>
namespace {
class pattern_source : private mapnik::noncopyable
{
public:
pattern_source(mapnik::image_data_32 const& pattern)
: pattern_(pattern) {}
inline unsigned int width() const
{
return pattern_.width();
}
inline unsigned int height() const
{
return pattern_.height();
}
inline agg::rgba8 pixel(int x, int y) const
{
unsigned c = pattern_(x,y);
return agg::rgba8_pre(c & 0xff,
(c >> 8) & 0xff,
(c >> 16) & 0xff,
(c >> 24) & 0xff);
}
private:
mapnik::image_data_32 const& pattern_;
};
}
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(line_pattern_symbolizer const& sym,
mapnik::feature_impl & feature,
proj_transform const& prj_trans)
{
typedef agg::rgba8 color;
typedef agg::order_rgba order;
typedef agg::comp_op_adaptor_rgba_pre<color, order> blender_type;
typedef agg::pattern_filter_bilinear_rgba8 pattern_filter_type;
typedef agg::line_image_pattern<pattern_filter_type> pattern_type;
typedef agg::pixfmt_custom_blend_rgba<blender_type, agg::rendering_buffer> pixfmt_type;
typedef agg::renderer_base<pixfmt_type> renderer_base;
typedef agg::renderer_outline_image<renderer_base, pattern_type> renderer_type;
typedef agg::rasterizer_outline_aa<renderer_type> rasterizer_type;
std::string filename = path_processor_type::evaluate( *sym.get_filename(), feature);
boost::optional<marker_ptr> mark = marker_cache::instance().find(filename,true);
if (!mark) return;
if (!(*mark)->is_bitmap())
{
MAPNIK_LOG_DEBUG(agg_renderer) << "agg_renderer: Only images (not '" << filename << "') are supported in the line_pattern_symbolizer";
return;
}
boost::optional<image_ptr> pat = (*mark)->get_bitmap_data();
if (!pat) return;
agg::rendering_buffer buf(current_buffer_->raw_data(),current_buffer_->width(),current_buffer_->height(), current_buffer_->width() * 4);
pixfmt_type pixf(buf);
pixf.comp_op(static_cast<agg::comp_op_e>(sym.comp_op()));
renderer_base ren_base(pixf);
agg::pattern_filter_bilinear_rgba8 filter;
pattern_source source(*(*pat));
pattern_type pattern (filter,source);
renderer_type ren(ren_base, pattern);
rasterizer_type ras(ren);
agg::trans_affine tr;
evaluate_transform(tr, feature, sym.get_transform());
box2d<double> clipping_extent = query_extent_;
if (sym.clip())
{
double padding = (double)(query_extent_.width()/pixmap_.width());
double half_stroke = (*mark)->width()/2.0;
if (half_stroke > 1)
padding *= half_stroke;
if (fabs(sym.offset()) > 0)
padding *= fabs(sym.offset()) * 1.2;
padding *= scale_factor_;
clipping_extent.pad(padding);
}
typedef boost::mpl::vector<clip_line_tag,transform_tag,offset_transform_tag,simplify_tag,smooth_tag> conv_types;
vertex_converter<box2d<double>, rasterizer_type, line_pattern_symbolizer,
CoordTransform, proj_transform, agg::trans_affine, conv_types>
converter(clipping_extent,ras,sym,t_,prj_trans,tr,scale_factor_);
if (sym.clip()) converter.set<clip_line_tag>(); //optional clip (default: true)
converter.set<transform_tag>(); //always transform
if (sym.simplify_tolerance() > 0.0) converter.set<simplify_tag>(); // optional simplify converter
if (fabs(sym.offset()) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
if (sym.smooth() > 0.0) converter.set<smooth_tag>(); // optional smooth converter
BOOST_FOREACH(geometry_type & geom, feature.paths())
{
if (geom.size() > 1)
{
converter.apply(geom);
}
}
}
template void agg_renderer<image_32>::process(line_pattern_symbolizer const&,
mapnik::feature_impl &,
proj_transform const&);
}
<commit_msg>use std::fabs not fabs<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2011 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// mapnik
#include <mapnik/feature.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/graphics.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/agg_rasterizer.hpp>
#include <mapnik/agg_pattern_source.hpp>
#include <mapnik/marker.hpp>
#include <mapnik/marker_cache.hpp>
#include <mapnik/line_pattern_symbolizer.hpp>
#include <mapnik/vertex_converters.hpp>
#include <mapnik/noncopyable.hpp>
#include <mapnik/parse_path.hpp>
// agg
#include "agg_basics.h"
#include "agg_pixfmt_rgba.h"
#include "agg_color_rgba.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_outline.h"
#include "agg_rasterizer_outline_aa.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_pattern_filters_rgba.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_renderer_outline_image.h"
#include "agg_conv_clip_polyline.h"
// boost
#include <boost/foreach.hpp>
namespace {
class pattern_source : private mapnik::noncopyable
{
public:
pattern_source(mapnik::image_data_32 const& pattern)
: pattern_(pattern) {}
inline unsigned int width() const
{
return pattern_.width();
}
inline unsigned int height() const
{
return pattern_.height();
}
inline agg::rgba8 pixel(int x, int y) const
{
unsigned c = pattern_(x,y);
return agg::rgba8_pre(c & 0xff,
(c >> 8) & 0xff,
(c >> 16) & 0xff,
(c >> 24) & 0xff);
}
private:
mapnik::image_data_32 const& pattern_;
};
}
namespace mapnik {
template <typename T>
void agg_renderer<T>::process(line_pattern_symbolizer const& sym,
mapnik::feature_impl & feature,
proj_transform const& prj_trans)
{
typedef agg::rgba8 color;
typedef agg::order_rgba order;
typedef agg::comp_op_adaptor_rgba_pre<color, order> blender_type;
typedef agg::pattern_filter_bilinear_rgba8 pattern_filter_type;
typedef agg::line_image_pattern<pattern_filter_type> pattern_type;
typedef agg::pixfmt_custom_blend_rgba<blender_type, agg::rendering_buffer> pixfmt_type;
typedef agg::renderer_base<pixfmt_type> renderer_base;
typedef agg::renderer_outline_image<renderer_base, pattern_type> renderer_type;
typedef agg::rasterizer_outline_aa<renderer_type> rasterizer_type;
std::string filename = path_processor_type::evaluate( *sym.get_filename(), feature);
boost::optional<marker_ptr> mark = marker_cache::instance().find(filename,true);
if (!mark) return;
if (!(*mark)->is_bitmap())
{
MAPNIK_LOG_DEBUG(agg_renderer) << "agg_renderer: Only images (not '" << filename << "') are supported in the line_pattern_symbolizer";
return;
}
boost::optional<image_ptr> pat = (*mark)->get_bitmap_data();
if (!pat) return;
agg::rendering_buffer buf(current_buffer_->raw_data(),current_buffer_->width(),current_buffer_->height(), current_buffer_->width() * 4);
pixfmt_type pixf(buf);
pixf.comp_op(static_cast<agg::comp_op_e>(sym.comp_op()));
renderer_base ren_base(pixf);
agg::pattern_filter_bilinear_rgba8 filter;
pattern_source source(*(*pat));
pattern_type pattern (filter,source);
renderer_type ren(ren_base, pattern);
rasterizer_type ras(ren);
agg::trans_affine tr;
evaluate_transform(tr, feature, sym.get_transform());
box2d<double> clipping_extent = query_extent_;
if (sym.clip())
{
double padding = (double)(query_extent_.width()/pixmap_.width());
double half_stroke = (*mark)->width()/2.0;
if (half_stroke > 1)
padding *= half_stroke;
if (std::fabs(sym.offset()) > 0)
padding *= std::fabs(sym.offset()) * 1.2;
padding *= scale_factor_;
clipping_extent.pad(padding);
}
typedef boost::mpl::vector<clip_line_tag,transform_tag,offset_transform_tag,simplify_tag,smooth_tag> conv_types;
vertex_converter<box2d<double>, rasterizer_type, line_pattern_symbolizer,
CoordTransform, proj_transform, agg::trans_affine, conv_types>
converter(clipping_extent,ras,sym,t_,prj_trans,tr,scale_factor_);
if (sym.clip()) converter.set<clip_line_tag>(); //optional clip (default: true)
converter.set<transform_tag>(); //always transform
if (sym.simplify_tolerance() > 0.0) converter.set<simplify_tag>(); // optional simplify converter
if (std::fabs(sym.offset()) > 0.0) converter.set<offset_transform_tag>(); // parallel offset
if (sym.smooth() > 0.0) converter.set<smooth_tag>(); // optional smooth converter
BOOST_FOREACH(geometry_type & geom, feature.paths())
{
if (geom.size() > 1)
{
converter.apply(geom);
}
}
}
template void agg_renderer<image_32>::process(line_pattern_symbolizer const&,
mapnik::feature_impl &,
proj_transform const&);
}
<|endoftext|> |
<commit_before>//#include <cstdlib>
//#include <stdint.h> /* Standard types */
//#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
//#include <fcntl.h> /* File control definitions */
//#include <termios.h> /* POSIX terminal control definitions */
//#include <sys/ioctl.h>
//#include <getopt.h>
//#include <stdbool.h>
#include <cstdio> /* Standard input/output definitions */
#include <errno.h> /* Error number definitions */
//#include <time.h>
//#include <cmath>
//#include <iostream>
#include <assert.h>
#include "arduino_comm.h"
#include "arduino_readnum.h"
#define SERIALPORT "/dev/ttyUSB0"
#define BAUD B9600
int main(void){
char buffer[10] = {0};
char f[2] = "f";
char b[2] = "b";
char u[2] = "u";
int arduino_fd = serialport_init(SERIALPORT, BAUD);
assert(arduino_fd != -1);
printf("a short int is %u bytes long\n",sizeof(short int));
float xfer_f;
xfer_f = readFloat(arduino_fd, f, buffer);
printf("rec float: %f\n", xfer_f);
short int xfer_si;
xfer_si = readSint16(arduino_fd, b, buffer);
printf("rec sint16: %d\n", xfer_si);
unsigned short int xfer_usi;
xfer_usi = readUint16(arduino_fd, u, buffer);
printf("rec uint16: %d\n", xfer_usi);
}
<commit_msg>removed header<commit_after>#include <unistd.h> /* UNIX standard function definitions */
#include <cstdio> /* Standard input/output definitions */
#include <cassert>
#include "arduino_comm.h"
#include "arduino_readnum.h"
#define SERIALPORT "/dev/ttyUSB0"
#define BAUD B9600
int main(void){
char buffer[10] = {0};
char f[2] = "f";
char b[2] = "b";
char u[2] = "u";
int arduino_fd = serialport_init(SERIALPORT, BAUD);
assert(arduino_fd != -1);
printf("a short int is %u bytes long\n",sizeof(short int));
float xfer_f;
xfer_f = readFloat(arduino_fd, f, buffer);
printf("rec float: %f\n", xfer_f);
short int xfer_si;
xfer_si = readSint16(arduino_fd, b, buffer);
printf("rec sint16: %d\n", xfer_si);
unsigned short int xfer_usi;
xfer_usi = readUint16(arduino_fd, u, buffer);
printf("rec uint16: %d\n", xfer_usi);
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*
* $Id$
*
*/
#include <pcl/visualization/common/shapes.h>
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createCylinder (const pcl::ModelCoefficients &coefficients, int numsides)
{
vtkSmartPointer<vtkLineSource> line = vtkSmartPointer<vtkLineSource>::New ();
line->SetPoint1 (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
line->SetPoint2 (coefficients.values[3]+coefficients.values[0], coefficients.values[4]+coefficients.values[1], coefficients.values[5]+coefficients.values[2]);
vtkSmartPointer<vtkTubeFilter> tuber = vtkSmartPointer<vtkTubeFilter>::New ();
tuber->SetInputConnection (line->GetOutputPort ());
tuber->SetRadius (coefficients.values[6]);
tuber->SetNumberOfSides (numsides);
return (tuber->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createSphere (const pcl::ModelCoefficients &coefficients, int res)
{
// Set the sphere origin
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity (); t->Translate (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
vtkSmartPointer<vtkSphereSource> s_sphere = vtkSmartPointer<vtkSphereSource>::New ();
s_sphere->SetRadius (coefficients.values[3]);
s_sphere->SetPhiResolution (res);
s_sphere->SetThetaResolution (res);
s_sphere->LatLongTessellationOff ();
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (s_sphere->GetOutputPort ());
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createCube (const pcl::ModelCoefficients &coefficients)
{
// coefficients = [Tx, Ty, Tz, Qx, Qy, Qz, Qw, width, height, depth]
double theta = acos (coefficients.values[6]) * 2.0;
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity ();
if (sin (theta / 2.0) == 0.0)
t->Translate (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
else
{
double ax = coefficients.values[3] / sin (theta / 2.0);
double ay = coefficients.values[4] / sin (theta / 2.0);
double az = coefficients.values[5] / sin (theta / 2.0);
t->Translate (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
t->RotateWXYZ (theta, ax, ay, az);
}
vtkSmartPointer<vtkCubeSource> cube = vtkSmartPointer<vtkCubeSource>::New ();
cube->SetXLength (coefficients.values[7]);
cube->SetYLength (coefficients.values[8]);
cube->SetZLength (coefficients.values[9]);
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (cube->GetOutputPort ());
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createLine (const pcl::ModelCoefficients &coefficients)
{
vtkSmartPointer<vtkLineSource> line = vtkSmartPointer<vtkLineSource>::New ();
line->SetPoint1 (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
line->SetPoint2 (coefficients.values[3] + coefficients.values[0],
coefficients.values[4] + coefficients.values[1],
coefficients.values[5] + coefficients.values[2]);
line->Update ();
return (line->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createPlane (const pcl::ModelCoefficients &coefficients)
{
vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New ();
plane->SetNormal (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
double norm_sqr = coefficients.values[0] * coefficients.values[0]
+ coefficients.values[1] * coefficients.values[1]
+ coefficients.values[2] * coefficients.values[2];
plane->Push (-coefficients.values[3] / sqrt(norm_sqr));
return (plane->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::create2DCircle (const pcl::ModelCoefficients &coefficients, double z)
{
vtkSmartPointer<vtkDiskSource> disk = vtkSmartPointer<vtkDiskSource>::New ();
// Maybe the resolution should be lower e.g. 50 or 25
disk->SetCircumferentialResolution (100);
disk->SetInnerRadius (coefficients.values[2] - 0.001);
disk->SetOuterRadius (coefficients.values[2] + 0.001);
disk->SetCircumferentialResolution (20);
// An alternative to <vtkDiskSource> could be <vtkRegularPolygonSource> with <vtkTubeFilter>
/*
vtkSmartPointer<vtkRegularPolygonSource> circle = vtkSmartPointer<vtkRegularPolygonSource>::New();
circle->SetRadius (coefficients.values[2]);
circle->SetNumberOfSides (100);
vtkSmartPointer<vtkTubeFilter> tube = vtkSmartPointer<vtkTubeFilter>::New();
tube->SetInput (circle->GetOutput());
tube->SetNumberOfSides (25);
tube->SetRadius (0.001);
*/
// Set the circle origin
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity ();
t->Translate (coefficients.values[0], coefficients.values[1], z);
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (disk->GetOutputPort ());
/*
tf->SetInputConnection (tube->GetOutputPort ());
*/
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createCone (const pcl::ModelCoefficients &coefficients)
{
vtkSmartPointer<vtkConeSource> cone = vtkSmartPointer<vtkConeSource>::New ();
cone->SetHeight (1.0);
cone->SetCenter (coefficients.values[0] + coefficients.values[3] * 0.5,
coefficients.values[1] + coefficients.values[1] * 0.5,
coefficients.values[2] + coefficients.values[2] * 0.5);
cone->SetDirection (-coefficients.values[3], -coefficients.values[4], -coefficients.values[5]);
cone->SetResolution (100);
cone->SetAngle (coefficients.values[6]);
return (cone->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createSphere (const Eigen::Vector4f ¢er, double radius, int res)
{
// Set the sphere origin
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity ();
t->Translate (center[0], center[1], center[2]);
vtkSmartPointer<vtkSphereSource> s_sphere = vtkSmartPointer<vtkSphereSource>::New ();
s_sphere->SetRadius (radius);
s_sphere->SetPhiResolution (res);
s_sphere->SetThetaResolution (res);
s_sphere->LatLongTessellationOff ();
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (s_sphere->GetOutputPort ());
tf->Update ();
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createLine (const Eigen::Vector4f &pt1, const Eigen::Vector4f &pt2)
{
vtkSmartPointer<vtkLineSource> line = vtkSmartPointer<vtkLineSource>::New ();
line->SetPoint1 (pt1.x (), pt1.y (), pt1.z ());
line->SetPoint2 (pt2.x (), pt2.y (), pt2.z ());
line->Update ();
return (line->GetOutput ());
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::allocVtkUnstructuredGrid (vtkSmartPointer<vtkUnstructuredGrid> &polydata)
{
polydata = vtkSmartPointer<vtkUnstructuredGrid>::New ();
}
<commit_msg>use Eigen::AngleAxis to compute the arguments of RotateWXYZ<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE 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.
*
* $Id$
*
*/
#include <pcl/visualization/common/shapes.h>
#include <pcl/common/angles.h>
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createCylinder (const pcl::ModelCoefficients &coefficients, int numsides)
{
vtkSmartPointer<vtkLineSource> line = vtkSmartPointer<vtkLineSource>::New ();
line->SetPoint1 (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
line->SetPoint2 (coefficients.values[3]+coefficients.values[0], coefficients.values[4]+coefficients.values[1], coefficients.values[5]+coefficients.values[2]);
vtkSmartPointer<vtkTubeFilter> tuber = vtkSmartPointer<vtkTubeFilter>::New ();
tuber->SetInputConnection (line->GetOutputPort ());
tuber->SetRadius (coefficients.values[6]);
tuber->SetNumberOfSides (numsides);
return (tuber->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createSphere (const pcl::ModelCoefficients &coefficients, int res)
{
// Set the sphere origin
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity (); t->Translate (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
vtkSmartPointer<vtkSphereSource> s_sphere = vtkSmartPointer<vtkSphereSource>::New ();
s_sphere->SetRadius (coefficients.values[3]);
s_sphere->SetPhiResolution (res);
s_sphere->SetThetaResolution (res);
s_sphere->LatLongTessellationOff ();
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (s_sphere->GetOutputPort ());
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createCube (const pcl::ModelCoefficients &coefficients)
{
// coefficients = [Tx, Ty, Tz, Qx, Qy, Qz, Qw, width, height, depth]
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity ();
t->Translate (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
Eigen::AngleAxisf a (Eigen::Quaternionf (coefficients.values[6], coefficients.values[3],
coefficients.values[4], coefficients.values[5]));
t->RotateWXYZ (pcl::rad2deg (a.angle ()), a.axis ()[0], a.axis ()[1], a.axis ()[2]);
vtkSmartPointer<vtkCubeSource> cube = vtkSmartPointer<vtkCubeSource>::New ();
cube->SetXLength (coefficients.values[7]);
cube->SetYLength (coefficients.values[8]);
cube->SetZLength (coefficients.values[9]);
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (cube->GetOutputPort ());
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createLine (const pcl::ModelCoefficients &coefficients)
{
vtkSmartPointer<vtkLineSource> line = vtkSmartPointer<vtkLineSource>::New ();
line->SetPoint1 (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
line->SetPoint2 (coefficients.values[3] + coefficients.values[0],
coefficients.values[4] + coefficients.values[1],
coefficients.values[5] + coefficients.values[2]);
line->Update ();
return (line->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createPlane (const pcl::ModelCoefficients &coefficients)
{
vtkSmartPointer<vtkPlaneSource> plane = vtkSmartPointer<vtkPlaneSource>::New ();
plane->SetNormal (coefficients.values[0], coefficients.values[1], coefficients.values[2]);
double norm_sqr = coefficients.values[0] * coefficients.values[0]
+ coefficients.values[1] * coefficients.values[1]
+ coefficients.values[2] * coefficients.values[2];
plane->Push (-coefficients.values[3] / sqrt(norm_sqr));
return (plane->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::create2DCircle (const pcl::ModelCoefficients &coefficients, double z)
{
vtkSmartPointer<vtkDiskSource> disk = vtkSmartPointer<vtkDiskSource>::New ();
// Maybe the resolution should be lower e.g. 50 or 25
disk->SetCircumferentialResolution (100);
disk->SetInnerRadius (coefficients.values[2] - 0.001);
disk->SetOuterRadius (coefficients.values[2] + 0.001);
disk->SetCircumferentialResolution (20);
// An alternative to <vtkDiskSource> could be <vtkRegularPolygonSource> with <vtkTubeFilter>
/*
vtkSmartPointer<vtkRegularPolygonSource> circle = vtkSmartPointer<vtkRegularPolygonSource>::New();
circle->SetRadius (coefficients.values[2]);
circle->SetNumberOfSides (100);
vtkSmartPointer<vtkTubeFilter> tube = vtkSmartPointer<vtkTubeFilter>::New();
tube->SetInput (circle->GetOutput());
tube->SetNumberOfSides (25);
tube->SetRadius (0.001);
*/
// Set the circle origin
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity ();
t->Translate (coefficients.values[0], coefficients.values[1], z);
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (disk->GetOutputPort ());
/*
tf->SetInputConnection (tube->GetOutputPort ());
*/
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createCone (const pcl::ModelCoefficients &coefficients)
{
vtkSmartPointer<vtkConeSource> cone = vtkSmartPointer<vtkConeSource>::New ();
cone->SetHeight (1.0);
cone->SetCenter (coefficients.values[0] + coefficients.values[3] * 0.5,
coefficients.values[1] + coefficients.values[1] * 0.5,
coefficients.values[2] + coefficients.values[2] * 0.5);
cone->SetDirection (-coefficients.values[3], -coefficients.values[4], -coefficients.values[5]);
cone->SetResolution (100);
cone->SetAngle (coefficients.values[6]);
return (cone->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createSphere (const Eigen::Vector4f ¢er, double radius, int res)
{
// Set the sphere origin
vtkSmartPointer<vtkTransform> t = vtkSmartPointer<vtkTransform>::New ();
t->Identity ();
t->Translate (center[0], center[1], center[2]);
vtkSmartPointer<vtkSphereSource> s_sphere = vtkSmartPointer<vtkSphereSource>::New ();
s_sphere->SetRadius (radius);
s_sphere->SetPhiResolution (res);
s_sphere->SetThetaResolution (res);
s_sphere->LatLongTessellationOff ();
vtkSmartPointer<vtkTransformPolyDataFilter> tf = vtkSmartPointer<vtkTransformPolyDataFilter>::New ();
tf->SetTransform (t);
tf->SetInputConnection (s_sphere->GetOutputPort ());
tf->Update ();
return (tf->GetOutput ());
}
////////////////////////////////////////////////////////////////////////////////////////////
vtkSmartPointer<vtkDataSet>
pcl::visualization::createLine (const Eigen::Vector4f &pt1, const Eigen::Vector4f &pt2)
{
vtkSmartPointer<vtkLineSource> line = vtkSmartPointer<vtkLineSource>::New ();
line->SetPoint1 (pt1.x (), pt1.y (), pt1.z ());
line->SetPoint2 (pt2.x (), pt2.y (), pt2.z ());
line->Update ();
return (line->GetOutput ());
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl::visualization::allocVtkUnstructuredGrid (vtkSmartPointer<vtkUnstructuredGrid> &polydata)
{
polydata = vtkSmartPointer<vtkUnstructuredGrid>::New ();
}
<|endoftext|> |
<commit_before>// flagStay.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <map>
#include <cmath>
class FlagStayZoneHandler : public bz_CustomMapObjectHandler
{
public:
virtual bool MapObject ( bz_ApiString object, bz_CustomMapObjectInfo *data );
};
FlagStayZoneHandler flagStayZoneHandler;
class EventHandler : public bz_Plugin
{
public:
virtual const char* Name (){return "Flag Stay Zones";}
virtual void Init ( const char* cl );
virtual void Cleanup ();
virtual void Event ( bz_EventData *eventData );
};
BZ_PLUGIN(EventHandler)
void EventHandler::Init ( const char* /*commandLine*/ )
{
bz_registerCustomMapObject("FLAGSTAYZONE",&flagStayZoneHandler);
Register(bz_ePlayerUpdateEvent);
}
void EventHandler::Cleanup ( void )
{
Flush();
bz_removeCustomMapObject("FLAGSTAYZONE");
}
class FlagStayZone
{
public:
FlagStayZone()
{
box = false;
xMax = xMin = yMax = yMin = zMax = zMin = rad = rot = 0;
}
bool box;
float xMax,xMin,yMax,yMin,zMax,zMin;
float rad, rot;
std::string message;
bool pointIn ( float pos[3] )
{
if ( box )
{
if (rot == 0 || rot == 180)
{
if ( pos[0] > xMax || pos[0] < xMin ) return false;
if ( pos[1] > yMax || pos[1] < yMin ) return false;
}
else if (rot == 90 || rot == 270)
{
if ( pos[1] > xMax || pos[1] < xMin ) return false;
if ( pos[0] > yMax || pos[0] < yMin ) return false;
}
else // the box is rotated, maths is needed
{
float pi = (float)(atan(1) * 4);
float rotRad = (rot * pi) / 180;
float height = (yMax - yMin);
float width = (xMax - xMin);
// Center of the rectangle, we can treat this as the "fake" origin
float cX = (xMax + xMin) / 2;
float cY = (yMax + yMin) / 2;
// Coordinates of original and rotated shape
float oX[4], oY[4], rX[4], rY[4];
// Coordinates for the original rectangle
oX[0] = xMin - cX; oY[0] = yMax - cY;
oX[1] = xMax - cX; oY[1] = yMax - cY;
oX[2] = xMax - cX; oY[2] = yMin - cY;
oX[3] = xMin - cX; oY[3] = yMin - cY;
// Coordinates for the rotated rectangle
rX[0] = (float)(oX[0] * cos(rotRad) - oY[0] * sin(rotRad)); rY[0] = (float)(oX[0] * sin(rotRad) + oY[0] * cos(rotRad));
rX[1] = (float)(oX[1] * cos(rotRad) - oY[1] * sin(rotRad)); rY[1] = (float)(oX[1] * sin(rotRad) + oY[1] * cos(rotRad));
rX[2] = (float)(oX[2] * cos(rotRad) - oY[2] * sin(rotRad)); rY[2] = (float)(oX[2] * sin(rotRad) + oY[2] * cos(rotRad));
rX[3] = (float)(oX[3] * cos(rotRad) - oY[3] * sin(rotRad)); rY[3] = (float)(oX[3] * sin(rotRad) + oY[3] * cos(rotRad));
// Coordinates of player relative to the "fake" origin
float pX = pos[0] - cX;
float pY = pos[1] - cY;
// Get the areas of all triangles that use the rectangle coordinates and player coordinate
float apd = triangleSum(rX[0], pX, rX[3], rY[0], pY, rY[3]);
float apb = triangleSum(rX[0], pX, rX[1], rY[0], pY, rY[1]);
float dpc = triangleSum(rX[3], pX, rX[2], rY[3], pY, rY[2]);
float bpc = triangleSum(rX[2], pX, rX[1], rY[2], pY, rY[1]);
// If the area of all the triangles summed together is greater than the area of the rectangle, the point is outside
if (apd + dpc + bpc + apb > (width * height)) return false;
}
}
else
{
float vec[3];
vec[0] = pos[0]-xMax;
vec[1] = pos[1]-yMax;
vec[2] = pos[2]-zMax;
float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]);
if ( dist > rad) return false;
}
return !(pos[2] > zMax || pos[2] < zMin);
}
bool checkFlag ( const char* flag )
{
for ( unsigned int i = 0; i < flagList.size(); i++ )
{
if ( flagList[i] == flag )
return true;
}
return false;
}
std::vector<std::string> flagList;
private:
float triangleSum(float x1, float x2, float x3, float y1, float y2, float y3)
{
return abs(((x1 * y2) + (x2 * y3) + (x3 * y1) - (y1 * x2) - (y2 * x3) - (y3 * x1))/2);
}
};
std::vector <FlagStayZone> zoneList;
bool FlagStayZoneHandler::MapObject ( bz_ApiString object, bz_CustomMapObjectInfo *data )
{
if (object != "FLAGSTAYZONE" || !data)
return false;
FlagStayZone newZone;
// Temporary placeholders for information with default values just in case
float pos[3] = {0,0,0}, size[3] = {5,5,5}, radius = 5, height = 5, rot = 0;
// parse all the chunks
for ( unsigned int i = 0; i < data->data.size(); i++ )
{
std::string line = data->data.get(i).c_str();
bz_APIStringList *nubs = bz_newStringList();
nubs->tokenize(line.c_str()," ",0,true);
if ( nubs->size() > 0)
{
std::string key = bz_toupper(nubs->get(0).c_str());
// @TODO Possibly deprecate 'BBOX' and 'Cylinder' in favor of having the code do the calculations and in favor of staying consistent with other map objects
if ( key == "BBOX" && nubs->size() > 6)
{
newZone.box = true;
newZone.xMin = (float)atof(nubs->get(1).c_str());
newZone.xMax = (float)atof(nubs->get(2).c_str());
newZone.yMin = (float)atof(nubs->get(3).c_str());
newZone.yMax = (float)atof(nubs->get(4).c_str());
newZone.zMin = (float)atof(nubs->get(5).c_str());
newZone.zMax = (float)atof(nubs->get(6).c_str());
}
else if ( key == "CYLINDER" && nubs->size() > 5)
{
newZone.box = false;
newZone.rad = (float)atof(nubs->get(5).c_str());
newZone.xMax =(float)atof(nubs->get(1).c_str());
newZone.yMax =(float)atof(nubs->get(2).c_str());
newZone.zMin =(float)atof(nubs->get(3).c_str());
newZone.zMax =(float)atof(nubs->get(4).c_str());
}
else if ((key == "POSITION" || key == "POS") && nubs->size() > 3)
{
pos[0] = {(float)atof(nubs->get(1).c_str())};
pos[1] = {(float)atof(nubs->get(2).c_str())};
pos[2] = {(float)atof(nubs->get(3).c_str())};
}
else if (key == "SIZE" && nubs->size() > 3)
{
newZone.box = true;
size[0] = {(float)atof(nubs->get(1).c_str())};
size[1] = {(float)atof(nubs->get(2).c_str())};
size[2] = {(float)atof(nubs->get(3).c_str())};
}
else if ((key == "ROTATION" || key == "ROT") && nubs->size() > 1)
{
rot = (float)atof(nubs->get(1).c_str());
}
else if ((key == "RADIUS" || key == "RAD") && nubs->size() > 1)
{
newZone.box = false;
radius = (float)atof(nubs->get(1).c_str());
}
else if (key == "HEIGHT" && nubs->size() > 1)
{
height = (float)atof(nubs->get(1).c_str());
}
else if ( key == "FLAG" && nubs->size() > 1)
{
std::string flag = bz_toupper(nubs->get(1).c_str());
newZone.flagList.push_back(flag);
}
else if ( key == "MESSAGE" && nubs->size() > 1 )
{
newZone.message = nubs->get(1).c_str();
}
}
bz_deleteStringList(nubs);
}
if (newZone.box)
{
newZone.xMin = pos[0] - size[0];
newZone.xMax = pos[0] + size[0];
newZone.yMin = pos[1] - size[1];
newZone.yMax = pos[1] + size[1];
newZone.zMin = pos[2];
newZone.zMax = pos[2] + size[2];
newZone.rot = (rot > 0 && rot < 360) ? rot : 0;
}
else
{
newZone.rad = radius;
newZone.xMax = pos[0];
newZone.yMax = pos[1];
newZone.zMin = pos[2];
newZone.zMax = pos[2] + height;
}
zoneList.push_back(newZone);
return true;
}
std::map<int,int> playerIDToZoneMap;
void EventHandler::Event ( bz_EventData *eventData )
{
float pos[3] = {0};
int playerID = -1;
switch (eventData->eventType)
{
case bz_ePlayerUpdateEvent:
pos[0] = ((bz_PlayerUpdateEventData_V1*)eventData)->state.pos[0];
pos[1] = ((bz_PlayerUpdateEventData_V1*)eventData)->state.pos[1];
pos[2] = ((bz_PlayerUpdateEventData_V1*)eventData)->state.pos[2];
playerID = ((bz_PlayerUpdateEventData_V1*)eventData)->playerID;
break;
case bz_eShotFiredEvent:
pos[0] = ((bz_ShotFiredEventData_V1*)eventData)->pos[0];
pos[1] = ((bz_ShotFiredEventData_V1*)eventData)->pos[1];
pos[2] = ((bz_ShotFiredEventData_V1*)eventData)->pos[2];
playerID = ((bz_ShotFiredEventData_V1*)eventData)->playerID;
break;
default:
return;
}
const char* flagAbrev = bz_getPlayerFlag(playerID);
if (!flagAbrev)
return;
std::vector<FlagStayZone*> validZones;
// check and see if a zone cares about the current flag
for ( unsigned int i = 0; i < zoneList.size(); i++ )
{
if ( zoneList[i].checkFlag(flagAbrev) )
validZones.push_back(&zoneList[i]);
}
// Check each zone for this flag to see if we are in one
bool insideOne = false;
for ( unsigned int i = 0; i < validZones.size(); i++ )
{
if ( validZones[i]->pointIn(pos) )
{
insideOne = true;
playerIDToZoneMap[playerID] = i;
}
}
// if they have taken the flag out of a zone, pop it.
if (!insideOne && validZones.size() > 0)
{
int lastZone = -1;
if ( playerIDToZoneMap.find(playerID) != playerIDToZoneMap.end() )
lastZone = playerIDToZoneMap[playerID];
bz_removePlayerFlag(playerID);
if (lastZone != -1 && zoneList[lastZone].message.size())
bz_sendTextMessage(BZ_SERVER,playerID,zoneList[lastZone].message.c_str());
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Removed C++11 braces to avoid narrowing conversions; Converted spaces to tabs<commit_after>// flagStay.cpp : Defines the entry point for the DLL application.
//
#include "bzfsAPI.h"
#include <map>
#include <cmath>
class FlagStayZoneHandler : public bz_CustomMapObjectHandler
{
public:
virtual bool MapObject ( bz_ApiString object, bz_CustomMapObjectInfo *data );
};
FlagStayZoneHandler flagStayZoneHandler;
class EventHandler : public bz_Plugin
{
public:
virtual const char* Name (){return "Flag Stay Zones";}
virtual void Init ( const char* cl );
virtual void Cleanup ();
virtual void Event ( bz_EventData *eventData );
};
BZ_PLUGIN(EventHandler)
void EventHandler::Init ( const char* /*commandLine*/ )
{
bz_registerCustomMapObject("FLAGSTAYZONE",&flagStayZoneHandler);
Register(bz_ePlayerUpdateEvent);
}
void EventHandler::Cleanup ( void )
{
Flush();
bz_removeCustomMapObject("FLAGSTAYZONE");
}
class FlagStayZone
{
public:
FlagStayZone()
{
box = false;
xMax = xMin = yMax = yMin = zMax = zMin = rad = rot = 0;
}
bool box;
float xMax,xMin,yMax,yMin,zMax,zMin;
float rad, rot;
std::string message;
bool pointIn ( float pos[3] )
{
if ( box )
{
if (rot == 0 || rot == 180)
{
if ( pos[0] > xMax || pos[0] < xMin ) return false;
if ( pos[1] > yMax || pos[1] < yMin ) return false;
}
else if (rot == 90 || rot == 270)
{
if ( pos[1] > xMax || pos[1] < xMin ) return false;
if ( pos[0] > yMax || pos[0] < yMin ) return false;
}
else // the box is rotated, maths is needed
{
float pi = (float)(atan(1) * 4);
float rotRad = (rot * pi) / 180;
float height = (yMax - yMin);
float width = (xMax - xMin);
// Center of the rectangle, we can treat this as the "fake" origin
float cX = (xMax + xMin) / 2;
float cY = (yMax + yMin) / 2;
// Coordinates of original and rotated shape
float oX[4], oY[4], rX[4], rY[4];
// Coordinates for the original rectangle
oX[0] = xMin - cX; oY[0] = yMax - cY;
oX[1] = xMax - cX; oY[1] = yMax - cY;
oX[2] = xMax - cX; oY[2] = yMin - cY;
oX[3] = xMin - cX; oY[3] = yMin - cY;
// Coordinates for the rotated rectangle
rX[0] = (float)(oX[0] * cos(rotRad) - oY[0] * sin(rotRad)); rY[0] = (float)(oX[0] * sin(rotRad) + oY[0] * cos(rotRad));
rX[1] = (float)(oX[1] * cos(rotRad) - oY[1] * sin(rotRad)); rY[1] = (float)(oX[1] * sin(rotRad) + oY[1] * cos(rotRad));
rX[2] = (float)(oX[2] * cos(rotRad) - oY[2] * sin(rotRad)); rY[2] = (float)(oX[2] * sin(rotRad) + oY[2] * cos(rotRad));
rX[3] = (float)(oX[3] * cos(rotRad) - oY[3] * sin(rotRad)); rY[3] = (float)(oX[3] * sin(rotRad) + oY[3] * cos(rotRad));
// Coordinates of player relative to the "fake" origin
float pX = pos[0] - cX;
float pY = pos[1] - cY;
// Get the areas of all triangles that use the rectangle coordinates and player coordinate
float apd = triangleSum(rX[0], pX, rX[3], rY[0], pY, rY[3]);
float apb = triangleSum(rX[0], pX, rX[1], rY[0], pY, rY[1]);
float dpc = triangleSum(rX[3], pX, rX[2], rY[3], pY, rY[2]);
float bpc = triangleSum(rX[2], pX, rX[1], rY[2], pY, rY[1]);
// If the area of all the triangles summed together is greater than the area of the rectangle, the point is outside
if (apd + dpc + bpc + apb > (width * height)) return false;
}
}
else
{
float vec[3];
vec[0] = pos[0]-xMax;
vec[1] = pos[1]-yMax;
vec[2] = pos[2]-zMax;
float dist = sqrt(vec[0]*vec[0]+vec[1]*vec[1]);
if ( dist > rad) return false;
}
return !(pos[2] > zMax || pos[2] < zMin);
}
bool checkFlag ( const char* flag )
{
for ( unsigned int i = 0; i < flagList.size(); i++ )
{
if ( flagList[i] == flag )
return true;
}
return false;
}
std::vector<std::string> flagList;
private:
float triangleSum(float x1, float x2, float x3, float y1, float y2, float y3)
{
return abs(((x1 * y2) + (x2 * y3) + (x3 * y1) - (y1 * x2) - (y2 * x3) - (y3 * x1))/2);
}
};
std::vector <FlagStayZone> zoneList;
bool FlagStayZoneHandler::MapObject ( bz_ApiString object, bz_CustomMapObjectInfo *data )
{
if (object != "FLAGSTAYZONE" || !data)
return false;
FlagStayZone newZone;
// Temporary placeholders for information with default values just in case
float pos[3] = {0,0,0}, size[3] = {5,5,5}, radius = 5, height = 5, rot = 0;
// parse all the chunks
for ( unsigned int i = 0; i < data->data.size(); i++ )
{
std::string line = data->data.get(i).c_str();
bz_APIStringList *nubs = bz_newStringList();
nubs->tokenize(line.c_str()," ",0,true);
if ( nubs->size() > 0)
{
std::string key = bz_toupper(nubs->get(0).c_str());
// @TODO Possibly deprecate 'BBOX' and 'Cylinder' in favor of having the code do the calculations and in favor of staying consistent with other map objects
if ( key == "BBOX" && nubs->size() > 6)
{
newZone.box = true;
newZone.xMin = (float)atof(nubs->get(1).c_str());
newZone.xMax = (float)atof(nubs->get(2).c_str());
newZone.yMin = (float)atof(nubs->get(3).c_str());
newZone.yMax = (float)atof(nubs->get(4).c_str());
newZone.zMin = (float)atof(nubs->get(5).c_str());
newZone.zMax = (float)atof(nubs->get(6).c_str());
}
else if ( key == "CYLINDER" && nubs->size() > 5)
{
newZone.box = false;
newZone.rad = (float)atof(nubs->get(5).c_str());
newZone.xMax =(float)atof(nubs->get(1).c_str());
newZone.yMax =(float)atof(nubs->get(2).c_str());
newZone.zMin =(float)atof(nubs->get(3).c_str());
newZone.zMax =(float)atof(nubs->get(4).c_str());
}
else if ((key == "POSITION" || key == "POS") && nubs->size() > 3)
{
pos[0] = (float)atof(nubs->get(1).c_str());
pos[1] = (float)atof(nubs->get(2).c_str());
pos[2] = (float)atof(nubs->get(3).c_str());
}
else if (key == "SIZE" && nubs->size() > 3)
{
newZone.box = true;
size[0] = (float)atof(nubs->get(1).c_str());
size[1] = (float)atof(nubs->get(2).c_str());
size[2] = (float)atof(nubs->get(3).c_str());
}
else if ((key == "ROTATION" || key == "ROT") && nubs->size() > 1)
{
rot = (float)atof(nubs->get(1).c_str());
}
else if ((key == "RADIUS" || key == "RAD") && nubs->size() > 1)
{
newZone.box = false;
radius = (float)atof(nubs->get(1).c_str());
}
else if (key == "HEIGHT" && nubs->size() > 1)
{
height = (float)atof(nubs->get(1).c_str());
}
else if ( key == "FLAG" && nubs->size() > 1)
{
std::string flag = bz_toupper(nubs->get(1).c_str());
newZone.flagList.push_back(flag);
}
else if ( key == "MESSAGE" && nubs->size() > 1 )
{
newZone.message = nubs->get(1).c_str();
}
}
bz_deleteStringList(nubs);
}
if (newZone.box)
{
newZone.xMin = pos[0] - size[0];
newZone.xMax = pos[0] + size[0];
newZone.yMin = pos[1] - size[1];
newZone.yMax = pos[1] + size[1];
newZone.zMin = pos[2];
newZone.zMax = pos[2] + size[2];
newZone.rot = (rot > 0 && rot < 360) ? rot : 0;
}
else
{
newZone.rad = radius;
newZone.xMax = pos[0];
newZone.yMax = pos[1];
newZone.zMin = pos[2];
newZone.zMax = pos[2] + height;
}
zoneList.push_back(newZone);
return true;
}
std::map<int,int> playerIDToZoneMap;
void EventHandler::Event ( bz_EventData *eventData )
{
float pos[3] = {0};
int playerID = -1;
switch (eventData->eventType)
{
case bz_ePlayerUpdateEvent:
pos[0] = ((bz_PlayerUpdateEventData_V1*)eventData)->state.pos[0];
pos[1] = ((bz_PlayerUpdateEventData_V1*)eventData)->state.pos[1];
pos[2] = ((bz_PlayerUpdateEventData_V1*)eventData)->state.pos[2];
playerID = ((bz_PlayerUpdateEventData_V1*)eventData)->playerID;
break;
case bz_eShotFiredEvent:
pos[0] = ((bz_ShotFiredEventData_V1*)eventData)->pos[0];
pos[1] = ((bz_ShotFiredEventData_V1*)eventData)->pos[1];
pos[2] = ((bz_ShotFiredEventData_V1*)eventData)->pos[2];
playerID = ((bz_ShotFiredEventData_V1*)eventData)->playerID;
break;
default:
return;
}
const char* flagAbrev = bz_getPlayerFlag(playerID);
if (!flagAbrev)
return;
std::vector<FlagStayZone*> validZones;
// check and see if a zone cares about the current flag
for ( unsigned int i = 0; i < zoneList.size(); i++ )
{
if ( zoneList[i].checkFlag(flagAbrev) )
validZones.push_back(&zoneList[i]);
}
// Check each zone for this flag to see if we are in one
bool insideOne = false;
for ( unsigned int i = 0; i < validZones.size(); i++ )
{
if ( validZones[i]->pointIn(pos) )
{
insideOne = true;
playerIDToZoneMap[playerID] = i;
}
}
// if they have taken the flag out of a zone, pop it.
if (!insideOne && validZones.size() > 0)
{
int lastZone = -1;
if ( playerIDToZoneMap.find(playerID) != playerIDToZoneMap.end() )
lastZone = playerIDToZoneMap[playerID];
bz_removePlayerFlag(playerID);
if (lastZone != -1 && zoneList[lastZone].message.size())
bz_sendTextMessage(BZ_SERVER,playerID,zoneList[lastZone].message.c_str());
}
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "KristalliProtocolModule.h"
#include "KristalliProtocolModuleEvents.h"
#include "Profiler.h"
#include "EventManager.h"
#include "CoreStringUtils.h"
#include <algorithm>
using namespace kNet;
namespace KristalliProtocol
{
namespace
{
const std::string moduleName("KristalliProtocolModule");
/*
const struct
{
SocketTransportLayer transport;
int portNumber;
} destinationPorts[] =
{
{ SocketOverUDP, 2345 }, // The default Kristalli over UDP port.
{ SocketOverTCP, 2345 }, // The default Kristalli over TCP port.
{ SocketOverUDP, 123 }, // Network Time Protocol.
{ SocketOverTCP, 80 }, // HTTP.
{ SocketOverTCP, 443 }, // HTTPS.
{ SocketOverTCP, 20 }, // FTP Data.
{ SocketOverTCP, 21 }, // FTP Control.
{ SocketOverTCP, 22 }, // SSH.
{ SocketOverTCP, 23 }, // TELNET.
{ SocketOverUDP, 25 }, // SMTP. (Microsoft)
{ SocketOverTCP, 25 }, // SMTP.
{ SocketOverTCP, 110 }, // POP3 Server listen port.
{ SocketOverTCP, 995 }, // POP3 over SSL.
{ SocketOverTCP, 109 }, // POP2.
{ SocketOverTCP, 6667 }, // IRC.
// For more info on the following windows ports, see: http://support.microsoft.com/kb/832017
{ SocketOverTCP, 135 }, // Windows RPC.
{ SocketOverUDP, 137 }, // Windows Cluster Administrator. / NetBIOS Name Resolution.
{ SocketOverUDP, 138 }, // Windows NetBIOS Datagram Service.
{ SocketOverTCP, 139 }, // Windows NetBIOS Session Service.
{ SocketOverUDP, 389 }, // Windows LDAP Server.
{ SocketOverTCP, 389 }, // Windows LDAP Server.
{ SocketOverTCP, 445 }, // Windows SMB.
{ SocketOverTCP, 5722 }, // Windows RPC.
{ SocketOverTCP, 993 }, // IMAP over SSL.
// { SocketOverTCP, 1433 }, // SQL over TCP.
// { SocketOverUDP, 1434 }, // SQL over UDP.
{ SocketOverUDP, 53 }, // DNS.
{ SocketOverTCP, 53 }, // DNS. Microsoft states it uses TCP 53 for DNS as well.
{ SocketOverUDP, 161 }, // SNMP agent port.
{ SocketOverUDP, 162 }, // SNMP manager port.
{ SocketOverUDP, 520 }, // RIP.
{ SocketOverUDP, 67 }, // DHCP client->server.
{ SocketOverUDP, 68 }, // DHCP server->client.
};
/// The number of different port choices to try from the list.
const int cNumPortChoices = sizeof(destinationPorts) / sizeof(destinationPorts[0]);
*/
}
static const int cInitialAttempts = 1;
static const int cReconnectAttempts = 5;
KristalliProtocolModule::KristalliProtocolModule()
:IModule(NameStatic())
, serverConnection(0)
, server(0)
, reconnectAttempts(0)
{
}
KristalliProtocolModule::~KristalliProtocolModule()
{
Disconnect();
}
void KristalliProtocolModule::Load()
{
}
void KristalliProtocolModule::Unload()
{
Disconnect();
}
void KristalliProtocolModule::PreInitialize()
{
}
void KristalliProtocolModule::Initialize()
{
Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
networkEventCategory = event_manager->RegisterEventCategory("Kristalli");
event_manager->RegisterEvent(networkEventCategory, Events::NETMESSAGE_IN, "NetMessageIn");
}
void KristalliProtocolModule::PostInitialize()
{
}
void KristalliProtocolModule::Uninitialize()
{
Disconnect();
}
void KristalliProtocolModule::Update(f64 frametime)
{
// Pulls all new inbound network messages and calls the message handler we've registered
// for each of them.
if (serverConnection)
serverConnection->ProcessMessages();
// Process server incoming connections & messages if server up
if (server)
server->ProcessMessages();
if ((!serverConnection || serverConnection->GetConnectionState() == ConnectionClosed || serverConnection->GetConnectionState() == ConnectionPending) && serverIp.length() != 0)
{
const int cReconnectTimeout = 5 * 1000.f;
if (reconnectTimer.Test())
{
if (reconnectAttempts)
{
PerformConnection();
--reconnectAttempts;
}
else
{
LogInfo("Failed to connect to " + serverIp + ":" + ToString(serverPort));
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::CONNECTION_FAILED, 0);
reconnectTimer.Stop();
serverIp = "";
}
}
else if (!reconnectTimer.Enabled())
reconnectTimer.StartMSecs(cReconnectTimeout);
}
// If connection was made, enable a larger number of reconnection attempts in case it gets lost
if (serverConnection && serverConnection->GetConnectionState() == ConnectionOK)
reconnectAttempts = cReconnectAttempts;
RESETPROFILER;
}
const std::string &KristalliProtocolModule::NameStatic()
{
return moduleName;
}
void KristalliProtocolModule::Connect(const char *ip, unsigned short port, SocketTransportLayer transport)
{
if (Connected() && serverConnection && serverConnection->GetEndPoint().ToString() != serverIp)
Disconnect();
serverIp = ip;
serverPort = port;
serverTransport = transport;
reconnectAttempts = cInitialAttempts; // Initial attempts when establishing connection
if (!Connected())
PerformConnection(); // Start performing a connection attempt to the desired address/port/transport
}
void KristalliProtocolModule::PerformConnection()
{
if (Connected() && serverConnection)
{
serverConnection->Close();
// network.CloseMessageConnection(serverConnection);
serverConnection = 0;
}
// Connect to the server.
serverConnection = network.Connect(serverIp.c_str(), serverPort, serverTransport, this);
if (!serverConnection)
{
LogError("Unable to connect to " + serverIp + ":" + ToString(serverPort));
return;
}
}
void KristalliProtocolModule::Disconnect()
{
if (serverConnection)
{
serverConnection->Disconnect();
// network.CloseMessageConnection(serverConnection);
///\todo Wait? This closes the connection.
serverConnection = 0;
}
// Clear the remembered destination server ip address so that the automatic connection timer will not try to reconnect.
serverIp = "";
reconnectTimer.Stop();
}
bool KristalliProtocolModule::StartServer(unsigned short port, SocketTransportLayer transport)
{
StopServer();
server = network.StartServer(port, transport, this);
if (!server)
{
LogError("Failed to start server on port " + ToString((int)port));
return false;
}
LogInfo("Started server on port " + ToString((int)port));
return true;
}
void KristalliProtocolModule::StopServer()
{
if (server)
{
network.StopServer();
connections.clear();
LogInfo("Stopped server");
server = 0;
}
}
void KristalliProtocolModule::NewConnectionEstablished(kNet::MessageConnection *source)
{
source->RegisterInboundMessageHandler(this);
///\todo Regression. Re-enable. -jj.
// source->SetDatagramInFlowRatePerSecond(200);
UserConnection connection;
connection.userID = AllocateNewConnectionID();
connection.connection = source;
connections.push_back(connection);
LogInfo("User connected from " + source->GetEndPoint().ToString() + ", connection ID " + ToString((int)connection.userID));
Events::KristalliUserConnected msg(&connection);
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_CONNECTED, &msg);
}
void KristalliProtocolModule::ClientDisconnected(MessageConnection *source)
{
// Delete from connection list if it was a known user
for(UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->connection == source)
{
Events::KristalliUserDisconnected msg(&(*iter));
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_DISCONNECTED, &msg);
connections.erase(iter);
LogInfo("User disconnected, connection ID " + ToString((int)iter->userID));
return;
}
}
LogInfo("Unknown user disconnected");
}
void KristalliProtocolModule::HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes)
{
assert(source);
assert(data);
try
{
Events::KristalliNetMessageIn msg(source, id, data, numBytes);
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::NETMESSAGE_IN, &msg);
} catch(std::exception &e)
{
LogError("KristalliProtocolModule: Exception \"" + std::string(e.what()) + "\" thrown when handling network message id " + ToString(id) + " size " + ToString((int)numBytes) + " from client "
+ source->ToString());
}
}
bool KristalliProtocolModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data)
{
return false;
}
u8 KristalliProtocolModule::AllocateNewConnectionID() const
{
u8 newID = 1;
for(UserConnectionList::const_iterator iter = connections.begin(); iter != connections.end(); ++iter)
newID = std::max((int)newID, (int)(iter->userID+1));
return newID;
}
UserConnection* KristalliProtocolModule::GetUserConnection(MessageConnection* source)
{
for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->connection == source)
return &(*iter);
}
return 0;
}
UserConnection* KristalliProtocolModule::GetUserConnection(u8 id)
{
for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->userID == id)
return &(*iter);
}
return 0;
}
UserConnectionList KristalliProtocolModule::GetAuthenticatedUsers() const
{
UserConnectionList ret;
for (UserConnectionList::const_iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->authenticated)
ret.push_back(*iter);
}
return ret;
}
} // ~KristalliProtocolModule namespace
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
using namespace KristalliProtocol;
POCO_BEGIN_MANIFEST(IModule)
POCO_EXPORT_CLASS(KristalliProtocolModule)
POCO_END_MANIFEST
<commit_msg>Fix crash: erase iterator after log print which uses the iterator.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "KristalliProtocolModule.h"
#include "KristalliProtocolModuleEvents.h"
#include "Profiler.h"
#include "EventManager.h"
#include "CoreStringUtils.h"
#include <algorithm>
using namespace kNet;
namespace KristalliProtocol
{
namespace
{
const std::string moduleName("KristalliProtocolModule");
/*
const struct
{
SocketTransportLayer transport;
int portNumber;
} destinationPorts[] =
{
{ SocketOverUDP, 2345 }, // The default Kristalli over UDP port.
{ SocketOverTCP, 2345 }, // The default Kristalli over TCP port.
{ SocketOverUDP, 123 }, // Network Time Protocol.
{ SocketOverTCP, 80 }, // HTTP.
{ SocketOverTCP, 443 }, // HTTPS.
{ SocketOverTCP, 20 }, // FTP Data.
{ SocketOverTCP, 21 }, // FTP Control.
{ SocketOverTCP, 22 }, // SSH.
{ SocketOverTCP, 23 }, // TELNET.
{ SocketOverUDP, 25 }, // SMTP. (Microsoft)
{ SocketOverTCP, 25 }, // SMTP.
{ SocketOverTCP, 110 }, // POP3 Server listen port.
{ SocketOverTCP, 995 }, // POP3 over SSL.
{ SocketOverTCP, 109 }, // POP2.
{ SocketOverTCP, 6667 }, // IRC.
// For more info on the following windows ports, see: http://support.microsoft.com/kb/832017
{ SocketOverTCP, 135 }, // Windows RPC.
{ SocketOverUDP, 137 }, // Windows Cluster Administrator. / NetBIOS Name Resolution.
{ SocketOverUDP, 138 }, // Windows NetBIOS Datagram Service.
{ SocketOverTCP, 139 }, // Windows NetBIOS Session Service.
{ SocketOverUDP, 389 }, // Windows LDAP Server.
{ SocketOverTCP, 389 }, // Windows LDAP Server.
{ SocketOverTCP, 445 }, // Windows SMB.
{ SocketOverTCP, 5722 }, // Windows RPC.
{ SocketOverTCP, 993 }, // IMAP over SSL.
// { SocketOverTCP, 1433 }, // SQL over TCP.
// { SocketOverUDP, 1434 }, // SQL over UDP.
{ SocketOverUDP, 53 }, // DNS.
{ SocketOverTCP, 53 }, // DNS. Microsoft states it uses TCP 53 for DNS as well.
{ SocketOverUDP, 161 }, // SNMP agent port.
{ SocketOverUDP, 162 }, // SNMP manager port.
{ SocketOverUDP, 520 }, // RIP.
{ SocketOverUDP, 67 }, // DHCP client->server.
{ SocketOverUDP, 68 }, // DHCP server->client.
};
/// The number of different port choices to try from the list.
const int cNumPortChoices = sizeof(destinationPorts) / sizeof(destinationPorts[0]);
*/
}
static const int cInitialAttempts = 1;
static const int cReconnectAttempts = 5;
KristalliProtocolModule::KristalliProtocolModule()
:IModule(NameStatic())
, serverConnection(0)
, server(0)
, reconnectAttempts(0)
{
}
KristalliProtocolModule::~KristalliProtocolModule()
{
Disconnect();
}
void KristalliProtocolModule::Load()
{
}
void KristalliProtocolModule::Unload()
{
Disconnect();
}
void KristalliProtocolModule::PreInitialize()
{
}
void KristalliProtocolModule::Initialize()
{
Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
networkEventCategory = event_manager->RegisterEventCategory("Kristalli");
event_manager->RegisterEvent(networkEventCategory, Events::NETMESSAGE_IN, "NetMessageIn");
}
void KristalliProtocolModule::PostInitialize()
{
}
void KristalliProtocolModule::Uninitialize()
{
Disconnect();
}
void KristalliProtocolModule::Update(f64 frametime)
{
// Pulls all new inbound network messages and calls the message handler we've registered
// for each of them.
if (serverConnection)
serverConnection->ProcessMessages();
// Process server incoming connections & messages if server up
if (server)
server->ProcessMessages();
if ((!serverConnection || serverConnection->GetConnectionState() == ConnectionClosed || serverConnection->GetConnectionState() == ConnectionPending) && serverIp.length() != 0)
{
const int cReconnectTimeout = 5 * 1000.f;
if (reconnectTimer.Test())
{
if (reconnectAttempts)
{
PerformConnection();
--reconnectAttempts;
}
else
{
LogInfo("Failed to connect to " + serverIp + ":" + ToString(serverPort));
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::CONNECTION_FAILED, 0);
reconnectTimer.Stop();
serverIp = "";
}
}
else if (!reconnectTimer.Enabled())
reconnectTimer.StartMSecs(cReconnectTimeout);
}
// If connection was made, enable a larger number of reconnection attempts in case it gets lost
if (serverConnection && serverConnection->GetConnectionState() == ConnectionOK)
reconnectAttempts = cReconnectAttempts;
RESETPROFILER;
}
const std::string &KristalliProtocolModule::NameStatic()
{
return moduleName;
}
void KristalliProtocolModule::Connect(const char *ip, unsigned short port, SocketTransportLayer transport)
{
if (Connected() && serverConnection && serverConnection->GetEndPoint().ToString() != serverIp)
Disconnect();
serverIp = ip;
serverPort = port;
serverTransport = transport;
reconnectAttempts = cInitialAttempts; // Initial attempts when establishing connection
if (!Connected())
PerformConnection(); // Start performing a connection attempt to the desired address/port/transport
}
void KristalliProtocolModule::PerformConnection()
{
if (Connected() && serverConnection)
{
serverConnection->Close();
// network.CloseMessageConnection(serverConnection);
serverConnection = 0;
}
// Connect to the server.
serverConnection = network.Connect(serverIp.c_str(), serverPort, serverTransport, this);
if (!serverConnection)
{
LogError("Unable to connect to " + serverIp + ":" + ToString(serverPort));
return;
}
}
void KristalliProtocolModule::Disconnect()
{
if (serverConnection)
{
serverConnection->Disconnect();
// network.CloseMessageConnection(serverConnection);
///\todo Wait? This closes the connection.
serverConnection = 0;
}
// Clear the remembered destination server ip address so that the automatic connection timer will not try to reconnect.
serverIp = "";
reconnectTimer.Stop();
}
bool KristalliProtocolModule::StartServer(unsigned short port, SocketTransportLayer transport)
{
StopServer();
server = network.StartServer(port, transport, this);
if (!server)
{
LogError("Failed to start server on port " + ToString((int)port));
return false;
}
LogInfo("Started server on port " + ToString((int)port));
return true;
}
void KristalliProtocolModule::StopServer()
{
if (server)
{
network.StopServer();
connections.clear();
LogInfo("Stopped server");
server = 0;
}
}
void KristalliProtocolModule::NewConnectionEstablished(kNet::MessageConnection *source)
{
source->RegisterInboundMessageHandler(this);
///\todo Regression. Re-enable. -jj.
// source->SetDatagramInFlowRatePerSecond(200);
UserConnection connection;
connection.userID = AllocateNewConnectionID();
connection.connection = source;
connections.push_back(connection);
LogInfo("User connected from " + source->GetEndPoint().ToString() + ", connection ID " + ToString((int)connection.userID));
Events::KristalliUserConnected msg(&connection);
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_CONNECTED, &msg);
}
void KristalliProtocolModule::ClientDisconnected(MessageConnection *source)
{
// Delete from connection list if it was a known user
for(UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->connection == source)
{
Events::KristalliUserDisconnected msg(&(*iter));
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::USER_DISCONNECTED, &msg);
LogInfo("User disconnected, connection ID " + ToString((int)iter->userID));
connections.erase(iter);
return;
}
}
LogInfo("Unknown user disconnected");
}
void KristalliProtocolModule::HandleMessage(MessageConnection *source, message_id_t id, const char *data, size_t numBytes)
{
assert(source);
assert(data);
try
{
Events::KristalliNetMessageIn msg(source, id, data, numBytes);
framework_->GetEventManager()->SendEvent(networkEventCategory, Events::NETMESSAGE_IN, &msg);
} catch(std::exception &e)
{
LogError("KristalliProtocolModule: Exception \"" + std::string(e.what()) + "\" thrown when handling network message id " + ToString(id) + " size " + ToString((int)numBytes) + " from client "
+ source->ToString());
}
}
bool KristalliProtocolModule::HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data)
{
return false;
}
u8 KristalliProtocolModule::AllocateNewConnectionID() const
{
u8 newID = 1;
for(UserConnectionList::const_iterator iter = connections.begin(); iter != connections.end(); ++iter)
newID = std::max((int)newID, (int)(iter->userID+1));
return newID;
}
UserConnection* KristalliProtocolModule::GetUserConnection(MessageConnection* source)
{
for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->connection == source)
return &(*iter);
}
return 0;
}
UserConnection* KristalliProtocolModule::GetUserConnection(u8 id)
{
for (UserConnectionList::iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->userID == id)
return &(*iter);
}
return 0;
}
UserConnectionList KristalliProtocolModule::GetAuthenticatedUsers() const
{
UserConnectionList ret;
for (UserConnectionList::const_iterator iter = connections.begin(); iter != connections.end(); ++iter)
{
if (iter->authenticated)
ret.push_back(*iter);
}
return ret;
}
} // ~KristalliProtocolModule namespace
extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
Foundation::ProfilerSection::SetProfiler(profiler);
}
using namespace KristalliProtocol;
POCO_BEGIN_MANIFEST(IModule)
POCO_EXPORT_CLASS(KristalliProtocolModule)
POCO_END_MANIFEST
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
// boost
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"
#include "shape.hpp"
DATASOURCE_PLUGIN(shape_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
shape_datasource::shape_datasource(const parameters ¶ms)
: datasource (params),
type_(datasource::Vector),
file_length_(0),
indexed_(false),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
shape_name_ = *base + "/" + *file;
else
shape_name_ = *file;
boost::algorithm::ireplace_last(shape_name_,".shp","");
if (!boost::filesystem::exists(shape_name_ + ".shp"))
{
throw datasource_exception("shapefile '" + shape_name_ + ".shp' does not exist");
}
if (boost::filesystem::is_directory(shape_name_ + ".shp"))
{
throw datasource_exception("shapefile '" + shape_name_ + ".shp' appears to be a directory not a file");
}
try
{
shape_ = boost::shared_ptr<shape_io>(new shape_io(shape_name_));
init(*shape_);
for (int i=0;i<shape_->dbf().num_fields();++i)
{
field_descriptor const& fd=shape_->dbf().descriptor(i);
std::string fld_name=fd.name_;
switch (fd.type_)
{
case 'C':
case 'D':
case 'M':
case 'L':
desc_.add_descriptor(attribute_descriptor(fld_name, String));
break;
case 'N':
case 'F':
{
if (fd.dec_>0)
{
desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8));
}
else
{
desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4));
}
break;
}
default:
#ifdef MAPNIK_DEBUG
std::clog << "unknown type "<<fd.type_<<"\n";
#endif
break;
}
}
}
catch (datasource_exception& ex)
{
std::clog<<ex.what()<<std::endl;
throw;
}
catch (...)
{
std::clog << " got exception ... \n";
throw;
}
}
shape_datasource::~shape_datasource() {}
const std::string shape_datasource::name_="shape";
void shape_datasource::init(shape_io& shape)
{
//first read header from *.shp
int file_code=shape.shp().read_xdr_integer();
if (file_code!=9994)
{
//invalid file code
throw datasource_exception((boost::format("wrong file code : %d") % file_code).str());
}
shape.shp().skip(5*4);
file_length_=shape.shp().read_xdr_integer();
int version=shape.shp().read_ndr_integer();
if (version!=1000)
{
//invalid version number
throw datasource_exception((boost::format("invalid version number: %d") % version).str());
}
#ifdef MAPNIK_DEBUG
int shape_type = shape.shp().read_ndr_integer();
#else
shape.shp().skip(4);
#endif
shape.shp().read_envelope(extent_);
#ifdef MAPNIK_DEBUG
double zmin = shape.shp().read_double();
double zmax = shape.shp().read_double();
double mmin = shape.shp().read_double();
double mmax = shape.shp().read_double();
std::clog << "Z min/max " << zmin << "," << zmax << "\n";
std::clog << "M min/max " << mmin << "," << mmax << "\n";
#else
shape.shp().skip(4*8);
#endif
// check if we have an index file around
indexed_ = shape.has_index();
//std::string index_name(shape_name_+".index");
//std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
//if (file)
//{
// indexed_=true;
// file.close();
//}
//else
//{
// std::clog << "### Notice: no .index file found for " + shape_name_ + ".shp, use the 'shapeindex' program to build an index for faster rendering\n";
//}
#ifdef MAPNIK_DEBUG
std::clog << extent_ << std::endl;
std::clog << "file_length=" << file_length_ << std::endl;
std::clog << "shape_type=" << shape_type << std::endl;
#endif
}
int shape_datasource::type() const
{
return type_;
}
layer_descriptor shape_datasource::get_descriptor() const
{
return desc_;
}
std::string shape_datasource::name()
{
return name_;
}
featureset_ptr shape_datasource::features(const query& q) const
{
filter_in_box filter(q.get_bbox());
if (indexed_)
{
shape_->shp().seek(0);
return featureset_ptr
(new shape_index_featureset<filter_in_box>(filter,
*shape_,
q.property_names(),
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding(),
file_length_));
}
}
featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
if (indexed_)
{
return featureset_ptr
(new shape_index_featureset<filter_at_point>(filter,
*shape_,
names,
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding(),
file_length_));
}
}
box2d<double> shape_datasource::envelope() const
{
return extent_;
}
<commit_msg>make sure to seek to the beginning of shapefile when querying points and using indexes - thanks tmcw for uncovering - closes #643<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <mapnik/geom_util.hpp>
// boost
#include <boost/version.hpp>
#include <boost/format.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include "shape_featureset.hpp"
#include "shape_index_featureset.hpp"
#include "shape.hpp"
DATASOURCE_PLUGIN(shape_datasource)
using mapnik::String;
using mapnik::Double;
using mapnik::Integer;
using mapnik::datasource_exception;
using mapnik::filter_in_box;
using mapnik::filter_at_point;
using mapnik::attribute_descriptor;
shape_datasource::shape_datasource(const parameters ¶ms)
: datasource (params),
type_(datasource::Vector),
file_length_(0),
indexed_(false),
desc_(*params.get<std::string>("type"), *params.get<std::string>("encoding","utf-8"))
{
boost::optional<std::string> file = params.get<std::string>("file");
if (!file) throw datasource_exception("missing <file> parameter");
boost::optional<std::string> base = params.get<std::string>("base");
if (base)
shape_name_ = *base + "/" + *file;
else
shape_name_ = *file;
boost::algorithm::ireplace_last(shape_name_,".shp","");
if (!boost::filesystem::exists(shape_name_ + ".shp"))
{
throw datasource_exception("shapefile '" + shape_name_ + ".shp' does not exist");
}
if (boost::filesystem::is_directory(shape_name_ + ".shp"))
{
throw datasource_exception("shapefile '" + shape_name_ + ".shp' appears to be a directory not a file");
}
try
{
shape_ = boost::shared_ptr<shape_io>(new shape_io(shape_name_));
init(*shape_);
for (int i=0;i<shape_->dbf().num_fields();++i)
{
field_descriptor const& fd=shape_->dbf().descriptor(i);
std::string fld_name=fd.name_;
switch (fd.type_)
{
case 'C':
case 'D':
case 'M':
case 'L':
desc_.add_descriptor(attribute_descriptor(fld_name, String));
break;
case 'N':
case 'F':
{
if (fd.dec_>0)
{
desc_.add_descriptor(attribute_descriptor(fld_name,Double,false,8));
}
else
{
desc_.add_descriptor(attribute_descriptor(fld_name,Integer,false,4));
}
break;
}
default:
#ifdef MAPNIK_DEBUG
std::clog << "unknown type "<<fd.type_<<"\n";
#endif
break;
}
}
}
catch (datasource_exception& ex)
{
std::clog<<ex.what()<<std::endl;
throw;
}
catch (...)
{
std::clog << " got exception ... \n";
throw;
}
}
shape_datasource::~shape_datasource() {}
const std::string shape_datasource::name_="shape";
void shape_datasource::init(shape_io& shape)
{
//first read header from *.shp
int file_code=shape.shp().read_xdr_integer();
if (file_code!=9994)
{
//invalid file code
throw datasource_exception((boost::format("wrong file code : %d") % file_code).str());
}
shape.shp().skip(5*4);
file_length_=shape.shp().read_xdr_integer();
int version=shape.shp().read_ndr_integer();
if (version!=1000)
{
//invalid version number
throw datasource_exception((boost::format("invalid version number: %d") % version).str());
}
#ifdef MAPNIK_DEBUG
int shape_type = shape.shp().read_ndr_integer();
#else
shape.shp().skip(4);
#endif
shape.shp().read_envelope(extent_);
#ifdef MAPNIK_DEBUG
double zmin = shape.shp().read_double();
double zmax = shape.shp().read_double();
double mmin = shape.shp().read_double();
double mmax = shape.shp().read_double();
std::clog << "Z min/max " << zmin << "," << zmax << "\n";
std::clog << "M min/max " << mmin << "," << mmax << "\n";
#else
shape.shp().skip(4*8);
#endif
// check if we have an index file around
indexed_ = shape.has_index();
//std::string index_name(shape_name_+".index");
//std::ifstream file(index_name.c_str(),std::ios::in | std::ios::binary);
//if (file)
//{
// indexed_=true;
// file.close();
//}
//else
//{
// std::clog << "### Notice: no .index file found for " + shape_name_ + ".shp, use the 'shapeindex' program to build an index for faster rendering\n";
//}
#ifdef MAPNIK_DEBUG
std::clog << extent_ << std::endl;
std::clog << "file_length=" << file_length_ << std::endl;
std::clog << "shape_type=" << shape_type << std::endl;
#endif
}
int shape_datasource::type() const
{
return type_;
}
layer_descriptor shape_datasource::get_descriptor() const
{
return desc_;
}
std::string shape_datasource::name()
{
return name_;
}
featureset_ptr shape_datasource::features(const query& q) const
{
filter_in_box filter(q.get_bbox());
if (indexed_)
{
shape_->shp().seek(0);
return featureset_ptr
(new shape_index_featureset<filter_in_box>(filter,
*shape_,
q.property_names(),
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_in_box>(filter,
shape_name_,
q.property_names(),
desc_.get_encoding(),
file_length_));
}
}
featureset_ptr shape_datasource::features_at_point(coord2d const& pt) const
{
filter_at_point filter(pt);
// collect all attribute names
std::vector<attribute_descriptor> const& desc_vector = desc_.get_descriptors();
std::vector<attribute_descriptor>::const_iterator itr = desc_vector.begin();
std::vector<attribute_descriptor>::const_iterator end = desc_vector.end();
std::set<std::string> names;
while (itr != end)
{
names.insert(itr->get_name());
++itr;
}
if (indexed_)
{
shape_->shp().seek(0);
return featureset_ptr
(new shape_index_featureset<filter_at_point>(filter,
*shape_,
names,
desc_.get_encoding()));
}
else
{
return featureset_ptr
(new shape_featureset<filter_at_point>(filter,
shape_name_,
names,
desc_.get_encoding(),
file_length_));
}
}
box2d<double> shape_datasource::envelope() const
{
return extent_;
}
<|endoftext|> |
<commit_before>#include <BALL/VIEW/DIALOGS/snapShotVisualisation.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>
#include <BALL/FORMAT/trajectoryFile.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qslider.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qprogressdialog.h>
namespace BALL
{
namespace VIEW
{
SnapshotVisualisationDialog::SnapshotVisualisationDialog
(QWidget* parent, const char* name)//, bool modal, WFlags fl)
: SnapshotVisualisationDialogData(parent, name),//, modal, fl),
ModularWidget(name)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "new SnapshotVisualisationDialog" << this << std::endl;
#endif
tmp_.setNum(1);
ModularWidget::registerWidget(this);
}
SnapshotVisualisationDialog::~SnapshotVisualisationDialog() throw()
{
}
void SnapshotVisualisationDialog::firstSnapshotClicked()
{
if (snap_shot_manager_->applyFirstSnapShot())
{
tmp_.setNum(1, 10);
snapShotSlider->setValue(1);
update_();
}
else
{
Log.error() << "Unable to apply first snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::oneForwardClicked()
{
forward(1);
}
void SnapshotVisualisationDialog::oneBackwardClicked()
{
backward(1);
}
void SnapshotVisualisationDialog::tenForwardClicked()
{
forward(10);
}
void SnapshotVisualisationDialog::tenBackwardClicked()
{
backward(10);
}
void SnapshotVisualisationDialog::hundredForwardClicked()
{
forward(100);
}
void SnapshotVisualisationDialog::hundredBackwardClicked()
{
backward(100);
}
void SnapshotVisualisationDialog::lastSnapshotClicked()
{
if (snap_shot_manager_->applySnapShot(
snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots()))
{
snapShotSlider->setValue(snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots());
update_();
}
else
{
Log.error() << "Unable to apply first snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::animateClicked()
{
Size tempo = getEndSnapshot();
Size speed = animationSpeedSlider->value();
bool forward = true;
QProgressDialog progress( "SnapShot Visualisation", "Abort Animation", tempo, this, "progress", TRUE );
for(Size i = getStartSnapshot(); i < tempo;)
{
progress.setProgress( i );
if ( progress.wasCancelled() )
break;
setCaption((String("CurrentSnapshot: ") + String(i)).c_str());
snapShotSlider->setValue(i);
update_();
if (export_PNG->isChecked())
{
SceneMessage* message = new SceneMessage(SceneMessage::EXPORT_PNG);
notify_(message);
}
tmp_.setNum(i, 10);
// speed things up after first snapshot is read
if (i == getStartSnapshot())
{
if (!snap_shot_manager_->applySnapShot(i)) return;
}
else
{
if (!snap_shot_manager_->applyNextSnapShot()) return;
}
if (forward)
{
if (speed>=(tempo-i))
{
i = tempo;
setCaption((String("CurrentSnapshot: ") + String(i)).c_str());
snapShotSlider->setValue(i);
update_();
if (export_PNG->isChecked())
{
SceneMessage* message = new SceneMessage(SceneMessage::EXPORT_PNG);
notify_(message);
}
if (forwardLoopButton->isChecked())
{
i = 1;
forward = true;
}
if (rockLoopButton->isChecked())
{
i = tempo-1;
forward = false;
}
}
else
i += speed;
}
else
if (speed<=i)
i -= speed;
else
{
i = 1;
forward = true;
}
}
progress.setProgress( tempo );
setCaption("Snapshot Visualisation");
}
void SnapshotVisualisationDialog::close()
{
lastSnapshotClicked();
update_();
if (snap_shot_manager_->getTrajectoryFile())
{
delete snap_shot_manager_->getTrajectoryFile();
}
delete snap_shot_manager_;
}
void SnapshotVisualisationDialog::backward(Size nr)
{
if (nr > (Size)currentSnapshot->text().toInt())
{
firstSnapshotClicked();
return;
}
Position tmpnr = (currentSnapshot->text().toInt()) - nr;
if (snap_shot_manager_->applySnapShot(tmpnr))
{
snapShotSlider->setValue(tmpnr);
tmp_.setNum(tmpnr);
update_();
}
else
{
Log.error() << "Could not apply snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::forward(Size nr)
{
Size tmpnr = (currentSnapshot->text().toInt()) + nr;
if (tmpnr >= snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots())
{
lastSnapshotClicked();
}
else
{
if (snap_shot_manager_->applySnapShot(tmpnr))
{
snapShotSlider->setValue(tmpnr);
tmp_.setNum(tmpnr);
update_();
}
else
{
Log.error() << "Could not apply snapshot" <<std::endl;
}
}
}
Size SnapshotVisualisationDialog::getStartSnapshot() const
{
try
{
return (Size)String(startSnapshot->text().ascii()).toUnsignedInt();
}
catch(...)
{
Log.error() << "Invalid Start-Snapshot" << std::endl;
return 1;
}
}
Size SnapshotVisualisationDialog::getEndSnapshot() const
{
try
{
return (Size)String(endSnapshot->text().ascii()).toUnsignedInt();
}
catch(...)
{
Log.error() << "Invalid End-Snapshot" << std::endl;
return number_of_snapshots_;
}
}
void SnapshotVisualisationDialog::sliderMovedToPos()
{
currentSnapshot->setText(String(snapShotSlider->value()).c_str());
Position tmpnr = (currentSnapshot->text().toInt());
if (snap_shot_manager_->applySnapShot(tmpnr))
{
tmp_.setNum(tmpnr);
update_();
}
else
{
Log.error() << "Could not apply snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::update_()
{
currentSnapshot->setText(tmp_);
update();
SceneMessage* new_message = new SceneMessage;
new_message->setType(SceneMessage::REBUILD_DISPLAY_LISTS);
notify_(new_message);
}
void SnapshotVisualisationDialog::setSnapShotManager(SnapShotManager* snapshot_manager)
{
snap_shot_manager_ = snapshot_manager;
tmp_.setNum(snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots());
numberOfSnapshots->setText(tmp_);
endSnapshot->setText(tmp_);
snapShotSlider->setRange(1,snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots());
animationSpeedLineEdit->setText(String(1).c_str() + String("x"));
tmp_.setNum(1);
currentSnapshot->setText(tmp_);
startSnapshot->setText(tmp_);
}
void SnapshotVisualisationDialog::snapShotInputTest()
{
String startSnap = startSnapshot->text().ascii();
String endSnap = endSnapshot->text().ascii();
String valid_char = "0123456789";
//test if input is valid
if(startSnap.size()!=0)
{
for(unsigned int i = 0; i!=startSnap.size(); i++)
{
if(valid_char.find(startSnap.substr(i,1)) == string::npos)
{
//if written char is not a number, set string to old string
startSnap = startSnap.substr(0,(startSnap.size()-1));
startSnapshot->setText(startSnap.c_str());
break;
}
}
}
if(endSnap.size()!=0)
{
for(unsigned int i = 0; i!=endSnap.size(); i++)
{
if(valid_char.find(endSnap.substr(i,1)) == string::npos)
{
//if written char is not a number, set string to old string
endSnap = endSnap.substr(0,(endSnap.size()-1));
endSnapshot->setText(endSnap.c_str());
break;
}
}
}
// set line edits to number of snapshots, if written number is bigger then number of snapshots
String num_of_shots = numberOfSnapshots->text().ascii();
String num_of_startsnap = startSnapshot->text().ascii();
String num_of_endsnap = endSnapshot->text().ascii();
Size num_shots = num_of_shots.toInt();
Size num_startsnap = num_of_startsnap.toInt();
Size num_endsnap = num_of_endsnap.toInt();
if(num_startsnap > num_shots)
{
startSnapshot->setText(num_of_shots.c_str());
}
if(num_endsnap > num_shots)
{
endSnapshot->setText(num_of_shots.c_str());
}
if (num_startsnap == 0)
startSnapshot->setText(String(1).c_str());
}
void SnapshotVisualisationDialog::animationSpeedChanged()
{
String animationSpeed = String(animationSpeedSlider->value()) + String("x");
animationSpeedLineEdit->setText(animationSpeed.c_str());
}
void SnapshotVisualisationDialog::checkNoLoop()
{
if(!noLoopButton->isChecked())
noLoopButton->setChecked(true);
forwardLoopButton->setChecked(false);
rockLoopButton->setChecked(false);
}
void SnapshotVisualisationDialog::checkLoop()
{
if(!forwardLoopButton->isChecked())
forwardLoopButton->setChecked(true);
noLoopButton->setChecked(false);
rockLoopButton->setChecked(false);
}
void SnapshotVisualisationDialog::checkRock()
{
if(!rockLoopButton->isChecked())
rockLoopButton->setChecked(true);
noLoopButton->setChecked(false);
forwardLoopButton->setChecked(false);
}
} } // namespace
<commit_msg>fixed: missing String->QString cast<commit_after>#include <BALL/VIEW/DIALOGS/snapShotVisualisation.h>
#include <BALL/VIEW/WIDGETS/scene.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>
#include <BALL/FORMAT/trajectoryFile.h>
#include <qlineedit.h>
#include <qcheckbox.h>
#include <qslider.h>
#include <qpushbutton.h>
#include <qradiobutton.h>
#include <qprogressdialog.h>
namespace BALL
{
namespace VIEW
{
SnapshotVisualisationDialog::SnapshotVisualisationDialog
(QWidget* parent, const char* name)//, bool modal, WFlags fl)
: SnapshotVisualisationDialogData(parent, name),//, modal, fl),
ModularWidget(name)
{
#ifdef BALL_VIEW_DEBUG
Log.error() << "new SnapshotVisualisationDialog" << this << std::endl;
#endif
tmp_.setNum(1);
ModularWidget::registerWidget(this);
}
SnapshotVisualisationDialog::~SnapshotVisualisationDialog() throw()
{
}
void SnapshotVisualisationDialog::firstSnapshotClicked()
{
if (snap_shot_manager_->applyFirstSnapShot())
{
tmp_.setNum(1, 10);
snapShotSlider->setValue(1);
update_();
}
else
{
Log.error() << "Unable to apply first snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::oneForwardClicked()
{
forward(1);
}
void SnapshotVisualisationDialog::oneBackwardClicked()
{
backward(1);
}
void SnapshotVisualisationDialog::tenForwardClicked()
{
forward(10);
}
void SnapshotVisualisationDialog::tenBackwardClicked()
{
backward(10);
}
void SnapshotVisualisationDialog::hundredForwardClicked()
{
forward(100);
}
void SnapshotVisualisationDialog::hundredBackwardClicked()
{
backward(100);
}
void SnapshotVisualisationDialog::lastSnapshotClicked()
{
if (snap_shot_manager_->applySnapShot(
snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots()))
{
snapShotSlider->setValue(snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots());
update_();
}
else
{
Log.error() << "Unable to apply first snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::animateClicked()
{
Size tempo = getEndSnapshot();
Size speed = animationSpeedSlider->value();
bool forward = true;
QProgressDialog progress( "SnapShot Visualisation", "Abort Animation", tempo, this, "progress", TRUE );
for(Size i = getStartSnapshot(); i < tempo;)
{
progress.setProgress( i );
if ( progress.wasCancelled() )
break;
setCaption((String("CurrentSnapshot: ") + String(i)).c_str());
snapShotSlider->setValue(i);
update_();
if (export_PNG->isChecked())
{
SceneMessage* message = new SceneMessage(SceneMessage::EXPORT_PNG);
notify_(message);
}
tmp_.setNum(i, 10);
// speed things up after first snapshot is read
if (i == getStartSnapshot())
{
if (!snap_shot_manager_->applySnapShot(i)) return;
}
else
{
if (!snap_shot_manager_->applyNextSnapShot()) return;
}
if (forward)
{
if (speed>=(tempo-i))
{
i = tempo;
setCaption((String("CurrentSnapshot: ") + String(i)).c_str());
snapShotSlider->setValue(i);
update_();
if (export_PNG->isChecked())
{
SceneMessage* message = new SceneMessage(SceneMessage::EXPORT_PNG);
notify_(message);
}
if (forwardLoopButton->isChecked())
{
i = 1;
forward = true;
}
if (rockLoopButton->isChecked())
{
i = tempo-1;
forward = false;
}
}
else
i += speed;
}
else
if (speed<=i)
i -= speed;
else
{
i = 1;
forward = true;
}
}
progress.setProgress( tempo );
setCaption("Snapshot Visualisation");
}
void SnapshotVisualisationDialog::close()
{
lastSnapshotClicked();
update_();
if (snap_shot_manager_->getTrajectoryFile())
{
delete snap_shot_manager_->getTrajectoryFile();
}
delete snap_shot_manager_;
}
void SnapshotVisualisationDialog::backward(Size nr)
{
if (nr > (Size)currentSnapshot->text().toInt())
{
firstSnapshotClicked();
return;
}
Position tmpnr = (currentSnapshot->text().toInt()) - nr;
if (snap_shot_manager_->applySnapShot(tmpnr))
{
snapShotSlider->setValue(tmpnr);
tmp_.setNum(tmpnr);
update_();
}
else
{
Log.error() << "Could not apply snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::forward(Size nr)
{
Size tmpnr = (currentSnapshot->text().toInt()) + nr;
if (tmpnr >= snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots())
{
lastSnapshotClicked();
}
else
{
if (snap_shot_manager_->applySnapShot(tmpnr))
{
snapShotSlider->setValue(tmpnr);
tmp_.setNum(tmpnr);
update_();
}
else
{
Log.error() << "Could not apply snapshot" <<std::endl;
}
}
}
Size SnapshotVisualisationDialog::getStartSnapshot() const
{
try
{
return (Size)String(startSnapshot->text().ascii()).toUnsignedInt();
}
catch(...)
{
Log.error() << "Invalid Start-Snapshot" << std::endl;
return 1;
}
}
Size SnapshotVisualisationDialog::getEndSnapshot() const
{
try
{
return (Size)String(endSnapshot->text().ascii()).toUnsignedInt();
}
catch(...)
{
Log.error() << "Invalid End-Snapshot" << std::endl;
return number_of_snapshots_;
}
}
void SnapshotVisualisationDialog::sliderMovedToPos()
{
currentSnapshot->setText(String(snapShotSlider->value()).c_str());
Position tmpnr = (currentSnapshot->text().toInt());
if (snap_shot_manager_->applySnapShot(tmpnr))
{
tmp_.setNum(tmpnr);
update_();
}
else
{
Log.error() << "Could not apply snapshot" <<std::endl;
}
}
void SnapshotVisualisationDialog::update_()
{
currentSnapshot->setText(tmp_);
update();
SceneMessage* new_message = new SceneMessage;
new_message->setType(SceneMessage::REBUILD_DISPLAY_LISTS);
notify_(new_message);
}
void SnapshotVisualisationDialog::setSnapShotManager(SnapShotManager* snapshot_manager)
{
snap_shot_manager_ = snapshot_manager;
tmp_.setNum(snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots());
numberOfSnapshots->setText(tmp_);
endSnapshot->setText(tmp_);
snapShotSlider->setRange(1,snap_shot_manager_->getTrajectoryFile()->getNumberOfSnapShots());
animationSpeedLineEdit->setText("1x");
tmp_.setNum(1);
currentSnapshot->setText(tmp_);
startSnapshot->setText(tmp_);
}
void SnapshotVisualisationDialog::snapShotInputTest()
{
String startSnap = startSnapshot->text().ascii();
String endSnap = endSnapshot->text().ascii();
String valid_char = "0123456789";
//test if input is valid
if(startSnap.size()!=0)
{
for(unsigned int i = 0; i!=startSnap.size(); i++)
{
if(valid_char.find(startSnap.substr(i,1)) == string::npos)
{
//if written char is not a number, set string to old string
startSnap = startSnap.substr(0,(startSnap.size()-1));
startSnapshot->setText(startSnap.c_str());
break;
}
}
}
if(endSnap.size()!=0)
{
for(unsigned int i = 0; i!=endSnap.size(); i++)
{
if(valid_char.find(endSnap.substr(i,1)) == string::npos)
{
//if written char is not a number, set string to old string
endSnap = endSnap.substr(0,(endSnap.size()-1));
endSnapshot->setText(endSnap.c_str());
break;
}
}
}
// set line edits to number of snapshots, if written number is bigger then number of snapshots
String num_of_shots = numberOfSnapshots->text().ascii();
String num_of_startsnap = startSnapshot->text().ascii();
String num_of_endsnap = endSnapshot->text().ascii();
Size num_shots = num_of_shots.toInt();
Size num_startsnap = num_of_startsnap.toInt();
Size num_endsnap = num_of_endsnap.toInt();
if(num_startsnap > num_shots)
{
startSnapshot->setText(num_of_shots.c_str());
}
if(num_endsnap > num_shots)
{
endSnapshot->setText(num_of_shots.c_str());
}
if (num_startsnap == 0)
startSnapshot->setText(String(1).c_str());
}
void SnapshotVisualisationDialog::animationSpeedChanged()
{
String animationSpeed = String(animationSpeedSlider->value()) + String("x");
animationSpeedLineEdit->setText(animationSpeed.c_str());
}
void SnapshotVisualisationDialog::checkNoLoop()
{
if(!noLoopButton->isChecked())
noLoopButton->setChecked(true);
forwardLoopButton->setChecked(false);
rockLoopButton->setChecked(false);
}
void SnapshotVisualisationDialog::checkLoop()
{
if(!forwardLoopButton->isChecked())
forwardLoopButton->setChecked(true);
noLoopButton->setChecked(false);
rockLoopButton->setChecked(false);
}
void SnapshotVisualisationDialog::checkRock()
{
if(!rockLoopButton->isChecked())
rockLoopButton->setChecked(true);
noLoopButton->setChecked(false);
forwardLoopButton->setChecked(false);
}
} } // namespace
<|endoftext|> |
<commit_before>// Natron
/* 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/. *//*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "InfoViewerWidget.h"
#include <cstdlib>
#include <iostream>
#include <QtGui/QImage>
#include <QHBoxLayout>
#include <QLabel>
#include "Engine/Lut.h"
#include "Gui/ViewerGL.h"
using std::cout; using std::endl;
using namespace Natron;
InfoViewerWidget::InfoViewerWidget(ViewerGL* v,QWidget* parent)
: QWidget(parent)
, _colorAndMouseVisible(false)
, mousePos(0,0)
, rectUser(0,0)
, colorUnderMouse(0,0,0,0)
, _fps(0)
{
this->viewer = v;
setObjectName(QString::fromUtf8("infoViewer"));
setMinimumHeight(20);
setMaximumHeight(20);
setStyleSheet(QString("background-color:black"));
layout = new QHBoxLayout(this);
QString reso("<font color=\"#DBE0E0\">");
reso.append(viewer->getDisplayWindow().getName().c_str());
reso.append("\t");
reso.append("</font>");
resolution = new QLabel(reso,this);
resolution->setContentsMargins(0, 0, 0, 0);
QString bbox;
bbox = QString("<font color=\"#DBE0E0\">RoD: %1 %2 %3 %4</font>")
.arg(viewer->getRoD().left())
.arg(viewer->getRoD().bottom())
.arg(viewer->getRoD().right())
.arg(viewer->getRoD().top());
_fpsLabel = new QLabel(this);
coordDispWindow = new QLabel(bbox,this);
coordDispWindow->setContentsMargins(0, 0, 0, 0);
QString coord;
coord = QString("<font color=\"#DBE0E0\">x=%1 y=%2</font>")
.arg(mousePos.x())
.arg(mousePos.y());
coordMouse = new QLabel(this);
//coordMouse->setText(coord);
coordMouse->setContentsMargins(0, 0, 0, 0);
rgbaValues = new QLabel(this);
rgbaValues->setContentsMargins(0, 0, 0, 0);
color = new QLabel(this);
color->setMaximumSize(20, 20);
color->setContentsMargins(0, 0, 0, 0);
color->setStyleSheet(QString("background-color:black;"));
hvl_lastOption = new QLabel(this);
hvl_lastOption->setContentsMargins(10, 0, 0, 0);
layout->addWidget(resolution);
layout->addWidget(coordDispWindow);
layout->addWidget(_fpsLabel);
layout->addWidget(coordMouse);
layout->addWidget(rgbaValues);
layout->addWidget(color);
layout->addWidget(hvl_lastOption);
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Minimum);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
}
QSize InfoViewerWidget::sizeHint() const { return QSize(0,0); }
void InfoViewerWidget::setFps(double actualFps,double desiredFps){
QString colorStr("green");
if (actualFps < (desiredFps - desiredFps / 10.f) && actualFps > (desiredFps / 2.f)) {
colorStr = QString("orange");
} else if(actualFps < (desiredFps / 2.f)) {
colorStr = QString("red");
}
QString str = QString("<font color='"+colorStr+"'>%1 fps</font>").arg(QString::number(actualFps,'f',1));
_fpsLabel->setText(str);
if(!_fpsLabel->isVisible()){
_fpsLabel->show();
}
}
void InfoViewerWidget::hideFps(){
_fpsLabel->hide();
}
void InfoViewerWidget::showColorAndMouseInfo(){
_colorAndMouseVisible=true;
}
void InfoViewerWidget::hideColorAndMouseInfo(){
coordMouse->setText("");
hvl_lastOption->setText("");
rgbaValues->setText("");
QPixmap pix(20,20);
pix.fill(Qt::black);
color->setPixmap(pix);
_colorAndMouseVisible=false;
}
InfoViewerWidget::~InfoViewerWidget(){
}
void InfoViewerWidget::updateColor()
{
float r = colorUnderMouse.x();
float g = colorUnderMouse.y();
float b = colorUnderMouse.z();
float a = colorUnderMouse.w();
QString values;
values = QString("<font color='red'>%1</font> <font color='green'>%2</font> <font color='blue'>%3</font> <font color=\"#DBE0E0\">%4</font>")
.arg(r,0,'f',5)
.arg(g,0,'f',5)
.arg(b,0,'f',5)
.arg(a,0,'f',5);
rgbaValues->setText(values);
float h,s,v,l;
// Nuke's HSV display is based on sRGB, an L is Rec.709.
// see http://forums.thefoundry.co.uk/phpBB2/viewtopic.php?t=2283
Color::rgb_to_hsv(Color::to_func_srgb(r),Color::to_func_srgb(g),Color::to_func_srgb(b),&h,&s,&v);
l = 0.2125*r + 0.7154*g + 0.0721*b; // L according to Rec.709
QString hsvlValues;
hsvlValues = QString("<font color=\"#DBE0E0\">H:%1 S:%2 V:%3 L:%4</font>")
.arg(h,0,'f',0)
.arg(s,0,'f',2)
.arg(v,0,'f',2)
.arg(l,0,'f',5);
hvl_lastOption->setText(hsvlValues);
}
void InfoViewerWidget::updateCoordMouse(){
QString coord;
coord = QString("<font color=\"#DBE0E0\">x=%1 y=%2</font>")
.arg(mousePos.x())
.arg(mousePos.y());
coordMouse->setText(coord);
}
void InfoViewerWidget::changeResolution(){
format = viewer->getDisplayWindow();
if(format.getName() == std::string("")){
QString reso;
reso = QString("<font color=\"#DBE0E0\">%1x%2\t</font>")
.arg(viewer->getDisplayWindow().width())
.arg(viewer->getDisplayWindow().height());
resolution->setText(reso);
resolution->setMaximumWidth(resolution->sizeHint().width());
}else{
QString reso("<font color=\"#DBE0E0\">");
reso.append(format.getName().c_str());
reso.append("\t");
reso.append("</font>");
resolution->setText(reso);
resolution->setMaximumWidth(resolution->sizeHint().width());
}
}
void InfoViewerWidget::changeDataWindow(){
QString bbox;
bbox = QString("<font color=\"#DBE0E0\">RoD: %1 %2 %3 %4</font>")
.arg(viewer->getRoD().left())
.arg(viewer->getRoD().bottom())
.arg(viewer->getRoD().right())
.arg(viewer->getRoD().top());
coordDispWindow->setText(bbox);
}
void InfoViewerWidget::changeUserRect(){
cout << "NOT IMPLEMENTED YET" << endl;
}
void InfoViewerWidget::setColor(float r,float g,float b,float a){
colorUnderMouse.setX(r);
colorUnderMouse.setY(g);
colorUnderMouse.setZ(b);
colorUnderMouse.setW(a);
}
<commit_msg>InfoViewerWidget: use equal-luminance colors for colored text<commit_after>// Natron
/* 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/. *//*
*Created by Alexandre GAUTHIER-FOICHAT on 6/1/2012.
*contact: immarespond at gmail dot com
*
*/
#include "InfoViewerWidget.h"
#include <cstdlib>
#include <iostream>
#include <QtGui/QImage>
#include <QHBoxLayout>
#include <QLabel>
#include "Engine/Lut.h"
#include "Gui/ViewerGL.h"
using std::cout; using std::endl;
using namespace Natron;
InfoViewerWidget::InfoViewerWidget(ViewerGL* v,QWidget* parent)
: QWidget(parent)
, _colorAndMouseVisible(false)
, mousePos(0,0)
, rectUser(0,0)
, colorUnderMouse(0,0,0,0)
, _fps(0)
{
this->viewer = v;
setObjectName(QString::fromUtf8("infoViewer"));
setMinimumHeight(20);
setMaximumHeight(20);
setStyleSheet(QString("background-color:black"));
layout = new QHBoxLayout(this);
QString reso("<font color=\"#DBE0E0\">");
reso.append(viewer->getDisplayWindow().getName().c_str());
reso.append("\t");
reso.append("</font>");
resolution = new QLabel(reso,this);
resolution->setContentsMargins(0, 0, 0, 0);
QString bbox;
bbox = QString("<font color=\"#DBE0E0\">RoD: %1 %2 %3 %4</font>")
.arg(viewer->getRoD().left())
.arg(viewer->getRoD().bottom())
.arg(viewer->getRoD().right())
.arg(viewer->getRoD().top());
_fpsLabel = new QLabel(this);
coordDispWindow = new QLabel(bbox,this);
coordDispWindow->setContentsMargins(0, 0, 0, 0);
QString coord;
coord = QString("<font color=\"#DBE0E0\">x=%1 y=%2</font>")
.arg(mousePos.x())
.arg(mousePos.y());
coordMouse = new QLabel(this);
//coordMouse->setText(coord);
coordMouse->setContentsMargins(0, 0, 0, 0);
rgbaValues = new QLabel(this);
rgbaValues->setContentsMargins(0, 0, 0, 0);
color = new QLabel(this);
color->setMaximumSize(20, 20);
color->setContentsMargins(0, 0, 0, 0);
color->setStyleSheet(QString("background-color:black;"));
hvl_lastOption = new QLabel(this);
hvl_lastOption->setContentsMargins(10, 0, 0, 0);
layout->addWidget(resolution);
layout->addWidget(coordDispWindow);
layout->addWidget(_fpsLabel);
layout->addWidget(coordMouse);
layout->addWidget(rgbaValues);
layout->addWidget(color);
layout->addWidget(hvl_lastOption);
setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Minimum);
layout->setSpacing(0);
layout->setContentsMargins(0, 0, 0, 0);
setLayout(layout);
}
QSize InfoViewerWidget::sizeHint() const { return QSize(0,0); }
void InfoViewerWidget::setFps(double actualFps,double desiredFps){
QString colorStr("green");
if (actualFps < (desiredFps - desiredFps / 10.f) && actualFps > (desiredFps / 2.f)) {
colorStr = QString("orange");
} else if(actualFps < (desiredFps / 2.f)) {
colorStr = QString("red");
}
QString str = QString("<font color='"+colorStr+"'>%1 fps</font>").arg(QString::number(actualFps,'f',1));
_fpsLabel->setText(str);
if(!_fpsLabel->isVisible()){
_fpsLabel->show();
}
}
void InfoViewerWidget::hideFps(){
_fpsLabel->hide();
}
void InfoViewerWidget::showColorAndMouseInfo(){
_colorAndMouseVisible=true;
}
void InfoViewerWidget::hideColorAndMouseInfo(){
coordMouse->setText("");
hvl_lastOption->setText("");
rgbaValues->setText("");
QPixmap pix(20,20);
pix.fill(Qt::black);
color->setPixmap(pix);
_colorAndMouseVisible=false;
}
InfoViewerWidget::~InfoViewerWidget(){
}
void InfoViewerWidget::updateColor()
{
float r = colorUnderMouse.x();
float g = colorUnderMouse.y();
float b = colorUnderMouse.z();
float a = colorUnderMouse.w();
QString values;
//values = QString("<font color='red'>%1</font> <font color='green'>%2</font> <font color='blue'>%3</font> <font color=\"#DBE0E0\">%4</font>")
// the following three colors have an equal luminance (=0.4), which makes the text easier to read.
values = QString("<font color='#d93232'>%1</font> <font color='#00a700'>%2</font> <font color='#5858ff'>%3</font> <font color=\"#DBE0E0\">%4</font>")
.arg(r,0,'f',5)
.arg(g,0,'f',5)
.arg(b,0,'f',5)
.arg(a,0,'f',5);
rgbaValues->setText(values);
float h,s,v,l;
// Nuke's HSV display is based on sRGB, an L is Rec.709.
// see http://forums.thefoundry.co.uk/phpBB2/viewtopic.php?t=2283
Color::rgb_to_hsv(Color::to_func_srgb(r),Color::to_func_srgb(g),Color::to_func_srgb(b),&h,&s,&v);
l = 0.2125*r + 0.7154*g + 0.0721*b; // L according to Rec.709
QString hsvlValues;
hsvlValues = QString("<font color=\"#DBE0E0\">H:%1 S:%2 V:%3 L:%4</font>")
.arg(h,0,'f',0)
.arg(s,0,'f',2)
.arg(v,0,'f',2)
.arg(l,0,'f',5);
hvl_lastOption->setText(hsvlValues);
}
void InfoViewerWidget::updateCoordMouse(){
QString coord;
coord = QString("<font color=\"#DBE0E0\">x=%1 y=%2</font>")
.arg(mousePos.x())
.arg(mousePos.y());
coordMouse->setText(coord);
}
void InfoViewerWidget::changeResolution(){
format = viewer->getDisplayWindow();
if(format.getName() == std::string("")){
QString reso;
reso = QString("<font color=\"#DBE0E0\">%1x%2\t</font>")
.arg(viewer->getDisplayWindow().width())
.arg(viewer->getDisplayWindow().height());
resolution->setText(reso);
resolution->setMaximumWidth(resolution->sizeHint().width());
}else{
QString reso("<font color=\"#DBE0E0\">");
reso.append(format.getName().c_str());
reso.append("\t");
reso.append("</font>");
resolution->setText(reso);
resolution->setMaximumWidth(resolution->sizeHint().width());
}
}
void InfoViewerWidget::changeDataWindow(){
QString bbox;
bbox = QString("<font color=\"#DBE0E0\">RoD: %1 %2 %3 %4</font>")
.arg(viewer->getRoD().left())
.arg(viewer->getRoD().bottom())
.arg(viewer->getRoD().right())
.arg(viewer->getRoD().top());
coordDispWindow->setText(bbox);
}
void InfoViewerWidget::changeUserRect(){
cout << "NOT IMPLEMENTED YET" << endl;
}
void InfoViewerWidget::setColor(float r,float g,float b,float a){
colorUnderMouse.setX(r);
colorUnderMouse.setY(g);
colorUnderMouse.setZ(b);
colorUnderMouse.setW(a);
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "statements/VReturnStatement.h"
#include "VisualizationBase/src/items/Static.h"
#include "VisualizationBase/src/items/VList.h"
#include "VisualizationBase/src/declarative/GridLayoutElement.h"
using namespace Visualization;
using namespace OOModel;
namespace OOVisualization {
ITEM_COMMON_DEFINITIONS(VReturnStatement, "item")
VReturnStatement::VReturnStatement(Item* parent, NodeType* node, const StyleType* style) :
Super(parent, node, style)
{
}
void VReturnStatement::initializeForms()
{
// TODO: layout style is not needed anymore, remove it?
addForm((new GridLayoutElement(2, 1))
->setTopMargin(5)
->setBottomMargin(5)
->setHorizontalSpacing(5)
->addElement(0, 0, item<Static, I>(&I::symbol_, [](I* v){return &v->style()->symbol();}))
->addElement(1, 0, item<VList,I>(&I::values_, [](I* v){return v->node()->values();},
[](I* v){return &v->style()->values();})));
}
Visualization::Item* VReturnStatement::returnSymbol() const
{
return symbol_->item();
}
}
<commit_msg>Fix return statement.<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2013 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "statements/VReturnStatement.h"
#include "VisualizationBase/src/items/Static.h"
#include "VisualizationBase/src/items/VList.h"
#include "VisualizationBase/src/declarative/GridLayoutElement.h"
using namespace Visualization;
using namespace OOModel;
namespace OOVisualization {
ITEM_COMMON_DEFINITIONS(VReturnStatement, "item")
VReturnStatement::VReturnStatement(Item* parent, NodeType* node, const StyleType* style) :
Super(parent, node, style)
{
}
void VReturnStatement::initializeForms()
{
// TODO: layout style is not needed anymore, remove it?
addForm((new GridLayoutElement())
->setTopMargin(5)
->setBottomMargin(5)
->setHorizontalSpacing(5)
->put(0, 0, item<Static, I>(&I::symbol_, [](I* v){return &v->style()->symbol();}))
->put(1, 0, item<VList,I>(&I::values_, [](I* v){return v->node()->values();},
[](I* v){return &v->style()->values();})));
}
Visualization::Item* VReturnStatement::returnSymbol() const
{
return symbol_->item();
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include "DynamicArray.h"
DynamicArray::DynamicArray() {
}
DynamicArray::DynamicArray(DynamicArray const & other) {
}
DynamicArray& DynamicArray::operator=(DynamicArray const & other) {
}
DynamicArray::~DynamicArray() {
}
void DynamicArray::free() {
}
void DynamicArray::reallocate(size_t newSize) {
}
void DynamicArray::add(int element) {
}
size_t DynamicArray::getAllocatedSize() const {
}
size_t DynamicArray::getLength() const {
}
int DynamicArray::getAt(size_t index) const {
}
void DynamicArray::setAt(size_t index, int value) {
}
void DynamicArray::print() const {
}
DynamicArray DynamicArray::operator+(DynamicArray const& rhs) const {
}
///
/// Returns proxy object which represents the element of the array with index "index"
///
/// This version of the operator is used for non-constant arrays and returns
/// proxy object which can be used to change the array's cells.
///
/// IMPORTANT!:
/// 1. The operator doesn't make validation of the array's index.
/// Such a validation is made each time when the proxy object is used.
/// 2. The proxy object is connected to a special index,
/// not with a special element in the array.
/// This means that no matter what changes are made in the dynamic array,
/// the proxy object will refer to the same index.
///
DynamicArrayElementProxy DynamicArray::operator[](size_t index) {
}
///
/// Returns proxy object which represents the element of the array with index "index"
///
/// This version of the operator is used for constant arrays and returns
/// constant proxy object that *can't* be used to change the array's cells.
///
const DynamicArrayElementProxy DynamicArray::operator[](size_t index) const {
}
/// ============================================================================
DynamicArrayElementProxy::DynamicArrayElementProxy(DynamicArray * pDynamicArray, size_t elementIndex) :
pParent(pDynamicArray),
parentElementIndex(elementIndex) {
}
DynamicArrayElementProxy::operator int() const {
}
DynamicArrayElementProxy & DynamicArrayElementProxy::operator=(int value) {
}<commit_msg>add DynamicArray-with-Proxy big four func declarations<commit_after>#include <iostream>
#include <algorithm>
#include "DynamicArray.h"
DynamicArray::DynamicArray() {
pData = NULL;
allocatedSize = 0;
length = 0;
}
DynamicArray::DynamicArray(DynamicArray const & other) {
copyFrom(other);
}
DynamicArray& DynamicArray::operator=(DynamicArray const & other) {
if (this != &other) {
free();
copyFrom(other);
}
return *this;
}
DynamicArray::~DynamicArray() {
free();
}
void DynamicArray::free() {
delete[] pData;
pData = NULL;
allocatedSize = 0;
length = 0;
}
void DynamicArray::copyFrom(DynamicArray const & other) {
free();
pData = new int[other.allocatedSize];
for (int i = 0; i < other.length; i++) {
pData[i] = other.pData[i];
}
allocatedSize = other.getAllocatedSize;
length = other.length;
}
void DynamicArray::reallocate(size_t newSize) {
}
void DynamicArray::add(int element) {
}
size_t DynamicArray::getAllocatedSize() const {
}
size_t DynamicArray::getLength() const {
}
int DynamicArray::getAt(size_t index) const {
}
void DynamicArray::setAt(size_t index, int value) {
}
void DynamicArray::print() const {
}
DynamicArray DynamicArray::operator+(DynamicArray const& rhs) const {
}
///
/// Returns proxy object which represents the element of the array with index "index"
///
/// This version of the operator is used for non-constant arrays and returns
/// proxy object which can be used to change the array's cells.
///
/// IMPORTANT!:
/// 1. The operator doesn't make validation of the array's index.
/// Such a validation is made each time when the proxy object is used.
/// 2. The proxy object is connected to a special index,
/// not with a special element in the array.
/// This means that no matter what changes are made in the dynamic array,
/// the proxy object will refer to the same index.
///
DynamicArrayElementProxy DynamicArray::operator[](size_t index) {
}
///
/// Returns proxy object which represents the element of the array with index "index"
///
/// This version of the operator is used for constant arrays and returns
/// constant proxy object that *can't* be used to change the array's cells.
///
const DynamicArrayElementProxy DynamicArray::operator[](size_t index) const {
}
/// ============================================================================
DynamicArrayElementProxy::DynamicArrayElementProxy(DynamicArray * pDynamicArray, size_t elementIndex) :
pParent(pDynamicArray),
parentElementIndex(elementIndex) {
}
DynamicArrayElementProxy::operator int() const {
}
DynamicArrayElementProxy & DynamicArrayElementProxy::operator=(int value) {
}<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <chrono>
#include <random>
#include "etl/fast_vector.hpp"
#include "etl/fast_matrix.hpp"
#include "etl/convolution.hpp"
typedef std::chrono::high_resolution_clock timer_clock;
typedef std::chrono::milliseconds milliseconds;
typedef std::chrono::microseconds microseconds;
namespace {
template<typename T>
void randomize_double(T& container){
static std::default_random_engine rand_engine(std::time(nullptr));
static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0);
static auto generator = std::bind(real_distribution, rand_engine);
for(auto& v : container){
v = generator();
}
}
template<typename T1>
void randomize(T1& container){
randomize_double(container);
}
template<typename T1, typename... TT>
void randomize(T1& container, TT&... containers){
randomize_double(container);
randomize(containers...);
}
std::string duration_str(std::size_t duration_us){
double duration = duration_us;
if(duration > 1000){
return std::to_string(duration / 1000.0) + "ms";
} else {
return std::to_string(duration_us) + "us";
}
}
template<typename Functor, typename... T>
void measure(const std::string& title, const std::string& reference, Functor&& functor, T&... references){
for(std::size_t i = 0; i < 100; ++i){
randomize(references...);
functor();
}
std::size_t duration_acc = 0;
for(std::size_t i = 0; i < 1000; ++i){
randomize(references...);
auto start_time = timer_clock::now();
functor();
auto end_time = timer_clock::now();
auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time);
duration_acc += duration.count();
}
std::cout << title << " took " << duration_str(duration_acc) << " (reference: " << reference << ")" << std::endl;
}
} //end of anonymous namespace
etl::fast_vector<double, 4096> double_vector_a;
etl::fast_vector<double, 4096> double_vector_b;
etl::fast_vector<double, 4096> double_vector_c;
etl::fast_matrix<double, 16, 256> double_matrix_a;
etl::fast_matrix<double, 16, 256> double_matrix_b;
etl::fast_matrix<double, 16, 256> double_matrix_c;
etl::fast_matrix<double, 256, 128> double_matrix_d;
etl::fast_matrix<double, 256, 128> double_matrix_e;
etl::fast_matrix<double, 256, 128> double_matrix_f;
etl::fast_matrix<double, 128, 128> double_conv_a;
etl::fast_matrix<double, 32, 32> double_conv_b;
etl::fast_matrix<double, 159, 159> double_conv_c;
int main(){
measure("fast_vector_simple(4096)", "72ms", [](){
double_vector_c = 3.5 * double_vector_a + etl::sigmoid(1.0 + double_vector_b);
}, double_vector_a, double_vector_b);
measure("fast_matrix_simple(16,256)(4096)", "72ms", [](){
double_matrix_c = 3.5 * double_matrix_a + etl::sigmoid(1.0 + double_matrix_b);
}, double_matrix_a, double_matrix_b);
measure("fast_matrix_simple(256,128)", "580ms", [](){
double_matrix_f = 3.5 * double_matrix_d + etl::sigmoid(1.0 + double_matrix_e);
}, double_matrix_d, double_matrix_e);
measure("fast_matrix_full_convolve(256,128)", "15s", [](){
etl::convolve_2d_full(double_conv_a, double_conv_b, double_conv_c);
}, double_conv_a, double_conv_b);
return 0;
}
<commit_msg>Complete benchmarks<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <chrono>
#include <random>
#include "etl/fast_vector.hpp"
#include "etl/fast_matrix.hpp"
#include "etl/convolution.hpp"
typedef std::chrono::high_resolution_clock timer_clock;
typedef std::chrono::milliseconds milliseconds;
typedef std::chrono::microseconds microseconds;
namespace {
template<typename T>
void randomize_double(T& container){
static std::default_random_engine rand_engine(std::time(nullptr));
static std::uniform_real_distribution<double> real_distribution(-1000.0, 1000.0);
static auto generator = std::bind(real_distribution, rand_engine);
for(auto& v : container){
v = generator();
}
}
template<typename T1>
void randomize(T1& container){
randomize_double(container);
}
template<typename T1, typename... TT>
void randomize(T1& container, TT&... containers){
randomize_double(container);
randomize(containers...);
}
std::string duration_str(std::size_t duration_us){
double duration = duration_us;
if(duration > 1000 * 1000){
return std::to_string(duration / 1000.0 / 1000.0) + "s";
} else if(duration > 1000){
return std::to_string(duration / 1000.0) + "ms";
} else {
return std::to_string(duration_us) + "us";
}
}
template<typename Functor, typename... T>
void measure(const std::string& title, const std::string& reference, Functor&& functor, T&... references){
for(std::size_t i = 0; i < 100; ++i){
randomize(references...);
functor();
}
std::size_t duration_acc = 0;
for(std::size_t i = 0; i < 1000; ++i){
randomize(references...);
auto start_time = timer_clock::now();
functor();
auto end_time = timer_clock::now();
auto duration = std::chrono::duration_cast<microseconds>(end_time - start_time);
duration_acc += duration.count();
}
std::cout << title << " took " << duration_str(duration_acc) << " (reference: " << reference << ")" << std::endl;
}
} //end of anonymous namespace
etl::fast_vector<double, 4096> double_vector_a;
etl::fast_vector<double, 4096> double_vector_b;
etl::fast_vector<double, 4096> double_vector_c;
etl::fast_matrix<double, 16, 256> double_matrix_a;
etl::fast_matrix<double, 16, 256> double_matrix_b;
etl::fast_matrix<double, 16, 256> double_matrix_c;
etl::fast_matrix<double, 256, 128> double_matrix_d;
etl::fast_matrix<double, 256, 128> double_matrix_e;
etl::fast_matrix<double, 256, 128> double_matrix_f;
etl::fast_matrix<double, 128, 128> double_conv_a;
etl::fast_matrix<double, 32, 32> double_conv_b;
etl::fast_matrix<double, 159, 159> double_conv_c;
int main(){
measure("fast_vector_simple(4096)", "72ms", [](){
double_vector_c = 3.5 * double_vector_a + etl::sigmoid(1.0 + double_vector_b);
}, double_vector_a, double_vector_b);
measure("fast_matrix_simple(16,256)(4096)", "72ms", [](){
double_matrix_c = 3.5 * double_matrix_a + etl::sigmoid(1.0 + double_matrix_b);
}, double_matrix_a, double_matrix_b);
measure("fast_matrix_simple(256,128)", "580ms", [](){
double_matrix_f = 3.5 * double_matrix_d + etl::sigmoid(1.0 + double_matrix_e);
}, double_matrix_d, double_matrix_e);
measure("fast_matrix_full_convolve(128,128)", "25s", [](){
etl::convolve_2d_full(double_conv_a, double_conv_b, double_conv_c);
}, double_conv_a, double_conv_b);
measure("fast_matrix_valid_convolve(128,128)", "40s", [](){
etl::convolve_2d_valid(double_conv_a, double_conv_b, double_conv_c);
}, double_conv_a, double_conv_b);
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2012, 2013 BlackBerry Limited.
*
* 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 "RequestHeaders.hpp"
#include <bb/data/JsonDataAccess>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslConfiguration>
#include <QUrl>
/**
* RequestHeaders
*
* In this class you will learn the following:
* -- How to use QNetworkAccessManager to make a network request
* -- How to setup a secure connection with QSslConfiguration
* -- How to read a network response with QNetworkReply
* -- How to parse JSON data using JsonDataAccess
* -- How to read the headers in an http response
*/
RequestHeaders::RequestHeaders(QObject* parent)
: QObject(parent)
, m_networkAccessManager(new QNetworkAccessManager(this))
{
}
/**
* RequestHeaders::getRequest()
*
* Setup an http get request using SSL if configured
*/
//! [0]
void RequestHeaders::getRequest()
{
const QUrl url("http://httpbin.org/get");
QNetworkRequest request(url);
QNetworkReply* reply = m_networkAccessManager->get(request);
bool ok = connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
//! [0]
/**
* RequestHeaders::onGetReply()
*
* SLOT
* Handles the http response by parsing JSON and printing out the response http headers
*/
//! [1]
void RequestHeaders::onGetReply()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
const int available = reply->bytesAvailable();
if (available > 0) {
const QByteArray buffer(reply->readAll());
// The data from reply is in a json format e.g
//"args": {},
//"headers": {
// "Accept": "*/*",
// "Connection": "close",
// "Content-Length": "",
// "Content-Type": "",
// "Host": "httpbin.org",
// "User-Agent": "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3"
//},
//"origin": "24.127.96.129",
//"url": "http://httpbin.org/get"
bb::data::JsonDataAccess ja;
const QVariant jsonva = ja.loadFromBuffer(buffer);
const QMap<QString, QVariant> jsonreply = jsonva.toMap();
// Locate the header array
// QMap<QString, QVariant>::const_iterator it = jsonreply.find("headers");
QMap<QString, QVariant>::const_iterator it = jsonreply.begin();
if (it != jsonreply.end()) {
// Print everything in header array
const QMap<QString, QVariant> headers = it.value().toMap();
for (QMap<QString, QVariant>::const_iterator hdrIter = headers.begin(); hdrIter != headers.end(); ++hdrIter) {
if (hdrIter.value().toString().trimmed().isEmpty())
continue; // Skip empty values
response += QString::fromLatin1("%1: %2\r\n").arg(hdrIter.key(), hdrIter.value().toString());
}
}
// Print everything else
for (it = jsonreply.begin(); it != jsonreply.end(); it++) {
if (it.value().toString().trimmed().isEmpty())
continue; // Skip empty values
response += QString::fromLatin1("%1: %2\r\n").arg(it.key(), it.value().toString());
}
}
} else {
response = tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
qDebug() << response;
}
reply->deleteLater();
}
if (response.trimmed().isEmpty()) {
response = tr("Unable to retrieve request headers");
}
emit complete(response);
}
//! [1]
<commit_msg>Incremental update to json handling<commit_after>/* Copyright (c) 2012, 2013 BlackBerry Limited.
*
* 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 "RequestHeaders.hpp"
#include <bb/data/JsonDataAccess>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslConfiguration>
#include <QUrl>
/**
* RequestHeaders
*
* In this class you will learn the following:
* -- How to use QNetworkAccessManager to make a network request
* -- How to setup a secure connection with QSslConfiguration
* -- How to read a network response with QNetworkReply
* -- How to parse JSON data using JsonDataAccess
* -- How to read the headers in an http response
*/
RequestHeaders::RequestHeaders(QObject* parent)
: QObject(parent)
, m_networkAccessManager(new QNetworkAccessManager(this))
{
}
/**
* RequestHeaders::getRequest()
*
* Setup an http get request using SSL if configured
*/
//! [0]
void RequestHeaders::getRequest()
{
const QUrl url("http://httpbin.org/get");
QNetworkRequest request(url);
QNetworkReply* reply = m_networkAccessManager->get(request);
bool ok = connect(reply, SIGNAL(finished()), this, SLOT(onGetReply()));
Q_ASSERT(ok);
Q_UNUSED(ok);
}
//! [0]
/**
* RequestHeaders::onGetReply()
*
* SLOT
* Handles the http response by parsing JSON and printing out the response http headers
*/
//! [1]
void RequestHeaders::onGetReply()
{
QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender());
QString response;
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
const int available = reply->bytesAvailable();
if (available > 0) {
const QByteArray buffer(reply->readAll());
// The data from reply is in a json format e.g
//"args": {},
//"headers": {
// "Accept": "*/*",
// "Connection": "close",
// "Content-Length": "",
// "Content-Type": "",
// "Host": "httpbin.org",
// "User-Agent": "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3"
//},
//"origin": "24.127.96.129",
//"url": "http://httpbin.org/get"
bb::data::JsonDataAccess ja;
const QVariant jsonva = ja.loadFromBuffer(buffer);
const QMap<QString, QVariant> jsonreply = jsonva.toMap();
// Locate the header array
// QMap<QString, QVariant>::const_iterator it = jsonreply.find("headers");
/*QMap<QString, QVariant>::const_iterator it = jsonreply.begin();
if (it != jsonreply.end()) {
// Print everything in header array
const QMap<QString, QVariant> headers = it.value().toMap();
for (QMap<QString, QVariant>::const_iterator hdrIter = headers.begin(); hdrIter != headers.end(); ++hdrIter) {
if (hdrIter.value().toString().trimmed().isEmpty())
continue; // Skip empty values
response += QString::fromLatin1("%1: %2\r\n").arg(hdrIter.key(), hdrIter.value().toString());
}
}
// Print everything else
for (it = jsonreply.begin(); it != jsonreply.end(); it++) {
if (it.value().toString().trimmed().isEmpty())
continue; // Skip empty values
response += QString::fromLatin1("%1: %2\r\n").arg(it.key(), it.value().toString());
}*/
for(int i = 0; i < jsonreply.keys().count(); i++)
{
response += jsonreply.keys().takeAt(i);
response += ": ";
response += jsonreply.values().takeAt(i).toString();
response += "\n";
}
}
} else {
response = tr("Error: %1 status: %2").arg(reply->errorString(), reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString());
qDebug() << response;
}
reply->deleteLater();
}
if (response.trimmed().isEmpty()) {
response = tr("Unable to retrieve request headers");
}
emit complete(response);
}
//! [1]
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007-2008 SlimDX Group
*
* 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 <d3d10.h>
#include <d3dx10.h>
#include "Buffer.h"
#include "InputAssemblerWrapper.h"
#include "InputLayout.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D10
{
InputAssemblerWrapper::InputAssemblerWrapper( ID3D10Device* device )
{
if( device == 0 )
throw gcnew ArgumentNullException( "device" );
m_Device = device;
}
void InputAssemblerWrapper::SetInputLayout( InputLayout^ value)
{
m_Device->IASetInputLayout( value->InternalPointer );
}
void InputAssemblerWrapper::SetPrimitiveTopology( PrimitiveTopology value)
{
m_Device->IASetPrimitiveTopology( static_cast<D3D10_PRIMITIVE_TOPOLOGY>( value ) );
}
void InputAssemblerWrapper::SetIndexBuffer( Buffer^ indexBuffer, DXGI::Format format, int offset )
{
m_Device->IASetIndexBuffer( static_cast<ID3D10Buffer*>( indexBuffer->InternalPointer ), static_cast<DXGI_FORMAT>( format ), offset );
}
void InputAssemblerWrapper::SetVertexBuffers( int slot, VertexBufferBinding vertexBufferBinding )
{
ID3D10Buffer* buffers[] = { static_cast<ID3D10Buffer*>( vertexBufferBinding.Buffer->InternalPointer ) };
UINT strides[] = { vertexBufferBinding.Stride };
UINT offsets[] = { vertexBufferBinding.Offset };
m_Device->IASetVertexBuffers( slot, 1, buffers, strides, offsets );
}
void InputAssemblerWrapper::SetVertexBuffers( int firstSlot, ... array<VertexBufferBinding>^ vertexBufferBinding )
{
ID3D10Buffer* buffers[D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
UINT strides[D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
UINT offsets[D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
for( int i = 0; i < vertexBufferBinding->Length; ++i )
{
buffers[i] = static_cast<ID3D10Buffer*>( vertexBufferBinding[ i ].Buffer->InternalPointer );
strides[i] = vertexBufferBinding[ i ].Stride;
offsets[i] = vertexBufferBinding[ i ].Offset;
}
m_Device->IASetVertexBuffers( firstSlot, vertexBufferBinding->Length, buffers, strides, offsets );
}
}
}
<commit_msg>Fixed a nullptr check in SetInputLayout.<commit_after>/*
* Copyright (c) 2007-2008 SlimDX Group
*
* 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 <d3d10.h>
#include <d3dx10.h>
#include "Buffer.h"
#include "InputAssemblerWrapper.h"
#include "InputLayout.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D10
{
InputAssemblerWrapper::InputAssemblerWrapper( ID3D10Device* device )
{
if( device == 0 )
throw gcnew ArgumentNullException( "device" );
m_Device = device;
}
void InputAssemblerWrapper::SetInputLayout( InputLayout^ value)
{
if( value == nullptr ) {
m_Device->IASetInputLayout( 0 );
} else {
m_Device->IASetInputLayout( value->InternalPointer );
}
}
void InputAssemblerWrapper::SetPrimitiveTopology( PrimitiveTopology value)
{
m_Device->IASetPrimitiveTopology( static_cast<D3D10_PRIMITIVE_TOPOLOGY>( value ) );
}
void InputAssemblerWrapper::SetIndexBuffer( Buffer^ indexBuffer, DXGI::Format format, int offset )
{
m_Device->IASetIndexBuffer( static_cast<ID3D10Buffer*>( indexBuffer->InternalPointer ), static_cast<DXGI_FORMAT>( format ), offset );
}
void InputAssemblerWrapper::SetVertexBuffers( int slot, VertexBufferBinding vertexBufferBinding )
{
ID3D10Buffer* buffers[] = { static_cast<ID3D10Buffer*>( vertexBufferBinding.Buffer->InternalPointer ) };
UINT strides[] = { vertexBufferBinding.Stride };
UINT offsets[] = { vertexBufferBinding.Offset };
m_Device->IASetVertexBuffers( slot, 1, buffers, strides, offsets );
}
void InputAssemblerWrapper::SetVertexBuffers( int firstSlot, ... array<VertexBufferBinding>^ vertexBufferBinding )
{
ID3D10Buffer* buffers[D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
UINT strides[D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
UINT offsets[D3D10_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT];
for( int i = 0; i < vertexBufferBinding->Length; ++i )
{
buffers[i] = static_cast<ID3D10Buffer*>( vertexBufferBinding[ i ].Buffer->InternalPointer );
strides[i] = vertexBufferBinding[ i ].Stride;
offsets[i] = vertexBufferBinding[ i ].Offset;
}
m_Device->IASetVertexBuffers( firstSlot, vertexBufferBinding->Length, buffers, strides, offsets );
}
}
}
<|endoftext|> |
<commit_before>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"
#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"
#define MOVE_DUMMY_IFPS (1.0f/100.0f)
#define MOVE_DUMMY_CLAMP 89.9f
#define MOVE_DUMMY_COLLISIONS 1
using namespace MathLib;
CMoveDummy::CMoveDummy() //캯
{
m_pObject = new CObjectDummy(); //һʵ
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(0.5f, 1.0f);
SetCollisionMask(1);
Clear();
}
CMoveDummy::~CMoveDummy()
{
m_pDummy->SetObject(NULL);
SAFE_DELETE(m_pObject);
SAFE_DELETE(m_pDummy);
}
void CMoveDummy::SetCollision(int c)
{
m_nCollision = c;
}
int CMoveDummy::GetCollision() const
{
return m_nCollision;
}
void CMoveDummy::SetCollisionMask(int m)
{
m_pShape->SetCollisionMask(m);
}
int CMoveDummy::GetCollisionMask() const
{
return m_nCollisionMask;
}
void CMoveDummy::SetGround(int g)
{
m_nGround = g;
}
int CMoveDummy::GetGround() const
{
return m_nGround;
}
void CMoveDummy::SetCeiling(int c)
{
m_nCeiling = c;
}
int CMoveDummy::GetCeiling() const
{
return m_nCeiling;
}
void CMoveDummy::SetPosition(const MathLib::vec3& p)
{
m_vPosition = p;
}
const MathLib::vec3& CMoveDummy::GetPosition() const
{
return m_vPosition;
}
void CMoveDummy::SetCollisionRadius(float radius)
{
if (!Compare(m_pShape->GetRadius(), radius))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
m_pShape->SetRadius(radius);
}
Update_Bounds();
}
float CMoveDummy::GetCollisionRadius() const
{
return m_pShape->GetRadius();
}
void CMoveDummy::SetCollisionHeight(float height)
{
if (!Compare(m_pShape->GetHeight(), height))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
m_pShape->SetHeight(height);
}
Update_Bounds();
}
float CMoveDummy::GetCollisionHeight() const
{
return m_pShape->GetHeight();
}
void CMoveDummy::SetUp(const MathLib::vec3& u)
{
m_vUp = u;
}
const MathLib::vec3& CMoveDummy::GetUp() const
{
return m_vUp;
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "MoveDummy.h"
#include "ObjectDummy.h"
#include "BodyDummy.h"
#include "ShapeCapsule.h"
#include "Utils.h"
#include "Engine.h"
#include "Physics.h"
#include "Game.h"
#include "World.h"
#define MOVE_DUMMY_IFPS (1.0f/100.0f)
#define MOVE_DUMMY_CLAMP 89.9f
#define MOVE_DUMMY_COLLISIONS 1
using namespace MathLib;
CMoveDummy::CMoveDummy() //캯
{
m_pObject = new CObjectDummy(); //һʵ
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(0.5f, 1.0f);
SetCollisionMask(1);
Clear();
}
CMoveDummy::~CMoveDummy()
{
m_pDummy->SetObject(NULL);
SAFE_DELETE(m_pObject);
SAFE_DELETE(m_pDummy);
}
void CMoveDummy::SetCollision(int c)
{
m_nCollision = c;
}
int CMoveDummy::GetCollision() const
{
return m_nCollision;
}
void CMoveDummy::SetCollisionMask(int m)
{
m_pShape->SetCollisionMask(m);
}
int CMoveDummy::GetCollisionMask() const
{
return m_nCollisionMask;
}
void CMoveDummy::SetGround(int g)
{
m_nGround = g;
}
int CMoveDummy::GetGround() const
{
return m_nGround;
}
void CMoveDummy::SetCeiling(int c)
{
m_nCeiling = c;
}
int CMoveDummy::GetCeiling() const
{
return m_nCeiling;
}
void CMoveDummy::SetPosition(const MathLib::vec3& p)
{
m_vPosition = p;
}
const MathLib::vec3& CMoveDummy::GetPosition() const
{
return m_vPosition;
}
void CMoveDummy::SetCollisionRadius(float radius)
{
if (!Compare(m_pShape->GetRadius(), radius))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (radius - m_pShape->GetRadius()))) * m_pDummy->GetTransform());
m_pShape->SetRadius(radius);
}
Update_Bounds();
}
float CMoveDummy::GetCollisionRadius() const
{
return m_pShape->GetRadius();
}
void CMoveDummy::SetCollisionHeight(float height)
{
if (!Compare(m_pShape->GetHeight(), height))
{
m_pDummy->SetPreserveTransform(Mat4(Translate(m_vUp * (height - m_pShape->GetHeight()) * 0.5f)) * m_pDummy->GetTransform());
m_pShape->SetHeight(height);
}
Update_Bounds();
}
float CMoveDummy::GetCollisionHeight() const
{
return m_pShape->GetHeight();
}
void CMoveDummy::SetUp(const MathLib::vec3& u)
{
m_vUp = u;
}
const MathLib::vec3& CMoveDummy::GetUp() const
{
return m_vUp;
}
void CMoveDummy::SetEnabled(int e)
{
m_nEnabled = e;
}
<|endoftext|> |
<commit_before>///
/// @file S2LoadBalancer.cpp
/// @brief The S2LoadBalancer evenly distributes the work load between
/// the threads in the computation of the special leaves.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed, especially if the interval
/// size is large and if the intervals are not adjacent. Also most
/// special leaves are in the first few segments whereas later on
/// there are very few special leaves.
///
/// Based on the above observations it is clear that we need a load
/// balancer in order to scale our parallel algorithm to compute the
/// special leaves. Below are the main rules I used to develop my load
/// balancing algorithm:
///
/// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x)
/// and one segment per thread. Our algorithm uses equally sized
/// intervals, for each thread the interval_size is
/// segment_size * segments_per_thread and the threads process
/// adjacent intervals i.e.
/// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)].
///
/// 2) If the relative standard deviation of the run times of the
/// threads is low then increase the segment size and/or segments
/// per thread, else if the relative standard deviation is large
/// then decrease the segment size and/or segments per thread. This
/// rule is derived from the fact that intervals with roughly the
/// same number of special leaves take about the same time to
/// process and the next intervals tend to have a similar
/// distribution of special leaves (especially if the interval size
/// is small).
///
/// 3) We can't use a static threshold for as to when the relative
/// standard deviation is low or large as this threshold varies for
/// different PC architectures e.g. 15 might be large relative
/// standard deviation for a quad-core CPU system whereas it is a
/// low standard deviation for a dual-socket system with 64
/// threads. So instead of using a static threshold we compare the
/// current relative standard deviation to the previous one.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <S2LoadBalancer.hpp>
#include <primecount-internal.hpp>
#include <aligned_vector.hpp>
#include <pmath.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
using namespace std;
using namespace primecount;
namespace {
double get_average(aligned_vector<double>& timings)
{
size_t n = timings.size();
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += timings[i];
return sum / n;
}
double relative_standard_deviation(aligned_vector<double>& timings)
{
size_t n = timings.size();
double average = get_average(timings);
double sum = 0;
if (average == 0)
return 0;
for (size_t i = 0; i < n; i++)
{
double mean = timings[i] - average;
sum += mean * mean;
}
double std_dev = sqrt(sum / max(1.0, n - 1.0));
double rsd = 100 * std_dev / average;
return rsd;
}
} // namespace
namespace primecount {
S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) :
x_((double) x),
z_((double) z),
rsd_(40),
avg_seconds_(0),
count_(0)
{
double log_threads = max(1.0, log((double) threads));
decrease_dividend_ = max(0.5, log_threads / 3);
min_seconds_ = 0.02 * log_threads;
max_size_ = next_power_of_2(isqrt(z));
update_min_size(log(x_) * log(log(x_)));
}
double S2LoadBalancer::get_rsd() const
{
return rsd_;
}
int64_t S2LoadBalancer::get_min_segment_size() const
{
return min_size_;
}
bool S2LoadBalancer::decrease_size(double seconds, double decrease) const
{
return seconds > min_seconds_ &&
rsd_ > decrease;
}
bool S2LoadBalancer::increase_size(double seconds, double decrease) const
{
return seconds < avg_seconds_ &&
!decrease_size(seconds, decrease);
}
/// Used to decide whether to use a smaller or larger
/// segment_size and/or segments_per_thread.
///
double S2LoadBalancer::get_decrease_threshold(double seconds) const
{
double log_seconds = max(min_seconds_, log(seconds));
double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_);
return rsd_ + dont_decrease;
}
void S2LoadBalancer::update_avg_seconds(double seconds)
{
seconds = max(seconds, min_seconds_);
double dividend = avg_seconds_ * count_ + seconds;
avg_seconds_ = dividend / (count_ + 1);
count_++;
}
void S2LoadBalancer::update_min_size(double divisor)
{
double size = sqrt(z_) / max(1.0, divisor);
min_size_ = max((int64_t) (1 << 9), (int64_t) size);
min_size_ = next_power_of_2(min_size_);
}
/// Balance the load in the computation of the special leaves
/// by dynamically adjusting the segment_size and segments_per_thread.
/// @param timings Timings of the threads.
///
void S2LoadBalancer::update(int64_t low,
int64_t threads,
int64_t* segment_size,
int64_t* segments_per_thread,
aligned_vector<double>& timings)
{
double seconds = get_average(timings);
update_avg_seconds(seconds);
double decrease_threshold = get_decrease_threshold(seconds);
rsd_ = max(0.1, relative_standard_deviation(timings));
// if low > sqrt(z) we use a larger min_size_ as the
// special leaves are distributed more evenly
if (low > max_size_)
{
update_min_size(log(x_));
*segment_size = max(*segment_size, min_size_);
}
// 1 segment per thread
if (*segment_size < max_size_)
{
if (increase_size(seconds, decrease_threshold))
*segment_size <<= 1;
else if (decrease_size(seconds, decrease_threshold))
if (*segment_size > min_size_)
*segment_size >>= 1;
// near sqrt(z) there is a short peak of special
// leaves so we use the minium segment size
int64_t high = low + *segment_size * *segments_per_thread * threads;
if (low <= max_size_ && high > max_size_)
*segment_size = min_size_;
}
else // many segments per thread
{
double factor = decrease_threshold / rsd_;
factor = in_between(0.5, factor, 2);
double n = *segments_per_thread * factor;
n = max(1.0, n);
if ((n < *segments_per_thread && seconds > min_seconds_) ||
(n > *segments_per_thread && seconds < avg_seconds_))
{
*segments_per_thread = (int) n;
}
}
}
} //namespace
<commit_msg>Update documentation<commit_after>///
/// @file S2LoadBalancer.cpp
/// @brief The S2LoadBalancer evenly distributes the work load between
/// the threads in the computation of the special leaves.
///
/// Simply parallelizing the computation of the special leaves in the
/// Lagarias-Miller-Odlyzko and Deleglise-Rivat algorithms by
/// subdividing the sieve interval by the number of threads into
/// equally sized subintervals does not scale because the distribution
/// of the special leaves is highly skewed, especially if the interval
/// size is large and if the intervals are not adjacent. Also most
/// special leaves are in the first few segments whereas later on
/// there are very few special leaves.
///
/// Based on the above observations it is clear that we need a load
/// balancer in order to scale our parallel algorithm to compute the
/// special leaves. Below are the main ideas I used to develop my load
/// balancing algorithm:
///
/// 1) Start with a tiny segment size of x^(1/3) / (log x * log log x)
/// and one segment per thread. Our algorithm uses equally sized
/// intervals, for each thread the interval_size is
/// segment_size * segments_per_thread and the threads process
/// adjacent intervals i.e.
/// [base + interval_size * thread_id, base + interval_size * (thread_id + 1)].
///
/// 2) If the relative standard deviation of the run times of the
/// threads is low then increase the segment size and/or segments
/// per thread, else if the relative standard deviation is large
/// then decrease the segment size and/or segments per thread. This
/// rule is derived from the fact that intervals with roughly the
/// same number of special leaves take about the same time to
/// process and the next intervals tend to have a similar
/// distribution of special leaves (especially if the interval size
/// is small).
///
/// 3) We can't use a static threshold for as to when the relative
/// standard deviation is low or large as this threshold varies for
/// different PC architectures e.g. 15 might be large relative
/// standard deviation for a quad-core CPU system whereas it is a
/// low standard deviation for a dual-socket system with 64 CPU
/// cores. So instead of using a static threshold we compare the
/// current relative standard deviation to the previous one.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <S2LoadBalancer.hpp>
#include <primecount-internal.hpp>
#include <aligned_vector.hpp>
#include <pmath.hpp>
#include <int128.hpp>
#include <stdint.h>
#include <algorithm>
#include <cmath>
using namespace std;
using namespace primecount;
namespace {
double get_average(aligned_vector<double>& timings)
{
size_t n = timings.size();
double sum = 0;
for (size_t i = 0; i < n; i++)
sum += timings[i];
return sum / n;
}
double relative_standard_deviation(aligned_vector<double>& timings)
{
size_t n = timings.size();
double average = get_average(timings);
double sum = 0;
if (average == 0)
return 0;
for (size_t i = 0; i < n; i++)
{
double mean = timings[i] - average;
sum += mean * mean;
}
double std_dev = sqrt(sum / max(1.0, n - 1.0));
double rsd = 100 * std_dev / average;
return rsd;
}
} // namespace
namespace primecount {
S2LoadBalancer::S2LoadBalancer(maxint_t x, int64_t z, int64_t threads) :
x_((double) x),
z_((double) z),
rsd_(40),
avg_seconds_(0),
count_(0)
{
double log_threads = max(1.0, log((double) threads));
decrease_dividend_ = max(0.5, log_threads / 3);
min_seconds_ = 0.02 * log_threads;
max_size_ = next_power_of_2(isqrt(z));
update_min_size(log(x_) * log(log(x_)));
}
double S2LoadBalancer::get_rsd() const
{
return rsd_;
}
int64_t S2LoadBalancer::get_min_segment_size() const
{
return min_size_;
}
bool S2LoadBalancer::decrease_size(double seconds, double decrease) const
{
return seconds > min_seconds_ &&
rsd_ > decrease;
}
bool S2LoadBalancer::increase_size(double seconds, double decrease) const
{
return seconds < avg_seconds_ &&
!decrease_size(seconds, decrease);
}
/// Used to decide whether to use a smaller or larger
/// segment_size and/or segments_per_thread.
///
double S2LoadBalancer::get_decrease_threshold(double seconds) const
{
double log_seconds = max(min_seconds_, log(seconds));
double dont_decrease = min(decrease_dividend_ / (seconds * log_seconds), rsd_);
return rsd_ + dont_decrease;
}
void S2LoadBalancer::update_avg_seconds(double seconds)
{
seconds = max(seconds, min_seconds_);
double dividend = avg_seconds_ * count_ + seconds;
avg_seconds_ = dividend / (count_ + 1);
count_++;
}
void S2LoadBalancer::update_min_size(double divisor)
{
double size = sqrt(z_) / max(1.0, divisor);
min_size_ = max((int64_t) (1 << 9), (int64_t) size);
min_size_ = next_power_of_2(min_size_);
}
/// Balance the load in the computation of the special leaves
/// by dynamically adjusting the segment_size and segments_per_thread.
/// @param timings Timings of the threads.
///
void S2LoadBalancer::update(int64_t low,
int64_t threads,
int64_t* segment_size,
int64_t* segments_per_thread,
aligned_vector<double>& timings)
{
double seconds = get_average(timings);
update_avg_seconds(seconds);
double decrease_threshold = get_decrease_threshold(seconds);
rsd_ = max(0.1, relative_standard_deviation(timings));
// if low > sqrt(z) we use a larger min_size_ as the
// special leaves are distributed more evenly
if (low > max_size_)
{
update_min_size(log(x_));
*segment_size = max(*segment_size, min_size_);
}
// 1 segment per thread
if (*segment_size < max_size_)
{
if (increase_size(seconds, decrease_threshold))
*segment_size <<= 1;
else if (decrease_size(seconds, decrease_threshold))
if (*segment_size > min_size_)
*segment_size >>= 1;
// near sqrt(z) there is a short peak of special
// leaves so we use the minium segment size
int64_t high = low + *segment_size * *segments_per_thread * threads;
if (low <= max_size_ && high > max_size_)
*segment_size = min_size_;
}
else // many segments per thread
{
double factor = decrease_threshold / rsd_;
factor = in_between(0.5, factor, 2);
double n = *segments_per_thread * factor;
n = max(1.0, n);
if ((n < *segments_per_thread && seconds > min_seconds_) ||
(n > *segments_per_thread && seconds < avg_seconds_))
{
*segments_per_thread = (int) n;
}
}
}
} //namespace
<|endoftext|> |
<commit_before>#include "SSTNetworkImpl.h"
#define SERVICE_NAME "cbr"
#define SERVICE_DESC "Constant Bit Rate Service"
#define PROTOCOL_NAME "cbr1.0"
#define PROTOCOL_DESC "Constant Bit Rate Protocol 1.0"
namespace CBR {
SSTStatsListener::SSTStatsListener(const QTime& start)
: mStartTime(start)
{
}
void SSTStatsListener::packetSent(qint32 size) {
qint32 msecs = mStartTime.elapsed();
//printf("packet sent: %d at %d\n", size, msecs);
}
void SSTStatsListener::packetReceived(qint32 size) {
qint32 msecs = mStartTime.elapsed();
//printf("packet received: %d at %d\n", size, msecs);
}
CBRSST::CBRSST()
{
mApp = new QApplication(0, 0);
mCurrentSendChunk = NULL;
}
CBRSST::~CBRSST() {
}
void CBRSST::handleInit() {
this->mMainCallback(NULL);
mApp->exit();
}
void CBRSST::init(void* (*x)(void*)){
mMainCallback=x;
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(handleInit()));
timer->start(0);
mApp->exec();
}
void CBRSST::start() {
mStartTime.start();
}
void CBRSST::listen(uint32 port) {
mHost = new SST::Host(NULL, port);
mAcceptor = new SST::StreamServer(mHost);
mAcceptor->listen(
SERVICE_NAME, SERVICE_DESC,
PROTOCOL_NAME, PROTOCOL_DESC
);
connect(mAcceptor, SIGNAL(newConnection()),
this, SLOT(handleConnection()));
}
void CBRSST::trySendCurrentChunk() {
// try to service the most recent
if (mCurrentSendChunk == NULL) return;
StreamInfo si = lookupOrConnect(mCurrentSendChunk->addr);
Stream* strm = si.stream;
uint32 new_bytes_sent = strm->writeMessage((const char*)&mCurrentSendChunk->data[mCurrentSendChunk->bytes_sent], mCurrentSendChunk->data.size() - mCurrentSendChunk->bytes_sent);
mCurrentSendChunk->bytes_sent += new_bytes_sent;
if (mCurrentSendChunk->bytes_sent == mCurrentSendChunk->data.size()) {
delete mCurrentSendChunk;
mCurrentSendChunk = NULL;
}
}
bool CBRSST::send(const Address4& addy, const Network::Chunk& data, bool reliable, bool ordered, int priority) {
trySendCurrentChunk();
if (mCurrentSendChunk != NULL)
return false;
mCurrentSendChunk = new NetworkChunk();
mCurrentSendChunk->addr = addy;
mCurrentSendChunk->data = data;
mCurrentSendChunk->bytes_sent = 0;
trySendCurrentChunk();
return true;
}
Network::Chunk* CBRSST::front(const Address4& from, uint32 max_size) {
assert(from != Address4::Null);
StreamInfo& si = lookupOrConnect(from);
if (si.peek != NULL) return si.peek;
SST::Stream* strm = si.stream;
if (strm->hasPendingMessages() && strm->pendingMessageSize() <= max_size) {
QByteArray msg = strm->peekMessage();
if (msg.isEmpty())
return NULL;
si.peek = new Network::Chunk( (const uint8*)msg.constData(), (const uint8*)msg.constData() + msg.size() );
return si.peek;
}
return NULL;
}
Network::Chunk* CBRSST::receiveOne(const Address4& from, uint32 max_size) {
assert(from != Address4::Null);
StreamInfo& si = lookupOrConnect(from);
SST::Stream* strm = si.stream;
if (strm->hasPendingMessages() && strm->pendingMessageSize() <= max_size) {
QByteArray msg = strm->readMessage();
Network::Chunk* result = si.peek;
if (result) {
assert( result->size() == msg.size() );
si.peek = NULL;
return result;
}
if (msg.isEmpty())
return NULL;
result = new Network::Chunk( (const uint8*)msg.constData(), (const uint8*)msg.constData() + msg.size() );
return result;
}
return NULL;
}
void CBRSST::service() {
mApp->processEvents();
}
void CBRSST::handleConnection() {
while(true) {
SST::Stream *strm = mAcceptor->accept();
if (strm == NULL)
return;
QByteArray remote_id = strm->remoteHostId();
assert( remote_id.size() == 7 && (uint32)remote_id[0] == 8 );
uint32 remote_ip;
uint16 remote_port;
memcpy(&remote_ip, remote_id.constData() + 1, 4);
memcpy(&remote_port, remote_id.constData() + 5, 2);
remote_ip = ntohl(remote_ip);
remote_port = ntohs(remote_port);
qDebug() << "remote ip: " << remote_ip << " remote port: " << remote_port;
//strm->setChildReceiveBuffer(sizeof(qint32));
strm->listen(SST::Stream::Reject);
strm->setParent(this);
connect(strm, SIGNAL(readyReadMessage()),
this, SLOT(handleReadyReadMessage()));
connect(strm, SIGNAL(readyReadDatagram()),
this, SLOT(handleReadyReadDatagram()));
connect(strm, SIGNAL(reset(const QString &)),
this, SLOT(handleReset()));
connect(strm, SIGNAL(newSubstream()),
this, SLOT(handleNewSubstream()), Qt::QueuedConnection);
Address4 remote_addy(remote_ip, remote_port);
SSTStatsListener* stats_listener = new SSTStatsListener(mStartTime);
strm->setStatListener( stats_listener );
StreamInfo si;
si.stream = strm;
si.stats = stats_listener;
assert( mReceiveConnections.find(remote_addy) == mReceiveConnections.end() );
mReceiveConnections[remote_addy] = si;
}
}
void CBRSST::handleReadyReadMessage() {
// don't do anything, they'll be serviced on demand in the receive method
}
void CBRSST::handleReadyReadDatagram() {
assert(false);
}
void CBRSST::handleNewSubstream() {
assert(false);
}
void CBRSST::handleReset() {
SST::Stream* strm = (SST::Stream*)sender();
strm->deleteLater();
}
CBRSST::StreamInfo& CBRSST::lookupOrConnect(const Address4& addy) {
// If we have one, just return it
StreamMap::iterator it = mSendConnections.find(addy);
if (it != mSendConnections.end())
return it->second;
// Otherwise we need to connect
SST::Stream* strm = new SST::Stream(mHost, this);
quint32 addy_ip = htonl(addy.ip);
strm->connectTo(SST::Ident::fromIpAddress(QHostAddress(addy_ip),addy.port).id(), SERVICE_NAME, PROTOCOL_NAME);
SSTStatsListener* stats_listener = new SSTStatsListener(mStartTime);
strm->setStatListener( stats_listener );
StreamInfo si;
si.stream = strm;
si.stats = stats_listener;
si.peek = NULL;
mSendConnections[addy] = si;
it = mSendConnections.find(addy);
return it->second;
}
} // namespace CBR
<commit_msg>Be more explicit about QApplication parameters so we actually use the correct constructor. Fixes problems with running runsim.py with --net=sst.<commit_after>#include "SSTNetworkImpl.h"
#define SERVICE_NAME "cbr"
#define SERVICE_DESC "Constant Bit Rate Service"
#define PROTOCOL_NAME "cbr1.0"
#define PROTOCOL_DESC "Constant Bit Rate Protocol 1.0"
namespace CBR {
SSTStatsListener::SSTStatsListener(const QTime& start)
: mStartTime(start)
{
}
void SSTStatsListener::packetSent(qint32 size) {
qint32 msecs = mStartTime.elapsed();
//printf("packet sent: %d at %d\n", size, msecs);
}
void SSTStatsListener::packetReceived(qint32 size) {
qint32 msecs = mStartTime.elapsed();
//printf("packet received: %d at %d\n", size, msecs);
}
CBRSST::CBRSST()
{
int argc = 0;
char** argv = NULL;
mApp = new QApplication((int&)argc, (char**)argv);
mCurrentSendChunk = NULL;
}
CBRSST::~CBRSST() {
}
void CBRSST::handleInit() {
this->mMainCallback(NULL);
mApp->exit();
}
void CBRSST::init(void* (*x)(void*)){
mMainCallback=x;
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(handleInit()));
timer->start(0);
mApp->exec();
}
void CBRSST::start() {
mStartTime.start();
}
void CBRSST::listen(uint32 port) {
mHost = new SST::Host(NULL, port);
mAcceptor = new SST::StreamServer(mHost);
mAcceptor->listen(
SERVICE_NAME, SERVICE_DESC,
PROTOCOL_NAME, PROTOCOL_DESC
);
connect(mAcceptor, SIGNAL(newConnection()),
this, SLOT(handleConnection()));
}
void CBRSST::trySendCurrentChunk() {
// try to service the most recent
if (mCurrentSendChunk == NULL) return;
StreamInfo si = lookupOrConnect(mCurrentSendChunk->addr);
Stream* strm = si.stream;
uint32 new_bytes_sent = strm->writeMessage((const char*)&mCurrentSendChunk->data[mCurrentSendChunk->bytes_sent], mCurrentSendChunk->data.size() - mCurrentSendChunk->bytes_sent);
mCurrentSendChunk->bytes_sent += new_bytes_sent;
if (mCurrentSendChunk->bytes_sent == mCurrentSendChunk->data.size()) {
delete mCurrentSendChunk;
mCurrentSendChunk = NULL;
}
}
bool CBRSST::send(const Address4& addy, const Network::Chunk& data, bool reliable, bool ordered, int priority) {
trySendCurrentChunk();
if (mCurrentSendChunk != NULL)
return false;
mCurrentSendChunk = new NetworkChunk();
mCurrentSendChunk->addr = addy;
mCurrentSendChunk->data = data;
mCurrentSendChunk->bytes_sent = 0;
trySendCurrentChunk();
return true;
}
Network::Chunk* CBRSST::front(const Address4& from, uint32 max_size) {
assert(from != Address4::Null);
StreamInfo& si = lookupOrConnect(from);
if (si.peek != NULL) return si.peek;
SST::Stream* strm = si.stream;
if (strm->hasPendingMessages() && strm->pendingMessageSize() <= max_size) {
QByteArray msg = strm->peekMessage();
if (msg.isEmpty())
return NULL;
si.peek = new Network::Chunk( (const uint8*)msg.constData(), (const uint8*)msg.constData() + msg.size() );
return si.peek;
}
return NULL;
}
Network::Chunk* CBRSST::receiveOne(const Address4& from, uint32 max_size) {
assert(from != Address4::Null);
StreamInfo& si = lookupOrConnect(from);
SST::Stream* strm = si.stream;
if (strm->hasPendingMessages() && strm->pendingMessageSize() <= max_size) {
QByteArray msg = strm->readMessage();
Network::Chunk* result = si.peek;
if (result) {
assert( result->size() == msg.size() );
si.peek = NULL;
return result;
}
if (msg.isEmpty())
return NULL;
result = new Network::Chunk( (const uint8*)msg.constData(), (const uint8*)msg.constData() + msg.size() );
return result;
}
return NULL;
}
void CBRSST::service() {
mApp->processEvents();
}
void CBRSST::handleConnection() {
while(true) {
SST::Stream *strm = mAcceptor->accept();
if (strm == NULL)
return;
QByteArray remote_id = strm->remoteHostId();
assert( remote_id.size() == 7 && (uint32)remote_id[0] == 8 );
uint32 remote_ip;
uint16 remote_port;
memcpy(&remote_ip, remote_id.constData() + 1, 4);
memcpy(&remote_port, remote_id.constData() + 5, 2);
remote_ip = ntohl(remote_ip);
remote_port = ntohs(remote_port);
qDebug() << "remote ip: " << remote_ip << " remote port: " << remote_port;
//strm->setChildReceiveBuffer(sizeof(qint32));
strm->listen(SST::Stream::Reject);
strm->setParent(this);
connect(strm, SIGNAL(readyReadMessage()),
this, SLOT(handleReadyReadMessage()));
connect(strm, SIGNAL(readyReadDatagram()),
this, SLOT(handleReadyReadDatagram()));
connect(strm, SIGNAL(reset(const QString &)),
this, SLOT(handleReset()));
connect(strm, SIGNAL(newSubstream()),
this, SLOT(handleNewSubstream()), Qt::QueuedConnection);
Address4 remote_addy(remote_ip, remote_port);
SSTStatsListener* stats_listener = new SSTStatsListener(mStartTime);
strm->setStatListener( stats_listener );
StreamInfo si;
si.stream = strm;
si.stats = stats_listener;
assert( mReceiveConnections.find(remote_addy) == mReceiveConnections.end() );
mReceiveConnections[remote_addy] = si;
}
}
void CBRSST::handleReadyReadMessage() {
// don't do anything, they'll be serviced on demand in the receive method
}
void CBRSST::handleReadyReadDatagram() {
assert(false);
}
void CBRSST::handleNewSubstream() {
assert(false);
}
void CBRSST::handleReset() {
SST::Stream* strm = (SST::Stream*)sender();
strm->deleteLater();
}
CBRSST::StreamInfo& CBRSST::lookupOrConnect(const Address4& addy) {
// If we have one, just return it
StreamMap::iterator it = mSendConnections.find(addy);
if (it != mSendConnections.end())
return it->second;
// Otherwise we need to connect
SST::Stream* strm = new SST::Stream(mHost, this);
quint32 addy_ip = htonl(addy.ip);
strm->connectTo(SST::Ident::fromIpAddress(QHostAddress(addy_ip),addy.port).id(), SERVICE_NAME, PROTOCOL_NAME);
SSTStatsListener* stats_listener = new SSTStatsListener(mStartTime);
strm->setStatListener( stats_listener );
StreamInfo si;
si.stream = strm;
si.stats = stats_listener;
si.peek = NULL;
mSendConnections[addy] = si;
it = mSendConnections.find(addy);
return it->second;
}
} // namespace CBR
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 BMW Car IT GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "capu/os/TcpServerSocket.h"
#include "capu/os/Thread.h"
#include "capu/os/TcpSocket.h"
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-generated-matchers.h"
#include "capu/container/HashTable.h"
#include "capu/os/NonBlockSocketChecker.h"
#include "capu/os/Time.h"
class RandomPort
{
public:
/**
* Gets a Random Port between 1024 and 10024
*/
static uint16_t get()
{
return (rand() % 10000) + 40000; // 0-1023 = Well Known, 1024-49151 = User, 49152 - 65535 = Dynamic
}
};
class AsyncSocketHandler
{
public:
AsyncSocketHandler(uint16_t port)
: m_socketInfos()
, m_receiveCount(0)
{
m_serverSocket.bind(port, "0.0.0.0");
m_serverSocket.listen(10);
m_socketInfos.push_back(capu::os::SocketInfoPair(m_serverSocket.getSocketDescription(), capu::os::SocketDelegate::Create<AsyncSocketHandler, &AsyncSocketHandler::acceptConnectionCallback>(*this)));
}
~AsyncSocketHandler()
{
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator current = m_clientSockets.begin();
const capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator end = m_clientSockets.end();
for (; current != end; ++current)
{
current->value->close();
delete current->value;
}
}
void acceptConnectionCallback(const capu::os::SocketDescription& socketDescription)
{
UNUSED(socketDescription);
capu::TcpSocket* clientSocket = m_serverSocket.accept();
EXPECT_TRUE(0 != clientSocket);
m_clientSockets.put(clientSocket->getSocketDescription(), clientSocket);
m_socketInfos.push_back(capu::os::SocketInfoPair(clientSocket->getSocketDescription(), capu::os::SocketDelegate::Create<AsyncSocketHandler, &AsyncSocketHandler::receiveDataCallback>(*this)));
}
void sendSomeData()
{
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator current = m_clientSockets.begin();
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator end = m_clientSockets.end();
for (; current != end; ++current)
{
uint32_t sendValue = 42;
int32_t sendBytes;
current->value->send(reinterpret_cast<char*>(&sendValue), sizeof(sendValue), sendBytes);
}
}
void receiveDataCallback(const capu::os::SocketDescription& socketDescription)
{
int32_t data;
int32_t numbytes = 0;
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator entry = m_clientSockets.find(socketDescription);
if (entry != m_clientSockets.end())
{
EXPECT_EQ(capu::CAPU_OK, entry->value->receive(reinterpret_cast<char*>(&data), sizeof(data), numbytes));
if (numbytes != 0)
{
EXPECT_EQ(42, data);
++m_receiveCount;
}
}
}
capu::Vector<capu::os::SocketInfoPair> m_socketInfos;
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*> m_clientSockets;
capu::TcpServerSocket m_serverSocket;
uint32_t m_receiveCount;
};
class AsyncClient : public capu::Runnable
{
public:
AsyncClient()
: m_port(0)
, m_send(false)
, m_receiveCount(0)
{
}
void receiveSomeData(const capu::os::SocketDescription&)
{
int32_t data;
int32_t numbytes = 0;
EXPECT_EQ(capu::CAPU_OK, m_clientSocket.receive(reinterpret_cast<char*>(&data), sizeof(data), numbytes));
if (numbytes!=0)
{
EXPECT_EQ(42, data);
++m_receiveCount;
}
}
void run()
{
m_clientSocket.setTimeout(1000);
while (m_clientSocket.connect("localhost", m_port) != capu::CAPU_OK){
if (isCancelRequested())
return;
}
m_socketInfos.push_back(capu::os::SocketInfoPair(m_clientSocket.getSocketDescription(), capu::os::SocketDelegate::Create<AsyncClient, &AsyncClient::receiveSomeData>(*this)));
if (m_send)
{
uint32_t sendValue = 42;
int32_t sendBytes = -1;
m_clientSocket.send(reinterpret_cast<char*>(&sendValue), sizeof(sendValue), sendBytes);
EXPECT_EQ(static_cast<int32_t>(sizeof(sendValue)), sendBytes);
}
}
void start(uint16_t port, bool send)
{
m_port = port;
m_send = send;
m_thread.start(*this);
}
void stop()
{
m_thread.cancel();
m_thread.join();
m_clientSocket.close();
}
capu::TcpSocket* getSocket()
{
return &m_clientSocket;
}
uint16_t m_port;
bool m_send;
capu::TcpSocket m_clientSocket;
capu::Thread m_thread;
capu::Vector<capu::os::SocketInfoPair> m_socketInfos;
uint32_t m_receiveCount;
};
TEST(NonBlockSocketCheckerTest, AcceptALotOfClients)
{
static const uint32_t clientcount = 10;
static const uint64_t testtimeout = 5000;
uint16_t port = RandomPort::get();
AsyncSocketHandler asyncSocketHandler(port);
AsyncClient asyncClient[clientcount];
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].start(port, false);
}
uint64_t startTime = capu::Time::GetMilliseconds();
bool timeout = false;
while (asyncSocketHandler.m_clientSockets.count() < clientcount && !timeout)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncSocketHandler.m_socketInfos, 10);
timeout = ((capu::Time::GetMilliseconds() - startTime) > testtimeout);
}
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].stop();
}
EXPECT_FALSE(timeout);
}
TEST(NonBlockSocketCheckerTest, DISABLED_ReceiveDataFromALotOfClients)
{
static const uint32_t clientcount = 50;
uint16_t port = RandomPort::get();
AsyncSocketHandler asyncSocketHandler(port);
AsyncClient asyncClient[clientcount];
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].start(port, true);
}
while (asyncSocketHandler.m_receiveCount < clientcount)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncSocketHandler.m_socketInfos, 10);
}
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].stop();
}
}
TEST(NonBlockSocketCheckerTest, DISABLED_ReceiveDataOnClientSide)
{
uint16_t port = RandomPort::get();
AsyncSocketHandler asyncSocketHandler(port);
AsyncClient asyncClient;
asyncClient.start(port, false);
while (asyncSocketHandler.m_clientSockets.count() < 1)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncSocketHandler.m_socketInfos, 0);
}
asyncSocketHandler.sendSomeData();
while (asyncClient.m_receiveCount < 1)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncClient.m_socketInfos, 1000);
}
asyncClient.stop();
}
<commit_msg>Fix concurrent access on datastructures in socket checker test<commit_after>/*
* Copyright (C) 2012 BMW Car IT GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "capu/os/TcpServerSocket.h"
#include "capu/os/Thread.h"
#include "capu/os/TcpSocket.h"
#include "gmock/gmock-matchers.h"
#include "gmock/gmock-generated-matchers.h"
#include "capu/container/HashTable.h"
#include "capu/os/NonBlockSocketChecker.h"
#include "capu/os/Time.h"
class RandomPort
{
public:
/**
* Gets a Random Port between 1024 and 10024
*/
static uint16_t get()
{
return (rand() % 10000) + 40000; // 0-1023 = Well Known, 1024-49151 = User, 49152 - 65535 = Dynamic
}
};
class AsyncSocketHandler
{
public:
AsyncSocketHandler(uint16_t port)
: m_socketInfos()
, m_receiveCount(0)
{
m_serverSocket.bind(port, "0.0.0.0");
m_serverSocket.listen(10);
m_socketInfos.push_back(capu::os::SocketInfoPair(m_serverSocket.getSocketDescription(), capu::os::SocketDelegate::Create<AsyncSocketHandler, &AsyncSocketHandler::acceptConnectionCallback>(*this)));
}
~AsyncSocketHandler()
{
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator current = m_clientSockets.begin();
const capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator end = m_clientSockets.end();
for (; current != end; ++current)
{
current->value->close();
delete current->value;
}
}
void acceptConnectionCallback(const capu::os::SocketDescription& socketDescription)
{
m_socketLock.lock();
UNUSED(socketDescription);
capu::TcpSocket* clientSocket = m_serverSocket.accept();
EXPECT_TRUE(0 != clientSocket);
m_clientSockets.put(clientSocket->getSocketDescription(), clientSocket);
m_socketInfos.push_back(capu::os::SocketInfoPair(clientSocket->getSocketDescription(), capu::os::SocketDelegate::Create<AsyncSocketHandler, &AsyncSocketHandler::receiveDataCallback>(*this)));
m_socketLock.unlock();
}
void sendSomeData()
{
m_socketLock.lock();
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator current = m_clientSockets.begin();
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator end = m_clientSockets.end();
for (; current != end; ++current)
{
uint32_t sendValue = 42;
int32_t sendBytes;
current->value->send(reinterpret_cast<char*>(&sendValue), sizeof(sendValue), sendBytes);
}
m_socketLock.unlock();
}
void receiveDataCallback(const capu::os::SocketDescription& socketDescription)
{
m_socketLock.lock();
int32_t data;
int32_t numbytes = 0;
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*>::Iterator entry = m_clientSockets.find(socketDescription);
if (entry != m_clientSockets.end())
{
EXPECT_EQ(capu::CAPU_OK, entry->value->receive(reinterpret_cast<char*>(&data), sizeof(data), numbytes));
if (numbytes != 0)
{
EXPECT_EQ(42, data);
++m_receiveCount;
}
}
m_socketLock.unlock();
}
capu::uint_t getNumberOfClientSockets()
{
m_socketLock.lock();
const capu::uint_t num = m_clientSockets.count();
m_socketLock.unlock();
return num;
}
capu::Vector<capu::os::SocketInfoPair> getSocketInfoCopy()
{
m_socketLock.lock();
const capu::Vector<capu::os::SocketInfoPair> copy = m_socketInfos;
m_socketLock.unlock();
return copy;
}
capu::Vector<capu::os::SocketInfoPair> m_socketInfos;
capu::HashTable<capu::os::SocketDescription, capu::TcpSocket*> m_clientSockets;
capu::Mutex m_socketLock;
capu::TcpServerSocket m_serverSocket;
uint32_t m_receiveCount;
};
class AsyncClient : public capu::Runnable
{
public:
AsyncClient()
: m_port(0)
, m_send(false)
, m_receiveCount(0)
{
}
void receiveSomeData(const capu::os::SocketDescription&)
{
int32_t data;
int32_t numbytes = 0;
EXPECT_EQ(capu::CAPU_OK, m_clientSocket.receive(reinterpret_cast<char*>(&data), sizeof(data), numbytes));
if (numbytes!=0)
{
EXPECT_EQ(42, data);
++m_receiveCount;
}
}
void run()
{
m_clientSocket.setTimeout(1000);
while (m_clientSocket.connect("localhost", m_port) != capu::CAPU_OK){
if (isCancelRequested())
return;
}
m_socketInfos.push_back(capu::os::SocketInfoPair(m_clientSocket.getSocketDescription(), capu::os::SocketDelegate::Create<AsyncClient, &AsyncClient::receiveSomeData>(*this)));
if (m_send)
{
uint32_t sendValue = 42;
int32_t sendBytes = -1;
m_clientSocket.send(reinterpret_cast<char*>(&sendValue), sizeof(sendValue), sendBytes);
EXPECT_EQ(static_cast<int32_t>(sizeof(sendValue)), sendBytes);
}
}
void start(uint16_t port, bool send)
{
m_port = port;
m_send = send;
m_thread.start(*this);
}
void stop()
{
m_thread.cancel();
m_thread.join();
m_clientSocket.close();
}
capu::TcpSocket* getSocket()
{
return &m_clientSocket;
}
uint16_t m_port;
bool m_send;
capu::TcpSocket m_clientSocket;
capu::Thread m_thread;
capu::Vector<capu::os::SocketInfoPair> m_socketInfos;
uint32_t m_receiveCount;
};
TEST(NonBlockSocketCheckerTest, AcceptALotOfClients)
{
static const uint32_t clientcount = 10;
static const uint64_t testtimeout = 5000;
uint16_t port = RandomPort::get();
AsyncSocketHandler asyncSocketHandler(port);
AsyncClient asyncClient[clientcount];
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].start(port, false);
}
uint64_t startTime = capu::Time::GetMilliseconds();
bool timeout = false;
while (asyncSocketHandler.getNumberOfClientSockets() < clientcount && !timeout)
{
capu::Vector<capu::os::SocketInfoPair> sockets = asyncSocketHandler.getSocketInfoCopy();
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(sockets, 10);
timeout = ((capu::Time::GetMilliseconds() - startTime) > testtimeout);
}
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].stop();
}
EXPECT_FALSE(timeout);
}
TEST(NonBlockSocketCheckerTest, DISABLED_ReceiveDataFromALotOfClients)
{
static const uint32_t clientcount = 50;
uint16_t port = RandomPort::get();
AsyncSocketHandler asyncSocketHandler(port);
AsyncClient asyncClient[clientcount];
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].start(port, true);
}
while (asyncSocketHandler.m_receiveCount < clientcount)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncSocketHandler.m_socketInfos, 10);
}
for (uint32_t i = 0; i < clientcount; ++i)
{
asyncClient[i].stop();
}
}
TEST(NonBlockSocketCheckerTest, DISABLED_ReceiveDataOnClientSide)
{
uint16_t port = RandomPort::get();
AsyncSocketHandler asyncSocketHandler(port);
AsyncClient asyncClient;
asyncClient.start(port, false);
while (asyncSocketHandler.m_clientSockets.count() < 1)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncSocketHandler.m_socketInfos, 0);
}
asyncSocketHandler.sendSomeData();
while (asyncClient.m_receiveCount < 1)
{
capu::NonBlockSocketChecker::CheckSocketsForIncomingData(asyncClient.m_socketInfos, 1000);
}
asyncClient.stop();
}
<|endoftext|> |
<commit_before>#include "Runtime/Graphics/Shaders/CParticleSwooshShaders.hpp"
#include <iterator>
#include "Runtime/Particle/CParticleSwoosh.hpp"
#include "Runtime/Particle/CSwooshDescription.hpp"
#include <hecl/Pipeline.hpp>
namespace urde {
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texNoZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texAdditiveZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texAdditiveNoZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexNoZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexAdditiveZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexAdditiveNoZWrite;
static boo::ObjToken<boo::IShaderPipeline> s_Pipeline;
void CParticleSwooshShaders::Initialize() {
m_texZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexZWriteAWrite{})};
m_texNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexNoZWriteAWrite{})};
m_texAdditiveZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveZWriteAWrite{})};
m_texAdditiveNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveNoZWriteAWrite{})};
m_noTexZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexZWriteAWrite{})};
m_noTexNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexNoZWriteAWrite{})};
m_noTexAdditiveZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveZWriteAWrite{})};
m_noTexAdditiveNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveNoZWriteAWrite{})};
}
void CParticleSwooshShaders::Shutdown() {
for (auto& s : m_texZWrite) s.reset();
for (auto& s : m_texNoZWrite) s.reset();
for (auto& s : m_texAdditiveZWrite) s.reset();
for (auto& s : m_texAdditiveNoZWrite) s.reset();
for (auto& s : m_noTexZWrite) s.reset();
for (auto& s : m_noTexNoZWrite) s.reset();
for (auto& s : m_noTexAdditiveZWrite) s.reset();
for (auto& s : m_noTexAdditiveNoZWrite) s.reset();
}
CParticleSwooshShaders::EShaderClass CParticleSwooshShaders::GetShaderClass(CParticleSwoosh& gen) {
CSwooshDescription* desc = gen.GetDesc();
if (desc->x3c_TEXR)
return EShaderClass::Tex;
else
return EShaderClass::NoTex;
}
void CParticleSwooshShaders::BuildShaderDataBinding(boo::IGraphicsDataFactory::Context& ctx, CParticleSwoosh& gen) {
CSwooshDescription* desc = gen.GetDesc();
std::array<boo::ObjToken<boo::IShaderPipeline>, 2>* pipeline = nullptr;
if (desc->x3c_TEXR) {
if (desc->x44_31_AALP) {
if (desc->x45_24_ZBUF)
pipeline = &m_texAdditiveZWrite;
else
pipeline = &m_texAdditiveNoZWrite;
} else {
if (desc->x45_24_ZBUF)
pipeline = &m_texZWrite;
else
pipeline = &m_texNoZWrite;
}
} else {
if (desc->x44_31_AALP) {
if (desc->x45_24_ZBUF)
pipeline = &m_noTexAdditiveZWrite;
else
pipeline = &m_noTexAdditiveNoZWrite;
} else {
if (desc->x45_24_ZBUF)
pipeline = &m_noTexZWrite;
else
pipeline = &m_noTexNoZWrite;
}
}
const CUVElement* const texr = desc->x3c_TEXR.get();
const std::array<boo::ObjToken<boo::ITexture>, 1> textures{
texr ? texr->GetValueTexture(0).GetObj()->GetBooTexture() : nullptr,
};
const std::array<boo::ObjToken<boo::IGraphicsBuffer>, 1> uniforms{gen.m_uniformBuf.get()};
for (size_t i = 0; i < gen.m_dataBind.size(); ++i) {
gen.m_dataBind[i] =
ctx.newShaderDataBinding((*pipeline)[i], gen.m_vertBuf.get(), nullptr, nullptr, uniforms.size(),
uniforms.data(), nullptr, texr ? 1 : 0, textures.data(), nullptr, nullptr);
}
}
} // namespace urde
<commit_msg>CParticleSwooshShaders: Remove unused file-scope variable<commit_after>#include "Runtime/Graphics/Shaders/CParticleSwooshShaders.hpp"
#include <iterator>
#include "Runtime/Particle/CParticleSwoosh.hpp"
#include "Runtime/Particle/CSwooshDescription.hpp"
#include <hecl/Pipeline.hpp>
namespace urde {
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texNoZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texAdditiveZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_texAdditiveNoZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexNoZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexAdditiveZWrite;
std::array<boo::ObjToken<boo::IShaderPipeline>, 2> CParticleSwooshShaders::m_noTexAdditiveNoZWrite;
void CParticleSwooshShaders::Initialize() {
m_texZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexZWriteAWrite{})};
m_texNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexNoZWriteAWrite{})};
m_texAdditiveZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveZWriteAWrite{})};
m_texAdditiveNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderTexAdditiveNoZWriteAWrite{})};
m_noTexZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexZWriteAWrite{})};
m_noTexNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexNoZWriteAWrite{})};
m_noTexAdditiveZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveZWriteAWrite{})};
m_noTexAdditiveNoZWrite = {hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveNoZWrite{}),
hecl::conv->convert(Shader_CParticleSwooshShaderNoTexAdditiveNoZWriteAWrite{})};
}
void CParticleSwooshShaders::Shutdown() {
for (auto& s : m_texZWrite) s.reset();
for (auto& s : m_texNoZWrite) s.reset();
for (auto& s : m_texAdditiveZWrite) s.reset();
for (auto& s : m_texAdditiveNoZWrite) s.reset();
for (auto& s : m_noTexZWrite) s.reset();
for (auto& s : m_noTexNoZWrite) s.reset();
for (auto& s : m_noTexAdditiveZWrite) s.reset();
for (auto& s : m_noTexAdditiveNoZWrite) s.reset();
}
CParticleSwooshShaders::EShaderClass CParticleSwooshShaders::GetShaderClass(CParticleSwoosh& gen) {
CSwooshDescription* desc = gen.GetDesc();
if (desc->x3c_TEXR)
return EShaderClass::Tex;
else
return EShaderClass::NoTex;
}
void CParticleSwooshShaders::BuildShaderDataBinding(boo::IGraphicsDataFactory::Context& ctx, CParticleSwoosh& gen) {
CSwooshDescription* desc = gen.GetDesc();
std::array<boo::ObjToken<boo::IShaderPipeline>, 2>* pipeline = nullptr;
if (desc->x3c_TEXR) {
if (desc->x44_31_AALP) {
if (desc->x45_24_ZBUF)
pipeline = &m_texAdditiveZWrite;
else
pipeline = &m_texAdditiveNoZWrite;
} else {
if (desc->x45_24_ZBUF)
pipeline = &m_texZWrite;
else
pipeline = &m_texNoZWrite;
}
} else {
if (desc->x44_31_AALP) {
if (desc->x45_24_ZBUF)
pipeline = &m_noTexAdditiveZWrite;
else
pipeline = &m_noTexAdditiveNoZWrite;
} else {
if (desc->x45_24_ZBUF)
pipeline = &m_noTexZWrite;
else
pipeline = &m_noTexNoZWrite;
}
}
const CUVElement* const texr = desc->x3c_TEXR.get();
const std::array<boo::ObjToken<boo::ITexture>, 1> textures{
texr ? texr->GetValueTexture(0).GetObj()->GetBooTexture() : nullptr,
};
const std::array<boo::ObjToken<boo::IGraphicsBuffer>, 1> uniforms{gen.m_uniformBuf.get()};
for (size_t i = 0; i < gen.m_dataBind.size(); ++i) {
gen.m_dataBind[i] =
ctx.newShaderDataBinding((*pipeline)[i], gen.m_vertBuf.get(), nullptr, nullptr, uniforms.size(),
uniforms.data(), nullptr, texr ? 1 : 0, textures.data(), nullptr, nullptr);
}
}
} // namespace urde
<|endoftext|> |
<commit_before>#include "EcController.h"
#include <mining-manager/ec-submanager/ec_manager.h>
#include <common/Keys.h>
#include <util/ustring/UString.h>
#include <vector>
#include <string>
#include <boost/unordered_set.hpp>
namespace sf1r
{
using driver::Keys;
using namespace izenelib::driver;
bool EcController::check_ec_manager_()
{
boost::shared_ptr<MiningManager> mining_manager = GetMiningManager();
ec_manager_ = mining_manager->GetEcManager();
if(!ec_manager_)
{
response().addError("Ec not enabled.");
return false;
}
return true;
}
bool EcController::require_tid_()
{
if (!izenelib::driver::nullValue( request()[Keys::tid] ) )
{
tid_ = asUint(request()[Keys::tid]);
}
else
{
response().addError("Require field tid in request.");
return false;
}
return true;
}
bool EcController::require_docs_()
{
Value& resources = request()[Keys::docid_list];
std::vector<std::pair<izenelib::util::UString,izenelib::util::UString> > input;
for(uint32_t i=0;i<resources.size();i++)
{
Value& resource = resources(i);
uint32_t docid = asUint(resource[Keys::query]);
docid_list_.push_back(docid);
}
if (docid_list_.empty())
{
response().addError("Require docid_list in request.");
return false;
}
return true;
}
void EcController::get_all_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
std::vector<uint32_t> all_tids;
if(!ec_manager_->GetAllGroupIdList(all_tids))
{
response().addError("GetAllGroupIdList failed.");
return;
}
Value& resources = response()[Keys::resources];
resources.reset<Value::ArrayType>();
for(uint32_t i=0;i<all_tids.size();i++)
{
resources() = all_tids[i];
}
}
void EcController::get_docs_by_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_tid_());
std::vector<uint32_t> docid_list;
std::vector<uint32_t> candidate_list;
if(!ec_manager_->GetGroupAll(tid_, docid_list, candidate_list))
{
response().addError("tid not exists.");
return;
}
Value& resources = response()[Keys::resources];
Value& docs = resources()[Keys::docid_list];
for(uint32_t i=0;i<docid_list.size();i++)
{
docs() = docid_list[i];
}
Value& candidate = resources()[Keys::candidate_list];
for(uint32_t i=0;i<candidate_list.size();i++)
{
candidate() = candidate_list[i];
}
}
void EcController::get_tids_by_docs()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
boost::unordered_set<uint32_t> tid_set;
for(uint32_t i=0;i<docid_list_.size();i++)
{
uint32_t tid = 0;
if(ec_manager_->GetGroupId(docid_list_[i], tid))
{
tid_set.insert(tid);
}
}
std::vector<uint32_t> result;
boost::unordered_set<uint32_t>::iterator it = tid_set.begin();
while(it!=tid_set.end())
{
result.push_back(*it);
++it;
}
std::sort(result.begin(), result.end());
Value& resources = response()[Keys::resources];
for(uint32_t i=0;i<result.size();i++)
{
resources() = result[i];
}
}
void EcController::add_new_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
std::vector<uint32_t> candidate_list;
uint32_t tid = 0;
if(!ec_manager_->AddNewGroup(docid_list_, candidate_list, tid))
{
response().addError("AddNewGroup failed.");
return;
}
response()[Keys::tid] = tid;
}
void EcController::add_docs_to_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_tid_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
if(!ec_manager_->AddDocInGroup(tid_, docid_list_))
{
response().addError("AddDocInGroup failed.");
return;
}
}
void EcController::remove_docs_from_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_tid_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
if(!ec_manager_->RemoveDocInGroup(tid_, docid_list_))
{
response().addError("RemoveDocInGroup failed.");
return;
}
}
}
<commit_msg>ec controller api docs.<commit_after>#include "EcController.h"
#include <mining-manager/ec-submanager/ec_manager.h>
#include <common/Keys.h>
#include <util/ustring/UString.h>
#include <vector>
#include <string>
#include <boost/unordered_set.hpp>
namespace sf1r
{
using driver::Keys;
using namespace izenelib::driver;
bool EcController::check_ec_manager_()
{
boost::shared_ptr<MiningManager> mining_manager = GetMiningManager();
ec_manager_ = mining_manager->GetEcManager();
if(!ec_manager_)
{
response().addError("Ec not enabled.");
return false;
}
return true;
}
bool EcController::require_tid_()
{
if (!izenelib::driver::nullValue( request()[Keys::tid] ) )
{
tid_ = asUint(request()[Keys::tid]);
}
else
{
response().addError("Require field tid in request.");
return false;
}
return true;
}
bool EcController::require_docs_()
{
Value& resources = request()[Keys::docid_list];
std::vector<std::pair<izenelib::util::UString,izenelib::util::UString> > input;
for(uint32_t i=0;i<resources.size();i++)
{
Value& resource = resources(i);
uint32_t docid = asUint(resource[Keys::query]);
docid_list_.push_back(docid);
}
if (docid_list_.empty())
{
response().addError("Require docid_list in request.");
return false;
}
return true;
}
/**
* @brief Action \b get_all_tid. Get all exist tids.
*
* @section request
*
* - @b collection* (@c String): Collection name.
* - @b tid* (@c Uint): specify tid
*
* @section response
*
* - @b resources (@c Array): Every item is a tid.
*
*
* @section Example
*
* Request
* @code
* {
* "collection" : "intel",
* "tid": 1
* }
* @endcode
*
* Response
* @code
* {
* "header": {"success": true},
* "resources" : [3,4]
* }
* @endcode
*/
void EcController::get_all_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
std::vector<uint32_t> all_tids;
if(!ec_manager_->GetAllGroupIdList(all_tids))
{
response().addError("GetAllGroupIdList failed.");
return;
}
Value& resources = response()[Keys::resources];
resources.reset<Value::ArrayType>();
for(uint32_t i=0;i<all_tids.size();i++)
{
resources() = all_tids[i];
}
}
/**
* @brief Action \b get_docs_by_tid. Get documents id by tid.
*
* @section request
*
* - @b collection* (@c String): Collection name.
* - @b tid* (@c Uint): specify tid
*
* @section response
*
* - @b resources (@c Array): Every item is a document id.
*
*
* @section Example
*
* Request
* @code
* {
* "collection" : "intel",
* "tid": 1
* }
* @endcode
*
* Response
* @code
* {
* "header": {"success": true},
* "resources" : [3,4]
* }
* @endcode
*/
void EcController::get_docs_by_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_tid_());
std::vector<uint32_t> docid_list;
std::vector<uint32_t> candidate_list;
if(!ec_manager_->GetGroupAll(tid_, docid_list, candidate_list))
{
response().addError("tid not exists.");
return;
}
Value& resources = response()[Keys::resources];
Value& docs = resources()[Keys::docid_list];
for(uint32_t i=0;i<docid_list.size();i++)
{
docs() = docid_list[i];
}
Value& candidate = resources()[Keys::candidate_list];
for(uint32_t i=0;i<candidate_list.size();i++)
{
candidate() = candidate_list[i];
}
}
/**
* @brief Action \b get_tids_by_docs. Get tid list by documents id list.
*
* @section request
*
* - @b collection* (@c String): Collection name.
* - @b docid_list* (@c Array): document id list
*
* @section response
*
* - @b resources (@c Array): Every item is a tid.
*
*
* @section Example
*
* Request
* @code
* {
* "collection" : "intel",
* "docid_list": [5,6,7,8]
* }
* @endcode
*
* Response
* @code
* {
* "header": {"success": true},
* "resources" : [3,4]
* }
* @endcode
*/
void EcController::get_tids_by_docs()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
boost::unordered_set<uint32_t> tid_set;
for(uint32_t i=0;i<docid_list_.size();i++)
{
uint32_t tid = 0;
if(ec_manager_->GetGroupId(docid_list_[i], tid))
{
tid_set.insert(tid);
}
}
std::vector<uint32_t> result;
boost::unordered_set<uint32_t>::iterator it = tid_set.begin();
while(it!=tid_set.end())
{
result.push_back(*it);
++it;
}
std::sort(result.begin(), result.end());
Value& resources = response()[Keys::resources];
for(uint32_t i=0;i<result.size();i++)
{
resources() = result[i];
}
}
/**
* @brief Action \b add_new_tid. Use new documents id list to generate a new tid group
*
* @section request
*
* - @b collection* (@c String): Collection name.
* - @b docid_list* (@c Array): document id list
*
* @section response
*
* - @b tid (@c Uint): Generated tid
*
*
* @section Example
*
* Request
* @code
* {
* "collection" : "intel",
* "docid_list": [5,6,7,8]
* }
* @endcode
*
* Response
* @code
* {
* "header": {"success": true},
* "tid" : 1
* }
* @endcode
*/
void EcController::add_new_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
std::vector<uint32_t> candidate_list;
uint32_t tid = 0;
if(!ec_manager_->AddNewGroup(docid_list_, candidate_list, tid))
{
response().addError("AddNewGroup failed.");
return;
}
response()[Keys::tid] = tid;
}
/**
* @brief Action \b add_docs_to_tid. Add documents id list to exist tid group
*
* @section request
*
* - @b collection* (@c String): Collection name.
* - @b tid* (@c Uint): tid.
* - @b docid_list* (@c Array): document id list
*
* @section response
*
*
*
* @section Example
*
* Request
* @code
* {
* "collection" : "intel",
* "tid" : 1,
* "docid_list": [5,6,7,8]
* }
* @endcode
*
* Response
* @code
* {
* "header": {"success": true},
* }
* @endcode
*/
void EcController::add_docs_to_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_tid_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
if(!ec_manager_->AddDocInGroup(tid_, docid_list_))
{
response().addError("AddDocInGroup failed.");
return;
}
}
/**
* @brief Action \b remove_docs_from_tid. Remove documents id list from exist tid group
*
* @section request
*
* - @b collection* (@c String): Collection name.
* - @b tid* (@c Uint): tid.
* - @b docid_list* (@c Array): document id list
*
* @section response
*
*
*
* @section Example
*
* Request
* @code
* {
* "collection" : "intel",
* "tid" : 1,
* "docid_list": [5,6,7,8]
* }
* @endcode
*
* Response
* @code
* {
* "header": {"success": true},
* }
* @endcode
*/
void EcController::remove_docs_from_tid()
{
IZENELIB_DRIVER_BEFORE_HOOK(check_ec_manager_());
IZENELIB_DRIVER_BEFORE_HOOK(require_tid_());
IZENELIB_DRIVER_BEFORE_HOOK(require_docs_());
if(!ec_manager_->RemoveDocInGroup(tid_, docid_list_))
{
response().addError("RemoveDocInGroup failed.");
return;
}
}
}
<|endoftext|> |
<commit_before>#include "proximitylist_api.h"
#include "type/pb_converter.h"
#include "utils/paginate.h"
namespace navitia { namespace proximitylist {
/**
* se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre
*
*/
typedef std::tuple<nt::idx_t, nt::GeographicalCoord, nt::Type_e> t_result;
typedef std::pair<nt::idx_t, nt::GeographicalCoord> idx_coord;
void create_pb(const std::vector<t_result>& result, uint32_t depth, const nt::Data& data,
pbnavitia::Response& pb_response, type::GeographicalCoord coord){
for(auto result_item : result){
pbnavitia::Place* place = pb_response.add_places_nearby();
//on récupére la date pour les impacts
auto current_date = boost::posix_time::second_clock::local_time();
auto idx = std::get<0>(result_item);
auto coord_item = std::get<1>(result_item);
auto type = std::get<2>(result_item);
switch(type){
case nt::Type_e::StopArea:
fill_pb_object(data.pt_data.stop_areas[idx], data, place->mutable_stop_area(), depth,
current_date);
place->set_name(data.pt_data.stop_areas[idx]->name);
place->set_uri(data.pt_data.stop_areas[idx]->uri);
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::STOP_AREA);
break;
case nt::Type_e::StopPoint:
fill_pb_object(data.pt_data.stop_points[idx], data, place->mutable_stop_point(), depth,
current_date);
place->set_name(data.pt_data.stop_points[idx]->name);
place->set_uri(data.pt_data.stop_points[idx]->uri);
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::STOP_POINT);
break;
case nt::Type_e::POI:
fill_pb_object(data.geo_ref.pois[idx], data, place->mutable_poi(), depth,
current_date);
place->set_name(data.geo_ref.pois[idx]->name);
place->set_uri(data.geo_ref.pois[idx]->uri);
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::POI);
break;
default:
break;
}
}
}
pbnavitia::Response find(const type::GeographicalCoord& coord, const double distance,
const std::vector<nt::Type_e>& filter,
const uint32_t depth, const uint32_t count, const uint32_t start_page,
const type::Data & data) {
pbnavitia::Response response;
int total_result = 0;
std::vector<t_result > result;
auto end_pagination = (start_page+1)*count;
for(nt::Type_e type : filter){
std::vector<idx_coord> list;
switch(type){
case nt::Type_e::StopArea:
list = data.pt_data.stop_area_proximity_list.find_within(coord, distance);
break;
case nt::Type_e::StopPoint:
list = data.pt_data.stop_point_proximity_list.find_within(coord, distance);
break;
case nt::Type_e::POI:
list = data.geo_ref.poi_proximity_list.find_within(coord, distance);
break;
default: break;
}
if(!list.empty()) {
total_result += list.size();
auto nb_sort = (list.size() < end_pagination) ? list.size():end_pagination;
std::partial_sort(list.begin(), list.begin() + nb_sort, list.end(),
[&](idx_coord a, idx_coord b)
{return coord.distance_to(a.second)< coord.distance_to(b.second);});
list.resize(nb_sort);
for(auto idx_coord : list) {
result.push_back(t_result(idx_coord.first, idx_coord.second, type));
}
}
}
auto nb_sort = (result.size() < end_pagination) ? result.size():end_pagination;
std::partial_sort(result.begin(), result.begin() + nb_sort, result.end(),
[&](t_result t1, t_result t2)
{ auto a = std::get<1>(t1); auto b = std::get<1>(t2);
return coord.distance_to(a)< coord.distance_to(b);});
result = paginate(result, count, start_page);
create_pb(result, depth, data, response, coord);
auto pagination = response.mutable_pagination();
pagination->set_totalresult(total_result);
pagination->set_startpage(start_page);
pagination->set_itemsperpage(count);
pagination->set_itemsonpage(result.size());
return response;
}
}} // namespace navitia::proximitylist
<commit_msg>Kraken : Ajout des addresses dans proximity_list<commit_after>#include "proximitylist_api.h"
#include "type/pb_converter.h"
#include "utils/paginate.h"
namespace navitia { namespace proximitylist {
/**
* se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre
*
*/
typedef std::tuple<nt::idx_t, nt::GeographicalCoord, nt::Type_e> t_result;
typedef std::pair<nt::idx_t, nt::GeographicalCoord> idx_coord;
void create_pb(const std::vector<t_result>& result, uint32_t depth, const nt::Data& data,
pbnavitia::Response& pb_response, type::GeographicalCoord coord){
for(auto result_item : result){
pbnavitia::Place* place = pb_response.add_places_nearby();
//on récupére la date pour les impacts
auto current_date = boost::posix_time::second_clock::local_time();
auto idx = std::get<0>(result_item);
auto coord_item = std::get<1>(result_item);
auto type = std::get<2>(result_item);
switch(type){
case nt::Type_e::StopArea:
fill_pb_object(data.pt_data.stop_areas[idx], data, place->mutable_stop_area(), depth,
current_date);
place->set_name(data.pt_data.stop_areas[idx]->name);
place->set_uri(data.pt_data.stop_areas[idx]->uri);
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::STOP_AREA);
break;
case nt::Type_e::StopPoint:
fill_pb_object(data.pt_data.stop_points[idx], data, place->mutable_stop_point(), depth,
current_date);
place->set_name(data.pt_data.stop_points[idx]->name);
place->set_uri(data.pt_data.stop_points[idx]->uri);
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::STOP_POINT);
break;
case nt::Type_e::POI:
fill_pb_object(data.geo_ref.pois[idx], data, place->mutable_poi(), depth,
current_date);
place->set_name(data.geo_ref.pois[idx]->name);
place->set_uri(data.geo_ref.pois[idx]->uri);
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::POI);
break;
case nt::Type_e::Address:
fill_pb_object(data.geo_ref.ways[idx], data, place->mutable_address(),
data.geo_ref.ways[idx]->nearest_number(coord), coord , depth);
place->set_name(data.geo_ref.ways[idx]->name);
place->set_uri(data.geo_ref.ways[idx]->uri + ":" + boost::lexical_cast<std::string>(data.geo_ref.ways[idx]->nearest_number(coord)));
place->set_distance(coord.distance_to(coord_item));
place->set_embedded_type(pbnavitia::ADDRESS);
default:
break;
}
}
}
template<typename T>
void sort_cut(std::vector<T> &list, const uint32_t end_pagination,
const type::GeographicalCoord& coord) {
if(!list.empty()) {
auto nb_sort = (list.size() < end_pagination) ? list.size():end_pagination;
std::partial_sort(list.begin(), list.begin() + nb_sort, list.end(),
[&](idx_coord a, idx_coord b)
{return coord.distance_to(a.second)< coord.distance_to(b.second);});
list.resize(nb_sort);
}
}
pbnavitia::Response find(const type::GeographicalCoord& coord, const double distance,
const std::vector<nt::Type_e>& filter,
const uint32_t depth, const uint32_t count, const uint32_t start_page,
const type::Data & data) {
pbnavitia::Response response;
int total_result = 0;
std::vector<t_result > result;
auto end_pagination = (start_page+1)*count;
for(nt::Type_e type : filter){
if(type == nt::Type_e::Address) {
try {
georef::edge_t e = data.geo_ref.nearest_edge(coord, data.geo_ref.pl);
++ total_result;
georef::Way *way = data.geo_ref.ways[data.geo_ref.graph[e].way_idx];
result.push_back(t_result(way->idx, coord, type));
} catch(proximitylist::NotFound) {}
} else{
std::vector< std::pair<type::idx_t, type::GeographicalCoord> > list;
switch(type){
case nt::Type_e::StopArea:
list = data.pt_data.stop_area_proximity_list.find_within(coord, distance);
break;
case nt::Type_e::StopPoint:
list = data.pt_data.stop_point_proximity_list.find_within(coord, distance);
break;
case nt::Type_e::POI:
list = data.geo_ref.poi_proximity_list.find_within(coord, distance);
break;
default: break;
}
total_result += list.size();
sort_cut<idx_coord>(list, end_pagination, coord);
for(auto idx_coord : list) {
result.push_back(t_result(idx_coord.first, idx_coord.second, type));
}
}
}
auto nb_sort = (result.size() < end_pagination) ? result.size():end_pagination;
std::partial_sort(result.begin(), result.begin() + nb_sort, result.end(),
[&](t_result t1, t_result t2)
{ auto a = std::get<1>(t1); auto b = std::get<1>(t2);
return coord.distance_to(a)< coord.distance_to(b);});
result = paginate(result, count, start_page);
create_pb(result, depth, data, response, coord);
auto pagination = response.mutable_pagination();
pagination->set_totalresult(total_result);
pagination->set_startpage(start_page);
pagination->set_itemsperpage(count);
pagination->set_itemsonpage(result.size());
return response;
}
}} // namespace navitia::proximitylist
<|endoftext|> |
<commit_before>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <Nazara/Renderer/RenderBuffer.hpp>
#include <Nazara/Utility/AbstractBuffer.hpp>
#include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <filesystem>
#include <Nazara/Renderer/Debug.hpp>
#ifdef NAZARA_DEBUG
#define NazaraRendererPattern "Nazara?*Renderer-d" NAZARA_DYNLIB_EXTENSION
#else
#define NazaraRendererPattern "Nazara?*Renderer" NAZARA_DYNLIB_EXTENSION
#endif
namespace Nz
{
bool Renderer::Initialize()
{
if (s_moduleReferenceCounter > 0)
{
s_moduleReferenceCounter++;
return true; // Already initialized
}
// Initialize module dependencies
if (!Utility::Initialize())
{
NazaraError("Failed to initialize Utility module");
return false;
}
if (!Platform::Initialize())
{
NazaraError("Failed to initialize Platform module");
return false;
}
s_moduleReferenceCounter++;
CallOnExit onExit(Renderer::Uninitialize);
NazaraDebug("Searching for renderer implementation");
DynLib chosenLib;
std::unique_ptr<RendererImpl> chosenImpl;
for (auto&& entry : std::filesystem::directory_iterator("."))
{
if (!entry.is_regular_file())
continue;
const std::filesystem::path& entryPath = entry.path();
std::filesystem::path fileName = entryPath.filename();
std::string fileNameStr = fileName.generic_u8string();
if (!MatchPattern(fileNameStr, NazaraRendererPattern))
continue;
NazaraDebug("Trying to load " + fileNameStr);
DynLib implLib;
if (!implLib.Load(entryPath))
{
NazaraWarning("Failed to load " + fileNameStr + ": " + implLib.GetLastError());
continue;
}
CreateRendererImplFunc createRenderer = reinterpret_cast<CreateRendererImplFunc>(implLib.GetSymbol("NazaraRenderer_Instantiate"));
if (!createRenderer)
{
NazaraDebug("Skipped " + fileNameStr + " (symbol not found)");
continue;
}
std::unique_ptr<RendererImpl> impl(createRenderer());
if (!impl || !impl->Prepare(s_initializationParameters))
{
NazaraError("Failed to create renderer implementation");
continue;
}
NazaraDebug("Loaded " + impl->QueryAPIString());
if (!chosenImpl || impl->IsBetterThan(chosenImpl.get()))
{
if (chosenImpl)
NazaraDebug("Choose " + impl->QueryAPIString() + " over " + chosenImpl->QueryAPIString());
chosenLib = std::move(implLib);
chosenImpl = std::move(impl);
}
}
if (!chosenImpl)
{
NazaraError("No renderer found");
return false;
}
s_rendererImpl = std::move(chosenImpl);
s_rendererLib = std::move(chosenLib);
NazaraDebug("Using " + s_rendererImpl->QueryAPIString() + " as renderer");
Buffer::SetBufferFactory(DataStorage_Hardware, CreateHardwareBufferImpl);
onExit.Reset();
NazaraNotice("Initialized: Renderer module");
return true;
}
void Renderer::Uninitialize()
{
if (s_moduleReferenceCounter != 1)
{
// Either the module is not initialized, either it was initialized multiple times
if (s_moduleReferenceCounter > 1)
s_moduleReferenceCounter--;
return;
}
s_moduleReferenceCounter = 0;
// Uninitialize module here
Buffer::SetBufferFactory(DataStorage_Hardware, nullptr);
s_rendererImpl.reset();
s_rendererLib.Unload();
NazaraNotice("Uninitialized: Renderer module");
// Free module dependencies
Platform::Uninitialize();
Utility::Uninitialize();
}
AbstractBuffer* Renderer::CreateHardwareBufferImpl(Buffer* parent, BufferType type)
{
return new RenderBuffer(parent, type);
}
std::unique_ptr<RendererImpl> Renderer::s_rendererImpl;
DynLib Renderer::s_rendererLib;
ParameterList Renderer::s_initializationParameters;
unsigned int Renderer::s_moduleReferenceCounter = 0;
}
<commit_msg>Renderer: Fix crash when choosing another renderer<commit_after>// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Renderer/Renderer.hpp>
#include <Nazara/Core/CallOnExit.hpp>
#include <Nazara/Core/DynLib.hpp>
#include <Nazara/Core/Log.hpp>
#include <Nazara/Core/StringExt.hpp>
#include <Nazara/Platform/Platform.hpp>
#include <Nazara/Renderer/RenderBuffer.hpp>
#include <Nazara/Utility/AbstractBuffer.hpp>
#include <Nazara/Utility/Buffer.hpp>
#include <Nazara/Utility/Utility.hpp>
#include <filesystem>
#include <Nazara/Renderer/Debug.hpp>
#ifdef NAZARA_DEBUG
#define NazaraRendererPattern "Nazara?*Renderer-d" NAZARA_DYNLIB_EXTENSION
#else
#define NazaraRendererPattern "Nazara?*Renderer" NAZARA_DYNLIB_EXTENSION
#endif
namespace Nz
{
bool Renderer::Initialize()
{
if (s_moduleReferenceCounter > 0)
{
s_moduleReferenceCounter++;
return true; // Already initialized
}
// Initialize module dependencies
if (!Utility::Initialize())
{
NazaraError("Failed to initialize Utility module");
return false;
}
if (!Platform::Initialize())
{
NazaraError("Failed to initialize Platform module");
return false;
}
s_moduleReferenceCounter++;
CallOnExit onExit(Renderer::Uninitialize);
NazaraDebug("Searching for renderer implementation");
DynLib chosenLib;
std::unique_ptr<RendererImpl> chosenImpl;
for (auto&& entry : std::filesystem::directory_iterator("."))
{
if (!entry.is_regular_file())
continue;
const std::filesystem::path& entryPath = entry.path();
std::filesystem::path fileName = entryPath.filename();
std::string fileNameStr = fileName.generic_u8string();
if (!MatchPattern(fileNameStr, NazaraRendererPattern))
continue;
NazaraDebug("Trying to load " + fileNameStr);
DynLib implLib;
if (!implLib.Load(entryPath))
{
NazaraWarning("Failed to load " + fileNameStr + ": " + implLib.GetLastError());
continue;
}
CreateRendererImplFunc createRenderer = reinterpret_cast<CreateRendererImplFunc>(implLib.GetSymbol("NazaraRenderer_Instantiate"));
if (!createRenderer)
{
NazaraDebug("Skipped " + fileNameStr + " (symbol not found)");
continue;
}
std::unique_ptr<RendererImpl> impl(createRenderer());
if (!impl || !impl->Prepare(s_initializationParameters))
{
NazaraError("Failed to create renderer implementation");
continue;
}
NazaraDebug("Loaded " + impl->QueryAPIString());
if (!chosenImpl || impl->IsBetterThan(chosenImpl.get()))
{
if (chosenImpl)
NazaraDebug("Choose " + impl->QueryAPIString() + " over " + chosenImpl->QueryAPIString());
chosenImpl = std::move(impl); //< Move (and delete previous) implementation before unloading library
chosenLib = std::move(implLib);
}
}
if (!chosenImpl)
{
NazaraError("No renderer found");
return false;
}
s_rendererImpl = std::move(chosenImpl);
s_rendererLib = std::move(chosenLib);
NazaraDebug("Using " + s_rendererImpl->QueryAPIString() + " as renderer");
Buffer::SetBufferFactory(DataStorage_Hardware, CreateHardwareBufferImpl);
onExit.Reset();
NazaraNotice("Initialized: Renderer module");
return true;
}
void Renderer::Uninitialize()
{
if (s_moduleReferenceCounter != 1)
{
// Either the module is not initialized, either it was initialized multiple times
if (s_moduleReferenceCounter > 1)
s_moduleReferenceCounter--;
return;
}
s_moduleReferenceCounter = 0;
// Uninitialize module here
Buffer::SetBufferFactory(DataStorage_Hardware, nullptr);
s_rendererImpl.reset();
s_rendererLib.Unload();
NazaraNotice("Uninitialized: Renderer module");
// Free module dependencies
Platform::Uninitialize();
Utility::Uninitialize();
}
AbstractBuffer* Renderer::CreateHardwareBufferImpl(Buffer* parent, BufferType type)
{
return new RenderBuffer(parent, type);
}
std::unique_ptr<RendererImpl> Renderer::s_rendererImpl;
DynLib Renderer::s_rendererLib;
ParameterList Renderer::s_initializationParameters;
unsigned int Renderer::s_moduleReferenceCounter = 0;
}
<|endoftext|> |
<commit_before>/*
* OpenNI2Interface.cpp
*
* Created on: 20 May 2013
* Author: thomas
*/
#include "OpenNI2Interface.h"
OpenNI2Interface::OpenNI2Interface(int inWidth, int inHeight, int fps)
: width(inWidth),
height(inHeight),
fps(fps),
initSuccessful(true)
{
//Setup
openni::Status rc = openni::STATUS_OK;
const char * deviceURI = openni::ANY_DEVICE;
rc = openni::OpenNI::initialize();
std::string errorString(openni::OpenNI::getExtendedError());
if(errorString.length() > 0)
{
errorText.append(errorString);
initSuccessful = false;
}
else
{
rc = device.open(deviceURI);
if (rc != openni::STATUS_OK)
{
errorText.append(openni::OpenNI::getExtendedError());
openni::OpenNI::shutdown();
initSuccessful = false;
}
else
{
device.setProperty(XN_MODULE_PROPERTY_USB_INTERFACE, XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS);
rc = depthStream.create(device, openni::SENSOR_DEPTH);
if (rc == openni::STATUS_OK)
{
rc = depthStream.start();
if (rc != openni::STATUS_OK)
{
errorText.append(openni::OpenNI::getExtendedError());
depthStream.destroy();
initSuccessful = false;
}
}
else
{
errorText.append(openni::OpenNI::getExtendedError());
initSuccessful = false;
}
rc = rgbStream.create(device, openni::SENSOR_COLOR);
if (rc == openni::STATUS_OK)
{
rc = rgbStream.start();
if (rc != openni::STATUS_OK)
{
errorText.append(openni::OpenNI::getExtendedError());
rgbStream.destroy();
initSuccessful = false;
}
}
else
{
errorText.append(openni::OpenNI::getExtendedError());
initSuccessful = false;
}
if (!depthStream.isValid() || !rgbStream.isValid())
{
errorText.append(openni::OpenNI::getExtendedError());
openni::OpenNI::shutdown();
initSuccessful = false;
}
if(initSuccessful)
{
rgbStream.setProperty(XN_STREAM_PROPERTY_INPUT_FORMAT, XN_IO_IMAGE_FORMAT_UNCOMPRESSED_YUV422);
//For printing out
formatMap[openni::PIXEL_FORMAT_DEPTH_1_MM] = "1mm";
formatMap[openni::PIXEL_FORMAT_DEPTH_100_UM] = "100um";
formatMap[openni::PIXEL_FORMAT_SHIFT_9_2] = "Shift 9 2";
formatMap[openni::PIXEL_FORMAT_SHIFT_9_3] = "Shift 9 3";
formatMap[openni::PIXEL_FORMAT_RGB888] = "RGB888";
formatMap[openni::PIXEL_FORMAT_YUV422] = "YUV422";
formatMap[openni::PIXEL_FORMAT_GRAY8] = "GRAY8";
formatMap[openni::PIXEL_FORMAT_GRAY16] = "GRAY16";
formatMap[openni::PIXEL_FORMAT_JPEG] = "JPEG";
assert(findMode(width, height, fps) && "Sorry, mode not supported!");
openni::VideoMode depthMode;
depthMode.setFps(fps);
depthMode.setPixelFormat(openni::PIXEL_FORMAT_DEPTH_1_MM);
depthMode.setResolution(width, height);
openni::VideoMode colorMode;
colorMode.setFps(fps);
colorMode.setPixelFormat(openni::PIXEL_FORMAT_RGB888);
colorMode.setResolution(width, height);
depthStream.setVideoMode(depthMode);
rgbStream.setVideoMode(colorMode);
depthStream.setMirroringEnabled(false);
rgbStream.setMirroringEnabled(false);
device.setDepthColorSyncEnabled(true);
device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);
setAutoExposure(false);
setAutoWhiteBalance(false);
latestDepthIndex.assignValue(-1);
latestRgbIndex.assignValue(-1);
for(int i = 0; i < numBuffers; i++)
{
uint8_t * newImage = (uint8_t *)calloc(width * height * 3, sizeof(uint8_t));
rgbBuffers[i] = std::pair<uint8_t *, int64_t>(newImage, 0);
}
for(int i = 0; i < numBuffers; i++)
{
uint8_t * newDepth = (uint8_t *)calloc(width * height * 2, sizeof(uint8_t));
uint8_t * newImage = (uint8_t *)calloc(width * height * 3, sizeof(uint8_t));
frameBuffers[i] = std::pair<std::pair<uint8_t *, uint8_t *>, int64_t>(std::pair<uint8_t *, uint8_t *>(newDepth, newImage), 0);
}
rgbCallback = new RGBCallback(lastRgbTime,
latestRgbIndex,
rgbBuffers);
depthCallback = new DepthCallback(lastDepthTime,
latestDepthIndex,
latestRgbIndex,
rgbBuffers,
frameBuffers);
rgbStream.addNewFrameListener(rgbCallback);
depthStream.addNewFrameListener(depthCallback);
}
}
}
}
OpenNI2Interface::~OpenNI2Interface()
{
if(initSuccessful)
{
rgbStream.removeNewFrameListener(rgbCallback);
depthStream.removeNewFrameListener(depthCallback);
depthStream.stop();
rgbStream.stop();
depthStream.destroy();
rgbStream.destroy();
device.close();
openni::OpenNI::shutdown();
for(int i = 0; i < numBuffers; i++)
{
free(rgbBuffers[i].first);
}
for(int i = 0; i < numBuffers; i++)
{
free(frameBuffers[i].first.first);
free(frameBuffers[i].first.second);
}
delete rgbCallback;
delete depthCallback;
}
}
bool OpenNI2Interface::findMode(int x, int y, int fps)
{
const openni::Array<openni::VideoMode> & depthModes = depthStream.getSensorInfo().getSupportedVideoModes();
bool found = false;
for(int i = 0; i < depthModes.getSize(); i++)
{
if(depthModes[i].getResolutionX() == x &&
depthModes[i].getResolutionY() == y &&
depthModes[i].getFps() == fps)
{
found = true;
break;
}
}
if(!found)
{
return false;
}
found = false;
const openni::Array<openni::VideoMode> & rgbModes = rgbStream.getSensorInfo().getSupportedVideoModes();
for(int i = 0; i < rgbModes.getSize(); i++)
{
if(rgbModes[i].getResolutionX() == x &&
rgbModes[i].getResolutionY() == y &&
rgbModes[i].getFps() == fps)
{
found = true;
break;
}
}
return found;
}
void OpenNI2Interface::printModes()
{
const openni::Array<openni::VideoMode> & depthModes = depthStream.getSensorInfo().getSupportedVideoModes();
openni::VideoMode currentDepth = depthStream.getVideoMode();
std::cout << "Depth Modes: (" << currentDepth.getResolutionX() <<
"x" <<
currentDepth.getResolutionY() <<
" @ " <<
currentDepth.getFps() <<
"fps " <<
formatMap[currentDepth.getPixelFormat()] << ")" << std::endl;
for(int i = 0; i < depthModes.getSize(); i++)
{
std::cout << depthModes[i].getResolutionX() <<
"x" <<
depthModes[i].getResolutionY() <<
" @ " <<
depthModes[i].getFps() <<
"fps " <<
formatMap[depthModes[i].getPixelFormat()] << std::endl;
}
const openni::Array<openni::VideoMode> & rgbModes = rgbStream.getSensorInfo().getSupportedVideoModes();
openni::VideoMode currentRGB = depthStream.getVideoMode();
std::cout << "RGB Modes: (" << currentRGB.getResolutionX() <<
"x" <<
currentRGB.getResolutionY() <<
" @ " <<
currentRGB.getFps() <<
"fps " <<
formatMap[currentRGB.getPixelFormat()] << ")" << std::endl;
for(int i = 0; i < rgbModes.getSize(); i++)
{
std::cout << rgbModes[i].getResolutionX() <<
"x" <<
rgbModes[i].getResolutionY() <<
" @ " <<
rgbModes[i].getFps() <<
"fps " <<
formatMap[rgbModes[i].getPixelFormat()] << std::endl;
}
}
void OpenNI2Interface::setAutoExposure(bool value)
{
rgbStream.getCameraSettings()->setAutoExposureEnabled(value);
}
void OpenNI2Interface::setAutoWhiteBalance(bool value)
{
rgbStream.getCameraSettings()->setAutoWhiteBalanceEnabled(value);
}
bool OpenNI2Interface::getAutoExposure()
{
return rgbStream.getCameraSettings()->getAutoExposureEnabled();
}
bool OpenNI2Interface::getAutoWhiteBalance()
{
return rgbStream.getCameraSettings()->getAutoWhiteBalanceEnabled();
}
<commit_msg>Update OpenNI2Interface.cpp<commit_after>/*
* OpenNI2Interface.cpp
*
* Created on: 20 May 2013
* Author: thomas
*/
#include "OpenNI2Interface.h"
OpenNI2Interface::OpenNI2Interface(int inWidth, int inHeight, int fps)
: width(inWidth),
height(inHeight),
fps(fps),
initSuccessful(true)
{
//Setup
openni::Status rc = openni::STATUS_OK;
const char * deviceURI = openni::ANY_DEVICE;
rc = openni::OpenNI::initialize();
std::string errorString(openni::OpenNI::getExtendedError());
if(errorString.length() > 0)
{
errorText.append(errorString);
initSuccessful = false;
}
else
{
rc = device.open(deviceURI);
if (rc != openni::STATUS_OK)
{
errorText.append(openni::OpenNI::getExtendedError());
openni::OpenNI::shutdown();
initSuccessful = false;
}
else
{
rc = depthStream.create(device, openni::SENSOR_DEPTH);
if (rc == openni::STATUS_OK)
{
rc = depthStream.start();
if (rc != openni::STATUS_OK)
{
errorText.append(openni::OpenNI::getExtendedError());
depthStream.destroy();
initSuccessful = false;
}
}
else
{
errorText.append(openni::OpenNI::getExtendedError());
initSuccessful = false;
}
rc = rgbStream.create(device, openni::SENSOR_COLOR);
if (rc == openni::STATUS_OK)
{
rc = rgbStream.start();
if (rc != openni::STATUS_OK)
{
errorText.append(openni::OpenNI::getExtendedError());
rgbStream.destroy();
initSuccessful = false;
}
}
else
{
errorText.append(openni::OpenNI::getExtendedError());
initSuccessful = false;
}
if (!depthStream.isValid() || !rgbStream.isValid())
{
errorText.append(openni::OpenNI::getExtendedError());
openni::OpenNI::shutdown();
initSuccessful = false;
}
if(initSuccessful)
{
//For printing out
formatMap[openni::PIXEL_FORMAT_DEPTH_1_MM] = "1mm";
formatMap[openni::PIXEL_FORMAT_DEPTH_100_UM] = "100um";
formatMap[openni::PIXEL_FORMAT_SHIFT_9_2] = "Shift 9 2";
formatMap[openni::PIXEL_FORMAT_SHIFT_9_3] = "Shift 9 3";
formatMap[openni::PIXEL_FORMAT_RGB888] = "RGB888";
formatMap[openni::PIXEL_FORMAT_YUV422] = "YUV422";
formatMap[openni::PIXEL_FORMAT_GRAY8] = "GRAY8";
formatMap[openni::PIXEL_FORMAT_GRAY16] = "GRAY16";
formatMap[openni::PIXEL_FORMAT_JPEG] = "JPEG";
assert(findMode(width, height, fps) && "Sorry, mode not supported!");
openni::VideoMode depthMode;
depthMode.setFps(fps);
depthMode.setPixelFormat(openni::PIXEL_FORMAT_DEPTH_1_MM);
depthMode.setResolution(width, height);
openni::VideoMode colorMode;
colorMode.setFps(fps);
colorMode.setPixelFormat(openni::PIXEL_FORMAT_RGB888);
colorMode.setResolution(width, height);
depthStream.setVideoMode(depthMode);
rgbStream.setVideoMode(colorMode);
depthStream.setMirroringEnabled(false);
rgbStream.setMirroringEnabled(false);
device.setDepthColorSyncEnabled(true);
device.setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR);
setAutoExposure(false);
setAutoWhiteBalance(false);
latestDepthIndex.assignValue(-1);
latestRgbIndex.assignValue(-1);
for(int i = 0; i < numBuffers; i++)
{
uint8_t * newImage = (uint8_t *)calloc(width * height * 3, sizeof(uint8_t));
rgbBuffers[i] = std::pair<uint8_t *, int64_t>(newImage, 0);
}
for(int i = 0; i < numBuffers; i++)
{
uint8_t * newDepth = (uint8_t *)calloc(width * height * 2, sizeof(uint8_t));
uint8_t * newImage = (uint8_t *)calloc(width * height * 3, sizeof(uint8_t));
frameBuffers[i] = std::pair<std::pair<uint8_t *, uint8_t *>, int64_t>(std::pair<uint8_t *, uint8_t *>(newDepth, newImage), 0);
}
rgbCallback = new RGBCallback(lastRgbTime,
latestRgbIndex,
rgbBuffers);
depthCallback = new DepthCallback(lastDepthTime,
latestDepthIndex,
latestRgbIndex,
rgbBuffers,
frameBuffers);
rgbStream.addNewFrameListener(rgbCallback);
depthStream.addNewFrameListener(depthCallback);
}
}
}
}
OpenNI2Interface::~OpenNI2Interface()
{
if(initSuccessful)
{
rgbStream.removeNewFrameListener(rgbCallback);
depthStream.removeNewFrameListener(depthCallback);
depthStream.stop();
rgbStream.stop();
depthStream.destroy();
rgbStream.destroy();
device.close();
openni::OpenNI::shutdown();
for(int i = 0; i < numBuffers; i++)
{
free(rgbBuffers[i].first);
}
for(int i = 0; i < numBuffers; i++)
{
free(frameBuffers[i].first.first);
free(frameBuffers[i].first.second);
}
delete rgbCallback;
delete depthCallback;
}
}
bool OpenNI2Interface::findMode(int x, int y, int fps)
{
const openni::Array<openni::VideoMode> & depthModes = depthStream.getSensorInfo().getSupportedVideoModes();
bool found = false;
for(int i = 0; i < depthModes.getSize(); i++)
{
if(depthModes[i].getResolutionX() == x &&
depthModes[i].getResolutionY() == y &&
depthModes[i].getFps() == fps)
{
found = true;
break;
}
}
if(!found)
{
return false;
}
found = false;
const openni::Array<openni::VideoMode> & rgbModes = rgbStream.getSensorInfo().getSupportedVideoModes();
for(int i = 0; i < rgbModes.getSize(); i++)
{
if(rgbModes[i].getResolutionX() == x &&
rgbModes[i].getResolutionY() == y &&
rgbModes[i].getFps() == fps)
{
found = true;
break;
}
}
return found;
}
void OpenNI2Interface::printModes()
{
const openni::Array<openni::VideoMode> & depthModes = depthStream.getSensorInfo().getSupportedVideoModes();
openni::VideoMode currentDepth = depthStream.getVideoMode();
std::cout << "Depth Modes: (" << currentDepth.getResolutionX() <<
"x" <<
currentDepth.getResolutionY() <<
" @ " <<
currentDepth.getFps() <<
"fps " <<
formatMap[currentDepth.getPixelFormat()] << ")" << std::endl;
for(int i = 0; i < depthModes.getSize(); i++)
{
std::cout << depthModes[i].getResolutionX() <<
"x" <<
depthModes[i].getResolutionY() <<
" @ " <<
depthModes[i].getFps() <<
"fps " <<
formatMap[depthModes[i].getPixelFormat()] << std::endl;
}
const openni::Array<openni::VideoMode> & rgbModes = rgbStream.getSensorInfo().getSupportedVideoModes();
openni::VideoMode currentRGB = depthStream.getVideoMode();
std::cout << "RGB Modes: (" << currentRGB.getResolutionX() <<
"x" <<
currentRGB.getResolutionY() <<
" @ " <<
currentRGB.getFps() <<
"fps " <<
formatMap[currentRGB.getPixelFormat()] << ")" << std::endl;
for(int i = 0; i < rgbModes.getSize(); i++)
{
std::cout << rgbModes[i].getResolutionX() <<
"x" <<
rgbModes[i].getResolutionY() <<
" @ " <<
rgbModes[i].getFps() <<
"fps " <<
formatMap[rgbModes[i].getPixelFormat()] << std::endl;
}
}
void OpenNI2Interface::setAutoExposure(bool value)
{
rgbStream.getCameraSettings()->setAutoExposureEnabled(value);
}
void OpenNI2Interface::setAutoWhiteBalance(bool value)
{
rgbStream.getCameraSettings()->setAutoWhiteBalanceEnabled(value);
}
bool OpenNI2Interface::getAutoExposure()
{
return rgbStream.getCameraSettings()->getAutoExposureEnabled();
}
bool OpenNI2Interface::getAutoWhiteBalance()
{
return rgbStream.getCameraSettings()->getAutoWhiteBalanceEnabled();
}
<|endoftext|> |
<commit_before>#include "test.h"
#include <RobustWiFiServer.h>
void prepareState(ServerState state, RobustWiFiServer& rs) {
WiFiClient& c = rs._getClient();
WiFiServer& s = rs._getServer();
switch(state){
case DISCONNECTED:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case ERR_SSID_NOT_AVAIL:
WiFi.setStatus(WL_NO_SSID_AVAIL);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case SERVER_LISTENING:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(true);
c.setAvailable(false);
c.setConnected(false);
break;
case CLIENT_CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(false);
c.setConnected(true);
break;
case DATA_AVAILABLE:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(true);
c.setConnected(true);
break;
default:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
}
printf("test");
rs._printInternalState();
}
void client_connect(RobustWiFiServer& rs) {
printf("test> client connects.\n");
prepareState(CLIENT_CONNECTED, rs);
}
void client_disconnects(RobustWiFiServer& rs) {
printf("test> client disconnects.\n");
prepareState(SERVER_LISTENING, rs);
}
void client_send_data(RobustWiFiServer& rs) {
printf("test> client sends data.\n");
prepareState(DATA_AVAILABLE, rs);
}
void wifi_disconnects(RobustWiFiServer& rs) {
printf("test> wifi disconnects.\n");
prepareState(ERR_SSID_NOT_AVAIL, rs);
}
const String ssid = "MY_SSID";
const String password = "my_password";
IPAddress myIP(192,168,1,127);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
uint16_t port = 1110;
TEST(StaticHandler, runthruWithDisconnect){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
// protocol:
// connects ordinary
// client disconnects
// wifi breaks down
// wifi back
// connect ordinary
for (int i=0; i<=15; i++){
printf("%d\n", i);
wifiServer.loop();
ServerState state = wifiServer.getState();
switch(i){
case 0:
EXPECT_EQ(state, DISCONNECTED);
//prepareState(CONNECTED, wifiServer);
break;
case 1:
EXPECT_EQ(state, CONNECTED);
//prepareState(SERVER_LISTENING, wifiServer);
break;
case 2:
EXPECT_EQ(state, SERVER_LISTENING);
client_connect(wifiServer);
break;
case 3:
EXPECT_EQ(state, CLIENT_CONNECTED);
client_send_data(wifiServer);
break;
case 4:
EXPECT_EQ(state, DATA_AVAILABLE);
client_disconnects(wifiServer);
break;
case 5:
EXPECT_EQ(state, CLIENT_CONNECTED);
wifi_disconnects(wifiServer);
break;
case 6:
case 7:
case 8:
case 9:
// will not allow that connect succeeds
wifi_disconnects(wifiServer);
break;
// needs 3 iterations back to disconnected
case 10:
case 11:
EXPECT_EQ(state, ERR_SSID_NOT_AVAIL);
WiFi.setNumSSIDs(0);
break;
case 12:
WiFi.setNumSSIDs(1);
break;
case 13:
EXPECT_EQ(state, DISCONNECTED);
break;
case 14:
EXPECT_EQ(state, CONNECTED);
break;
}
}
}
TEST(StaticHandler, runWithTimeout){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
WiFi.setNumSSIDs(0);
for (int i=0; i<=7; i++){
printf("%d\n", i);
mock_increaseTime(1000);
wifiServer.loop();
// dont succeed server start
prepareState(DISCONNECTED, wifiServer);
ServerCondition cond = wifiServer.getCondition();
switch(i){
case 0:
case 1:
case 2:
case 3:
EXPECT_EQ(cond.numberOfTimeouts, 0);
break;
case 4:
// timeout occured
EXPECT_EQ(cond.numberOfTimeouts, 1);
break;
}
}
} <commit_msg>more test cond<commit_after>#include "test.h"
#include <RobustWiFiServer.h>
void prepareState(ServerState state, RobustWiFiServer& rs) {
WiFiClient& c = rs._getClient();
WiFiServer& s = rs._getServer();
switch(state){
case DISCONNECTED:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case ERR_SSID_NOT_AVAIL:
WiFi.setStatus(WL_NO_SSID_AVAIL);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
case SERVER_LISTENING:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(false);
s.setListening(true);
c.setAvailable(false);
c.setConnected(false);
break;
case CLIENT_CONNECTED:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(false);
c.setConnected(true);
break;
case DATA_AVAILABLE:
WiFi.setStatus(WL_CONNECTED);
s.setAvailable(true);
s.setListening(true);
c.setAvailable(true);
c.setConnected(true);
break;
default:
WiFi.setStatus(WL_DISCONNECTED);
s.setAvailable(false);
s.setListening(false);
c.setAvailable(false);
c.setConnected(false);
break;
}
printf("test");
rs._printInternalState();
}
void client_connect(RobustWiFiServer& rs) {
printf("test> client connects.\n");
prepareState(CLIENT_CONNECTED, rs);
}
void client_disconnects(RobustWiFiServer& rs) {
printf("test> client disconnects.\n");
prepareState(SERVER_LISTENING, rs);
}
void client_send_data(RobustWiFiServer& rs) {
printf("test> client sends data.\n");
prepareState(DATA_AVAILABLE, rs);
}
void wifi_disconnects(RobustWiFiServer& rs) {
printf("test> wifi disconnects.\n");
prepareState(ERR_SSID_NOT_AVAIL, rs);
}
const String ssid = "MY_SSID";
const String password = "my_password";
IPAddress myIP(192,168,1,127);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
uint16_t port = 1110;
TEST(StaticHandler, runthruWithDisconnect){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
// protocol:
// connects ordinary
// client disconnects
// wifi breaks down
// wifi back
// connect ordinary
for (int i=0; i<=15; i++){
printf("%d\n", i);
wifiServer.loop();
ServerCondition cond = wifiServer.getCondition();
ServerState state = wifiServer.getState();
switch(i){
case 0:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(CONNECTED, wifiServer);
break;
case 1:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
//prepareState(SERVER_LISTENING, wifiServer);
break;
case 2:
EXPECT_EQ(state, SERVER_LISTENING);
EXPECT_EQ(cond.error, NO_ERROR);
client_connect(wifiServer);
break;
case 3:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
client_send_data(wifiServer);
break;
case 4:
EXPECT_EQ(state, DATA_AVAILABLE);
EXPECT_EQ(cond.error, NO_ERROR);
client_disconnects(wifiServer);
break;
case 5:
EXPECT_EQ(state, CLIENT_CONNECTED);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
wifi_disconnects(wifiServer);
break;
case 6:
case 7:
case 8:
case 9:
// will not allow that connect succeeds
wifi_disconnects(wifiServer);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
break;
// needs 3 iterations back to disconnected
case 10:
case 11:
EXPECT_EQ(state, ERR_SSID_NOT_AVAIL);
EXPECT_EQ(cond.error, STATE_CHECK_FAILED);
WiFi.setNumSSIDs(0);
break;
case 12:
WiFi.setNumSSIDs(1);
break;
case 13:
EXPECT_EQ(state, DISCONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
case 14:
EXPECT_EQ(state, CONNECTED);
EXPECT_EQ(cond.error, NO_ERROR);
break;
}
}
}
TEST(StaticHandler, runWithTimeout){
RobustWiFiServer wifiServer;
wifiServer.init(myIP, gateway, subnet, port, ssid, password);
wifiServer.connect();
prepareState(DISCONNECTED, wifiServer);
EXPECT_EQ( wifiServer.getState(), DISCONNECTED);
WiFi.setNumSSIDs(0);
for (int i=0; i<=7; i++){
printf("%d\n", i);
mock_increaseTime(1000);
wifiServer.loop();
// dont succeed server start
prepareState(DISCONNECTED, wifiServer);
ServerCondition cond = wifiServer.getCondition();
switch(i){
case 0:
case 1:
case 2:
case 3:
EXPECT_EQ(cond.error, NO_ERROR);
EXPECT_EQ(cond.numberOfTimeouts, 0);
break;
case 4:
// timeout occured
EXPECT_EQ(cond.error, TRANSITION_TIMEOUT_REACHED);
EXPECT_EQ(cond.numberOfTimeouts, 1);
break;
}
}
} <|endoftext|> |
<commit_before>/*
* 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* RobeWidget.cpp
* Read and Write to a Robe USB Widget.
* Copyright (C) 2011 Simon Newton
*/
#include <string.h>
#include <string>
#include <vector>
#include "ola/BaseTypes.h"
#include "ola/Logging.h"
#include "ola/rdm/RDMCommand.h"
#include "ola/rdm/UID.h"
#include "ola/rdm/UIDSet.h"
#include "plugins/usbpro/RobeWidget.h"
namespace ola {
namespace plugin {
namespace usbpro {
using ola::rdm::UID;
using ola::rdm::UIDSet;
// The DMX frames have an extra 4 bytes at the end
const int RobeWidgetImpl::DMX_FRAME_DATA_SIZE = DMX_UNIVERSE_SIZE + 4;
RobeWidgetImpl::RobeWidgetImpl(ola::io::ConnectedDescriptor *descriptor,
ola::thread::SchedulingExecutorInterface *ss,
const ola::rdm::UID &uid)
: BaseRobeWidget(descriptor),
m_ss(ss),
m_rdm_request_callback(NULL),
m_mute_callback(NULL),
m_unmute_callback(NULL),
m_branch_callback(NULL),
m_discovery_agent(this),
m_dmx_callback(NULL),
m_pending_request(NULL),
m_uid(uid),
m_transaction_number(0) {
}
/**
* Stop the widget.
*/
void RobeWidgetImpl::Stop() {
std::vector<std::string> packets;
if (m_rdm_request_callback) {
ola::rdm::RDMCallback *callback = m_rdm_request_callback;
m_rdm_request_callback = NULL;
callback->Run(ola::rdm::RDM_TIMEOUT, NULL, packets);
}
m_discovery_agent.Abort();
if (m_pending_request) {
delete m_pending_request;
m_pending_request = NULL;
}
}
/**
* Send DMX
* @param buffer the DMX data
*/
bool RobeWidgetImpl::SendDMX(const DmxBuffer &buffer) {
// the data is 512 + an extra 4 bytes
uint8_t output_data[DMX_FRAME_DATA_SIZE];
memset(output_data, 0, DMX_FRAME_DATA_SIZE);
unsigned int length = DMX_UNIVERSE_SIZE;
buffer.Get(output_data, &length);
return SendMessage(CHANNEL_A_OUT,
reinterpret_cast<uint8_t*>(&output_data),
length + 4);
}
/**
* Send a RDM Message
*/
void RobeWidgetImpl::SendRDMRequest(const ola::rdm::RDMRequest *request,
ola::rdm::RDMCallback *on_complete) {
std::vector<string> packets;
if (m_rdm_request_callback) {
OLA_FATAL << "Previous request hasn't completed yet, dropping request";
on_complete->Run(ola::rdm::RDM_FAILED_TO_SEND, NULL, packets);
delete request;
return;
}
// prepare the buffer for the RDM data, we don't need to include the start
// code. We need to include 4 bytes at the end, these bytes can be any value.
unsigned int data_size = request->Size() + RDM_PADDING_BYTES;
uint8_t *data = new uint8_t[data_size];
memset(data, 0, data_size);
unsigned int this_transaction_number = m_transaction_number++;
unsigned int port_id = 1;
bool r = request->PackWithControllerParams(data,
&data_size,
m_uid,
this_transaction_number,
port_id);
if (!r) {
OLA_WARN << "Failed to pack message, dropping request";
delete[] data;
delete request;
on_complete->Run(ola::rdm::RDM_FAILED_TO_SEND, NULL, packets);
return;
}
m_rdm_request_callback = on_complete;
// convert the request into one that matches this widget
m_pending_request = request->DuplicateWithControllerParams(
m_uid,
this_transaction_number,
port_id);
delete request;
OLA_DEBUG << "Sending RDM command to Robe Widget";
if (!SendMessage(BaseRobeWidget::RDM_REQUEST, data, data_size +
RDM_PADDING_BYTES)) {
m_rdm_request_callback = NULL;
m_pending_request = NULL;
delete[] data;
delete request;
on_complete->Run(ola::rdm::RDM_FAILED_TO_SEND, NULL, packets);
return;
}
delete[] data;
// sent ok
if (m_pending_request->DestinationUID().IsBroadcast()) {
m_rdm_request_callback = NULL;
delete m_pending_request;
m_pending_request = NULL;
on_complete->Run(ola::rdm::RDM_WAS_BROADCAST, NULL, packets);
}
}
/**
* Perform full discovery.
*/
void RobeWidgetImpl::RunFullDiscovery(
ola::rdm::RDMDiscoveryCallback *callback) {
OLA_INFO << "Full discovery";
m_discovery_agent.StartFullDiscovery(
ola::NewSingleCallback(this,
&RobeWidgetImpl::DiscoveryComplete,
callback));
}
/**
* Perform incremental discovery.
*/
void RobeWidgetImpl::RunIncrementalDiscovery(
ola::rdm::RDMDiscoveryCallback *callback) {
OLA_INFO << "Incremental discovery";
m_discovery_agent.StartIncrementalDiscovery(
ola::NewSingleCallback(this,
&RobeWidgetImpl::DiscoveryComplete,
callback));
}
/**
* Change to receive mode.
*/
bool RobeWidgetImpl::ChangeToReceiveMode() {
m_buffer.Reset();
return SendMessage(DMX_IN_REQUEST, NULL, 0);
}
void RobeWidgetImpl::SetDmxCallback(Callback0<void> *callback) {
m_dmx_callback.reset(callback);
}
/**
* Mute a responder
* @param target the UID to mute
* @param MuteDeviceCallback the callback to run once the mute request
* completes.
*/
void RobeWidgetImpl::MuteDevice(const UID &target,
MuteDeviceCallback *mute_complete) {
ola::rdm::MuteRequest mute_request(
m_uid,
target,
m_transaction_number++);
unsigned int length = mute_request.Size();
uint8_t data[length + RDM_PADDING_BYTES];
memset(data, 0, length + RDM_PADDING_BYTES);
mute_request.Pack(data, &length);
OLA_DEBUG << "Muting " << target;
bool r = SendMessage(RDM_REQUEST,
data,
length + RDM_PADDING_BYTES);
if (r)
m_mute_callback = mute_complete;
else
mute_complete->Run(false);
}
/**
* Unmute all responders
* @param UnMuteDeviceCallback the callback to run once the unmute request
* completes.
*/
void RobeWidgetImpl::UnMuteAll(UnMuteDeviceCallback *unmute_complete) {
ola::rdm::UnMuteRequest unmute_request(
m_uid,
ola::rdm::UID::AllDevices(),
m_transaction_number++);
unsigned int length = unmute_request.Size();
uint8_t data[length + RDM_PADDING_BYTES];
memset(data, 0, length + RDM_PADDING_BYTES);
unmute_request.Pack(data, &length);
OLA_DEBUG << "UnMuting all devices";
SendMessage(RDM_REQUEST,
data,
length + RDM_PADDING_BYTES);
m_unmute_callback = unmute_complete;
}
/**
* Send a Discovery Unique Branch
*/
void RobeWidgetImpl::Branch(const UID &lower,
const UID &upper,
BranchCallback *callback) {
ola::rdm::DiscoveryUniqueBranchRequest branch_request(
m_uid,
lower,
upper,
m_transaction_number++);
unsigned int length = branch_request.Size();
uint8_t data[length + RDM_PADDING_BYTES];
memset(data + length, 0, RDM_PADDING_BYTES);
branch_request.Pack(data, &length);
SendMessage(RDM_DISCOVERY,
data,
length + RDM_PADDING_BYTES);
m_branch_callback = callback;
}
/**
* Handle a Robe message
*/
void RobeWidgetImpl::HandleMessage(uint8_t label,
const uint8_t *data,
unsigned int length) {
switch (label) {
case BaseRobeWidget::RDM_RESPONSE:
HandleRDMResponse(data, length);
return;
case BaseRobeWidget::RDM_DISCOVERY_RESPONSE:
HandleDiscoveryResponse(data, length);
return;
case DMX_IN_RESPONSE:
HandleDmxFrame(data, length);
return;
default:
OLA_INFO << "Unknown message from Robe widget " << std::hex <<
static_cast<unsigned int>(label);
}
}
/**
* Handle a RDM response
*/
void RobeWidgetImpl::HandleRDMResponse(const uint8_t *data,
unsigned int length) {
OLA_DEBUG << "Got RDM Response from Robe Widget";
std::vector<std::string> packets;
if (m_unmute_callback) {
UnMuteDeviceCallback *callback = m_unmute_callback;
m_unmute_callback = NULL;
callback->Run();
return;
}
if (m_mute_callback) {
MuteDeviceCallback *callback = m_mute_callback;
m_mute_callback = NULL;
// TODO(simon): actually check the response here
callback->Run(length > RDM_PADDING_BYTES);
return;
}
if (m_rdm_request_callback == NULL) {
OLA_FATAL << "Got a RDM response but no callback to run!";
return;
}
ola::rdm::RDMCallback *callback = m_rdm_request_callback;
m_rdm_request_callback = NULL;
const ola::rdm::RDMRequest *request = m_pending_request;
m_pending_request = NULL;
if (length == RDM_PADDING_BYTES) {
// this indicates that no request was recieved
callback->Run(ola::rdm::RDM_TIMEOUT, NULL, packets);
delete request;
return;
}
string packet;
packet.assign(reinterpret_cast<const char*>(data), length);
packets.push_back(packet);
// try to inflate
ola::rdm::rdm_response_code response_code;
ola::rdm::RDMResponse *response = ola::rdm::RDMResponse::InflateFromData(
packet,
&response_code,
request);
callback->Run(response_code, response, packets);
delete request;
}
/**
* Handle a response to a Discovery unique branch request
*/
void RobeWidgetImpl::HandleDiscoveryResponse(const uint8_t *data,
unsigned int length) {
if (m_branch_callback) {
BranchCallback *callback = m_branch_callback;
m_branch_callback = NULL;
// there are always 4 bytes padded on the end of the response
if (length <= RDM_PADDING_BYTES)
callback->Run(NULL, 0);
else
callback->Run(data, length - RDM_PADDING_BYTES);
} else {
OLA_WARN << "Got response to DUB but no callback defined!";
}
}
/**
* Called when the discovery process finally completes
* @param callback the callback passed to StartFullDiscovery or
* StartIncrementalDiscovery that we should execute.
* @param status true if discovery worked, false otherwise
* @param uids the UIDSet of UIDs that were found.
*/
void RobeWidgetImpl::DiscoveryComplete(
ola::rdm::RDMDiscoveryCallback *callback,
bool status,
const UIDSet &uids) {
if (callback)
callback->Run(uids);
(void) status;
}
/**
* Handle DMX data
*/
void RobeWidgetImpl::HandleDmxFrame(const uint8_t *data, unsigned int length) {
m_buffer.Set(data, length);
if (m_dmx_callback.get())
m_dmx_callback->Run();
}
/**
* RobeWidget Constructor
*/
RobeWidget::RobeWidget(ola::io::ConnectedDescriptor *descriptor,
ola::thread::SchedulingExecutorInterface *ss,
const ola::rdm::UID &uid,
unsigned int queue_size) {
m_impl = new RobeWidgetImpl(descriptor, ss, uid);
m_controller = new ola::rdm::DiscoverableQueueingRDMController(m_impl,
queue_size);
}
RobeWidget::~RobeWidget() {
// delete the controller after the impl because the controller owns the
// callback
delete m_impl;
delete m_controller;
}
} // usbpro
} // plugin
} // ola
<commit_msg> * add more Robe RDM debug infomation<commit_after>/*
* 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* RobeWidget.cpp
* Read and Write to a Robe USB Widget.
* Copyright (C) 2011 Simon Newton
*/
#include <string.h>
#include <string>
#include <vector>
#include "ola/BaseTypes.h"
#include "ola/Logging.h"
#include "ola/rdm/RDMCommand.h"
#include "ola/rdm/UID.h"
#include "ola/rdm/UIDSet.h"
#include "plugins/usbpro/RobeWidget.h"
namespace ola {
namespace plugin {
namespace usbpro {
using ola::rdm::UID;
using ola::rdm::UIDSet;
// The DMX frames have an extra 4 bytes at the end
const int RobeWidgetImpl::DMX_FRAME_DATA_SIZE = DMX_UNIVERSE_SIZE + 4;
RobeWidgetImpl::RobeWidgetImpl(ola::io::ConnectedDescriptor *descriptor,
ola::thread::SchedulingExecutorInterface *ss,
const ola::rdm::UID &uid)
: BaseRobeWidget(descriptor),
m_ss(ss),
m_rdm_request_callback(NULL),
m_mute_callback(NULL),
m_unmute_callback(NULL),
m_branch_callback(NULL),
m_discovery_agent(this),
m_dmx_callback(NULL),
m_pending_request(NULL),
m_uid(uid),
m_transaction_number(0) {
}
/**
* Stop the widget.
*/
void RobeWidgetImpl::Stop() {
std::vector<std::string> packets;
if (m_rdm_request_callback) {
ola::rdm::RDMCallback *callback = m_rdm_request_callback;
m_rdm_request_callback = NULL;
callback->Run(ola::rdm::RDM_TIMEOUT, NULL, packets);
}
m_discovery_agent.Abort();
if (m_pending_request) {
delete m_pending_request;
m_pending_request = NULL;
}
}
/**
* Send DMX
* @param buffer the DMX data
*/
bool RobeWidgetImpl::SendDMX(const DmxBuffer &buffer) {
// the data is 512 + an extra 4 bytes
uint8_t output_data[DMX_FRAME_DATA_SIZE];
memset(output_data, 0, DMX_FRAME_DATA_SIZE);
unsigned int length = DMX_UNIVERSE_SIZE;
buffer.Get(output_data, &length);
return SendMessage(CHANNEL_A_OUT,
reinterpret_cast<uint8_t*>(&output_data),
length + 4);
}
/**
* Send a RDM Message
*/
void RobeWidgetImpl::SendRDMRequest(const ola::rdm::RDMRequest *request,
ola::rdm::RDMCallback *on_complete) {
std::vector<string> packets;
if (m_rdm_request_callback) {
OLA_FATAL << "Previous request hasn't completed yet, dropping request";
on_complete->Run(ola::rdm::RDM_FAILED_TO_SEND, NULL, packets);
delete request;
return;
}
// prepare the buffer for the RDM data, we don't need to include the start
// code. We need to include 4 bytes at the end, these bytes can be any value.
unsigned int data_size = request->Size() + RDM_PADDING_BYTES;
uint8_t *data = new uint8_t[data_size];
memset(data, 0, data_size);
unsigned int this_transaction_number = m_transaction_number++;
unsigned int port_id = 1;
bool r = request->PackWithControllerParams(data,
&data_size,
m_uid,
this_transaction_number,
port_id);
if (!r) {
OLA_WARN << "Failed to pack message, dropping request";
delete[] data;
delete request;
on_complete->Run(ola::rdm::RDM_FAILED_TO_SEND, NULL, packets);
return;
}
m_rdm_request_callback = on_complete;
// convert the request into one that matches this widget
m_pending_request = request->DuplicateWithControllerParams(
m_uid,
this_transaction_number,
port_id);
delete request;
OLA_DEBUG << "Sending RDM command. CC: 0x" << std::hex <<
request->CommandClass() << ", PID 0x" << std::hex << request->ParamId() <<
", TN: " << this_transaction_number;
if (!SendMessage(BaseRobeWidget::RDM_REQUEST, data, data_size +
RDM_PADDING_BYTES)) {
m_rdm_request_callback = NULL;
m_pending_request = NULL;
delete[] data;
delete request;
on_complete->Run(ola::rdm::RDM_FAILED_TO_SEND, NULL, packets);
return;
}
delete[] data;
// sent ok
if (m_pending_request->DestinationUID().IsBroadcast()) {
m_rdm_request_callback = NULL;
delete m_pending_request;
m_pending_request = NULL;
on_complete->Run(ola::rdm::RDM_WAS_BROADCAST, NULL, packets);
}
}
/**
* Perform full discovery.
*/
void RobeWidgetImpl::RunFullDiscovery(
ola::rdm::RDMDiscoveryCallback *callback) {
OLA_INFO << "Full discovery";
m_discovery_agent.StartFullDiscovery(
ola::NewSingleCallback(this,
&RobeWidgetImpl::DiscoveryComplete,
callback));
}
/**
* Perform incremental discovery.
*/
void RobeWidgetImpl::RunIncrementalDiscovery(
ola::rdm::RDMDiscoveryCallback *callback) {
OLA_INFO << "Incremental discovery";
m_discovery_agent.StartIncrementalDiscovery(
ola::NewSingleCallback(this,
&RobeWidgetImpl::DiscoveryComplete,
callback));
}
/**
* Change to receive mode.
*/
bool RobeWidgetImpl::ChangeToReceiveMode() {
m_buffer.Reset();
return SendMessage(DMX_IN_REQUEST, NULL, 0);
}
void RobeWidgetImpl::SetDmxCallback(Callback0<void> *callback) {
m_dmx_callback.reset(callback);
}
/**
* Mute a responder
* @param target the UID to mute
* @param MuteDeviceCallback the callback to run once the mute request
* completes.
*/
void RobeWidgetImpl::MuteDevice(const UID &target,
MuteDeviceCallback *mute_complete) {
ola::rdm::MuteRequest mute_request(
m_uid,
target,
m_transaction_number++);
unsigned int length = mute_request.Size();
uint8_t data[length + RDM_PADDING_BYTES];
memset(data, 0, length + RDM_PADDING_BYTES);
mute_request.Pack(data, &length);
OLA_DEBUG << "Muting " << target;
bool r = SendMessage(RDM_REQUEST,
data,
length + RDM_PADDING_BYTES);
if (r)
m_mute_callback = mute_complete;
else
mute_complete->Run(false);
}
/**
* Unmute all responders
* @param UnMuteDeviceCallback the callback to run once the unmute request
* completes.
*/
void RobeWidgetImpl::UnMuteAll(UnMuteDeviceCallback *unmute_complete) {
ola::rdm::UnMuteRequest unmute_request(
m_uid,
ola::rdm::UID::AllDevices(),
m_transaction_number++);
unsigned int length = unmute_request.Size();
uint8_t data[length + RDM_PADDING_BYTES];
memset(data, 0, length + RDM_PADDING_BYTES);
unmute_request.Pack(data, &length);
OLA_DEBUG << "UnMuting all devices";
SendMessage(RDM_REQUEST,
data,
length + RDM_PADDING_BYTES);
m_unmute_callback = unmute_complete;
}
/**
* Send a Discovery Unique Branch
*/
void RobeWidgetImpl::Branch(const UID &lower,
const UID &upper,
BranchCallback *callback) {
ola::rdm::DiscoveryUniqueBranchRequest branch_request(
m_uid,
lower,
upper,
m_transaction_number++);
unsigned int length = branch_request.Size();
uint8_t data[length + RDM_PADDING_BYTES];
memset(data + length, 0, RDM_PADDING_BYTES);
branch_request.Pack(data, &length);
SendMessage(RDM_DISCOVERY,
data,
length + RDM_PADDING_BYTES);
m_branch_callback = callback;
}
/**
* Handle a Robe message
*/
void RobeWidgetImpl::HandleMessage(uint8_t label,
const uint8_t *data,
unsigned int length) {
switch (label) {
case BaseRobeWidget::RDM_RESPONSE:
HandleRDMResponse(data, length);
return;
case BaseRobeWidget::RDM_DISCOVERY_RESPONSE:
HandleDiscoveryResponse(data, length);
return;
case DMX_IN_RESPONSE:
HandleDmxFrame(data, length);
return;
default:
OLA_INFO << "Unknown message from Robe widget " << std::hex <<
static_cast<unsigned int>(label);
}
}
/**
* Handle a RDM response
*/
void RobeWidgetImpl::HandleRDMResponse(const uint8_t *data,
unsigned int length) {
OLA_DEBUG << "Got RDM Response from Robe Widget";
std::vector<std::string> packets;
if (m_unmute_callback) {
UnMuteDeviceCallback *callback = m_unmute_callback;
m_unmute_callback = NULL;
callback->Run();
return;
}
if (m_mute_callback) {
MuteDeviceCallback *callback = m_mute_callback;
m_mute_callback = NULL;
// TODO(simon): actually check the response here
callback->Run(length > RDM_PADDING_BYTES);
return;
}
if (m_rdm_request_callback == NULL) {
OLA_FATAL << "Got a RDM response but no callback to run!";
return;
}
ola::rdm::RDMCallback *callback = m_rdm_request_callback;
m_rdm_request_callback = NULL;
const ola::rdm::RDMRequest *request = m_pending_request;
m_pending_request = NULL;
if (length == RDM_PADDING_BYTES) {
// this indicates that no request was recieved
callback->Run(ola::rdm::RDM_TIMEOUT, NULL, packets);
delete request;
return;
}
string packet;
packet.assign(reinterpret_cast<const char*>(data), length);
packets.push_back(packet);
// try to inflate
ola::rdm::rdm_response_code response_code;
ola::rdm::RDMResponse *response = ola::rdm::RDMResponse::InflateFromData(
packet,
&response_code,
request);
callback->Run(response_code, response, packets);
delete request;
}
/**
* Handle a response to a Discovery unique branch request
*/
void RobeWidgetImpl::HandleDiscoveryResponse(const uint8_t *data,
unsigned int length) {
if (m_branch_callback) {
BranchCallback *callback = m_branch_callback;
m_branch_callback = NULL;
// there are always 4 bytes padded on the end of the response
if (length <= RDM_PADDING_BYTES)
callback->Run(NULL, 0);
else
callback->Run(data, length - RDM_PADDING_BYTES);
} else {
OLA_WARN << "Got response to DUB but no callback defined!";
}
}
/**
* Called when the discovery process finally completes
* @param callback the callback passed to StartFullDiscovery or
* StartIncrementalDiscovery that we should execute.
* @param status true if discovery worked, false otherwise
* @param uids the UIDSet of UIDs that were found.
*/
void RobeWidgetImpl::DiscoveryComplete(
ola::rdm::RDMDiscoveryCallback *callback,
bool status,
const UIDSet &uids) {
if (callback)
callback->Run(uids);
(void) status;
}
/**
* Handle DMX data
*/
void RobeWidgetImpl::HandleDmxFrame(const uint8_t *data, unsigned int length) {
m_buffer.Set(data, length);
if (m_dmx_callback.get())
m_dmx_callback->Run();
}
/**
* RobeWidget Constructor
*/
RobeWidget::RobeWidget(ola::io::ConnectedDescriptor *descriptor,
ola::thread::SchedulingExecutorInterface *ss,
const ola::rdm::UID &uid,
unsigned int queue_size) {
m_impl = new RobeWidgetImpl(descriptor, ss, uid);
m_controller = new ola::rdm::DiscoverableQueueingRDMController(m_impl,
queue_size);
}
RobeWidget::~RobeWidget() {
// delete the controller after the impl because the controller owns the
// callback
delete m_impl;
delete m_controller;
}
} // usbpro
} // plugin
} // ola
<|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 "mitkEventInteractor.h"
mitk::EventInteractor::EventInteractor()
{
m_DataNode = NULL;
}
mitk::DataNode::Pointer mitk::EventInteractor::GetDataNode()
{
return m_DataNode;
}
void mitk::EventInteractor::SetDataNode(DataNode::Pointer dataNode)
{
m_DataNode = dataNode;
if (m_DataNode.IsNotNull()) {
m_DataNode->SetInteractor(dynamic_cast <mitk::Interactor*>(this));
}
}
int mitk::EventInteractor::GetLayer()
{
int layer = -1;
if (m_DataNode.IsNotNull()) {
m_DataNode->GetIntProperty("layer",layer);
}
return layer;
}
bool mitk::EventInteractor::operator <(const EventInteractor::Pointer eventInteractor)
{
return (GetLayer() < eventInteractor->GetLayer());
}
mitk::EventInteractor::~EventInteractor()
{
// TODO Auto-generated destructor stub
}
<commit_msg>mitk::MousePressEvent Class, Test for equality of InteractionEvents<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 "mitkEventInteractor.h"
mitk::EventInteractor::EventInteractor()
{
m_DataNode = NULL;
}
mitk::DataNode::Pointer mitk::EventInteractor::GetDataNode()
{
return m_DataNode;
}
void mitk::EventInteractor::SetDataNode(DataNode::Pointer dataNode)
{
m_DataNode = dataNode;
if (m_DataNode.IsNotNull()) {
m_DataNode->SetInteractor(dynamic_cast <mitk::Interactor*>(this));
}
}
int mitk::EventInteractor::GetLayer()
{
int layer = -1;
if (m_DataNode.IsNotNull()) {
m_DataNode->GetIntProperty("layer",layer);
}
return layer;
}
bool mitk::EventInteractor::operator <(const EventInteractor::Pointer eventInteractor)
{
return (GetLayer() < eventInteractor->GetLayer());
}
mitk::EventInteractor::~EventInteractor()
{
}
<|endoftext|> |
<commit_before><commit_msg>planning: discard adc trajectory points out of range (+/-8s)<commit_after><|endoftext|> |
<commit_before>#include "ge/sdl_subsystem.hpp"
#include "ge/gl.hpp"
#include "SDL.h"
#include "ge/input_subsystem.hpp"
#include <chrono>
using namespace ge;
key sdl_to_ge_key(SDL_Keycode code)
{
switch (code) {
case SDLK_EXCLAIM: return key::e_1;
case SDLK_QUOTEDBL: return key::e_apostrophe;
case SDLK_HASH: return key::e_3;
case SDLK_PERCENT: return key::e_5;
case SDLK_DOLLAR: return key::e_4;
case SDLK_AMPERSAND: return key::e_7;
case SDLK_LEFTPAREN: return key::e_9;
case SDLK_RIGHTPAREN: return key::e_0;
case SDLK_ASTERISK: return key::e_8;
case SDLK_PLUS: return key::e_equals;
case SDLK_LESS: return key::e_comma;
case SDLK_GREATER: return key::e_period;
case SDLK_QUESTION: return key::e_forward_slash;
case SDLK_AT: return key::e_2;
case SDLK_CARET: return key::e_6;
case SDLK_UNDERSCORE: return key::e_minus;
case SDLK_CAPSLOCK: return key::e_caps_lock;
case SDLK_F1: return key::e_F1;
case SDLK_F2: return key::e_F2;
case SDLK_F3: return key::e_F3;
case SDLK_F4: return key::e_F4;
case SDLK_F5: return key::e_F5;
case SDLK_F6: return key::e_F6;
case SDLK_F7: return key::e_F7;
case SDLK_F8: return key::e_F8;
case SDLK_F9: return key::e_F9;
case SDLK_F10: return key::e_F10;
case SDLK_F11: return key::e_F11;
case SDLK_F12: return key::e_F12;
case SDLK_PRINTSCREEN: return key::e_print_screen;
case SDLK_SCROLLLOCK: return key::e_scroll_lock;
case SDLK_PAUSE: return key::e_pause;
case SDLK_INSERT: return key::e_insert;
case SDLK_HOME: return key::e_home;
case SDLK_PAGEUP: return key::e_page_up;
case SDLK_PAGEDOWN: return key::e_page_down;
case SDLK_END: return key::e_end;
case SDLK_RIGHT: return key::e_right;
case SDLK_LEFT: return key::e_left;
case SDLK_UP: return key::e_up;
case SDLK_DOWN: return key::e_down;
case SDLK_NUMLOCKCLEAR: return key::e_num_lock;
case SDLK_KP_DIVIDE: return key::e_numpad_divide;
case SDLK_KP_PLUS: return key::e_numpad_plus;
case SDLK_KP_MULTIPLY: return key::e_numpad_times;
case SDLK_KP_MINUS: return key::e_numpad_minus;
case SDLK_KP_ENTER: return key::e_numpad_enter;
case SDLK_KP_0: return key::e_numpad_0;
case SDLK_KP_1: return key::e_numpad_1;
case SDLK_KP_2: return key::e_numpad_2;
case SDLK_KP_3: return key::e_numpad_3;
case SDLK_KP_4: return key::e_numpad_4;
case SDLK_KP_5: return key::e_numpad_5;
case SDLK_KP_6: return key::e_numpad_6;
case SDLK_KP_7: return key::e_numpad_7;
case SDLK_KP_8: return key::e_numpad_8;
case SDLK_KP_9: return key::e_numpad_9;
case SDLK_LCTRL: return key::e_left_ctrl;
case SDLK_RCTRL: return key::e_right_ctrl;
case SDLK_LALT: return key::e_left_alt;
case SDLK_RALT: return key::e_right_alt;
case SDLK_LSHIFT: return key::e_left_shift;
case SDLK_RSHIFT: return key::e_right_shift;
case SDLK_LGUI: return key::e_left_meta;
case SDLK_RGUI: return key::e_right_meta;
}
// if we are still here, it is convertable
return static_cast<key>(code);
}
mouse_button sdl_mb_to_ge(Uint8 button)
{
switch (button) {
case SDL_BUTTON_LEFT: return mouse_button::e_left_button;
case SDL_BUTTON_MIDDLE: return mouse_button::e_middle_button;
case SDL_BUTTON_RIGHT: return mouse_button::e_right_button;
case SDL_BUTTON_X1: return mouse_button::e_button_1;
case SDL_BUTTON_X2: return mouse_button::e_button_2;
}
return static_cast<mouse_button>(0);
}
int sdl_mods_to_ge(int mod)
{
int ret = 0x0;
if (mod & KMOD_LSHIFT) ret |= key_modifier::e_left_shift;
if (mod & KMOD_RSHIFT) ret |= key_modifier::e_right_shift;
if (mod & KMOD_LCTRL) ret |= key_modifier::e_left_ctrl;
if (mod & KMOD_RCTRL) ret |= key_modifier::e_right_ctrl;
if (mod & KMOD_LALT) ret |= key_modifier::e_left_alt;
if (mod & KMOD_RALT) ret |= key_modifier::e_right_alt;
if (mod & KMOD_LGUI) ret |= key_modifier::e_left_gui;
if (mod & KMOD_RGUI) ret |= key_modifier::e_right_gui;
if (mod & KMOD_NUM) ret |= key_modifier::e_num_lock;
if (mod & KMOD_CAPS) ret |= key_modifier::e_caps_lock;
return ret;
}
bool sdl_subsystem::initialize(const sdl_subsystem::config& config)
{
SDL_Init(SDL_INIT_VIDEO);
// create the window
int flags = SDL_WINDOW_OPENGL | (config.fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0) |
(config.decorated ? 0 : SDL_WINDOW_BORDERLESS);
#ifndef EMSCRIPTEN
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
#endif
glm::uvec2 loc = config.location ? config.location.get()
: glm::uvec2{SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED};
// initalize the window
m_window =
SDL_CreateWindow(config.title.c_str(), loc.x, loc.y, config.size.x, config.size.y, flags);
using namespace std::string_literals;
if (!m_window) {
logger->error("Error initalizing SDL window"s + SDL_GetError());
return false;
}
// create the context
m_context = SDL_GL_CreateContext(m_window);
SDL_GL_MakeCurrent(m_window, m_context);
#ifdef WIN32
if (!gladLoadGL()) {
logger->error("Failed to load OpenGL functions from glad");
return false;
}
#endif
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return true;
}
bool sdl_subsystem::update(std::chrono::duration<float> delta)
{
SDL_GL_SwapWindow(m_window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(m_background_color.r, m_background_color.g, m_background_color.b, 1.f);
static auto last_tick = std::chrono::system_clock::now();
auto now = std::chrono::system_clock::now();
std::chrono::duration<float> diff = now - last_tick;
// app->signal_update(diff.count());
// app->elapsed_time += diff.count();
last_tick = now;
SDL_Event event;
auto input_sub = m_runtime->get_subsystem<input_subsystem>();
// run until there is an event that we recognize
while (SDL_PollEvent(&event)) {
input_event ev;
switch (event.type) {
case SDL_QUIT: return false;
case SDL_KEYDOWN:
if (!event.key.repeat)
ev = input_keyboard{sdl_to_ge_key(event.key.keysym.sym), true,
sdl_mods_to_ge(event.key.keysym.mod)};
break;
case SDL_KEYUP:
if (!event.key.repeat)
ev = input_keyboard{sdl_to_ge_key(event.key.keysym.sym), false,
sdl_mods_to_ge(event.key.keysym.mod)};
break;
case SDL_MOUSEMOTION:
ev = input_mouse_move{
{event.motion.x, event.motion.y}, sdl_mods_to_ge(SDL_GetModState())};
break;
case SDL_MOUSEBUTTONDOWN:
ev = input_mouse_button{sdl_mb_to_ge(event.button.button), true,
sdl_mods_to_ge(SDL_GetModState()), {event.button.x, event.button.x}};
break;
case SDL_MOUSEBUTTONUP:
ev = input_mouse_button{sdl_mb_to_ge(event.button.button), false,
sdl_mods_to_ge(SDL_GetModState()), {event.button.x, event.button.x}};
break;
case SDL_MOUSEWHEEL:
if (event.wheel.direction == SDL_MOUSEWHEEL_NORMAL) {
ev = input_scroll_wheel{
{event.wheel.x, event.wheel.y}, sdl_mods_to_ge(SDL_GetModState())};
} else {
ev = input_scroll_wheel{
{-event.wheel.x, -event.wheel.y}, sdl_mods_to_ge(SDL_GetModState())};
}
break;
}
if (input_sub) {
input_sub->add_event(ev);
}
}
// render!
if (m_camera) {
m_camera->render_actors(
*m_runtime->get_root_actor(), float(get_size().x) / float(get_size().y));
}
return true;
}
bool sdl_subsystem::shutdown()
{
SDL_GL_DeleteContext(m_context);
SDL_DestroyWindow(m_window);
SDL_Quit();
return true;
}
glm::uvec2 sdl_subsystem::get_size() const
{
glm::ivec2 ret;
SDL_GetWindowSize(m_window, &ret.x, &ret.y);
return ret;
}
void sdl_subsystem::set_size(glm::uvec2 new_size)
{
SDL_SetWindowSize(m_window, new_size.x, new_size.y);
}
std::string sdl_subsystem::get_title() const { return SDL_GetWindowTitle(m_window); }
void sdl_subsystem::set_title(const std::string& newTitle)
{
SDL_SetWindowTitle(m_window, newTitle.c_str());
}
<commit_msg>Make it so we don't require a GL version<commit_after>#include "ge/sdl_subsystem.hpp"
#include "ge/gl.hpp"
#include "SDL.h"
#include "ge/input_subsystem.hpp"
#include <chrono>
using namespace ge;
key sdl_to_ge_key(SDL_Keycode code)
{
switch (code) {
case SDLK_EXCLAIM: return key::e_1;
case SDLK_QUOTEDBL: return key::e_apostrophe;
case SDLK_HASH: return key::e_3;
case SDLK_PERCENT: return key::e_5;
case SDLK_DOLLAR: return key::e_4;
case SDLK_AMPERSAND: return key::e_7;
case SDLK_LEFTPAREN: return key::e_9;
case SDLK_RIGHTPAREN: return key::e_0;
case SDLK_ASTERISK: return key::e_8;
case SDLK_PLUS: return key::e_equals;
case SDLK_LESS: return key::e_comma;
case SDLK_GREATER: return key::e_period;
case SDLK_QUESTION: return key::e_forward_slash;
case SDLK_AT: return key::e_2;
case SDLK_CARET: return key::e_6;
case SDLK_UNDERSCORE: return key::e_minus;
case SDLK_CAPSLOCK: return key::e_caps_lock;
case SDLK_F1: return key::e_F1;
case SDLK_F2: return key::e_F2;
case SDLK_F3: return key::e_F3;
case SDLK_F4: return key::e_F4;
case SDLK_F5: return key::e_F5;
case SDLK_F6: return key::e_F6;
case SDLK_F7: return key::e_F7;
case SDLK_F8: return key::e_F8;
case SDLK_F9: return key::e_F9;
case SDLK_F10: return key::e_F10;
case SDLK_F11: return key::e_F11;
case SDLK_F12: return key::e_F12;
case SDLK_PRINTSCREEN: return key::e_print_screen;
case SDLK_SCROLLLOCK: return key::e_scroll_lock;
case SDLK_PAUSE: return key::e_pause;
case SDLK_INSERT: return key::e_insert;
case SDLK_HOME: return key::e_home;
case SDLK_PAGEUP: return key::e_page_up;
case SDLK_PAGEDOWN: return key::e_page_down;
case SDLK_END: return key::e_end;
case SDLK_RIGHT: return key::e_right;
case SDLK_LEFT: return key::e_left;
case SDLK_UP: return key::e_up;
case SDLK_DOWN: return key::e_down;
case SDLK_NUMLOCKCLEAR: return key::e_num_lock;
case SDLK_KP_DIVIDE: return key::e_numpad_divide;
case SDLK_KP_PLUS: return key::e_numpad_plus;
case SDLK_KP_MULTIPLY: return key::e_numpad_times;
case SDLK_KP_MINUS: return key::e_numpad_minus;
case SDLK_KP_ENTER: return key::e_numpad_enter;
case SDLK_KP_0: return key::e_numpad_0;
case SDLK_KP_1: return key::e_numpad_1;
case SDLK_KP_2: return key::e_numpad_2;
case SDLK_KP_3: return key::e_numpad_3;
case SDLK_KP_4: return key::e_numpad_4;
case SDLK_KP_5: return key::e_numpad_5;
case SDLK_KP_6: return key::e_numpad_6;
case SDLK_KP_7: return key::e_numpad_7;
case SDLK_KP_8: return key::e_numpad_8;
case SDLK_KP_9: return key::e_numpad_9;
case SDLK_LCTRL: return key::e_left_ctrl;
case SDLK_RCTRL: return key::e_right_ctrl;
case SDLK_LALT: return key::e_left_alt;
case SDLK_RALT: return key::e_right_alt;
case SDLK_LSHIFT: return key::e_left_shift;
case SDLK_RSHIFT: return key::e_right_shift;
case SDLK_LGUI: return key::e_left_meta;
case SDLK_RGUI: return key::e_right_meta;
}
// if we are still here, it is convertable
return static_cast<key>(code);
}
mouse_button sdl_mb_to_ge(Uint8 button)
{
switch (button) {
case SDL_BUTTON_LEFT: return mouse_button::e_left_button;
case SDL_BUTTON_MIDDLE: return mouse_button::e_middle_button;
case SDL_BUTTON_RIGHT: return mouse_button::e_right_button;
case SDL_BUTTON_X1: return mouse_button::e_button_1;
case SDL_BUTTON_X2: return mouse_button::e_button_2;
}
return static_cast<mouse_button>(0);
}
int sdl_mods_to_ge(int mod)
{
int ret = 0x0;
if (mod & KMOD_LSHIFT) ret |= key_modifier::e_left_shift;
if (mod & KMOD_RSHIFT) ret |= key_modifier::e_right_shift;
if (mod & KMOD_LCTRL) ret |= key_modifier::e_left_ctrl;
if (mod & KMOD_RCTRL) ret |= key_modifier::e_right_ctrl;
if (mod & KMOD_LALT) ret |= key_modifier::e_left_alt;
if (mod & KMOD_RALT) ret |= key_modifier::e_right_alt;
if (mod & KMOD_LGUI) ret |= key_modifier::e_left_gui;
if (mod & KMOD_RGUI) ret |= key_modifier::e_right_gui;
if (mod & KMOD_NUM) ret |= key_modifier::e_num_lock;
if (mod & KMOD_CAPS) ret |= key_modifier::e_caps_lock;
return ret;
}
bool sdl_subsystem::initialize(const sdl_subsystem::config& config)
{
SDL_Init(SDL_INIT_VIDEO);
// create the window
int flags = SDL_WINDOW_OPENGL | (config.fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0) |
(config.decorated ? 0 : SDL_WINDOW_BORDERLESS);
glm::uvec2 loc = config.location ? config.location.get()
: glm::uvec2{SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED};
// initalize the window
m_window =
SDL_CreateWindow(config.title.c_str(), loc.x, loc.y, config.size.x, config.size.y, flags);
using namespace std::string_literals;
if (!m_window) {
logger->error("Error initalizing SDL window"s + SDL_GetError());
return false;
}
// create the context
m_context = SDL_GL_CreateContext(m_window);
SDL_GL_MakeCurrent(m_window, m_context);
#ifdef WIN32
if (!gladLoadGL()) {
logger->error("Failed to load OpenGL functions from glad");
return false;
}
#endif
// Enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
return true;
}
bool sdl_subsystem::update(std::chrono::duration<float> delta)
{
SDL_GL_SwapWindow(m_window);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glClearColor(m_background_color.r, m_background_color.g, m_background_color.b, 1.f);
static auto last_tick = std::chrono::system_clock::now();
auto now = std::chrono::system_clock::now();
std::chrono::duration<float> diff = now - last_tick;
// app->signal_update(diff.count());
// app->elapsed_time += diff.count();
last_tick = now;
SDL_Event event;
auto input_sub = m_runtime->get_subsystem<input_subsystem>();
// run until there is an event that we recognize
while (SDL_PollEvent(&event)) {
input_event ev;
switch (event.type) {
case SDL_QUIT: return false;
case SDL_KEYDOWN:
if (!event.key.repeat)
ev = input_keyboard{sdl_to_ge_key(event.key.keysym.sym), true,
sdl_mods_to_ge(event.key.keysym.mod)};
break;
case SDL_KEYUP:
if (!event.key.repeat)
ev = input_keyboard{sdl_to_ge_key(event.key.keysym.sym), false,
sdl_mods_to_ge(event.key.keysym.mod)};
break;
case SDL_MOUSEMOTION:
ev = input_mouse_move{
{event.motion.x, event.motion.y}, sdl_mods_to_ge(SDL_GetModState())};
break;
case SDL_MOUSEBUTTONDOWN:
ev = input_mouse_button{sdl_mb_to_ge(event.button.button), true,
sdl_mods_to_ge(SDL_GetModState()), {event.button.x, event.button.x}};
break;
case SDL_MOUSEBUTTONUP:
ev = input_mouse_button{sdl_mb_to_ge(event.button.button), false,
sdl_mods_to_ge(SDL_GetModState()), {event.button.x, event.button.x}};
break;
case SDL_MOUSEWHEEL:
if (event.wheel.direction == SDL_MOUSEWHEEL_NORMAL) {
ev = input_scroll_wheel{
{event.wheel.x, event.wheel.y}, sdl_mods_to_ge(SDL_GetModState())};
} else {
ev = input_scroll_wheel{
{-event.wheel.x, -event.wheel.y}, sdl_mods_to_ge(SDL_GetModState())};
}
break;
}
if (input_sub) {
input_sub->add_event(ev);
}
}
// render!
if (m_camera) {
m_camera->render_actors(
*m_runtime->get_root_actor(), float(get_size().x) / float(get_size().y));
}
return true;
}
bool sdl_subsystem::shutdown()
{
SDL_GL_DeleteContext(m_context);
SDL_DestroyWindow(m_window);
SDL_Quit();
return true;
}
glm::uvec2 sdl_subsystem::get_size() const
{
glm::ivec2 ret;
SDL_GetWindowSize(m_window, &ret.x, &ret.y);
return ret;
}
void sdl_subsystem::set_size(glm::uvec2 new_size)
{
SDL_SetWindowSize(m_window, new_size.x, new_size.y);
}
std::string sdl_subsystem::get_title() const { return SDL_GetWindowTitle(m_window); }
void sdl_subsystem::set_title(const std::string& newTitle)
{
SDL_SetWindowTitle(m_window, newTitle.c_str());
}
<|endoftext|> |
<commit_before>#include "ValueProcessor.h"
#include <sstream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
TokenList* ValueProcessor::processValue(TokenList* value) {
TokenList newvalue;
Value* v;
while (value->size() > 0) {
v = processStatement(value);
if (v != NULL) {
newvalue.push(v->getToken()->clone());
delete v;
} else if (value->front()->type == Token::ATKEYWORD &&
variables.count(value->front()->str)) {
newvalue.push(variables[value->front()->str]);
delete value->shift();
} else
newvalue.push(value->shift());
}
value->push(&newvalue);
return value;
}
void ValueProcessor::putVariable(string key, TokenList* value) {
variables[key] = value;
}
Value* ValueProcessor::processStatement(TokenList* value) {
Value* op, *v = processConstant(value);
if (v != NULL) {
while ((op = processOperator(value, v)))
v = op;
return v;
} else
return NULL;
}
Value* ValueProcessor::processOperator(TokenList* value, Value* v1,
Token* lastop) {
Value* v2, *tmp;
Token* op;
string operators("+-*/");
if (!operators.find(value->front()->str))
return NULL;
if (lastop != NULL &&
operators.find(lastop->str) >
operators.find(value->front()->str)) {
return v1;
}
op = value->shift();
v2 = processConstant(value);
while ((tmp = processOperator(value, v2, op)))
v2 = tmp;
if (op->str == "+")
v1->add(v2);
else if (op->str == "-")
v1->substract(v2);
else if (op->str == "*")
v1->multiply(v2);
else if (op->str == "/")
v1->divide(v2);
delete v2;
return v1;
}
Value* ValueProcessor::processConstant(TokenList* value) {
Token* token = value->front();
Value* ret;
vector<Value*> arguments;
switch(token->type) {
case Token::HASH:
// generate color from hex value
return new Color(value->shift());
case Token::NUMBER:
case Token::PERCENTAGE:
case Token::DIMENSION:
return new Value(value->shift());
case Token::FUNCTION:
value->shift();
if (value->front()->type != Token::PAREN_CLOSED)
arguments.push_back(processConstant(value));
while (value->front()->str == ",") {
delete value->shift();
arguments.push_back(processConstant(value));
}
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return processFunction(token, arguments);
case Token::ATKEYWORD:
if (variables.count(token->str)) {
ret = processConstant(variables[token->str]);
delete value->shift();
return ret;
} else
return NULL;
case Token::PAREN_OPEN:
delete value->shift();
ret = processStatement(value);
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return ret;
default:
if (value->size() > 1) {
TokenList* var = processDeepVariable(token, value->at(1));
if (var != NULL) {
ret = processStatement(var);
delete value->shift();
return ret;
}
}
return NULL;
}
}
TokenList* ValueProcessor::processDeepVariable (Token* token, Token* nexttoken) {
TokenList* var;
string key("@");
if (token->type != Token::OTHER ||
token->str != "@" ||
nexttoken->type != Token::ATKEYWORD ||
!variables.count(nexttoken->str))
return NULL;
var = variables[nexttoken->str];
if (var->size() > 1 || var->front()->type != Token::STRING)
return NULL;
// generate key with '@' + var without quotes
key.append(var->front()->
str.substr(1, var->front()->str.size() - 2));
if (!variables.count(key))
return NULL;
return variables[key];
}
Value* ValueProcessor::processFunction(Token* function,
vector<Value*> arguments) {
Color* color;
string percentage;
if(function->str == "rgb(") {
if (arguments.size() == 3 &&
arguments[0]->type == Value::NUMBER &&
arguments[1]->type == Value::NUMBER &&
arguments[2]->type == Value::NUMBER) {
return new Color(0,0,0);
}
// Color rgb(@red: NUMBER, @green: NUMBER, @blue: NUMBER)
} else if (function->str == "lighten(") {
// Color lighten(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->lighten(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "darken(") {
// Color darken(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->darken(arguments[1]->getPercent()());
return arguments[0];
}
} else if (function->str == "saturate(") {
// Color saturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->saturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "desaturate(") {
// Color desaturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->desaturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadein(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadein(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadeout(") {
// Color fadeout(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadeout(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "spin(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->spin(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "hsl(") {
// Color hsl(PERCENTAGE, PERCENTAGE, PERCENTAGE)
if (arguments.size() == 3 &&
arguments[0]->type == Value::PERCENTAGE &&
arguments[1]->type == Value::PERCENTAGE &&
arguments[2]->type == Value::PERCENTAGE) {
color = new Color(0,0,0);
color->setHSL(arguments[0]->getPercent(),
arguments[1]->getPercent(),
arguments[2]->getPercent());
return color;
}
} else if (function->str == "hue(") {
// PERCENTAGE hue(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getHue()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "saturation(") {
// PERCENTAGE saturation(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getSaturation()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "lightness(") {
// PERCENTAGE lightness(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getLightness()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else
return NULL;
return NULL;
}
<commit_msg>Adding empty TokenList checks.<commit_after>#include "ValueProcessor.h"
#include <sstream>
#include <iostream>
template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
TokenList* ValueProcessor::processValue(TokenList* value) {
TokenList newvalue;
Value* v;
std::cout << *value->toString() << endl;
while (value->size() > 0) {
v = processStatement(value);
if (v != NULL) {
newvalue.push(v->getToken()->clone());
delete v;
} else if (value->front()->type == Token::ATKEYWORD &&
variables.count(value->front()->str)) {
newvalue.push(variables[value->front()->str]);
delete value->shift();
} else
newvalue.push(value->shift());
}
value->push(&newvalue);
return value;
}
void ValueProcessor::putVariable(string key, TokenList* value) {
variables[key] = value;
}
Value* ValueProcessor::processStatement(TokenList* value) {
Value* op, *v = processConstant(value);
if (v != NULL) {
while ((op = processOperator(value, v)))
v = op;
return v;
} else
return NULL;
}
Value* ValueProcessor::processOperator(TokenList* value, Value* v1,
Token* lastop) {
Value* v2, *tmp;
Token* op;
string operators("+-*/");
if (value->size() == 0 || !operators.find(value->front()->str))
return NULL;
if (lastop != NULL &&
operators.find(lastop->str) >
operators.find(value->front()->str)) {
return v1;
}
op = value->shift();
v2 = processConstant(value);
while ((tmp = processOperator(value, v2, op)))
v2 = tmp;
if (op->str == "+")
v1->add(v2);
else if (op->str == "-")
v1->substract(v2);
else if (op->str == "*")
v1->multiply(v2);
else if (op->str == "/")
v1->divide(v2);
delete v2;
return v1;
}
Value* ValueProcessor::processConstant(TokenList* value) {
Token* token;
Value* ret;
vector<Value*> arguments;
if (value->size() == 0)
return NULL;
token = value->front();
switch(token->type) {
case Token::HASH:
// generate color from hex value
return new Color(value->shift());
case Token::NUMBER:
case Token::PERCENTAGE:
case Token::DIMENSION:
return new Value(value->shift());
case Token::FUNCTION:
value->shift();
if (value->front()->type != Token::PAREN_CLOSED)
arguments.push_back(processConstant(value));
while (value->front()->str == ",") {
delete value->shift();
arguments.push_back(processConstant(value));
}
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return processFunction(token, arguments);
case Token::ATKEYWORD:
if (variables.count(token->str)) {
ret = processConstant(variables[token->str]);
delete value->shift();
return ret;
} else
return NULL;
case Token::PAREN_OPEN:
delete value->shift();
ret = processStatement(value);
if (value->front()->type == Token::PAREN_CLOSED)
delete value->shift();
return ret;
default:
if (value->size() > 1) {
TokenList* var = processDeepVariable(token, value->at(1));
if (var != NULL) {
ret = processStatement(var);
delete value->shift();
return ret;
}
}
return NULL;
}
}
TokenList* ValueProcessor::processDeepVariable (Token* token, Token* nexttoken) {
TokenList* var;
string key("@");
if (token->type != Token::OTHER ||
token->str != "@" ||
nexttoken->type != Token::ATKEYWORD ||
!variables.count(nexttoken->str))
return NULL;
var = variables[nexttoken->str];
if (var->size() > 1 || var->front()->type != Token::STRING)
return NULL;
// generate key with '@' + var without quotes
key.append(var->front()->
str.substr(1, var->front()->str.size() - 2));
if (!variables.count(key))
return NULL;
return variables[key];
}
Value* ValueProcessor::processFunction(Token* function,
vector<Value*> arguments) {
Color* color;
string percentage;
if(function->str == "rgb(") {
if (arguments.size() == 3 &&
arguments[0]->type == Value::NUMBER &&
arguments[1]->type == Value::NUMBER &&
arguments[2]->type == Value::NUMBER) {
return new Color(0,0,0);
}
// Color rgb(@red: NUMBER, @green: NUMBER, @blue: NUMBER)
} else if (function->str == "lighten(") {
// Color lighten(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->lighten(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "darken(") {
// Color darken(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->darken(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "saturate(") {
// Color saturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->saturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "desaturate(") {
// Color desaturate(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->desaturate(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadein(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadein(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "fadeout(") {
// Color fadeout(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->fadeout(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "spin(") {
// Color fadein(Color, PERCENTAGE)
if (arguments.size() == 2 &&
arguments[0]->type == Value::COLOR &&
arguments[1]->type == Value::PERCENTAGE) {
static_cast<Color*>(arguments[0])->spin(arguments[1]->getPercent());
return arguments[0];
}
} else if (function->str == "hsl(") {
// Color hsl(PERCENTAGE, PERCENTAGE, PERCENTAGE)
if (arguments.size() == 3 &&
arguments[0]->type == Value::PERCENTAGE &&
arguments[1]->type == Value::PERCENTAGE &&
arguments[2]->type == Value::PERCENTAGE) {
color = new Color(0,0,0);
color->setHSL(arguments[0]->getPercent(),
arguments[1]->getPercent(),
arguments[2]->getPercent());
return color;
}
} else if (function->str == "hue(") {
// PERCENTAGE hue(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getHue()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "saturation(") {
// PERCENTAGE saturation(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getSaturation()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else if (function->str == "lightness(") {
// PERCENTAGE lightness(Color)
if (arguments.size() == 1 &&
arguments[0]->type == Value::COLOR) {
percentage.append(to_string(static_cast<Color*>(arguments[0])->getLightness()));
percentage.append("%");
return new Value(new Token(percentage, Token::PERCENTAGE));
}
} else
return NULL;
return NULL;
}
<|endoftext|> |
<commit_before>//
// random.cpp
// yamcmc++
//
// Created by Dr. Brandon C. Kelly on 11/21/12.
// Source file for a class that generates pseudorandom numbers from common distributions.
// This is basically a wrapper for BOOST::RANDOM
//
// Standard includes
#include <iostream>
#include <fstream>
// Local include
#include "include/random.hpp"
// Global random number generator. This same generator should be used for
// generating all random variates for a MCMC sampler. The default random
// number generator is the Mersenne Twister mt19937 from the BOOST library.
boost::random::mt19937 rng;
// Method to set the seed of the global random number generator.
void RandomGenerator::SetSeed(unsigned long seed) const
{
rng.seed(seed);
}
// Method to save the seed of the global random number generator to a file.
// The default filename is "seed.txt"
void RandomGenerator::SaveSeed(std::string seed_filename) const
{
std::ofstream seed_file(seed_filename.c_str());
if (seed_file.is_open()) {
seed_file << rng;
} else {
std::cout << "Cannot write random number generator seed to file "
<< seed_filename << ".\n";
}
seed_file.close();
}
// Method to recover the seed of the global random number generator from a file.
// The default filename is "seed.txt"
void RandomGenerator::RecoverSeed(std::string seed_filename) const
{
std::ifstream seed_file(seed_filename.c_str());
if (seed_file.is_open()) {
seed_file >> rng;
} else {
std::cout << "Cannot read random number generator seed from file "
<< seed_filename << ".\n";
}
seed_file.close();
}
// Method to return a exponentially distributed random variate. The parameter
// lambda denotes the scale parameter for the exponential distribution:
//
// p(x|lambda) = lambda * exp(-lambda * x)
double RandomGenerator::exp(double lambda)
{ // Initialize an exponential parameter object with parameter lambda.
boost::random::exponential_distribution<>::param_type exp_params(lambda);
// Set the parameter object owned by the exp_ distribution object to be
// the new parameter object with scale parameter lambda.
exp_.param(exp_params);
// Generate and return a exponentially-distribution random deviate. Note
// that rng is the global random number generator defined in the header file.
return exp_(rng);
}
// Method to return a normally distributed random variate. The parameters are
// the mean, mu, and the standard deviation, sigma.
double RandomGenerator::normal(double mu, double sigma)
{
boost::random::normal_distribution<>::param_type normal_params(mu, sigma);
normal_.param(normal_params);
return normal_(rng);
}
// Over-loaded Method to return a random vector drawn from a multivariate normal distribution
// of mean zero:
//
// p(x|covar) \propto 1 / |covar|^{1/2} exp(-0.5 x^T covar^{-1} x)
arma::vec RandomGenerator::normal(arma::mat covar)
{
// Get matrix square root of covar via Cholesky decomposition
arma::mat R = arma::chol(covar);
// Rest normal distribution parameters
boost::random::normal_distribution<>::param_type normal_params(0.0, 1.0);
normal_.param(normal_params);
// Vector of random variate independently drawn from a standard normal
arma::vec z(covar.n_rows);
for (int i=0; i<z.n_elem; i++) {
z(i) = normal_(rng);
}
arma::vec x = R.t() * z;
return x;
}
// Method to return a log-normally distributed random variate. The parameters are
// the geometric mean, geomean, and the fractional standard deviation, frac_sigma:
//
// p(x|geomean,frac_sigma) /propto
// (1 / (x * frac_sigma)) * exp(-0.5 * (log(x) - geomean)^2 / frac_sigma^2)
double RandomGenerator::lognormal(double logmean, double frac_sigma)
{
boost::random::lognormal_distribution<>::param_type lognormal_params(logmean, frac_sigma);
lognormal_.param(lognormal_params);
return lognormal_(rng);
}
// Method to return a uniformaly distributed random variate between lowbound and upbound.
double RandomGenerator::uniform(double lowbound, double upbound)
{
boost::random::uniform_real_distribution<>::param_type unif_params(lowbound, upbound);
uniform_.param(unif_params);
return uniform_(rng);
}
// Overloaded method to return a uniformaly distributed integer between lowbound and upbound.
int RandomGenerator::uniform(int lowbound, int upbound)
{
boost::random::uniform_int_distribution<>::param_type unif_params(lowbound, upbound);
uniform_integer_.param(unif_params);
return uniform_integer_(rng);
}
// Method to return a random variate drawn from a bounded power-law distribution. The
// parameters are the slope, slope, the lowerbound, lower, and the upperbound, upper:
//
// p(x|slope,lower,upper) \propto x^slope, lower < x < upper
double RandomGenerator::powerlaw(double lower, double upper, double slope)
{
// First draw Y ~ Uniform(0,1)
double unif = uniform(0.0, 1.0);
// Now do transformation Y -> X such that X ~ Powerlaw(slope,lower,upper)
double power = 1.0 / (slope + 1.0);
double base_value= (pow(upper, slope+1) - pow(lower, slope+1)) * unif + pow(lower,slope+1);
return pow(base_value, power);
}
// Method to return a random variate drawn from a Student's t-distribution. The parameters
// are the degrees of freedom, dof, the mean, mean, and the scale parameter, scale:
//
// p(x|dof,mean,scale) \propto (1 + (x - mean)^2 / (dof * scale^2))^(-(n+1)/2)
double RandomGenerator::tdist(double dof, double mean, double scale)
{
boost::random::student_t_distribution<>::param_type t_param(dof);
tdist_.param(t_param);
double zdraw = tdist_(rng);
return mean + scale * zdraw;
}
// Method to return a chi-squared random variate. The parameters are the
// degrees of freedom, dof.
double RandomGenerator::chisqr(int dof)
{
boost::random::chi_squared_distribution<>::param_type chisqr_param(dof);
chisqr_.param(chisqr_param);
return chisqr_(rng);
}
// Method to return a random variate drawn from a scaled inverse chi-square distribution. The
// parameters are the degrees of freedom, dof, and the scale parameter, ssqr:
//
// p(x|dof,ssqr) \propto 1 / x^(1 + dof/2) * exp(-dof * ssqr / (dof * x))
double RandomGenerator::scaled_inverse_chisqr(int dof, double ssqr)
{
boost::random::chi_squared_distribution<>::param_type chisqr_param(dof);
chisqr_.param(chisqr_param);
double chi2 = chisqr_(rng);
return ssqr / chi2 * ((double)(dof));
}
// Method to return a random variate drawn from a gamma distribution with shape
// parameter alpha and scale parameter beta:
//
// p(x|alpha,beta) \propto x^(alpha-1) exp(-x / beta)
double RandomGenerator::gamma(double alpha, double beta)
{
boost::random::gamma_distribution<>::param_type gamma_params(alpha,beta);
gamma_.param(gamma_params);
return gamma_(rng);
}
// Method to return a random variate drawn from an inverse gamma distribution
// with shape parameter alpha and inverse scale parameter beta:
//
// p(x|alpha,beta) \propto x^(-alpha-1) exp(-beta / x)
double RandomGenerator::invgamma(double alpha, double beta)
{
boost::random::gamma_distribution<>::param_type gamma_params(alpha, 1.0 / beta);
gamma_.param(gamma_params);
return 1.0 / gamma_(rng);
}
// Method to return a random variate drawn from an inverse gaussian distribution with
// mean parameter mu and shape parameter lambda:
//
// p(x|mu,lambda) \propto (lambda / x^3)^{1/2} * exp{-0.5 * lambda * (x-mu)^2 / (mu^2 * x)}
double RandomGenerator::invgauss(double mu, double lambda) {
double snorm = normal(0.0, 1.0);
double snorm_sqr = snorm * snorm;
double mu_sqr = mu * mu;
double x = mu + mu_sqr * snorm_sqr / (2.0 * lambda) -
mu / (2.0 * lambda) * sqrt(4.0 * mu * lambda * snorm_sqr + mu_sqr * snorm_sqr);
double unif = uniform(0.0, 1.0);
double value = unif <= mu / (mu + x) ? x : mu_sqr / x;
return value;
}
// Method to return a random vector drawn from a multivariate Student's t-distribution.
// More to come later.
arma::vec RandomGenerator::mtdist(arma::mat covar, double dof)
{
arma::vec t(covar.n_rows);
return t;
}
// Method to return a random variate drawn from a beta distribution. More to come.
double RandomGenerator::beta()
{
return 0.0;
}
// Method to return a random variate drawn from a Weibull distribution. More to come.
double RandomGenerator::weibull()
{
return 0.0;
}
<commit_msg>Added comment to remind me that cholesky factor is upper triangular.<commit_after>//
// random.cpp
// yamcmc++
//
// Created by Dr. Brandon C. Kelly on 11/21/12.
// Source file for a class that generates pseudorandom numbers from common distributions.
// This is basically a wrapper for BOOST::RANDOM
//
// Standard includes
#include <iostream>
#include <fstream>
// Local include
#include "include/random.hpp"
// Global random number generator. This same generator should be used for
// generating all random variates for a MCMC sampler. The default random
// number generator is the Mersenne Twister mt19937 from the BOOST library.
boost::random::mt19937 rng;
// Method to set the seed of the global random number generator.
void RandomGenerator::SetSeed(unsigned long seed) const
{
rng.seed(seed);
}
// Method to save the seed of the global random number generator to a file.
// The default filename is "seed.txt"
void RandomGenerator::SaveSeed(std::string seed_filename) const
{
std::ofstream seed_file(seed_filename.c_str());
if (seed_file.is_open()) {
seed_file << rng;
} else {
std::cout << "Cannot write random number generator seed to file "
<< seed_filename << ".\n";
}
seed_file.close();
}
// Method to recover the seed of the global random number generator from a file.
// The default filename is "seed.txt"
void RandomGenerator::RecoverSeed(std::string seed_filename) const
{
std::ifstream seed_file(seed_filename.c_str());
if (seed_file.is_open()) {
seed_file >> rng;
} else {
std::cout << "Cannot read random number generator seed from file "
<< seed_filename << ".\n";
}
seed_file.close();
}
// Method to return a exponentially distributed random variate. The parameter
// lambda denotes the scale parameter for the exponential distribution:
//
// p(x|lambda) = lambda * exp(-lambda * x)
double RandomGenerator::exp(double lambda)
{ // Initialize an exponential parameter object with parameter lambda.
boost::random::exponential_distribution<>::param_type exp_params(lambda);
// Set the parameter object owned by the exp_ distribution object to be
// the new parameter object with scale parameter lambda.
exp_.param(exp_params);
// Generate and return a exponentially-distribution random deviate. Note
// that rng is the global random number generator defined in the header file.
return exp_(rng);
}
// Method to return a normally distributed random variate. The parameters are
// the mean, mu, and the standard deviation, sigma.
double RandomGenerator::normal(double mu, double sigma)
{
boost::random::normal_distribution<>::param_type normal_params(mu, sigma);
normal_.param(normal_params);
return normal_(rng);
}
// Over-loaded Method to return a random vector drawn from a multivariate normal distribution
// of mean zero:
//
// p(x|covar) \propto 1 / |covar|^{1/2} exp(-0.5 x^T covar^{-1} x)
arma::vec RandomGenerator::normal(arma::mat covar)
{
// Get matrix square root of covar via Cholesky decomposition
arma::mat R = arma::chol(covar); // R is upper triangular
// Rest normal distribution parameters
boost::random::normal_distribution<>::param_type normal_params(0.0, 1.0);
normal_.param(normal_params);
// Vector of random variate independently drawn from a standard normal
arma::vec z(covar.n_rows);
for (int i=0; i<z.n_elem; i++) {
z(i) = normal_(rng);
}
arma::vec x = R.t() * z;
return x;
}
// Method to return a log-normally distributed random variate. The parameters are
// the geometric mean, geomean, and the fractional standard deviation, frac_sigma:
//
// p(x|geomean,frac_sigma) /propto
// (1 / (x * frac_sigma)) * exp(-0.5 * (log(x) - geomean)^2 / frac_sigma^2)
double RandomGenerator::lognormal(double logmean, double frac_sigma)
{
boost::random::lognormal_distribution<>::param_type lognormal_params(logmean, frac_sigma);
lognormal_.param(lognormal_params);
return lognormal_(rng);
}
// Method to return a uniformaly distributed random variate between lowbound and upbound.
double RandomGenerator::uniform(double lowbound, double upbound)
{
boost::random::uniform_real_distribution<>::param_type unif_params(lowbound, upbound);
uniform_.param(unif_params);
return uniform_(rng);
}
// Overloaded method to return a uniformaly distributed integer between lowbound and upbound.
int RandomGenerator::uniform(int lowbound, int upbound)
{
boost::random::uniform_int_distribution<>::param_type unif_params(lowbound, upbound);
uniform_integer_.param(unif_params);
return uniform_integer_(rng);
}
// Method to return a random variate drawn from a bounded power-law distribution. The
// parameters are the slope, slope, the lowerbound, lower, and the upperbound, upper:
//
// p(x|slope,lower,upper) \propto x^slope, lower < x < upper
double RandomGenerator::powerlaw(double lower, double upper, double slope)
{
// First draw Y ~ Uniform(0,1)
double unif = uniform(0.0, 1.0);
// Now do transformation Y -> X such that X ~ Powerlaw(slope,lower,upper)
double power = 1.0 / (slope + 1.0);
double base_value= (pow(upper, slope+1) - pow(lower, slope+1)) * unif + pow(lower,slope+1);
return pow(base_value, power);
}
// Method to return a random variate drawn from a Student's t-distribution. The parameters
// are the degrees of freedom, dof, the mean, mean, and the scale parameter, scale:
//
// p(x|dof,mean,scale) \propto (1 + (x - mean)^2 / (dof * scale^2))^(-(n+1)/2)
double RandomGenerator::tdist(double dof, double mean, double scale)
{
boost::random::student_t_distribution<>::param_type t_param(dof);
tdist_.param(t_param);
double zdraw = tdist_(rng);
return mean + scale * zdraw;
}
// Method to return a chi-squared random variate. The parameters are the
// degrees of freedom, dof.
double RandomGenerator::chisqr(int dof)
{
boost::random::chi_squared_distribution<>::param_type chisqr_param(dof);
chisqr_.param(chisqr_param);
return chisqr_(rng);
}
// Method to return a random variate drawn from a scaled inverse chi-square distribution. The
// parameters are the degrees of freedom, dof, and the scale parameter, ssqr:
//
// p(x|dof,ssqr) \propto 1 / x^(1 + dof/2) * exp(-dof * ssqr / (dof * x))
double RandomGenerator::scaled_inverse_chisqr(int dof, double ssqr)
{
boost::random::chi_squared_distribution<>::param_type chisqr_param(dof);
chisqr_.param(chisqr_param);
double chi2 = chisqr_(rng);
return ssqr / chi2 * ((double)(dof));
}
// Method to return a random variate drawn from a gamma distribution with shape
// parameter alpha and scale parameter beta:
//
// p(x|alpha,beta) \propto x^(alpha-1) exp(-x / beta)
double RandomGenerator::gamma(double alpha, double beta)
{
boost::random::gamma_distribution<>::param_type gamma_params(alpha,beta);
gamma_.param(gamma_params);
return gamma_(rng);
}
// Method to return a random variate drawn from an inverse gamma distribution
// with shape parameter alpha and inverse scale parameter beta:
//
// p(x|alpha,beta) \propto x^(-alpha-1) exp(-beta / x)
double RandomGenerator::invgamma(double alpha, double beta)
{
boost::random::gamma_distribution<>::param_type gamma_params(alpha, 1.0 / beta);
gamma_.param(gamma_params);
return 1.0 / gamma_(rng);
}
// Method to return a random variate drawn from an inverse gaussian distribution with
// mean parameter mu and shape parameter lambda:
//
// p(x|mu,lambda) \propto (lambda / x^3)^{1/2} * exp{-0.5 * lambda * (x-mu)^2 / (mu^2 * x)}
double RandomGenerator::invgauss(double mu, double lambda) {
double snorm = normal(0.0, 1.0);
double snorm_sqr = snorm * snorm;
double mu_sqr = mu * mu;
double x = mu + mu_sqr * snorm_sqr / (2.0 * lambda) -
mu / (2.0 * lambda) * sqrt(4.0 * mu * lambda * snorm_sqr + mu_sqr * snorm_sqr);
double unif = uniform(0.0, 1.0);
double value = unif <= mu / (mu + x) ? x : mu_sqr / x;
return value;
}
// Method to return a random vector drawn from a multivariate Student's t-distribution.
// More to come later.
arma::vec RandomGenerator::mtdist(arma::mat covar, double dof)
{
arma::vec t(covar.n_rows);
return t;
}
// Method to return a random variate drawn from a beta distribution. More to come.
double RandomGenerator::beta()
{
return 0.0;
}
// Method to return a random variate drawn from a Weibull distribution. More to come.
double RandomGenerator::weibull()
{
return 0.0;
}
<|endoftext|> |
<commit_before>// Based on Fjellstad & Fossen 1994: Quaternion Feedback Regulation of Underwater Vehicles
#include "quaternion_pd_controller.h"
QuaternionPdController::QuaternionPdController()
{
stateSub = nh.subscribe("state_estimate", 10, &QuaternionPdController::stateCallback, this);
setpointSub = nh.subscribe("pose_setpoints", 10, &QuaternionPdController::setpointCallback, this);
controlPub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
enabled = false;
// Initial values
p << 0, 0, 0;
q.w() = 0;
q.vec() << 0, 0, 0;
nu << 0, 0, 0, 0, 0, 0;
p_d << 0, 0, 0;
q_d.w() = 0;
q_d.vec() << 0, 0, 0;
tau << -1, -1, -1, -1, -1, -1;
// Gains etc. (from paper, temporary)
K_D = Eigen::MatrixXd::Identity(6,6);
K_p = 30*Eigen::MatrixXd::Identity(3,3);
c = 200;
r_g.setZero();
r_b.setZero();
W = 185*9.8;
B = 185*9.8;
}
void QuaternionPdController::stateCallback(const uranus_dp::State &msg)
{
tf::pointMsgToEigen(msg.pose.position, p);
tf::quaternionMsgToEigen(msg.pose.orientation, q);
tf::twistMsgToEigen(msg.twist, nu);
// Update rotation matrix
R = q.toRotationMatrix();
}
void QuaternionPdController::setpointCallback(const geometry_msgs::Pose &msg)
{
tf::pointMsgToEigen(msg.position, p_d);
tf::quaternionMsgToEigen(msg.orientation, q_d);
}
void QuaternionPdController::compute()
{
if (enabled)
{
updateProportionalGainMatrix();
updateErrorVector();
updateRestoringForceVector();
tau = - K_D*nu - K_P*z + g;
geometry_msgs::Wrench msg;
tf::wrenchEigenToMsg(tau, msg);
controlPub.publish(msg);
}
}
void QuaternionPdController::enable()
{
enabled = true;
}
void QuaternionPdController::disable()
{
enabled = false;
}
void QuaternionPdController::updateProportionalGainMatrix()
{
K_P << R.transpose() * K_p, Eigen::MatrixXd::Zero(3,3),
Eigen::MatrixXd::Zero(3,3), c*Eigen::MatrixXd::Identity(3,3);
}
void QuaternionPdController::updateErrorVector()
{
Eigen::Vector3d p_tilde = p - p_d;
Eigen::Quaterniond q_tilde = q_d.conjugate()*q;
z << p_tilde,
sgn(q_tilde.w())*q_tilde.vec();
}
void QuaternionPdController::updateRestoringForceVector()
{
// Should I assume an updated R, or force an update here?
Eigen::Vector3d f_g = R.transpose() * Eigen::Vector3d(0, 0, W);
Eigen::Vector3d f_b = R.transpose() * Eigen::Vector3d(0, 0, -B);
g << f_g + f_b,
r_g.cross(f_g) + r_b.cross(f_b);
}
int QuaternionPdController::sgn(double x)
{
if (x < 0)
{
return -1;
}
return 1;
}
Eigen::Matrix3d QuaternionPdController::skew(const Eigen::Vector3d &v)
{
Eigen::Matrix3d S;
S << 0 , -v(2), v(1),
v(2), 0, -v(0),
-v(1), v(0), 0 ;
return S;
}
<commit_msg>Better init and a lot of debug printing<commit_after>// Based on Fjellstad & Fossen 1994: Quaternion Feedback Regulation of Underwater Vehicles
#include "quaternion_pd_controller.h"
// void Print
QuaternionPdController::QuaternionPdController()
{
stateSub = nh.subscribe("state_estimate", 10, &QuaternionPdController::stateCallback, this);
setpointSub = nh.subscribe("pose_setpoints", 10, &QuaternionPdController::setpointCallback, this);
controlPub = nh.advertise<geometry_msgs::Wrench>("rov_forces", 10);
enabled = false;
// Initialize all values to zero/identity
p.setZero();
q.setIdentity();
nu.setZero();
p_d.setZero();
q_d.setIdentity();
z.setZero();
tau.setZero();
g.setZero();
R = q.toRotationMatrix();
// Gains etc. (temporary values from paper)
K_D = Eigen::MatrixXd::Identity(6,6);
K_p = 30*Eigen::MatrixXd::Identity(3,3);
c = 200;
r_g.setZero();
r_b.setZero();
W = 185*9.8;
B = 185*9.8;
}
void QuaternionPdController::stateCallback(const uranus_dp::State &msg)
{
// ROS_INFO("quaternion_pd_controller: stateCallback running.");
tf::pointMsgToEigen(msg.pose.position, p);
tf::quaternionMsgToEigen(msg.pose.orientation, q);
tf::twistMsgToEigen(msg.twist, nu);
// ROS_INFO_STREAM("p set to [" << p(0) << ", " << p(1) << ", " << p(2) << "].");
// ROS_INFO_STREAM("q set to [" << q.w() << ", " << q.x() << ", " << q.y() << ", " << q.z() << "].");
// ROS_INFO_STREAM("nu set to [" << nu(0) << ", " << nu(1) << ", " << nu(2) << ", " << nu(3) << ", " << nu(4) << ", " << nu(5) << "].");
R = q.toRotationMatrix();
// ROS_INFO_STREAM("R = [" << R(0,0) << ", " << R(0,1) << ", " << R(0,2) << "]");
// ROS_INFO_STREAM("R = [" << R(1,0) << ", " << R(1,1) << ", " << R(1,2) << "]");
// ROS_INFO_STREAM("R = [" << R(2,0) << ", " << R(2,1) << ", " << R(2,2) << "]");
}
void QuaternionPdController::setpointCallback(const geometry_msgs::Pose &msg)
{
// ROS_INFO("quaternion_pd_controller: setpointCallback running.");
tf::pointMsgToEigen(msg.position, p_d);
tf::quaternionMsgToEigen(msg.orientation, q_d);
// ROS_INFO_STREAM("p_d set to [" << p_d(0) << ", " << p_d(1) << ", " << p_d(2) << "].");
// ROS_INFO_STREAM("q_d set to [" << q_d.w() << ", " << q_d.x() << ", " << q_d.y() << ", " << q_d.z() << "].");
}
void QuaternionPdController::compute()
{
if (enabled)
{
updateProportionalGainMatrix();
updateErrorVector();
updateRestoringForceVector();
tau = - K_D*nu - K_P*z + g;
// ROS_INFO_STREAM("compute(): nu = [" << nu(0) << ", " << nu(1) << ", " << nu(2) << ", " << nu(3) << ", " << nu(4) << ", " << nu(5) << "].");
// ROS_INFO_STREAM("compute(): z = [" << z(0) << ", " << z(1) << ", " << z(2) << ", " << z(3) << ", " << z(4) << ", " << z(5) << "].");
// ROS_INFO_STREAM("compute(): g = [" << g(0) << ", " << g(1) << ", " << g(2) << "].");
// ROS_INFO_STREAM("tau = [" << tau(0) << ", " << tau(1) << ", " << tau(2) << ", " << tau(3) << ", " << tau(4) << ", " << tau(5) << "].");
geometry_msgs::Wrench msg;
tf::wrenchEigenToMsg(tau, msg);
controlPub.publish(msg);
}
}
void QuaternionPdController::enable()
{
enabled = true;
}
void QuaternionPdController::disable()
{
enabled = false;
}
void QuaternionPdController::updateProportionalGainMatrix()
{
K_P << R.transpose() * K_p, Eigen::MatrixXd::Zero(3,3),
Eigen::MatrixXd::Zero(3,3), c*Eigen::MatrixXd::Identity(3,3);
}
void QuaternionPdController::updateErrorVector()
{
Eigen::Vector3d p_tilde = p - p_d;
Eigen::Quaterniond q_tilde = q_d.conjugate()*q;
z << p_tilde,
sgn(q_tilde.w())*q_tilde.vec();
}
void QuaternionPdController::updateRestoringForceVector()
{
// Should I assume an updated R, or force an update here?
Eigen::Vector3d f_g = R.transpose() * Eigen::Vector3d(0, 0, W);
Eigen::Vector3d f_b = R.transpose() * Eigen::Vector3d(0, 0, -B);
// ROS_INFO_STREAM("updateRestoringForceVector(): f_g = [" << f_g(0) << ", " << f_g(1) << ", " << f_g(2) << "].");
// ROS_INFO_STREAM("updateRestoringForceVector(): f_b = [" << f_b(0) << ", " << f_b(1) << ", " << f_b(2) << "].");
g << f_g + f_b,
r_g.cross(f_g) + r_b.cross(f_b);
}
int QuaternionPdController::sgn(double x)
{
if (x < 0)
{
return -1;
}
return 1;
}
Eigen::Matrix3d QuaternionPdController::skew(const Eigen::Vector3d &v)
{
Eigen::Matrix3d S;
S << 0 , -v(2), v(1),
v(2), 0, -v(0),
-v(1), v(0), 0 ;
return S;
}
<|endoftext|> |
<commit_before>// Copyright 2019 Intel Corporation.
#include "pmlc/dialect/tile/gradient.h"
// TODO: Clean includes
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Support/DebugStringHelper.h"
#include "base/util/logging.h"
#include "pmlc/dialect/tile/builder.h"
#include "pmlc/dialect/tile/ops.h"
#include "pmlc/util/slice.h"
namespace pmlc::dialect::tile {
Gradient::Gradient(mlir::Value* loss, TileBuilder* builder) : builder_(builder) {
IVLOG(3, "Gradient::Gradient> loss: " << mlir::debugString(*loss));
grads_[loss] = builder_->MakeScalarConstantOp(1.0);
llvm::SetVector<mlir::Value*> loss_setvec;
loss_setvec.insert(loss);
auto defs = util::getBackwardSlice(loss_setvec, false, std::function<bool(mlir::Value*)>{[](mlir::Value* val) {
auto op = val->getDefiningOp();
// TODO: This is an ad hoc list of what to filter out; make it principled
return !mlir::isa<AffineConstraintsOp>(op) && !mlir::isa<AffineMapOp>(op) &&
!mlir::isa<AffineIndexOp>(op) && !mlir::isa<DimOp>(op) &&
!mlir::isa<eltwise::ScalarConstantOp>(op);
}});
for (auto def = defs.rbegin(); def != defs.rend(); def++) {
ComputeOperandDerivs(*def);
}
if (VLOG_IS_ON(5)) {
IVLOG(5, "Gradient::Gradient> Computed the following gradients: ");
for (auto [key, value] : grads_) {
IVLOG(5, " key is " << mlir::debugString(*key) << "\n for val " << mlir::debugString(*value));
}
}
}
void Gradient::AddToGradient(Value* source_op, Value* deriv) {
// Adds the gradient `deriv` computed for one use of `source_op` to the overall gradient of `source_op`
if (!grads_.count(source_op)) {
grads_[source_op] = deriv;
} else {
grads_[source_op] = builder_->MakePrimitiveOp("add", {grads_[source_op], deriv});
}
}
void Gradient::ComputeOperandDerivs(mlir::Value* val) {
IVLOG(4, "Gradient::ComputeDerivative> " << mlir::debugString(*val));
// TODO: Throw on ops with multiple results?
auto op = val->getDefiningOp();
if (mlir::isa<AffineConstraintsOp>(op) || mlir::isa<AffineMapOp>(op) || mlir::isa<AffineIndexOp>(op)) {
// TODO: Make the list of which ops these are more principled. Also, should these all be caught in the backwards
// slice filter? If so, probably throw here.
IVLOG(6, "Gradient::ComputeDerivative> Skipping computing derivatives for op "
<< mlir::debugString(*op) << ", as it is not a type of op for which gradients apply");
return;
}
if (!grads_.count(val)) {
IVLOG(1, "Gradient::ComputeOperandDerivs> Called on Value which has not itself been differentiated: "
<< mlir::debugString(*val));
throw std::runtime_error("Unexpected missing derivative in ComputeOperandDerivs");
}
if (mlir::isa<eltwise::EltwiseOp>(op)) {
size_t idx = 0; // Need to track which operand we're at
for (const auto& operand : op->getOperands()) {
auto dop = DeriveEltwise(grads_[val], val, idx);
AddToGradient(operand, dop);
idx++;
}
// TODO: if grads_[operand] has rank > 0, call a simple_reduce
} else if (auto cion_op = mlir::dyn_cast<SymbolicContractionOp>(op)) {
{
// TODO: Do `init` deriv right: we should passthrough on plus, conditional against result on max/min, throw on
// product
// TODO: This is a temporary hack!
AddToGradient(cion_op.init(), grads_[val]);
}
size_t idx = 0; // Need to track which operand we're at
for (auto src : cion_op.srcs()) {
auto dop = DeriveContraction(grads_[val], val, idx);
AddToGradient(src, dop);
idx++;
}
} else if (mlir::isa<SpecialOp>(op)) {
// TODO: Possibly can merge w/ EltwiseOp case?
throw std::runtime_error("TODO: Derivs of Specials not yet implemented");
} else if (mlir::isa<DimOp>(op) || mlir::isa<eltwise::ScalarConstantOp>(op)) {
// TODO: If it turns out one of these matters, be sure to split it off from the ones that don't matter
// TODO: Or otherwise skip? These shouldn't matter...
// TODO: See if int/float matters...
auto dop = builder_->MakeScalarConstantOp(0.);
for (const auto& operand : op->getOperands()) {
AddToGradient(operand, dop);
}
} else if (auto tmap_op = mlir::dyn_cast<AffineTensorMapOp>(op)) {
// Just forward the gradient in a tmap to the tensor
AddToGradient(tmap_op.tensor(), grads_[val]);
} else {
if (op->getNumOperands()) {
throw std::runtime_error("Unexpected Operation type in ComputeOperandDerivs! Operation is " +
mlir::debugString(*op));
}
// If it has no operands, it doesn't matter whether we can differentiate it, so we do nothing
}
}
mlir::Value* Gradient::GetDerivative(mlir::Value* val) {
IVLOG(5, "Gradient::GetDerivative> " << mlir::debugString(*val));
auto it = grads_.find(val);
if (it != grads_.end()) {
IVLOG(6, " Gradient::GetDerivative> Derivative retrieved: " << mlir::debugString(*it->second));
return it->second;
}
// TODO:
// In the long run, this should probably just return 0 or otherwise indicate a continuation
// For now, I want to know if we hit this (as we shouldn't in most cases)
IVLOG(1, "Gradient::GetDerivative> The requested derivative of " << mlir::debugString(*val) << " was not computed!");
throw std::runtime_error("TODO: requested derivative not from getBackwardSlice");
}
mlir::Value* Gradient::DeriveEltwise(mlir::Value* dout, mlir::Value* out, size_t idx) {
auto op = out->getDefiningOp();
IVLOG(5, "Gradient::DeriveEltwise> dout=" << mlir::debugString(*dout) << ", op=" << mlir::debugString(*op)
<< ", idx=" << idx);
// TODO: Handle reshape specially. AST code for that follows
// if (op->fn == "reshape") {
// std::vector<ExprPtr> args = {dout};
// auto in = op->args[0];
// auto dim_exprs = in->shape.dims_as_exprs();
// for (size_t i = 0; i < in->shape.dims.size(); ++i) {
// args.push_back(std::make_shared<DimExprExpr>(dim_exprs[i]));
// }
// return MakeCall("reshape", args);
// }
auto deriv = DerivRegistry::Instance()->Resolve(op->getName().getStringRef());
llvm::SmallVector<mlir::Value*, 3> operands{op->getOperands()}; // TODO: Size
return deriv.fn(out, dout, operands, deriv.user_fn, deriv.user_ctx)[idx];
}
mlir::Value* Gradient::DeriveContraction(mlir::Value* dout, mlir::Value* out, size_t idx) {
IVLOG(5, "Gradient::DeriveContraction> dout=" << mlir::debugString(*dout) << ", out=" << mlir::debugString(*out)
<< ", idx=" << idx);
auto op = llvm::dyn_cast_or_null<SymbolicContractionOp>(out->getDefiningOp());
if (!op) {
throw std::runtime_error("DeriveContraction called on non-contraction");
}
auto combo_kind = util::CombinationKind::none; // This may be reset later if necessary
size_t i = 0;
std::vector<Value*> new_srcs;
Value* target_src = nullptr;
for (auto src : op.srcs()) {
if (i == idx) {
// This is the differentiated input; so swap in dout here to create the new op
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
// This is the non-differentiated input; behavior depends on combo op
switch (op.combo()) {
case util::CombinationKind::none:
IVLOG(1, "About to fail on a NONE combo, with idx==" << idx << ", and i==" << i);
throw std::runtime_error(
"Unexpected multiple inputs found when differentiating contraction with NONE combination op");
break;
case util::CombinationKind::add:
// For +, we ignore the non-differentiated input
combo_kind = util::CombinationKind::none;
break;
case util::CombinationKind::cond:
throw std::runtime_error("Gradient of sum of conditionals not supported");
break;
case util::CombinationKind::eq:
throw std::runtime_error("Gradient of sum of equalities not supported");
break;
case util::CombinationKind::mul:
// For *, we multiply by the non-differentiated input
new_srcs.push_back(src);
combo_kind = util::CombinationKind::mul;
break;
default:
throw std::runtime_error("Failed to recognize combination op during differentiation");
}
}
i++;
}
if (!target_src) {
throw std::runtime_error(
llvm::formatv("Trying to derive contraction at out of range index (requested source operand {0})", idx).str());
}
auto target_src_op = llvm::cast<AffineTensorMapOp>(target_src->getDefiningOp());
std::vector<mlir::Value*> sizes;
for (size_t i = 0; i < target_src_op.tensor()->getType().dyn_cast<RankedTensorType>().getRank(); ++i) {
sizes.push_back(builder_->MakeDimOp(target_src_op.tensor(), i));
}
std::vector<mlir::Value*> dsrc_idxs;
for (const auto& dim : target_src_op.dims()) {
dsrc_idxs.push_back(dim);
}
// TODO: Need to copy the constraints!
auto dop = builder_->MakeContractionOp( //
util::AggregationKind::add, //
combo_kind, //
new_srcs, //
builder_->MakeAffineSinkIndexMapOp(dsrc_idxs), //
builder_->MakeAffineSizeMapOp(sizes), //
llvm::formatv("d{0}", op.name()).str());
return dop;
}
mlir::Value* Gradient::DeriveSpecial(const mlir::Value* dout, SpecialOp* op, size_t idx) {
throw std::runtime_error("Made it to DeriveSpecial!");
}
} // namespace pmlc::dialect::tile
<commit_msg>Fix non-+ contraction gradients<commit_after>// Copyright 2019 Intel Corporation.
#include "pmlc/dialect/tile/gradient.h"
// TODO: Clean includes
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/FormatVariadic.h"
#include "mlir/Support/DebugStringHelper.h"
#include "base/util/logging.h"
#include "pmlc/dialect/tile/builder.h"
#include "pmlc/dialect/tile/ops.h"
#include "pmlc/util/slice.h"
namespace pmlc::dialect::tile {
Gradient::Gradient(mlir::Value* loss, TileBuilder* builder) : builder_(builder) {
IVLOG(3, "Gradient::Gradient> loss: " << mlir::debugString(*loss));
grads_[loss] = builder_->MakeScalarConstantOp(1.0);
llvm::SetVector<mlir::Value*> loss_setvec;
loss_setvec.insert(loss);
auto defs = util::getBackwardSlice(loss_setvec, false, std::function<bool(mlir::Value*)>{[](mlir::Value* val) {
auto op = val->getDefiningOp();
// TODO: This is an ad hoc list of what to filter out; make it principled
return !mlir::isa<AffineConstraintsOp>(op) && !mlir::isa<AffineMapOp>(op) &&
!mlir::isa<AffineIndexOp>(op) && !mlir::isa<DimOp>(op) &&
!mlir::isa<AffineAddOp>(op) && !mlir::isa<AffineDivOp>(op) &&
!mlir::isa<AffineMulOp>(op) && !mlir::isa<AffineNegOp>(op) &&
!mlir::isa<AffineSubOp>(op) && !mlir::isa<AffineMaxOp>(op) &&
!mlir::isa<AffineMinOp>(op) && !mlir::isa<eltwise::ScalarConstantOp>(op);
}});
for (auto def = defs.rbegin(); def != defs.rend(); def++) {
ComputeOperandDerivs(*def);
}
if (VLOG_IS_ON(5)) {
IVLOG(5, "Gradient::Gradient> Computed the following gradients: ");
for (auto [key, value] : grads_) {
IVLOG(5, " key is " << mlir::debugString(*key) << "\n for val " << mlir::debugString(*value));
}
}
}
void Gradient::AddToGradient(Value* source_op, Value* deriv) {
// Adds the gradient `deriv` computed for one use of `source_op` to the overall gradient of `source_op`
if (!grads_.count(source_op)) {
grads_[source_op] = deriv;
} else {
grads_[source_op] = builder_->MakePrimitiveOp("add", {grads_[source_op], deriv});
}
}
void Gradient::ComputeOperandDerivs(mlir::Value* val) {
IVLOG(4, "Gradient::ComputeDerivative> " << mlir::debugString(*val));
// TODO: Throw on ops with multiple results?
auto op = val->getDefiningOp();
if (mlir::isa<AffineConstraintsOp>(op) || mlir::isa<AffineMapOp>(op) || mlir::isa<AffineIndexOp>(op)) {
// TODO: Make the list of which ops these are more principled. Also, should these all be caught in the backwards
// slice filter? If so, probably throw here.
IVLOG(6, "Gradient::ComputeDerivative> Skipping computing derivatives for op "
<< mlir::debugString(*op) << ", as it is not a type of op for which gradients apply");
return;
}
if (!grads_.count(val)) {
IVLOG(1, "Gradient::ComputeOperandDerivs> Called on Value which has not itself been differentiated: "
<< mlir::debugString(*val));
throw std::runtime_error("Unexpected missing derivative in ComputeOperandDerivs");
}
if (mlir::isa<eltwise::EltwiseOp>(op)) {
size_t idx = 0; // Need to track which operand we're at
for (const auto& operand : op->getOperands()) {
auto dop = DeriveEltwise(grads_[val], val, idx);
AddToGradient(operand, dop);
idx++;
}
// TODO: if grads_[operand] has rank > 0, call a simple_reduce
} else if (auto cion_op = mlir::dyn_cast<SymbolicContractionOp>(op)) {
{
// TODO: Do `init` deriv right: we should passthrough on plus, conditional against result on max/min, throw on
// product
// TODO: This is a temporary hack!
AddToGradient(cion_op.init(), grads_[val]);
}
size_t idx = 0; // Need to track which operand we're at
for (auto src : cion_op.srcs()) {
auto dop = DeriveContraction(grads_[val], val, idx);
AddToGradient(src, dop);
idx++;
}
} else if (mlir::isa<SpecialOp>(op)) {
// TODO: Possibly can merge w/ EltwiseOp case?
throw std::runtime_error("TODO: Derivs of Specials not yet implemented");
} else if (mlir::isa<DimOp>(op) || mlir::isa<eltwise::ScalarConstantOp>(op)) {
// TODO: If it turns out one of these matters, be sure to split it off from the ones that don't matter
// TODO: Or otherwise skip? These shouldn't matter...
// TODO: See if int/float matters...
auto dop = builder_->MakeScalarConstantOp(0.);
for (const auto& operand : op->getOperands()) {
AddToGradient(operand, dop);
}
} else if (auto tmap_op = mlir::dyn_cast<AffineTensorMapOp>(op)) {
// Just forward the gradient in a tmap to the tensor
AddToGradient(tmap_op.tensor(), grads_[val]);
} else {
if (op->getNumOperands()) {
throw std::runtime_error("Unexpected Operation type in ComputeOperandDerivs! Operation is " +
mlir::debugString(*op));
}
// If it has no operands, it doesn't matter whether we can differentiate it, so we do nothing
}
}
mlir::Value* Gradient::GetDerivative(mlir::Value* val) {
IVLOG(5, "Gradient::GetDerivative> " << mlir::debugString(*val));
auto it = grads_.find(val);
if (it != grads_.end()) {
IVLOG(6, " Gradient::GetDerivative> Derivative retrieved: " << mlir::debugString(*it->second));
return it->second;
}
// TODO:
// In the long run, this should probably just return 0 or otherwise indicate a continuation
// For now, I want to know if we hit this (as we shouldn't in most cases)
IVLOG(1, "Gradient::GetDerivative> The requested derivative of " << mlir::debugString(*val) << " was not computed!");
throw std::runtime_error("TODO: requested derivative not from getBackwardSlice");
}
mlir::Value* Gradient::DeriveEltwise(mlir::Value* dout, mlir::Value* out, size_t idx) {
auto op = out->getDefiningOp();
IVLOG(5, "Gradient::DeriveEltwise> dout=" << mlir::debugString(*dout) << ", op=" << mlir::debugString(*op)
<< ", idx=" << idx);
// TODO: Handle reshape specially. AST code for that follows
// if (op->fn == "reshape") {
// std::vector<ExprPtr> args = {dout};
// auto in = op->args[0];
// auto dim_exprs = in->shape.dims_as_exprs();
// for (size_t i = 0; i < in->shape.dims.size(); ++i) {
// args.push_back(std::make_shared<DimExprExpr>(dim_exprs[i]));
// }
// return MakeCall("reshape", args);
// }
auto deriv = DerivRegistry::Instance()->Resolve(op->getName().getStringRef());
llvm::SmallVector<mlir::Value*, 3> operands{op->getOperands()}; // TODO: Size
return deriv.fn(out, dout, operands, deriv.user_fn, deriv.user_ctx)[idx];
}
mlir::Value* Gradient::DeriveContraction(mlir::Value* dout, mlir::Value* out, size_t idx) {
IVLOG(5, "Gradient::DeriveContraction> dout=" << mlir::debugString(*dout) << ", out=" << mlir::debugString(*out)
<< ", idx=" << idx);
auto op = llvm::dyn_cast_or_null<SymbolicContractionOp>(out->getDefiningOp());
if (!op) {
throw std::runtime_error("DeriveContraction called on non-contraction");
}
if (op.combo() == util::CombinationKind::eq) {
// TODO: What type should this 0 be?
return builder_->MakeScalarConstantOp(0.);
}
auto combo_kind = util::CombinationKind::none; // This may be reset later if necessary
std::vector<Value*> new_srcs;
Value* target_src = nullptr;
switch (op.agg()) {
case util::AggregationKind::max:
case util::AggregationKind::min: {
size_t i = 0;
// TODO: Is there a better option to do "Get the unique src (or throw if not unique)"?
for (auto src : op.srcs()) {
if (i == idx) {
combo_kind = util::CombinationKind::cond;
auto src_op = mlir::dyn_cast_or_null<AffineTensorMapOp>(
src->getDefiningOp()); // TODO: Track that this is target_src_op
if (!src_op) {
throw std::runtime_error("src_op as cast is null");
}
new_srcs.push_back(src_op);
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(op, dout_idxs));
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
throw std::runtime_error("Cannot differentiate max/min contractions with multiple input tensors");
}
i++;
}
} break;
case util::AggregationKind::add:
case util::AggregationKind::assign: {
size_t i = 0;
for (auto src : op.srcs()) {
if (i == idx) {
// This is the differentiated input; so swap in dout here to create the new op
std::vector<Value*> dout_idxs;
for (const auto& dim : llvm::cast<AffineMapOp>(op.sink()->getDefiningOp()).dims()) {
dout_idxs.push_back(dim);
}
new_srcs.push_back(builder_->MakeAffineSourceIndexMapOp(dout, dout_idxs));
// Also track that this is the differentiated source for later use
target_src = src;
} else {
// This is the non-differentiated input; behavior depends on combo op
switch (op.combo()) {
case util::CombinationKind::none:
IVLOG(1, "About to fail on a NONE combo, with idx==" << idx << ", and i==" << i);
throw std::runtime_error(
"Unexpected multiple inputs found when differentiating contraction with NONE combination op");
break;
case util::CombinationKind::add:
// For +, we ignore the non-differentiated input
combo_kind = util::CombinationKind::none;
break;
case util::CombinationKind::cond:
throw std::runtime_error("Gradient of sum of conditionals not supported");
break;
case util::CombinationKind::eq:
throw std::logic_error("Gradient unexpectedly failed to detect combo op as equality");
break;
case util::CombinationKind::mul:
// For *, we multiply by the non-differentiated input
new_srcs.push_back(src);
combo_kind = util::CombinationKind::mul;
break;
default:
throw std::runtime_error("Failed to recognize combination op during differentiation");
}
}
i++;
}
} break;
case util::AggregationKind::mul:
throw std::runtime_error("Cannot differentiate multiplication aggregations");
break;
default:
throw std::runtime_error("Did not recognize aggregation operation when differentiating " +
mlir::debugString(*out));
}
if (!target_src) {
throw std::runtime_error(
llvm::formatv("Trying to derive contraction at out of range index (requested source operand {0})", idx).str());
}
auto target_src_op = llvm::cast<AffineTensorMapOp>(target_src->getDefiningOp());
std::vector<mlir::Value*> sizes;
for (size_t i = 0; i < target_src_op.tensor()->getType().dyn_cast<RankedTensorType>().getRank(); ++i) {
sizes.push_back(builder_->MakeDimOp(target_src_op.tensor(), i));
}
std::vector<mlir::Value*> dsrc_idxs;
for (const auto& dim : target_src_op.dims()) {
dsrc_idxs.push_back(dim);
}
// TODO: Need to copy the constraints!
auto dop = builder_->MakeContractionOp( //
util::AggregationKind::add, //
combo_kind, //
new_srcs, //
builder_->MakeAffineSinkIndexMapOp(dsrc_idxs), //
builder_->MakeAffineSizeMapOp(sizes), //
llvm::formatv("d{0}", op.name()).str());
return dop;
}
mlir::Value* Gradient::DeriveSpecial(const mlir::Value* dout, SpecialOp* op, size_t idx) {
throw std::runtime_error("Made it to DeriveSpecial!");
}
} // namespace pmlc::dialect::tile
<|endoftext|> |
<commit_before>/*
openpnp test application
Niels Moseley
*/
#include <stdio.h>
#include <conio.h>
#include <windows.h> // for Sleep
#include <chrono>
#include "openpnp-capture.h"
#include "../common/context.h"
std::string FourCCToString(uint32_t fourcc)
{
std::string v;
for(uint32_t i=0; i<4; i++)
{
v += static_cast<char>(fourcc & 0xFF);
fourcc >>= 8;
}
return v;
}
bool writeBufferAsPPM(uint32_t frameNum, uint32_t width, uint32_t height, const uint8_t *bufferPtr, size_t bytes)
{
char fname[100];
sprintf(fname, "frame_%d.ppm",frameNum);
FILE *fout = fopen(fname, "wb");
if (fout == 0)
{
fprintf(stderr, "Cannot open %s for writing\n", fname);
return false;
}
fprintf(fout, "P6 %d %d 255\n", width, height); // PGM header
fwrite(bufferPtr, 1, bytes, fout);
fclose(fout);
return true;
}
void estimateFrameRate(CapContext ctx, int32_t streamID)
{
std::chrono::time_point<std::chrono::system_clock> tstart, tend;
tstart = std::chrono::system_clock::now();
uint32_t fstart = Cap_getStreamFrameCount(ctx, streamID);
Sleep(2000); // 2-second wait
uint32_t fend = Cap_getStreamFrameCount(ctx, streamID);
tend = std::chrono::system_clock::now();
std::chrono::duration<double> fsec = tend-tstart;
uint32_t frames = fend - fstart;
printf("Frames = %d\n", frames);
std::chrono::milliseconds d = std::chrono::duration_cast<std::chrono::milliseconds>(fsec);
printf("Measured fps=%5.2f\n", 1000.0f*frames/static_cast<float>(d.count()));
}
int main(int argc, char*argv[])
{
uint32_t deviceFormatID = 0;
uint32_t deviceID = 0;
printf("==============================\n");
printf(" OpenPNP Capture Test Program\n");
printf(" %s\n", Cap_getLibraryVersion());
printf("==============================\n");
Cap_setLogLevel(7);
if (argc == 1)
{
printf("Usage: openpnp-capture-test <camera ID> <frame format ID>\n");
printf("\n..continuing with default camera parameters.\n\n");
}
if (argc >= 2)
{
deviceID = atoi(argv[1]);
}
if (argc >= 3)
{
deviceFormatID = atoi(argv[2]);
}
CapContext ctx = Cap_createContext();
uint32_t deviceCount = Cap_getDeviceCount(ctx);
printf("Number of devices: %d\n", deviceCount);
for(uint32_t i=0; i<deviceCount; i++)
{
printf("ID %d -> %s\n", i, Cap_getDeviceName(ctx,i));
printf("Unique: %s\n", Cap_getDeviceUniqueID(ctx,i));
// show all supported frame buffer formats
int32_t nFormats = Cap_getNumFormats(ctx, i);
printf(" Number of formats: %d\n", nFormats);
std::string fourccString;
for(int32_t j=0; j<nFormats; j++)
{
CapFormatInfo finfo;
Cap_getFormatInfo(ctx, i, j, &finfo);
fourccString = FourCCToString(finfo.fourcc);
printf(" Format ID %d: %d x %d pixels FOURCC=%s\n",
j, finfo.width, finfo.height, fourccString.c_str());
}
}
int32_t streamID = Cap_openStream(ctx, deviceID, deviceFormatID);
printf("Stream ID = %d\n", streamID);
if (Cap_isOpenStream(ctx, streamID) == 1)
{
printf("Stream is open\n");
}
else
{
printf("Stream is closed (?)\n");
Cap_releaseContext(ctx);
return 1;
}
printf("=== KEY MAPPINGS ===\n");
printf("Press q to exit.\n");
printf("Press + or - to change the exposure.\n");
printf("Press f or g to change the focus.\n");
printf("Press z or x to change the zoom.\n");
printf("Press a or s to change the gain.\n");
printf("Press [ or ] to change the white balance.\n");
printf("Press p to estimate the actual frame rate.\n");
printf("Press w to write the current frame to a PPM file.\n");
// get current stream parameters
CapFormatInfo finfo;
Cap_getFormatInfo(ctx, deviceID, deviceFormatID, &finfo);
//disable auto exposure, focus and white balance
Cap_setAutoProperty(ctx, streamID, CAPPROPID_EXPOSURE, 0);
Cap_setAutoProperty(ctx, streamID, CAPPROPID_FOCUS, 0);
Cap_setAutoProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, 0);
Cap_setAutoProperty(ctx, streamID, CAPPROPID_GAIN, 0);
// set exposure in the middle of the range
int32_t exposure = 0;
int32_t exmax, exmin;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_EXPOSURE, &exmin, &exmax) == CAPRESULT_OK)
{
exposure = (exmax + exmin) / 2;
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, exposure);
printf("Set exposure to %d\n", exposure);
}
else
{
printf("Could not get exposure limits.\n");
}
// set focus in the middle of the range
int32_t focus = 0;
int32_t fomax, fomin;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_FOCUS, &fomin, &fomax) == CAPRESULT_OK)
{
focus = (fomax + fomin) / 2;
Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, focus);
printf("Set focus to %d\n", focus);
}
else
{
printf("Could not get focus limits.\n");
}
// set zoom in the middle of the range
int32_t zoom = 0;
int32_t zomax, zomin;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_ZOOM, &zomin, &zomax) == CAPRESULT_OK)
{
zoom = zomin;
Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, zoom);
printf("Set zoom to %d\n", zoom);
}
else
{
printf("Could not get zoom limits.\n");
}
// set white balance in the middle of the range
int32_t wbalance = 0;
int32_t wbmax, wbmin;
int32_t wbstep = 0;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_WHITEBALANCE, &wbmin, &wbmax) == CAPRESULT_OK)
{
wbalance = (wbmax+wbmin)/2;
wbstep = (wbmax-wbmin) / 20;
Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance);
printf("Set white balance to %d\n", wbalance);
}
else
{
printf("Could not get white balance limits.\n");
}
// set gain in the middle of the range
int32_t gain = 0;
int32_t gmax, gmin;
int32_t gstep = 0;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_GAIN, &gmin, &gmax) == CAPRESULT_OK)
{
gstep = (gmax-gmin) / 20;
Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain);
printf("Set gain to %d (min=%d max=%d)\n", gain, gmin, gmax);
}
else
{
printf("Could not get gain limits.\n");
}
// try to create a message loop so the preview
// window doesn't crash..
MSG msg;
BOOL bRet;
std::vector<uint8_t> m_buffer;
m_buffer.resize(finfo.width*finfo.height*3);
char c = 0;
uint32_t frameWriteCounter=0;
while((c != 'q') && (c != 'Q'))
{
if (PeekMessage(&msg, NULL, 0, 0, 0) != 0)
{
bRet = GetMessage(&msg, NULL, 0, 0);
if (bRet > 0) // (bRet > 0 indicates a message that must be processed.)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
if (_kbhit())
{
c = _getch();
switch(c)
{
case '+':
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, ++exposure);
printf("exposure = %d \r", exposure);
break;
case '-':
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, --exposure);
printf("exposure = %d \r", exposure);
break;
case '0':
exposure = (exmax + exmin) / 2;
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, exposure);
printf("exposure = %d \r", exposure);
break;
case 'f':
Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, ++focus);
printf("focus = %d \r", focus);
break;
case 'g':
Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, --focus);
printf("focus = %d \r", focus);
break;
case 'z':
Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, ++zoom);
printf("zoom = %d \r", zoom);
break;
case 'x':
Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, --zoom);
printf("zoom = %d \r", zoom);
break;
case '[':
wbalance -= wbstep;
Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance);
printf("wbal = %d \r", wbalance);
break;
case ']':
wbalance += wbstep;
Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance);
printf("wbal = %d \r", wbalance);
break;
case 'a':
gain -= gstep;
Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain);
printf("gain = %d \r", gain);
break;
case 's':
gain += gstep;
Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain);
printf("gain = %d \r", gain);
break;
case 'p':
printf("Estimating frame rate..\n");
estimateFrameRate(ctx, streamID);
break;
case 'w':
if (Cap_captureFrame(ctx, streamID, &m_buffer[0], m_buffer.size()) == CAPRESULT_OK)
{
if (writeBufferAsPPM(frameWriteCounter,
finfo.width,
finfo.height,
&m_buffer[0],
m_buffer.size()))
{
printf("Written frame to frame_%d.ppm\n", frameWriteCounter++);
}
}
break;
}
}
Sleep(10);
}
Cap_closeStream(ctx, streamID);
CapResult result = Cap_releaseContext(ctx);
return 0;
}
<commit_msg>Added more error checking to windows test program<commit_after>/*
openpnp test application
Niels Moseley
*/
#include <stdio.h>
#include <conio.h>
#include <windows.h> // for Sleep
#include <chrono>
#include "openpnp-capture.h"
#include "../common/context.h"
std::string FourCCToString(uint32_t fourcc)
{
std::string v;
for(uint32_t i=0; i<4; i++)
{
v += static_cast<char>(fourcc & 0xFF);
fourcc >>= 8;
}
return v;
}
bool writeBufferAsPPM(uint32_t frameNum, uint32_t width, uint32_t height, const uint8_t *bufferPtr, size_t bytes)
{
char fname[100];
sprintf(fname, "frame_%d.ppm",frameNum);
FILE *fout = fopen(fname, "wb");
if (fout == 0)
{
fprintf(stderr, "Cannot open %s for writing\n", fname);
return false;
}
fprintf(fout, "P6 %d %d 255\n", width, height); // PGM header
fwrite(bufferPtr, 1, bytes, fout);
fclose(fout);
return true;
}
void estimateFrameRate(CapContext ctx, int32_t streamID)
{
std::chrono::time_point<std::chrono::system_clock> tstart, tend;
tstart = std::chrono::system_clock::now();
uint32_t fstart = Cap_getStreamFrameCount(ctx, streamID);
Sleep(2000); // 2-second wait
uint32_t fend = Cap_getStreamFrameCount(ctx, streamID);
tend = std::chrono::system_clock::now();
std::chrono::duration<double> fsec = tend-tstart;
uint32_t frames = fend - fstart;
printf("Frames = %d\n", frames);
std::chrono::milliseconds d = std::chrono::duration_cast<std::chrono::milliseconds>(fsec);
printf("Measured fps=%5.2f\n", 1000.0f*frames/static_cast<float>(d.count()));
}
int main(int argc, char*argv[])
{
uint32_t deviceFormatID = 0;
uint32_t deviceID = 0;
printf("==============================\n");
printf(" OpenPNP Capture Test Program\n");
printf(" %s\n", Cap_getLibraryVersion());
printf("==============================\n");
Cap_setLogLevel(7);
if (argc == 1)
{
printf("Usage: openpnp-capture-test <camera ID> <frame format ID>\n");
printf("\n..continuing with default camera parameters.\n\n");
}
if (argc >= 2)
{
deviceID = atoi(argv[1]);
}
if (argc >= 3)
{
deviceFormatID = atoi(argv[2]);
}
CapContext ctx = Cap_createContext();
uint32_t deviceCount = Cap_getDeviceCount(ctx);
printf("Number of devices: %d\n", deviceCount);
for(uint32_t i=0; i<deviceCount; i++)
{
printf("ID %d -> %s\n", i, Cap_getDeviceName(ctx,i));
printf("Unique: %s\n", Cap_getDeviceUniqueID(ctx,i));
// show all supported frame buffer formats
int32_t nFormats = Cap_getNumFormats(ctx, i);
printf(" Number of formats: %d\n", nFormats);
std::string fourccString;
for(int32_t j=0; j<nFormats; j++)
{
CapFormatInfo finfo;
Cap_getFormatInfo(ctx, i, j, &finfo);
fourccString = FourCCToString(finfo.fourcc);
printf(" Format ID %d: %d x %d pixels FOURCC=%s\n",
j, finfo.width, finfo.height, fourccString.c_str());
}
}
int32_t streamID = Cap_openStream(ctx, deviceID, deviceFormatID);
printf("Stream ID = %d\n", streamID);
if (Cap_isOpenStream(ctx, streamID) == 1)
{
printf("Stream is open\n");
}
else
{
printf("Stream is closed (?)\n");
Cap_releaseContext(ctx);
return 1;
}
printf("=== KEY MAPPINGS ===\n");
printf("Press q to exit.\n");
printf("Press + or - to change the exposure.\n");
printf("Press f or g to change the focus.\n");
printf("Press z or x to change the zoom.\n");
printf("Press a or s to change the gain.\n");
printf("Press [ or ] to change the white balance.\n");
printf("Press p to estimate the actual frame rate.\n");
printf("Press w to write the current frame to a PPM file.\n");
// get current stream parameters
CapFormatInfo finfo;
Cap_getFormatInfo(ctx, deviceID, deviceFormatID, &finfo);
//disable auto exposure, focus and white balance
if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_EXPOSURE, 0) != CAPRESULT_OK)
{
printf("Could not disable auto-exposure\n");
}
if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_FOCUS, 0) != CAPRESULT_OK)
{
printf("Could not disable auto-focus\n");
}
if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, 0) != CAPRESULT_OK)
{
printf("Could not disabe auto-whitebalance\n");
}
if (Cap_setAutoProperty(ctx, streamID, CAPPROPID_GAIN, 0) != CAPRESULT_OK)
{
printf("Could not disable auto-gain\n");
}
// set exposure in the middle of the range
int32_t exposure = 0;
int32_t exmax, exmin;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_EXPOSURE, &exmin, &exmax) == CAPRESULT_OK)
{
exposure = (exmax + exmin) / 2;
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, exposure);
printf("Set exposure to %d\n", exposure);
}
else
{
printf("Could not get exposure limits.\n");
}
// set focus in the middle of the range
int32_t focus = 0;
int32_t fomax, fomin;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_FOCUS, &fomin, &fomax) == CAPRESULT_OK)
{
focus = (fomax + fomin) / 2;
Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, focus);
printf("Set focus to %d\n", focus);
}
else
{
printf("Could not get focus limits.\n");
}
// set zoom in the middle of the range
int32_t zoom = 0;
int32_t zomax, zomin;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_ZOOM, &zomin, &zomax) == CAPRESULT_OK)
{
zoom = zomin;
Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, zoom);
printf("Set zoom to %d\n", zoom);
}
else
{
printf("Could not get zoom limits.\n");
}
// set white balance in the middle of the range
int32_t wbalance = 0;
int32_t wbmax, wbmin;
int32_t wbstep = 0;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_WHITEBALANCE, &wbmin, &wbmax) == CAPRESULT_OK)
{
wbalance = (wbmax+wbmin)/2;
wbstep = (wbmax-wbmin) / 20;
Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance);
printf("Set white balance to %d\n", wbalance);
}
else
{
printf("Could not get white balance limits.\n");
}
// set gain in the middle of the range
int32_t gain = 0;
int32_t gmax, gmin;
int32_t gstep = 0;
if (Cap_getPropertyLimits(ctx, streamID, CAPPROPID_GAIN, &gmin, &gmax) == CAPRESULT_OK)
{
gstep = (gmax-gmin) / 20;
Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain);
printf("Set gain to %d (min=%d max=%d)\n", gain, gmin, gmax);
}
else
{
printf("Could not get gain limits.\n");
}
// try to create a message loop so the preview
// window doesn't crash..
MSG msg;
BOOL bRet;
std::vector<uint8_t> m_buffer;
m_buffer.resize(finfo.width*finfo.height*3);
char c = 0;
uint32_t frameWriteCounter=0;
while((c != 'q') && (c != 'Q'))
{
if (PeekMessage(&msg, NULL, 0, 0, 0) != 0)
{
bRet = GetMessage(&msg, NULL, 0, 0);
if (bRet > 0) // (bRet > 0 indicates a message that must be processed.)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
if (_kbhit())
{
c = _getch();
switch(c)
{
case '+':
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, ++exposure);
printf("exposure = %d \r", exposure);
break;
case '-':
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, --exposure);
printf("exposure = %d \r", exposure);
break;
case '0':
exposure = (exmax + exmin) / 2;
Cap_setProperty(ctx, streamID, CAPPROPID_EXPOSURE, exposure);
printf("exposure = %d \r", exposure);
break;
case 'f':
Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, ++focus);
printf("focus = %d \r", focus);
break;
case 'g':
Cap_setProperty(ctx, streamID, CAPPROPID_FOCUS, --focus);
printf("focus = %d \r", focus);
break;
case 'z':
Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, ++zoom);
printf("zoom = %d \r", zoom);
break;
case 'x':
Cap_setProperty(ctx, streamID, CAPPROPID_ZOOM, --zoom);
printf("zoom = %d \r", zoom);
break;
case '[':
wbalance -= wbstep;
Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance);
printf("wbal = %d \r", wbalance);
break;
case ']':
wbalance += wbstep;
Cap_setProperty(ctx, streamID, CAPPROPID_WHITEBALANCE, wbalance);
printf("wbal = %d \r", wbalance);
break;
case 'a':
gain -= gstep;
Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain);
printf("gain = %d \r", gain);
break;
case 's':
gain += gstep;
Cap_setProperty(ctx, streamID, CAPPROPID_GAIN, gain);
printf("gain = %d \r", gain);
break;
case 'p':
printf("Estimating frame rate..\n");
estimateFrameRate(ctx, streamID);
break;
case 'w':
if (Cap_captureFrame(ctx, streamID, &m_buffer[0], m_buffer.size()) == CAPRESULT_OK)
{
if (writeBufferAsPPM(frameWriteCounter,
finfo.width,
finfo.height,
&m_buffer[0],
m_buffer.size()))
{
printf("Written frame to frame_%d.ppm\n", frameWriteCounter++);
}
}
break;
}
}
Sleep(10);
}
Cap_closeStream(ctx, streamID);
CapResult result = Cap_releaseContext(ctx);
return 0;
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
#include <dsn/utility/rand.h>
#include "asio_net_provider.h"
#include "asio_rpc_session.h"
namespace dsn {
namespace tools {
asio_network_provider::asio_network_provider(rpc_engine *srv, network *inner_provider)
: connection_oriented_network(srv, inner_provider)
{
_acceptor = nullptr;
}
error_code asio_network_provider::start(rpc_channel channel, int port, bool client_only)
{
if (_acceptor != nullptr)
return ERR_SERVICE_ALREADY_RUNNING;
int io_service_worker_count =
(int)dsn_config_get_value_uint64("network",
"io_service_worker_count",
1,
"thread number for io service (timer and boost network)");
for (int i = 0; i < io_service_worker_count; i++) {
_workers.push_back(std::shared_ptr<std::thread>(new std::thread([this, i]() {
task::set_tls_dsn_context(node(), nullptr);
const char *name = ::dsn::tools::get_service_node_name(node());
char buffer[128];
sprintf(buffer, "%s.asio.%d", name, i);
task_worker::set_name(buffer);
boost::asio::io_service::work work(_io_service);
_io_service.run();
})));
}
_acceptor = nullptr;
dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP,
"invalid given channel %s",
channel.to_string());
_address.assign_ipv4(get_local_ipv4(), port);
if (!client_only) {
auto v4_addr = boost::asio::ip::address_v4::any(); //(ntohl(_address.ip));
::boost::asio::ip::tcp::endpoint endpoint(v4_addr, _address.port());
boost::system::error_code ec;
_acceptor.reset(new boost::asio::ip::tcp::acceptor(_io_service));
_acceptor->open(endpoint.protocol(), ec);
if (ec) {
derror("asio tcp acceptor open failed, error = %s", ec.message().c_str());
_acceptor.reset();
return ERR_NETWORK_INIT_FAILED;
}
_acceptor->set_option(boost::asio::socket_base::reuse_address(true));
_acceptor->bind(endpoint, ec);
if (ec) {
derror("asio tcp acceptor bind failed, error = %s", ec.message().c_str());
_acceptor.reset();
return ERR_NETWORK_INIT_FAILED;
}
int backlog = boost::asio::socket_base::max_connections;
_acceptor->listen(backlog, ec);
if (ec) {
derror("asio tcp acceptor listen failed, port = %u, error = %s",
_address.port(),
ec.message().c_str());
_acceptor.reset();
return ERR_NETWORK_INIT_FAILED;
}
do_accept();
}
return ERR_OK;
}
rpc_session_ptr asio_network_provider::create_client_session(::dsn::rpc_address server_addr)
{
auto sock = std::shared_ptr<boost::asio::ip::tcp::socket>(
new boost::asio::ip::tcp::socket(_io_service));
message_parser_ptr parser(new_message_parser(_client_hdr_format));
return rpc_session_ptr(new asio_rpc_session(*this, server_addr, sock, parser, true));
}
void asio_network_provider::do_accept()
{
auto socket = std::shared_ptr<boost::asio::ip::tcp::socket>(
new boost::asio::ip::tcp::socket(_io_service));
_acceptor->async_accept(*socket, [this, socket](boost::system::error_code ec) {
if (!ec) {
auto ip = socket->remote_endpoint().address().to_v4().to_ulong();
auto port = socket->remote_endpoint().port();
::dsn::rpc_address client_addr(ip, port);
message_parser_ptr null_parser;
rpc_session_ptr s =
new asio_rpc_session(*this,
client_addr,
(std::shared_ptr<boost::asio::ip::tcp::socket> &)socket,
null_parser,
false);
on_server_session_accepted(s);
// we should start read immediately after the rpc session is completely created.
s->start_read_next();
}
do_accept();
});
}
void asio_udp_provider::send_message(message_ex *request)
{
auto parser = get_message_parser(request->hdr_format);
parser->prepare_on_send(request);
auto lcount = parser->get_buffer_count_on_send(request);
std::unique_ptr<message_parser::send_buf[]> bufs(new message_parser::send_buf[lcount]);
auto rcount = parser->get_buffers_on_send(request, bufs.get());
dassert(lcount >= rcount, "%d VS %d", lcount, rcount);
size_t tlen = 0, offset = 0;
for (int i = 0; i < rcount; i++) {
tlen += bufs[i].sz;
}
dassert(tlen <= max_udp_packet_size, "the message is too large to send via a udp channel");
std::unique_ptr<char[]> packet_buffer(new char[tlen]);
for (int i = 0; i < rcount; i++) {
memcpy(&packet_buffer[offset], bufs[i].buf, bufs[i].sz);
offset += bufs[i].sz;
};
::boost::asio::ip::udp::endpoint ep(::boost::asio::ip::address_v4(request->to_address.ip()),
request->to_address.port());
_socket->async_send_to(
::boost::asio::buffer(packet_buffer.get(), tlen),
ep,
[=](const boost::system::error_code &error, std::size_t bytes_transferred) {
if (error) {
dwarn("send udp packet to ep %s:%d failed, message = %s",
ep.address().to_string().c_str(),
ep.port(),
error.message().c_str());
// we do not handle failure here, rpc matcher would handle timeouts
}
});
}
asio_udp_provider::asio_udp_provider(rpc_engine *srv, network *inner_provider)
: network(srv, inner_provider), _is_client(false), _recv_reader(_message_buffer_block_size)
{
_parsers = new message_parser *[network_header_format::max_value() + 1];
memset(_parsers, 0, sizeof(message_parser *) * (network_header_format::max_value() + 1));
}
asio_udp_provider::~asio_udp_provider()
{
for (int i = 0; i <= network_header_format::max_value(); i++) {
if (_parsers[i] != nullptr) {
delete _parsers[i];
_parsers[i] = nullptr;
}
}
delete[] _parsers;
_parsers = nullptr;
}
message_parser *asio_udp_provider::get_message_parser(network_header_format hdr_format)
{
if (_parsers[hdr_format] == nullptr) {
utils::auto_lock<utils::ex_lock_nr> l(_lock);
if (_parsers[hdr_format] == nullptr) // double check
{
_parsers[hdr_format] = new_message_parser(hdr_format);
}
}
return _parsers[hdr_format];
}
void asio_udp_provider::do_receive()
{
std::shared_ptr<::boost::asio::ip::udp::endpoint> send_endpoint(
new ::boost::asio::ip::udp::endpoint);
_recv_reader.truncate_read();
auto buffer_ptr = _recv_reader.read_buffer_ptr(max_udp_packet_size);
dassert(_recv_reader.read_buffer_capacity() >= max_udp_packet_size,
"failed to load enough buffer in parser");
_socket->async_receive_from(
::boost::asio::buffer(buffer_ptr, max_udp_packet_size),
*send_endpoint,
[this, send_endpoint](const boost::system::error_code &error,
std::size_t bytes_transferred) {
if (!!error) {
derror(
"%s: asio udp read failed: %s", _address.to_string(), error.message().c_str());
do_receive();
return;
}
if (bytes_transferred < sizeof(uint32_t)) {
derror("%s: asio udp read failed: too short message", _address.to_string());
do_receive();
return;
}
auto hdr_format = message_parser::get_header_type(_recv_reader._buffer.data());
if (NET_HDR_INVALID == hdr_format) {
derror("%s: asio udp read failed: invalid header type '%s'",
_address.to_string(),
message_parser::get_debug_string(_recv_reader._buffer.data()).c_str());
do_receive();
return;
}
auto parser = get_message_parser(hdr_format);
parser->reset();
_recv_reader.mark_read(bytes_transferred);
int read_next = -1;
message_ex *msg = parser->get_message_on_receive(&_recv_reader, read_next);
if (msg == nullptr) {
derror("%s: asio udp read failed: invalid udp packet", _address.to_string());
do_receive();
return;
}
msg->to_address = _address;
if (msg->header->context.u.is_request) {
on_recv_request(msg, 0);
} else {
on_recv_reply(msg->header->id, msg, 0);
}
do_receive();
});
}
error_code asio_udp_provider::start(rpc_channel channel, int port, bool client_only)
{
_is_client = client_only;
int io_service_worker_count =
(int)dsn_config_get_value_uint64("network",
"io_service_worker_count",
1,
"thread number for io service (timer and boost network)");
dassert(channel == RPC_CHANNEL_UDP, "invalid given channel %s", channel.to_string());
if (client_only) {
do {
// FIXME: we actually do not need to set a random port for client if the rpc_engine is
// refactored
_address.assign_ipv4(get_local_ipv4(),
std::numeric_limits<uint16_t>::max() -
rand::next_u64(std::numeric_limits<uint64_t>::min(),
std::numeric_limits<uint64_t>::max()) %
5000);
::boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address_v4::any(),
_address.port());
boost::system::error_code ec;
_socket.reset(new ::boost::asio::ip::udp::socket(_io_service));
_socket->open(endpoint.protocol(), ec);
if (ec) {
dwarn("asio udp socket open failed, error = %s", ec.message().c_str());
_socket.reset();
continue;
}
_socket->bind(endpoint, ec);
if (ec) {
dwarn("asio udp socket bind failed, port = %u, error = %s",
_address.port(),
ec.message().c_str());
_socket.reset();
continue;
}
break;
} while (true);
} else {
_address.assign_ipv4(get_local_ipv4(), port);
::boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address_v4::any(),
_address.port());
boost::system::error_code ec;
_socket.reset(new ::boost::asio::ip::udp::socket(_io_service));
_socket->open(endpoint.protocol(), ec);
if (ec) {
dwarn("asio udp socket open failed, error = %s", ec.message().c_str());
_socket.reset();
return ERR_NETWORK_INIT_FAILED;
}
_socket->bind(endpoint, ec);
if (ec) {
dwarn("asio udp socket bind failed, port = %u, error = %s",
_address.port(),
ec.message().c_str());
_socket.reset();
return ERR_NETWORK_INIT_FAILED;
}
}
for (int i = 0; i < io_service_worker_count; i++) {
_workers.push_back(std::shared_ptr<std::thread>(new std::thread([this, i]() {
task::set_tls_dsn_context(node(), nullptr);
const char *name = ::dsn::tools::get_service_node_name(node());
char buffer[128];
sprintf(buffer, "%s.asio.udp.%d.%d", name, (int)(this->address().port()), i);
task_worker::set_name(buffer);
boost::asio::io_service::work work(_io_service);
_io_service.run();
})));
}
do_receive();
return ERR_OK;
}
}
}
<commit_msg>rpc: fix pegasus-186 (#169)<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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.
*/
/*
* Description:
* What is this file about?
*
* Revision history:
* xxxx-xx-xx, author, first version
* xxxx-xx-xx, author, fix bug about xxx
*/
#include <dsn/utility/rand.h>
#include "asio_net_provider.h"
#include "asio_rpc_session.h"
namespace dsn {
namespace tools {
asio_network_provider::asio_network_provider(rpc_engine *srv, network *inner_provider)
: connection_oriented_network(srv, inner_provider)
{
_acceptor = nullptr;
}
error_code asio_network_provider::start(rpc_channel channel, int port, bool client_only)
{
if (_acceptor != nullptr)
return ERR_SERVICE_ALREADY_RUNNING;
int io_service_worker_count =
(int)dsn_config_get_value_uint64("network",
"io_service_worker_count",
1,
"thread number for io service (timer and boost network)");
for (int i = 0; i < io_service_worker_count; i++) {
_workers.push_back(std::shared_ptr<std::thread>(new std::thread([this, i]() {
task::set_tls_dsn_context(node(), nullptr);
const char *name = ::dsn::tools::get_service_node_name(node());
char buffer[128];
sprintf(buffer, "%s.asio.%d", name, i);
task_worker::set_name(buffer);
boost::asio::io_service::work work(_io_service);
boost::system::error_code ec;
_io_service.run(ec);
dassert(false, "boost::asio::io_service run failed: err(%s)", ec.message().data());
})));
}
_acceptor = nullptr;
dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP,
"invalid given channel %s",
channel.to_string());
_address.assign_ipv4(get_local_ipv4(), port);
if (!client_only) {
auto v4_addr = boost::asio::ip::address_v4::any(); //(ntohl(_address.ip));
::boost::asio::ip::tcp::endpoint endpoint(v4_addr, _address.port());
boost::system::error_code ec;
_acceptor.reset(new boost::asio::ip::tcp::acceptor(_io_service));
_acceptor->open(endpoint.protocol(), ec);
if (ec) {
derror("asio tcp acceptor open failed, error = %s", ec.message().c_str());
_acceptor.reset();
return ERR_NETWORK_INIT_FAILED;
}
_acceptor->set_option(boost::asio::socket_base::reuse_address(true));
_acceptor->bind(endpoint, ec);
if (ec) {
derror("asio tcp acceptor bind failed, error = %s", ec.message().c_str());
_acceptor.reset();
return ERR_NETWORK_INIT_FAILED;
}
int backlog = boost::asio::socket_base::max_connections;
_acceptor->listen(backlog, ec);
if (ec) {
derror("asio tcp acceptor listen failed, port = %u, error = %s",
_address.port(),
ec.message().c_str());
_acceptor.reset();
return ERR_NETWORK_INIT_FAILED;
}
do_accept();
}
return ERR_OK;
}
rpc_session_ptr asio_network_provider::create_client_session(::dsn::rpc_address server_addr)
{
auto sock = std::shared_ptr<boost::asio::ip::tcp::socket>(
new boost::asio::ip::tcp::socket(_io_service));
message_parser_ptr parser(new_message_parser(_client_hdr_format));
return rpc_session_ptr(new asio_rpc_session(*this, server_addr, sock, parser, true));
}
void asio_network_provider::do_accept()
{
auto socket = std::shared_ptr<boost::asio::ip::tcp::socket>(
new boost::asio::ip::tcp::socket(_io_service));
_acceptor->async_accept(*socket, [this, socket](boost::system::error_code ec) {
if (!ec) {
auto remote = socket->remote_endpoint(ec);
if (ec) {
derror("failed to get the remote endpoint: %s", ec.message().data());
} else {
auto ip = remote.address().to_v4().to_ulong();
auto port = remote.port();
::dsn::rpc_address client_addr(ip, port);
message_parser_ptr null_parser;
rpc_session_ptr s =
new asio_rpc_session(*this,
client_addr,
(std::shared_ptr<boost::asio::ip::tcp::socket> &)socket,
null_parser,
false);
on_server_session_accepted(s);
// we should start read immediately after the rpc session is completely created.
s->start_read_next();
}
}
do_accept();
});
}
void asio_udp_provider::send_message(message_ex *request)
{
auto parser = get_message_parser(request->hdr_format);
parser->prepare_on_send(request);
auto lcount = parser->get_buffer_count_on_send(request);
std::unique_ptr<message_parser::send_buf[]> bufs(new message_parser::send_buf[lcount]);
auto rcount = parser->get_buffers_on_send(request, bufs.get());
dassert(lcount >= rcount, "%d VS %d", lcount, rcount);
size_t tlen = 0, offset = 0;
for (int i = 0; i < rcount; i++) {
tlen += bufs[i].sz;
}
dassert(tlen <= max_udp_packet_size, "the message is too large to send via a udp channel");
std::unique_ptr<char[]> packet_buffer(new char[tlen]);
for (int i = 0; i < rcount; i++) {
memcpy(&packet_buffer[offset], bufs[i].buf, bufs[i].sz);
offset += bufs[i].sz;
};
::boost::asio::ip::udp::endpoint ep(::boost::asio::ip::address_v4(request->to_address.ip()),
request->to_address.port());
_socket->async_send_to(
::boost::asio::buffer(packet_buffer.get(), tlen),
ep,
[=](const boost::system::error_code &error, std::size_t bytes_transferred) {
if (error) {
dwarn("send udp packet to ep %s:%d failed, message = %s",
ep.address().to_string().c_str(),
ep.port(),
error.message().c_str());
// we do not handle failure here, rpc matcher would handle timeouts
}
});
}
asio_udp_provider::asio_udp_provider(rpc_engine *srv, network *inner_provider)
: network(srv, inner_provider), _is_client(false), _recv_reader(_message_buffer_block_size)
{
_parsers = new message_parser *[network_header_format::max_value() + 1];
memset(_parsers, 0, sizeof(message_parser *) * (network_header_format::max_value() + 1));
}
asio_udp_provider::~asio_udp_provider()
{
for (int i = 0; i <= network_header_format::max_value(); i++) {
if (_parsers[i] != nullptr) {
delete _parsers[i];
_parsers[i] = nullptr;
}
}
delete[] _parsers;
_parsers = nullptr;
}
message_parser *asio_udp_provider::get_message_parser(network_header_format hdr_format)
{
if (_parsers[hdr_format] == nullptr) {
utils::auto_lock<utils::ex_lock_nr> l(_lock);
if (_parsers[hdr_format] == nullptr) // double check
{
_parsers[hdr_format] = new_message_parser(hdr_format);
}
}
return _parsers[hdr_format];
}
void asio_udp_provider::do_receive()
{
std::shared_ptr<::boost::asio::ip::udp::endpoint> send_endpoint(
new ::boost::asio::ip::udp::endpoint);
_recv_reader.truncate_read();
auto buffer_ptr = _recv_reader.read_buffer_ptr(max_udp_packet_size);
dassert(_recv_reader.read_buffer_capacity() >= max_udp_packet_size,
"failed to load enough buffer in parser");
_socket->async_receive_from(
::boost::asio::buffer(buffer_ptr, max_udp_packet_size),
*send_endpoint,
[this, send_endpoint](const boost::system::error_code &error,
std::size_t bytes_transferred) {
if (!!error) {
derror(
"%s: asio udp read failed: %s", _address.to_string(), error.message().c_str());
do_receive();
return;
}
if (bytes_transferred < sizeof(uint32_t)) {
derror("%s: asio udp read failed: too short message", _address.to_string());
do_receive();
return;
}
auto hdr_format = message_parser::get_header_type(_recv_reader._buffer.data());
if (NET_HDR_INVALID == hdr_format) {
derror("%s: asio udp read failed: invalid header type '%s'",
_address.to_string(),
message_parser::get_debug_string(_recv_reader._buffer.data()).c_str());
do_receive();
return;
}
auto parser = get_message_parser(hdr_format);
parser->reset();
_recv_reader.mark_read(bytes_transferred);
int read_next = -1;
message_ex *msg = parser->get_message_on_receive(&_recv_reader, read_next);
if (msg == nullptr) {
derror("%s: asio udp read failed: invalid udp packet", _address.to_string());
do_receive();
return;
}
msg->to_address = _address;
if (msg->header->context.u.is_request) {
on_recv_request(msg, 0);
} else {
on_recv_reply(msg->header->id, msg, 0);
}
do_receive();
});
}
error_code asio_udp_provider::start(rpc_channel channel, int port, bool client_only)
{
_is_client = client_only;
int io_service_worker_count =
(int)dsn_config_get_value_uint64("network",
"io_service_worker_count",
1,
"thread number for io service (timer and boost network)");
dassert(channel == RPC_CHANNEL_UDP, "invalid given channel %s", channel.to_string());
if (client_only) {
do {
// FIXME: we actually do not need to set a random port for client if the rpc_engine is
// refactored
_address.assign_ipv4(get_local_ipv4(),
std::numeric_limits<uint16_t>::max() -
rand::next_u64(std::numeric_limits<uint64_t>::min(),
std::numeric_limits<uint64_t>::max()) %
5000);
::boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address_v4::any(),
_address.port());
boost::system::error_code ec;
_socket.reset(new ::boost::asio::ip::udp::socket(_io_service));
_socket->open(endpoint.protocol(), ec);
if (ec) {
dwarn("asio udp socket open failed, error = %s", ec.message().c_str());
_socket.reset();
continue;
}
_socket->bind(endpoint, ec);
if (ec) {
dwarn("asio udp socket bind failed, port = %u, error = %s",
_address.port(),
ec.message().c_str());
_socket.reset();
continue;
}
break;
} while (true);
} else {
_address.assign_ipv4(get_local_ipv4(), port);
::boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address_v4::any(),
_address.port());
boost::system::error_code ec;
_socket.reset(new ::boost::asio::ip::udp::socket(_io_service));
_socket->open(endpoint.protocol(), ec);
if (ec) {
dwarn("asio udp socket open failed, error = %s", ec.message().c_str());
_socket.reset();
return ERR_NETWORK_INIT_FAILED;
}
_socket->bind(endpoint, ec);
if (ec) {
dwarn("asio udp socket bind failed, port = %u, error = %s",
_address.port(),
ec.message().c_str());
_socket.reset();
return ERR_NETWORK_INIT_FAILED;
}
}
for (int i = 0; i < io_service_worker_count; i++) {
_workers.push_back(std::shared_ptr<std::thread>(new std::thread([this, i]() {
task::set_tls_dsn_context(node(), nullptr);
const char *name = ::dsn::tools::get_service_node_name(node());
char buffer[128];
sprintf(buffer, "%s.asio.udp.%d.%d", name, (int)(this->address().port()), i);
task_worker::set_name(buffer);
boost::asio::io_service::work work(_io_service);
boost::system::error_code ec;
_io_service.run(ec);
dassert(false, "boost::asio::io_service run failed: err(%s)", ec.message().data());
})));
}
do_receive();
return ERR_OK;
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments;
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list. Also log and
// record.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<commit_msg>[tf.data] Stop to record graduated experiments for in the future some of them may not appear in the `graduated_experiments` list.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/kernels/data/optimize_dataset_op.h"
// On mobile we do not provide optimize dataset op because not all of its
// dependencies are available there. The op is replaced with a no-op.
#if !defined(IS_MOBILE_PLATFORM)
#include <map>
#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/dataset_utils.h"
#include "tensorflow/core/kernels/data/rewrite_utils.h"
#include "tensorflow/core/lib/random/random.h"
#include "tensorflow/core/platform/host_info.h"
#include "tensorflow/core/protobuf/rewriter_config.pb.h"
namespace tensorflow {
namespace data {
/* static */ constexpr const char* const OptimizeDatasetOp::kDatasetType;
/* static */ constexpr const char* const OptimizeDatasetOp::kInputDataset;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizations;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsEnabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDisabled;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationsDefault;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputTypes;
/* static */ constexpr const char* const OptimizeDatasetOp::kOutputShapes;
/* static */ constexpr const char* const
OptimizeDatasetOp::kOptimizationConfigs;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV1;
/* static */ constexpr const char* const OptimizeDatasetOp::kOptimizeDatasetV2;
constexpr char kOptimizerName[] = "tf_data_meta_optimizer";
constexpr char kOptimizers[] = "optimizers";
constexpr char kOptimizerConfigs[] = "optimizer_configs";
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {
auto& op_name = ctx->def().op();
if (op_name == kOptimizeDatasetV1) {
op_version_ = 1;
} else if (op_name == kOptimizeDatasetV2) {
op_version_ = 2;
}
OP_REQUIRES_OK(ctx,
ctx->GetAttr(kOptimizationConfigs, &optimization_configs_));
}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
std::vector<tstring> optimizations;
if (op_version_ == 1) {
OP_REQUIRES_OK(
ctx, ParseVectorArgument<tstring>(ctx, kOptimizations, &optimizations));
} else if (op_version_ == 2) {
std::vector<tstring> optimizations_enabled, optimizations_disabled,
optimizations_default;
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsEnabled,
&optimizations_enabled));
OP_REQUIRES_OK(ctx,
ParseVectorArgument<tstring>(ctx, kOptimizationsDisabled,
&optimizations_disabled));
OP_REQUIRES_OK(ctx, ParseVectorArgument<tstring>(ctx, kOptimizationsDefault,
&optimizations_default));
string job_name = port::JobName();
// The map that stores the live experiment names and for how much percentage
// of the Borg jobs, the experiments will be randomly turned on.
// clang-format off
absl::flat_hash_map<string, uint64> live_experiments;
// clang-format on
auto hash_func = [](const string& str) { return Hash64(str); };
optimizations = SelectOptimizations(
job_name, live_experiments, optimizations_enabled,
optimizations_disabled, optimizations_default, hash_func);
// Log and record the live experiments that will be applied.
if (!job_name.empty() && !live_experiments.empty()) {
VLOG(1) << "The input pipeline is subject to tf.data experiment. "
"Please see `go/tf-data-experiments` for more details.";
for (auto& pair : live_experiments) {
string experiment = pair.first;
if (std::find(optimizations.begin(), optimizations.end(), experiment) !=
optimizations.end()) {
VLOG(1) << "The live experiment \"" << experiment << "\" is applied.";
metrics::RecordTFDataExperiment(experiment);
}
}
}
}
// The vector stores the graduated experiment names which will be turned on
// for all input pipelines.
// clang-format off
std::vector<string> graduated_experiments = {"disable_intra_op_parallelism"};
// clang-format on
// Add the graduated experiments to the optimization list and log them.
for (auto& experiment : graduated_experiments) {
if (std::find(optimizations.begin(), optimizations.end(), experiment) ==
optimizations.end()) {
optimizations.push_back(experiment);
}
VLOG(1) << "The graduated experiment \"" << experiment << "\" is applied.";
}
// If there are no optimizations to be applied, directly return the input.
if (optimizations.empty()) {
*output = input;
input->Ref();
return;
}
auto config_factory = [this, &optimizations]() {
return CreateConfig(optimizations, optimization_configs_);
};
Status s = RewriteDataset(ctx, input, std::move(config_factory),
/*record_fingerprint=*/true, output);
if (errors::IsDeadlineExceeded(s)) {
// Ignore DeadlineExceeded as it implies that the attempted rewrite took too
// long which should not prevent further computation.
LOG(WARNING) << s.ToString();
*output = input;
input->Ref();
return;
}
OP_REQUIRES_OK(ctx, s);
}
RewriterConfig OptimizeDatasetOp::CreateConfig(
std::vector<tstring> optimizations,
std::vector<string> optimizations_configs) {
RewriterConfig rewriter_config;
rewriter_config.add_optimizers(kOptimizerName);
rewriter_config.set_meta_optimizer_iterations(RewriterConfig::ONE);
rewriter_config.set_fail_on_optimizer_errors(true);
auto custom_optimizer = rewriter_config.add_custom_optimizers();
custom_optimizer->set_name(kOptimizerName);
auto* custom_optimizations_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizers].mutable_list();
for (const auto& opt : optimizations) {
custom_optimizations_list->add_s(opt.data(), opt.size());
}
auto* config_list =
(*custom_optimizer->mutable_parameter_map())[kOptimizerConfigs]
.mutable_list();
for (const auto& config : optimizations_configs) {
config_list->add_s(config.data(), config.size());
}
return rewriter_config;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#else // !IS_MOBILE_PLATFORM
namespace tensorflow {
namespace data {
OptimizeDatasetOp::OptimizeDatasetOp(OpKernelConstruction* ctx)
: UnaryDatasetOpKernel(ctx) {}
void OptimizeDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input,
DatasetBase** output) {
input->Ref();
*output = input;
}
namespace {
REGISTER_KERNEL_BUILDER(Name("OptimizeDataset").Device(DEVICE_CPU),
OptimizeDatasetOp);
REGISTER_KERNEL_BUILDER(Name("OptimizeDatasetV2").Device(DEVICE_CPU),
OptimizeDatasetOp);
} // namespace
} // namespace data
} // namespace tensorflow
#endif // !IS_MOBILE_PLATFORM
<|endoftext|> |
<commit_before><commit_msg>Fix compile warning<commit_after><|endoftext|> |
<commit_before><commit_msg>Use simpler double unlink algo<commit_after><|endoftext|> |
<commit_before>// RUN: %clangxx_asan -std=c++11 -pthread %s -o %t && %run %t 2>&1
// Regression test for the versioned pthread_create interceptor on linux/i386.
// pthread_attr_init is not intercepted and binds to the new abi
// pthread_create is intercepted; dlsym always returns the oldest version.
// This results in a crash inside pthread_create in libc.
#include <pthread.h>
#include <stdlib.h>
void *ThreadFunc(void *) { return nullptr; }
int main() {
pthread_t t;
const size_t sz = 1024 * 1024;
void *p = malloc(sz);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstack(&attr, p, sz);
pthread_create(&t, &attr, ThreadFunc, nullptr);
pthread_join(t, nullptr);
free(p);
return 0;
}
<commit_msg>[asan] Disable pthread_create_version test on mips.<commit_after>// RUN: %clangxx_asan -std=c++11 -pthread %s -o %t && %run %t 2>&1
// Regression test for the versioned pthread_create interceptor on linux/i386.
// pthread_attr_init is not intercepted and binds to the new abi
// pthread_create is intercepted; dlsym always returns the oldest version.
// This results in a crash inside pthread_create in libc.
// UNSUPPORTED: mips
#include <pthread.h>
#include <stdlib.h>
void *ThreadFunc(void *) { return nullptr; }
int main() {
pthread_t t;
const size_t sz = 1024 * 1024;
void *p = malloc(sz);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstack(&attr, p, sz);
pthread_create(&t, &attr, ThreadFunc, nullptr);
pthread_join(t, nullptr);
free(p);
return 0;
}
<|endoftext|> |
<commit_before>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;
// Roll the dice.
int diceRoll(int qty, int sides)
{
int subTotal = 0; // Dice addition subtotal.
// Roll the dice.
// Loop to roll the dice
for (int i = 0; i < qty; i++)
{
int currentRoll = rand() % sides + 1;
subTotal += currentRoll;
}
return subTotal;
}
// Race Choices
enum RACE { HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD };
// Class Choices
enum OCC { FIGHTER, CLERIC, THEIF, BARD, ROUGE, TINKER, MAGE };
// Stats Tree
struct ATTRIBUTES
{
unsigned int strength;
unsigned int faith;
unsigned int dexterity;
unsigned int insperation;
unsigned int cleverness;
unsigned int focus;
unsigned int hp, hpMax;
unsigned int mp, mpMax;
};
// Display the stats of the roll.
void displayStats(ATTRIBUTES atts)
{
cout << " +---------------------+ \n";
cout << " | Attributes: | \n";
cout << " +---------------------+ \n";
cout << "\n";
cout << " Strength: " << atts.strength << "\n";
cout << " Faith: " << atts.faith << "\n";
cout << " Dexterity: " << atts.dexterity << "\n";
cout << " Insperation: " << atts.insperation << "\n";
cout << " Cleverness: " << atts.cleverness << "\n";
cout << " Focus: " << atts.focus << "\n";
cout << "\n\n";
}
// Class for the character.
class character
{
protected:
ATTRIBUTES atts;
int copper;
OCC charClass;
RACE charRace;
public:
character()
{
copper = 50000;
}
};
// Class for the fighter.
class fighter : public character
{
public:
fighter()
{
cout << "Fighter Created.\n";
atts.hpMax = atts.hp = diceRoll(10, 6);
atts.mpMax = atts.mp = 20;
}
};
// Class for the Cleric.
class cleric : public character
{
public:
cleric()
{
cout << "Cleric Created.\n";
atts.hpMax = atts.hp = diceRoll(7, 6);
atts.mpMax = atts.mp = 50;
}
};
// Class for the Rouge.
class rouge : public character
{
public:
rouge()
{
cout << "Rouge Created.\n";
atts.hpMax = atts.hp = diceRoll(7, 6);
atts.mpMax = atts.mp = 20;
}
};
// Class for the Bard.
class bard : public character
{
public:
bard()
{
cout << "Bard Created.\n";
atts.hpMax = atts.hp = diceRoll(5, 6);
atts.mpMax = atts.mp = 50;
}
};
// Class for the Tinker.
class tinker : public character
{
public:
tinker()
{
cout << "Tinker Created.\n";
atts.hpMax = atts.hp = diceRoll(5, 6);
atts.mpMax = atts.mp = 20;
}
};
// Class for the Mage.
class mage : public character
{
public:
mage()
{
cout << "Mage Created.\n";
atts.hpMax = atts.hp = diceRoll(3, 6);
atts.mpMax = atts.mp = 50;
}
};
// Startup
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
RACE inputRace; // The race that is chosen.
char inputs; // The inputs.
ATTRIBUTES tempStats; // The stats the player gets by random.
bool reroll = true; // The bool for rerolling.
OCC inputClass; // The class that is chosen.
bool retry = true; // The fix for the race chooser.
character *player1;
// Clear the console.
system("cls");
cout << "Welcome to Zoro\n";
// Check for the reroll
while (reroll == true)
{
cout << "Please Select a Race:\n";
cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";
// Check for the retry
while (retry == true)
{
// The input for the chosen race.
cin >> inputs;
// Reset the retry var.
retry == false;
switch (inputs)
{
case 'h':
case 'H':
cout << "Human\n";
inputRace = HUMAN;
tempStats.strength = diceRoll(3, 6);
tempStats.faith = diceRoll(3, 6);
tempStats.dexterity = diceRoll(3, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(3, 6);
tempStats.focus = diceRoll(3, 6);
retry = false; // End the retry.
break;
case 'e':
case 'E':
cout << "Elf\n";
inputRace = ELF;
tempStats.strength = diceRoll(3, 6);
tempStats.faith = diceRoll(3, 6);
tempStats.dexterity = diceRoll(3, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(2, 6);
tempStats.focus = diceRoll(4, 6);
break;
case 'd':
case 'D':
cout << "Dark Elf\n";
inputRace = DARKELF;
tempStats.strength = diceRoll(3, 6);
tempStats.faith = diceRoll(3, 6);
tempStats.dexterity = diceRoll(4, 6);
tempStats.insperation = diceRoll(2, 6);
tempStats.cleverness = diceRoll(3, 6);
tempStats.focus = diceRoll(3, 6);
break;
case 'a':
case 'A':
cout << "Angel\n";
inputRace = ANGEL;
tempStats.strength = diceRoll(3, 6);
tempStats.faith = diceRoll(4, 6);
tempStats.dexterity = diceRoll(3, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(3, 6);
tempStats.focus = diceRoll(3, 6);
break;
case 'm':
case 'M':
cout << "Mongrel\n";
inputRace = MONGREL;
tempStats.strength = diceRoll(4, 6);
tempStats.faith = diceRoll(3, 6);
tempStats.dexterity = diceRoll(3, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(3, 6);
tempStats.focus = diceRoll(2, 6);
break;
case 's':
case 'S':
cout << "Shamani\n";
inputRace = SHAMANI;
tempStats.strength = diceRoll(2, 6);
tempStats.faith = diceRoll(4, 6);
tempStats.dexterity = diceRoll(3, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(3, 6);
tempStats.focus = diceRoll(3, 6);
break;
case 'n':
case 'N':
cout << "Nibelung\n";
inputRace = NIBELUNG;
tempStats.strength = diceRoll(3, 6);
tempStats.faith = diceRoll(3, 6);
tempStats.dexterity = diceRoll(2, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(4, 6);
tempStats.focus = diceRoll(3, 6);
break;
case 'u':
case 'U':
cout << "Undead\n";
inputRace = UNDEAD;
tempStats.strength = diceRoll(3, 6);
tempStats.faith = diceRoll(3, 6);
tempStats.dexterity = diceRoll(3, 6);
tempStats.insperation = diceRoll(3, 6);
tempStats.cleverness = diceRoll(2, 6);
tempStats.focus = diceRoll(3, 6);
break;
default:
cout << "Please input a vaild race.\n";
retry = true; // Set the retry to default
break;
}
}
// Display the stats
displayStats(tempStats);
cout << "Reroll? [Y]es [N]o\n";
// Input for the reroll.
cin >> inputs;
// End the reroll
reroll = false;
if (inputs == 'y' || inputs == 'Y')
{
// Reset the reroll to default.
reroll = true;
}
}
// Reset the reroll to default for the second reroll.
reroll = true;
while (reroll) // While reroll == true
{
// End the reroll for now
reroll = false;
cout << "Please select a class\n";
cout << "[F]ighter [C]leric [T]heif [B]ard [R]ouge [M]age\n";
// Check for inputs of which class.
cin >> inputs;
// Check for which class.
switch (inputs)
{
case 'f':
case 'F':
inputClass = FIGHTER;
cout << "Fighter\n";
player1 = new fighter;
break;
case 'c':
case 'C':
inputClass = CLERIC;
cout << "Cleric\n";
player1 = new fighter;
break;
case 't':
case 'T':
inputClass = THEIF;
cout << "Theif\n";
player1 = new rouge;
break;
case 'b':
case 'B':
inputClass = BARD;
cout << "Bard\n";
player1 = new bard;
break;
case 'r':
case 'R':
inputClass = ROUGE;
cout << "Rouge\n";
player1 = new rouge;
break;
case 'm':
case 'M':
inputClass = MAGE;
cout << "Mage\n";
player1 = new mage;
break;
default:
cout << "Please input a valid class.\n";
reroll = true;
break;
}
}
return 0;
}<commit_msg>Added some comments<commit_after>// ConsoleRPG.cpp : Defines the entry point for the console application.
// Created by Nick Mullally a.k.a. thakyZ / Nire Inicana
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include "time.h"
using namespace std;
// Roll the dice.
int diceRoll(int qty, int sides)
{
int subTotal = 0; // Dice addition subtotal.
// Roll the dice.
// Loop to roll the dice
for (int i = 0; i < qty; i++)
{
int currentRoll = rand() % sides + 1;
subTotal += currentRoll;
}
return subTotal;
}
// Race Choices
enum RACE { HUMAN, ELF, DARKELF, ANGEL, MONGREL, SHAMANI, NIBELUNG, UNDEAD };
// Class Choices
enum OCC { FIGHTER, CLERIC, THEIF, BARD, ROUGE, TINKER, MAGE };
// Stats Tree
struct ATTRIBUTES
{
unsigned int strength;
unsigned int faith;
unsigned int dexterity;
unsigned int insperation;
unsigned int cleverness;
unsigned int focus;
};
// Display the stats of the roll.
void displayStats(ATTRIBUTES atts, bool split)
{
cout << " +---------------------+ \n";
cout << " | Attributes: | \n";
cout << " +---------------------+ \n";
cout << "\n";
cout << " Strength: " << atts.strength << "\n";
cout << " Faith: " << atts.faith << "\n";
cout << " Dexterity: " << atts.dexterity << "\n";
cout << " Insperation: " << atts.insperation << "\n";
cout << " Cleverness: " << atts.cleverness << "\n";
cout << " Focus: " << atts.focus << "\n";
if (split == true)
{
cout << "\n\n";
}
}
// Class for the character.
class character
{
protected:
ATTRIBUTES atts;
int copper; // Money var.
OCC charClass;
RACE charRace;
unsigned int hp, hpMax;
unsigned int mp, mpMax;
public:
// Constructors
character()
{
copper = 50000;
}
// Accessors
void setAtts(ATTRIBUTES tmpAtts)
{
atts = tmpAtts;
}
ATTRIBUTES getAtts()
{
return atts;
}
void displayAllStats()
{
cout << " +---------------------+\n";
cout << " | " << charRace << " |\n";
cout << " | " << charClass << " |\n";
displayStats(atts, false);
cout << " Hitpoints: " << hp << "/" << hpMax << "\n";
cout << " Mana: " << mp << "/" << mpMax << "\n";
cout << "\n\n";
}
};
// Class for the fighter.
class fighter : public character
{
public:
fighter()
{
cout << "Fighter Created.\n";
hpMax = hp = diceRoll(10, 6);
mpMax = mp = 20;
}
};
// Class for the Cleric.
class cleric : public character
{
public:
cleric()
{
cout << "Cleric Created.\n";
hpMax = hp = diceRoll(7, 6);
mpMax = mp = 50;
}
};
// Class for the Rouge.
class rouge : public character
{
public:
rouge()
{
cout << "Rouge Created.\n";
hpMax = hp = diceRoll(7, 6);
mpMax = mp = 20;
}
};
// Class for the Bard.
class bard : public character
{
public:
bard()
{
cout << "Bard Created.\n";
hpMax = hp = diceRoll(5, 6);
mpMax = mp = 50;
}
};
// Class for the Tinker.
class tinker : public character
{
public:
tinker()
{
cout << "Tinker Created.\n";
hpMax = hp = diceRoll(5, 6);
mpMax = mp = 20;
}
};
// Class for the Mage.
class mage : public character
{
public:
mage()
{
cout << "Mage Created.\n";
hpMax = hp = diceRoll(3, 6);
mpMax = mp = 50;
}
};
// Startup
int _tmain(int argc, _TCHAR* argv[])
{
srand(time(NULL));
RACE inputRace; // The race that is chosen.
char inputs; // The inputs.
ATTRIBUTES tmpStats; // The stats the player gets by random.
bool reroll = true; // The bool for rerolling.
OCC inputClass; // The class that is chosen.
bool retry = true; // The fix for the race chooser.
// Set the character to pointer var.
character *player1;
// Clear the console.
system("cls");
cout << "Welcome to Zoro\n";
// Check for the reroll
while (reroll == true)
{
// End the reroll;
reroll = false;
cout << "Please Select a Race:\n";
cout << "[H]uman [E]lf [D]ark elf [A]ngel [M]ongrel [S]hamani [N]ibelung [U]ndead\n";
// Check for the retry
while (retry == true)
{
// The input for the chosen race.
cin >> inputs;
// End the retry.
retry = false;
switch (inputs)
{
case 'h':
case 'H':
cout << "\nHuman!\n";
inputRace = HUMAN;
tmpStats.strength = diceRoll(3, 6);
tmpStats.faith = diceRoll(3, 6);
tmpStats.dexterity = diceRoll(3, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(3, 6);
tmpStats.focus = diceRoll(3, 6);
retry = false; // End the retry.
break;
case 'e':
case 'E':
cout << "\nElf!\n";
inputRace = ELF;
tmpStats.strength = diceRoll(3, 6);
tmpStats.faith = diceRoll(3, 6);
tmpStats.dexterity = diceRoll(3, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(2, 6);
tmpStats.focus = diceRoll(4, 6);
break;
case 'd':
case 'D':
cout << "\nDark Elf!\n";
inputRace = DARKELF;
tmpStats.strength = diceRoll(3, 6);
tmpStats.faith = diceRoll(3, 6);
tmpStats.dexterity = diceRoll(4, 6);
tmpStats.insperation = diceRoll(2, 6);
tmpStats.cleverness = diceRoll(3, 6);
tmpStats.focus = diceRoll(3, 6);
break;
case 'a':
case 'A':
cout << "Angel!\n";
inputRace = ANGEL;
tmpStats.strength = diceRoll(3, 6);
tmpStats.faith = diceRoll(4, 6);
tmpStats.dexterity = diceRoll(3, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(3, 6);
tmpStats.focus = diceRoll(3, 6);
break;
case 'm':
case 'M':
cout << "\nMongrel!\n";
inputRace = MONGREL;
tmpStats.strength = diceRoll(4, 6);
tmpStats.faith = diceRoll(3, 6);
tmpStats.dexterity = diceRoll(3, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(3, 6);
tmpStats.focus = diceRoll(2, 6);
break;
case 's':
case 'S':
cout << "\nShamani!\n";
inputRace = SHAMANI;
tmpStats.strength = diceRoll(2, 6);
tmpStats.faith = diceRoll(4, 6);
tmpStats.dexterity = diceRoll(3, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(3, 6);
tmpStats.focus = diceRoll(3, 6);
break;
case 'n':
case 'N':
cout << "\nNibelung!\n";
inputRace = NIBELUNG;
tmpStats.strength = diceRoll(3, 6);
tmpStats.faith = diceRoll(3, 6);
tmpStats.dexterity = diceRoll(2, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(4, 6);
tmpStats.focus = diceRoll(3, 6);
break;
case 'u':
case 'U':
cout << "\nUndead!\n";
inputRace = UNDEAD;
tmpStats.strength = diceRoll(3, 6);
tmpStats.faith = diceRoll(3, 6);
tmpStats.dexterity = diceRoll(3, 6);
tmpStats.insperation = diceRoll(3, 6);
tmpStats.cleverness = diceRoll(2, 6);
tmpStats.focus = diceRoll(3, 6);
break;
default:
cout << "\nPlease input a vaild race.\n";
retry = true; // Set the retry to default
break;
}
}
cout << "\n";
// Display the stats
displayStats(tmpStats, true);
cout << "Reroll? [Y]es [N]o\n\n";
// Input for the reroll.
cin >> inputs;
// End the reroll
reroll = false;
if (inputs == 'y' || inputs == 'Y')
{
cout << inputs;
// Reset the reroll to default.
reroll = true;
}
}
// Reset the reroll to default for the second reroll.
reroll = true;
while (reroll) // While reroll == true
{
// End the reroll for now
reroll = false;
cout << "Please select a class\n";
cout << "[F]ighter [C]leric [T]heif [B]ard [R]ouge [M]age\n";
// Check for inputs of which class.
cin >> inputs;
// Check for which class.
switch (inputs)
{
case 'f':
case 'F':
inputClass = FIGHTER;
cout << "Fighter!\n";
player1 = new fighter;
break;
case 'c':
case 'C':
inputClass = CLERIC;
cout << "Cleric!\n";
player1 = new fighter;
break;
case 't':
case 'T':
inputClass = THEIF;
cout << "Theif!\n";
player1 = new rouge;
break;
case 'b':
case 'B':
inputClass = BARD;
cout << "Bard!\n";
player1 = new bard;
break;
case 'r':
case 'R':
inputClass = ROUGE;
cout << "Rouge!\n";
player1 = new rouge;
break;
case 'm':
case 'M':
inputClass = MAGE;
cout << "Mage!\n";
player1 = new mage;
break;
default:
cout << "Please input a valid class.\n";
reroll = true;
break;
}
}
// Set the attributes as they are at this point.
player1->setAtts(tmpStats);
// Display the displayAllStats function.
player1->displayAllStats();
return 0;
}<|endoftext|> |
<commit_before>#ifndef TCL_EXECUTE_HPP
#define TCL_EXECUTE_HPP
#include <typeinfo>
#include "CLInformation.hpp"
#include "CLSourceArray.hpp"
#include "CLExecuteProperty.hpp"
#include "CLDeviceInformation.hpp"
#include "CLWorkGroupSettings.hpp"
#include "CLBuffer.hpp"
namespace tcl
{
class CLExecute
{
private:
CLExecuteProperty executeProperty;
cl_event event;
unsigned argCount;
private:
void TestKernelArg(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_KERNEL:
throw CLException("ȃJ[lw肳Ă܂");
case CL_INVALID_ARG_INDEX:
throw CLException("̃CfbNXsł");
case CL_INVALID_ARG_VALUE:
throw CLException("̒lsł");
case CL_INVALID_MEM_OBJECT:
throw CLException("IuWFNgsł");
case CL_INVALID_SAMPLER:
throw CLException("Tv[IuWFNgsł");
case CL_INVALID_ARG_SIZE:
throw CLException("Ŏw肵TCYsł");
case CL_OUT_OF_RESOURCES:
throw CLException("foCX̃\[Xmۂł܂ł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃\[Xmۂł܂ł");
}
}
}
void TestEnqueueTask(const cl_int& result) const
{
if (result != CL_SUCCESS)
throw CLException("G[Nă^XNsł܂ł", result);
}
void TestNDRange(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_PROGRAM_EXECUTABLE:
throw CLException("R}hL[Ɋ֘AtꂽɃrhꂽvO݂܂");
case CL_INVALID_COMMAND_QUEUE:
throw CLException("R}hL[ł");
case CL_INVALID_KERNEL:
throw CLException("J[lł");
case CL_INVALID_CONTEXT:
throw CLException("ReLXgł");
case CL_INVALID_KERNEL_ARGS:
throw CLException("J[lw肳Ă܂");
case CL_INVALID_WORK_DIMENSION:
throw CLException("J[l̕Kł͂܂");
case CL_INVALID_GLOBAL_OFFSET:
throw CLException("ItZbg̒l[NTCYĂ܂");
case CL_INVALID_WORK_GROUP_SIZE:
throw CLException("[NO[v̑傫sł");
case CL_INVALID_WORK_ITEM_SIZE:
throw CLException("[NACesł");
case CL_MISALIGNED_SUB_BUFFER_OFFSET:
throw CLException("Tuobt@ItZbg̃ACgsł");
case CL_INVALID_IMAGE_SIZE:
throw CLException("J[lɎw肵C[WIuWFNgfoCXŃT|[gĂ܂");
case CL_OUT_OF_RESOURCES:
throw CLException("J[l̎sɕKvȃ\[XsĂ܂");
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
throw CLException("IuWFNg̗̈mۂ̂Ɏs܂");
case CL_INVALID_EVENT_WAIT_LIST:
throw CLException("Cxg҂Xgsł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃̃\[XmۂɎs܂");
}
}
}
public:
inline cl_command_queue& CommandQueue() {
return executeProperty.commandQueue;
}
inline cl_program& Program() {
return executeProperty.program;
}
inline cl_kernel& Kernel() {
return executeProperty.kernel;
}
public:
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] useDeviceIdpfoCXID
*/
CLExecute(CLSource& source, const cl_device_id& useDeviceId)
: executeProperty(source, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] useDeviceId pfoCXID
*/
CLExecute(CLSourceArray& sourceArray, const cl_device_id& useDeviceId)
: executeProperty(sourceArray, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSource& source, const CLDeviceInformation& device)
: executeProperty(source, device.DeviceId()), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSourceArray& sourceArray, const CLDeviceInformation& device)
: executeProperty(sourceArray, device.DeviceId()), argCount(0)
{
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
*/
template <typename T>
CLExecute& SetArg(T& buffer)
{
#define TEST_BUFFER(X) typeid(buffer)==typeid(X)
// CLBufferpĂ邩ǂ
// @ΒNācc
if (
TEST_BUFFER(CLReadWriteBuffer) ||
TEST_BUFFER(CLReadBuffer) ||
TEST_BUFFER(CLWriteBuffer) ||
TEST_BUFFER(CLBuffer) ||
TEST_BUFFER(CLHostCopyBuffer) ||
TEST_BUFFER(CLAllocHostBuffer) ||
TEST_BUFFER(CLUseHostBuffer))
#undef TEST_BUFFER
{
SetBuffer(buffer);
}
else
{
cl_int resultArg;
resultArg = clSetKernelArg(Kernel(), argCount++, sizeof(T), &buffer);
TestKernelArg(resultArg);
}
return *this;
}
/**
* J[lɓn߂̈ւorݒ肷
* \param argIndex ̃CfbNX
* \param buffer J[lŗpobt@
*/
template <typename T>
CLExecute& SetArg(const cl_uint argIndex, T& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(T), &buffer);
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
* \param[in] otherBuffers ϒ
*/
template <typename T, typename... Args>
CLExecute& SetArg(T& buffer, Args&... otherBuffers)
{
if (typeid(buffer) == typeid(CLReadWriteBuffer))
SetBuffer(buffer);
else
SetArg(buffer);
argCount++;
SetArg(otherBuffers...);
argCount = 0;
return *this;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
*/
CLExecute& SetBuffer(CLBuffer& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argCount++, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̃obt@ԍw肵Đݒ肷
* \param[in] argIndex ԍ
* \param[in] buffer CLBuffer̃CX^X
*/
CLExecute& SetBuffer(const cl_uint argIndex, CLBuffer& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
* \param[in] otherBuffers CCLBuffer̃CX^X
*/
template <typename... Args>
CLExecute& SetBuffer(CLBuffer& buffer, Args&... otherBuffers)
{
SetBuffer(buffer);
argCount++;
SetBuffer(otherBuffers...);
argCount = 0;
return *this;
}
/**
* P̃J[ls
* \param[in] wait sI܂ő҂ǂ
*/
CLExecute& Run()
{
auto resultTask = clEnqueueTask(CommandQueue(), Kernel(), 0, NULL, &event);
TestEnqueueTask(resultTask);
return *this;
}
/**
* ͈͎w肵ăJ[ls
* \param[in] setting s͈͂w肷NX̃CX^X
* \param[in] wait sI܂ő҂ǂ
*/
CLExecute& Run(CLWorkGroupSettings& setting)
{
auto result = clEnqueueNDRangeKernel(
CommandQueue(), Kernel(), setting.Dimension(),
setting.Offset(), setting.WorkerRange(), setting.SplitSize(),
0, NULL, &event);
TestNDRange(result);
return *this;
}
CLExecute& Wait()
{
clWaitForEvents(1, &event);
return *this;
}
};
}
#endif<commit_msg>本来存在しないテストを削除<commit_after>#ifndef TCL_EXECUTE_HPP
#define TCL_EXECUTE_HPP
#include <typeinfo>
#include "CLInformation.hpp"
#include "CLSourceArray.hpp"
#include "CLExecuteProperty.hpp"
#include "CLDeviceInformation.hpp"
#include "CLWorkGroupSettings.hpp"
#include "CLBuffer.hpp"
namespace tcl
{
class CLExecute
{
private:
CLExecuteProperty executeProperty;
cl_event event;
unsigned argCount;
private:
void TestKernelArg(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_KERNEL:
throw CLException("ȃJ[lw肳Ă܂");
case CL_INVALID_ARG_INDEX:
throw CLException("̃CfbNXsł");
case CL_INVALID_ARG_VALUE:
throw CLException("̒lsł");
case CL_INVALID_MEM_OBJECT:
throw CLException("IuWFNgsł");
case CL_INVALID_SAMPLER:
throw CLException("Tv[IuWFNgsł");
case CL_INVALID_ARG_SIZE:
throw CLException("Ŏw肵TCYsł");
case CL_OUT_OF_RESOURCES:
throw CLException("foCX̃\[Xmۂł܂ł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃\[Xmۂł܂ł");
}
}
}
void TestEnqueueTask(const cl_int& result) const
{
if (result != CL_SUCCESS)
throw CLException("G[Nă^XNsł܂ł", result);
}
void TestNDRange(const cl_int& result) const
{
if (result != CL_SUCCESS)
{
switch (result)
{
case CL_INVALID_PROGRAM_EXECUTABLE:
throw CLException("R}hL[Ɋ֘AtꂽɃrhꂽvO݂܂");
case CL_INVALID_COMMAND_QUEUE:
throw CLException("R}hL[ł");
case CL_INVALID_KERNEL:
throw CLException("J[lł");
case CL_INVALID_CONTEXT:
throw CLException("ReLXgł");
case CL_INVALID_KERNEL_ARGS:
throw CLException("J[lw肳Ă܂");
case CL_INVALID_WORK_DIMENSION:
throw CLException("J[l̕Kł͂܂");
case CL_INVALID_GLOBAL_OFFSET:
throw CLException("ItZbg̒l[NTCYĂ܂");
case CL_INVALID_WORK_GROUP_SIZE:
throw CLException("[NO[v̑傫sł");
case CL_INVALID_WORK_ITEM_SIZE:
throw CLException("[NACesł");
case CL_MISALIGNED_SUB_BUFFER_OFFSET:
throw CLException("Tuobt@ItZbg̃ACgsł");
case CL_INVALID_IMAGE_SIZE:
throw CLException("J[lɎw肵C[WIuWFNgfoCXŃT|[gĂ܂");
case CL_OUT_OF_RESOURCES:
throw CLException("J[l̎sɕKvȃ\[XsĂ܂");
case CL_MEM_OBJECT_ALLOCATION_FAILURE:
throw CLException("IuWFNg̗̈mۂ̂Ɏs܂");
case CL_INVALID_EVENT_WAIT_LIST:
throw CLException("Cxg҂Xgsł");
case CL_OUT_OF_HOST_MEMORY:
throw CLException("zXg̃̃\[XmۂɎs܂");
}
}
}
public:
inline cl_command_queue& CommandQueue() {
return executeProperty.commandQueue;
}
inline cl_program& Program() {
return executeProperty.program;
}
inline cl_kernel& Kernel() {
return executeProperty.kernel;
}
public:
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] useDeviceIdpfoCXID
*/
CLExecute(CLSource& source, const cl_device_id& useDeviceId)
: executeProperty(source, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] useDeviceId pfoCXID
*/
CLExecute(CLSourceArray& sourceArray, const cl_device_id& useDeviceId)
: executeProperty(sourceArray, useDeviceId), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] source \[XR[h
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSource& source, const CLDeviceInformation& device)
: executeProperty(source, device.DeviceId()), argCount(0)
{
}
/**
* J[l̎sobt@̓]Ǘ
* \param[in] info OpenCL̏NX
* \param[in] sourceArray \[XR[h̔zNX
* \param[in] device foCX̃CX^X
*/
CLExecute(CLSourceArray& sourceArray, const CLDeviceInformation& device)
: executeProperty(sourceArray, device.DeviceId()), argCount(0)
{
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
*/
template <typename T>
CLExecute& SetArg(T& buffer)
{
#define TEST_BUFFER(X) typeid(buffer)==typeid(X)
// CLBufferpĂ邩ǂ
// @ΒNācc
if (
TEST_BUFFER(CLReadWriteBuffer) ||
TEST_BUFFER(CLReadBuffer) ||
TEST_BUFFER(CLWriteBuffer) ||
TEST_BUFFER(CLBuffer))
#undef TEST_BUFFER
{
SetBuffer(buffer);
}
else
{
cl_int resultArg;
resultArg = clSetKernelArg(Kernel(), argCount++, sizeof(T), &buffer);
TestKernelArg(resultArg);
}
return *this;
}
/**
* J[lɓn߂̈ւorݒ肷
* \param argIndex ̃CfbNX
* \param buffer J[lŗpobt@
*/
template <typename T>
CLExecute& SetArg(const cl_uint argIndex, T& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(T), &buffer);
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̈ݒ肷
* \param[in] buffer J[lŗp邽߂̃obt@
* \param[in] otherBuffers ϒ
*/
template <typename T, typename... Args>
CLExecute& SetArg(T& buffer, Args&... otherBuffers)
{
if (typeid(buffer) == typeid(CLReadWriteBuffer))
SetBuffer(buffer);
else
SetArg(buffer);
argCount++;
SetArg(otherBuffers...);
argCount = 0;
return *this;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
*/
CLExecute& SetBuffer(CLBuffer& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argCount++, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̃obt@ԍw肵Đݒ肷
* \param[in] argIndex ԍ
* \param[in] buffer CLBuffer̃CX^X
*/
CLExecute& SetBuffer(const cl_uint argIndex, CLBuffer& buffer)
{
const auto resultArg = clSetKernelArg(Kernel(), argIndex, sizeof(cl_mem), &buffer.Memory());
TestKernelArg(resultArg);
return *this;
}
/**
* J[lɓn߂̃obt@ݒ肷
* \param[in] buffer CLBuffer̃CX^X
* \param[in] otherBuffers CCLBuffer̃CX^X
*/
template <typename... Args>
CLExecute& SetBuffer(CLBuffer& buffer, Args&... otherBuffers)
{
SetBuffer(buffer);
argCount++;
SetBuffer(otherBuffers...);
argCount = 0;
return *this;
}
/**
* P̃J[ls
* \param[in] wait sI܂ő҂ǂ
*/
CLExecute& Run()
{
auto resultTask = clEnqueueTask(CommandQueue(), Kernel(), 0, NULL, &event);
TestEnqueueTask(resultTask);
return *this;
}
/**
* ͈͎w肵ăJ[ls
* \param[in] setting s͈͂w肷NX̃CX^X
* \param[in] wait sI܂ő҂ǂ
*/
CLExecute& Run(CLWorkGroupSettings& setting)
{
auto result = clEnqueueNDRangeKernel(
CommandQueue(), Kernel(), setting.Dimension(),
setting.Offset(), setting.WorkerRange(), setting.SplitSize(),
0, NULL, &event);
TestNDRange(result);
return *this;
}
CLExecute& Wait()
{
clWaitForEvents(1, &event);
return *this;
}
};
}
#endif<|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.
#include "ppapi/proxy/serialized_var.h"
#include "base/logging.h"
#include "ipc/ipc_message_utils.h"
#include "ppapi/proxy/dispatcher.h"
#include "ppapi/proxy/ppapi_param_traits.h"
#include "ppapi/proxy/var_serialization_rules.h"
namespace pp {
namespace proxy {
// SerializedVar::Inner --------------------------------------------------------
SerializedVar::Inner::Inner()
: serialization_rules_(NULL),
var_(PP_MakeUndefined()),
cleanup_mode_(CLEANUP_NONE) {
#ifndef NDEBUG
has_been_serialized_ = false;
has_been_deserialized_ = false;
#endif
}
SerializedVar::Inner::Inner(VarSerializationRules* serialization_rules)
: serialization_rules_(serialization_rules),
var_(PP_MakeUndefined()),
cleanup_mode_(CLEANUP_NONE) {
#ifndef NDEBUG
has_been_serialized_ = false;
has_been_deserialized_ = false;
#endif
}
SerializedVar::Inner::Inner(VarSerializationRules* serialization_rules,
const PP_Var& var)
: serialization_rules_(serialization_rules),
var_(var),
cleanup_mode_(CLEANUP_NONE) {
#ifndef NDEBUG
has_been_serialized_ = false;
has_been_deserialized_ = false;
#endif
}
SerializedVar::Inner::~Inner() {
switch (cleanup_mode_) {
case END_SEND_PASS_REF:
serialization_rules_->EndSendPassRef(var_);
break;
case END_RECEIVE_CALLER_OWNED:
serialization_rules_->EndReceiveCallerOwned(var_);
break;
default:
break;
}
}
PP_Var SerializedVar::Inner::GetVar() const {
DCHECK(serialization_rules_);
// If we're a string var, we should have already converted the string value
// to a var ID.
DCHECK(var_.type != PP_VARTYPE_STRING || var_.value.as_id != 0);
return var_;
}
PP_Var SerializedVar::Inner::GetIncompleteVar() const {
DCHECK(serialization_rules_);
return var_;
}
void SerializedVar::Inner::SetVar(PP_Var var) {
// Sanity check, when updating the var we should have received a
// serialization rules pointer already.
DCHECK(serialization_rules_);
var_ = var;
}
const std::string& SerializedVar::Inner::GetString() const {
DCHECK(serialization_rules_);
return string_value_;
}
std::string* SerializedVar::Inner::GetStringPtr() {
DCHECK(serialization_rules_);
return &string_value_;
}
void SerializedVar::Inner::WriteToMessage(IPC::Message* m) const {
// When writing to the IPC messages, a serization rules handler should
// always have been set.
//
// When sending a message, it should be difficult to trigger this if you're
// using the SerializedVarSendInput class and giving a non-NULL dispatcher.
// Make sure you're using the proper "Send" helper class.
//
// It should be more common to see this when handling an incoming message
// that returns a var. This means the message handler didn't write to the
// output parameter, or possibly you used the wrong helper class
// (normally SerializedVarReturnValue).
DCHECK(serialization_rules_);
#ifndef NDEBUG
// We should only be serializing something once.
DCHECK(!has_been_serialized_);
has_been_serialized_ = true;
#endif
// If the var is not a string type, we should not have ended up with any
// string data.
DCHECK(var_.type == PP_VARTYPE_STRING || string_value_.empty());
m->WriteInt(static_cast<int>(var_.type));
switch (var_.type) {
case PP_VARTYPE_UNDEFINED:
case PP_VARTYPE_NULL:
// These don't need any data associated with them other than the type we
// just serialized.
break;
case PP_VARTYPE_BOOL:
m->WriteBool(var_.value.as_bool);
break;
case PP_VARTYPE_INT32:
m->WriteInt(var_.value.as_int);
break;
case PP_VARTYPE_DOUBLE:
IPC::ParamTraits<double>::Write(m, var_.value.as_double);
break;
case PP_VARTYPE_STRING:
// TODO(brettw) in the case of an invalid string ID, it would be nice
// to send something to the other side such that a 0 ID would be
// generated there. Then the function implementing the interface can
// handle the invalid string as if it was in process rather than seeing
// what looks like a valid empty string.
m->WriteString(string_value_);
break;
case PP_VARTYPE_OBJECT:
m->WriteInt64(var_.value.as_id);
break;
}
}
bool SerializedVar::Inner::ReadFromMessage(const IPC::Message* m, void** iter) {
#ifndef NDEBUG
// We should only deserialize something once or will end up with leaked
// references.
//
// One place this has happened in the past is using
// std::vector<SerializedVar>.resize(). If you're doing this manually instead
// of using the helper classes for handling in/out vectors of vars, be
// sure you use the same pattern as the SerializedVarVector classes.
DCHECK(!has_been_deserialized_);
has_been_deserialized_ = true;
#endif
// When reading, the dispatcher should be set when we get a Deserialize
// call (which will supply a dispatcher).
int type;
if (!m->ReadInt(iter, &type))
return false;
bool success = false;
switch (type) {
case PP_VARTYPE_UNDEFINED:
case PP_VARTYPE_NULL:
// These don't have any data associated with them other than the type we
// just serialized.
success = true;
break;
case PP_VARTYPE_BOOL:
success = m->ReadBool(iter, &var_.value.as_bool);
break;
case PP_VARTYPE_INT32:
success = m->ReadInt(iter, &var_.value.as_int);
break;
case PP_VARTYPE_DOUBLE:
success = IPC::ParamTraits<double>::Read(m, iter, &var_.value.as_double);
break;
case PP_VARTYPE_STRING:
success = m->ReadString(iter, &string_value_);
var_.value.as_id = 0;
break;
case PP_VARTYPE_OBJECT:
success = m->ReadInt64(iter, &var_.value.as_id);
break;
default:
// Leave success as false.
break;
}
// All success cases get here. We avoid writing the type above so that the
// output param is untouched (defaults to VARTYPE_UNDEFINED) even in the
// failure case.
if (success)
var_.type = static_cast<PP_VarType>(type);
return success;
}
// SerializedVar ---------------------------------------------------------------
SerializedVar::SerializedVar() : inner_(new Inner) {
}
SerializedVar::SerializedVar(VarSerializationRules* serialization_rules)
: inner_(new Inner(serialization_rules)) {
}
SerializedVar::SerializedVar(VarSerializationRules* serialization_rules,
const PP_Var& var)
: inner_(new Inner(serialization_rules, var)) {
}
SerializedVar::~SerializedVar() {
}
// SerializedVarSendInput ------------------------------------------------------
SerializedVarSendInput::SerializedVarSendInput(Dispatcher* dispatcher,
const PP_Var& var)
: SerializedVar(dispatcher->serialization_rules(), var) {
dispatcher->serialization_rules()->SendCallerOwned(var, GetStringPtr());
}
// static
void SerializedVarSendInput::ConvertVector(Dispatcher* dispatcher,
const PP_Var* input,
size_t input_count,
std::vector<SerializedVar>* output) {
output->resize(input_count);
for (size_t i = 0; i < input_count; i++) {
(*output)[i] = SerializedVar(dispatcher->serialization_rules(), input[i]);
dispatcher->serialization_rules()->SendCallerOwned(input[i],
(*output)[i].GetStringPtr());
}
}
// ReceiveSerializedVarReturnValue ---------------------------------------------
ReceiveSerializedVarReturnValue::ReceiveSerializedVarReturnValue() {
}
PP_Var ReceiveSerializedVarReturnValue::Return(Dispatcher* dispatcher) {
set_serialization_rules(dispatcher->serialization_rules());
SetVar(serialization_rules()->ReceivePassRef(GetIncompleteVar(),
GetString()));
return GetVar();
}
// ReceiveSerializedException --------------------------------------------------
ReceiveSerializedException::ReceiveSerializedException(Dispatcher* dispatcher,
PP_Var* exception)
: SerializedVar(dispatcher->serialization_rules()),
exception_(exception) {
}
ReceiveSerializedException::~ReceiveSerializedException() {
if (exception_) {
// When an output exception is specified, it will take ownership of the
// reference.
SetVar(serialization_rules()->ReceivePassRef(GetIncompleteVar(),
GetString()));
*exception_ = GetVar();
} else {
// When no output exception is specified, the browser thinks we have a ref
// to an object that we don't want (this will happen only in the plugin
// since the browser will always specify an out exception for the plugin to
// write into).
//
// Strings don't need this handling since we can just avoid creating a
// Var from the std::string in the first place.
if (GetVar().type == PP_VARTYPE_OBJECT)
serialization_rules()->ReleaseObjectRef(GetVar());
}
}
bool ReceiveSerializedException::IsThrown() const {
return exception_ && exception_->type != PP_VARTYPE_UNDEFINED;
}
// ReceiveSerializedVarVectorOutParam ------------------------------------------
ReceiveSerializedVarVectorOutParam::ReceiveSerializedVarVectorOutParam(
Dispatcher* dispatcher,
uint32_t* output_count,
PP_Var** output)
: dispatcher_(dispatcher),
output_count_(output_count),
output_(output) {
}
ReceiveSerializedVarVectorOutParam::~ReceiveSerializedVarVectorOutParam() {
*output_count_ = static_cast<uint32_t>(vector_.size());
if (!vector_.size()) {
*output_ = NULL;
return;
}
*output_ = static_cast<PP_Var*>(malloc(vector_.size() * sizeof(PP_Var)));
for (size_t i = 0; i < vector_.size(); i++) {
// Here we just mimic what happens when returning a value.
ReceiveSerializedVarReturnValue converted;
SerializedVar* serialized = &converted;
*serialized = vector_[i];
(*output_)[i] = converted.Return(dispatcher_);
}
}
std::vector<SerializedVar>* ReceiveSerializedVarVectorOutParam::OutParam() {
return &vector_;
}
// SerializedVarReceiveInput ---------------------------------------------------
SerializedVarReceiveInput::SerializedVarReceiveInput(
const SerializedVar& serialized)
: serialized_(serialized),
dispatcher_(NULL),
var_(PP_MakeUndefined()) {
}
SerializedVarReceiveInput::~SerializedVarReceiveInput() {
}
PP_Var SerializedVarReceiveInput::Get(Dispatcher* dispatcher) {
serialized_.set_serialization_rules(dispatcher->serialization_rules());
// Ensure that when the serialized var goes out of scope it cleans up the
// stuff we're making in BeginReceiveCallerOwned.
serialized_.set_cleanup_mode(SerializedVar::END_RECEIVE_CALLER_OWNED);
serialized_.SetVar(
serialized_.serialization_rules()->BeginReceiveCallerOwned(
serialized_.GetIncompleteVar(), serialized_.GetStringPtr()));
return serialized_.GetVar();
}
// SerializedVarVectorReceiveInput ---------------------------------------------
SerializedVarVectorReceiveInput::SerializedVarVectorReceiveInput(
const std::vector<SerializedVar>& serialized)
: serialized_(serialized) {
}
SerializedVarVectorReceiveInput::~SerializedVarVectorReceiveInput() {
for (size_t i = 0; i < deserialized_.size(); i++) {
serialized_[i].serialization_rules()->EndReceiveCallerOwned(
deserialized_[i]);
}
}
PP_Var* SerializedVarVectorReceiveInput::Get(Dispatcher* dispatcher,
uint32_t* array_size) {
deserialized_.resize(serialized_.size());
for (size_t i = 0; i < serialized_.size(); i++) {
// The vector must be able to clean themselves up after this call is
// torn down.
serialized_[i].set_serialization_rules(dispatcher->serialization_rules());
serialized_[i].SetVar(
serialized_[i].serialization_rules()->BeginReceiveCallerOwned(
serialized_[i].GetIncompleteVar(), serialized_[i].GetStringPtr()));
deserialized_[i] = serialized_[i].GetVar();
}
*array_size = static_cast<uint32_t>(serialized_.size());
return deserialized_.size() > 0 ? &deserialized_[0] : NULL;
}
// SerializedVarReturnValue ----------------------------------------------------
SerializedVarReturnValue::SerializedVarReturnValue(SerializedVar* serialized)
: serialized_(serialized) {
}
void SerializedVarReturnValue::Return(Dispatcher* dispatcher,
const PP_Var& var) {
serialized_->set_serialization_rules(dispatcher->serialization_rules());
serialized_->SetVar(var);
// Var must clean up after our BeginSendPassRef call.
serialized_->set_cleanup_mode(SerializedVar::END_SEND_PASS_REF);
dispatcher->serialization_rules()->BeginSendPassRef(
serialized_->GetIncompleteVar(), serialized_->GetStringPtr());
}
// SerializedVarOutParam -------------------------------------------------------
SerializedVarOutParam::SerializedVarOutParam(SerializedVar* serialized)
: serialized_(serialized),
writable_var_(PP_MakeUndefined()) {
}
SerializedVarOutParam::~SerializedVarOutParam() {
if (serialized_->serialization_rules()) {
// When unset, OutParam wasn't called. We'll just leave the var untouched
// in that case.
serialized_->SetVar(writable_var_);
serialized_->serialization_rules()->BeginSendPassRef(
writable_var_, serialized_->GetStringPtr());
// Normally the current object will be created on the stack to wrap a
// SerializedVar and won't have a scope around the actual IPC send. So we
// need to tell the SerializedVar to do the begin/end send pass ref calls.
serialized_->set_cleanup_mode(SerializedVar::END_SEND_PASS_REF);
}
}
PP_Var* SerializedVarOutParam::OutParam(Dispatcher* dispatcher) {
serialized_->set_serialization_rules(dispatcher->serialization_rules());
return &writable_var_;
}
// SerializedVarVectorOutParam -------------------------------------------------
SerializedVarVectorOutParam::SerializedVarVectorOutParam(
std::vector<SerializedVar>* serialized)
: dispatcher_(NULL),
serialized_(serialized),
count_(0),
array_(NULL) {
}
SerializedVarVectorOutParam::~SerializedVarVectorOutParam() {
DCHECK(dispatcher_);
// Convert the array written by the pepper code to the serialized structure.
// Note we can't use resize here, we have to allocate a new SerializedVar
// for each serialized item. See ParamTraits<vector<SerializedVar>>::Read.
serialized_->reserve(count_);
for (uint32_t i = 0; i < count_; i++) {
// Just mimic what we do for regular OutParams.
SerializedVar var;
SerializedVarOutParam out(&var);
*out.OutParam(dispatcher_) = array_[i];
serialized_->push_back(var);
}
// When returning arrays, the pepper code expects the caller to take
// ownership of the array.
free(array_);
}
PP_Var** SerializedVarVectorOutParam::ArrayOutParam(Dispatcher* dispatcher) {
DCHECK(!dispatcher_); // Should only be called once.
dispatcher_ = dispatcher;
return &array_;
}
} // namespace proxy
} // namespace pp
<commit_msg>Remove serialized var file from previous check that shouldn't have been there.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2009 - Mozy, Inc.
#include "mordor/pch.h"
#include "log.h"
#include <iostream>
#include <boost/bind.hpp>
#include <boost/regex.hpp>
#include "assert.h"
#include "config.h"
#include "fiber.h"
#include "mordor/streams/file.h"
#include "mordor/string.h"
#include "timer.h"
namespace Mordor {
static void enableLoggers();
static void enableStdoutLogging();
static void enableFileLogging();
#ifdef WINDOWS
static void enableDebugLogging();
#endif
static ConfigVar<std::string>::ptr g_logError =
Config::lookup("log.errormask", std::string(".*"), "Regex of loggers to enable error for.");
static ConfigVar<std::string>::ptr g_logWarn =
Config::lookup("log.warnmask", std::string(".*"), "Regex of loggers to enable warning for.");
static ConfigVar<std::string>::ptr g_logInfo =
Config::lookup("log.infomask", std::string(".*"), "Regex of loggers to enable info for.");
static ConfigVar<std::string>::ptr g_logVerbose =
Config::lookup("log.verbosemask", std::string(""), "Regex of loggers to enable verbose for.");
static ConfigVar<std::string>::ptr g_logDebug =
Config::lookup("log.debugmask", std::string(""), "Regex of loggers to enable debugging for.");
static ConfigVar<std::string>::ptr g_logTrace =
Config::lookup("log.tracemask", std::string(""), "Regex of loggers to enable trace for.");
static ConfigVar<bool>::ptr g_logStdout =
Config::lookup("log.stdout", false, "Log to stdout");
#ifdef WINDOWS
static ConfigVar<bool>::ptr g_logDebugWindow =
Config::lookup("log.debug", false, "Log to Debug Window");
#endif
static ConfigVar<std::string>::ptr g_logFile =
Config::lookup("log.file", std::string(""), "Log to file");
static FiberLocalStorage<bool> f_logDisabled;
static unsigned long long g_start;
namespace {
static struct LogInitializer
{
LogInitializer()
{
g_start = TimerManager::now();
g_logError->monitor(&enableLoggers);
g_logWarn->monitor(&enableLoggers);
g_logInfo->monitor(&enableLoggers);
g_logVerbose->monitor(&enableLoggers);
g_logDebug->monitor(&enableLoggers);
g_logTrace->monitor(&enableLoggers);
g_logFile->monitor(&enableFileLogging);
g_logStdout->monitor(&enableStdoutLogging);
#ifdef WINDOWS
g_logDebugWindow->monitor(&enableDebugLogging);
#endif
}
} g_init;
}
static void enableLogger(Logger::ptr logger,
const boost::regex &errorRegex, const boost::regex &warnRegex,
const boost::regex &infoRegex, const boost::regex &verboseRegex,
const boost::regex &debugRegex, const boost::regex &traceRegex)
{
Log::Level level = Log::FATAL;
if (boost::regex_match(logger->name(), errorRegex))
level = Log::ERROR;
if (boost::regex_match(logger->name(), warnRegex))
level = Log::WARNING;
if (boost::regex_match(logger->name(), infoRegex))
level = Log::INFO;
if (boost::regex_match(logger->name(), verboseRegex))
level = Log::VERBOSE;
if (boost::regex_match(logger->name(), debugRegex))
level = Log::DEBUG;
if (boost::regex_match(logger->name(), traceRegex))
level = Log::TRACE;
if (logger->level() != level)
logger->level(level, false);
}
static void enableLoggers()
{
boost::regex errorRegex("^" + g_logError->val() + "$");
boost::regex warnRegex("^" + g_logWarn->val() + "$");
boost::regex infoRegex("^" + g_logInfo->val() + "$");
boost::regex verboseRegex("^" + g_logVerbose->val() + "$");
boost::regex debugRegex("^" + g_logDebug->val() + "$");
boost::regex traceRegex("^" + g_logTrace->val() + "$");
Log::visit(boost::bind(&enableLogger, _1,
boost::cref(errorRegex), boost::cref(warnRegex),
boost::cref(infoRegex), boost::cref(verboseRegex),
boost::cref(debugRegex), boost::cref(traceRegex)));
}
static void enableStdoutLogging()
{
static LogSink::ptr stdoutSink;
bool log = g_logStdout->val();
if (stdoutSink.get() && !log) {
Log::removeSink(stdoutSink);
stdoutSink.reset();
} else if (!stdoutSink.get() && log) {
stdoutSink.reset(new StdoutLogSink());
Log::addSink(stdoutSink);
}
}
#ifdef WINDOWS
static void enableDebugLogging()
{
static LogSink::ptr debugSink;
bool log = g_logDebugWindow->val();
if (debugSink.get() && !log) {
Log::removeSink(debugSink);
debugSink.reset();
} else if (!debugSink.get() && log) {
debugSink.reset(new DebugLogSink());
Log::addSink(debugSink);
}
}
#endif
static void enableFileLogging()
{
static LogSink::ptr fileSink;
std::string file = g_logFile->val();
if (fileSink.get() && file.empty()) {
Log::removeSink(fileSink);
fileSink.reset();
} else if (!file.empty()) {
if (fileSink.get()) {
if (static_cast<FileLogSink*>(fileSink.get())->file() == file)
return;
Log::removeSink(fileSink);
fileSink.reset();
}
fileSink.reset(new FileLogSink(file));
Log::addSink(fileSink);
}
}
void
StdoutLogSink::log(const std::string &logger,
boost::posix_time::ptime now, unsigned long long elapsed,
tid_t thread, void *fiber,
Log::Level level, const std::string &str,
const char *file, int line)
{
std::ostringstream os;
os << now << " " << elapsed << " " << level << " " << thread << " "
<< fiber << " " << logger << " " << file << ":" << line << " "
<< str << std::endl;
std::cout << os.str();
std::cout.flush();
}
#ifdef WINDOWS
void
DebugLogSink::log(const std::string &logger,
boost::posix_time::ptime now, unsigned long long elapsed,
tid_t thread, void *fiber,
Log::Level level, const std::string &str,
const char *file, int line)
{
std::wostringstream os;
os << now << " " << elapsed << " " << level << " " << thread << " "
<< fiber << " " << toUtf16(logger) << " " << toUtf16(file)
<< ":" << line << " " << toUtf16(str) << std::endl;
OutputDebugStringW(os.str().c_str());
}
#endif
FileLogSink::FileLogSink(const std::string &file)
{
m_stream.reset(new FileStream(file, FileStream::APPEND,
FileStream::OPEN_OR_CREATE));
m_file = file;
}
void
FileLogSink::log(const std::string &logger,
boost::posix_time::ptime now, unsigned long long elapsed,
tid_t thread, void *fiber,
Log::Level level, const std::string &str,
const char *file, int line)
{
std::ostringstream os;
os << now << " " << elapsed << " " << level << " " << thread << " "
<< fiber << " " << logger << " " << file << ":" << line << " "
<< str << std::endl;
std::string logline = os.str();
m_stream->write(logline.c_str(), logline.size());
m_stream->flush();
}
static void deleteNothing(Logger *l)
{}
Logger::ptr Log::root()
{
static Logger::ptr _root(new Logger());
return _root;
}
Logger::ptr Log::lookup(const std::string &name)
{
Logger::ptr log = root();
if(name.empty() || name == ":"){
return log;
}
std::set<Logger::ptr, LoggerLess>::iterator it;
Logger dummy(name, log);
Logger::ptr dummyPtr(&dummy, &deleteNothing);
size_t start = 0;
std::string child_name;
std::string node_name;
while (start < name.size()) {
size_t pos = name.find(':', start);
if(pos == std::string::npos){
child_name = name.substr(start);
start = name.size();
}else{
child_name = name.substr(start, pos - start);
start = pos + 1;
}
if(child_name.empty()){
continue;
}
if(!node_name.empty()){
node_name += ":";
}
node_name += child_name;
dummyPtr->m_name = node_name;
it = log->m_children.lower_bound(dummyPtr);
if(it == log->m_children.end() || (*it)->m_name != node_name){
Logger::ptr child(new Logger(node_name, log));
log->m_children.insert(child);
log = child;
}else{
log = *it;
}
}
return log;
}
void
Log::visit(boost::function<void (boost::shared_ptr<Logger>)> dg)
{
std::list<Logger::ptr> toVisit;
toVisit.push_back(root());
while (!toVisit.empty())
{
Logger::ptr cur = toVisit.front();
toVisit.pop_front();
dg(cur);
for (std::set<Logger::ptr, LoggerLess>::iterator it = cur->m_children.begin();
it != cur->m_children.end();
++it) {
toVisit.push_back(*it);
}
}
}
void
Log::addSink(LogSink::ptr sink)
{
root()->addSink(sink);
}
void
Log::removeSink(LogSink::ptr sink)
{
root()->removeSink(sink);
}
void
Log::clearSinks()
{
root()->clearSinks();
}
LogDisabler::LogDisabler()
{
m_disabled = !f_logDisabled;
f_logDisabled = true;
}
LogDisabler::~LogDisabler()
{
if (m_disabled)
f_logDisabled = false;
}
bool
LoggerLess::operator ()(const Logger::ptr &lhs,
const Logger::ptr &rhs) const
{
return lhs->m_name < rhs->m_name;
}
Logger::Logger()
: m_name(":"),
m_level(Log::INFO),
m_inheritSinks(false)
{}
Logger::Logger(const std::string &name, Logger::ptr parent)
: m_name(name),
m_parent(parent),
m_level(Log::INFO),
m_inheritSinks(true)
{}
bool
Logger::enabled(Log::Level level)
{
return level == Log::FATAL || (m_level >= level && !f_logDisabled);
}
void
Logger::level(Log::Level level, bool propagate)
{
m_level = level;
if (propagate) {
for (std::set<Logger::ptr, LoggerLess>::iterator it(m_children.begin());
it != m_children.end();
++it) {
(*it)->level(level);
}
}
}
void
Logger::removeSink(LogSink::ptr sink)
{
std::list<LogSink::ptr>::iterator it =
std::find(m_sinks.begin(), m_sinks.end(), sink);
if (it != m_sinks.end())
m_sinks.erase(it);
}
void
Logger::log(Log::Level level, const std::string &str,
const char *file, int line)
{
if (str.empty() || !enabled(level))
return;
error_t error = lastError();
LogDisabler disable;
unsigned long long elapsed = TimerManager::now() - g_start;
boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
Logger::ptr _this = shared_from_this();
#ifdef WINDOWS
DWORD thread = GetCurrentThreadId();
#elif defined(LINUX)
pid_t thread = syscall(__NR_gettid);
#else
pid_t thread = getpid();
#endif
void *fiber = Fiber::getThis().get();
bool somethingLogged = false;
while (_this) {
for (std::list<LogSink::ptr>::iterator it(_this->m_sinks.begin());
it != _this->m_sinks.end();
++it) {
somethingLogged = true;
(*it)->log(m_name, now, elapsed, thread, fiber, level, str, file, line);
}
if (!_this->m_inheritSinks)
break;
_this = _this->m_parent.lock();
}
// Restore lastError
if (somethingLogged)
lastError(error);
}
LogEvent::~LogEvent()
{
m_logger->log(m_level, m_os.str(), m_file, m_line);
}
static const char *levelStrs[] = {
"NONE",
"FATAL",
"ERROR",
"WARN",
"INFO",
"VERBOSE",
"DEBUG",
"TRACE",
};
std::ostream &operator <<(std::ostream &os, Log::Level level)
{
MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE);
return os << levelStrs[level];
}
#ifdef WINDOWS
static const wchar_t *levelStrsw[] = {
L"NONE",
L"FATAL",
L"ERROR",
L"WARN",
L"INFO",
L"VERBOSE",
L"DEBUG",
L"TRACE",
};
std::wostream &operator <<(std::wostream &os, Log::Level level)
{
MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE);
return os << levelStrsw[level];
}
#endif
}
<commit_msg>don't crash when invalid log mask regex is supplied<commit_after>// Copyright (c) 2009 - Mozy, Inc.
#include "mordor/pch.h"
#include "log.h"
#include <iostream>
#include <boost/bind.hpp>
#include <boost/regex.hpp>
#include "assert.h"
#include "config.h"
#include "fiber.h"
#include "mordor/streams/file.h"
#include "mordor/string.h"
#include "timer.h"
namespace Mordor {
static void enableLoggers();
static void enableStdoutLogging();
static void enableFileLogging();
#ifdef WINDOWS
static void enableDebugLogging();
#endif
static ConfigVar<std::string>::ptr g_logError =
Config::lookup("log.errormask", std::string(".*"), "Regex of loggers to enable error for.");
static ConfigVar<std::string>::ptr g_logWarn =
Config::lookup("log.warnmask", std::string(".*"), "Regex of loggers to enable warning for.");
static ConfigVar<std::string>::ptr g_logInfo =
Config::lookup("log.infomask", std::string(".*"), "Regex of loggers to enable info for.");
static ConfigVar<std::string>::ptr g_logVerbose =
Config::lookup("log.verbosemask", std::string(""), "Regex of loggers to enable verbose for.");
static ConfigVar<std::string>::ptr g_logDebug =
Config::lookup("log.debugmask", std::string(""), "Regex of loggers to enable debugging for.");
static ConfigVar<std::string>::ptr g_logTrace =
Config::lookup("log.tracemask", std::string(""), "Regex of loggers to enable trace for.");
static ConfigVar<bool>::ptr g_logStdout =
Config::lookup("log.stdout", false, "Log to stdout");
#ifdef WINDOWS
static ConfigVar<bool>::ptr g_logDebugWindow =
Config::lookup("log.debug", false, "Log to Debug Window");
#endif
static ConfigVar<std::string>::ptr g_logFile =
Config::lookup("log.file", std::string(""), "Log to file");
static FiberLocalStorage<bool> f_logDisabled;
static unsigned long long g_start;
namespace {
static struct LogInitializer
{
LogInitializer()
{
g_start = TimerManager::now();
g_logError->monitor(&enableLoggers);
g_logWarn->monitor(&enableLoggers);
g_logInfo->monitor(&enableLoggers);
g_logVerbose->monitor(&enableLoggers);
g_logDebug->monitor(&enableLoggers);
g_logTrace->monitor(&enableLoggers);
g_logFile->monitor(&enableFileLogging);
g_logStdout->monitor(&enableStdoutLogging);
#ifdef WINDOWS
g_logDebugWindow->monitor(&enableDebugLogging);
#endif
}
} g_init;
}
static void enableLogger(Logger::ptr logger,
const boost::regex &errorRegex, const boost::regex &warnRegex,
const boost::regex &infoRegex, const boost::regex &verboseRegex,
const boost::regex &debugRegex, const boost::regex &traceRegex)
{
Log::Level level = Log::FATAL;
if (boost::regex_match(logger->name(), errorRegex))
level = Log::ERROR;
if (boost::regex_match(logger->name(), warnRegex))
level = Log::WARNING;
if (boost::regex_match(logger->name(), infoRegex))
level = Log::INFO;
if (boost::regex_match(logger->name(), verboseRegex))
level = Log::VERBOSE;
if (boost::regex_match(logger->name(), debugRegex))
level = Log::DEBUG;
if (boost::regex_match(logger->name(), traceRegex))
level = Log::TRACE;
if (logger->level() != level)
logger->level(level, false);
}
static boost::regex buildLogRegex(const std::string &exp, const std::string &default_exp)
{
try
{
return boost::regex(exp);
}
catch(boost::bad_expression &)
{
return boost::regex(default_exp);
}
}
static void enableLoggers()
{
boost::regex errorRegex = buildLogRegex(g_logError->val(), ".*");
boost::regex warnRegex = buildLogRegex(g_logWarn->val(), ".*");
boost::regex infoRegex = buildLogRegex(g_logInfo->val(), ".*");
boost::regex verboseRegex = buildLogRegex(g_logVerbose->val(), "");
boost::regex debugRegex = buildLogRegex(g_logDebug->val(), "");
boost::regex traceRegex = buildLogRegex(g_logTrace->val(), "");
Log::visit(boost::bind(&enableLogger, _1,
boost::cref(errorRegex), boost::cref(warnRegex),
boost::cref(infoRegex), boost::cref(verboseRegex),
boost::cref(debugRegex), boost::cref(traceRegex)));
}
static void enableStdoutLogging()
{
static LogSink::ptr stdoutSink;
bool log = g_logStdout->val();
if (stdoutSink.get() && !log) {
Log::removeSink(stdoutSink);
stdoutSink.reset();
} else if (!stdoutSink.get() && log) {
stdoutSink.reset(new StdoutLogSink());
Log::addSink(stdoutSink);
}
}
#ifdef WINDOWS
static void enableDebugLogging()
{
static LogSink::ptr debugSink;
bool log = g_logDebugWindow->val();
if (debugSink.get() && !log) {
Log::removeSink(debugSink);
debugSink.reset();
} else if (!debugSink.get() && log) {
debugSink.reset(new DebugLogSink());
Log::addSink(debugSink);
}
}
#endif
static void enableFileLogging()
{
static LogSink::ptr fileSink;
std::string file = g_logFile->val();
if (fileSink.get() && file.empty()) {
Log::removeSink(fileSink);
fileSink.reset();
} else if (!file.empty()) {
if (fileSink.get()) {
if (static_cast<FileLogSink*>(fileSink.get())->file() == file)
return;
Log::removeSink(fileSink);
fileSink.reset();
}
fileSink.reset(new FileLogSink(file));
Log::addSink(fileSink);
}
}
void
StdoutLogSink::log(const std::string &logger,
boost::posix_time::ptime now, unsigned long long elapsed,
tid_t thread, void *fiber,
Log::Level level, const std::string &str,
const char *file, int line)
{
std::ostringstream os;
os << now << " " << elapsed << " " << level << " " << thread << " "
<< fiber << " " << logger << " " << file << ":" << line << " "
<< str << std::endl;
std::cout << os.str();
std::cout.flush();
}
#ifdef WINDOWS
void
DebugLogSink::log(const std::string &logger,
boost::posix_time::ptime now, unsigned long long elapsed,
tid_t thread, void *fiber,
Log::Level level, const std::string &str,
const char *file, int line)
{
std::wostringstream os;
os << now << " " << elapsed << " " << level << " " << thread << " "
<< fiber << " " << toUtf16(logger) << " " << toUtf16(file)
<< ":" << line << " " << toUtf16(str) << std::endl;
OutputDebugStringW(os.str().c_str());
}
#endif
FileLogSink::FileLogSink(const std::string &file)
{
m_stream.reset(new FileStream(file, FileStream::APPEND,
FileStream::OPEN_OR_CREATE));
m_file = file;
}
void
FileLogSink::log(const std::string &logger,
boost::posix_time::ptime now, unsigned long long elapsed,
tid_t thread, void *fiber,
Log::Level level, const std::string &str,
const char *file, int line)
{
std::ostringstream os;
os << now << " " << elapsed << " " << level << " " << thread << " "
<< fiber << " " << logger << " " << file << ":" << line << " "
<< str << std::endl;
std::string logline = os.str();
m_stream->write(logline.c_str(), logline.size());
m_stream->flush();
}
static void deleteNothing(Logger *l)
{}
Logger::ptr Log::root()
{
static Logger::ptr _root(new Logger());
return _root;
}
Logger::ptr Log::lookup(const std::string &name)
{
Logger::ptr log = root();
if(name.empty() || name == ":"){
return log;
}
std::set<Logger::ptr, LoggerLess>::iterator it;
Logger dummy(name, log);
Logger::ptr dummyPtr(&dummy, &deleteNothing);
size_t start = 0;
std::string child_name;
std::string node_name;
while (start < name.size()) {
size_t pos = name.find(':', start);
if(pos == std::string::npos){
child_name = name.substr(start);
start = name.size();
}else{
child_name = name.substr(start, pos - start);
start = pos + 1;
}
if(child_name.empty()){
continue;
}
if(!node_name.empty()){
node_name += ":";
}
node_name += child_name;
dummyPtr->m_name = node_name;
it = log->m_children.lower_bound(dummyPtr);
if(it == log->m_children.end() || (*it)->m_name != node_name){
Logger::ptr child(new Logger(node_name, log));
log->m_children.insert(child);
log = child;
}else{
log = *it;
}
}
return log;
}
void
Log::visit(boost::function<void (boost::shared_ptr<Logger>)> dg)
{
std::list<Logger::ptr> toVisit;
toVisit.push_back(root());
while (!toVisit.empty())
{
Logger::ptr cur = toVisit.front();
toVisit.pop_front();
dg(cur);
for (std::set<Logger::ptr, LoggerLess>::iterator it = cur->m_children.begin();
it != cur->m_children.end();
++it) {
toVisit.push_back(*it);
}
}
}
void
Log::addSink(LogSink::ptr sink)
{
root()->addSink(sink);
}
void
Log::removeSink(LogSink::ptr sink)
{
root()->removeSink(sink);
}
void
Log::clearSinks()
{
root()->clearSinks();
}
LogDisabler::LogDisabler()
{
m_disabled = !f_logDisabled;
f_logDisabled = true;
}
LogDisabler::~LogDisabler()
{
if (m_disabled)
f_logDisabled = false;
}
bool
LoggerLess::operator ()(const Logger::ptr &lhs,
const Logger::ptr &rhs) const
{
return lhs->m_name < rhs->m_name;
}
Logger::Logger()
: m_name(":"),
m_level(Log::INFO),
m_inheritSinks(false)
{}
Logger::Logger(const std::string &name, Logger::ptr parent)
: m_name(name),
m_parent(parent),
m_level(Log::INFO),
m_inheritSinks(true)
{}
bool
Logger::enabled(Log::Level level)
{
return level == Log::FATAL || (m_level >= level && !f_logDisabled);
}
void
Logger::level(Log::Level level, bool propagate)
{
m_level = level;
if (propagate) {
for (std::set<Logger::ptr, LoggerLess>::iterator it(m_children.begin());
it != m_children.end();
++it) {
(*it)->level(level);
}
}
}
void
Logger::removeSink(LogSink::ptr sink)
{
std::list<LogSink::ptr>::iterator it =
std::find(m_sinks.begin(), m_sinks.end(), sink);
if (it != m_sinks.end())
m_sinks.erase(it);
}
void
Logger::log(Log::Level level, const std::string &str,
const char *file, int line)
{
if (str.empty() || !enabled(level))
return;
error_t error = lastError();
LogDisabler disable;
unsigned long long elapsed = TimerManager::now() - g_start;
boost::posix_time::ptime now = boost::posix_time::microsec_clock::universal_time();
Logger::ptr _this = shared_from_this();
#ifdef WINDOWS
DWORD thread = GetCurrentThreadId();
#elif defined(LINUX)
pid_t thread = syscall(__NR_gettid);
#else
pid_t thread = getpid();
#endif
void *fiber = Fiber::getThis().get();
bool somethingLogged = false;
while (_this) {
for (std::list<LogSink::ptr>::iterator it(_this->m_sinks.begin());
it != _this->m_sinks.end();
++it) {
somethingLogged = true;
(*it)->log(m_name, now, elapsed, thread, fiber, level, str, file, line);
}
if (!_this->m_inheritSinks)
break;
_this = _this->m_parent.lock();
}
// Restore lastError
if (somethingLogged)
lastError(error);
}
LogEvent::~LogEvent()
{
m_logger->log(m_level, m_os.str(), m_file, m_line);
}
static const char *levelStrs[] = {
"NONE",
"FATAL",
"ERROR",
"WARN",
"INFO",
"VERBOSE",
"DEBUG",
"TRACE",
};
std::ostream &operator <<(std::ostream &os, Log::Level level)
{
MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE);
return os << levelStrs[level];
}
#ifdef WINDOWS
static const wchar_t *levelStrsw[] = {
L"NONE",
L"FATAL",
L"ERROR",
L"WARN",
L"INFO",
L"VERBOSE",
L"DEBUG",
L"TRACE",
};
std::wostream &operator <<(std::wostream &os, Log::Level level)
{
MORDOR_ASSERT(level >= Log::FATAL && level <= Log::TRACE);
return os << levelStrsw[level];
}
#endif
}
<|endoftext|> |
<commit_before>#include "Pong/Pong.hpp"
#include "Pong/Defs.hpp"
#include "Pong/State/GameState.hpp"
#include "Pong/State/GameReadyState.hpp"
using namespace sf;
namespace pong {
void Pong::create() {
int flags = sf::Style::Titlebar | sf::Style::Close;
window_.create(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), WINDOW_TITLE, flags);
assets_.loadAssets();
GameState* gameState = new GameState(this);
gameState->create();
GameReadyState* gameReadyState = new GameReadyState(this, gameState);
gameReadyState->create();
pushState(gameState);
pushState(gameReadyState);
}
void Pong::destroy() {
clearStates();
window_.close();
}
void Pong::tick() {
sf::Time time = clock_.restart();
currentState()->processEvents();
timeAccumulator_ += time.asSeconds();
if (timeAccumulator_ >= GAME_TIME_STEP) {
currentState()->update();
timeAccumulator_ -= GAME_TIME_STEP;
}
window_.clear();
currentState()->render();
window_.display();
}
} /* namespace pong */
<commit_msg>Enable VSync<commit_after>#include "Pong/Pong.hpp"
#include "Pong/Defs.hpp"
#include "Pong/State/GameState.hpp"
#include "Pong/State/GameReadyState.hpp"
using namespace sf;
namespace pong {
void Pong::create() {
int flags = sf::Style::Titlebar | sf::Style::Close;
window_.create(VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), WINDOW_TITLE, flags);
window_.setVerticalSyncEnabled(true);
assets_.loadAssets();
GameState* gameState = new GameState(this);
gameState->create();
GameReadyState* gameReadyState = new GameReadyState(this, gameState);
gameReadyState->create();
pushState(gameState);
pushState(gameReadyState);
}
void Pong::destroy() {
clearStates();
window_.close();
}
void Pong::tick() {
sf::Time time = clock_.restart();
currentState()->processEvents();
timeAccumulator_ += time.asSeconds();
if (timeAccumulator_ >= GAME_TIME_STEP) {
currentState()->update();
timeAccumulator_ -= GAME_TIME_STEP;
}
window_.clear();
currentState()->render();
window_.display();
}
} /* namespace pong */
<|endoftext|> |
<commit_before>#include <cassert>
#include "Processor.h"
using namespace Simulator;
using namespace std;
//
// Processor implementation
//
Processor::Processor(Object* parent, Kernel& kernel, PID pid, PSize numProcs, const std::string& name, IMemory& memory, const Config& config, MemAddr runAddress, bool legacy)
: IComponent(parent, kernel, name, 0),
m_pid(pid), m_kernel(kernel), m_memory(memory), m_numProcs(numProcs),
m_localFamilyCompletion(0),
m_allocator (*this, "alloc", m_familyTable, m_threadTable, m_registerFile, m_raunit, m_icache, m_network, m_pipeline, numProcs, config.allocator),
m_icache (*this, "icache", m_allocator, config.icache),
m_dcache (*this, "dcache", m_allocator, m_familyTable, m_registerFile, config.dcache),
m_registerFile(*this, m_icache, m_dcache, m_allocator, config.registerFile),
m_pipeline (*this, "pipeline", m_registerFile, m_network, m_allocator, m_familyTable, m_threadTable, m_icache, m_dcache, m_fpu, config.pipeline),
m_fpu (*this, "fpu", m_registerFile, config.fpu),
m_raunit (*this, "rau", m_registerFile, config.raunit),
m_familyTable (*this, config.familyTable),
m_threadTable (*this, config.threadTable),
m_network (*this, "network", m_allocator, m_registerFile, m_familyTable)
{
//
// Set port priorities and connections on all components
//
m_registerFile.p_asyncW.setPriority(m_fpu, 0);
m_registerFile.p_asyncW.setPriority(m_dcache, 1);
m_registerFile.p_asyncW.setPriority(m_network, 2);
m_registerFile.p_asyncW.setPriority(m_allocator, 3);
m_registerFile.p_asyncR.setPriority(m_network, 0);
m_registerFile.p_pipelineR1.setComponent(m_pipeline.m_read);
m_registerFile.p_pipelineR2.setComponent(m_pipeline.m_read);
m_registerFile.p_pipelineW.setComponent(m_pipeline.m_writeback);
// Set thread activation (cache-line query) order.
// Primary concern is keeping the pipeline flowing. So order from back to front.
m_icache.p_request.setPriority(m_pipeline.m_writeback, 0); // Writebacks
m_icache.p_request.setPriority(m_pipeline.m_execute, 1); // Reschedules
m_icache.p_request.setPriority(m_fpu, 2); // FPU writeback
m_icache.p_request.setPriority(m_dcache, 3); // Memory read writebacks
m_icache.p_request.setPriority(m_network, 4); // Remote shareds writebacks
m_icache.p_request.setPriority(m_allocator, 5); // Family completion, etc
m_allocator.p_cleanup.setPriority(m_pipeline.m_read, 0);
m_memory.registerListener(*this);
if (pid == 0)
{
// Allocate the startup family on the first processor
m_allocator.allocateInitialFamily(runAddress,legacy);
}
}
void Processor::initialize(Processor& prev, Processor& next)
{
m_network.initialize(prev.m_network, next.m_network);
}
Result Processor::readMemory(MemAddr address, void* data, MemSize size, MemTag tag)
{
return m_memory.read(*this, address, data, size, tag);
}
Result Processor::writeMemory(MemAddr address, void* data, MemSize size, MemTag tag)
{
return m_memory.write(*this, address, data, size, tag);
}
bool Processor::checkPermissions(MemAddr address, MemSize size, int access) const
{
return m_memory.checkPermissions(address, size, access);
}
bool Processor::onMemoryReadCompleted(const MemData& data)
{
// Dispatch result to I-Cache, D-Cache or Create Process, depending on tag
assert(data.tag.cid != INVALID_CID);
if (data.tag.data)
{
return m_dcache.onMemoryReadCompleted(data);
}
return m_icache.onMemoryReadCompleted(data);
}
bool Processor::onMemoryWriteCompleted(const MemTag& tag)
{
// Dispatch result to D-Cache
assert(tag.fid != INVALID_LFID);
return m_dcache.onMemoryWriteCompleted(tag);
}
bool Processor::onMemorySnooped(MemAddr addr, const MemData& data)
{
return m_dcache.onMemorySnooped(addr, data);
}
void Processor::OnFamilyTerminatedLocally(MemAddr pc)
{
if (pc == 0x88)
{
CycleNo cycle = getKernel().getCycleNo();
m_localFamilyCompletion = cycle;
}
}
<commit_msg>Changed family completion timing to work for all families<commit_after>#include <cassert>
#include "Processor.h"
using namespace Simulator;
using namespace std;
//
// Processor implementation
//
Processor::Processor(Object* parent, Kernel& kernel, PID pid, PSize numProcs, const std::string& name, IMemory& memory, const Config& config, MemAddr runAddress, bool legacy)
: IComponent(parent, kernel, name, 0),
m_pid(pid), m_kernel(kernel), m_memory(memory), m_numProcs(numProcs),
m_localFamilyCompletion(0),
m_allocator (*this, "alloc", m_familyTable, m_threadTable, m_registerFile, m_raunit, m_icache, m_network, m_pipeline, numProcs, config.allocator),
m_icache (*this, "icache", m_allocator, config.icache),
m_dcache (*this, "dcache", m_allocator, m_familyTable, m_registerFile, config.dcache),
m_registerFile(*this, m_icache, m_dcache, m_allocator, config.registerFile),
m_pipeline (*this, "pipeline", m_registerFile, m_network, m_allocator, m_familyTable, m_threadTable, m_icache, m_dcache, m_fpu, config.pipeline),
m_fpu (*this, "fpu", m_registerFile, config.fpu),
m_raunit (*this, "rau", m_registerFile, config.raunit),
m_familyTable (*this, config.familyTable),
m_threadTable (*this, config.threadTable),
m_network (*this, "network", m_allocator, m_registerFile, m_familyTable)
{
//
// Set port priorities and connections on all components
//
m_registerFile.p_asyncW.setPriority(m_fpu, 0);
m_registerFile.p_asyncW.setPriority(m_dcache, 1);
m_registerFile.p_asyncW.setPriority(m_network, 2);
m_registerFile.p_asyncW.setPriority(m_allocator, 3);
m_registerFile.p_asyncR.setPriority(m_network, 0);
m_registerFile.p_pipelineR1.setComponent(m_pipeline.m_read);
m_registerFile.p_pipelineR2.setComponent(m_pipeline.m_read);
m_registerFile.p_pipelineW.setComponent(m_pipeline.m_writeback);
// Set thread activation (cache-line query) order.
// Primary concern is keeping the pipeline flowing. So order from back to front.
m_icache.p_request.setPriority(m_pipeline.m_writeback, 0); // Writebacks
m_icache.p_request.setPriority(m_pipeline.m_execute, 1); // Reschedules
m_icache.p_request.setPriority(m_fpu, 2); // FPU writeback
m_icache.p_request.setPriority(m_dcache, 3); // Memory read writebacks
m_icache.p_request.setPriority(m_network, 4); // Remote shareds writebacks
m_icache.p_request.setPriority(m_allocator, 5); // Family completion, etc
m_allocator.p_cleanup.setPriority(m_pipeline.m_read, 0);
m_memory.registerListener(*this);
if (pid == 0)
{
// Allocate the startup family on the first processor
m_allocator.allocateInitialFamily(runAddress,legacy);
}
}
void Processor::initialize(Processor& prev, Processor& next)
{
m_network.initialize(prev.m_network, next.m_network);
}
Result Processor::readMemory(MemAddr address, void* data, MemSize size, MemTag tag)
{
return m_memory.read(*this, address, data, size, tag);
}
Result Processor::writeMemory(MemAddr address, void* data, MemSize size, MemTag tag)
{
return m_memory.write(*this, address, data, size, tag);
}
bool Processor::checkPermissions(MemAddr address, MemSize size, int access) const
{
return m_memory.checkPermissions(address, size, access);
}
bool Processor::onMemoryReadCompleted(const MemData& data)
{
// Dispatch result to I-Cache, D-Cache or Create Process, depending on tag
assert(data.tag.cid != INVALID_CID);
if (data.tag.data)
{
return m_dcache.onMemoryReadCompleted(data);
}
return m_icache.onMemoryReadCompleted(data);
}
bool Processor::onMemoryWriteCompleted(const MemTag& tag)
{
// Dispatch result to D-Cache
assert(tag.fid != INVALID_LFID);
return m_dcache.onMemoryWriteCompleted(tag);
}
bool Processor::onMemorySnooped(MemAddr addr, const MemData& data)
{
return m_dcache.onMemorySnooped(addr, data);
}
void Processor::OnFamilyTerminatedLocally(MemAddr pc)
{
CycleNo cycle = getKernel().getCycleNo();
m_localFamilyCompletion = cycle;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.