text stringlengths 54 60.6k |
|---|
<commit_before>#include <QFileInfo>
#include <QMessageBox>
#include <QDir>
#include <QTime>
#include "hrwplayer.h"
QString moduleFileName;
HrwPlayer::HrwPlayer()
{
setupUi(this);
audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
mediaObject = new Phonon::MediaObject(this);
metaInformationResolver = new Phonon::MediaObject(this);
mediaObject->setTickInterval(1000); // for remaining time display
Phonon::createPath(mediaObject, audioOutput);
connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this, SLOT(StateChanged(Phonon::State,Phonon::State)));
// connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
// this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));
// connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),
// this, SLOT(sourceChanged(Phonon::MediaSource)));
connect(mediaObject, SIGNAL(finished()), this, SLOT(FinishedPlaying()));
connect(LoadButton, SIGNAL(clicked()), this, SLOT(OpenFileName()));
connect(SongsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PlaySelected(QListWidgetItem*)));
connect(PlayButton, SIGNAL(clicked()), mediaObject, SLOT(play()));
connect(PauseButton, SIGNAL(clicked()), mediaObject, SLOT(pause()) );
connect(StopButton, SIGNAL(clicked()), mediaObject, SLOT(stop()));
seekSlider->setMediaObject(mediaObject);
volumeSlider->setAudioOutput(audioOutput);
QDir moduleList("./Jester/");
QStringList filters;
filters << "*.mod";
SongsList->insertItems(0, moduleList.entryList(filters));
};
HrwPlayer::~HrwPlayer() {};
void HrwPlayer::OpenFileName()
{
QString fileName = QFileDialog::getOpenFileName(NULL, "Select module", moduleFileName);
if (!fileName.isEmpty())
{
mediaObject->setCurrentSource(fileName);
QFileInfo fileinfo(fileName);
TitleLabel->setText(fileinfo.baseName());
}
}
void HrwPlayer::StateChanged(Phonon::State newState, Phonon::State /* oldState */)
{
switch (newState)
{
case Phonon::ErrorState:
if (mediaObject->errorType() == Phonon::FatalError)
{
QMessageBox::warning(this, tr("Fatal Error"),
mediaObject->errorString());
}
else
{
QMessageBox::warning(this, tr("Error"),
mediaObject->errorString());
}
break;
case Phonon::PlayingState:
PlayButton->setEnabled(false);
PauseButton->setEnabled(true);
StopButton->setEnabled(true);
break;
case Phonon::StoppedState:
StopButton->setEnabled(false);
PlayButton->setEnabled(true);
PauseButton->setEnabled(false);
break;
case Phonon::PausedState:
PauseButton->setEnabled(false);
StopButton->setEnabled(true);
PlayButton->setEnabled(true);
break;
case Phonon::BufferingState:
break;
default:
;
}
}
void HrwPlayer::PlaySelected(QListWidgetItem* selectedItem)
{
QString fileName = "Jester/";
fileName.append(selectedItem->text());
mediaObject->setCurrentSource(fileName);
QFileInfo fileinfo(fileName);
TitleLabel->setText(fileinfo.baseName());
TimeLabel->setText("00:00");
mediaObject->play();
}
void HrwPlayer::FinishedPlaying()
{
QListWidgetItem* selectedItem = SongsList->item(SongsList->currentRow() + 1);
PlaySelected(selectedItem);
SongsList->setCurrentRow(SongsList->currentRow() + 1);
}
void HrwPlayer::tick(qint64 time)
{
QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60);
TimeLabel->setText(displayTime.toString("mm:ss"));
}
<commit_msg>loop on songlist if last song is played<commit_after>#include <QFileInfo>
#include <QMessageBox>
#include <QDir>
#include <QTime>
#include "hrwplayer.h"
QString moduleFileName;
HrwPlayer::HrwPlayer()
{
setupUi(this);
audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
mediaObject = new Phonon::MediaObject(this);
metaInformationResolver = new Phonon::MediaObject(this);
mediaObject->setTickInterval(1000); // for remaining time display
Phonon::createPath(mediaObject, audioOutput);
connect(mediaObject, SIGNAL(tick(qint64)), this, SLOT(tick(qint64)));
connect(mediaObject, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
this, SLOT(StateChanged(Phonon::State,Phonon::State)));
// connect(metaInformationResolver, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
// this, SLOT(metaStateChanged(Phonon::State,Phonon::State)));
// connect(mediaObject, SIGNAL(currentSourceChanged(Phonon::MediaSource)),
// this, SLOT(sourceChanged(Phonon::MediaSource)));
connect(mediaObject, SIGNAL(finished()), this, SLOT(FinishedPlaying()));
connect(LoadButton, SIGNAL(clicked()), this, SLOT(OpenFileName()));
connect(SongsList, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(PlaySelected(QListWidgetItem*)));
connect(PlayButton, SIGNAL(clicked()), mediaObject, SLOT(play()));
connect(PauseButton, SIGNAL(clicked()), mediaObject, SLOT(pause()) );
connect(StopButton, SIGNAL(clicked()), mediaObject, SLOT(stop()));
seekSlider->setMediaObject(mediaObject);
volumeSlider->setAudioOutput(audioOutput);
QDir moduleList("./Jester/");
QStringList filters;
filters << "*.mod";
SongsList->insertItems(0, moduleList.entryList(filters));
};
HrwPlayer::~HrwPlayer() {};
void HrwPlayer::OpenFileName()
{
QString fileName = QFileDialog::getOpenFileName(NULL, "Select module", moduleFileName);
if (!fileName.isEmpty())
{
mediaObject->setCurrentSource(fileName);
QFileInfo fileinfo(fileName);
TitleLabel->setText(fileinfo.baseName());
}
}
void HrwPlayer::StateChanged(Phonon::State newState, Phonon::State /* oldState */)
{
switch (newState)
{
case Phonon::ErrorState:
if (mediaObject->errorType() == Phonon::FatalError)
{
QMessageBox::warning(this, tr("Fatal Error"),
mediaObject->errorString());
}
else
{
QMessageBox::warning(this, tr("Error"),
mediaObject->errorString());
}
break;
case Phonon::PlayingState:
PlayButton->setEnabled(false);
PauseButton->setEnabled(true);
StopButton->setEnabled(true);
break;
case Phonon::StoppedState:
StopButton->setEnabled(false);
PlayButton->setEnabled(true);
PauseButton->setEnabled(false);
break;
case Phonon::PausedState:
PauseButton->setEnabled(false);
StopButton->setEnabled(true);
PlayButton->setEnabled(true);
break;
case Phonon::BufferingState:
break;
default:
;
}
}
void HrwPlayer::PlaySelected(QListWidgetItem* selectedItem)
{
QString fileName = "Jester/";
fileName.append(selectedItem->text());
mediaObject->setCurrentSource(fileName);
QFileInfo fileinfo(fileName);
TitleLabel->setText(fileinfo.baseName());
TimeLabel->setText("00:00");
mediaObject->play();
}
void HrwPlayer::FinishedPlaying()
{
QListWidgetItem* selectedItem;
if(SongsList->currentRow() == (SongsList->count() - 1))
{
selectedItem = SongsList->item(0);
SongsList->setCurrentRow(0);
}
else
{
selectedItem = SongsList->item(SongsList->currentRow() + 1);
SongsList->setCurrentRow(SongsList->currentRow() + 1);
}
PlaySelected(selectedItem);
}
void HrwPlayer::tick(qint64 time)
{
QTime displayTime(0, (time / 60000) % 60, (time / 1000) % 60);
TimeLabel->setText(displayTime.toString("mm:ss"));
}
<|endoftext|> |
<commit_before>#include <string>
#include <vector>
#include <sstream>
using namespace std;
#include "error_handling.h"
#include "game.h"
#include "colors.h"
#include "command.h"
#include "io.h"
#include "armor.h"
#include "daemons.h"
#include "monster.h"
#include "rings.h"
#include "misc.h"
#include "level.h"
#include "player.h"
#include "weapons.h"
#include "death.h"
#include "options.h"
#include "rogue.h"
#include "os.h"
#include "attack_modifier.h"
#include "fight.h"
// Calculate the damage an attacker does.
// Weapon can be null when no weapon was used
static attack_modifier
calculate_attacker(Character const& attacker, Item* weapon, bool thrown)
{
attack_modifier mod;
// Weapons override base attack (at the moment, monsters shouldn't use weapons)
if (weapon != nullptr) {
mod.to_hit = weapon->get_hit_plus();
mod.to_dmg = weapon->get_damage_plus();
if (thrown) {
mod.damage.push_back(weapon->get_throw_damage());
class Weapon* bow = player->equipped_weapon();
if (bow != nullptr) {
int multiplier = bow->get_ammo_multiplier();
for (damage& dmg : mod.damage) {
dmg.dices *= multiplier;
}
}
} else {
mod.damage.push_back(weapon->get_attack_damage());
}
// But otherwise we use the attacker's stats (can happen to both monsters and player)
} else {
mod.damage = attacker.get_attacks();
if (mod.damage.empty()) {
error("No damage was copied from attacker. Bad template?");
}
}
mod.add_strength_modifiers(attacker.get_strength());
if (&attacker == player) {
mod.to_dmg += player->pack_get_ring_modifier(Ring::Damage);
mod.to_hit += player->pack_get_ring_modifier(Ring::Accuracy);
if (thrown) {
Item const* held_weapon = player->equipped_weapon();
// If the weapon was an arrow and player is holding the bow. Add
// modifiers
if (weapon->o_launch != Weapon::NO_WEAPON && held_weapon != nullptr &&
weapon->o_launch == held_weapon->o_which) {
mod.damage.at(0) = held_weapon->get_throw_damage();
mod.to_hit += held_weapon->get_hit_plus();
mod.to_dmg += held_weapon->get_damage_plus();
}
}
// Venus Flytraps have a different kind of dmg system. It adds damage for
// every successful hit
} else if (attacker.get_type() == 'F') {
mod.damage[0].sides = monster_flytrap_hit;
}
return mod;
}
// Roll attackers attack vs defenders defense and then take damage if it hits
static bool
roll_attacks(Character* attacker, Character* defender, Item* weapon, bool thrown) {
if (attacker == nullptr) {
error("Attacker was null");
} else if (defender == nullptr) {
error("Defender was null");
}
attack_modifier mod = calculate_attacker(*attacker, weapon, thrown);
/* If defender is stuck in some way,the attacker gets a bonus to hit */
if ((defender == player && player_turns_without_action)
|| defender->is_held()
|| defender->is_stuck()) {
mod.to_hit += 4;
}
if (mod.damage.empty()) {
error("No damage at all?");
} else if (mod.damage.at(0).sides < 0 || mod.damage.at(0).dices < 0) {
error("Damage dice was negative");
}
bool did_hit = false;
for (damage const& dmg : mod.damage) {
if (dmg.sides == 0 && dmg.dices == 0) {
continue;
}
int defense = defender->get_armor();
if (fight_swing_hits(attacker->get_level(), defense, mod.to_hit)) {
int damage = roll(dmg.dices, dmg.sides) + mod.to_dmg;
if (damage > 0) {
defender->take_damage(damage);
}
did_hit = true;
}
}
return did_hit;
}
// Print a message to indicate a hit or miss
static void
print_attack(bool hit, Character* attacker, Character* defender) {
stringstream ss;
ss << attacker->get_name() << " "
<< attacker->get_attack_string(hit) << " "
<< defender->get_name();
Game::io->message(ss.str());
}
int
fight_against_monster(Coordinate const* monster_pos, Item* weapon, bool thrown,
string const* name_override) {
if (monster_pos == nullptr) {
error("monster_pos was null");
}
Monster* tp = Game::level->get_monster(*monster_pos);
if (tp == nullptr) {
return !io_fail("fight_against_monster(%p, %p, %b) nullptr monster\r\n",
monster_pos, weapon, thrown);
}
/* Since we are fighting, things are not quiet so no healing takes place */
command_stop(false);
Daemons::daemon_reset_doctor();
/* Let him know it was really a xeroc (if it was one) */
if (!player->is_blind() && tp->get_subtype() == Monster::Xeroc &&
tp->get_disguise() != tp->get_type()) {
tp->set_disguise(static_cast<char>(tp->get_type()));
Game::io->message("wait! That's a xeroc!");
if (!thrown) {
return false;
}
}
if (roll_attacks(player, tp, weapon, thrown)) {
if (tp->get_health() <= 0) {
monster_on_death(&tp, true);
return true;
}
if (!to_death) {
if (thrown) {
if (weapon->o_type == IO::Weapon) {
stringstream os;
os
<< "the "
<< (name_override == nullptr
? Weapon::name(static_cast<Weapon::Type>(weapon->o_which))
: *name_override)
<< " hits "
<< tp->get_name();
Game::io->message(os.str());
} else {
stringstream os;
os
<< "you hit "
<< tp->get_name();
Game::io->message(os.str());
}
} else {
print_attack(true, player, tp);
}
}
if (player->has_confusing_attack()) {
tp->set_confused();
player->remove_confusing_attack();
if (!player->is_blind()) {
Game::io->message("your hands stop glowing red");
Game::io->message(tp->get_name() + " appears confused");
}
}
monster_start_running(monster_pos);
return true;
}
monster_start_running(monster_pos);
if (thrown && !to_death) {
fight_missile_miss(weapon, tp->get_name().c_str(), name_override);
} else if (!to_death) {
print_attack(false, player, tp);
}
return false;
}
int
fight_against_player(Monster* mp) {
// Since this is an attack, stop running and any healing that was
// going on at the time
player_alerted = true;
command_stop(false);
Daemons::daemon_reset_doctor();
// Stop fighting to death if we are backstabbed
if (to_death && !mp->is_players_target()) {
to_death = false;
}
// If it's a xeroc, tag it as known
if (!player->is_blind() && mp->get_subtype() == Monster::Xeroc &&
mp->get_disguise() != mp->get_type()) {
mp->set_disguise('X');
}
if (roll_attacks(mp, player, nullptr, false)) {
// Monster hit player, and probably delt damage
// berzerking causes to much text
if (!to_death) {
print_attack(true, mp, player);
}
// Check player death (doesn't return)
if (player->get_health() <= 0) {
death(mp->get_subtype());
}
// Do monster ability (mp can be null after this!)
monster_do_special_ability(&mp);
} else {
if (mp->get_type() == 'F') {
player->take_damage(monster_flytrap_hit);
if (player->get_health() <= 0) {
death(mp->get_subtype());
}
}
if (!to_death) {
print_attack(false, mp, player);
}
}
command_stop(false);
Game::io->refresh();
return(mp == nullptr ? -1 : 0);
}
int
fight_swing_hits(int at_lvl, int op_arm, int wplus) {
int rand = os_rand_range(20) + 1;
stringstream os;
os << at_lvl << " + " << wplus << " + " << rand << " vs " << op_arm;
Game::io->message(os.str());
// Forced miss
if (rand == 1) {
return false;
// Forced hit
} else if (rand == 20) {
return true;
}
return at_lvl + wplus + rand >= op_arm;
}
void
fight_missile_miss(Item const* weap, string const& mname, string const* name_override) {
if (weap->o_type == IO::Weapon) {
if (name_override == nullptr) {
Game::io->message("the " + Weapon::name(static_cast<Weapon::Type>(weap->o_which)) +
" misses " + mname);
} else {
Game::io->message("the " + *name_override +
" misses " + mname);
}
} else {
Game::io->message("you missed " + mname);
}
}
<commit_msg>tiny change<commit_after>#include <string>
#include <vector>
#include <sstream>
using namespace std;
#include "error_handling.h"
#include "game.h"
#include "colors.h"
#include "command.h"
#include "io.h"
#include "armor.h"
#include "daemons.h"
#include "monster.h"
#include "rings.h"
#include "misc.h"
#include "level.h"
#include "player.h"
#include "weapons.h"
#include "death.h"
#include "options.h"
#include "rogue.h"
#include "os.h"
#include "attack_modifier.h"
#include "fight.h"
// Calculate the damage an attacker does.
// Weapon can be null when no weapon was used
static attack_modifier
calculate_attacker(Character const& attacker, Item* weapon, bool thrown)
{
attack_modifier mod;
// Weapons override base attack (at the moment, monsters shouldn't use weapons)
if (weapon != nullptr) {
mod.to_hit = weapon->get_hit_plus();
mod.to_dmg = weapon->get_damage_plus();
if (thrown) {
mod.damage.push_back(weapon->get_throw_damage());
class Weapon* bow = player->equipped_weapon();
if (bow != nullptr) {
int multiplier = bow->get_ammo_multiplier();
for (damage& dmg : mod.damage) {
dmg.dices *= multiplier;
}
}
} else {
mod.damage.push_back(weapon->get_attack_damage());
}
// But otherwise we use the attacker's stats (can happen to both monsters and player)
} else {
mod.damage = attacker.get_attacks();
if (mod.damage.empty()) {
error("No damage was copied from attacker. Bad template?");
}
}
mod.add_strength_modifiers(attacker.get_strength());
if (&attacker == player) {
mod.to_dmg += player->pack_get_ring_modifier(Ring::Damage);
mod.to_hit += player->pack_get_ring_modifier(Ring::Accuracy);
if (thrown) {
Item const* held_weapon = player->equipped_weapon();
// If the weapon was an arrow and player is holding the bow. Add
// modifiers
if (weapon->o_launch != Weapon::NO_WEAPON && held_weapon != nullptr &&
weapon->o_launch == held_weapon->o_which) {
mod.damage.at(0) = held_weapon->get_throw_damage();
mod.to_hit += held_weapon->get_hit_plus();
mod.to_dmg += held_weapon->get_damage_plus();
}
}
// Venus Flytraps have a different kind of dmg system. It adds damage for
// every successful hit
} else if (attacker.get_type() == 'F') {
mod.damage[0].sides = monster_flytrap_hit;
}
return mod;
}
// Roll attackers attack vs defenders defense and then take damage if it hits
static bool
roll_attacks(Character* attacker, Character* defender, Item* weapon, bool thrown) {
if (attacker == nullptr) {
error("Attacker was null");
} else if (defender == nullptr) {
error("Defender was null");
}
attack_modifier mod = calculate_attacker(*attacker, weapon, thrown);
/* If defender is stuck in some way,the attacker gets a bonus to hit */
if ((defender == player && player_turns_without_action)
|| defender->is_held()
|| defender->is_stuck()) {
mod.to_hit += 4;
}
if (mod.damage.empty()) {
error("No damage at all?");
} else if (mod.damage.at(0).sides < 0 || mod.damage.at(0).dices < 0) {
error("Damage dice was negative");
}
bool did_hit = false;
for (damage const& dmg : mod.damage) {
if (dmg.sides == 0 && dmg.dices == 0) {
continue;
}
int defense = defender->get_armor();
if (fight_swing_hits(attacker->get_level(), defense, mod.to_hit)) {
int damage = roll(dmg.dices, dmg.sides) + mod.to_dmg;
if (damage > 0) {
defender->take_damage(damage);
}
did_hit = true;
}
}
return did_hit;
}
// Print a message to indicate a hit or miss
static void
print_attack(bool hit, Character* attacker, Character* defender) {
stringstream ss;
ss << attacker->get_name() << " "
<< attacker->get_attack_string(hit) << " "
<< defender->get_name();
Game::io->message(ss.str());
}
int
fight_against_monster(Coordinate const* monster_pos, Item* weapon, bool thrown,
string const* name_override) {
if (monster_pos == nullptr) {
error("monster_pos was null");
}
Monster* tp = Game::level->get_monster(*monster_pos);
if (tp == nullptr) {
return !io_fail("fight_against_monster(%p, %p, %b) nullptr monster\r\n",
monster_pos, weapon, thrown);
}
/* Since we are fighting, things are not quiet so no healing takes place */
command_stop(false);
Daemons::daemon_reset_doctor();
/* Let him know it was really a xeroc (if it was one) */
if (!player->is_blind() && tp->get_subtype() == Monster::Xeroc &&
tp->get_disguise() != tp->get_type()) {
tp->set_disguise(static_cast<char>(tp->get_type()));
Game::io->message("wait! That's a xeroc!");
if (!thrown) {
return false;
}
}
if (roll_attacks(player, tp, weapon, thrown)) {
if (tp->get_health() <= 0) {
monster_on_death(&tp, true);
return true;
}
if (!to_death) {
if (thrown) {
if (weapon->o_type == IO::Weapon) {
stringstream os;
os
<< "the "
<< (name_override == nullptr
? Weapon::name(static_cast<Weapon::Type>(weapon->o_which))
: *name_override)
<< " hits "
<< tp->get_name();
Game::io->message(os.str());
} else {
stringstream os;
os
<< "you hit "
<< tp->get_name();
Game::io->message(os.str());
}
} else {
print_attack(true, player, tp);
}
}
if (player->has_confusing_attack()) {
tp->set_confused();
player->remove_confusing_attack();
if (!player->is_blind()) {
Game::io->message("your hands stop glowing red");
Game::io->message(tp->get_name() + " appears confused");
}
}
monster_start_running(monster_pos);
return true;
}
monster_start_running(monster_pos);
if (thrown && !to_death) {
fight_missile_miss(weapon, tp->get_name().c_str(), name_override);
} else if (!to_death) {
print_attack(false, player, tp);
}
return false;
}
int
fight_against_player(Monster* mp) {
// Since this is an attack, stop running and any healing that was
// going on at the time
player_alerted = true;
command_stop(false);
Daemons::daemon_reset_doctor();
// Stop fighting to death if we are backstabbed
if (to_death && !mp->is_players_target()) {
to_death = false;
}
// If it's a xeroc, tag it as known
if (!player->is_blind() && mp->get_subtype() == Monster::Xeroc &&
mp->get_disguise() != mp->get_type()) {
mp->set_disguise('X');
}
if (roll_attacks(mp, player, nullptr, false)) {
// Monster hit player, and probably delt damage
// berzerking causes to much text
if (!to_death) {
print_attack(true, mp, player);
}
// Check player death (doesn't return)
if (player->get_health() <= 0) {
death(mp->get_subtype());
}
// Do monster ability (mp can be null after this!)
monster_do_special_ability(&mp);
} else {
if (mp->get_type() == 'F') {
player->take_damage(monster_flytrap_hit);
if (player->get_health() <= 0) {
death(mp->get_subtype());
}
}
if (!to_death) {
print_attack(false, mp, player);
}
}
command_stop(false);
Game::io->refresh();
return(mp == nullptr ? -1 : 0);
}
int
fight_swing_hits(int at_lvl, int op_arm, int wplus) {
int rand = os_rand_range(20) + 1;
stringstream os;
os << at_lvl << " + " << wplus << " + " << rand << " vs " << op_arm;
Game::io->message(os.str());
// Forced miss
if (rand == 1) {
return false;
// Forced hit
} else if (rand == 20) {
return true;
} else {
return at_lvl + wplus + rand >= op_arm;
}
}
void
fight_missile_miss(Item const* weap, string const& mname, string const* name_override) {
if (weap->o_type == IO::Weapon) {
if (name_override == nullptr) {
Game::io->message("the " + Weapon::name(static_cast<Weapon::Type>(weap->o_which)) +
" misses " + mname);
} else {
Game::io->message("the " + *name_override +
" misses " + mname);
}
} else {
Game::io->message("you missed " + mname);
}
}
<|endoftext|> |
<commit_before>/**
* Implementation of Monotone Chain for convex hull
* computation of a set of points in the 2d space.
*/
#ifndef monotone_chain_h
#define monotone_chain_h
#include "angle.hpp"
#include "point_concept.hpp"
#include "static_assert.hpp"
#include <algorithm>
namespace hull::algorithms {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
static_assert_is_random_access_iterator_to_point<RandomIt1>();
static_assert_is_random_access_iterator_to_point<RandomIt2>();
// Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate)
std::sort(first, last, [](const auto& p1, const auto& p2) {
return (x(p1) < x(p2) || (hull::equals(x(p1), x(p2)) && y(p1) < y(p2)));
});
const auto N = std::distance(first, last);
if (N <= 1) {
return std::copy(first, last, first2);
}
std::size_t k{};
auto no_counter_clockwise = [&k, first, first2](auto i) {
return cross(*(first2 + (k - 2)), *(first2 + (k - 1)), *(first + i)) <= 0;
};
auto copy = [&k, first, first2](auto i) {
*(first2 + k) = *(first + i);
k++;
};
// Lower hull
for (int i{}; i < N; i++) {
while (k >= 2 && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
// Upper hull
auto t = k + 1;
for (int i{static_cast<int>(N - 2)}; i >= 0; i--) {
while (k >= t && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
return first2 + (k - 1);
}
}
namespace hull {
/**
* Compile-time enumeration to choose the
* algorithm thanks to a policy approach.
* @param monotone_chain_t - Monotone Chain algorithm.
*/
struct monotone_chain_t {};
/**
* Algorithms policies to choose an overload.
* @param monotone_chain - Monotone Chain algorithm.
*/
namespace choice {
static constexpr const monotone_chain_t monotone_chain{};
}
/**
* Overload of iterator-based convex hull computation for Monotone Chain.
* Note that the input is modified.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* It is unfortunately not possible to use a std::back_insert_iterator.
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* destination container of points.
*/
template <typename RandomIt1, typename RandomIt2>
auto compute_convex_hull(monotone_chain_t policy, RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
using value_type = typename std::iterator_traits<RandomIt2>::value_type;
std::fill_n(first2, 2 * std::distance(first, last), value_type{});
return algorithms::monotone_chain(first, last, first2);
}
namespace convex {
/**
* Overload of container-based convex hull computation for Monotone Chain.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(4 * N).
* @param c1 - the input container.
* @param c2 - the destination container.
*/
template <typename TContainer1, typename TContainer2>
void compute(monotone_chain_t policy, TContainer1 c1, TContainer2& c2) {
c2.resize(2 * c1.size());
std::fill(std::begin(c2), std::end(c2), typename TContainer2::value_type{});
auto last = hull::algorithms::monotone_chain(std::begin(c1), std::end(c1), std::begin(c2));
c2.erase(last, std::end(c2));
}
}
}
#endif
<commit_msg>Start refactoring Monotone Chain.<commit_after>/**
* Implementation of Monotone Chain for convex hull
* computation of a set of points in the 2d space.
*/
#ifndef monotone_chain_h
#define monotone_chain_h
#include "angle.hpp"
#include "point_concept.hpp"
#include "static_assert.hpp"
#include <algorithm>
namespace hull::algorithms::details {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain_impl(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
// Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate)
std::sort(first, last, [](const auto& p1, const auto& p2) {
return (x(p1) < x(p2) || (hull::equals(x(p1), x(p2)) && y(p1) < y(p2)));
});
std::size_t k{};
auto no_counter_clockwise = [&k, first, first2](auto i) {
return cross(*(first2 + (k - 2)), *(first2 + (k - 1)), *(first + i)) <= 0;
};
auto copy = [&k, first, first2](auto i) {
*(first2 + k) = *(first + i);
k++;
};
const auto N = std::distance(first, last);
// Lower hull
for (int i{}; i < N; i++) {
while (k >= 2 && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
// Upper hull
auto t = k + 1;
for (int i{static_cast<int>(N - 2)}; i >= 0; i--) {
while (k >= t && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
return first2 + (k - 1);
}
}
namespace hull::algorithms {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
static_assert_is_random_access_iterator_to_point<RandomIt1>();
static_assert_is_random_access_iterator_to_point<RandomIt2>();
const auto N = std::distance(first, last);
if (N <= 1) {
return std::copy(first, last, first2);
}
return details::monotone_chain_impl(first, last, first2);
}
}
namespace hull {
/**
* Compile-time enumeration to choose the
* algorithm thanks to a policy approach.
* @param monotone_chain_t - Monotone Chain algorithm.
*/
struct monotone_chain_t {};
/**
* Algorithms policies to choose an overload.
* @param monotone_chain - Monotone Chain algorithm.
*/
namespace choice {
static constexpr const monotone_chain_t monotone_chain{};
}
/**
* Overload of iterator-based convex hull computation for Monotone Chain.
* Note that the input is modified.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* It is unfortunately not possible to use a std::back_insert_iterator.
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* destination container of points.
*/
template <typename RandomIt1, typename RandomIt2>
auto compute_convex_hull(monotone_chain_t policy, RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
using value_type = typename std::iterator_traits<RandomIt2>::value_type;
std::fill_n(first2, 2 * std::distance(first, last), value_type{});
return algorithms::monotone_chain(first, last, first2);
}
namespace convex {
/**
* Overload of container-based convex hull computation for Monotone Chain.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(4 * N).
* @param c1 - the input container.
* @param c2 - the destination container.
*/
template <typename TContainer1, typename TContainer2>
void compute(monotone_chain_t policy, TContainer1 c1, TContainer2& c2) {
c2.resize(2 * c1.size());
std::fill(std::begin(c2), std::end(c2), typename TContainer2::value_type{});
auto last = hull::algorithms::monotone_chain(std::begin(c1), std::end(c1), std::begin(c2));
c2.erase(last, std::end(c2));
}
}
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "VLCThumbnailer.h"
#include <cstring>
#ifdef WITH_JPEG
#include <jpeglib.h>
#if ( !defined(JPEG_LIB_VERSION_MAJOR) && !defined(JPEG_LIB_VERSION_MINOR) ) || \
( JPEG_LIB_VERSION_MAJOR <= 8 && JPEG_LIB_VERSION_MINOR < 4 )
//FIXME: I don't think we can expect this to work without VLC outputing BGR...
#define JPEG_COLORSPACE JCS_EXT_BGR
#else
#define JPEG_COLORSPACE JCS_RGB
#endif
#elif defined(WITH_EVAS)
#include <Evas_Engine_Buffer.h>
#endif
#include <setjmp.h>
#include "IMedia.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
VLCThumbnailer::VLCThumbnailer(const VLC::Instance &vlc)
: m_instance( vlc )
, m_cb( nullptr )
, m_ml( nullptr )
#ifdef WITH_EVAS
, m_canvas( nullptr, &evas_free )
#endif
, m_snapshotRequired( false )
, m_width( 0 )
, m_height( 0 )
, m_prevSize( 0 )
{
#ifdef WITH_EVAS
static int fakeBuffer;
evas_init();
auto method = evas_render_method_lookup("buffer");
m_canvas.reset( evas_new() );
if ( m_canvas == nullptr )
throw std::runtime_error( "Failed to allocate canvas" );
evas_output_method_set( m_canvas.get(), method );
evas_output_size_set(m_canvas.get(), 1, 1 );
evas_output_viewport_set( m_canvas.get(), 0, 0, 1, 1 );
auto einfo = (Evas_Engine_Info_Buffer *)evas_engine_info_get( m_canvas.get() );
einfo->info.depth_type = EVAS_ENGINE_BUFFER_DEPTH_ARGB32;
einfo->info.dest_buffer = &fakeBuffer;
einfo->info.dest_buffer_row_bytes = 4;
einfo->info.use_color_key = 0;
einfo->info.alpha_threshold = 0;
einfo->info.func.new_update_region = NULL;
einfo->info.func.free_update_region = NULL;
evas_engine_info_set( m_canvas.get(), (Evas_Engine_Info *)einfo );
m_cropBuffer.reset( new uint8_t[ DesiredWidth * DesiredHeight * Bpp ] );
#endif
}
VLCThumbnailer::~VLCThumbnailer()
{
#ifdef WITH_EVAS
evas_shutdown();
#endif
}
bool VLCThumbnailer::initialize(IMetadataServiceCb *callback, MediaLibrary* ml)
{
m_cb = callback;
m_ml = ml;
return true;
}
unsigned int VLCThumbnailer::priority() const
{
// This needs to be lower than the VLCMetadataService, since we want to know the file type.
return 50;
}
void VLCThumbnailer::run(std::shared_ptr<Media> file, void *data )
{
if ( file->type() == IMedia::Type::UnknownType )
{
// If we don't know the file type yet, it actually looks more like a bug
// since this should run after file type deduction, and not run in case
// that step fails.
m_cb->done( file, Status::Fatal, data );
return;
}
else if ( file->type() != IMedia::Type::VideoType )
{
// There's no point in generating a thumbnail for a non-video file.
m_cb->done( file, Status::Success, data );
return;
}
else if ( file->snapshot().empty() == false )
{
LOG_INFO(file->snapshot(), " already has a snapshot" );
m_cb->done( file, Status::Success, data );
return;
}
LOG_INFO( "Generating ", file->mrl(), " thumbnail..." );
VLC::Media media( m_instance, file->mrl(), VLC::Media::FromPath );
media.addOption( ":no-audio" );
VLC::MediaPlayer mp( media );
setupVout( mp );
if ( startPlayback( file, mp, data ) == false )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail" );
return;
}
// Seek ahead to have a significant preview
if ( seekAhead( file, mp, data ) == false )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail" );
return;
}
takeSnapshot( file, mp, data );
LOG_INFO( "Done generating ", file->mrl(), " thumbnail" );
}
bool VLCThumbnailer::startPlayback(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void* data )
{
bool failed = true;
std::unique_lock<std::mutex> lock( m_mutex );
mp.eventManager().onPlaying([this, &failed]() {
std::unique_lock<std::mutex> lock( m_mutex );
failed = false;
m_cond.notify_all();
});
mp.eventManager().onEncounteredError([this]() {
std::unique_lock<std::mutex> lock( m_mutex );
m_cond.notify_all();
});
mp.play();
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&mp]() {
return mp.state() == libvlc_Playing || mp.state() == libvlc_Error;
});
if ( success == false || failed == true )
{
// In case of timeout or error, don't go any further
m_cb->done( file, Status::Error, data );
return false;
}
return true;
}
bool VLCThumbnailer::seekAhead(std::shared_ptr<Media> file, VLC::MediaPlayer& mp, void* data )
{
std::unique_lock<std::mutex> lock( m_mutex );
float pos = .0f;
auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
std::unique_lock<std::mutex> lock( m_mutex );
pos = p;
m_cond.notify_all();
});
mp.setPosition( .4f );
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
return pos >= .1f;
});
// Since we're locking a mutex for each position changed, let's unregister ASAP
event->unregister();
if ( success == false )
{
m_cb->done( file, Status::Error, data );
return false;
}
return true;
}
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
mp.setVideoFormatCallbacks(
// Setup
[this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
strcpy( chroma, VLC_FOURCC );
const float inputAR = (float)*width / *height;
m_width = DesiredWidth;
m_height = (float)m_width / inputAR + 1;
if ( m_height < DesiredHeight )
{
// Avoid downscaling too much for really wide pictures
m_width = inputAR * DesiredHeight;
m_height = DesiredHeight;
}
auto size = m_width * m_height * Bpp;
// If our buffer isn't enough anymore, reallocate a new one.
if ( size > m_prevSize )
{
m_buff.reset( new uint8_t[size] );
m_prevSize = size;
}
*width = m_width;
*height = m_height;
*pitches = m_width * Bpp;
*lines = m_height;
return 1;
},
// Cleanup
nullptr);
mp.setVideoCallbacks(
// Lock
[this](void** pp_buff) {
*pp_buff = m_buff.get();
return nullptr;
},
//unlock
[this](void*, void*const*) {
bool expected = true;
if ( m_snapshotRequired.compare_exchange_strong( expected, false ) )
{
m_cond.notify_all();
}
}
,
//display
nullptr
);
}
bool VLCThumbnailer::takeSnapshot(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void *data)
{
// lock, signal that we want a snapshot, and wait.
{
std::unique_lock<std::mutex> lock( m_mutex );
m_snapshotRequired = true;
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
// Keep waiting if the vmem thread hasn't restored m_snapshotRequired to false
return m_snapshotRequired == false;
});
if ( success == false )
{
m_cb->done( file, Status::Error, data );
return false;
}
}
mp.stop();
return compress( file, data );
}
#ifdef WITH_JPEG
struct jpegError : public jpeg_error_mgr
{
jmp_buf buff;
char message[JMSG_LENGTH_MAX];
static void jpegErrorHandler(j_common_ptr common)
{
auto error = reinterpret_cast<jpegError*>(common->err);
(*error->format_message)( common, error->message );
longjmp(error->buff, 1);
}
};
#endif
bool VLCThumbnailer::compress( std::shared_ptr<Media> file, void *data )
{
auto path = m_ml->snapshotPath();
path += "/";
path += std::to_string( file->id() ) +
#ifdef WITH_EVAS
".png";
#else
".jpg";
#endif
auto hOffset = m_width > DesiredWidth ? ( m_width - DesiredWidth ) / 2 : 0;
auto vOffset = m_height > DesiredHeight ? ( m_height - DesiredHeight ) / 2 : 0;
const auto stride = m_width * Bpp;
#ifdef WITH_JPEG
//FIXME: Abstract this away, though libjpeg requires a FILE*...
auto fOut = std::unique_ptr<FILE, int(*)(FILE*)>( fopen( path.c_str(), "wb" ), &fclose );
if ( fOut == nullptr )
{
LOG_ERROR("Failed to open snapshot file ", path);
m_cb->done( file, Status::Error, data );
return false;
}
jpeg_compress_struct compInfo;
JSAMPROW row_pointer[1];
//libjpeg's default error handling is to call exit(), which would
//be slightly problematic...
jpegError err;
compInfo.err = jpeg_std_error(&err);
err.error_exit = jpegError::jpegErrorHandler;
if ( setjmp( err.buff ) )
{
LOG_ERROR("JPEG failure: ", err.message);
jpeg_destroy_compress(&compInfo);
m_cb->done( file, Status::Error, data );
return false;
}
jpeg_create_compress(&compInfo);
jpeg_stdio_dest(&compInfo, fOut.get());
compInfo.image_width = DesiredWidth;
compInfo.image_height = DesiredHeight;
compInfo.input_components = Bpp;
compInfo.in_color_space = JPEG_COLORSPACE;
jpeg_set_defaults( &compInfo );
jpeg_set_quality( &compInfo, 85, TRUE );
jpeg_start_compress( &compInfo, TRUE );
while (compInfo.next_scanline < DesiredHeight)
{
row_pointer[0] = &m_buff[(compInfo.next_scanline + vOffset ) * stride + hOffset];
jpeg_write_scanlines(&compInfo, row_pointer, 1);
}
jpeg_finish_compress(&compInfo);
jpeg_destroy_compress(&compInfo);
#elif defined(WITH_EVAS)
auto evas_obj = std::unique_ptr<Evas_Object, void(*)(Evas_Object*)>( evas_object_image_add( m_canvas.get() ), evas_object_del );
if ( evas_obj == nullptr )
return false;
uint8_t *p_buff = m_buff.get();
if ( DesiredWidth != m_width )
{
p_buff += vOffset * stride;
for ( auto y = 0u; y < DesiredHeight; ++y )
{
memcpy( m_cropBuffer.get() + y * DesiredWidth * Bpp, p_buff + (hOffset * Bpp), DesiredWidth * Bpp );
p_buff += stride;
}
vOffset = 0;
p_buff = m_cropBuffer.get();
}
evas_object_image_colorspace_set( evas_obj.get(), EVAS_COLORSPACE_ARGB8888 );
evas_object_image_size_set( evas_obj.get(), DesiredWidth, DesiredHeight );
evas_object_image_data_set( evas_obj.get(), p_buff + vOffset * stride );
evas_object_image_save( evas_obj.get(), path.c_str(), NULL, "quality=100 compress=9");
#else
#error FIXME
#endif
file->setSnapshot( path );
m_cb->done( file, Status::Success, data );
return true;
}
<commit_msg>VLCThumbnailer: Fix error detection<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#include "VLCThumbnailer.h"
#include <cstring>
#ifdef WITH_JPEG
#include <jpeglib.h>
#if ( !defined(JPEG_LIB_VERSION_MAJOR) && !defined(JPEG_LIB_VERSION_MINOR) ) || \
( JPEG_LIB_VERSION_MAJOR <= 8 && JPEG_LIB_VERSION_MINOR < 4 )
//FIXME: I don't think we can expect this to work without VLC outputing BGR...
#define JPEG_COLORSPACE JCS_EXT_BGR
#else
#define JPEG_COLORSPACE JCS_RGB
#endif
#elif defined(WITH_EVAS)
#include <Evas_Engine_Buffer.h>
#endif
#include <setjmp.h>
#include "IMedia.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
VLCThumbnailer::VLCThumbnailer(const VLC::Instance &vlc)
: m_instance( vlc )
, m_cb( nullptr )
, m_ml( nullptr )
#ifdef WITH_EVAS
, m_canvas( nullptr, &evas_free )
#endif
, m_snapshotRequired( false )
, m_width( 0 )
, m_height( 0 )
, m_prevSize( 0 )
{
#ifdef WITH_EVAS
static int fakeBuffer;
evas_init();
auto method = evas_render_method_lookup("buffer");
m_canvas.reset( evas_new() );
if ( m_canvas == nullptr )
throw std::runtime_error( "Failed to allocate canvas" );
evas_output_method_set( m_canvas.get(), method );
evas_output_size_set(m_canvas.get(), 1, 1 );
evas_output_viewport_set( m_canvas.get(), 0, 0, 1, 1 );
auto einfo = (Evas_Engine_Info_Buffer *)evas_engine_info_get( m_canvas.get() );
einfo->info.depth_type = EVAS_ENGINE_BUFFER_DEPTH_ARGB32;
einfo->info.dest_buffer = &fakeBuffer;
einfo->info.dest_buffer_row_bytes = 4;
einfo->info.use_color_key = 0;
einfo->info.alpha_threshold = 0;
einfo->info.func.new_update_region = NULL;
einfo->info.func.free_update_region = NULL;
evas_engine_info_set( m_canvas.get(), (Evas_Engine_Info *)einfo );
m_cropBuffer.reset( new uint8_t[ DesiredWidth * DesiredHeight * Bpp ] );
#endif
}
VLCThumbnailer::~VLCThumbnailer()
{
#ifdef WITH_EVAS
evas_shutdown();
#endif
}
bool VLCThumbnailer::initialize(IMetadataServiceCb *callback, MediaLibrary* ml)
{
m_cb = callback;
m_ml = ml;
return true;
}
unsigned int VLCThumbnailer::priority() const
{
// This needs to be lower than the VLCMetadataService, since we want to know the file type.
return 50;
}
void VLCThumbnailer::run(std::shared_ptr<Media> file, void *data )
{
if ( file->type() == IMedia::Type::UnknownType )
{
// If we don't know the file type yet, it actually looks more like a bug
// since this should run after file type deduction, and not run in case
// that step fails.
m_cb->done( file, Status::Fatal, data );
return;
}
else if ( file->type() != IMedia::Type::VideoType )
{
// There's no point in generating a thumbnail for a non-video file.
m_cb->done( file, Status::Success, data );
return;
}
else if ( file->snapshot().empty() == false )
{
LOG_INFO(file->snapshot(), " already has a snapshot" );
m_cb->done( file, Status::Success, data );
return;
}
LOG_INFO( "Generating ", file->mrl(), " thumbnail..." );
VLC::Media media( m_instance, file->mrl(), VLC::Media::FromPath );
media.addOption( ":no-audio" );
VLC::MediaPlayer mp( media );
setupVout( mp );
if ( startPlayback( file, mp, data ) == false )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail" );
return;
}
// Seek ahead to have a significant preview
if ( seekAhead( file, mp, data ) == false )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail" );
return;
}
takeSnapshot( file, mp, data );
LOG_INFO( "Done generating ", file->mrl(), " thumbnail" );
}
bool VLCThumbnailer::startPlayback(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void* data )
{
std::unique_lock<std::mutex> lock( m_mutex );
mp.eventManager().onPlaying([this]() {
std::unique_lock<std::mutex> lock( m_mutex );
m_cond.notify_all();
});
mp.eventManager().onEncounteredError([this]() {
std::unique_lock<std::mutex> lock( m_mutex );
m_cond.notify_all();
});
mp.play();
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&mp]() {
auto s = mp.state();
return s == libvlc_Playing || s == libvlc_Error || s == libvlc_Ended;
});
if ( success == false || mp.state() == libvlc_Error || mp.state() == libvlc_Ended )
{
// In case of timeout or error, don't go any further
m_cb->done( file, Status::Error, data );
return false;
}
return true;
}
bool VLCThumbnailer::seekAhead(std::shared_ptr<Media> file, VLC::MediaPlayer& mp, void* data )
{
std::unique_lock<std::mutex> lock( m_mutex );
float pos = .0f;
auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
std::unique_lock<std::mutex> lock( m_mutex );
pos = p;
m_cond.notify_all();
});
mp.setPosition( .4f );
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
return pos >= .1f;
});
// Since we're locking a mutex for each position changed, let's unregister ASAP
event->unregister();
if ( success == false )
{
m_cb->done( file, Status::Error, data );
return false;
}
return true;
}
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
mp.setVideoFormatCallbacks(
// Setup
[this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
strcpy( chroma, VLC_FOURCC );
const float inputAR = (float)*width / *height;
m_width = DesiredWidth;
m_height = (float)m_width / inputAR + 1;
if ( m_height < DesiredHeight )
{
// Avoid downscaling too much for really wide pictures
m_width = inputAR * DesiredHeight;
m_height = DesiredHeight;
}
auto size = m_width * m_height * Bpp;
// If our buffer isn't enough anymore, reallocate a new one.
if ( size > m_prevSize )
{
m_buff.reset( new uint8_t[size] );
m_prevSize = size;
}
*width = m_width;
*height = m_height;
*pitches = m_width * Bpp;
*lines = m_height;
return 1;
},
// Cleanup
nullptr);
mp.setVideoCallbacks(
// Lock
[this](void** pp_buff) {
*pp_buff = m_buff.get();
return nullptr;
},
//unlock
[this](void*, void*const*) {
bool expected = true;
if ( m_snapshotRequired.compare_exchange_strong( expected, false ) )
{
m_cond.notify_all();
}
}
,
//display
nullptr
);
}
bool VLCThumbnailer::takeSnapshot(std::shared_ptr<Media> file, VLC::MediaPlayer &mp, void *data)
{
// lock, signal that we want a snapshot, and wait.
{
std::unique_lock<std::mutex> lock( m_mutex );
m_snapshotRequired = true;
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
// Keep waiting if the vmem thread hasn't restored m_snapshotRequired to false
return m_snapshotRequired == false;
});
if ( success == false )
{
m_cb->done( file, Status::Error, data );
return false;
}
}
mp.stop();
return compress( file, data );
}
#ifdef WITH_JPEG
struct jpegError : public jpeg_error_mgr
{
jmp_buf buff;
char message[JMSG_LENGTH_MAX];
static void jpegErrorHandler(j_common_ptr common)
{
auto error = reinterpret_cast<jpegError*>(common->err);
(*error->format_message)( common, error->message );
longjmp(error->buff, 1);
}
};
#endif
bool VLCThumbnailer::compress( std::shared_ptr<Media> file, void *data )
{
auto path = m_ml->snapshotPath();
path += "/";
path += std::to_string( file->id() ) +
#ifdef WITH_EVAS
".png";
#else
".jpg";
#endif
auto hOffset = m_width > DesiredWidth ? ( m_width - DesiredWidth ) / 2 : 0;
auto vOffset = m_height > DesiredHeight ? ( m_height - DesiredHeight ) / 2 : 0;
const auto stride = m_width * Bpp;
#ifdef WITH_JPEG
//FIXME: Abstract this away, though libjpeg requires a FILE*...
auto fOut = std::unique_ptr<FILE, int(*)(FILE*)>( fopen( path.c_str(), "wb" ), &fclose );
if ( fOut == nullptr )
{
LOG_ERROR("Failed to open snapshot file ", path);
m_cb->done( file, Status::Error, data );
return false;
}
jpeg_compress_struct compInfo;
JSAMPROW row_pointer[1];
//libjpeg's default error handling is to call exit(), which would
//be slightly problematic...
jpegError err;
compInfo.err = jpeg_std_error(&err);
err.error_exit = jpegError::jpegErrorHandler;
if ( setjmp( err.buff ) )
{
LOG_ERROR("JPEG failure: ", err.message);
jpeg_destroy_compress(&compInfo);
m_cb->done( file, Status::Error, data );
return false;
}
jpeg_create_compress(&compInfo);
jpeg_stdio_dest(&compInfo, fOut.get());
compInfo.image_width = DesiredWidth;
compInfo.image_height = DesiredHeight;
compInfo.input_components = Bpp;
compInfo.in_color_space = JPEG_COLORSPACE;
jpeg_set_defaults( &compInfo );
jpeg_set_quality( &compInfo, 85, TRUE );
jpeg_start_compress( &compInfo, TRUE );
while (compInfo.next_scanline < DesiredHeight)
{
row_pointer[0] = &m_buff[(compInfo.next_scanline + vOffset ) * stride + hOffset];
jpeg_write_scanlines(&compInfo, row_pointer, 1);
}
jpeg_finish_compress(&compInfo);
jpeg_destroy_compress(&compInfo);
#elif defined(WITH_EVAS)
auto evas_obj = std::unique_ptr<Evas_Object, void(*)(Evas_Object*)>( evas_object_image_add( m_canvas.get() ), evas_object_del );
if ( evas_obj == nullptr )
return false;
uint8_t *p_buff = m_buff.get();
if ( DesiredWidth != m_width )
{
p_buff += vOffset * stride;
for ( auto y = 0u; y < DesiredHeight; ++y )
{
memcpy( m_cropBuffer.get() + y * DesiredWidth * Bpp, p_buff + (hOffset * Bpp), DesiredWidth * Bpp );
p_buff += stride;
}
vOffset = 0;
p_buff = m_cropBuffer.get();
}
evas_object_image_colorspace_set( evas_obj.get(), EVAS_COLORSPACE_ARGB8888 );
evas_object_image_size_set( evas_obj.get(), DesiredWidth, DesiredHeight );
evas_object_image_data_set( evas_obj.get(), p_buff + vOffset * stride );
evas_object_image_save( evas_obj.get(), path.c_str(), NULL, "quality=100 compress=9");
#else
#error FIXME
#endif
file->setSnapshot( path );
m_cb->done( file, Status::Success, data );
return true;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
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 author 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.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/config.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef TORRENT_WINDOWS
// windows part
#include "libtorrent/utf8.hpp"
#include <windows.h>
#include <winioctl.h>
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// posix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
#ifdef TORRENT_WINDOWS
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
#ifdef TORRENT_WINDOWS
const file::open_mode file::in(GENERIC_READ);
const file::open_mode file::out(GENERIC_WRITE);
const file::seek_mode file::begin(FILE_BEGIN);
const file::seek_mode file::end(FILE_END);
#else
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(SEEK_SET);
const file::seek_mode file::end(SEEK_END);
#endif
file::file()
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{}
file::file(fs::path const& path, open_mode mode, error_code& ec)
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{
open(path, mode, ec);
}
file::~file()
{
close();
}
bool file::open(fs::path const& path, open_mode mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
#ifdef UNICODE
std::wstring file_path(safe_convert(path.native_file_string()));
#else
std::string file_path = utf8_native(path.native_file_string());
#endif
m_file_handle = CreateFile(
file_path.c_str()
, mode.m_mask
, FILE_SHARE_READ
, 0
, (mode & out)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
if (m_file_handle == INVALID_HANDLE_VALUE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
// try to make the file sparse if supported
if (mode & out)
{
DWORD temp;
::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0
, 0, 0, &temp, 0);
}
#else
// rely on default umask to filter x and w permissions
// for group and others
m_fd = ::open(path.native_file_string().c_str()
, map_open_mode(mode.m_mask), S_IRWXU | S_IRWXG | S_IRWXO);
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
#ifndef NDEBUG
m_open_mode = mode;
#endif
TORRENT_ASSERT(is_open());
return true;
}
bool file::is_open() const
{
#ifdef TORRENT_WINDOWS
return m_file_handle != INVALID_HANDLE_VALUE;
#else
return m_fd != -1;
#endif
}
void file::close()
{
#ifdef TORRENT_WINDOWS
if (m_file_handle == INVALID_HANDLE_VALUE) return;
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
#else
if (m_fd == -1) return;
::close(m_fd);
m_fd = -1;
#endif
#ifndef NDEBUG
m_open_mode = 0;
#endif
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & in) == in);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
TORRENT_ASSERT(DWORD(num_bytes) == num_bytes);
DWORD ret = 0;
if (num_bytes != 0)
{
if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & out) == out);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
DWORD ret = 0;
if (num_bytes != 0)
{
if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
bool file::set_size(size_type s, error_code& ec)
{
TORRENT_ASSERT(is_open());
TORRENT_ASSERT(s >= 0);
#ifdef TORRENT_WINDOWS
size_type pos = tell(ec);
if (ec) return false;
seek(s, begin, ec);
if (ec) return false;
if (::SetEndOfFile(m_file_handle) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
return true;
}
size_type file::seek(size_type offset, seek_mode m, error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = offset;
if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret = lseek(m_fd, offset, m.m_val);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
size_type file::tell(error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (SetFilePointerEx(m_file_handle, offs, &offs
, FILE_CURRENT) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret;
ret = lseek(m_fd, 0, SEEK_CUR);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
}
<commit_msg>don't set executable permission of files<commit_after>/*
Copyright (c) 2003, Arvid Norberg
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 author 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.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/config.hpp"
#include <boost/scoped_ptr.hpp>
#ifdef TORRENT_WINDOWS
// windows part
#include "libtorrent/utf8.hpp"
#include <windows.h>
#include <winioctl.h>
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// posix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#include <cstring>
#include <vector>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
#ifdef TORRENT_WINDOWS
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
#ifdef TORRENT_WINDOWS
const file::open_mode file::in(GENERIC_READ);
const file::open_mode file::out(GENERIC_WRITE);
const file::seek_mode file::begin(FILE_BEGIN);
const file::seek_mode file::end(FILE_END);
#else
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(SEEK_SET);
const file::seek_mode file::end(SEEK_END);
#endif
file::file()
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{}
file::file(fs::path const& path, open_mode mode, error_code& ec)
#ifdef TORRENT_WINDOWS
: m_file_handle(INVALID_HANDLE_VALUE)
#else
: m_fd(-1)
#endif
#ifndef NDEBUG
, m_open_mode(0)
#endif
{
open(path, mode, ec);
}
file::~file()
{
close();
}
bool file::open(fs::path const& path, open_mode mode, error_code& ec)
{
close();
#ifdef TORRENT_WINDOWS
#ifdef UNICODE
std::wstring file_path(safe_convert(path.native_file_string()));
#else
std::string file_path = utf8_native(path.native_file_string());
#endif
m_file_handle = CreateFile(
file_path.c_str()
, mode.m_mask
, FILE_SHARE_READ
, 0
, (mode & out)?OPEN_ALWAYS:OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, 0);
if (m_file_handle == INVALID_HANDLE_VALUE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
// try to make the file sparse if supported
if (mode & out)
{
DWORD temp;
::DeviceIoControl(m_file_handle, FSCTL_SET_SPARSE, 0, 0
, 0, 0, &temp, 0);
}
#else
// rely on default umask to filter x and w permissions
// for group and others
int permissions = S_IRUSR | S_IWUSR
| S_IRGRP | S_IWGRP
| S_IROTH | S_IWOTH;
m_fd = ::open(path.native_file_string().c_str()
, map_open_mode(mode.m_mask), permissions);
if (m_fd == -1)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
#ifndef NDEBUG
m_open_mode = mode;
#endif
TORRENT_ASSERT(is_open());
return true;
}
bool file::is_open() const
{
#ifdef TORRENT_WINDOWS
return m_file_handle != INVALID_HANDLE_VALUE;
#else
return m_fd != -1;
#endif
}
void file::close()
{
#ifdef TORRENT_WINDOWS
if (m_file_handle == INVALID_HANDLE_VALUE) return;
CloseHandle(m_file_handle);
m_file_handle = INVALID_HANDLE_VALUE;
#else
if (m_fd == -1) return;
::close(m_fd);
m_fd = -1;
#endif
#ifndef NDEBUG
m_open_mode = 0;
#endif
}
size_type file::read(char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & in) == in);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
TORRENT_ASSERT(DWORD(num_bytes) == num_bytes);
DWORD ret = 0;
if (num_bytes != 0)
{
if (ReadFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::read(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
size_type file::write(const char* buf, size_type num_bytes, error_code& ec)
{
TORRENT_ASSERT((m_open_mode & out) == out);
TORRENT_ASSERT(buf);
TORRENT_ASSERT(num_bytes >= 0);
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
DWORD ret = 0;
if (num_bytes != 0)
{
if (WriteFile(m_file_handle, buf, (DWORD)num_bytes, &ret, 0) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
}
#else
size_type ret = ::write(m_fd, buf, num_bytes);
if (ret == -1) ec = error_code(errno, get_posix_category());
#endif
return ret;
}
bool file::set_size(size_type s, error_code& ec)
{
TORRENT_ASSERT(is_open());
TORRENT_ASSERT(s >= 0);
#ifdef TORRENT_WINDOWS
size_type pos = tell(ec);
if (ec) return false;
seek(s, begin, ec);
if (ec) return false;
if (::SetEndOfFile(m_file_handle) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return false;
}
#else
if (ftruncate(m_fd, s) < 0)
{
ec = error_code(errno, get_posix_category());
return false;
}
#endif
return true;
}
size_type file::seek(size_type offset, seek_mode m, error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = offset;
if (SetFilePointerEx(m_file_handle, offs, &offs, m.m_val) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret = lseek(m_fd, offset, m.m_val);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
size_type file::tell(error_code& ec)
{
TORRENT_ASSERT(is_open());
#ifdef TORRENT_WINDOWS
LARGE_INTEGER offs;
offs.QuadPart = 0;
// is there any other way to get offset?
if (SetFilePointerEx(m_file_handle, offs, &offs
, FILE_CURRENT) == FALSE)
{
ec = error_code(GetLastError(), get_system_category());
return -1;
}
return offs.QuadPart;
#else
size_type ret;
ret = lseek(m_fd, 0, SEEK_CUR);
if (ret < 0) ec = error_code(errno, get_posix_category());
return ret;
#endif
}
}
<|endoftext|> |
<commit_before>/**
* Implementation of Monotone Chain for convex hull
* computation of a set of points in the 2d space.
*/
#ifndef monotone_chain_h
#define monotone_chain_h
#include "angle.hpp"
#include "point_concept.hpp"
#include "static_assert.hpp"
#include <algorithm>
namespace hull::algorithms::details {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain_impl(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
// Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate)
std::sort(first, last, [](const auto& p1, const auto& p2) {
return (x(p1) < x(p2) || (hull::equals(x(p1), x(p2)) && y(p1) < y(p2)));
});
std::size_t k{};
auto no_counter_clockwise = [&k, first, first2](auto i) {
return cross(*(first2 + (k - 2)), *(first2 + (k - 1)), *(first + i)) <= 0;
};
auto copy = [&k, first, first2](auto i) {
*(first2 + k) = *(first + i);
k++;
};
const auto N = std::distance(first, last);
// Lower hull
for (int i{}; i < N; i++) {
while (k >= 2 && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
// Upper hull
auto t = k + 1;
for (int i{static_cast<int>(N - 2)}; i >= 0; i--) {
while (k >= t && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
return first2 + (k - 1);
}
}
namespace hull::algorithms {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
static_assert_is_random_access_iterator_to_point<RandomIt1>();
static_assert_is_random_access_iterator_to_point<RandomIt2>();
const auto N = std::distance(first, last);
if (N <= 1) {
return std::copy(first, last, first2);
}
return details::monotone_chain_impl(first, last, first2);
}
}
namespace hull {
/**
* Compile-time enumeration to choose the
* algorithm thanks to a policy approach.
* @param monotone_chain_t - Monotone Chain algorithm.
*/
struct monotone_chain_t {};
/**
* Algorithms policies to choose an overload.
* @param monotone_chain - Monotone Chain algorithm.
*/
namespace choice {
static constexpr const monotone_chain_t monotone_chain{};
}
/**
* Overload of iterator-based convex hull computation for Monotone Chain.
* Note that the input is modified.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* It is unfortunately not possible to use a std::back_insert_iterator.
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* destination container of points.
*/
template <typename RandomIt1, typename RandomIt2>
auto compute_convex_hull(monotone_chain_t policy, RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
using value_type = typename std::iterator_traits<RandomIt2>::value_type;
std::fill_n(first2, 2 * std::distance(first, last), value_type{});
return algorithms::monotone_chain(first, last, first2);
}
namespace convex {
/**
* Overload of container-based convex hull computation for Monotone Chain.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(4 * N).
* @param c1 - the input container.
* @param c2 - the destination container.
*/
template <typename TContainer1, typename TContainer2>
void compute(monotone_chain_t policy, TContainer1 c1, TContainer2& c2) {
c2.resize(2 * c1.size());
std::fill(std::begin(c2), std::end(c2), typename TContainer2::value_type{});
auto last = hull::algorithms::monotone_chain(std::begin(c1), std::end(c1), std::begin(c2));
c2.erase(last, std::end(c2));
}
}
}
#endif
<commit_msg>Continue refactoring Monotone Chain.<commit_after>/**
* Implementation of Monotone Chain for convex hull
* computation of a set of points in the 2d space.
*/
#ifndef monotone_chain_h
#define monotone_chain_h
#include "angle.hpp"
#include "point_concept.hpp"
#include "static_assert.hpp"
#include <algorithm>
namespace hull::algorithms::details::monotone {
/**
* Sort the points of P by x-coordinate (in case of a tie, sort by y-coordinate).
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
*/
template <typename RandomIt>
void sort(RandomIt first, RandomIt last) {
std::sort(first, last, [](const auto& p1, const auto& p2) {
return (x(p1) < x(p2) || (hull::equals(x(p1), x(p2)) && y(p1) < y(p2)));
});
}
/**
* Builds a lambda function which tells whether a given point
* (the one at index i with respect to first iterator) is on the
* left (that is, not counter-clockwise) of the vector made of
* the last 2 points on the result convex hull.
* @param k - the index of the last point on the convex hull.
* @param first - iterator to the first point in the input container of points.
* @param first2 - iterator to the first point in the resulting convex hull.
* @return - a lambda function which takes an index i and tells whether
* the point at first+i is on the left of vector first2+(k-2) first2+(k-1).
*/
template <typename RandomIt1, typename RandomIt2>
auto no_counter_clockwise(std::size_t& k, RandomIt1 first, RandomIt2 first2) {
return [&k, first, first2](auto i) {
return cross(*(first2 + (k - 2)), *(first2 + (k - 1)), *(first + i)) <= 0;
};
};
}
namespace hull::algorithms::details {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain_impl(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
monotone::sort(first, last);
std::size_t k{};
auto no_counter_clockwise = monotone::no_counter_clockwise(k, first, first2);
auto copy = [&k, first, first2](auto i) {
*(first2 + k) = *(first + i);
k++;
};
const auto N = std::distance(first, last);
// Lower hull
for (int i{}; i < N; i++) {
while (k >= 2 && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
// Upper hull
auto t = k + 1;
for (int i{static_cast<int>(N - 2)}; i >= 0; i--) {
while (k >= t && no_counter_clockwise(i)) {
k--;
}
copy(i);
}
return first2 + (k - 1);
}
}
namespace hull::algorithms {
/**
* Compute the convex hull of a container of points following
* the Monotone Chain algorithm. This algorithm does not work in-place, but
* it still modifies the input points (it sorts them by x-coordinates).
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* Reference: https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* provided container of points.
*/
template <typename RandomIt1, typename RandomIt2>
RandomIt2 monotone_chain(RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
static_assert_is_random_access_iterator_to_point<RandomIt1>();
static_assert_is_random_access_iterator_to_point<RandomIt2>();
const auto N = std::distance(first, last);
if (N <= 1) {
return std::copy(first, last, first2);
}
return details::monotone_chain_impl(first, last, first2);
}
}
namespace hull {
/**
* Compile-time enumeration to choose the
* algorithm thanks to a policy approach.
* @param monotone_chain_t - Monotone Chain algorithm.
*/
struct monotone_chain_t {};
/**
* Algorithms policies to choose an overload.
* @param monotone_chain - Monotone Chain algorithm.
*/
namespace choice {
static constexpr const monotone_chain_t monotone_chain{};
}
/**
* Overload of iterator-based convex hull computation for Monotone Chain.
* Note that the input is modified.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(3 * N).
* It is unfortunately not possible to use a std::back_insert_iterator.
* @param first - the random access iterator to the first point of the container.
* @param last - the random access iterator to the one-past last point of the container.
* @param first2 - the random access iterator to the first point of the destination container.
* @return - the iterator to the last element forming the convex hull of the
* destination container of points.
*/
template <typename RandomIt1, typename RandomIt2>
auto compute_convex_hull(monotone_chain_t policy, RandomIt1 first, RandomIt1 last, RandomIt2 first2) {
using value_type = typename std::iterator_traits<RandomIt2>::value_type;
std::fill_n(first2, 2 * std::distance(first, last), value_type{});
return algorithms::monotone_chain(first, last, first2);
}
namespace convex {
/**
* Overload of container-based convex hull computation for Monotone Chain.
* Average time complexity: O(N * log(N)) where N is the number of
* points.
* Average space complexity: O(4 * N).
* @param c1 - the input container.
* @param c2 - the destination container.
*/
template <typename TContainer1, typename TContainer2>
void compute(monotone_chain_t policy, TContainer1 c1, TContainer2& c2) {
c2.resize(2 * c1.size());
std::fill(std::begin(c2), std::end(c2), typename TContainer2::value_type{});
auto last = hull::algorithms::monotone_chain(std::begin(c1), std::end(c1), std::begin(c2));
c2.erase(last, std::end(c2));
}
}
}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "VLCThumbnailer.h"
#include "Media.h"
#include "File.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/VLCInstance.h"
#include "utils/ModificationsNotifier.h"
#ifdef HAVE_JPEG
#include "imagecompressors/JpegCompressor.h"
#elif defined(HAVE_EVAS)
#include "imagecompressors/EvasCompressor.h"
#else
#error No image compressor available
#endif
namespace medialibrary
{
VLCThumbnailer::VLCThumbnailer()
: m_instance( VLCInstance::get() )
, m_thumbnailRequired( false )
, m_width( 0 )
, m_height( 0 )
, m_prevSize( 0 )
{
#ifdef HAVE_JPEG
m_compressor.reset( new JpegCompressor );
#elif defined(HAVE_EVAS)
m_compressor.reset( new EvasCompressor );
#endif
}
bool VLCThumbnailer::initialize()
{
return true;
}
File::ParserStep VLCThumbnailer::step() const
{
return File::ParserStep::Thumbnailer;
}
parser::Task::Status VLCThumbnailer::run( parser::Task& task )
{
auto media = task.media;
auto file = task.file;
if ( media->type() == IMedia::Type::AudioType )
{
// There's no point in generating a thumbnail for a non-video media.
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
return parser::Task::Status::Success;
}
LOG_INFO( "Generating ", file->mrl(), " thumbnail..." );
if ( task.vlcMedia.isValid() == false )
{
auto fromType = file->mrl().find( "://" ) != std::string::npos ? VLC::Media::FromType::FromLocation :
VLC::Media::FromType::FromPath;
task.vlcMedia = VLC::Media( m_instance, file->mrl(), fromType );
}
task.vlcMedia.addOption( ":no-audio" );
task.vlcMedia.addOption( ":no-osd" );
task.vlcMedia.addOption( ":no-spu" );
task.vlcMedia.addOption( ":input-fast-seek" );
VLC::MediaPlayer mp( task.vlcMedia );
setupVout( mp );
auto res = startPlayback( task, mp );
if ( res != parser::Task::Status::Success )
{
// If the media became an audio file, it's not an error
if ( task.media->type() == Media::Type::AudioType )
{
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
LOG_INFO( file->mrl(), " type has changed to Audio. Skipping thumbnail generation" );
return parser::Task::Status::Success;
}
// Otherwise, we failed to start the playback and this is an error indeed
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Can't start playback" );
return res;
}
// Seek ahead to have a significant preview
res = seekAhead( mp );
if ( res != parser::Task::Status::Success )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Failed to seek ahead" );
return res;
}
res = takeThumbnail( media, file, mp );
if ( res != parser::Task::Status::Success )
return res;
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
return parser::Task::Status::Success;
}
parser::Task::Status VLCThumbnailer::startPlayback( parser::Task& task, VLC::MediaPlayer &mp )
{
// Use a copy of the event manager to automatically unregister all events as soon
// as we leave this method.
auto em = mp.eventManager();
bool hasVideoTrack = false;
bool failedToStart = false;
em.onESAdded([this, &hasVideoTrack]( libvlc_track_type_t type, int ) {
if ( type == libvlc_track_video )
{
std::lock_guard<compat::Mutex> lock( m_mutex );
hasVideoTrack = true;
m_cond.notify_all();
}
});
em.onEncounteredError([this, &failedToStart]() {
std::lock_guard<compat::Mutex> lock( m_mutex );
failedToStart = true;
m_cond.notify_all();
});
std::unique_lock<compat::Mutex> lock( m_mutex );
mp.play();
bool success = m_cond.wait_for( lock, std::chrono::seconds( 1 ), [&failedToStart, &hasVideoTrack]() {
return failedToStart == true || hasVideoTrack == true;
});
// If a video track was added, we can continue right away.
if ( hasVideoTrack == true )
{
assert( success == true );
return parser::Task::Status::Success;
}
// In case the playback failed, we probably won't fetch anything interesting anyway.
if ( failedToStart == true )
return parser::Task::Status::Fatal;
// We are now in the case of a timeout: No failure, but no video track either.
// The file might be an audio file we haven't detected yet:
if ( task.media->type() == Media::Type::UnknownType )
{
task.media->setType( Media::Type::AudioType );
if ( task.media->save() == false )
return parser::Task::Status::Fatal;
// We still return an error since we don't want to attempt the thumbnail generation for a
// file without video tracks
}
return parser::Task::Status::Fatal;
}
parser::Task::Status VLCThumbnailer::seekAhead( VLC::MediaPlayer& mp )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
float pos = .0f;
auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
std::unique_lock<compat::Mutex> lock( m_mutex );
pos = p;
m_cond.notify_all();
});
mp.setPosition( .4f );
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
return pos >= .1f;
});
// Since we're locking a mutex for each position changed, let's unregister ASAP
event->unregister();
if ( success == false )
return parser::Task::Status::Fatal;
return parser::Task::Status::Success;
}
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
mp.setVideoFormatCallbacks(
// Setup
[this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
strcpy( chroma, m_compressor->fourCC() );
const float inputAR = (float)*width / *height;
m_width = DesiredWidth;
m_height = (float)m_width / inputAR + 1;
if ( m_height < DesiredHeight )
{
// Avoid downscaling too much for really wide pictures
m_width = inputAR * DesiredHeight;
m_height = DesiredHeight;
}
auto size = m_width * m_height * m_compressor->bpp();
// If our buffer isn't enough anymore, reallocate a new one.
if ( size > m_prevSize )
{
m_buff.reset( new uint8_t[size] );
m_prevSize = size;
}
*width = m_width;
*height = m_height;
*pitches = m_width * m_compressor->bpp();
*lines = m_height;
return 1;
},
// Cleanup
nullptr);
mp.setVideoCallbacks(
// Lock
[this](void** pp_buff) {
*pp_buff = m_buff.get();
return nullptr;
},
//unlock
nullptr,
//display
[this](void*) {
bool expected = true;
if ( m_thumbnailRequired.compare_exchange_strong( expected, false ) )
{
m_cond.notify_all();
}
}
);
}
parser::Task::Status VLCThumbnailer::takeThumbnail( std::shared_ptr<Media> media, std::shared_ptr<File> file, VLC::MediaPlayer &mp )
{
// lock, signal that we want a thumbnail, and wait.
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_thumbnailRequired = true;
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
// Keep waiting if the vmem thread hasn't restored m_thumbnailRequired to false
return m_thumbnailRequired == false;
});
if ( success == false )
{
LOG_WARN( "Timed out while computing ", file->mrl(), " snapshot" );
return parser::Task::Status::Fatal;
}
}
mp.stop();
return compress( media, file );
}
parser::Task::Status VLCThumbnailer::compress( std::shared_ptr<Media> media, std::shared_ptr<File> file )
{
auto path = m_ml->thumbnailPath();
path += "/";
path += std::to_string( media->id() ) + "." + m_compressor->extension();
auto hOffset = m_width > DesiredWidth ? ( m_width - DesiredWidth ) / 2 : 0;
auto vOffset = m_height > DesiredHeight ? ( m_height - DesiredHeight ) / 2 : 0;
if ( m_compressor->compress( m_buff.get(), path, m_width, m_height, DesiredWidth, DesiredHeight,
hOffset, vOffset ) == false )
return parser::Task::Status::Fatal;
media->setThumbnail( path );
LOG_INFO( "Done generating ", file->mrl(), " thumbnail" );
auto t = m_ml->getConn()->newTransaction();
if ( media->save() == false )
return parser::Task::Status::Fatal;
file->markStepCompleted( File::ParserStep::Thumbnailer );
if ( file->saveParserStep() == false )
return parser::Task::Status::Fatal;
t->commit();
m_notifier->notifyMediaModification( media );
return parser::Task::Status::Success;
}
const char*VLCThumbnailer::name() const
{
return "Thumbnailer";
}
uint8_t VLCThumbnailer::nbThreads() const
{
return 1;
}
}
<commit_msg>VLCThumbnailer: Start directly at the wanted position, when doable<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
*
* Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "VLCThumbnailer.h"
#include "Media.h"
#include "File.h"
#include "logging/Logger.h"
#include "MediaLibrary.h"
#include "utils/VLCInstance.h"
#include "utils/ModificationsNotifier.h"
#ifdef HAVE_JPEG
#include "imagecompressors/JpegCompressor.h"
#elif defined(HAVE_EVAS)
#include "imagecompressors/EvasCompressor.h"
#else
#error No image compressor available
#endif
namespace medialibrary
{
VLCThumbnailer::VLCThumbnailer()
: m_instance( VLCInstance::get() )
, m_thumbnailRequired( false )
, m_width( 0 )
, m_height( 0 )
, m_prevSize( 0 )
{
#ifdef HAVE_JPEG
m_compressor.reset( new JpegCompressor );
#elif defined(HAVE_EVAS)
m_compressor.reset( new EvasCompressor );
#endif
}
bool VLCThumbnailer::initialize()
{
return true;
}
File::ParserStep VLCThumbnailer::step() const
{
return File::ParserStep::Thumbnailer;
}
parser::Task::Status VLCThumbnailer::run( parser::Task& task )
{
auto media = task.media;
auto file = task.file;
if ( media->type() == IMedia::Type::AudioType )
{
// There's no point in generating a thumbnail for a non-video media.
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
return parser::Task::Status::Success;
}
LOG_INFO( "Generating ", file->mrl(), " thumbnail..." );
if ( task.vlcMedia.isValid() == false )
{
auto fromType = file->mrl().find( "://" ) != std::string::npos ? VLC::Media::FromType::FromLocation :
VLC::Media::FromType::FromPath;
task.vlcMedia = VLC::Media( m_instance, file->mrl(), fromType );
}
task.vlcMedia.addOption( ":no-audio" );
task.vlcMedia.addOption( ":no-osd" );
task.vlcMedia.addOption( ":no-spu" );
task.vlcMedia.addOption( ":input-fast-seek" );
auto duration = task.vlcMedia.duration();
if ( duration > 0 )
{
std::ostringstream ss;
// Duration is in ms, start-time in seconds, and we're aiming at 1/4th of the media
ss << ":start-time=" << duration / 4000;
task.vlcMedia.addOption( ss.str() );
}
VLC::MediaPlayer mp( task.vlcMedia );
setupVout( mp );
auto res = startPlayback( task, mp );
if ( res != parser::Task::Status::Success )
{
// If the media became an audio file, it's not an error
if ( task.media->type() == Media::Type::AudioType )
{
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
LOG_INFO( file->mrl(), " type has changed to Audio. Skipping thumbnail generation" );
return parser::Task::Status::Success;
}
// Otherwise, we failed to start the playback and this is an error indeed
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Can't start playback" );
return res;
}
if ( duration <= 0 )
{
// Seek ahead to have a significant preview
res = seekAhead( mp );
if ( res != parser::Task::Status::Success )
{
LOG_WARN( "Failed to generate ", file->mrl(), " thumbnail: Failed to seek ahead" );
return res;
}
}
res = takeThumbnail( media, file, mp );
if ( res != parser::Task::Status::Success )
return res;
task.file->markStepCompleted( File::ParserStep::Thumbnailer );
task.file->saveParserStep();
return parser::Task::Status::Success;
}
parser::Task::Status VLCThumbnailer::startPlayback( parser::Task& task, VLC::MediaPlayer &mp )
{
// Use a copy of the event manager to automatically unregister all events as soon
// as we leave this method.
auto em = mp.eventManager();
bool hasVideoTrack = false;
bool failedToStart = false;
em.onESAdded([this, &hasVideoTrack]( libvlc_track_type_t type, int ) {
if ( type == libvlc_track_video )
{
std::lock_guard<compat::Mutex> lock( m_mutex );
hasVideoTrack = true;
m_cond.notify_all();
}
});
em.onEncounteredError([this, &failedToStart]() {
std::lock_guard<compat::Mutex> lock( m_mutex );
failedToStart = true;
m_cond.notify_all();
});
std::unique_lock<compat::Mutex> lock( m_mutex );
mp.play();
bool success = m_cond.wait_for( lock, std::chrono::seconds( 1 ), [&failedToStart, &hasVideoTrack]() {
return failedToStart == true || hasVideoTrack == true;
});
// If a video track was added, we can continue right away.
if ( hasVideoTrack == true )
{
assert( success == true );
return parser::Task::Status::Success;
}
// In case the playback failed, we probably won't fetch anything interesting anyway.
if ( failedToStart == true )
return parser::Task::Status::Fatal;
// We are now in the case of a timeout: No failure, but no video track either.
// The file might be an audio file we haven't detected yet:
if ( task.media->type() == Media::Type::UnknownType )
{
task.media->setType( Media::Type::AudioType );
if ( task.media->save() == false )
return parser::Task::Status::Fatal;
// We still return an error since we don't want to attempt the thumbnail generation for a
// file without video tracks
}
return parser::Task::Status::Fatal;
}
parser::Task::Status VLCThumbnailer::seekAhead( VLC::MediaPlayer& mp )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
float pos = .0f;
auto event = mp.eventManager().onPositionChanged([this, &pos](float p) {
std::unique_lock<compat::Mutex> lock( m_mutex );
pos = p;
m_cond.notify_all();
});
mp.setPosition( .4f );
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [&pos]() {
return pos >= .1f;
});
// Since we're locking a mutex for each position changed, let's unregister ASAP
event->unregister();
if ( success == false )
return parser::Task::Status::Fatal;
return parser::Task::Status::Success;
}
void VLCThumbnailer::setupVout( VLC::MediaPlayer& mp )
{
mp.setVideoFormatCallbacks(
// Setup
[this, &mp](char* chroma, unsigned int* width, unsigned int *height, unsigned int *pitches, unsigned int *lines) {
strcpy( chroma, m_compressor->fourCC() );
const float inputAR = (float)*width / *height;
m_width = DesiredWidth;
m_height = (float)m_width / inputAR + 1;
if ( m_height < DesiredHeight )
{
// Avoid downscaling too much for really wide pictures
m_width = inputAR * DesiredHeight;
m_height = DesiredHeight;
}
auto size = m_width * m_height * m_compressor->bpp();
// If our buffer isn't enough anymore, reallocate a new one.
if ( size > m_prevSize )
{
m_buff.reset( new uint8_t[size] );
m_prevSize = size;
}
*width = m_width;
*height = m_height;
*pitches = m_width * m_compressor->bpp();
*lines = m_height;
return 1;
},
// Cleanup
nullptr);
mp.setVideoCallbacks(
// Lock
[this](void** pp_buff) {
*pp_buff = m_buff.get();
return nullptr;
},
//unlock
nullptr,
//display
[this](void*) {
bool expected = true;
if ( m_thumbnailRequired.compare_exchange_strong( expected, false ) )
{
m_cond.notify_all();
}
}
);
}
parser::Task::Status VLCThumbnailer::takeThumbnail( std::shared_ptr<Media> media, std::shared_ptr<File> file, VLC::MediaPlayer &mp )
{
// lock, signal that we want a thumbnail, and wait.
{
std::unique_lock<compat::Mutex> lock( m_mutex );
m_thumbnailRequired = true;
bool success = m_cond.wait_for( lock, std::chrono::seconds( 3 ), [this]() {
// Keep waiting if the vmem thread hasn't restored m_thumbnailRequired to false
return m_thumbnailRequired == false;
});
if ( success == false )
{
LOG_WARN( "Timed out while computing ", file->mrl(), " snapshot" );
return parser::Task::Status::Fatal;
}
}
mp.stop();
return compress( media, file );
}
parser::Task::Status VLCThumbnailer::compress( std::shared_ptr<Media> media, std::shared_ptr<File> file )
{
auto path = m_ml->thumbnailPath();
path += "/";
path += std::to_string( media->id() ) + "." + m_compressor->extension();
auto hOffset = m_width > DesiredWidth ? ( m_width - DesiredWidth ) / 2 : 0;
auto vOffset = m_height > DesiredHeight ? ( m_height - DesiredHeight ) / 2 : 0;
if ( m_compressor->compress( m_buff.get(), path, m_width, m_height, DesiredWidth, DesiredHeight,
hOffset, vOffset ) == false )
return parser::Task::Status::Fatal;
media->setThumbnail( path );
LOG_INFO( "Done generating ", file->mrl(), " thumbnail" );
auto t = m_ml->getConn()->newTransaction();
if ( media->save() == false )
return parser::Task::Status::Fatal;
file->markStepCompleted( File::ParserStep::Thumbnailer );
if ( file->saveParserStep() == false )
return parser::Task::Status::Fatal;
t->commit();
m_notifier->notifyMediaModification( media );
return parser::Task::Status::Success;
}
const char*VLCThumbnailer::name() const
{
return "Thumbnailer";
}
uint8_t VLCThumbnailer::nbThreads() const
{
return 1;
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
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 author 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.
*/
#include "libtorrent/pch.hpp"
#include "libtorrent/assert.hpp"
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
void open(fs::path const& path, int mode)
{
TORRENT_ASSERT(path.is_complete());
close();
#if defined(_WIN32) && defined(UNICODE)
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
m_fd = ::_open(
#else
m_fd = ::open(
#endif
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode)
#ifdef _WIN32
, S_IREAD | S_IWRITE);
#else
, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< strerror(errno);
throw file_error(msg.str());
}
m_open_mode = mode;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
void set_size(size_type s)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
std::stringstream msg;
msg << "ftruncate failed: '" << strerror(errno);
throw file_error(msg.str());
}
#endif
}
size_type seek(size_type offset, int m = 1)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
throw file_error(msg.str());
}
return ret;
}
size_type tell()
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
void file::open(fs::path const& p, file::open_mode m)
{
m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
void file::set_size(size_type s)
{
m_impl->set_size(s);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
}
<commit_msg>fixed static assert being hit on linux systems<commit_after>/*
Copyright (c) 2003, Arvid Norberg
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 author 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.
*/
#include "libtorrent/pch.hpp"
#ifdef _WIN32
// windows part
#include "libtorrent/utf8.hpp"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef _MODE_T_
typedef int mode_t;
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#else
// unix part
#define _FILE_OFFSET_BITS 64
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <boost/static_assert.hpp>
// make sure the _FILE_OFFSET_BITS define worked
// on this platform
BOOST_STATIC_ASSERT(sizeof(lseek(0, 0, 0)) >= 8);
#endif
#include <boost/filesystem/operations.hpp>
#include "libtorrent/file.hpp"
#include <sstream>
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_RANDOM
#define O_RANDOM 0
#endif
#ifdef UNICODE
#include "libtorrent/storage.hpp"
#endif
#include "libtorrent/assert.hpp"
namespace
{
enum { mode_in = 1, mode_out = 2 };
mode_t map_open_mode(int m)
{
if (m == (mode_in | mode_out)) return O_RDWR | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_out) return O_WRONLY | O_CREAT | O_BINARY | O_RANDOM;
if (m == mode_in) return O_RDONLY | O_BINARY | O_RANDOM;
TORRENT_ASSERT(false);
return 0;
}
#ifdef WIN32
std::string utf8_native(std::string const& s)
{
try
{
std::wstring ws;
libtorrent::utf8_wchar(s, ws);
std::size_t size = wcstombs(0, ws.c_str(), 0);
if (size == std::size_t(-1)) return s;
std::string ret;
ret.resize(size);
size = wcstombs(&ret[0], ws.c_str(), size + 1);
if (size == wchar_t(-1)) return s;
ret.resize(size);
return ret;
}
catch(std::exception)
{
return s;
}
}
#else
std::string utf8_native(std::string const& s)
{
return s;
}
#endif
}
namespace libtorrent
{
namespace fs = boost::filesystem;
const file::open_mode file::in(mode_in);
const file::open_mode file::out(mode_out);
const file::seek_mode file::begin(1);
const file::seek_mode file::end(2);
struct file::impl
{
impl()
: m_fd(-1)
, m_open_mode(0)
{}
impl(fs::path const& path, int mode)
: m_fd(-1)
, m_open_mode(0)
{
open(path, mode);
}
~impl()
{
close();
}
void open(fs::path const& path, int mode)
{
TORRENT_ASSERT(path.is_complete());
close();
#if defined(_WIN32) && defined(UNICODE)
std::wstring wpath(safe_convert(path.native_file_string()));
m_fd = ::_wopen(
wpath.c_str()
, map_open_mode(mode)
, S_IREAD | S_IWRITE);
#else
#ifdef _WIN32
m_fd = ::_open(
#else
m_fd = ::open(
#endif
utf8_native(path.native_file_string()).c_str()
, map_open_mode(mode)
#ifdef _WIN32
, S_IREAD | S_IWRITE);
#else
, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
#endif
#endif
if (m_fd == -1)
{
std::stringstream msg;
msg << "open failed: '" << path.native_file_string() << "'. "
<< strerror(errno);
throw file_error(msg.str());
}
m_open_mode = mode;
}
void close()
{
if (m_fd == -1) return;
#ifdef _WIN32
::_close(m_fd);
#else
::close(m_fd);
#endif
m_fd = -1;
m_open_mode = 0;
}
size_type read(char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_in);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
size_type ret = ::_read(m_fd, buf, num_bytes);
#else
size_type ret = ::read(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "read failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
size_type write(const char* buf, size_type num_bytes)
{
TORRENT_ASSERT(m_open_mode & mode_out);
TORRENT_ASSERT(m_fd != -1);
// TODO: Test this a bit more, what happens with random failures in
// the files?
// if ((rand() % 100) > 80)
// throw file_error("debug");
#ifdef _WIN32
size_type ret = ::_write(m_fd, buf, num_bytes);
#else
size_type ret = ::write(m_fd, buf, num_bytes);
#endif
if (ret == -1)
{
std::stringstream msg;
msg << "write failed: " << strerror(errno);
throw file_error(msg.str());
}
return ret;
}
void set_size(size_type s)
{
#ifdef _WIN32
#error file.cpp is for posix systems only. use file_win.cpp on windows
#else
if (ftruncate(m_fd, s) < 0)
{
std::stringstream msg;
msg << "ftruncate failed: '" << strerror(errno);
throw file_error(msg.str());
}
#endif
}
size_type seek(size_type offset, int m = 1)
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
int seekdir = (m == 1)?SEEK_SET:SEEK_END;
#ifdef _WIN32
size_type ret = _lseeki64(m_fd, offset, seekdir);
#else
size_type ret = lseek(m_fd, offset, seekdir);
#endif
// For some strange reason this fails
// on win32. Use windows specific file
// wrapper instead.
if (ret == -1)
{
std::stringstream msg;
msg << "seek failed: '" << strerror(errno)
<< "' fd: " << m_fd
<< " offset: " << offset
<< " seekdir: " << seekdir;
throw file_error(msg.str());
}
return ret;
}
size_type tell()
{
TORRENT_ASSERT(m_open_mode);
TORRENT_ASSERT(m_fd != -1);
#ifdef _WIN32
return _telli64(m_fd);
#else
return lseek(m_fd, 0, SEEK_CUR);
#endif
}
int m_fd;
int m_open_mode;
};
// pimpl forwardings
file::file() : m_impl(new impl()) {}
file::file(fs::path const& p, file::open_mode m)
: m_impl(new impl(p, m.m_mask))
{}
file::~file() {}
void file::open(fs::path const& p, file::open_mode m)
{
m_impl->open(p, m.m_mask);
}
void file::close()
{
m_impl->close();
}
size_type file::write(const char* buf, size_type num_bytes)
{
return m_impl->write(buf, num_bytes);
}
size_type file::read(char* buf, size_type num_bytes)
{
return m_impl->read(buf, num_bytes);
}
void file::set_size(size_type s)
{
m_impl->set_size(s);
}
size_type file::seek(size_type pos, file::seek_mode m)
{
return m_impl->seek(pos, m.m_val);
}
size_type file::tell()
{
return m_impl->tell();
}
}
<|endoftext|> |
<commit_before>#include <numeric>
#include <iterator>
#include <algorithm>
#include <cstring>
#include <mutex>
#include <cassert>
#include "util.h"
#include "film.h"
#include "sampler.h"
#include "reinhard.h"
using std::transform;
using std::back_inserter;
using std::copy;
using std::cout;
using std::ostream_iterator;
using std::accumulate;
using std::cerr;
using std::endl;
Film::Film(uint w_, uint h_)
: width(w_), height(h_), plate(w_ * h_)
{
}
Film::Film(const Film& f)
: width(f.width), height(f.height), plate(f.plate)
{
}
Film::Film(istream& in) : width(0), height(0)
{
char buf[8];
in.read(buf, 8);
if (strncmp(buf, "TWINKLE", 8) != 0)
return;
in.read(reinterpret_cast<char*>(const_cast<uint32_t*>(&width)), sizeof(width));
in.read(reinterpret_cast<char*>(const_cast<uint32_t*>(&height)), sizeof(height));
if (!in.good())
return;
if (width == 0 || height == 0)
return;
plate.resize(width*height);
for (uint32_t i = 0; i < width * height; ++i)
{
plate[i] = AccPixel{ spectrum::deserialize(in) };
}
}
void Film::add_sample(const PixelSample& ps, const spectrum& s, scalar w)
{
BoxFilter().add_sample(*this, ps, s, w);
}
vector<spectrum> Film::pixel_list() const
{
vector<spectrum> ret;
for (const auto& p: plate)
{
assert(p.weight > 0);
ret.push_back( p.total / p.weight );
}
return ret;
}
void Film::merge(const Film& f)
{
assert(width == f.width);
assert(height == f.height);
assert(plate.size() == f.plate.size());
transform(plate.begin(), plate.end(), f.plate.begin(),
plate.begin(), [](auto& x, const auto& y) { return x + y; });
}
scalar Film::average_intensity() const
{
scalar r = 0, w = 0;
for (const auto& p: plate)
{
w += p.weight;
r += (p.total.luminance() - r) / w;
}
return r;
}
void Film::render_to_ppm(ostream& out, const ToneMapper& mapper)
{
vector<spectrum> final = pixel_list();
mapper.tonemap(final, final, width, height);
auto pl = pixel_list();
out << "P3 " << width << " " << height << " 255\n";
for (int y = height - 1; y >= 0; --y)
{
for(uint x = 0; x < width; ++x)
{
const auto& c = final[index(x, y)];//.clamp(0, 1);
if (std::isnan(c.x))
{
cerr << x << ", " << y << ", " << c.x << std::endl;
const auto& p = plate[index(x, y)];
cerr << p.mean << ", " << p.ss << ", " << p.weight << std::endl;
}
assert(c.x >= 0);
assert(c.y >= 0);
assert(c.z >= 0);
assert(c.x <= 1);
assert(c.y <= 1);
assert(c.z <= 1);
out << int(c.x * 255) << " " << int(c.y * 255) << " " << int(c.z * 255) << " ";
}
out << "\n";
}
}
void Film::render_to_twi(ostream& out) const
{
vector<spectrum> raw = pixel_list();
out.write("TWINKLE", 8);
out.write(reinterpret_cast<const char*>(&width), sizeof(width));
out.write(reinterpret_cast<const char*>(&height), sizeof(height));
for (auto& s: raw)
s.serialize(out);
}
void Film::render_to_console(ostream& out) const
{
for (int y = height - 1; y >= 0; --y)
{
for (uint x = 0; x < width; ++x)
{
spectrum s = plate[index(x,y)].total;
if (norm(s) > 0.5)
out << '*';
else if (norm(s) > 0.25)
out << '.';
else
out << ' ';
}
out << '\n';
}
}
Film Film::as_weights() const
{
Film f(this->width, this->height);
transform(plate.begin(), plate.end(),
f.plate.begin(),
[] (const auto& pixel)
{
return AccPixel(spectrum{pixel.weight});
});
return f;
}
Film Film::as_pv() const
{
Film f(this->width, this->height);
transform(plate.begin(), plate.end(),
f.plate.begin(),
[] (const auto& pixel)
{
return AccPixel(spectrum{pixel.perceptual_variance()});
});
return f;
}
Array2D<uint> Film::samples_by_variance(uint spp) const
{
uint64_t total_samples = spp * width * height;
// FIX: This number should be dependent on spp.
const double epsilon = 0.001;
vector<double> weights(plate.size());
// The weights are proportional to the (tonemapped) perceptual variances, with
// a small epsilon to ensure a minimum number of samples for every pixel.
{
vector<spectrum> variances(plate.size());
transform(plate.begin(), plate.end(), variances.begin(),
[] (const auto& pixel) { return spectrum(pixel.perceptual_variance()); });
vector<spectrum> ov(plate.size());
//ReinhardGlobal().tonemap(variances, ov, width, height);
ov = variances;
double tv = accumulate(ov.begin(), ov.end(), 0.0,
[](double v, const spectrum& s) { return v + s.x; });
cerr << "Total variance: " << tv << "\n";
transform(ov.begin(), ov.end(), weights.begin(),
[=] (const auto& v) { return epsilon + (1-epsilon) * v.x / tv; });
scalar tw = accumulate(weights.begin(), weights.end(), 0.0);
transform(weights.begin(), weights.end(), weights.begin(),
[=] (const auto& w) { return w / tw * total_samples; });
}
cerr << "Starting with " << total_samples << " samples.\n";
vector<uint> samples(plate.size(), 0);
int64_t remaining_samples = total_samples;
for (uint i = 0u; i < samples.size(); ++i)
{
scalar f = std::floor(weights[i]);
samples[i] = f;
remaining_samples -= samples[i];
weights[i] -= f;
}
cerr << "Now at " << remaining_samples << " samples.\n";
// Get the samples from the residual distribution
auto residual_samples = multinomial_distribution(weights, remaining_samples);
transform(samples.begin(), samples.end(), residual_samples.begin(), samples.begin(),
[](auto s, auto r) { return s + r; });
return Array2D<uint>(width, height, samples);
}
void Film::clear()
{
fill(plate.begin(), plate.end(), AccPixel());
}
////////////////////////////////////////////////////////////////////////////////
void BoxFilter::add_sample(Film& film, const PixelSample& p,
const spectrum& s, scalar w) const
{
Film::AccPixel& fp = film.at(p.x, p.y);
fp.add_sample(s, w);
}
Film::AccPixel::AccPixel()
: weight(0), total(0.0), mean(0), ss(0), count(0)
{
}
Film::AccPixel& Film::AccPixel::operator+=(const AccPixel& p)
{
const scalar tw = weight + p.weight;
if (p.weight == 0)
return *this;
const scalar delta = (p.mean - mean);
mean += delta * p.weight / tw;
ss += p.ss + delta * delta * weight * p.weight / tw;
count += p.count;
total += p.total;
weight = tw;
return *this;
}
void Film::AccPixel::add_sample(const spectrum& v, scalar w)
{
if (unlikely(w == 0))
return;
total += v * w;
scalar tw = weight + w;
scalar c = v.luminance();
scalar d = c - mean;
scalar R = d * w / tw;
mean += R;
ss += weight * d * R;
count += 1;
weight = tw;
}
scalar Film::AccPixel::variance() const
{
if (unlikely(weight <= 0))
return 0;
return (ss / weight);
}
scalar Film::AccPixel::perceptual_variance() const
{
if (unlikely(weight <= 0))
return 0;
return (ss / weight) / tvi(mean);
}
Film::AccPixel Film::AccPixel::operator+(const AccPixel& p) const
{
AccPixel x(*this);
return x += p;
}
////////////////////////////////////////////////////////////////////////////////
ostream& operator<<(ostream& o, const Film::AccPixel& pixel)
{
o << "Rect(" << pixel.total << ", " << pixel.weight << ")";
return o;
}
ostream& operator<<(ostream& o, const Film::Rect& rect)
{
o << "Rect(" << rect.x << ", " << rect.y << "; " << rect.width << ", " << rect.height << ")";
return o;
}
<commit_msg>film additional error checking<commit_after>#include <numeric>
#include <iterator>
#include <algorithm>
#include <cstring>
#include <mutex>
#include <cassert>
#include "util.h"
#include "film.h"
#include "sampler.h"
#include "reinhard.h"
using std::transform;
using std::back_inserter;
using std::copy;
using std::cout;
using std::ostream_iterator;
using std::accumulate;
using std::cerr;
using std::endl;
Film::Film(uint w_, uint h_)
: width(w_), height(h_), plate(w_ * h_)
{
}
Film::Film(const Film& f)
: width(f.width), height(f.height), plate(f.plate)
{
}
Film::Film(istream& in) : width(0), height(0)
{
char buf[8];
in.read(buf, 8);
if (strncmp(buf, "TWINKLE", 8) != 0)
return;
in.read(reinterpret_cast<char*>(const_cast<uint32_t*>(&width)), sizeof(width));
in.read(reinterpret_cast<char*>(const_cast<uint32_t*>(&height)), sizeof(height));
if (!in.good())
return;
if (width == 0 || height == 0)
return;
plate.resize(width*height);
for (uint32_t i = 0; i < width * height; ++i)
{
plate[i] = AccPixel{ spectrum::deserialize(in) };
}
}
void Film::add_sample(const PixelSample& ps, const spectrum& s, scalar w)
{
BoxFilter().add_sample(*this, ps, s, w);
}
vector<spectrum> Film::pixel_list() const
{
vector<spectrum> ret;
for (const auto& p: plate)
{
assert(p.weight > 0);
ret.push_back( p.total / p.weight );
}
return ret;
}
void Film::merge(const Film& f)
{
assert(width == f.width);
assert(height == f.height);
assert(plate.size() == f.plate.size());
transform(plate.begin(), plate.end(), f.plate.begin(),
plate.begin(), [](auto& x, const auto& y) { return x + y; });
}
scalar Film::average_intensity() const
{
scalar r = 0, w = 0;
for (const auto& p: plate)
{
w += p.weight;
r += (p.total.luminance() - r) / w;
}
return r;
}
void Film::render_to_ppm(ostream& out, const ToneMapper& mapper)
{
vector<spectrum> final = pixel_list();
mapper.tonemap(final, final, width, height);
auto pl = pixel_list();
out << "P3 " << width << " " << height << " 255\n";
for (int y = height - 1; y >= 0; --y)
{
for(uint x = 0; x < width; ++x)
{
const auto& c = final[index(x, y)];//.clamp(0, 1);
if (std::isnan(c.x) || c.x < 0 || c.y < 0 || c.z < 0)
{
cerr << x << ", " << y << ", " << c << std::endl;
const auto& p = plate[index(x, y)];
cerr << p.mean << ", " << p.ss << ", " << p.weight << std::endl;
}
assert(c.x >= 0);
assert(c.y >= 0);
assert(c.z >= 0);
assert(c.x <= 1);
assert(c.y <= 1);
assert(c.z <= 1);
out << int(c.x * 255) << " " << int(c.y * 255) << " " << int(c.z * 255) << " ";
}
out << "\n";
}
}
void Film::render_to_twi(ostream& out) const
{
vector<spectrum> raw = pixel_list();
out.write("TWINKLE", 8);
out.write(reinterpret_cast<const char*>(&width), sizeof(width));
out.write(reinterpret_cast<const char*>(&height), sizeof(height));
for (auto& s: raw)
s.serialize(out);
}
void Film::render_to_console(ostream& out) const
{
for (int y = height - 1; y >= 0; --y)
{
for (uint x = 0; x < width; ++x)
{
spectrum s = plate[index(x,y)].total;
if (norm(s) > 0.5)
out << '*';
else if (norm(s) > 0.25)
out << '.';
else
out << ' ';
}
out << '\n';
}
}
Film Film::as_weights() const
{
Film f(this->width, this->height);
transform(plate.begin(), plate.end(),
f.plate.begin(),
[] (const auto& pixel)
{
return AccPixel(spectrum{pixel.weight});
});
return f;
}
Film Film::as_pv() const
{
Film f(this->width, this->height);
transform(plate.begin(), plate.end(),
f.plate.begin(),
[] (const auto& pixel)
{
return AccPixel(spectrum{pixel.perceptual_variance()});
});
return f;
}
Array2D<uint> Film::samples_by_variance(uint spp) const
{
uint64_t total_samples = spp * width * height;
// FIX: This number should be dependent on spp.
const double epsilon = 0.001;
vector<double> weights(plate.size());
// The weights are proportional to the (tonemapped) perceptual variances, with
// a small epsilon to ensure a minimum number of samples for every pixel.
{
vector<spectrum> variances(plate.size());
transform(plate.begin(), plate.end(), variances.begin(),
[] (const auto& pixel) { return spectrum(pixel.perceptual_variance()); });
vector<spectrum> ov(plate.size());
//ReinhardGlobal().tonemap(variances, ov, width, height);
ov = variances;
double tv = accumulate(ov.begin(), ov.end(), 0.0,
[](double v, const spectrum& s) { return v + s.x; });
//cerr << "Average variance: " << tv / (width * height) << "\n";
transform(ov.begin(), ov.end(), weights.begin(),
[=] (const auto& v) { return epsilon + (1-epsilon) * v.x / tv; });
scalar tw = accumulate(weights.begin(), weights.end(), 0.0);
transform(weights.begin(), weights.end(), weights.begin(),
[=] (const auto& w) { return w / tw * total_samples; });
}
vector<uint> samples(plate.size(), 0);
int64_t remaining_samples = total_samples;
for (uint i = 0u; i < samples.size(); ++i)
{
scalar f = std::floor(weights[i]);
samples[i] = f;
remaining_samples -= samples[i];
weights[i] -= f;
}
// Get the samples from the residual distribution
auto residual_samples = multinomial_distribution(weights, remaining_samples);
transform(samples.begin(), samples.end(), residual_samples.begin(), samples.begin(),
[](auto s, auto r) { return s + r; });
return Array2D<uint>(width, height, samples);
}
void Film::clear()
{
fill(plate.begin(), plate.end(), AccPixel());
}
////////////////////////////////////////////////////////////////////////////////
void BoxFilter::add_sample(Film& film, const PixelSample& p,
const spectrum& s, scalar w) const
{
Film::AccPixel& fp = film.at(p.x, p.y);
fp.add_sample(s, w);
}
Film::AccPixel::AccPixel()
: weight(0), total(0.0), mean(0), ss(0), count(0)
{
}
Film::AccPixel& Film::AccPixel::operator+=(const AccPixel& p)
{
const scalar tw = weight + p.weight;
if (p.weight == 0)
return *this;
const scalar delta = (p.mean - mean);
mean += delta * p.weight / tw;
ss += p.ss + delta * delta * weight * p.weight / tw;
count += p.count;
total += p.total;
weight = tw;
return *this;
}
void Film::AccPixel::add_sample(const spectrum& v, scalar w)
{
if (unlikely(w == 0))
return;
total += v * w;
scalar tw = weight + w;
const scalar c = v.luminance();
const scalar d = c - mean;
const scalar R = d * w / tw;
mean += R;
ss += weight * d * R;
count += 1;
weight = tw;
if (isnan(mean))
{
cerr << w << " " << c << " " << d << " " << tw << " " << R << "\n";
}
assert(!isnan(mean));
// assert(!isnan(ss));
}
scalar Film::AccPixel::variance() const
{
if (unlikely(weight <= 0))
return 0;
return (ss / weight);
}
scalar Film::AccPixel::perceptual_variance() const
{
if (unlikely(weight <= 0))
return 0;
return (ss / weight) / tvi(mean);
}
Film::AccPixel Film::AccPixel::operator+(const AccPixel& p) const
{
AccPixel x(*this);
return x += p;
}
////////////////////////////////////////////////////////////////////////////////
ostream& operator<<(ostream& o, const Film::AccPixel& pixel)
{
o << "Rect(" << pixel.total << ", " << pixel.weight << ")";
return o;
}
ostream& operator<<(ostream& o, const Film::Rect& rect)
{
o << "Rect(" << rect.x << ", " << rect.y << "; " << rect.width << ", " << rect.height << ")";
return o;
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (C) 2012 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file fixedwing.cpp
*
* Controller library code
*/
#include "fixedwing.hpp"
namespace control
{
namespace fixedwing
{
BlockYawDamper::BlockYawDamper(SuperBlock *parent, const char *name) :
SuperBlock(parent, name),
_rLowPass(this, "R_LP"),
_rWashout(this, "R_HP"),
_r2Rdr(this, "R2RDR"),
_rudder(0)
{
}
BlockYawDamper::~BlockYawDamper() {};
void BlockYawDamper::update(float rCmd, float r, float outputScale)
{
_rudder = outputScale*_r2Rdr.update(rCmd -
_rWashout.update(_rLowPass.update(r)));
}
BlockStabilization::BlockStabilization(SuperBlock *parent, const char *name) :
SuperBlock(parent, name),
_yawDamper(this, ""),
_pLowPass(this, "P_LP"),
_qLowPass(this, "Q_LP"),
_p2Ail(this, "P2AIL"),
_q2Elv(this, "Q2ELV"),
_aileron(0),
_elevator(0)
{
}
BlockStabilization::~BlockStabilization() {};
void BlockStabilization::update(float pCmd, float qCmd, float rCmd,
float p, float q, float r, float outputScale)
{
_aileron = outputScale*_p2Ail.update(
pCmd - _pLowPass.update(p));
_elevator = outputScale*_q2Elv.update(
qCmd - _qLowPass.update(q));
_yawDamper.update(rCmd, r, outputScale);
}
BlockMultiModeBacksideAutopilot::BlockMultiModeBacksideAutopilot(SuperBlock *parent, const char *name) :
BlockUorbEnabledAutopilot(parent, name),
_stabilization(this, ""), // no name needed, already unique
// heading hold
_psi2Phi(this, "PSI2PHI"),
_phi2P(this, "PHI2P"),
_phiLimit(this, "PHI_LIM"),
// velocity hold
_v2Theta(this, "V2THE"),
_theta2Q(this, "THE2Q"),
_theLimit(this, "THE"),
_vLimit(this, "V"),
// altitude/climb rate hold
_h2Thr(this, "H2THR"),
_cr2Thr(this, "CR2THR"),
// guidance block
_guide(this, ""),
_trimAil(this, "TRIM_ROLL", false), /* general roll trim (full name: TRIM_ROLL) */
_trimElv(this, "TRIM_PITCH", false), /* general pitch trim */
_trimRdr(this, "TRIM_YAW", false), /* general yaw trim */
_trimThr(this, "TRIM_THR"), /* FWB_ specific throttle trim (full name: FWB_TRIM_THR) */
_trimV(this, "TRIM_V"), /* FWB_ specific trim velocity (full name : FWB_TRIM_V) */
_vCmd(this, "V_CMD"),
_crMax(this, "CR_MAX"),
_attPoll(),
_lastPosCmd(),
_timeStamp(0)
{
_attPoll.fd = _att.getHandle();
_attPoll.events = POLLIN;
}
void BlockMultiModeBacksideAutopilot::update()
{
// wait for a sensor update, check for exit condition every 100 ms
if (poll(&_attPoll, 1, 100) < 0) return; // poll error
uint64_t newTimeStamp = hrt_absolute_time();
float dt = (newTimeStamp - _timeStamp) / 1.0e6f;
_timeStamp = newTimeStamp;
// check for sane values of dt
// to prevent large control responses
if (dt > 1.0f || dt < 0) return;
// set dt for all child blocks
setDt(dt);
// store old position command before update if new command sent
if (_posCmd.updated()) {
_lastPosCmd = _posCmd.getData();
}
// check for new updates
if (_param_update.updated()) updateParams();
// get new information from subscriptions
updateSubscriptions();
// default all output to zero unless handled by mode
for (unsigned i = 4; i < NUM_ACTUATOR_CONTROLS; i++)
_actuators.control[i] = 0.0f;
// only update guidance in auto mode
if (_status.navigation_state == NAVIGATION_STATE_AUTO_MISSION) { // TODO use vehicle_control_mode here?
// update guidance
_guide.update(_pos, _att, _posCmd.current, _lastPosCmd.current);
}
// XXX handle STABILIZED (loiter on spot) as well
// once the system switches from manual or auto to stabilized
// the setpoint should update to loitering around this position
// handle autopilot modes
if (_status.navigation_state == NAVIGATION_STATE_AUTO_MISSION ||
_status.navigation_state == NAVIGATION_STATE_STABILIZE) { // TODO use vehicle_control_mode here?
// update guidance
_guide.update(_pos, _att, _posCmd.current, _lastPosCmd.current);
// calculate velocity, XXX should be airspeed, but using ground speed for now
// for the purpose of control we will limit the velocity feedback between
// the min/max velocity
float v = _vLimit.update(sqrtf(
_pos.vx * _pos.vx +
_pos.vy * _pos.vy +
_pos.vz * _pos.vz));
// limit velocity command between min/max velocity
float vCmd = _vLimit.update(_vCmd.get());
// altitude hold
float dThrottle = _h2Thr.update(_posCmd.current.altitude - _pos.alt);
// heading hold
float psiError = _wrap_pi(_guide.getPsiCmd() - _att.yaw);
float phiCmd = _phiLimit.update(_psi2Phi.update(psiError));
float pCmd = _phi2P.update(phiCmd - _att.roll);
// velocity hold
// negative sign because nose over to increase speed
float thetaCmd = _theLimit.update(-_v2Theta.update(vCmd - v));
float qCmd = _theta2Q.update(thetaCmd - _att.pitch);
// yaw rate cmd
float rCmd = 0;
// stabilization
float velocityRatio = _trimV.get()/v;
float outputScale = velocityRatio*velocityRatio;
// this term scales the output based on the dynamic pressure change from trim
_stabilization.update(pCmd, qCmd, rCmd,
_att.rollspeed, _att.pitchspeed, _att.yawspeed,
outputScale);
// output
_actuators.control[CH_AIL] = _stabilization.getAileron() + _trimAil.get();
_actuators.control[CH_ELV] = _stabilization.getElevator() + _trimElv.get();
_actuators.control[CH_RDR] = _stabilization.getRudder() + _trimRdr.get();
_actuators.control[CH_THR] = dThrottle + _trimThr.get();
// XXX limit throttle to manual setting (safety) for now.
// If it turns out to be confusing, it can be removed later once
// a first binary release can be targeted.
// This is not a hack, but a design choice.
/* do not limit in HIL */
if (_status.hil_state != HIL_STATE_ON) {
/* limit to value of manual throttle */
_actuators.control[CH_THR] = (_actuators.control[CH_THR] < _manual.throttle) ?
_actuators.control[CH_THR] : _manual.throttle;
}
} else if (_status.navigation_state == NAVIGATION_STATE_DIRECT) { // TODO use vehicle_control_mode here?
_actuators.control[CH_AIL] = _manual.roll;
_actuators.control[CH_ELV] = _manual.pitch;
_actuators.control[CH_RDR] = _manual.yaw;
_actuators.control[CH_THR] = _manual.throttle;
} else if (_status.navigation_state == NAVIGATION_STATE_STABILIZE) { // TODO use vehicle_control_mode here?
// calculate velocity, XXX should be airspeed, but using ground speed for now
// for the purpose of control we will limit the velocity feedback between
// the min/max velocity
float v = _vLimit.update(sqrtf(
_pos.vx * _pos.vx +
_pos.vy * _pos.vy +
_pos.vz * _pos.vz));
// pitch channel -> rate of climb
// TODO, might want to put a gain on this, otherwise commanding
// from +1 -> -1 m/s for rate of climb
//float dThrottle = _cr2Thr.update(
//_crMax.get()*_manual.pitch - _pos.vz);
// roll channel -> bank angle
float phiCmd = _phiLimit.update(_manual.roll * _phiLimit.getMax());
float pCmd = _phi2P.update(phiCmd - _att.roll);
// throttle channel -> velocity
// negative sign because nose over to increase speed
float vCmd = _vLimit.update(_manual.throttle *
(_vLimit.getMax() - _vLimit.getMin()) +
_vLimit.getMin());
float thetaCmd = _theLimit.update(-_v2Theta.update(vCmd - v));
float qCmd = _theta2Q.update(thetaCmd - _att.pitch);
// yaw rate cmd
float rCmd = 0;
// stabilization
_stabilization.update(pCmd, qCmd, rCmd,
_att.rollspeed, _att.pitchspeed, _att.yawspeed);
// output
_actuators.control[CH_AIL] = _stabilization.getAileron() + _trimAil.get();
_actuators.control[CH_ELV] = _stabilization.getElevator() + _trimElv.get();
_actuators.control[CH_RDR] = _stabilization.getRudder() + _trimRdr.get();
// currently using manual throttle
// XXX if you enable this watch out, vz might be very noisy
//_actuators.control[CH_THR] = dThrottle + _trimThr.get();
_actuators.control[CH_THR] = _manual.throttle;
// XXX limit throttle to manual setting (safety) for now.
// If it turns out to be confusing, it can be removed later once
// a first binary release can be targeted.
// This is not a hack, but a design choice.
/* do not limit in HIL */
if (_status.hil_state != HIL_STATE_ON) {
/* limit to value of manual throttle */
_actuators.control[CH_THR] = (_actuators.control[CH_THR] < _manual.throttle) ?
_actuators.control[CH_THR] : _manual.throttle;
}
// body rates controller, disabled for now
// TODO
} else if (0 /*_status.manual_control_mode == VEHICLE_MANUAL_CONTROL_MODE_SAS*/) { // TODO use vehicle_control_mode here?
_stabilization.update(_manual.roll, _manual.pitch, _manual.yaw,
_att.rollspeed, _att.pitchspeed, _att.yawspeed);
_actuators.control[CH_AIL] = _stabilization.getAileron();
_actuators.control[CH_ELV] = _stabilization.getElevator();
_actuators.control[CH_RDR] = _stabilization.getRudder();
_actuators.control[CH_THR] = _manual.throttle;
}
// update all publications
updatePublications();
}
BlockMultiModeBacksideAutopilot::~BlockMultiModeBacksideAutopilot()
{
// send one last publication when destroyed, setting
// all output to zero
for (unsigned i = 0; i < NUM_ACTUATOR_CONTROLS; i++)
_actuators.control[i] = 0.0f;
updatePublications();
}
} // namespace fixedwing
} // namespace control
<commit_msg>Improved mode mapping for fixedwing_backside.<commit_after>/****************************************************************************
*
* Copyright (C) 2012 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file fixedwing.cpp
*
* Controller library code
*/
#include "fixedwing.hpp"
namespace control
{
namespace fixedwing
{
BlockYawDamper::BlockYawDamper(SuperBlock *parent, const char *name) :
SuperBlock(parent, name),
_rLowPass(this, "R_LP"),
_rWashout(this, "R_HP"),
_r2Rdr(this, "R2RDR"),
_rudder(0)
{
}
BlockYawDamper::~BlockYawDamper() {};
void BlockYawDamper::update(float rCmd, float r, float outputScale)
{
_rudder = outputScale*_r2Rdr.update(rCmd -
_rWashout.update(_rLowPass.update(r)));
}
BlockStabilization::BlockStabilization(SuperBlock *parent, const char *name) :
SuperBlock(parent, name),
_yawDamper(this, ""),
_pLowPass(this, "P_LP"),
_qLowPass(this, "Q_LP"),
_p2Ail(this, "P2AIL"),
_q2Elv(this, "Q2ELV"),
_aileron(0),
_elevator(0)
{
}
BlockStabilization::~BlockStabilization() {};
void BlockStabilization::update(float pCmd, float qCmd, float rCmd,
float p, float q, float r, float outputScale)
{
_aileron = outputScale*_p2Ail.update(
pCmd - _pLowPass.update(p));
_elevator = outputScale*_q2Elv.update(
qCmd - _qLowPass.update(q));
_yawDamper.update(rCmd, r, outputScale);
}
BlockMultiModeBacksideAutopilot::BlockMultiModeBacksideAutopilot(SuperBlock *parent, const char *name) :
BlockUorbEnabledAutopilot(parent, name),
_stabilization(this, ""), // no name needed, already unique
// heading hold
_psi2Phi(this, "PSI2PHI"),
_phi2P(this, "PHI2P"),
_phiLimit(this, "PHI_LIM"),
// velocity hold
_v2Theta(this, "V2THE"),
_theta2Q(this, "THE2Q"),
_theLimit(this, "THE"),
_vLimit(this, "V"),
// altitude/climb rate hold
_h2Thr(this, "H2THR"),
_cr2Thr(this, "CR2THR"),
// guidance block
_guide(this, ""),
_trimAil(this, "TRIM_ROLL", false), /* general roll trim (full name: TRIM_ROLL) */
_trimElv(this, "TRIM_PITCH", false), /* general pitch trim */
_trimRdr(this, "TRIM_YAW", false), /* general yaw trim */
_trimThr(this, "TRIM_THR"), /* FWB_ specific throttle trim (full name: FWB_TRIM_THR) */
_trimV(this, "TRIM_V"), /* FWB_ specific trim velocity (full name : FWB_TRIM_V) */
_vCmd(this, "V_CMD"),
_crMax(this, "CR_MAX"),
_attPoll(),
_lastPosCmd(),
_timeStamp(0)
{
_attPoll.fd = _att.getHandle();
_attPoll.events = POLLIN;
}
void BlockMultiModeBacksideAutopilot::update()
{
// wait for a sensor update, check for exit condition every 100 ms
if (poll(&_attPoll, 1, 100) < 0) return; // poll error
uint64_t newTimeStamp = hrt_absolute_time();
float dt = (newTimeStamp - _timeStamp) / 1.0e6f;
_timeStamp = newTimeStamp;
// check for sane values of dt
// to prevent large control responses
if (dt > 1.0f || dt < 0) return;
// set dt for all child blocks
setDt(dt);
// store old position command before update if new command sent
if (_posCmd.updated()) {
_lastPosCmd = _posCmd.getData();
}
// check for new updates
if (_param_update.updated()) updateParams();
// get new information from subscriptions
updateSubscriptions();
// default all output to zero unless handled by mode
for (unsigned i = 4; i < NUM_ACTUATOR_CONTROLS; i++)
_actuators.control[i] = 0.0f;
// only update guidance in auto mode
if (_status.main_state == MAIN_STATE_AUTO) {
// TODO use vehicle_control_mode here?
// update guidance
_guide.update(_pos, _att, _posCmd.current, _lastPosCmd.current);
}
// XXX handle STABILIZED (loiter on spot) as well
// once the system switches from manual or auto to stabilized
// the setpoint should update to loitering around this position
// handle autopilot modes
if (_status.main_state != MAIN_STATE_AUTO) {
// calculate velocity, XXX should be airspeed,
// but using ground speed for now for the purpose
// of control we will limit the velocity feedback between
// the min/max velocity
float v = _vLimit.update(sqrtf(
_pos.vx * _pos.vx +
_pos.vy * _pos.vy +
_pos.vz * _pos.vz));
// limit velocity command between min/max velocity
float vCmd = _vLimit.update(_vCmd.get());
// altitude hold
float dThrottle = _h2Thr.update(_posCmd.current.altitude - _pos.alt);
// heading hold
float psiError = _wrap_pi(_guide.getPsiCmd() - _att.yaw);
float phiCmd = _phiLimit.update(_psi2Phi.update(psiError));
float pCmd = _phi2P.update(phiCmd - _att.roll);
// velocity hold
// negative sign because nose over to increase speed
float thetaCmd = _theLimit.update(-_v2Theta.update(vCmd - v));
float qCmd = _theta2Q.update(thetaCmd - _att.pitch);
// yaw rate cmd
float rCmd = 0;
// stabilization
float velocityRatio = _trimV.get()/v;
float outputScale = velocityRatio*velocityRatio;
// this term scales the output based on the dynamic pressure change from trim
_stabilization.update(pCmd, qCmd, rCmd,
_att.rollspeed, _att.pitchspeed, _att.yawspeed,
outputScale);
// output
_actuators.control[CH_AIL] = _stabilization.getAileron() + _trimAil.get();
_actuators.control[CH_ELV] = _stabilization.getElevator() + _trimElv.get();
_actuators.control[CH_RDR] = _stabilization.getRudder() + _trimRdr.get();
_actuators.control[CH_THR] = dThrottle + _trimThr.get();
// XXX limit throttle to manual setting (safety) for now.
// If it turns out to be confusing, it can be removed later once
// a first binary release can be targeted.
// This is not a hack, but a design choice.
// do not limit in HIL
if (_status.hil_state != HIL_STATE_ON) {
/* limit to value of manual throttle */
_actuators.control[CH_THR] = (_actuators.control[CH_THR] < _manual.throttle) ?
_actuators.control[CH_THR] : _manual.throttle;
}
} else if (_status.main_state == MAIN_STATE_MANUAL) {
_actuators.control[CH_AIL] = _manual.roll;
_actuators.control[CH_ELV] = _manual.pitch;
_actuators.control[CH_RDR] = _manual.yaw;
_actuators.control[CH_THR] = _manual.throttle;
} else if (_status.main_state == MAIN_STATE_SEATBELT ||
_status.main_state == MAIN_STATE_EASY /* TODO, implement easy */) {
// calculate velocity, XXX should be airspeed, but using ground speed for now
// for the purpose of control we will limit the velocity feedback between
// the min/max velocity
float v = _vLimit.update(sqrtf(
_pos.vx * _pos.vx +
_pos.vy * _pos.vy +
_pos.vz * _pos.vz));
// pitch channel -> rate of climb
// TODO, might want to put a gain on this, otherwise commanding
// from +1 -> -1 m/s for rate of climb
//float dThrottle = _cr2Thr.update(
//_crMax.get()*_manual.pitch - _pos.vz);
// roll channel -> bank angle
float phiCmd = _phiLimit.update(_manual.roll * _phiLimit.getMax());
float pCmd = _phi2P.update(phiCmd - _att.roll);
// throttle channel -> velocity
// negative sign because nose over to increase speed
float vCmd = _vLimit.update(_manual.throttle *
(_vLimit.getMax() - _vLimit.getMin()) +
_vLimit.getMin());
float thetaCmd = _theLimit.update(-_v2Theta.update(vCmd - v));
float qCmd = _theta2Q.update(thetaCmd - _att.pitch);
// yaw rate cmd
float rCmd = 0;
// stabilization
_stabilization.update(pCmd, qCmd, rCmd,
_att.rollspeed, _att.pitchspeed, _att.yawspeed);
// output
_actuators.control[CH_AIL] = _stabilization.getAileron() + _trimAil.get();
_actuators.control[CH_ELV] = _stabilization.getElevator() + _trimElv.get();
_actuators.control[CH_RDR] = _stabilization.getRudder() + _trimRdr.get();
// currently using manual throttle
// XXX if you enable this watch out, vz might be very noisy
//_actuators.control[CH_THR] = dThrottle + _trimThr.get();
_actuators.control[CH_THR] = _manual.throttle;
// XXX limit throttle to manual setting (safety) for now.
// If it turns out to be confusing, it can be removed later once
// a first binary release can be targeted.
// This is not a hack, but a design choice.
/* do not limit in HIL */
if (_status.hil_state != HIL_STATE_ON) {
/* limit to value of manual throttle */
_actuators.control[CH_THR] = (_actuators.control[CH_THR] < _manual.throttle) ?
_actuators.control[CH_THR] : _manual.throttle;
}
// body rates controller, disabled for now
// TODO
} else if (0 /*_status.manual_control_mode == VEHICLE_MANUAL_CONTROL_MODE_SAS*/) { // TODO use vehicle_control_mode here?
_stabilization.update(_manual.roll, _manual.pitch, _manual.yaw,
_att.rollspeed, _att.pitchspeed, _att.yawspeed);
_actuators.control[CH_AIL] = _stabilization.getAileron();
_actuators.control[CH_ELV] = _stabilization.getElevator();
_actuators.control[CH_RDR] = _stabilization.getRudder();
_actuators.control[CH_THR] = _manual.throttle;
}
// update all publications
updatePublications();
}
BlockMultiModeBacksideAutopilot::~BlockMultiModeBacksideAutopilot()
{
// send one last publication when destroyed, setting
// all output to zero
for (unsigned i = 0; i < NUM_ACTUATOR_CONTROLS; i++)
_actuators.control[i] = 0.0f;
updatePublications();
}
} // namespace fixedwing
} // namespace control
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: linepropertiescontext.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef OOX_DRAWINGML_LINEPROPERTIESCONTEXT_HXX
#define OOX_DRAWINGML_LINEPROPERTIESCONTEXT_HXX
#include "oox/core/contexthandler.hxx"
#include "oox/drawingml/lineproperties.hxx"
namespace oox { namespace core {
class PropertyMap;
} }
namespace oox { namespace drawingml {
// ---------------------------------------------------------------------
class LinePropertiesContext : public ::oox::core::ContextHandler
{
public:
LinePropertiesContext( ::oox::core::ContextHandler& rParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes,
LineProperties& rLineProperties ) throw();
~LinePropertiesContext();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL
createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
protected:
LineProperties& mrLineProperties;
};
} }
#endif // OOX_DRAWINGML_LINEPROPERTIESCONTEXT_HXX
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.4.6); FILE MERGED 2008/06/09 15:16:11 dr 1.4.6.3: more chart line formatting, add line dashs to chart dash container 2008/06/06 16:27:51 dr 1.4.6.2: chart formatting: builtin line/fill/effect styles, manual line formatting 2008/05/27 10:40:27 dr 1.4.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: linepropertiescontext.hxx,v $
* $Revision: 1.5 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef OOX_DRAWINGML_LINEPROPERTIESCONTEXT_HXX
#define OOX_DRAWINGML_LINEPROPERTIESCONTEXT_HXX
#include "oox/core/contexthandler.hxx"
namespace oox { namespace drawingml {
// ---------------------------------------------------------------------
struct LineProperties;
class LinePropertiesContext : public ::oox::core::ContextHandler
{
public:
LinePropertiesContext( ::oox::core::ContextHandler& rParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& xAttributes,
LineProperties& rLineProperties ) throw();
~LinePropertiesContext();
virtual ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastContextHandler > SAL_CALL
createFastChildContext( ::sal_Int32 Element, const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XFastAttributeList >& Attribs )
throw (::com::sun::star::xml::sax::SAXException, ::com::sun::star::uno::RuntimeException);
protected:
LineProperties& mrLineProperties;
};
} }
#endif // OOX_DRAWINGML_LINEPROPERTIESCONTEXT_HXX
<|endoftext|> |
<commit_before>/**
* This is an open source non-commercial project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*
* @file FileProviderList.cpp
* @brief
* @details
* @date Created on 06.12.2016
* @copyright 2016 DDwarf LLC, <dev@ddwarf.org>
* @author Gilmanov Ildar <dev@ddwarf.org>
*/
#include <QDebug>
#include <QtQml>
#include "FileProviderList.h"
#include "FileProvider.h"
namespace DDwarf {
namespace Files {
FileProviderList *FileProviderList::m_instance = nullptr;
FileProviderList *FileProviderList::initStatic()
{
if(m_instance)
{
qWarning().noquote() << QString("FileProviderList is already initialized");
return m_instance;
}
m_instance = new FileProviderList();
qmlRegisterSingletonType<FileProviderList>("org.ddwarf.files",
1, 0,
"FileProviderList",
&FileProviderList::fileProviderListProvider);
qmlRegisterType<FileProvider>("org.ddwarf.files", 1, 0, "FileProvider");
return m_instance;
}
FileProviderList *FileProviderList::instance()
{
return m_instance;
}
FileProviderList::FileProviderList(QObject *parent) :
QAbstractListModel(parent)
{
m_roles.insert(Qt::UserRole, "modelData");
int index = Qt::UserRole + 1;
for(int i = 0; i < FileProvider::staticMetaObject.propertyCount(); ++i)
{
QMetaProperty prop = FileProvider::staticMetaObject.property(i);
if(prop.isReadable())
{
m_roles.insert(index, prop.name());
++index;
}
}
}
QObject *FileProviderList::fileProviderListProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
return m_instance;
}
int FileProviderList::rowCount(const QModelIndex &parent) const
{
if(parent.isValid())
{
return 0;
}
return m_list.count();
}
QVariant FileProviderList::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
{
return QVariant();
}
FileProvider *item = at(index.row());
if(item)
{
if(role == Qt::UserRole)
{
return QVariant::fromValue(item);
}
else if(m_roles.contains(role))
{
int propIndex = item->metaObject()->indexOfProperty(m_roles.value(role));
if(propIndex >= 0 && propIndex < item->metaObject()->propertyCount())
{
return item->metaObject()->property(propIndex).read(item);
}
else
{
qWarning().noquote() << QString("Can not find role '%1'")
.arg(QString(m_roles.value(role)));
return QVariant();
}
}
else
{
qWarning().noquote() << QString("Can not recognize role '%1'").arg(role);
return QVariant();
}
}
else
{
return QVariant();
}
}
QHash<int, QByteArray> FileProviderList::roleNames() const
{
return m_roles;
}
int FileProviderList::length() const
{
return m_list.count();
}
void FileProviderList::append(FileProvider *item)
{
if(!m_list.contains(item))
{
beginInsertRows(QModelIndex(), m_list.count(), m_list.count());
item->setParent(this);
m_list.push_back(item);
endInsertRows();
emit listChanged();
}
}
void FileProviderList::insert(int index, FileProvider *item)
{
if(!m_list.contains(item))
{
beginInsertRows(QModelIndex(), index, index);
item->setParent(this);
m_list.insert(index, item);
endInsertRows();
emit listChanged();
}
}
void FileProviderList::remove(FileProvider *item)
{
int index = m_list.indexOf(item);
if(index >= 0)
{
removeAt(index);
}
else
{
qWarning().noquote() << "Can not find IFileProvider to remove";
}
}
void FileProviderList::removeAt(int index)
{
if(index >= 0 && index < m_list.count())
{
beginRemoveRows(QModelIndex(), index, index);
m_list.takeAt(index)->deleteLater();
endRemoveRows();
emit listChanged();
}
else
{
qWarning().noquote() << QString("index %1 is out of range [0, %2]")
.arg(index)
.arg(m_list.count());
}
}
void FileProviderList::clear()
{
if(!m_list.isEmpty())
{
beginResetModel();
while(!m_list.isEmpty())
{
m_list.takeFirst()->deleteLater();
}
emit listChanged();
endResetModel();
}
}
FileProvider *FileProviderList::at(int index) const
{
if(index >= 0 && index < m_list.count())
{
return m_list.at(index);
}
else
{
qWarning().noquote() << QString("index %1 is out of range [0, %2]")
.arg(index)
.arg(m_list.count());
return nullptr;
}
}
} // namespace Files
} // namespace DDwarf
<commit_msg>add a comment<commit_after>/**
* This is an open source non-commercial project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*
* @file FileProviderList.cpp
* @brief
* @details
* @date Created on 06.12.2016
* @copyright 2016 DDwarf LLC, <dev@ddwarf.org>
* @author Gilmanov Ildar <dev@ddwarf.org>
*/
#include <QDebug>
#include <QtQml>
#include "FileProviderList.h"
#include "FileProvider.h"
namespace DDwarf {
namespace Files {
FileProviderList *FileProviderList::m_instance = nullptr;
FileProviderList *FileProviderList::initStatic()
{
if(m_instance)
{
qWarning().noquote() << QString("FileProviderList is already initialized");
return m_instance;
}
m_instance = new FileProviderList();
// org.ddwarf.files
qmlRegisterSingletonType<FileProviderList>("org.ddwarf.files",
1, 0,
"FileProviderList",
&FileProviderList::fileProviderListProvider);
qmlRegisterType<FileProvider>("org.ddwarf.files", 1, 0, "FileProvider");
return m_instance;
}
FileProviderList *FileProviderList::instance()
{
return m_instance;
}
FileProviderList::FileProviderList(QObject *parent) :
QAbstractListModel(parent)
{
m_roles.insert(Qt::UserRole, "modelData");
int index = Qt::UserRole + 1;
for(int i = 0; i < FileProvider::staticMetaObject.propertyCount(); ++i)
{
QMetaProperty prop = FileProvider::staticMetaObject.property(i);
if(prop.isReadable())
{
m_roles.insert(index, prop.name());
++index;
}
}
}
QObject *FileProviderList::fileProviderListProvider(QQmlEngine *engine, QJSEngine *scriptEngine)
{
Q_UNUSED(engine)
Q_UNUSED(scriptEngine)
return m_instance;
}
int FileProviderList::rowCount(const QModelIndex &parent) const
{
if(parent.isValid())
{
return 0;
}
return m_list.count();
}
QVariant FileProviderList::data(const QModelIndex &index, int role) const
{
if(!index.isValid())
{
return QVariant();
}
FileProvider *item = at(index.row());
if(item)
{
if(role == Qt::UserRole)
{
return QVariant::fromValue(item);
}
else if(m_roles.contains(role))
{
int propIndex = item->metaObject()->indexOfProperty(m_roles.value(role));
if(propIndex >= 0 && propIndex < item->metaObject()->propertyCount())
{
return item->metaObject()->property(propIndex).read(item);
}
else
{
qWarning().noquote() << QString("Can not find role '%1'")
.arg(QString(m_roles.value(role)));
return QVariant();
}
}
else
{
qWarning().noquote() << QString("Can not recognize role '%1'").arg(role);
return QVariant();
}
}
else
{
return QVariant();
}
}
QHash<int, QByteArray> FileProviderList::roleNames() const
{
return m_roles;
}
int FileProviderList::length() const
{
return m_list.count();
}
void FileProviderList::append(FileProvider *item)
{
if(!m_list.contains(item))
{
beginInsertRows(QModelIndex(), m_list.count(), m_list.count());
item->setParent(this);
m_list.push_back(item);
endInsertRows();
emit listChanged();
}
}
void FileProviderList::insert(int index, FileProvider *item)
{
if(!m_list.contains(item))
{
beginInsertRows(QModelIndex(), index, index);
item->setParent(this);
m_list.insert(index, item);
endInsertRows();
emit listChanged();
}
}
void FileProviderList::remove(FileProvider *item)
{
int index = m_list.indexOf(item);
if(index >= 0)
{
removeAt(index);
}
else
{
qWarning().noquote() << "Can not find IFileProvider to remove";
}
}
void FileProviderList::removeAt(int index)
{
if(index >= 0 && index < m_list.count())
{
beginRemoveRows(QModelIndex(), index, index);
m_list.takeAt(index)->deleteLater();
endRemoveRows();
emit listChanged();
}
else
{
qWarning().noquote() << QString("index %1 is out of range [0, %2]")
.arg(index)
.arg(m_list.count());
}
}
void FileProviderList::clear()
{
if(!m_list.isEmpty())
{
beginResetModel();
while(!m_list.isEmpty())
{
m_list.takeFirst()->deleteLater();
}
emit listChanged();
endResetModel();
}
}
FileProvider *FileProviderList::at(int index) const
{
if(index >= 0 && index < m_list.count())
{
return m_list.at(index);
}
else
{
qWarning().noquote() << QString("index %1 is out of range [0, %2]")
.arg(index)
.arg(m_list.count());
return nullptr;
}
}
} // namespace Files
} // namespace DDwarf
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <utility>
using namespace std;
// Assume all inputs are invalid.
// Assume n is the number of elements to be sorted.
// TC: Best = O(n^2), Average = O(n^2), Worst = O(n^2)
// SC: O(1)
void SelectionSort(int *data, int first, int last)
{
// [first, first_unsorted) is sorted, [first_unsorted, last) is unsorted.
for(int first_unsorted = first; first_unsorted < last; ++first_unsorted)
{
int min_index = first_unsorted;
for(int compare_index = first_unsorted + 1; compare_index < last; ++compare_index)
{
if(data[min_index] > data[compare_index])
{
min_index = compare_index;
}
}
if(min_index != first_unsorted)
{
swap(data[min_index], data[first_unsorted]);
}
// One more element is sorted:
// [first, first_unsorted + 1) is sorted, [first_unsorted + 1, last) is unsorted.
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TC: Best = O(n), Average = O(n^2), Worst = O(n^2)
// SC: O(1)
void BubbleSort(int *data, int first, int last) // [first, last)
{
// [first, first + unsorted_number) is unsorted
// [first + unsorted_number, last) is sorted.
for(int unsorted_number = last - first; unsorted_number > 0; )
{
int last_swap_index = -1;
// Traverse [first, first + unsorted_number)
for(int latter_index = first + 1;
latter_index < first + unsorted_number;
++latter_index)
{
if(data[latter_index - 1] > data[latter_index])
{
swap(data[latter_index - 1], data[latter_index]);
last_swap_index = latter_index;
}
}
// [first, last_swap_index) is unsorted, [last_swap_index, last) is sorted.
unsorted_number = last_swap_index - first;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TC: Best = O(n), Average = O(n^2), Worst = O(n^2)
// SC: O(1)
void InsertionSort(int *data, int first, int last)
{
// [first, first_unsorted) is sorted, [first_unsorted, last) is unsorted.
for(int first_unsorted = first; first_unsorted < last; ++first_unsorted)
{
for(int latter_index = first_unsorted;
latter_index - 1 >= first && data[latter_index - 1] > data[latter_index];
--latter_index)
{
swap(data[latter_index - 1], data[latter_index]);
}
// One more element is sorted.
// [first, first_unsorted + 1) is sorted; [first_unsorted + 1, last) is unsorted.
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int Partition(int *data, int first, int last) // O(n)
{
int pivot = data[last - 1];
int not_greater_number = 0;
for(int index = first; index < last - 1; ++index)
{
if(data[index] <= pivot)
{
++not_greater_number;
if(index != first + not_greater_number - 1)
{
swap(data[index], data[first + not_greater_number - 1]);
}
}
}
if(first + not_greater_number != last - 1)
{
swap(data[first + not_greater_number], data[last - 1]);
}
return first + not_greater_number;
}
// TC: Best = O(nlogn), Average = O(nlogn), Worst = O(n^2)
// SC: Best = O(logn), Worst = O(n)
void QuickSort(int *data, int first, int last) // [first, last)
{
if(last - first <= 1) // Only one element is auto sorted.
{
return;
}
// Divide: [first, divide) <= [divide, divide + 1) < [divide + 1, last)
int divide = Partition(data, first, last);
// Conquer: sort [first, divide) and [divide + 1, last) by recursive calls.
QuickSort(data, first, divide);
QuickSort(data, divide + 1, last);
// Combine: sub arrays are sorted, no work is needed to combine them.
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Merge(int *data, int first, int middle, int last, int *helper) // O(n)
{
int left = first; // index in left-subrange [first, middle).
int right = middle; // index in right-subrange [middle, last).
int helper_index = first; // index in helper.
while(left < middle || right < last) // Either subrange is not empty
{
// Copy left element into helper when:
// 1. Left subrange is not empty and right subrange is empty:
// `left < middle && right >= last`
// 2. Both are not empty and left element is lesser than or equal to right element:
// `left < middle && right < last && data[left] <= data[right]`
// NOTE:
// 1. `||` is short-circuit.
// 2. `<=` keep the relative order of equal elements, thus guarantee sorting stability.
if(right >= last || (left < middle && data[left] <= data[right]))
{
helper[helper_index++] = data[left++];
}
else
{
helper[helper_index++] = data[right++];
}
}
// Copy sorted elements into data.
for(int index = first; index < last; ++index)
{
data[index] = helper[index];
}
}
void MergeSortMain(int *data, int first, int last, int *helper)
{
if(last - first <= 1) // Only 1 element is auto sorted.
{
return;
}
// Divide: divide n-element array into two n/2-element subarrays.
int middle = first + (last - first) / 2;
// Conquer: sort two subarrays [first, middle) and [middle, last) recursively.
MergeSortMain(data, first, middle, helper);
MergeSortMain(data, middle, last, helper);
// Combine: merge two sorted subarrays.
Merge(data, first, middle, last, helper);
}
// TC: Best = O(nlogn), Average = O(nlogn), Worst = O(nlogn)
// SC: O(n)
void MergeSort(int *data, int first, int last) // [first, last)
{
int helper[last]; // helper temporary stores the sorted subarrays in Merge.
MergeSortMain(data, first, last, helper);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void MinHeapFixDown(int *data, int parent_index, int last)
{
int max_child_index = parent_index * 2 + 1;
while(max_child_index < last)
{
if(max_child_index < last - 1 &&
data[max_child_index] < data[max_child_index + 1])
{
++max_child_index;
}
if(data[parent_index] >= data[max_child_index]) // `=` guarantee stable.
{
return;
}
std::swap(data[parent_index], data[max_child_index]);
parent_index = max_child_index;
max_child_index = parent_index * 2 + 1;
}
}
// TC: Best = O(nlogn), Average = O(nlogn), Worst = O(nlogn)
// SC: O(1)
void HeapSort(int *data, int first, int last)// 改成正序!!!
{
// 1. Convert array to min heap. [first, first + length/2 - 1] has children.
// O(n): See ITA Page 159
for(int parent_index = first + (last - first) / 2 - 1; parent_index >= first; --parent_index)
{
MinHeapFixDown(data, parent_index, last);
}
// 2. Extract min. O(nlogn)
for(int index = last - 1; index >= first; --index)
{
if(data[first] != data[index]) // Guarantee stable.
{
std::swap(data[first], data[index]);
MinHeapFixDown(data, first, index);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// n is the number of inputs, m is the max value.
// TC: Best = Average = Worst = O(n + m)
// SC: O(n + m)
void CountingSort(int *data, int first, int last) // [first, last)
{
// Get the maximum value.
int max_value = data[first];
for(int index = first + 1; index < last; ++index)
{
if(max_value < data[index])
{
max_value = data[index];
}
}
int count[max_value + 1]; // count[value] is the count of elements that are <= value.
memset(count, 0, sizeof count);
int temp[last]; // Temporary store the sorted elements.
// Count the frequency of every value in data.
for(int index = first; index < last; ++index)
{
++count[data[index]];
}
// Compute how many elements are <= value.
for(int value = 1; value <= max_value; ++value)
{
count[value] += count[value - 1];
}
// 1. x elements <= value: place value in [x - 1].
// 2. Place from back to front: keep stability.
for(int index = last - 1; index >= first; --index)
{
temp[--count[data[index]]] = data[index];
}
// Copy the sorted elements into data.
for(int index = first; index < last; ++index)
{
data[index] = temp[index];
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// n is the number of inputs, d is the number of digits, m is the max value in each digit.
// TC: Best = Average = Worst = O(d(n + m))
// SC: O(n + m)
void RadixSort(int *data, int first, int last)
{
const int kMaxDigitValue = 9;
const int kDigitValueNumber = kMaxDigitValue + 1;
int digit_number[last], count[kDigitValueNumber], temp[last];
const int kMaxDigitNumber = 10; // 10^10 < 2^31 < 10^11, thus has at most 10 digits.
int divisor = 1;
for(int digit = 1; digit <= kMaxDigitNumber; ++digit)
{
memset(count, 0, sizeof count);
// Get each digit number from least to most significant digit.
for(int index = first; index < last; ++index)
{
digit_number[index] = (data[index] / divisor) % kDigitValueNumber;
++count[digit_number[index]];
}
for(int value = 1; value <= kMaxDigitValue; ++value)
{
count[value] += count[value - 1];
}
for(int index = last - 1; index >= first; --index)
{
// Sort according to digit_number, but store data.
temp[--count[digit_number[index]]] = data[index];
}
for(int index = first; index < last; ++index)
{
data[index] = temp[index];
}
// Update divisor to get the next digit_number.
divisor *= kDigitValueNumber;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PrintData(int *data, int first, int last)
{
for(int index = 0; index < last; ++index)
{
printf("%d ", data[index]);
}
printf("\n");
}
using SortFunction = void(*)(int*, int, int);
void Test(const char *name, SortFunction Sort)
{
printf("----------%s----------\n", name);
const int data_length = 10;
int data[][data_length] =
{
{0,1,2,3,4,5,6,7,8,9},
{9,8,7,6,5,4,3,2,1,0},
{0,2,4,6,8,9,7,5,3,1}
};
int data_number = static_cast<int>(sizeof(data) / sizeof(data[0]));
for(int data_index = 0; data_index < data_number; ++data_index)
{
Sort(data[data_index], 0, data_length);
PrintData(data[data_index], 0, data_length);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
Test("SelectionSort", SelectionSort);
Test("BubbleSort", BubbleSort);
Test("InsertionSort", InsertionSort);
Test("QuickSort", QuickSort);
Test("MergeSort", MergeSort);
Test("HeapSort", HeapSort);
Test("CountingSort", CountingSort);
Test("RadixSort", RadixSort);
}
<commit_msg>docs: update readme<commit_after>#include <stdio.h>
#include <string.h>
#include <utility>
using namespace std;
// Assume all inputs are invalid.
// Assume n is the number of elements to be sorted.
// TC: Best = O(n^2), Average = O(n^2), Worst = O(n^2)
// SC: O(1)
void SelectionSort(int *data, int first, int last)
{
// [first, first_unsorted) is sorted, [first_unsorted, last) is unsorted.
for(int first_unsorted = first; first_unsorted < last; ++first_unsorted)
{
int min_index = first_unsorted;
for(int compare_index = first_unsorted + 1; compare_index < last; ++compare_index)
{
if(data[min_index] > data[compare_index])
{
min_index = compare_index;
}
}
if(min_index != first_unsorted)
{
swap(data[min_index], data[first_unsorted]);
}
// One more element is sorted:
// [first, first_unsorted + 1) is sorted, [first_unsorted + 1, last) is unsorted.
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TC: Best = O(n), Average = O(n^2), Worst = O(n^2)
// SC: O(1)
void BubbleSort(int *data, int first, int last) // [first, last)
{
// [first, first + unsorted_number) is unsorted
// [first + unsorted_number, last) is sorted.
for(int unsorted_number = last - first; unsorted_number > 0; )
{
int last_swap_index = -1;
// Traverse [first, first + unsorted_number)
for(int latter_index = first + 1;
latter_index < first + unsorted_number;
++latter_index)
{
if(data[latter_index - 1] > data[latter_index])
{
swap(data[latter_index - 1], data[latter_index]);
last_swap_index = latter_index;
}
}
// [first, last_swap_index) is unsorted, [last_swap_index, last) is sorted.
unsorted_number = last_swap_index - first;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TC: Best = O(n), Average = O(n^2), Worst = O(n^2)
// SC: O(1)
void InsertionSort(int *data, int first, int last)
{
// [first, first_unsorted) is sorted, [first_unsorted, last) is unsorted.
for(int first_unsorted = first; first_unsorted < last; ++first_unsorted)
{
for(int latter_index = first_unsorted;
latter_index - 1 >= first && data[latter_index - 1] > data[latter_index];
--latter_index)
{
swap(data[latter_index - 1], data[latter_index]);
}
// One more element is sorted.
// [first, first_unsorted + 1) is sorted; [first_unsorted + 1, last) is unsorted.
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int Partition(int *data, int first, int last) // O(n)
{
int pivot = data[last - 1];
int not_greater_number = 0;
for(int index = first; index < last - 1; ++index)
{
if(data[index] <= pivot)
{
++not_greater_number;
if(index != first + not_greater_number - 1)
{
swap(data[index], data[first + not_greater_number - 1]);
}
}
}
if(first + not_greater_number != last - 1)
{
swap(data[first + not_greater_number], data[last - 1]);
}
return first + not_greater_number;
}
// TC: Best = O(nlogn), Average = O(nlogn), Worst = O(n^2)
// SC: Best = O(logn), Worst = O(n)
void QuickSort(int *data, int first, int last) // [first, last)
{
if(last - first <= 1) // Only one element is auto sorted.
{
return;
}
// Divide: [first, divide) <= [divide, divide + 1) < [divide + 1, last)
int divide = Partition(data, first, last);
// Conquer: sort [first, divide) and [divide + 1, last) by recursive calls.
QuickSort(data, first, divide);
QuickSort(data, divide + 1, last);
// Combine: sub arrays are sorted, no work is needed to combine them.
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Merge(int *data, int first, int middle, int last, int *helper) // O(n)
{
int left = first; // index in left-subrange [first, middle).
int right = middle; // index in right-subrange [middle, last).
int helper_index = first; // index in helper.
while(left < middle || right < last) // Either subrange is not empty
{
// Copy left element into helper when:
// 1. Left subrange is not empty and right subrange is empty:
// `left < middle && right >= last`
// 2. Both are not empty and left element is lesser than or equal to right element:
// `left < middle && right < last && data[left] <= data[right]`
// NOTE:
// 1. `||` is short-circuit.
// 2. `<=` keep the relative order of equal elements, thus guarantee sorting stability.
if(right >= last || (left < middle && data[left] <= data[right]))
{
helper[helper_index++] = data[left++];
}
else
{
helper[helper_index++] = data[right++];
}
}
// Copy sorted elements into data.
for(int index = first; index < last; ++index)
{
data[index] = helper[index];
}
}
void MergeSortMain(int *data, int first, int last, int *helper)
{
if(last - first <= 1) // Only 1 element is auto sorted.
{
return;
}
// Divide: divide n-element array into two n/2-element subarrays.
int middle = first + (last - first) / 2;
// Conquer: sort two subarrays [first, middle) and [middle, last) recursively.
MergeSortMain(data, first, middle, helper);
MergeSortMain(data, middle, last, helper);
// Combine: merge two sorted subarrays.
Merge(data, first, middle, last, helper);
}
// TC: Best = O(nlogn), Average = O(nlogn), Worst = O(nlogn)
// SC: O(n)
void MergeSort(int *data, int first, int last) // [first, last)
{
int helper[last]; // helper temporary stores the sorted subarrays in Merge.
MergeSortMain(data, first, last, helper);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void FixDown(int *data, int parent_index, int last)
{
int max_child_index = parent_index * 2 + 1;
while(max_child_index < last)
{
if(max_child_index < last - 1 &&
data[max_child_index] < data[max_child_index + 1])
{
++max_child_index;
}
if(data[parent_index] >= data[max_child_index]) // `=` guarantee stable.
{
return;
}
swap(data[parent_index], data[max_child_index]);
parent_index = max_child_index;
max_child_index = parent_index * 2 + 1;
}
}
// TC: Best = O(nlogn), Average = O(nlogn), Worst = O(nlogn)
// SC: O(1)
void HeapSort(int *data, int first, int last)
{
// 1. Convert to max heap. O(n): See ITA Page 159.
// [first, first + ((length - 1) - 1) / 2] has children.
for(int parent_index = first + ((last - first - 1) - 1) / 2;
parent_index >= first;
--parent_index)
{
FixDown(data, parent_index, last);
}
// 2. Extract maximum. O(nlogn)
for(int index = last - 1; index >= first; --index)
{
if(data[first] != data[index]) // Guarantee stable.
{
swap(data[first], data[index]);
FixDown(data, first, index);
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// n is the number of inputs, m is the max value.
// TC: Best = Average = Worst = O(n + m)
// SC: O(n + m)
void CountingSort(int *data, int first, int last) // [first, last)
{
// Get the maximum value.
int max_value = data[first];
for(int index = first + 1; index < last; ++index)
{
if(max_value < data[index])
{
max_value = data[index];
}
}
int count[max_value + 1]; // count[value] is the count of elements that are <= value.
memset(count, 0, sizeof count);
int temp[last]; // Temporary store the sorted elements.
// Count the frequency of every value in data.
for(int index = first; index < last; ++index)
{
++count[data[index]];
}
// Compute how many elements are <= value.
for(int value = 1; value <= max_value; ++value)
{
count[value] += count[value - 1];
}
// 1. x elements <= value: place value in [x - 1].
// 2. Place from back to front: keep stability.
for(int index = last - 1; index >= first; --index)
{
temp[--count[data[index]]] = data[index];
}
// Copy the sorted elements into data.
for(int index = first; index < last; ++index)
{
data[index] = temp[index];
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// n is the number of inputs, d is the number of digits, m is the max value in each digit.
// TC: Best = Average = Worst = O(d(n + m))
// SC: O(n + m)
void RadixSort(int *data, int first, int last)
{
const int kMaxDigitValue = 9;
const int kDigitValueNumber = kMaxDigitValue + 1;
int digit_number[last], count[kDigitValueNumber], temp[last];
const int kMaxDigitNumber = 10; // 10^10 < 2^31 < 10^11, thus has at most 10 digits.
int divisor = 1;
for(int digit = 1; digit <= kMaxDigitNumber; ++digit)
{
memset(count, 0, sizeof count);
// Get each digit number from least to most significant digit.
for(int index = first; index < last; ++index)
{
digit_number[index] = (data[index] / divisor) % kDigitValueNumber;
++count[digit_number[index]];
}
for(int value = 1; value <= kMaxDigitValue; ++value)
{
count[value] += count[value - 1];
}
for(int index = last - 1; index >= first; --index)
{
// Sort according to digit_number, but store data.
temp[--count[digit_number[index]]] = data[index];
}
for(int index = first; index < last; ++index)
{
data[index] = temp[index];
}
// Update divisor to get the next digit_number.
divisor *= kDigitValueNumber;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PrintData(int *data, int first, int last)
{
for(int index = 0; index < last; ++index)
{
printf("%d ", data[index]);
}
printf("\n");
}
using SortFunction = void(*)(int*, int, int);
void Test(const char *name, SortFunction Sort)
{
printf("----------%s----------\n", name);
const int data_length = 10;
int data[][data_length] =
{
{0,1,2,3,4,5,6,7,8,9},
{9,8,7,6,5,4,3,2,1,0},
{0,2,4,6,8,9,7,5,3,1}
};
int data_number = static_cast<int>(sizeof(data) / sizeof(data[0]));
for(int data_index = 0; data_index < data_number; ++data_index)
{
Sort(data[data_index], 0, data_length);
PrintData(data[data_index], 0, data_length);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main()
{
Test("SelectionSort", SelectionSort);
Test("BubbleSort", BubbleSort);
Test("InsertionSort", InsertionSort);
Test("QuickSort", QuickSort);
Test("MergeSort", MergeSort);
Test("HeapSort", HeapSort);
Test("CountingSort", CountingSort);
Test("RadixSort", RadixSort);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstring>
#include "ataxx.hpp"
#include "search.hpp"
#include "movegen.hpp"
#include "move.hpp"
#include "makemove.hpp"
#include "hashtable.hpp"
#include "pv.hpp"
#include "searchinfo.hpp"
#include "eval.hpp"
#include "score.hpp"
#include "zobrist.hpp"
#include "sorting.hpp"
#include "nextMove.hpp"
#include "searchstack.hpp"
int alphaBeta(const Position& pos, searchInfo& info, searchStack *ss, PV& pv, int alpha, int beta, int depth)
{
if(depth == 0 || info.depth >= MAX_DEPTH)
{
pv.numMoves = 0;
info.leafNodes++;
return eval(pos);
}
if(info.nodes != 0)
{
// Stop searching if we've ran out of time
if(*info.stop == true || clock() >= info.end)
{
return 0;
}
// Send an update on what we're doing
if(info.nodes % 2000000 == 0)
{
double timeSpent = (double)(clock() - info.start)/CLOCKS_PER_SEC;
std::cout << "info"
<< " nps " << (uint64_t)(info.nodes/timeSpent)
<< std::endl;
}
}
uint64_t key = generateKey(pos);
Move ttMove = NO_MOVE;
// Check the hash table
Entry entry = probe(info.tt, key);
if(key == entry.key)
{
ttMove = getMove(entry);
if(getDepth(entry) >= depth && legalMove(pos, ttMove) == true)
{
pv.numMoves = 1;
pv.moves[0] = ttMove;
return getEval(entry);
}
}
#ifdef NULLMOVE
#define R (2)
if(ss->nullmove && depth > 2)
{
PV newPV;
newPV.numMoves = 0;
Position newPos = pos;
newPos.turn = !newPos.turn;
(ss+1)->nullmove = false;
int score = -alphaBeta(newPos, info, ss+1, newPV, -beta, -beta+1, depth-1-R);
if(score >= beta)
{
return score;
}
}
(ss+1)->nullmove = true;
#endif
PV newPV;
newPV.numMoves = 0;
Move bestMove = NO_MOVE;
Move moves[256];
int numMoves = movegen(pos, moves);
// Score moves
int scores[256] = {0};
for(int n = 0; n < numMoves; ++n)
{
if(moves[n] == ttMove)
{
scores[n] = 1000;
}
#ifdef KILLER_MOVES
else if(moves[n] == ss->killer)
{
scores[n] = 500;
}
#endif
else
{
scores[n] = countCaptures(pos, moves[n]);
}
scores[n] += (isSingle(moves[n]) ? 1 : 0);
}
Move move;
while(nextMove(moves, numMoves, move, scores))
{
Position newPos = pos;
makemove(newPos, move);
info.nodes++;
int score = -alphaBeta(newPos, info, ss+1, newPV, -beta, -alpha, depth-1);
if(score >= beta)
{
#ifdef KILLER_MOVES
ss->killer = move;
#endif
return beta;
}
if(score > alpha)
{
alpha = score;
bestMove = move;
// Update PV
pv.moves[0] = move;
memcpy(pv.moves + 1, newPV.moves, newPV.numMoves * sizeof(Move));
pv.numMoves = newPV.numMoves + 1;
}
}
if(numMoves == 0)
{
pv.numMoves = 0;
int val = score(pos);
if(val > 0)
{
return INF - ss->ply;
}
else if(val < 0)
{
return -INF + ss->ply;
}
else
{
return 0;
}
}
// Add the hash table entry
add(info.tt, key, depth, alpha, bestMove);
return alpha;
}
<commit_msg>Some work on LMR<commit_after>#include <iostream>
#include <cstring>
#include "ataxx.hpp"
#include "search.hpp"
#include "movegen.hpp"
#include "move.hpp"
#include "makemove.hpp"
#include "hashtable.hpp"
#include "pv.hpp"
#include "searchinfo.hpp"
#include "eval.hpp"
#include "score.hpp"
#include "zobrist.hpp"
#include "sorting.hpp"
#include "nextMove.hpp"
#include "searchstack.hpp"
int reduction(const int moveNum, const int depth)
{
if(moveNum < 4 || depth < 3)
{
return 0;
}
return 1;
}
int alphaBeta(const Position& pos, searchInfo& info, searchStack *ss, PV& pv, int alpha, int beta, int depth)
{
if(depth == 0 || info.depth >= MAX_DEPTH)
{
pv.numMoves = 0;
info.leafNodes++;
return eval(pos);
}
if(info.nodes != 0)
{
// Stop searching if we've ran out of time
if(*info.stop == true || clock() >= info.end)
{
return 0;
}
// Send an update on what we're doing
if(info.nodes % 2000000 == 0)
{
double timeSpent = (double)(clock() - info.start)/CLOCKS_PER_SEC;
std::cout << "info"
<< " nps " << (uint64_t)(info.nodes/timeSpent)
<< std::endl;
}
}
uint64_t key = generateKey(pos);
Move ttMove = NO_MOVE;
// Check the hash table
Entry entry = probe(info.tt, key);
if(key == entry.key)
{
ttMove = getMove(entry);
if(getDepth(entry) >= depth && legalMove(pos, ttMove) == true)
{
pv.numMoves = 1;
pv.moves[0] = ttMove;
return getEval(entry);
}
}
#ifdef NULLMOVE
#define R (2)
if(ss->nullmove && depth > 2)
{
PV newPV;
newPV.numMoves = 0;
Position newPos = pos;
newPos.turn = !newPos.turn;
(ss+1)->nullmove = false;
int score = -alphaBeta(newPos, info, ss+1, newPV, -beta, -beta+1, depth-1-R);
if(score >= beta)
{
return score;
}
}
(ss+1)->nullmove = true;
#endif
PV newPV;
newPV.numMoves = 0;
Move bestMove = NO_MOVE;
Move moves[256];
int numMoves = movegen(pos, moves);
// Score moves
int scores[256] = {0};
for(int n = 0; n < numMoves; ++n)
{
if(moves[n] == ttMove)
{
scores[n] = 1000;
}
#ifdef KILLER_MOVES
else if(moves[n] == ss->killer)
{
scores[n] = 500;
}
#endif
else
{
scores[n] = countCaptures(pos, moves[n]);
}
scores[n] += (isSingle(moves[n]) ? 1 : 0);
}
int moveNum = 0;
Move move;
while(nextMove(moves, numMoves, move, scores))
{
Position newPos = pos;
makemove(newPos, move);
info.nodes++;
#ifdef LMR
int r = reduction(moveNum, depth);
int score = -alphaBeta(newPos, info, ss+1, newPV, -beta, -alpha, depth-1-r);
// Re-search
if(score > alpha && score < beta)
{
score = -alphaBeta(newPos, info, ss+1, newPV, -beta, -alpha, depth-1);
if(score > alpha)
{
alpha = score;
}
}
#else
int score = -alphaBeta(newPos, info, ss+1, newPV, -beta, -alpha, depth-1);
#endif
if(score >= beta)
{
#ifdef KILLER_MOVES
ss->killer = move;
#endif
return beta;
}
if(score > alpha)
{
alpha = score;
bestMove = move;
// Update PV
pv.moves[0] = move;
memcpy(pv.moves + 1, newPV.moves, newPV.numMoves * sizeof(Move));
pv.numMoves = newPV.numMoves + 1;
}
moveNum++;
}
if(numMoves == 0)
{
pv.numMoves = 0;
int val = score(pos);
if(val > 0)
{
return INF - ss->ply;
}
else if(val < 0)
{
return -INF + ss->ply;
}
else
{
return 0;
}
}
// Add the hash table entry
add(info.tt, key, depth, alpha, bestMove);
return alpha;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2016 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains an std::array-like implementation but with aligned data
* access.
*
* This implementation is limited to C++17. In earlier versions, it will only be
* aligned for stack-allocation variables, but not when dynamically allocated.
* In C++17, this is now fixed
*/
#ifndef CPP_SOFT_ALIGNED_ARRAY_HPP
#define CPP_SOFT_ALIGNED_ARRAY_HPP
/*!
* \brief Aligned std::array implementation
* \tparam T The value type
* \tparam S The size of the collection
* \tparam A The alignment in bytes
*/
template <typename T, std::size_t S, std::size_t A>
struct alignas(A) soft_aligned_array : std::array<T, S> {};
} //end of namespace cpp
#endif //CPP_SOFT_ALIGNED_ARRAY_HPP
<commit_msg>Fix namespace<commit_after>//=======================================================================
// Copyright (c) 2013-2016 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief Contains an std::array-like implementation but with aligned data
* access.
*
* This implementation is limited to C++17. In earlier versions, it will only be
* aligned for stack-allocation variables, but not when dynamically allocated.
* In C++17, this is now fixed
*/
#ifndef CPP_SOFT_ALIGNED_ARRAY_HPP
#define CPP_SOFT_ALIGNED_ARRAY_HPP
namespace cpp {
/*!
* \brief Aligned std::array implementation
* \tparam T The value type
* \tparam S The size of the collection
* \tparam A The alignment in bytes
*/
template <typename T, std::size_t S, std::size_t A>
struct alignas(A) soft_aligned_array : std::array<T, S> {};
} //end of namespace cpp
#endif //CPP_SOFT_ALIGNED_ARRAY_HPP
<|endoftext|> |
<commit_before>// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains string processing functions related to
// uppercase, lowercase, etc.
#include "ortools/base/case.h"
#include <functional>
#include <string>
//#include "base/port.h"
#include "absl/hash/hash.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
namespace strings {
std::ostream& operator<<(std::ostream& os,
const AsciiCapitalizationType& type) {
switch (type) {
case AsciiCapitalizationType::kLower:
return os << "kLower";
case AsciiCapitalizationType::kUpper:
return os << "kUpper";
case AsciiCapitalizationType::kFirst:
return os << "kFirst";
case AsciiCapitalizationType::kMixed:
return os << "kMixed";
case AsciiCapitalizationType::kNoAlpha:
return os << "kNoAlpha";
default:
return os << "INVALID";
}
}
AsciiCapitalizationType GetAsciiCapitalization(const absl::string_view input) {
const char* s = input.data();
const char* const end = s + input.size();
// find the caps type of the first alpha char
for (; s != end && !(absl::ascii_isupper(*s) || absl::ascii_islower(*s));
++s) {
}
if (s == end) return AsciiCapitalizationType::kNoAlpha;
const AsciiCapitalizationType firstcapstype =
(absl::ascii_islower(*s)) ? AsciiCapitalizationType::kLower
: AsciiCapitalizationType::kUpper;
// skip ahead to the next alpha char
for (++s; s != end && !(absl::ascii_isupper(*s) || absl::ascii_islower(*s));
++s) {
}
if (s == end) return firstcapstype;
const AsciiCapitalizationType capstype =
(absl::ascii_islower(*s)) ? AsciiCapitalizationType::kLower
: AsciiCapitalizationType::kUpper;
if (firstcapstype == AsciiCapitalizationType::kLower &&
capstype == AsciiCapitalizationType::kUpper)
return AsciiCapitalizationType::kMixed;
for (; s != end; ++s)
if ((absl::ascii_isupper(*s) &&
capstype != AsciiCapitalizationType::kUpper) ||
(absl::ascii_islower(*s) &&
capstype != AsciiCapitalizationType::kLower))
return AsciiCapitalizationType::kMixed;
if (firstcapstype == AsciiCapitalizationType::kUpper &&
capstype == AsciiCapitalizationType::kLower)
return AsciiCapitalizationType::kFirst;
return capstype;
}
int AsciiCaseInsensitiveCompare(absl::string_view s1, absl::string_view s2) {
if (s1.size() == s2.size()) {
return strncasecmp(s1.data(), s2.data(), s1.size());
} else if (s1.size() < s2.size()) {
int res = strncasecmp(s1.data(), s2.data(), s1.size());
return (res == 0) ? -1 : res;
} else {
int res = strncasecmp(s1.data(), s2.data(), s2.size());
return (res == 0) ? 1 : res;
}
}
size_t AsciiCaseInsensitiveHash::operator()(absl::string_view s) const {
//return absl::HashOf(absl::AsciiStrToLower(s));
return std::hash<std::string>{}(absl::AsciiStrToLower(s));
}
bool AsciiCaseInsensitiveEq::operator()(absl::string_view s1,
absl::string_view s2) const {
return s1.size() == s2.size() &&
strncasecmp(s1.data(), s2.data(), s1.size()) == 0;
}
void MakeAsciiTitlecase(std::string* s, absl::string_view delimiters) {
bool upper = true;
for (auto &ch : *s) {
if (upper) {
ch = absl::ascii_toupper(ch);
}
upper = (absl::StrContains(delimiters, ch));
}
}
std::string MakeAsciiTitlecase(absl::string_view s,
absl::string_view delimiters) {
std::string result(s);
MakeAsciiTitlecase(&result, delimiters);
return result;
}
} // namespace strings
<commit_msg>fix windows compilation<commit_after>// Copyright 2010-2021 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This file contains string processing functions related to
// uppercase, lowercase, etc.
#include "ortools/base/case.h"
#include <functional>
#include <string>
//#include "base/port.h"
#include "absl/hash/hash.h"
#include "absl/strings/ascii.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#ifdef _MSC_VER
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
#endif
namespace strings {
std::ostream& operator<<(std::ostream& os,
const AsciiCapitalizationType& type) {
switch (type) {
case AsciiCapitalizationType::kLower:
return os << "kLower";
case AsciiCapitalizationType::kUpper:
return os << "kUpper";
case AsciiCapitalizationType::kFirst:
return os << "kFirst";
case AsciiCapitalizationType::kMixed:
return os << "kMixed";
case AsciiCapitalizationType::kNoAlpha:
return os << "kNoAlpha";
default:
return os << "INVALID";
}
}
AsciiCapitalizationType GetAsciiCapitalization(const absl::string_view input) {
const char* s = input.data();
const char* const end = s + input.size();
// find the caps type of the first alpha char
for (; s != end && !(absl::ascii_isupper(*s) || absl::ascii_islower(*s));
++s) {
}
if (s == end) return AsciiCapitalizationType::kNoAlpha;
const AsciiCapitalizationType firstcapstype =
(absl::ascii_islower(*s)) ? AsciiCapitalizationType::kLower
: AsciiCapitalizationType::kUpper;
// skip ahead to the next alpha char
for (++s; s != end && !(absl::ascii_isupper(*s) || absl::ascii_islower(*s));
++s) {
}
if (s == end) return firstcapstype;
const AsciiCapitalizationType capstype =
(absl::ascii_islower(*s)) ? AsciiCapitalizationType::kLower
: AsciiCapitalizationType::kUpper;
if (firstcapstype == AsciiCapitalizationType::kLower &&
capstype == AsciiCapitalizationType::kUpper)
return AsciiCapitalizationType::kMixed;
for (; s != end; ++s)
if ((absl::ascii_isupper(*s) &&
capstype != AsciiCapitalizationType::kUpper) ||
(absl::ascii_islower(*s) &&
capstype != AsciiCapitalizationType::kLower))
return AsciiCapitalizationType::kMixed;
if (firstcapstype == AsciiCapitalizationType::kUpper &&
capstype == AsciiCapitalizationType::kLower)
return AsciiCapitalizationType::kFirst;
return capstype;
}
int AsciiCaseInsensitiveCompare(absl::string_view s1, absl::string_view s2) {
if (s1.size() == s2.size()) {
return strncasecmp(s1.data(), s2.data(), s1.size());
} else if (s1.size() < s2.size()) {
int res = strncasecmp(s1.data(), s2.data(), s1.size());
return (res == 0) ? -1 : res;
} else {
int res = strncasecmp(s1.data(), s2.data(), s2.size());
return (res == 0) ? 1 : res;
}
}
size_t AsciiCaseInsensitiveHash::operator()(absl::string_view s) const {
//return absl::HashOf(absl::AsciiStrToLower(s));
return std::hash<std::string>{}(absl::AsciiStrToLower(s));
}
bool AsciiCaseInsensitiveEq::operator()(absl::string_view s1,
absl::string_view s2) const {
return s1.size() == s2.size() &&
strncasecmp(s1.data(), s2.data(), s1.size()) == 0;
}
void MakeAsciiTitlecase(std::string* s, absl::string_view delimiters) {
bool upper = true;
for (auto &ch : *s) {
if (upper) {
ch = absl::ascii_toupper(ch);
}
upper = (absl::StrContains(delimiters, ch));
}
}
std::string MakeAsciiTitlecase(absl::string_view s,
absl::string_view delimiters) {
std::string result(s);
MakeAsciiTitlecase(&result, delimiters);
return result;
}
} // namespace strings
<|endoftext|> |
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_CXXAUX_HH__
#define __BSE_CXXAUX_HH__
#include <sfi/sysconfig.h>
#include <sys/types.h> // uint, ssize
#include <cstdint> // uint64_t
#include <vector>
#include <map>
namespace Bse {
// == uint ==
#if BSE_SIZEOF_SYS_TYPESH_UINT == 0
typedef unsigned int uint; ///< Provide 'uint' if sys/types.h fails to do so.
#else
static_assert (BSE_SIZEOF_SYS_TYPESH_UINT == 4, "");
#endif
static_assert (sizeof (uint) == 4, "");
// == type aliases ==
typedef uint8_t uint8; ///< An 8-bit unsigned integer.
typedef uint16_t uint16; ///< A 16-bit unsigned integer.
typedef uint32_t uint32; ///< A 32-bit unsigned integer.
typedef uint64_t uint64; ///< A 64-bit unsigned integer, use PRI*64 in format strings.
typedef int8_t int8; ///< An 8-bit signed integer.
typedef int16_t int16; ///< A 16-bit signed integer.
typedef int32_t int32; ///< A 32-bit signed integer.
typedef int64_t int64; ///< A 64-bit unsigned integer, use PRI*64 in format strings.
typedef uint32_t unichar; ///< A 32-bit unsigned integer used for Unicode characters.
static_assert (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8, "");
static_assert (sizeof (int8) == 1 && sizeof (int16) == 2 && sizeof (int32) == 4 && sizeof (int64) == 8, "");
static_assert (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4, "");
using std::map;
using std::vector;
typedef std::string String; ///< Convenience alias for std::string.
typedef vector<String> StringVector; ///< Convenience alias for a std::vector<std::string>.
// == Utility Macros ==
#define BSE_CPP_STRINGIFY(s) BSE_CPP_STRINGIFY_ (s) ///< Convert macro argument into a C const char*.
#define BSE_CPP_STRINGIFY_(s) #s // Indirection helper, required to expand macros like __LINE__
#define BSE_ISLIKELY(expr) __builtin_expect (bool (expr), 1) ///< Compiler hint to optimize for @a expr evaluating to true.
#define BSE_UNLIKELY(expr) __builtin_expect (bool (expr), 0) ///< Compiler hint to optimize for @a expr evaluating to false.
#define BSE_ABS(a) ((a) < 0 ? -(a) : (a)) ///< Yield the absolute value of @a a.
#define BSE_MIN(a,b) ((a) <= (b) ? (a) : (b)) ///< Yield the smaller value of @a a and @a b.
#define BSE_MAX(a,b) ((a) >= (b) ? (a) : (b)) ///< Yield the greater value of @a a and @a b.
#define BSE_CLAMP(v,mi,ma) ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v))) ///< Yield @a v clamped to [ @a mi .. @a ma ].
#define BSE_ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0])) ///< Yield the number of C @a array elements.
#define BSE_ALIGN(size, base) ((base) * (((size) + (base) - 1) / (base))) ///< Round up @a size to multiples of @a base.
/// @addtogroup GCC Attributes
/// Bse macros that are shorthands for <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attributes</a>.
/// @{
#define BSE_ALWAYS_INLINE __attribute__ ((always_inline))
#define BSE_CONST __attribute__ ((__const__))
#define BSE_CONSTRUCTOR __attribute__ ((constructor,used)) // gcc-3.3 also needs "used" to emit code
#define BSE_DEPRECATED __attribute__ ((__deprecated__))
#define BSE_MALLOC __attribute__ ((__malloc__))
#define BSE_MAY_ALIAS __attribute__ ((may_alias))
#define BSE_NOINLINE __attribute__ ((noinline))
#define BSE_NORETURN __attribute__ ((__noreturn__))
#define BSE_NO_INSTRUMENT __attribute__ ((__no_instrument_function__))
#define BSE_PRINTF(fx, ax) __attribute__ ((__format__ (__printf__, fx, ax)))
#define BSE_PURE __attribute__ ((__pure__))
#define BSE_SCANF(fx, ax) __attribute__ ((__format__ (__scanf__, fx, ax)))
#define BSE_SENTINEL __attribute__ ((__sentinel__))
#define BSE_UNUSED __attribute__ ((__unused__))
#define BSE_USED __attribute__ ((__used__))
/// @}
/// Return silently if @a cond does not evaluate to true, with return value @a ...
#define BSE_RETURN_UNLESS(cond, ...) do { if (BSE_UNLIKELY (!bool (cond))) return __VA_ARGS__; } while (0)
/// Delete copy ctor and assignment operator.
#define BSE_CLASS_NON_COPYABLE(ClassName) \
/*copy-ctor*/ ClassName (const ClassName&) = delete; \
ClassName& operator= (const ClassName&) = delete
#ifdef __clang__ // clang++-3.8.0: work around 'variable length array of non-POD element type'
#define BSE_DECLARE_VLA(Type, var, count) std::vector<Type> var (count)
#else // sane c++
#define BSE_DECLARE_VLA(Type, var, count) Type var[count] ///< Declare a variable length array (clang++ uses std::vector<>).
#endif
} // Bse
#endif // __BSE_CXXAUX_HH__
<commit_msg>SFI: provide BSE_FORMAT()<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html
#ifndef __BSE_CXXAUX_HH__
#define __BSE_CXXAUX_HH__
#include <sfi/sysconfig.h>
#include <sys/types.h> // uint, ssize
#include <cstdint> // uint64_t
#include <vector>
#include <map>
namespace Bse {
// == uint ==
#if BSE_SIZEOF_SYS_TYPESH_UINT == 0
typedef unsigned int uint; ///< Provide 'uint' if sys/types.h fails to do so.
#else
static_assert (BSE_SIZEOF_SYS_TYPESH_UINT == 4, "");
#endif
static_assert (sizeof (uint) == 4, "");
// == type aliases ==
typedef uint8_t uint8; ///< An 8-bit unsigned integer.
typedef uint16_t uint16; ///< A 16-bit unsigned integer.
typedef uint32_t uint32; ///< A 32-bit unsigned integer.
typedef uint64_t uint64; ///< A 64-bit unsigned integer, use PRI*64 in format strings.
typedef int8_t int8; ///< An 8-bit signed integer.
typedef int16_t int16; ///< A 16-bit signed integer.
typedef int32_t int32; ///< A 32-bit signed integer.
typedef int64_t int64; ///< A 64-bit unsigned integer, use PRI*64 in format strings.
typedef uint32_t unichar; ///< A 32-bit unsigned integer used for Unicode characters.
static_assert (sizeof (uint8) == 1 && sizeof (uint16) == 2 && sizeof (uint32) == 4 && sizeof (uint64) == 8, "");
static_assert (sizeof (int8) == 1 && sizeof (int16) == 2 && sizeof (int32) == 4 && sizeof (int64) == 8, "");
static_assert (sizeof (int) == 4 && sizeof (uint) == 4 && sizeof (unichar) == 4, "");
using std::map;
using std::vector;
typedef std::string String; ///< Convenience alias for std::string.
typedef vector<String> StringVector; ///< Convenience alias for a std::vector<std::string>.
// == Utility Macros ==
#define BSE_CPP_STRINGIFY(s) BSE_CPP_STRINGIFY_ (s) ///< Convert macro argument into a C const char*.
#define BSE_CPP_STRINGIFY_(s) #s // Indirection helper, required to expand macros like __LINE__
#define BSE_ISLIKELY(expr) __builtin_expect (bool (expr), 1) ///< Compiler hint to optimize for @a expr evaluating to true.
#define BSE_UNLIKELY(expr) __builtin_expect (bool (expr), 0) ///< Compiler hint to optimize for @a expr evaluating to false.
#define BSE_ABS(a) ((a) < 0 ? -(a) : (a)) ///< Yield the absolute value of @a a.
#define BSE_MIN(a,b) ((a) <= (b) ? (a) : (b)) ///< Yield the smaller value of @a a and @a b.
#define BSE_MAX(a,b) ((a) >= (b) ? (a) : (b)) ///< Yield the greater value of @a a and @a b.
#define BSE_CLAMP(v,mi,ma) ((v) < (mi) ? (mi) : ((v) > (ma) ? (ma) : (v))) ///< Yield @a v clamped to [ @a mi .. @a ma ].
#define BSE_ARRAY_SIZE(array) (sizeof (array) / sizeof ((array)[0])) ///< Yield the number of C @a array elements.
#define BSE_ALIGN(size, base) ((base) * (((size) + (base) - 1) / (base))) ///< Round up @a size to multiples of @a base.
/// @addtogroup GCC Attributes
/// Bse macros that are shorthands for <a href="https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html">GCC Attributes</a>.
/// @{
#define BSE_ALWAYS_INLINE __attribute__ ((always_inline))
#define BSE_CONST __attribute__ ((__const__))
#define BSE_CONSTRUCTOR __attribute__ ((constructor,used)) // gcc-3.3 also needs "used" to emit code
#define BSE_DEPRECATED __attribute__ ((__deprecated__))
#define BSE_FORMAT(fx) __attribute__ ((__format_arg__ (fx)))
#define BSE_MALLOC __attribute__ ((__malloc__))
#define BSE_MAY_ALIAS __attribute__ ((may_alias))
#define BSE_NOINLINE __attribute__ ((noinline))
#define BSE_NORETURN __attribute__ ((__noreturn__))
#define BSE_NO_INSTRUMENT __attribute__ ((__no_instrument_function__))
#define BSE_PRINTF(fx, ax) __attribute__ ((__format__ (__printf__, fx, ax)))
#define BSE_PURE __attribute__ ((__pure__))
#define BSE_SCANF(fx, ax) __attribute__ ((__format__ (__scanf__, fx, ax)))
#define BSE_SENTINEL __attribute__ ((__sentinel__))
#define BSE_UNUSED __attribute__ ((__unused__))
#define BSE_USED __attribute__ ((__used__))
/// @}
/// Return silently if @a cond does not evaluate to true, with return value @a ...
#define BSE_RETURN_UNLESS(cond, ...) do { if (BSE_UNLIKELY (!bool (cond))) return __VA_ARGS__; } while (0)
/// Delete copy ctor and assignment operator.
#define BSE_CLASS_NON_COPYABLE(ClassName) \
/*copy-ctor*/ ClassName (const ClassName&) = delete; \
ClassName& operator= (const ClassName&) = delete
#ifdef __clang__ // clang++-3.8.0: work around 'variable length array of non-POD element type'
#define BSE_DECLARE_VLA(Type, var, count) std::vector<Type> var (count)
#else // sane c++
#define BSE_DECLARE_VLA(Type, var, count) Type var[count] ///< Declare a variable length array (clang++ uses std::vector<>).
#endif
} // Bse
#endif // __BSE_CXXAUX_HH__
<|endoftext|> |
<commit_before>#include "uniform_buffer.hpp"
#include "../../util/logger.hpp"
namespace nova::renderer {
uniform_buffer::uniform_buffer(const std::string& name,
VmaAllocator allocator,
const VkBufferCreateInfo& create_info,
const uint64_t min_alloc_size,
const bool mapped)
: name(std::move(name)), alignment(min_alloc_size), allocator(allocator) {
VmaAllocationCreateInfo alloc_create = {};
alloc_create.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
if(mapped) {
alloc_create.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
const VkResult buffer_create_result = vmaCreateBuffer(allocator,
reinterpret_cast<const VkBufferCreateInfo*>(&create_info),
&alloc_create,
reinterpret_cast<VkBuffer*>(&buffer),
&allocation,
&allocation_info);
if(buffer_create_result != VK_SUCCESS) {
NOVA_LOG(ERROR) << "Could not allocate a an autobuffer because " << buffer_create_result;
}
else {
NOVA_LOG(TRACE) << "Auto buffer allocation success! Buffer ID: " << buffer;
}
}
uniform_buffer::uniform_buffer(uniform_buffer&& old) noexcept
: name(std::move(old.name)),
alignment(old.alignment),
allocator(old.allocator),
device(old.device),
buffer(old.buffer),
allocation(old.allocation),
allocation_info(old.allocation_info) {
old.device = nullptr;
old.buffer = nullptr;
old.allocation = {};
old.allocation_info = {};
}
uniform_buffer& uniform_buffer::operator=(uniform_buffer&& old) noexcept {
name = std::move(old.name);
alignment = old.alignment;
allocator = old.allocator;
device = old.device;
buffer = old.buffer;
allocation = old.allocation;
allocation_info = old.allocation_info;
old.device = nullptr;
old.buffer = nullptr;
old.allocation = {};
old.allocation_info = {};
return *this;
}
uniform_buffer::~uniform_buffer() {
if(allocator && buffer != VkBuffer()) {
NOVA_LOG(TRACE) << "uniform_buffer: About to destroy buffer " << buffer;
vmaDestroyBuffer(allocator, buffer, allocation);
}
}
VmaAllocation& uniform_buffer::get_allocation() { return allocation; }
VmaAllocationInfo& uniform_buffer::get_allocation_info() { return allocation_info; }
const std::string& uniform_buffer::get_name() const { return name; }
const VkBuffer& uniform_buffer::get_vk_buffer() const { return buffer; }
uint64_t uniform_buffer::get_size() const { return alignment; }
// ReSharper disable once CppMemberFunctionMayBeConst
void uniform_buffer::set_data(const void* data, uint32_t size) {
void* mapped_data;
vmaMapMemory(allocator, allocation, &mapped_data);
std::memcpy(mapped_data, data, size);
vmaUnmapMemory(allocator, allocation);
}
} // namespace nova::renderer<commit_msg>Include cstring<commit_after>#include "uniform_buffer.hpp"
#include "../../util/logger.hpp"
#include <cstring>
namespace nova::renderer {
uniform_buffer::uniform_buffer(const std::string& name,
VmaAllocator allocator,
const VkBufferCreateInfo& create_info,
const uint64_t min_alloc_size,
const bool mapped)
: name(std::move(name)), alignment(min_alloc_size), allocator(allocator) {
VmaAllocationCreateInfo alloc_create = {};
alloc_create.usage = VMA_MEMORY_USAGE_CPU_TO_GPU;
if(mapped) {
alloc_create.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT | VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
}
const VkResult buffer_create_result = vmaCreateBuffer(allocator,
reinterpret_cast<const VkBufferCreateInfo*>(&create_info),
&alloc_create,
reinterpret_cast<VkBuffer*>(&buffer),
&allocation,
&allocation_info);
if(buffer_create_result != VK_SUCCESS) {
NOVA_LOG(ERROR) << "Could not allocate a an autobuffer because " << buffer_create_result;
}
else {
NOVA_LOG(TRACE) << "Auto buffer allocation success! Buffer ID: " << buffer;
}
}
uniform_buffer::uniform_buffer(uniform_buffer&& old) noexcept
: name(std::move(old.name)),
alignment(old.alignment),
allocator(old.allocator),
device(old.device),
buffer(old.buffer),
allocation(old.allocation),
allocation_info(old.allocation_info) {
old.device = nullptr;
old.buffer = nullptr;
old.allocation = {};
old.allocation_info = {};
}
uniform_buffer& uniform_buffer::operator=(uniform_buffer&& old) noexcept {
name = std::move(old.name);
alignment = old.alignment;
allocator = old.allocator;
device = old.device;
buffer = old.buffer;
allocation = old.allocation;
allocation_info = old.allocation_info;
old.device = nullptr;
old.buffer = nullptr;
old.allocation = {};
old.allocation_info = {};
return *this;
}
uniform_buffer::~uniform_buffer() {
if(allocator && buffer != VkBuffer()) {
NOVA_LOG(TRACE) << "uniform_buffer: About to destroy buffer " << buffer;
vmaDestroyBuffer(allocator, buffer, allocation);
}
}
VmaAllocation& uniform_buffer::get_allocation() { return allocation; }
VmaAllocationInfo& uniform_buffer::get_allocation_info() { return allocation_info; }
const std::string& uniform_buffer::get_name() const { return name; }
const VkBuffer& uniform_buffer::get_vk_buffer() const { return buffer; }
uint64_t uniform_buffer::get_size() const { return alignment; }
// ReSharper disable once CppMemberFunctionMayBeConst
void uniform_buffer::set_data(const void* data, uint32_t size) {
void* mapped_data;
vmaMapMemory(allocator, allocation, &mapped_data);
std::memcpy(mapped_data, data, size);
vmaUnmapMemory(allocator, allocation);
}
} // namespace nova::renderer<|endoftext|> |
<commit_before>#include "grid.h"
#include <QDebug>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <exception>
Grid::Grid()
{
this->row = 0;
this->column = 0;
}
bool fileExists(QString path) {
QFileInfo checkFile(path);
// check if file exists. If yes then is it really a file and not a directory
return (checkFile.exists() && checkFile.isFile());
}
Grid::Grid(const QString& filePath)
{
try
{
if (fileExists(filePath))
{
QFile file(filePath);
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
this->row = json["row"].toInt();
this->column = json["column"].toInt();
gameGrid = new Path*[row];
for (int i = 0; i < row; ++i)
{
gameGrid[i] = new Path[column];
}
QJsonArray jsonArray = json["level"].toArray();
std::vector<int> v, n, p;
int color = 0, x = 0, y = 0;
bool origin = false, firstOrigin = false, secondOrigin = false;
int nextColor = 0, nextX = 0, nextY = 0;
int previousColor = 0, previousX = 0, previousY = 0;
bool nOk = false, pOk = false, pathComplete = false;
foreach (const QJsonValue& item, jsonArray)
{
foreach (const QJsonValue& i, item.toArray())
{
if (!i.isObject()){
v.push_back(i.toInt());
}
else {
QJsonArray settingsArray = i.toObject()["settings"].toArray();
foreach (const QJsonValue& settingsItem, settingsArray)
{
QString name = settingsItem.toObject().value("name").toString();
if (name == "origin")
{
origin = settingsItem.toObject().value("value").toBool();
}
if (name == "first origin")
{
firstOrigin = settingsItem.toObject().value("value").toBool();
}
else if (name == "second origin")
{
secondOrigin = settingsItem.toObject().value("value").toBool();
}
else if (name == "path complete")
{
pathComplete = settingsItem.toObject().value("value").toBool();
}
else if (name == "next")
{
QJsonArray value = settingsItem.toObject().value("value").toArray();
for (int i = 0; i < value.size(); ++i)
{
n.push_back(value[i].toInt());
}
}
else if (name == "previous")
{
QJsonArray value = settingsItem.toObject().value("value").toArray();
for (int i = 0; i < value.size(); ++i)
{
p.push_back(value[i].toInt());
}
}
}
}
}
color = v.back();
v.pop_back();
y = v.back();
v.pop_back();
x = v.back();
v.pop_back();
if (!n.empty())
{
nextColor = n.back();
n.pop_back();
nextY = n.back();
n.pop_back();
nextX = n.back();
n.pop_back();
nOk = true;
}
if (!p.empty())
{
previousColor = p.back();
p.pop_back();
previousY = p.back();
p.pop_back();
previousX = p.back();
p.pop_back();
pOk = true;
}
if (firstOrigin)
{
if (nOk && origin)
{
gameGrid[x][y].next[0] = &gameGrid[nextX][nextY];
gameGrid[x][y].setData(color);
gameGrid[x][y].setFirstOrigin(true);
gameGrid[x][y].setCoveredFlag(true);
}
}
else if (secondOrigin)
{
if (pOk && origin)
{
gameGrid[x][y].previous[0] = &gameGrid[previousX][previousY];
gameGrid[x][y].setData(color);
gameGrid[x][y].setSecondOrigin(true);
gameGrid[x][y].setCoveredFlag(true);
gameGrid[x][y].setPathComplete(true);
}
}
else
{
// it is a standard level
if (json["standard"].toBool())
{
gameGrid[x][y].setData(color);
}
// it is a point
else
{
// there is a next point to the current grid point
if (nOk)
{
gameGrid[x][y].next[0] = &gameGrid[nextX][nextY];
gameGrid[x][y].setColor(color);
gameGrid[x][y].setCoveredFlag(true);
}
// there is a previous point to the current grid point
if (pOk)
{
gameGrid[x][y].previous[0] = &gameGrid[previousX][previousY];
gameGrid[x][y].setColor(color);
gameGrid[x][y].setCoveredFlag(true);
}
// if the point is an origin
if (origin)
{
gameGrid[x][y].setData(color);
}
}
}
nOk = false;
pOk = false;
}
}
else
{
std::cout << "The file doesn't exist\n";
}
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
}
}
Grid::Grid(int nbRow, int nbCol)
{
this->row = nbRow;
this->column = nbCol;
gameGrid = new Path*[nbRow];
for (int i = 0; i < nbRow; ++i)
{
gameGrid[i] = new Path[nbCol];
}
}
Grid::~Grid()
{
for (int i = 0; i < this->row; ++i)
{
delete [] gameGrid[i];
}
delete [] gameGrid;
}
Path Grid::getPath(int i, int j)
{
return gameGrid[i][j];
}
void Grid::setPath(int i, int j, Path path)
{
gameGrid[i][j] = path;
}
void Grid::setPosition(int i, int j)
{
gameGrid[i][j].x = i;
gameGrid[i][j].y = j;
}
int Grid::getNbRow()
{
return row;
}
int Grid::getNbColumn()
{
return column;
}
//Finds if the game is won
bool Grid::isCompleted()
{
int completedPaths = 0, totalPaths = 0;
for(int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
Path path = gameGrid[i][j];
if(!path.isCovered() && !path.isOrigin())
{
return false;
}
else if(path.isOrigin())
{
totalPaths++;
completedPaths += path.getPathComplete() ? 1 : 0;
}
}
}
return completedPaths == totalPaths/2;
}
<commit_msg>Fixed bug on override last case before an origin<commit_after>#include "grid.h"
#include <QDebug>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <exception>
Grid::Grid()
{
this->row = 0;
this->column = 0;
}
bool fileExists(QString path) {
QFileInfo checkFile(path);
// check if file exists. If yes then is it really a file and not a directory
return (checkFile.exists() && checkFile.isFile());
}
Grid::Grid(const QString& filePath)
{
try
{
if (fileExists(filePath))
{
QFile file(filePath);
file.open(QIODevice::ReadOnly);
QByteArray rawData = file.readAll();
// Parse document
QJsonDocument doc(QJsonDocument::fromJson(rawData));
// Get JSON object
QJsonObject json = doc.object();
// Access properties
this->row = json["row"].toInt();
this->column = json["column"].toInt();
gameGrid = new Path*[row];
for (int i = 0; i < row; ++i)
{
gameGrid[i] = new Path[column];
}
QJsonArray jsonArray = json["level"].toArray();
std::vector<int> v, n, p;
int color = 0, x = 0, y = 0;
bool origin = false, firstOrigin = false, secondOrigin = false;
int nextColor = 0, nextX = 0, nextY = 0;
int previousColor = 0, previousX = 0, previousY = 0;
bool nOk = false, pOk = false, pathComplete = false;
foreach (const QJsonValue& item, jsonArray)
{
foreach (const QJsonValue& i, item.toArray())
{
if (!i.isObject()){
v.push_back(i.toInt());
}
else {
QJsonArray settingsArray = i.toObject()["settings"].toArray();
foreach (const QJsonValue& settingsItem, settingsArray)
{
QString name = settingsItem.toObject().value("name").toString();
if (name == "origin")
{
origin = settingsItem.toObject().value("value").toBool();
}
if (name == "first origin")
{
firstOrigin = settingsItem.toObject().value("value").toBool();
}
else if (name == "second origin")
{
secondOrigin = settingsItem.toObject().value("value").toBool();
}
else if (name == "path complete")
{
pathComplete = settingsItem.toObject().value("value").toBool();
}
else if (name == "next")
{
QJsonArray value = settingsItem.toObject().value("value").toArray();
for (int i = 0; i < value.size(); ++i)
{
n.push_back(value[i].toInt());
}
}
else if (name == "previous")
{
QJsonArray value = settingsItem.toObject().value("value").toArray();
for (int i = 0; i < value.size(); ++i)
{
p.push_back(value[i].toInt());
}
}
}
}
}
color = v.back();
v.pop_back();
y = v.back();
v.pop_back();
x = v.back();
v.pop_back();
if (!n.empty())
{
nextColor = n.back();
n.pop_back();
nextY = n.back();
n.pop_back();
nextX = n.back();
n.pop_back();
nOk = true;
}
if (!p.empty())
{
previousColor = p.back();
p.pop_back();
previousY = p.back();
p.pop_back();
previousX = p.back();
p.pop_back();
pOk = true;
}
if (firstOrigin)
{
if (nOk || origin)
{
gameGrid[x][y].next[0] = &gameGrid[nextX][nextY];
gameGrid[x][y].setData(color);
gameGrid[x][y].setFirstOrigin(true);
gameGrid[x][y].setCoveredFlag(true);
}
}
else if (secondOrigin)
{
if (pOk || origin)
{
gameGrid[x][y].previous[0] = &gameGrid[previousX][previousY];
gameGrid[x][y].setData(color);
gameGrid[x][y].setSecondOrigin(true);
gameGrid[x][y].setCoveredFlag(true);
gameGrid[x][y].setPathComplete(true);
}
}
else
{
// it is a standard level
if (json["standard"].toBool())
{
gameGrid[x][y].setData(color);
}
// it is a point
else
{
// there is a next point to the current grid point
if (nOk)
{
gameGrid[x][y].next[0] = &gameGrid[nextX][nextY];
gameGrid[x][y].setColor(color);
gameGrid[x][y].setCoveredFlag(true);
}
// there is a previous point to the current grid point
if (pOk)
{
gameGrid[x][y].previous[0] = &gameGrid[previousX][previousY];
gameGrid[x][y].setColor(color);
gameGrid[x][y].setCoveredFlag(true);
}
// if the point is an origin
if (origin)
{
gameGrid[x][y].setData(color);
}
}
}
nOk = false;
pOk = false;
}
}
else
{
std::cout << "The file doesn't exist\n";
}
}
catch (std::exception const& e)
{
std::cerr << e.what() << std::endl;
}
}
Grid::Grid(int nbRow, int nbCol)
{
this->row = nbRow;
this->column = nbCol;
gameGrid = new Path*[nbRow];
for (int i = 0; i < nbRow; ++i)
{
gameGrid[i] = new Path[nbCol];
}
}
Grid::~Grid()
{
for (int i = 0; i < this->row; ++i)
{
delete [] gameGrid[i];
}
delete [] gameGrid;
}
Path Grid::getPath(int i, int j)
{
return gameGrid[i][j];
}
void Grid::setPath(int i, int j, Path path)
{
gameGrid[i][j] = path;
}
void Grid::setPosition(int i, int j)
{
gameGrid[i][j].x = i;
gameGrid[i][j].y = j;
}
int Grid::getNbRow()
{
return row;
}
int Grid::getNbColumn()
{
return column;
}
//Finds if the game is won
bool Grid::isCompleted()
{
int completedPaths = 0, totalPaths = 0;
for(int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
{
Path path = gameGrid[i][j];
if(!path.isCovered() && !path.isOrigin())
{
return false;
}
else if(path.isOrigin())
{
totalPaths++;
completedPaths += path.getPathComplete() ? 1 : 0;
}
}
}
return completedPaths == totalPaths/2;
}
<|endoftext|> |
<commit_before><commit_msg>Test using a different but equal id in scopednode<commit_after><|endoftext|> |
<commit_before>/// @provides in ferred types for elementary functions
#include <boost/integer/static_min_max.hpp>
#include <boost/integer/static_log2.hpp>
namespace core {
namespace {
using boost::mpl::eval_if;
using boost::mpl::and_;
using boost::static_unsigned_max;
using boost::static_log2;
}
/// LOG
template<typename T, size_t n, size_t f, class op, class up>
class fixed_point;
template<typename T>
class get_
{
public:
typedef double log_type;
typedef double sqrt_type;
typedef double max_signed_type;
typedef double sin_type;
typedef sin_type cos_type;
typedef double tan_type;
typedef double arc_type;
//typedef double product_type;
//typedef double quotient_type;
//typedef double sum_type;
//typedef double diff_type;
};
template<typename T, size_t n, size_t f, class op, class up>
class get_<fixed_point<T, n, f, op, up> >
{
typedef fixed_point<T, n, f, op, up> operand_type;
struct log_info
{
static size_t const extra_bits =
static_unsigned_max<static_log2<f>::value + 1u, n + static_log2<n>::value + 1u>::value;
struct can_expand
{
enum { value = (f != 0) &&
(n + log_info::extra_bits + 1u < std::numeric_limits<boost::intmax_t>::digits) };
};
struct expanded
{
typedef fixed_point<
typename boost::int_t<n + extra_bits + 1u>::least,
n + extra_bits,
f,
op,
up
> type;
};
struct same
{
typedef operand_type type;
};
};
public:
typedef typename eval_if<
typename log_info::can_expand,
typename log_info::expanded,
typename log_info::same
>::type log_type;
typedef fixed_point<typename boost::uint_t<n / 2>::least, n / 2, f / 2, op, up> sqrt_type;
typedef fixed_point<boost::uintmax_t,
std::numeric_limits<boost::uintmax_t>::digits, f, op, up> max_unsigned_type;
typedef fixed_point<boost::intmax_t,
std::numeric_limits<boost::intmax_t>::digits, f, op, up> max_signed_type;
typedef fixed_point<typename boost::int_t<1u + f>::least, 1u + f, f, op, up> sin_type;
typedef sin_type cos_type;
typedef typename quotient<sin_type, cos_type>::type tan_type;
typedef max_unsigned_type exp_type;
//typedef fixed_point<typename boost::uintmax_t<2u + f>::least, f, op, up> arcsin_type;
//typedef arcsin_type arccos_type;
};
}
<commit_msg>get_.hpp: commit before deletion<commit_after>/// @provides in ferred types for elementary functions
#include <boost/integer/static_min_max.hpp>
#include <boost/integer/static_log2.hpp>
namespace core {
namespace {
using boost::mpl::eval_if;
using boost::mpl::and_;
using boost::static_unsigned_max;
using boost::static_log2;
}
/// LOG
template<typename T, size_t n, size_t f, class op, class up>
class fixed_point;
template<typename T>
class get_
{
public:
typedef double log_type;
typedef double sqrt_type;
typedef double max_signed_type;
typedef double sin_type;
typedef sin_type cos_type;
typedef double tan_type;
typedef double arc_type;
};
template<typename T, size_t n, size_t f, class op, class up>
class get_<fixed_point<T, n, f, op, up> >
{
typedef fixed_point<T, n, f, op, up> operand_type;
struct sqrt_info
{
static size_t const integer_bits =
((n - f) & 1u)? ((n - f)/2u) + 1u : (n - f)/2u;
static size_t const fractional_bits =
(f & 1u)? (f/2u) + 1u : (f/2u);
static size_t const total_bits = integer_bits + fractional_bits;
};
struct log_info
{
static size_t const extra_bits =
static_unsigned_max<static_log2<f>::value + 1u, n + static_log2<n>::value + 1u>::value;
struct can_expand
{
enum { value = (f != 0) &&
(n + log_info::extra_bits + 1u < std::numeric_limits<boost::intmax_t>::digits) };
};
struct expanded
{
typedef fixed_point<
typename boost::int_t<n + extra_bits + 1u>::least,
n + extra_bits,
f,
op,
up
> type;
};
struct same
{
typedef operand_type type;
};
};
struct sin_info
{
struct can_expand
{
enum { value = (f + 1u + 1u < std::numeric_limits<boost::intmax_t>::digits) };
};
struct expanded
{
typedef fixed_point<
typename boost::int_t<f + 1u + 1u>::least,
f + 1u,
f,
op,
up
> type;
};
struct reduced
{
typedef fixed_point<
typename boost::int_t<f + 1u>::least,
f,
f - 1u,
op,
up
> type;
};
};
struct asin_info
{
static size_t const available_bits = std::numeric_limits<boost::intmax_t>::digits - f;
struct can_expand
{
enum { value = (available_bits > 2u) };
};
struct expanded
{
typedef fixed_point<
typename boost::int_t<f + 2u + 1u>::least,
f + 2u,
f,
op,
up
> type;
};
struct reduced
{
typedef fixed_point<
typename boost::int_t<f + 2u>::least,
f + available_bits,
f + available_bits - 2u,
op,
up
> type;
};
};
struct acos_info
{
static size_t const available_bits = std::numeric_limits<boost::intmax_t>::digits - f;
struct can_expand
{
enum { value = (available_bits > 3u) };
};
struct expanded
{
typedef fixed_point<
typename boost::int_t<f + 3u + 1u>::least,
f + 3u,
f,
op,
up
> type;
};
struct reduced
{
typedef fixed_point<
typename boost::int_t<f + 3u>::least,
f + available_bits,
f + available_bits - 3u,
op,
up
> type;
};
};
public:
typedef typename eval_if<
typename log_info::can_expand,
typename log_info::expanded,
typename log_info::same
>::type log_type;
// exists always
typedef fixed_point<
typename boost::uint_t<sqrt_info::total_bits>::least,
sqrt_info::total_bits,
sqrt_info::fractional_bits,
op,
up
> sqrt_type;
typedef fixed_point<boost::uintmax_t,
std::numeric_limits<boost::uintmax_t>::digits, f, op, up> max_unsigned_type;
typedef fixed_point<boost::intmax_t,
std::numeric_limits<boost::intmax_t>::digits, f, op, up> max_signed_type;
typedef typename eval_if<
typename sin_info::can_expand,
typename sin_info::expanded,
typename sin_info::reduced
>::type sin_type;
typedef sin_type cos_type;
typedef typename quotient<sin_type, cos_type>::type tan_type;
typedef max_unsigned_type exp_type;
typedef typename eval_if<
typename asin_info::can_expand,
typename asin_info::expanded,
typename asin_info::reduced
>::type asin_type;
typedef asin_type atan_type;
typedef typename eval_if<
typename acos_info::can_expand,
typename acos_info::expanded,
typename acos_info::reduced
>::type acos_type;
typedef typename get_<operand_type>::log_type asinh_type;
};
}
<|endoftext|> |
<commit_before>//===- StringExtrasTest.cpp - Unit tests for String extras ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"
using namespace llvm;
TEST(StringExtrasTest, Join) {
std::vector<std::string> Items;
EXPECT_EQ("", join(Items.begin(), Items.end(), " <sep> "));
Items = {"foo"};
EXPECT_EQ("foo", join(Items.begin(), Items.end(), " <sep> "));
Items = {"foo", "bar"};
EXPECT_EQ("foo <sep> bar", join(Items.begin(), Items.end(), " <sep> "));
Items = {"foo", "bar", "baz"};
EXPECT_EQ("foo <sep> bar <sep> baz",
join(Items.begin(), Items.end(), " <sep> "));
}
TEST(StringExtrasTest, JoinItems) {
const char *Foo = "foo";
std::string Bar = "bar";
llvm::StringRef Baz = "baz";
char X = 'x';
EXPECT_EQ("", join_items(" <sep> "));
EXPECT_EQ("", join_items('/'));
EXPECT_EQ("foo", join_items(" <sep> ", Foo));
EXPECT_EQ("foo", join_items('/', Foo));
EXPECT_EQ("foo <sep> bar", join_items(" <sep> ", Foo, Bar));
EXPECT_EQ("foo/bar", join_items('/', Foo, Bar));
EXPECT_EQ("foo <sep> bar <sep> baz", join_items(" <sep> ", Foo, Bar, Baz));
EXPECT_EQ("foo/bar/baz", join_items('/', Foo, Bar, Baz));
EXPECT_EQ("foo <sep> bar <sep> baz <sep> x",
join_items(" <sep> ", Foo, Bar, Baz, X));
EXPECT_EQ("foo/bar/baz/x", join_items('/', Foo, Bar, Baz, X));
}
TEST(StringExtrasTest, ToAndFromHex) {
std::vector<uint8_t> OddBytes = {0x5, 0xBD, 0x0D, 0x3E, 0xCD};
std::string OddStr = "05BD0D3ECD";
StringRef OddData(reinterpret_cast<const char *>(OddBytes.data()),
OddBytes.size());
EXPECT_EQ(OddStr, toHex(OddData));
EXPECT_EQ(OddData, fromHex(StringRef(OddStr).drop_front()));
std::vector<uint8_t> EvenBytes = {0xA5, 0xBD, 0x0D, 0x3E, 0xCD};
std::string EvenStr = "A5BD0D3ECD";
StringRef EvenData(reinterpret_cast<const char *>(EvenBytes.data()),
EvenBytes.size());
EXPECT_EQ(EvenStr, toHex(EvenData));
EXPECT_EQ(EvenData, fromHex(EvenStr));
}
TEST(StringExtrasTest, to_float) {
float F;
EXPECT_TRUE(to_float("4.7", F));
EXPECT_FLOAT_EQ(4.7f, F);
double D;
EXPECT_TRUE(to_float("4.7", D));
EXPECT_DOUBLE_EQ(4.7, D);
long double LD;
EXPECT_TRUE(to_float("4.7", LD));
EXPECT_DOUBLE_EQ(4.7, LD);
EXPECT_FALSE(to_float("foo", F));
EXPECT_FALSE(to_float("7.4 foo", F));
EXPECT_FLOAT_EQ(4.7f, F); // F should be unchanged
}
TEST(StringExtrasTest, printLowerCase) {
std::string str;
raw_string_ostream OS(str);
printLowerCase("ABCdefg01234.,&!~`'}\"", OS);
EXPECT_EQ("abcdefg01234.,&!~`'}\"", OS.str());
}
<commit_msg>[ADT] Add unit test for PrintHTMLEscaped<commit_after>//===- StringExtrasTest.cpp - Unit tests for String extras ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "gtest/gtest.h"
using namespace llvm;
TEST(StringExtrasTest, Join) {
std::vector<std::string> Items;
EXPECT_EQ("", join(Items.begin(), Items.end(), " <sep> "));
Items = {"foo"};
EXPECT_EQ("foo", join(Items.begin(), Items.end(), " <sep> "));
Items = {"foo", "bar"};
EXPECT_EQ("foo <sep> bar", join(Items.begin(), Items.end(), " <sep> "));
Items = {"foo", "bar", "baz"};
EXPECT_EQ("foo <sep> bar <sep> baz",
join(Items.begin(), Items.end(), " <sep> "));
}
TEST(StringExtrasTest, JoinItems) {
const char *Foo = "foo";
std::string Bar = "bar";
llvm::StringRef Baz = "baz";
char X = 'x';
EXPECT_EQ("", join_items(" <sep> "));
EXPECT_EQ("", join_items('/'));
EXPECT_EQ("foo", join_items(" <sep> ", Foo));
EXPECT_EQ("foo", join_items('/', Foo));
EXPECT_EQ("foo <sep> bar", join_items(" <sep> ", Foo, Bar));
EXPECT_EQ("foo/bar", join_items('/', Foo, Bar));
EXPECT_EQ("foo <sep> bar <sep> baz", join_items(" <sep> ", Foo, Bar, Baz));
EXPECT_EQ("foo/bar/baz", join_items('/', Foo, Bar, Baz));
EXPECT_EQ("foo <sep> bar <sep> baz <sep> x",
join_items(" <sep> ", Foo, Bar, Baz, X));
EXPECT_EQ("foo/bar/baz/x", join_items('/', Foo, Bar, Baz, X));
}
TEST(StringExtrasTest, ToAndFromHex) {
std::vector<uint8_t> OddBytes = {0x5, 0xBD, 0x0D, 0x3E, 0xCD};
std::string OddStr = "05BD0D3ECD";
StringRef OddData(reinterpret_cast<const char *>(OddBytes.data()),
OddBytes.size());
EXPECT_EQ(OddStr, toHex(OddData));
EXPECT_EQ(OddData, fromHex(StringRef(OddStr).drop_front()));
std::vector<uint8_t> EvenBytes = {0xA5, 0xBD, 0x0D, 0x3E, 0xCD};
std::string EvenStr = "A5BD0D3ECD";
StringRef EvenData(reinterpret_cast<const char *>(EvenBytes.data()),
EvenBytes.size());
EXPECT_EQ(EvenStr, toHex(EvenData));
EXPECT_EQ(EvenData, fromHex(EvenStr));
}
TEST(StringExtrasTest, to_float) {
float F;
EXPECT_TRUE(to_float("4.7", F));
EXPECT_FLOAT_EQ(4.7f, F);
double D;
EXPECT_TRUE(to_float("4.7", D));
EXPECT_DOUBLE_EQ(4.7, D);
long double LD;
EXPECT_TRUE(to_float("4.7", LD));
EXPECT_DOUBLE_EQ(4.7, LD);
EXPECT_FALSE(to_float("foo", F));
EXPECT_FALSE(to_float("7.4 foo", F));
EXPECT_FLOAT_EQ(4.7f, F); // F should be unchanged
}
TEST(StringExtrasTest, printLowerCase) {
std::string str;
raw_string_ostream OS(str);
printLowerCase("ABCdefg01234.,&!~`'}\"", OS);
EXPECT_EQ("abcdefg01234.,&!~`'}\"", OS.str());
}
TEST(StringExtrasTest, PrintHTMLEscaped) {
std::string str;
raw_string_ostream OS(str);
PrintHTMLEscaped("ABCdef123&<>\"'", OS);
EXPECT_EQ("ABCdef123&<>"'", OS.str());
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include <termdb.hpp>
TEST(Constructor, Success)
{
TermDb parser("xterm", "terminfo/");
ASSERT_TRUE(parser);
ASSERT_EQ(0, parser.getStatus());
ASSERT_NE(0, parser.getTermName().size());
}
TEST(Constructor, NON_EXISTENT_TERM)
{
TermDb parser("NON_EXISTENT_TERM_FOR_DEMO");
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-2, parser.getStatus());
}
TEST(Parse, Success)
{
TermDb parser;
auto result = parser.parse("xterm", "terminfo/");
ASSERT_TRUE(result);
ASSERT_TRUE(parser);
ASSERT_EQ(0, parser.getStatus());
}
TEST(Parse, NON_EXISTENT_TERM)
{
TermDb parser;
auto result = parser.parse("NON_EXISTENT_TERM_FOR_DEMO");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-2, parser.getStatus());
ASSERT_EQ(0, parser.getTermName().size());
}
TEST(Parse, NoMagicBytes)
{
TermDb parser;
auto result = parser.parse("corrupt-magic", "terminfo/");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-3, parser.getStatus());
}
TEST(Parse, Size0)
{
TermDb parser;
auto result = parser.parse("corrupt-size", "terminfo/");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-2, parser.getStatus());
}
TEST(Parse, Corrupted)
{
TermDb parser;
auto result = parser.parse("corrupted", "terminfo/");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-4, parser.getStatus());
}
TEST(Parse, DataResets)
{
TermDb parser;
auto result = parser.parse("xterm", "terminfo/");
EXPECT_TRUE(result);
auto name = parser.getTermName();
result = parser.parse("adm3a", "terminfo/");
EXPECT_TRUE(result);
ASSERT_NE(name, parser.getTermName());
}
TEST(Parse, WrongArguments)
{
TermDb parser;
auto result = parser.parse("");
ASSERT_FALSE(result);
result = parser.parse("xterm", "");
ASSERT_FALSE(result);
}
<commit_msg>Remove extra includes from test.cpp<commit_after>#include <gtest/gtest.h>
#include <termdb.hpp>
TEST(Constructor, Success)
{
TermDb parser("xterm", "terminfo/");
ASSERT_TRUE(parser);
ASSERT_EQ(0, parser.getStatus());
ASSERT_NE(0, parser.getTermName().size());
}
TEST(Constructor, NON_EXISTENT_TERM)
{
TermDb parser("NON_EXISTENT_TERM_FOR_DEMO");
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-2, parser.getStatus());
}
TEST(Parse, Success)
{
TermDb parser;
auto result = parser.parse("xterm", "terminfo/");
ASSERT_TRUE(result);
ASSERT_TRUE(parser);
ASSERT_EQ(0, parser.getStatus());
}
TEST(Parse, NON_EXISTENT_TERM)
{
TermDb parser;
auto result = parser.parse("NON_EXISTENT_TERM_FOR_DEMO");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-2, parser.getStatus());
ASSERT_EQ(0, parser.getTermName().size());
}
TEST(Parse, NoMagicBytes)
{
TermDb parser;
auto result = parser.parse("corrupt-magic", "terminfo/");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-3, parser.getStatus());
}
TEST(Parse, Size0)
{
TermDb parser;
auto result = parser.parse("corrupt-size", "terminfo/");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-2, parser.getStatus());
}
TEST(Parse, Corrupted)
{
TermDb parser;
auto result = parser.parse("corrupted", "terminfo/");
ASSERT_FALSE(result);
ASSERT_FALSE(parser);
ASSERT_NE(0, parser.getStatus());
ASSERT_EQ(-4, parser.getStatus());
}
TEST(Parse, DataResets)
{
TermDb parser;
auto result = parser.parse("xterm", "terminfo/");
EXPECT_TRUE(result);
auto name = parser.getTermName();
result = parser.parse("adm3a", "terminfo/");
EXPECT_TRUE(result);
ASSERT_NE(name, parser.getTermName());
}
TEST(Parse, WrongArguments)
{
TermDb parser;
auto result = parser.parse("");
ASSERT_FALSE(result);
result = parser.parse("xterm", "");
ASSERT_FALSE(result);
}
<|endoftext|> |
<commit_before>#include "caio.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <string>
#include <iostream>
using namespace std;
Caio::Caio()
{
m_position.x = 50;
m_position.y = 350;
m_position.w = 50;
m_position.h = 100;
m_clips[0].x = 0;
m_clips[0].y = 0;
m_clips[0].w = 50;
m_clips[0].h = 100;
m_clips[1].x = 50;
m_clips[1].y = 0;
m_clips[1].w = 50;
m_clips[1].h = 100;
m_clips[2].x = 100;
m_clips[2].y = 0;
m_clips[2].w = 50;
m_clips[2].h = 100;
m_clips[3].x = 150;
m_clips[3].y = 0;
m_clips[3].w = 50;
m_clips[3].h = 100;
m_clips[4].x = 0;
m_clips[4].y = 100;
m_clips[4].w = 50;
m_clips[4].h = 100;
m_clips[5].x = 50;
m_clips[5].y = 100;
m_clips[5].w = 50;
m_clips[5].h = 100;
m_clips[6].x = 100;
m_clips[6].y = 100;
m_clips[6].w = 50;
m_clips[6].h = 100;
m_clips[7].x = 150;
m_clips[7].y = 100;
m_clips[7].w = 50;
m_clips[7].h = 100;
m_clips[8].x = 0;
m_clips[8].y = 200;
m_clips[8].w = 50;
m_clips[8].h = 100;
m_clips[9].x = 50;
m_clips[9].y = 200;
m_clips[9].w = 50;
m_clips[9].h = 85;
m_clips[10].x = 100;
m_clips[10].y = 200;
m_clips[10].w = 50;
m_clips[10].h = 60;
m_clips[11].x = 150;
m_clips[11].y = 200;
m_clips[11].w = 50;
m_clips[11].h = 50;
m_clips[12].x = 0;
m_clips[12].y = 300;
m_clips[12].w = 50;
m_clips[12].h = 100;
m_clips[13].x = 50;
m_clips[13].y = 300;
m_clips[13].w = 50;
m_clips[13].h = 100;
m_clips[14].x = 100;
m_clips[14].y = 300;
m_clips[14].w = 50;
m_clips[14].h = 100;
m_clips[15].x = 150;
m_clips[15].y = 300;
m_clips[15].w = 50;
m_clips[15].h = 100;
isDrawn = false;
speed = 110;
gravity = 0;
dx = 0;
dy = 0;
u = 0;
imageLoad = imageLoad->getInstance();
m_imageSprite = new ImageSprite();
}
Caio::~Caio()
{
// Nothing yet
}
void
Caio::init()
{
m_imageSprite->loadFromFile("res/images/s_caio.png");
}
void
Caio::draw()
{
imageLoad->update(m_imageSprite->m_texture, &m_clips[u], &m_position);
}
void
Caio::update(Uint32 delta)
{
m_position.x += ((speed*delta)/1000.0)*dx;
m_position.y -= ((speed*delta)/1000.0)*dy;
if( (m_position.x < 0) || ( m_position.x > 800 ) )
{
m_position.x -= ((speed*delta)/1000.0)*dx;
}
if( m_position.y < 150)
{
m_position.y += ((speed*delta)/1000.0)*dy;
gravity = 0;
}
}
void
Caio::release()
{
SDL_DestroyTexture(m_imageSprite->m_texture);
}
bool
Caio::handle(SDL_Event& event)
{
bool processed = false;
switch (event.type)
{
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_a:
dx = -1;
processed = true;
u = 4;
break;
case SDLK_d:
dx = 1;
processed = true;
u = 0;
break;
case SDLK_SPACE:
dy = 1;
processed = true;
u = 12;
break;
default:
break;
}
break;
case SDL_KEYUP:
switch(event.key.keysym.sym)
{
case SDLK_a:
dx = 0;
processed = true;
break;
case SDLK_d:
dx = 0;
processed = true;
break;
case SDLK_SPACE:
dy = 0;
processed = true;
break;
default:
break;
}
break;
default:
break;
}
return processed;
}
<commit_msg>Inserindo tratamento simples para Animação de Caio<commit_after>#include "caio.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <string>
#include <iostream>
using namespace std;
Caio::Caio()
{
m_position.x = 50;
m_position.y = 350;
m_position.w = 50;
m_position.h = 100;
m_clips[0].x = 0;
m_clips[0].y = 0;
m_clips[0].w = 50;
m_clips[0].h = 100;
m_clips[1].x = 50;
m_clips[1].y = 0;
m_clips[1].w = 50;
m_clips[1].h = 100;
m_clips[2].x = 100;
m_clips[2].y = 0;
m_clips[2].w = 50;
m_clips[2].h = 100;
m_clips[3].x = 150;
m_clips[3].y = 0;
m_clips[3].w = 50;
m_clips[3].h = 100;
m_clips[4].x = 0;
m_clips[4].y = 100;
m_clips[4].w = 50;
m_clips[4].h = 100;
m_clips[5].x = 50;
m_clips[5].y = 100;
m_clips[5].w = 50;
m_clips[5].h = 100;
m_clips[6].x = 100;
m_clips[6].y = 100;
m_clips[6].w = 50;
m_clips[6].h = 100;
m_clips[7].x = 150;
m_clips[7].y = 100;
m_clips[7].w = 50;
m_clips[7].h = 100;
m_clips[8].x = 0;
m_clips[8].y = 200;
m_clips[8].w = 50;
m_clips[8].h = 100;
m_clips[9].x = 50;
m_clips[9].y = 200;
m_clips[9].w = 50;
m_clips[9].h = 85;
m_clips[10].x = 100;
m_clips[10].y = 200;
m_clips[10].w = 50;
m_clips[10].h = 60;
m_clips[11].x = 150;
m_clips[11].y = 200;
m_clips[11].w = 50;
m_clips[11].h = 50;
m_clips[12].x = 0;
m_clips[12].y = 300;
m_clips[12].w = 50;
m_clips[12].h = 100;
m_clips[13].x = 50;
m_clips[13].y = 300;
m_clips[13].w = 50;
m_clips[13].h = 100;
m_clips[14].x = 100;
m_clips[14].y = 300;
m_clips[14].w = 50;
m_clips[14].h = 100;
m_clips[15].x = 150;
m_clips[15].y = 300;
m_clips[15].w = 50;
m_clips[15].h = 100;
isDrawn = false;
speed = 110;
gravity = 0;
dx = 0;
dy = 0;
u = 0;
imageLoad = imageLoad->getInstance();
m_imageSprite = new ImageSprite();
}
Caio::~Caio()
{
// Nothing yet
}
void
Caio::init()
{
m_imageSprite->loadFromFile("res/images/s_caio.png");
}
void
Caio::draw()
{
imageLoad->update(m_imageSprite->m_texture, &m_clips[u], &m_position);
}
void
Caio::update(Uint32 delta)
{
m_position.x += ((speed*delta)/1000.0)*dx;
m_position.y -= ((speed*delta)/1000.0)*dy;
if( (m_position.x < 0) || ( m_position.x > 800 ) )
{
m_position.x -= ((speed*delta)/1000.0)*dx;
}
if( m_position.y < 150)
{
m_position.y += ((speed*delta)/1000.0)*dy;
gravity = 0;
}
}
void
Caio::release()
{
SDL_DestroyTexture(m_imageSprite->m_texture);
}
bool
Caio::handle(SDL_Event& event)
{
bool processed = false;
switch (event.type)
{
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_a:
dx = -1;
processed = true;
if(u<=3)
u++;
else
u=0;
break;
case SDLK_d:
dx = 1;
processed = true;
if((u>=4) && (u<8))
u++;
else
u=4;
break;
case SDLK_SPACE:
dy = 1;
processed = true;
u++;
if((u>=12) && (u<15))
u++;
else
u=12;
break;
default:
break;
}
break;
case SDL_KEYUP:
switch(event.key.keysym.sym)
{
case SDLK_a:
dx = 0;
processed = true;
break;
case SDLK_d:
dx = 0;
processed = true;
break;
case SDLK_SPACE:
dy = 0;
processed = true;
break;
default:
break;
}
break;
default:
break;
}
return processed;
}
<|endoftext|> |
<commit_before>#include "../SDP_Solver.hxx"
#include "../../../set_stream_precision.hxx"
void SDP_Solver::save_solution(
const SDP_Solver_Terminate_Reason terminate_reason,
const boost::filesystem::path &out_file) const
{
// El::Print requires all processors, but we do not want all processors
// writing header information.
// FIXME: Write separate files for each rank.
boost::filesystem::ofstream ofs(out_file);
set_stream_precision(ofs);
if(El::mpi::Rank() == 0)
{
std::cout << "Saving solution to : " << out_file << '\n';
ofs << "terminateReason = \"" << terminate_reason << "\";\n"
<< "primalObjective = " << primal_objective << ";\n"
<< "dualObjective = " << dual_objective << ";\n"
<< "dualityGap = " << duality_gap << ";\n"
<< "primalError = " << primal_error << ";\n"
<< "dualError = " << dual_error << ";\n"
<< "y = {";
}
if(!y.blocks.empty())
{
El::Print(y.blocks.at(0), "", ofs);
}
if(El::mpi::Rank() == 0)
{
ofs << "};\nx = {";
}
for(auto &block : x.blocks)
{
El::Print(block, "", ofs);
}
if(El::mpi::Rank() == 0)
{
ofs << "};\n";
}
}
<commit_msg>Fix output corruption<commit_after>#include "../SDP_Solver.hxx"
#include "../../../set_stream_precision.hxx"
void SDP_Solver::save_solution(
const SDP_Solver_Terminate_Reason terminate_reason,
const boost::filesystem::path &out_file) const
{
// Internally, El::Print() sync's everything to the root core and
// outputs it from there. So do not actually open the file on
// anything but the root node.
boost::filesystem::ofstream out_stream;
if(El::mpi::Rank() == 0)
{
std::cout << "Saving solution to : " << out_file << '\n';
out_stream.open(out_file);
set_stream_precision(out_stream);
out_stream << "terminateReason = \"" << terminate_reason << "\";\n"
<< "primalObjective = " << primal_objective << ";\n"
<< "dualObjective = " << dual_objective << ";\n"
<< "dualityGap = " << duality_gap << ";\n"
<< "primalError = " << primal_error << ";\n"
<< "dualError = " << dual_error << ";\n"
<< "y = {";
}
if(!y.blocks.empty())
{
El::Print(y.blocks.at(0), "", out_stream);
}
if(El::mpi::Rank() == 0)
{
out_stream << "};\nx = {";
}
for(auto &block : x.blocks)
{
El::Print(block, "", out_stream);
}
if(El::mpi::Rank() == 0)
{
out_stream << "};\n";
}
}
<|endoftext|> |
<commit_before>//
// Name: LinearStructDlg.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "LinearStructDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "LinearStructDlg.h"
#define HEIGHT_MIN 1.0f
#define HEIGHT_MAX 6.0f
#define SPACING_MIN 1.0f
#define SPACING_MAX 4.0f
// WDR: class implementations
//----------------------------------------------------------------------------
// LinearStructureDlg
//----------------------------------------------------------------------------
// WDR: event table for LinearStructureDlg
BEGIN_EVENT_TABLE(LinearStructureDlg,AutoDialog)
EVT_CHOICE( ID_TYPE, LinearStructureDlg::OnFenceType )
EVT_TEXT( ID_HEIGHTEDIT, LinearStructureDlg::OnHeightEdit )
EVT_TEXT( ID_SPACINGEDIT, LinearStructureDlg::OnSpacingEdit )
EVT_SLIDER( ID_HEIGHTSLIDER, LinearStructureDlg::OnHeightSlider )
EVT_SLIDER( ID_SPACINGSLIDER, LinearStructureDlg::OnSpacingSlider )
END_EVENT_TABLE()
LinearStructureDlg::LinearStructureDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
LinearStructDialogFunc( this, TRUE );
m_pSpacingSlider = GetSpacingslider();
m_pHeightSlider = GetHeightslider();
m_pFenceChoice = GetFencetype();
}
// WDR: handler implementations for LinearStructureDlg
void LinearStructureDlg::OnSpacingSlider( wxCommandEvent &event )
{
TransferDataFromWindow();
SlidersToValues();
TransferDataToWindow();
OnSetOptions(m_opts);
}
void LinearStructureDlg::OnHeightSlider( wxCommandEvent &event )
{
OnSpacingSlider(event);
}
void LinearStructureDlg::OnSpacingEdit( wxCommandEvent &event )
{
TransferDataFromWindow();
ValuesToSliders();
TransferDataToWindow();
OnSetOptions(m_opts);
}
void LinearStructureDlg::OnHeightEdit( wxCommandEvent &event )
{
OnSpacingEdit(event);
}
void LinearStructureDlg::OnFenceType( wxCommandEvent &event )
{
TransferDataFromWindow();
m_opts.eType = (FenceType) m_iType;
OnSetOptions(m_opts);
}
void LinearStructureDlg::OnInitDialog(wxInitDialogEvent& event)
{
AddValidator(ID_TYPE, &m_iType);
AddValidator(ID_HEIGHTSLIDER, &m_iHeight);
AddValidator(ID_SPACINGSLIDER, &m_iSpacing);
AddNumValidator(ID_HEIGHTEDIT, &m_opts.fHeight);
AddNumValidator(ID_SPACINGEDIT, &m_opts.fSpacing);
m_iType = 0;
m_opts.fHeight = FENCE_DEFAULT_HEIGHT;
m_opts.fSpacing = FENCE_DEFAULT_SPACING;
ValuesToSliders();
// NB -- these must match the FT_ enum in order
m_pFenceChoice->Clear();
m_pFenceChoice->Append(_T("Wooden posts, 3 wires"));
m_pFenceChoice->Append(_T("Metal poles, chain-link"));
m_pFenceChoice->Append(_T("English Hedgerow"));
m_pFenceChoice->Append(_T("English Drystone"));
m_pFenceChoice->Append(_T("English Privet"));
m_pFenceChoice->Append(_T("Stone"));
m_pFenceChoice->Append(_T("English Beech"));
TransferDataToWindow();
m_opts.eType = (FenceType) m_iType;
OnSetOptions(m_opts);
}
void LinearStructureDlg::SlidersToValues()
{
m_opts.fHeight = HEIGHT_MIN + m_iHeight * (HEIGHT_MAX - HEIGHT_MIN) / 100.0f;
m_opts.fSpacing = SPACING_MIN + m_iSpacing * (SPACING_MAX - SPACING_MIN) / 100.0f;
}
void LinearStructureDlg::ValuesToSliders()
{
m_iHeight = (int) ((m_opts.fHeight - HEIGHT_MIN) / (HEIGHT_MAX - HEIGHT_MIN) * 100.0f);
m_iSpacing = (int) ((m_opts.fSpacing - SPACING_MIN) / (SPACING_MAX - SPACING_MIN) * 100.0f);
}
<commit_msg>reorder items, from RJ<commit_after>//
// Name: LinearStructDlg.cpp
//
// Copyright (c) 2001-2003 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
#ifdef __GNUG__
#pragma implementation "LinearStructDlg.cpp"
#endif
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "LinearStructDlg.h"
#define HEIGHT_MIN 1.0f
#define HEIGHT_MAX 6.0f
#define SPACING_MIN 1.0f
#define SPACING_MAX 4.0f
// WDR: class implementations
//----------------------------------------------------------------------------
// LinearStructureDlg
//----------------------------------------------------------------------------
// WDR: event table for LinearStructureDlg
BEGIN_EVENT_TABLE(LinearStructureDlg,AutoDialog)
EVT_CHOICE( ID_TYPE, LinearStructureDlg::OnFenceType )
EVT_TEXT( ID_HEIGHTEDIT, LinearStructureDlg::OnHeightEdit )
EVT_TEXT( ID_SPACINGEDIT, LinearStructureDlg::OnSpacingEdit )
EVT_SLIDER( ID_HEIGHTSLIDER, LinearStructureDlg::OnHeightSlider )
EVT_SLIDER( ID_SPACINGSLIDER, LinearStructureDlg::OnSpacingSlider )
END_EVENT_TABLE()
LinearStructureDlg::LinearStructureDlg( wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &position, const wxSize& size, long style ) :
AutoDialog( parent, id, title, position, size, style )
{
LinearStructDialogFunc( this, TRUE );
m_pSpacingSlider = GetSpacingslider();
m_pHeightSlider = GetHeightslider();
m_pFenceChoice = GetFencetype();
}
// WDR: handler implementations for LinearStructureDlg
void LinearStructureDlg::OnSpacingSlider( wxCommandEvent &event )
{
TransferDataFromWindow();
SlidersToValues();
TransferDataToWindow();
OnSetOptions(m_opts);
}
void LinearStructureDlg::OnHeightSlider( wxCommandEvent &event )
{
OnSpacingSlider(event);
}
void LinearStructureDlg::OnSpacingEdit( wxCommandEvent &event )
{
TransferDataFromWindow();
ValuesToSliders();
TransferDataToWindow();
OnSetOptions(m_opts);
}
void LinearStructureDlg::OnHeightEdit( wxCommandEvent &event )
{
OnSpacingEdit(event);
}
void LinearStructureDlg::OnFenceType( wxCommandEvent &event )
{
TransferDataFromWindow();
m_opts.eType = (FenceType) m_iType;
OnSetOptions(m_opts);
}
void LinearStructureDlg::OnInitDialog(wxInitDialogEvent& event)
{
AddValidator(ID_TYPE, &m_iType);
AddValidator(ID_HEIGHTSLIDER, &m_iHeight);
AddValidator(ID_SPACINGSLIDER, &m_iSpacing);
AddNumValidator(ID_HEIGHTEDIT, &m_opts.fHeight);
AddNumValidator(ID_SPACINGEDIT, &m_opts.fSpacing);
m_iType = 0;
m_opts.fHeight = FENCE_DEFAULT_HEIGHT;
m_opts.fSpacing = FENCE_DEFAULT_SPACING;
ValuesToSliders();
// NB -- these must match the FT_ enum in order
m_pFenceChoice->Clear();
m_pFenceChoice->Append(_T("Wooden posts, 3 wires"));
m_pFenceChoice->Append(_T("Metal poles, chain-link"));
m_pFenceChoice->Append(_T("English Hedgerow"));
m_pFenceChoice->Append(_T("English Drystone"));
m_pFenceChoice->Append(_T("English Privet"));
m_pFenceChoice->Append(_T("English Beech"));
m_pFenceChoice->Append(_T("Coursed Stone"));
TransferDataToWindow();
m_opts.eType = (FenceType) m_iType;
OnSetOptions(m_opts);
}
void LinearStructureDlg::SlidersToValues()
{
m_opts.fHeight = HEIGHT_MIN + m_iHeight * (HEIGHT_MAX - HEIGHT_MIN) / 100.0f;
m_opts.fSpacing = SPACING_MIN + m_iSpacing * (SPACING_MAX - SPACING_MIN) / 100.0f;
}
void LinearStructureDlg::ValuesToSliders()
{
m_iHeight = (int) ((m_opts.fHeight - HEIGHT_MIN) / (HEIGHT_MAX - HEIGHT_MIN) * 100.0f);
m_iSpacing = (int) ((m_opts.fSpacing - SPACING_MIN) / (SPACING_MAX - SPACING_MIN) * 100.0f);
}
<|endoftext|> |
<commit_before>/*************************************************************************
* Copyright (C) 2011-2012 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* TeapotNet is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "http.h"
#include "exception.h"
#include "html.h"
namespace tpot
{
Http::Request::Request(void)
{
clear();
}
Http::Request::Request(const String &url, const String &method)
{
clear();
int p = url.find("://");
if(p == String::NotFound) this->url = url;
else {
String protocol(url.substr(0,p));
if(protocol != "http") throw Exception(String("Unknown protocol in URL: ")+protocol);
String host(url.substr(p+3));
this->url = String('/') + host.cut('/');
headers["Host"] = host;
}
if(!method.empty()) this->method = method;
this->headers["User-Agent"] = String(APPNAME) + '/' + APPVERSION;
}
void Http::Request::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && !headers.contains("Connexion"))
headers["Connection"] = "close";
//if(!headers.contains("Accept-Encoding"))
// headers["Accept-Encoding"] = "identity";
String completeUrl(url);
if(!get.empty())
{
if(completeUrl.find('?') == String::NotFound)
completeUrl+= '?';
for( StringMap::iterator it = get.begin();
it != get.end();
++it)
{
completeUrl<<'&'<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
}
String postData;
if(!post.empty())
{
for( StringMap::iterator it = post.begin();
it != post.end();
++it)
{
if(!postData.empty()) postData<<'&';
postData<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
headers["Content-Length"] = "";
headers["Content-Length"] << postData.size();
headers["Content-Type"] = "application/x-www-form-urlencoded";
}
String buf;
buf<<method<<" "<<completeUrl<<" HTTP/"<<version<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
buf<<it->first<<": "<<*l<<"\r\n";
}
}
for( StringMap::iterator it = cookies.begin();
it != cookies.end();
++it)
{
buf<<"Set-Cookie: "<< it->first<<'='<<it->second<<"\r\n";
}
buf<<"\r\n";
sock<<buf;
if(!postData.empty())
sock<<postData;
}
void Http::Request::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
method.clear();
url.clear();
line.readString(method);
line.readString(url);
String protocol;
line.readString(protocol);
version = protocol.cut('/');
if(url.empty() || version.empty() || protocol != "HTTP")
throw 400;
if(method != "GET" && method != "POST" /*&& method != "HEAD"*/)
throw 405;
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
// Read cookies
String cookie;
if(headers.get("Cookie",cookie))
{
while(!cookie.empty())
{
String next = cookie.cut(';');
String value = cookie.cut('=');
cookie.trim();
value.trim();
cookies.insert(cookie,value);
cookie = next;
}
}
// Read URL variables
String getData = url.cut('?');
if(!getData.empty())
{
List<String> exploded;
getData.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
get.insert(it->urlDecode(), value);
}
}
// Read post variables
if(method == "POST")
{
if(!headers.contains("Content-Length"))
throw Exception("Missing Content-Length header in POST request");
size_t size = 0;
String contentLength(headers["Content-Length"]);
contentLength >> size;
String data;
if(sock.read(data, size) != size)
throw IOException("Connection unexpectedly closed");
if(headers.contains("Content-Type"))
{
String type = headers["Content-Type"];
String parameters = type.cut(';');
type.trim();
if(type == "application/x-www-form-urlencoded")
{
List<String> exploded;
data.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
post.insert(it->urlDecode(), value);
}
}
}
}
}
void Http::Request::clear(void)
{
method = "GET";
version = "1.0";
url.clear();
headers.clear();
cookies.clear();
get.clear();
post.clear();
}
Http::Response::Response(void)
{
clear();
}
Http::Response::Response(const Request &request, int code)
{
clear();
this->code = code;
this->version = request.version;
this->sock = request.sock;
this->headers["Content-Type"] = "text/html; charset=UTF-8";
}
void Http::Response::send(void)
{
send(*sock);
}
void Http::Response::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && code >= 200 && !headers.contains("Connexion"))
headers["Connection"] = "close";
if(!headers.contains("Date"))
{
// TODO
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
char buffer[256];
strftime(buffer, 256, "%a, %d %b %Y %H:%M:%S %Z", timeinfo);
headers["Date"] = buffer;
}
if(message.empty())
{
switch(code)
{
case 100: message = "Continue"; break;
case 200: message = "OK"; break;
case 204: message = "No content"; break;
case 206: message = "Partial Content"; break;
case 301: message = "Moved Permanently"; break;
case 302: message = "Found"; break;
case 303: message = "See Other"; break;
case 304: message = "Not Modified"; break;
case 305: message = "Use Proxy"; break;
case 307: message = "Temporary Redirect"; break;
case 400: message = "Bad Request"; break;
case 401: message = "Unauthorized"; break;
case 403: message = "Forbidden"; break;
case 404: message = "Not Found"; break;
case 405: message = "Method Not Allowed"; break;
case 406: message = "Not Acceptable"; break;
case 408: message = "Request Timeout"; break;
case 410: message = "Gone"; break;
case 413: message = "Request Entity Too Large"; break;
case 414: message = "Request-URI Too Long"; break;
case 416: message = "Requested Range Not Satisfiable"; break;
case 500: message = "Internal Server Error"; break;
case 501: message = "Not Implemented"; break;
case 502: message = "Bad Gateway"; break;
case 503: message = "Service Unavailable"; break;
case 504: message = "Gateway Timeout"; break;
case 505: message = "HTTP Version Not Supported"; break;
default:
if(code < 300) message = "OK";
else message = "Error";
break;
}
}
sock<<"HTTP/"<<version<<" "<<code<<" "<<message<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
sock<<it->first<<": "<<*l<<"\r\n";
}
}
sock<<"\r\n";
}
void Http::Response::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
String protocol;
line.readString(protocol);
version = protocol.cut('/');
line.read(code);
message = line;
if(version.empty() || protocol != "HTTP")
throw Exception("Invalid HTTP response");
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
}
void Http::Response::clear(void)
{
code = 200;
version = "1.0";
message.clear();
version.clear();
}
Http::Server::Server(int port) :
mSock(port)
{
}
Http::Server::~Server(void)
{
mSock.close(); // useless
}
void Http::Server::run(void)
{
try {
while(true)
{
Socket *sock = new Socket;
mSock.accept(*sock);
Handler *client = new Handler(this, sock);
client->start(true); // client will destroy itself
}
}
catch(const NetException &e)
{
return;
}
}
Http::Server::Handler::Handler(Server *server, Socket *sock) :
mServer(server),
mSock(sock)
{
}
Http::Server::Handler::~Handler(void)
{
delete mSock; // deletion closes the socket
}
void Http::Server::Handler::run(void)
{
Request request;
try {
try {
request.recv(*mSock);
String expect;
if(request.headers.get("Expect",expect)
&& expect.toLower() == "100-continue")
{
mSock->write("HTTP/1.1 100 Continue\r\n\r\n");
}
mServer->process(request);
}
catch(const NetException &e)
{
Log("Http::Server::Handler", e.what());
}
catch(const Exception &e)
{
Log("Http::Server::Handler", String("Error: ") + e.what());
throw 500;
}
}
catch(int code)
{
Response response(request, code);
response.headers["Content-Type"] = "text/html; charset=UTF-8";
response.send();
if(request.method != "HEAD")
{
Html page(response.sock);
page.header(response.message);
page.open("h1");
page.text(String::number(response.code) + " - " + response.message);
page.close("h1");
page.footer();
}
}
}
int Http::Get(const String &url, Stream *output)
{
Request request(url,"GET");
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// TODO: relative location (even if not RFC-compliant)
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
int Http::Post(const String &url, const StringMap &post, Stream *output)
{
Request request(url,"POST");
request.post = post;
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// Location MAY NOT be a relative URL
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
}
<commit_msg>Added NetException catcher<commit_after>/*************************************************************************
* Copyright (C) 2011-2012 by Paul-Louis Ageneau *
* paul-louis (at) ageneau (dot) org *
* *
* This file is part of TeapotNet. *
* *
* TeapotNet is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of *
* the License, or (at your option) any later version. *
* *
* TeapotNet is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public *
* License along with TeapotNet. *
* If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
#include "http.h"
#include "exception.h"
#include "html.h"
namespace tpot
{
Http::Request::Request(void)
{
clear();
}
Http::Request::Request(const String &url, const String &method)
{
clear();
int p = url.find("://");
if(p == String::NotFound) this->url = url;
else {
String protocol(url.substr(0,p));
if(protocol != "http") throw Exception(String("Unknown protocol in URL: ")+protocol);
String host(url.substr(p+3));
this->url = String('/') + host.cut('/');
headers["Host"] = host;
}
if(!method.empty()) this->method = method;
this->headers["User-Agent"] = String(APPNAME) + '/' + APPVERSION;
}
void Http::Request::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && !headers.contains("Connexion"))
headers["Connection"] = "close";
//if(!headers.contains("Accept-Encoding"))
// headers["Accept-Encoding"] = "identity";
String completeUrl(url);
if(!get.empty())
{
if(completeUrl.find('?') == String::NotFound)
completeUrl+= '?';
for( StringMap::iterator it = get.begin();
it != get.end();
++it)
{
completeUrl<<'&'<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
}
String postData;
if(!post.empty())
{
for( StringMap::iterator it = post.begin();
it != post.end();
++it)
{
if(!postData.empty()) postData<<'&';
postData<<it->first.urlEncode()<<'='<<it->second.urlEncode();
}
headers["Content-Length"] = "";
headers["Content-Length"] << postData.size();
headers["Content-Type"] = "application/x-www-form-urlencoded";
}
String buf;
buf<<method<<" "<<completeUrl<<" HTTP/"<<version<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
buf<<it->first<<": "<<*l<<"\r\n";
}
}
for( StringMap::iterator it = cookies.begin();
it != cookies.end();
++it)
{
buf<<"Set-Cookie: "<< it->first<<'='<<it->second<<"\r\n";
}
buf<<"\r\n";
sock<<buf;
if(!postData.empty())
sock<<postData;
}
void Http::Request::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
method.clear();
url.clear();
line.readString(method);
line.readString(url);
String protocol;
line.readString(protocol);
version = protocol.cut('/');
if(url.empty() || version.empty() || protocol != "HTTP")
throw 400;
if(method != "GET" && method != "POST" /*&& method != "HEAD"*/)
throw 405;
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
// Read cookies
String cookie;
if(headers.get("Cookie",cookie))
{
while(!cookie.empty())
{
String next = cookie.cut(';');
String value = cookie.cut('=');
cookie.trim();
value.trim();
cookies.insert(cookie,value);
cookie = next;
}
}
// Read URL variables
String getData = url.cut('?');
if(!getData.empty())
{
List<String> exploded;
getData.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
get.insert(it->urlDecode(), value);
}
}
// Read post variables
if(method == "POST")
{
if(!headers.contains("Content-Length"))
throw Exception("Missing Content-Length header in POST request");
size_t size = 0;
String contentLength(headers["Content-Length"]);
contentLength >> size;
String data;
if(sock.read(data, size) != size)
throw IOException("Connection unexpectedly closed");
if(headers.contains("Content-Type"))
{
String type = headers["Content-Type"];
String parameters = type.cut(';');
type.trim();
if(type == "application/x-www-form-urlencoded")
{
List<String> exploded;
data.explode(exploded,'&');
for( List<String>::iterator it = exploded.begin();
it != exploded.end();
++it)
{
String value = it->cut('=').urlDecode();
post.insert(it->urlDecode(), value);
}
}
}
}
}
void Http::Request::clear(void)
{
method = "GET";
version = "1.0";
url.clear();
headers.clear();
cookies.clear();
get.clear();
post.clear();
}
Http::Response::Response(void)
{
clear();
}
Http::Response::Response(const Request &request, int code)
{
clear();
this->code = code;
this->version = request.version;
this->sock = request.sock;
this->headers["Content-Type"] = "text/html; charset=UTF-8";
}
void Http::Response::send(void)
{
send(*sock);
}
void Http::Response::send(Socket &sock)
{
this->sock = &sock;
if(version == "1.1" && code >= 200 && !headers.contains("Connexion"))
headers["Connection"] = "close";
if(!headers.contains("Date"))
{
// TODO
time_t rawtime;
time(&rawtime);
struct tm *timeinfo = localtime(&rawtime);
char buffer[256];
strftime(buffer, 256, "%a, %d %b %Y %H:%M:%S %Z", timeinfo);
headers["Date"] = buffer;
}
if(message.empty())
{
switch(code)
{
case 100: message = "Continue"; break;
case 200: message = "OK"; break;
case 204: message = "No content"; break;
case 206: message = "Partial Content"; break;
case 301: message = "Moved Permanently"; break;
case 302: message = "Found"; break;
case 303: message = "See Other"; break;
case 304: message = "Not Modified"; break;
case 305: message = "Use Proxy"; break;
case 307: message = "Temporary Redirect"; break;
case 400: message = "Bad Request"; break;
case 401: message = "Unauthorized"; break;
case 403: message = "Forbidden"; break;
case 404: message = "Not Found"; break;
case 405: message = "Method Not Allowed"; break;
case 406: message = "Not Acceptable"; break;
case 408: message = "Request Timeout"; break;
case 410: message = "Gone"; break;
case 413: message = "Request Entity Too Large"; break;
case 414: message = "Request-URI Too Long"; break;
case 416: message = "Requested Range Not Satisfiable"; break;
case 500: message = "Internal Server Error"; break;
case 501: message = "Not Implemented"; break;
case 502: message = "Bad Gateway"; break;
case 503: message = "Service Unavailable"; break;
case 504: message = "Gateway Timeout"; break;
case 505: message = "HTTP Version Not Supported"; break;
default:
if(code < 300) message = "OK";
else message = "Error";
break;
}
}
sock<<"HTTP/"<<version<<" "<<code<<" "<<message<<"\r\n";
for( StringMap::iterator it = headers.begin();
it != headers.end();
++it)
{
List<String> lines;
it->second.remove('\r');
it->second.explode(lines,'\n');
for( List<String>::iterator l = lines.begin();
l != lines.end();
++l)
{
sock<<it->first<<": "<<*l<<"\r\n";
}
}
sock<<"\r\n";
}
void Http::Response::recv(Socket &sock)
{
this->sock = &sock;
clear();
// Read first line
String line;
if(!sock.readLine(line)) throw IOException("Connection closed");
String protocol;
line.readString(protocol);
version = protocol.cut('/');
line.read(code);
message = line;
if(version.empty() || protocol != "HTTP")
throw Exception("Invalid HTTP response");
// Read headers
while(true)
{
String line;
AssertIO(sock.readLine(line));
if(line.empty()) break;
String value = line.cut(':');
line.trim();
value.trim();
headers.insert(line,value);
}
}
void Http::Response::clear(void)
{
code = 200;
version = "1.0";
message.clear();
version.clear();
}
Http::Server::Server(int port) :
mSock(port)
{
}
Http::Server::~Server(void)
{
mSock.close(); // useless
}
void Http::Server::run(void)
{
try {
while(true)
{
Socket *sock = new Socket;
mSock.accept(*sock);
Handler *client = new Handler(this, sock);
client->start(true); // client will destroy itself
}
}
catch(const NetException &e)
{
return;
}
}
Http::Server::Handler::Handler(Server *server, Socket *sock) :
mServer(server),
mSock(sock)
{
}
Http::Server::Handler::~Handler(void)
{
delete mSock; // deletion closes the socket
}
void Http::Server::Handler::run(void)
{
Request request;
try {
try {
try {
request.recv(*mSock);
String expect;
if(request.headers.get("Expect",expect)
&& expect.toLower() == "100-continue")
{
mSock->write("HTTP/1.1 100 Continue\r\n\r\n");
}
mServer->process(request);
}
catch(const NetException &e)
{
Log("Http::Server::Handler", e.what());
}
catch(const Exception &e)
{
Log("Http::Server::Handler", String("Error: ") + e.what());
throw 500;
}
}
catch(int code)
{
Response response(request, code);
response.headers["Content-Type"] = "text/html; charset=UTF-8";
response.send();
if(request.method != "HEAD")
{
Html page(response.sock);
page.header(response.message);
page.open("h1");
page.text(String::number(response.code) + " - " + response.message);
page.close("h1");
page.footer();
}
}
}
catch(const NetException &e)
{
Log("Http::Server::Handler", e.what());
}
}
int Http::Get(const String &url, Stream *output)
{
Request request(url,"GET");
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// TODO: relative location (even if not RFC-compliant)
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
int Http::Post(const String &url, const StringMap &post, Stream *output)
{
Request request(url,"POST");
request.post = post;
String host;
if(!request.headers.get("Host",host))
throw Exception("Invalid URL");
String service(host.cut(':'));
if(service.empty()) service = "80";
Socket sock(Address(host, service));
request.send(sock);
Response response;
response.recv(sock);
if(response.code/100 == 3 && response.headers.contains("Location"))
{
sock.discard();
sock.close();
// Location MAY NOT be a relative URL
return Get(response.headers["Location"], output);
}
if(output) sock.read(*output);
else sock.discard();
return response.code;
}
}
<|endoftext|> |
<commit_before>/* clang++ test_spsc_ring.cpp -o test_spsc_ring -std=c++11 -l pthread
./test_spsc_ring
*/
#include <memory>
#include <thread>
#include <cstring>
#include <cassert>
#include <chrono>
#include <atomic>
template< typename T, typename IndexT = uint32_t >
class SimpleRing {
public:
static constexpr uint32_t SLOTSIZE = sizeof(T);
SimpleRing( uint32_t sz ) : size(sz) {
data = (T*)std::malloc( size*SLOTSIZE );
read_idx = 0;
write_idx = 0;
}
~SimpleRing() {
::free( data );
}
bool push( const T& obj ) {
uint32_t next_idx = write_idx+1<size ? write_idx+1 : 0;
if ( next_idx != read_idx ) {
data[write_idx] = obj;
write_idx = next_idx;
return true;
}
return false;
}
bool pop( T& obj ) {
uint32_t next_idx = read_idx+1<size ? read_idx+1 : 0;
if ( read_idx != write_idx ) {
obj = data[read_idx];
read_idx = next_idx;
return true;
}
return false;
}
private:
SimpleRing();
SimpleRing( const SimpleRing& );
std::atomic<IndexT> read_idx;
std::atomic<IndexT> write_idx;
const uint32_t size;
T* data;
};
template< typename T, typename IndexT = uint32_t >
class SnellmanRing {
public:
static constexpr uint32_t SLOTSIZE = sizeof(T);
SnellmanRing( uint32_t sz ) : size(sz) {
data = (T*)std::malloc( size*SLOTSIZE );
read_idx = 0;
write_idx = 0;
}
~SnellmanRing() {
::free( data );
}
bool push( const T& obj ) {
uint32_t numel = write_idx - read_idx;
if ( numel < size ) {
data[write_idx%size] = obj;
write_idx++;
return true;
}
return false;
}
bool pop( T& obj ) {
uint32_t numel = write_idx - read_idx;
if ( numel>0 ) {
obj = data[read_idx%size];
read_idx++;
return true;
}
return false;
}
private:
SnellmanRing();
SnellmanRing( const SnellmanRing& );
std::atomic<IndexT> read_idx;
std::atomic<IndexT> write_idx;
const uint32_t size;
T* data;
};
template< typename T, typename IndexT = uint32_t >
class VitorianRing {
public:
static constexpr uint32_t SLOTSIZE = sizeof(T);
VitorianRing( uint32_t sz ) : size(sz) {
data = (T*)std::malloc( size*SLOTSIZE );
read_idx = 0;
write_idx = 2*size;
}
~VitorianRing() {
::free( data );
}
bool push( const T& obj ) {
uint32_t numel = (write_idx-read_idx) % (2*size);
//fprintf( stderr, "Push read:%d write:%d diff:%d\n", read_idx, write_idx, numel );
if ( numel < size ) {
data[write_idx%size] = obj;
write_idx = ( write_idx+1 < 4*size ) ? write_idx + 1 : 2*size;
return true;
}
return false;
}
bool pop( T& obj ) {
uint32_t numel = (write_idx-read_idx) % (2*size);
//fprintf( stderr, "Pop read:%d write:%d diff:%d\n", read_idx, write_idx, numel );
if ( numel > 0 ) {
obj = data[read_idx%size];
read_idx = ( read_idx+1 < 2*size ) ? read_idx+1 : 0;
return true;
}
return false;
}
private:
VitorianRing();
VitorianRing( const VitorianRing& );
std::atomic<IndexT> read_idx;
std::atomic<IndexT> write_idx;
const uint32_t size;
T* data;
};
template< class RingT >
void producer( RingT& rng, int count, int seed ) {
for ( int j=0; j<count; ++j ) {
while ( !rng.push( j + seed ) )
std::this_thread::sleep_for( std::chrono::milliseconds(1) );
//fprintf( stderr, " >> pushed %d\n", j+val );
}
}
template< class RingT >
void consumer( RingT& rng, int count, int seed ) {
for ( int j=0; j<count; ++j ) {
int res;
while ( !rng.pop( res ) )
std::this_thread::sleep_for( std::chrono::milliseconds(1) );
//fprintf( stderr, " >> popped %d\n", res );
assert( res==seed+j );
}
}
template< class RingT >
void test()
{
printf( "Testing...\n" );
try {
RingT rng( 8 );
std::thread th1( producer<RingT>, std::ref(rng), 10000, 99 );
std::thread th2( consumer<RingT>, std::ref(rng), 10000, 99 );
th1.join();
th2.join();
}
catch( std::exception& ex ) {
printf( "%s\n", ex.what() );
}
}
int main( int argc, char* argv[] ) {
test<SimpleRing<int>>();
test<SnellmanRing<int>>();
test<VitorianRing<int>>();
}
<commit_msg>Added opening for custom allocators and choice of index type<commit_after>/* clang++ test_spsc_ring.cpp -o test_spsc_ring -std=c++11 -l pthread
./test_spsc_ring
*/
#include <memory>
#include <thread>
#include <cstring>
#include <cassert>
#include <chrono>
#include <atomic>
template< typename T, typename IndexT = uint32_t, typename AllocT = std::allocator<T> >
class SimpleRing {
public:
static constexpr uint32_t SLOTSIZE = sizeof(T);
SimpleRing( uint32_t sz ) : size(sz) {
data = allocator.allocate( size );
read_idx = 0;
write_idx = 0;
}
~SimpleRing() {
allocator.deallocate( data, size );
}
bool push( const T& obj ) {
uint32_t next_idx = write_idx+1<size ? write_idx+1 : 0;
if ( next_idx != read_idx ) {
data[write_idx] = obj;
write_idx = next_idx;
return true;
}
return false;
}
bool pop( T& obj ) {
uint32_t next_idx = read_idx+1<size ? read_idx+1 : 0;
if ( read_idx != write_idx ) {
obj = data[read_idx];
read_idx = next_idx;
return true;
}
return false;
}
private:
SimpleRing();
SimpleRing( const SimpleRing& );
std::atomic<IndexT> read_idx;
std::atomic<IndexT> write_idx;
const uint32_t size;
T* data;
AllocT allocator;
};
template< typename T, typename IndexT = uint32_t, typename AllocT = std::allocator<T> >
class SnellmanRing {
public:
static constexpr uint32_t SLOTSIZE = sizeof(T);
SnellmanRing( uint32_t sz ) : size(sz) {
data = allocator.allocate( sz );
read_idx = 0;
write_idx = 0;
}
~SnellmanRing() {
allocator.deallocate( data, size );
}
bool push( const T& obj ) {
uint32_t numel = write_idx - read_idx;
if ( numel < size ) {
data[write_idx%size] = obj;
write_idx++;
return true;
}
return false;
}
bool pop( T& obj ) {
uint32_t numel = write_idx - read_idx;
if ( numel>0 ) {
obj = data[read_idx%size];
read_idx++;
return true;
}
return false;
}
private:
SnellmanRing();
SnellmanRing( const SnellmanRing& );
std::atomic<IndexT> read_idx;
std::atomic<IndexT> write_idx;
const uint32_t size;
T* data;
AllocT allocator;
};
template< typename T, typename IndexT = uint32_t, typename AllocT = std::allocator<T> >
class VitorianRing {
public:
static constexpr uint32_t SLOTSIZE = sizeof(T);
VitorianRing( uint32_t sz ) : size(sz) {
data = allocator.allocate( sz );
read_idx = 0;
write_idx = 2*size;
}
~VitorianRing() {
allocator.deallocate( data, size );
}
bool push( const T& obj ) {
uint32_t numel = (write_idx-read_idx) % (2*size);
//fprintf( stderr, "Push read:%d write:%d diff:%d\n", read_idx, write_idx, numel );
if ( numel < size ) {
data[write_idx%size] = obj;
write_idx = ( write_idx+1 < 4*size ) ? write_idx + 1 : 2*size;
return true;
}
return false;
}
bool pop( T& obj ) {
uint32_t numel = (write_idx-read_idx) % (2*size);
//fprintf( stderr, "Pop read:%d write:%d diff:%d\n", read_idx, write_idx, numel );
if ( numel > 0 ) {
obj = data[read_idx%size];
read_idx = ( read_idx+1 < 2*size ) ? read_idx+1 : 0;
return true;
}
return false;
}
private:
VitorianRing();
VitorianRing( const VitorianRing& );
std::atomic<IndexT> read_idx;
std::atomic<IndexT> write_idx;
const uint32_t size;
T* data;
AllocT allocator;
};
template< class RingT >
void producer( RingT& rng, int count, int seed ) {
for ( int j=0; j<count; ++j ) {
while ( !rng.push( j + seed ) );
//std::this_thread::sleep_for( std::chrono::milliseconds(1) );
//fprintf( stderr, " >> pushed %d\n", j+val );
}
}
template< class RingT >
void consumer( RingT& rng, int count, int seed ) {
for ( int j=0; j<count; ++j ) {
int res;
while ( !rng.pop( res ) );
//std::this_thread::sleep_for( std::chrono::milliseconds(1) );
//fprintf( stderr, " >> popped %d\n", res );
assert( res==seed+j );
}
}
template< class RingT >
void test()
{
printf( "Testing...\n" );
try {
RingT rng( 8 );
std::thread th1( producer<RingT>, std::ref(rng), 10000, 99 );
std::thread th2( consumer<RingT>, std::ref(rng), 10000, 99 );
th1.join();
th2.join();
}
catch( std::exception& ex ) {
printf( "%s\n", ex.what() );
}
}
int main( int argc, char* argv[] ) {
test<SimpleRing<int>>();
test<SnellmanRing<int>>();
test<VitorianRing<int>>();
}
<|endoftext|> |
<commit_before>// servo.cpp
#include "servo.h"
void Servo::init(uint8_t pin, int min_us, int max_us, int duration) {
_pin = pin;
_min_us = min_us;
_max_us = max_us;
_duration = duration;
}
void Servo::start() {
start_time = millis();
_started = true;
}
void Servo::do_register() {
add_subdevice(new Subdevice(""));
add_subdevice(new Subdevice("set",true))->with_receive_cb(
[&] (const Ustring& payload) {
int value=payload.as_int();
set(value);
return true;
}
);
}
void Servo::turn_to(int value) {
if(!started()) return;
if(stopped) {
_servo.attach(_pin, _min_us, _max_us);
stopped = false;
}
start_time = millis();
_servo.write(value);
_value = value;
measured_value(0).from(value);
}
void Servo::set(int value) {
turn_to(value);
}
bool Servo::measure() {
if(_duration > 0 && (millis() - start_time > (unsigned long)_duration)) {
stop();
}
return false;
}
void Servo::stop() {
if(!started()) return;
_servo.detach();
stopped = true;
}
<commit_msg>fix non-register in servo<commit_after>// servo.cpp
#include "servo.h"
void Servo::init(uint8_t pin, int min_us, int max_us, int duration) {
_pin = pin;
_min_us = min_us;
_max_us = max_us;
_duration = duration;
do_register();
}
void Servo::start() {
start_time = millis();
_started = true;
}
void Servo::do_register() {
add_subdevice(new Subdevice(""));
add_subdevice(new Subdevice("set",true))->with_receive_cb(
[&] (const Ustring& payload) {
int value=payload.as_int();
set(value);
return true;
}
);
}
void Servo::turn_to(int value) {
if(!started()) return;
if(stopped) {
_servo.attach(_pin, _min_us, _max_us);
stopped = false;
}
start_time = millis();
_servo.write(value);
_value = value;
measured_value(0).from(value);
}
void Servo::set(int value) {
turn_to(value);
}
bool Servo::measure() {
if(_duration > 0 && (millis() - start_time > (unsigned long)_duration)) {
stop();
}
return false;
}
void Servo::stop() {
if(!started()) return;
_servo.detach();
stopped = true;
}
<|endoftext|> |
<commit_before>/**
*
* \file test3.cc
*
* \author Manlio Morini
* \date 2011/03/15
*
* This file is part of VITA
*
*/
#include <cstdlib>
#include <iostream>
#include "boost/assign.hpp"
#include "environment.h"
#include "primitive/sr_pri.h"
#include "evolution.h"
#define BOOST_TEST_MODULE Population
#include "boost/test/included/unit_test.hpp"
using namespace boost;
struct F
{
F()
: num(new vita::sr::number(-200,200)),
f_add(new vita::sr::add()),
f_sub(new vita::sr::sub()),
f_mul(new vita::sr::mul()),
f_ifl(new vita::sr::ifl()),
f_ife(new vita::sr::ife())
{
BOOST_TEST_MESSAGE("Setup fixture");
env.insert(num);
env.insert(f_add);
env.insert(f_sub);
env.insert(f_mul);
env.insert(f_ifl);
env.insert(f_ife);
}
~F()
{
BOOST_TEST_MESSAGE("Teardown fixture");
delete num;
delete f_add;
delete f_sub;
delete f_mul;
delete f_ifl;
delete f_ife;
}
vita::sr::number *const num;
vita::sr::add *const f_add;
vita::sr::sub *const f_sub;
vita::sr::mul *const f_mul;
vita::sr::ifl *const f_ifl;
vita::sr::ife *const f_ife;
vita::environment env;
};
BOOST_FIXTURE_TEST_SUITE(Population,F)
BOOST_AUTO_TEST_CASE(RandomCreation)
{
for (unsigned n(4); n <= 100; ++n)
for (unsigned l(1); l <= 100; l+=(l < 10 ? 1 : 30))
{
env.individuals = n;
env.code_length = l;
std::auto_ptr<vita::evaluator> eva(new vita::random_evaluator());
vita::population p(env);
vita::evolution evo(env,p,eva.get());
/*
if (unit_test::runtime_config::log_level() <= unit_test::log_messages)
{
vita::analyzer ay;
evo.pick_stats(&ay);
const boost::uint64_t nef(ay.functions(true));
const boost::uint64_t net(ay.terminals(true));
const boost::uint64_t ne(nef+net);
std::cout << std::string(40,'-') << std::endl;
for (vita::analyzer::const_iterator i(ay.begin());
i != ay.end();
++i)
std::cout << std::setfill(' ') << (i->first)->display() << ": "
<< std::setw(5) << i->second.counter[true]
<< " (" << std::setw(3) << 100*i->second.counter[true]/ne
<< "%)" << std::endl;
std::cout << "Average code length: " << ay.length_dist().mean
<< std::endl
<< "Code length standard deviation: "
<< std::sqrt(ay.length_dist().variance) << std::endl
<< "Max code length: " << ay.length_dist().max << std::endl
<< "Functions: " << nef << " (" << nef*100/ne << "%)"
<< std::endl
<< "Terminals: " << net << " (" << net*100/ne << "%)"
<< std::endl << std::string(40,'-') << std::endl;
}
*/
BOOST_REQUIRE(evo.check());
}
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Compatibility updates to tests.<commit_after>/**
*
* \file test3.cc
*
* \author Manlio Morini
* \date 2011/03/15
*
* This file is part of VITA
*
*/
#include <cstdlib>
#include <iostream>
#include "boost/assign.hpp"
#include "environment.h"
#include "primitive/sr_pri.h"
#include "evolution.h"
#define BOOST_TEST_MODULE Population
#include "boost/test/included/unit_test.hpp"
using namespace boost;
struct F
{
F()
: num(new vita::sr::number(-200,200)),
f_add(new vita::sr::add()),
f_sub(new vita::sr::sub()),
f_mul(new vita::sr::mul()),
f_ifl(new vita::sr::ifl()),
f_ife(new vita::sr::ife())
{
BOOST_TEST_MESSAGE("Setup fixture");
env.insert(num);
env.insert(f_add);
env.insert(f_sub);
env.insert(f_mul);
env.insert(f_ifl);
env.insert(f_ife);
}
~F()
{
BOOST_TEST_MESSAGE("Teardown fixture");
delete num;
delete f_add;
delete f_sub;
delete f_mul;
delete f_ifl;
delete f_ife;
}
vita::sr::number *const num;
vita::sr::add *const f_add;
vita::sr::sub *const f_sub;
vita::sr::mul *const f_mul;
vita::sr::ifl *const f_ifl;
vita::sr::ife *const f_ife;
vita::environment env;
};
BOOST_FIXTURE_TEST_SUITE(Population,F)
BOOST_AUTO_TEST_CASE(RandomCreation)
{
for (unsigned n(4); n <= 100; ++n)
for (unsigned l(1); l <= 100; l+=(l < 10 ? 1 : 30))
{
env.individuals = n;
env.code_length = l;
std::auto_ptr<vita::evaluator> eva(new vita::random_evaluator());
vita::population p(env);
vita::evolution evo(p,eva.get());
/*
if (unit_test::runtime_config::log_level() <= unit_test::log_messages)
{
vita::analyzer ay;
evo.pick_stats(&ay);
const boost::uint64_t nef(ay.functions(true));
const boost::uint64_t net(ay.terminals(true));
const boost::uint64_t ne(nef+net);
std::cout << std::string(40,'-') << std::endl;
for (vita::analyzer::const_iterator i(ay.begin());
i != ay.end();
++i)
std::cout << std::setfill(' ') << (i->first)->display() << ": "
<< std::setw(5) << i->second.counter[true]
<< " (" << std::setw(3) << 100*i->second.counter[true]/ne
<< "%)" << std::endl;
std::cout << "Average code length: " << ay.length_dist().mean
<< std::endl
<< "Code length standard deviation: "
<< std::sqrt(ay.length_dist().variance) << std::endl
<< "Max code length: " << ay.length_dist().max << std::endl
<< "Functions: " << nef << " (" << nef*100/ne << "%)"
<< std::endl
<< "Terminals: " << net << " (" << net*100/ne << "%)"
<< std::endl << std::string(40,'-') << std::endl;
}
*/
BOOST_REQUIRE(evo.check());
}
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2016 Ingo Wald
// //
// 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. //
// ======================================================================== //
// pbrt
#include "pbrt/Parser.h"
// stl
#include <iostream>
#include <vector>
using namespace plib::pbrt;
namespace plib {
namespace pbrt {
using std::cout;
using std::endl;
FileName basePath = "";
// the output file we're writing.
FILE *out = NULL;
FILE *bin = NULL;
size_t numUniqueTriangles = 0;
size_t numInstancedTriangles = 0;
size_t numUniqueObjects = 0;
size_t numInstances = 0;
std::map<Shape *,int> alreadyExported;
//! transform used when original instance was emitted
std::map<int,affine3f> transformOfFirstInstance;
std::map<int,int> numTrisOfInstance;
size_t nextTransformID = 0;
std::vector<int> rootObjects;
int nextNodeID = 0;
int writeTriangleMesh(Ref<Shape> shape, const affine3f &instanceXfm)
{
numUniqueObjects++;
int thisID = nextNodeID++;
const affine3f xfm = instanceXfm*shape->transform;
alreadyExported[shape.ptr] = thisID;
transformOfFirstInstance[thisID] = xfm;
fprintf(out,"<Mesh id=\"%i\">\n",thisID);
fprintf(out," <materiallist>0</materiallist>\n");
{ // parse "point P"
Ref<ParamT<float> > param_P = shape->findParam<float>("P");
if (param_P) {
size_t ofs = ftell(bin);
const size_t numPoints = param_P->paramVec.size() / 3;
for (int i=0;i<numPoints;i++) {
vec3f v(param_P->paramVec[3*i+0],
param_P->paramVec[3*i+1],
param_P->paramVec[3*i+2]);
v = xfmPoint(xfm,v);
fwrite(&v,sizeof(v),1,bin);
// fprintf(out,"v %f %f %f\n",v.x,v.y,v.z);
// numVerticesWritten++;
}
fprintf(out," <vertex num=\"%li\" ofs=\"%li\"/>\n",
numPoints,ofs);
}
}
{ // parse "int indices"
Ref<ParamT<int> > param_indices = shape->findParam<int>("indices");
if (param_indices) {
size_t ofs = ftell(bin);
const size_t numIndices = param_indices->paramVec.size() / 3;
numTrisOfInstance[thisID] = numIndices;
numUniqueTriangles+=numIndices;
for (int i=0;i<numIndices;i++) {
vec4i v(param_indices->paramVec[3*i+0],
param_indices->paramVec[3*i+1],
param_indices->paramVec[3*i+2],
0);
fwrite(&v,sizeof(v),1,bin);
}
fprintf(out," <prim num=\"%li\" ofs=\"%li\"/>\n",
numIndices,ofs);
}
}
fprintf(out,"</Mesh>\n");
return thisID;
}
void parsePLY(const std::string &fileName,
std::vector<vec3f> &v,
std::vector<vec3f> &n,
std::vector<vec3i> &idx);
int writePlyMesh(Ref<Shape> shape, const affine3f &instanceXfm)
{
std::vector<vec3f> p, n;
std::vector<vec3i> idx;
numUniqueObjects++;
Ref<ParamT<std::string> > param_fileName = shape->findParam<std::string>("filename");
FileName fn = FileName(basePath) + param_fileName->paramVec[0];
parsePLY(fn.str(),p,n,idx);
int thisID = nextNodeID++;
const affine3f xfm = instanceXfm*shape->transform;
alreadyExported[shape.ptr] = thisID;
transformOfFirstInstance[thisID] = xfm;
// -------------------------------------------------------
fprintf(out,"<Mesh id=\"%i\">\n",thisID);
fprintf(out," <materiallist>0</materiallist>\n");
// -------------------------------------------------------
fprintf(out," <vertex num=\"%li\" ofs=\"%li\"/>\n",
p.size(),ftell(bin));
for (int i=0;i<p.size();i++) {
vec3f v = xfmPoint(xfm,p[i]);
fwrite(&v,sizeof(v),1,bin);
}
// -------------------------------------------------------
fprintf(out," <prim num=\"%li\" ofs=\"%li\"/>\n",
idx.size(),ftell(bin));
for (int i=0;i<idx.size();i++) {
vec3i v = idx[i];
fwrite(&v,sizeof(v),1,bin);
int z = 0.f;
fwrite(&z,sizeof(z),1,bin);
}
numTrisOfInstance[thisID] = idx.size();
numUniqueTriangles += idx.size();
// -------------------------------------------------------
fprintf(out,"</Mesh>\n");
// -------------------------------------------------------
return thisID;
}
void writeObject(const Ref<Object> &object,
const affine3f &instanceXfm)
{
cout << "writing " << object->toString() << endl;
// std::vector<int> child;
for (int shapeID=0;shapeID<object->shapes.size();shapeID++) {
Ref<Shape> shape = object->shapes[shapeID];
numInstances++;
if (alreadyExported.find(shape.ptr) != alreadyExported.end()) {
int childID = alreadyExported[shape.ptr];
affine3f xfm = instanceXfm * //shape->transform *
rcp(transformOfFirstInstance[childID]);
numInstancedTriangles += numTrisOfInstance[childID];
int thisID = nextNodeID++;
fprintf(out,"<Transform id=\"%i\" child=\"%i\">\n",
thisID,
childID);
fprintf(out," %f %f %f\n",
xfm.l.vx.x,
xfm.l.vx.y,
xfm.l.vx.z);
fprintf(out," %f %f %f\n",
xfm.l.vy.x,
xfm.l.vy.y,
xfm.l.vy.z);
fprintf(out," %f %f %f\n",
xfm.l.vz.x,
xfm.l.vz.y,
xfm.l.vz.z);
fprintf(out," %f %f %f\n",
xfm.p.x,
xfm.p.y,
xfm.p.z);
fprintf(out,"</Transform>\n");
rootObjects.push_back(thisID);
continue;
}
if (shape->type == "trianglemesh") {
int thisID = writeTriangleMesh(shape,instanceXfm);
rootObjects.push_back(thisID);
continue;
}
if (shape->type == "plymesh") {
int thisID = writePlyMesh(shape,instanceXfm);
rootObjects.push_back(thisID);
continue;
}
cout << "**** invalid shape #" << shapeID << " : " << shape->type << endl;
}
for (int instID=0;instID<object->objectInstances.size();instID++) {
writeObject(object->objectInstances[instID]->object,
instanceXfm*object->objectInstances[instID]->xfm);
}
}
void pbrt2obj(int ac, char **av)
{
std::vector<std::string> fileName;
bool dbg = false;
std::string outFileName = "a.xml";
for (int i=1;i<ac;i++) {
const std::string arg = av[i];
if (arg[0] == '-') {
if (arg == "-dbg" || arg == "--dbg")
dbg = true;
else if (arg == "--path" || arg == "-path")
basePath = av[++i];
else if (arg == "-o")
outFileName = av[++i];
else
THROW_RUNTIME_ERROR("invalid argument '"+arg+"'");
} else {
fileName.push_back(arg);
}
}
out = fopen(outFileName.c_str(),"w");
bin = fopen((outFileName+".bin").c_str(),"w");
assert(out);
assert(bin);
fprintf(out,"<?xml version=\"1.0\"?>\n");
fprintf(out,"<BGFscene>\n");
int thisID = nextNodeID++;
fprintf(out,"<Material name=\"default\" type=\"OBJMaterial\" id=\"%i\">\n",thisID);
fprintf(out," <param name=\"kd\" type=\"float3\">0.7 0.7 0.7</param>\n");
fprintf(out,"</Material>\n");
std::cout << "-------------------------------------------------------" << std::endl;
std::cout << "parsing:";
for (int i=0;i<fileName.size();i++)
std::cout << " " << fileName[i];
std::cout << std::endl;
if (basePath.str() == "")
basePath = FileName(fileName[0]).path();
plib::pbrt::Parser *parser = new plib::pbrt::Parser(dbg,basePath);
try {
for (int i=0;i<fileName.size();i++)
parser->parse(fileName[i]);
std::cout << "==> parsing successful (grammar only for now)" << std::endl;
embree::Ref<Scene> scene = parser->getScene();
writeObject(scene->world.ptr,embree::one);
{
int thisID = nextNodeID++;
fprintf(out,"<Group id=\"%i\" numChildren=\"%i\">\n",thisID,rootObjects.size());
for (int i=0;i<rootObjects.size();i++)
fprintf(out,"%i ",rootObjects[i]);
fprintf(out,"\n</Group>\n");
}
fprintf(out,"</BGFscene>");
fclose(out);
fclose(bin);
cout << "Done exporting to OSP file" << endl;
cout << " - unique triangles written " << numUniqueTriangles << endl;
cout << " - instanced tris written " << numInstancedTriangles << endl;
cout << " - unique objects/shapes " << numUniqueObjects << endl;
cout << " - num instances (inc.1sts) " << numInstances << endl;
} catch (std::runtime_error e) {
std::cout << "**** ERROR IN PARSING ****" << std::endl << e.what() << std::endl;
exit(1);
}
}
}
}
int main(int ac, char **av)
{
plib::pbrt::pbrt2obj(ac,av);
return 0;
}
<commit_msg>pretty-numbers<commit_after>// ======================================================================== //
// Copyright 2016 Ingo Wald
// //
// 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. //
// ======================================================================== //
// pbrt
#include "pbrt/Parser.h"
// stl
#include <iostream>
#include <vector>
using namespace plib::pbrt;
namespace plib {
namespace pbrt {
using std::cout;
using std::endl;
FileName basePath = "";
// the output file we're writing.
FILE *out = NULL;
FILE *bin = NULL;
size_t numUniqueTriangles = 0;
size_t numInstancedTriangles = 0;
size_t numUniqueObjects = 0;
size_t numInstances = 0;
std::map<Shape *,int> alreadyExported;
//! transform used when original instance was emitted
std::map<int,affine3f> transformOfFirstInstance;
std::map<int,int> numTrisOfInstance;
size_t nextTransformID = 0;
std::vector<int> rootObjects;
inline std::string prettyNumber(const size_t s) {
double val = s;
char result[100];
if (val >= 1e12f) {
sprintf(result,"%.1fT",val/1e12f);
} else if (val >= 1e9f) {
sprintf(result,"%.1fG",val/1e9f);
} else if (val >= 1e6f) {
sprintf(result,"%.1fM",val/1e6f);
} else if (val >= 1e3f) {
sprintf(result,"%.1fK",val/1e3f);
} else {
sprintf(result,"%lu",s);
}
return result;
}
int nextNodeID = 0;
int writeTriangleMesh(Ref<Shape> shape, const affine3f &instanceXfm)
{
numUniqueObjects++;
int thisID = nextNodeID++;
const affine3f xfm = instanceXfm*shape->transform;
alreadyExported[shape.ptr] = thisID;
transformOfFirstInstance[thisID] = xfm;
fprintf(out,"<Mesh id=\"%i\">\n",thisID);
fprintf(out," <materiallist>0</materiallist>\n");
{ // parse "point P"
Ref<ParamT<float> > param_P = shape->findParam<float>("P");
if (param_P) {
size_t ofs = ftell(bin);
const size_t numPoints = param_P->paramVec.size() / 3;
for (int i=0;i<numPoints;i++) {
vec3f v(param_P->paramVec[3*i+0],
param_P->paramVec[3*i+1],
param_P->paramVec[3*i+2]);
v = xfmPoint(xfm,v);
fwrite(&v,sizeof(v),1,bin);
// fprintf(out,"v %f %f %f\n",v.x,v.y,v.z);
// numVerticesWritten++;
}
fprintf(out," <vertex num=\"%li\" ofs=\"%li\"/>\n",
numPoints,ofs);
}
}
{ // parse "int indices"
Ref<ParamT<int> > param_indices = shape->findParam<int>("indices");
if (param_indices) {
size_t ofs = ftell(bin);
const size_t numIndices = param_indices->paramVec.size() / 3;
numTrisOfInstance[thisID] = numIndices;
numUniqueTriangles+=numIndices;
for (int i=0;i<numIndices;i++) {
vec4i v(param_indices->paramVec[3*i+0],
param_indices->paramVec[3*i+1],
param_indices->paramVec[3*i+2],
0);
fwrite(&v,sizeof(v),1,bin);
}
fprintf(out," <prim num=\"%li\" ofs=\"%li\"/>\n",
numIndices,ofs);
}
}
fprintf(out,"</Mesh>\n");
return thisID;
}
void parsePLY(const std::string &fileName,
std::vector<vec3f> &v,
std::vector<vec3f> &n,
std::vector<vec3i> &idx);
int writePlyMesh(Ref<Shape> shape, const affine3f &instanceXfm)
{
std::vector<vec3f> p, n;
std::vector<vec3i> idx;
numUniqueObjects++;
Ref<ParamT<std::string> > param_fileName = shape->findParam<std::string>("filename");
FileName fn = FileName(basePath) + param_fileName->paramVec[0];
parsePLY(fn.str(),p,n,idx);
int thisID = nextNodeID++;
const affine3f xfm = instanceXfm*shape->transform;
alreadyExported[shape.ptr] = thisID;
transformOfFirstInstance[thisID] = xfm;
// -------------------------------------------------------
fprintf(out,"<Mesh id=\"%i\">\n",thisID);
fprintf(out," <materiallist>0</materiallist>\n");
// -------------------------------------------------------
fprintf(out," <vertex num=\"%li\" ofs=\"%li\"/>\n",
p.size(),ftell(bin));
for (int i=0;i<p.size();i++) {
vec3f v = xfmPoint(xfm,p[i]);
fwrite(&v,sizeof(v),1,bin);
}
// -------------------------------------------------------
fprintf(out," <prim num=\"%li\" ofs=\"%li\"/>\n",
idx.size(),ftell(bin));
for (int i=0;i<idx.size();i++) {
vec3i v = idx[i];
fwrite(&v,sizeof(v),1,bin);
int z = 0.f;
fwrite(&z,sizeof(z),1,bin);
}
numTrisOfInstance[thisID] = idx.size();
numUniqueTriangles += idx.size();
// -------------------------------------------------------
fprintf(out,"</Mesh>\n");
// -------------------------------------------------------
return thisID;
}
void writeObject(const Ref<Object> &object,
const affine3f &instanceXfm)
{
cout << "writing " << object->toString() << endl;
// std::vector<int> child;
for (int shapeID=0;shapeID<object->shapes.size();shapeID++) {
Ref<Shape> shape = object->shapes[shapeID];
numInstances++;
if (alreadyExported.find(shape.ptr) != alreadyExported.end()) {
int childID = alreadyExported[shape.ptr];
affine3f xfm = instanceXfm * //shape->transform *
rcp(transformOfFirstInstance[childID]);
numInstancedTriangles += numTrisOfInstance[childID];
int thisID = nextNodeID++;
fprintf(out,"<Transform id=\"%i\" child=\"%i\">\n",
thisID,
childID);
fprintf(out," %f %f %f\n",
xfm.l.vx.x,
xfm.l.vx.y,
xfm.l.vx.z);
fprintf(out," %f %f %f\n",
xfm.l.vy.x,
xfm.l.vy.y,
xfm.l.vy.z);
fprintf(out," %f %f %f\n",
xfm.l.vz.x,
xfm.l.vz.y,
xfm.l.vz.z);
fprintf(out," %f %f %f\n",
xfm.p.x,
xfm.p.y,
xfm.p.z);
fprintf(out,"</Transform>\n");
rootObjects.push_back(thisID);
continue;
}
if (shape->type == "trianglemesh") {
int thisID = writeTriangleMesh(shape,instanceXfm);
rootObjects.push_back(thisID);
continue;
}
if (shape->type == "plymesh") {
int thisID = writePlyMesh(shape,instanceXfm);
rootObjects.push_back(thisID);
continue;
}
cout << "**** invalid shape #" << shapeID << " : " << shape->type << endl;
}
for (int instID=0;instID<object->objectInstances.size();instID++) {
writeObject(object->objectInstances[instID]->object,
instanceXfm*object->objectInstances[instID]->xfm);
}
}
void pbrt2obj(int ac, char **av)
{
std::vector<std::string> fileName;
bool dbg = false;
std::string outFileName = "a.xml";
for (int i=1;i<ac;i++) {
const std::string arg = av[i];
if (arg[0] == '-') {
if (arg == "-dbg" || arg == "--dbg")
dbg = true;
else if (arg == "--path" || arg == "-path")
basePath = av[++i];
else if (arg == "-o")
outFileName = av[++i];
else
THROW_RUNTIME_ERROR("invalid argument '"+arg+"'");
} else {
fileName.push_back(arg);
}
}
out = fopen(outFileName.c_str(),"w");
bin = fopen((outFileName+".bin").c_str(),"w");
assert(out);
assert(bin);
fprintf(out,"<?xml version=\"1.0\"?>\n");
fprintf(out,"<BGFscene>\n");
int thisID = nextNodeID++;
fprintf(out,"<Material name=\"default\" type=\"OBJMaterial\" id=\"%i\">\n",thisID);
fprintf(out," <param name=\"kd\" type=\"float3\">0.7 0.7 0.7</param>\n");
fprintf(out,"</Material>\n");
std::cout << "-------------------------------------------------------" << std::endl;
std::cout << "parsing:";
for (int i=0;i<fileName.size();i++)
std::cout << " " << fileName[i];
std::cout << std::endl;
if (basePath.str() == "")
basePath = FileName(fileName[0]).path();
plib::pbrt::Parser *parser = new plib::pbrt::Parser(dbg,basePath);
try {
for (int i=0;i<fileName.size();i++)
parser->parse(fileName[i]);
std::cout << "==> parsing successful (grammar only for now)" << std::endl;
embree::Ref<Scene> scene = parser->getScene();
writeObject(scene->world.ptr,embree::one);
{
int thisID = nextNodeID++;
fprintf(out,"<Group id=\"%i\" numChildren=\"%i\">\n",thisID,rootObjects.size());
for (int i=0;i<rootObjects.size();i++)
fprintf(out,"%i ",rootObjects[i]);
fprintf(out,"\n</Group>\n");
}
fprintf(out,"</BGFscene>");
fclose(out);
fclose(bin);
cout << "Done exporting to OSP file" << endl;
cout << " - unique objects/shapes " << prettyNumber(numUniqueObjects) << endl;
cout << " - num instances (inc.1sts) " << prettyNumber(numInstances) << endl;
cout << " - unique triangles written " << prettyNumber(numUniqueTriangles) << endl;
cout << " - instanced tris written " << prettyNumber(numUniqueTriangles+numInstancedTriangles) << endl;
} catch (std::runtime_error e) {
std::cout << "**** ERROR IN PARSING ****" << std::endl << e.what() << std::endl;
exit(1);
}
}
}
}
int main(int ac, char **av)
{
plib::pbrt::pbrt2obj(ac,av);
return 0;
}
<|endoftext|> |
<commit_before>// $Id: Box_test.C,v 1.1 2000/02/23 02:45:36 amoll Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
# include <BALL/MATHS/box3.h>
# include <BALL/MATHS/vector3.h>
///////////////////////////
START_TEST(class_name, "$Id: Box_test.C,v 1.1 2000/02/23 02:45:36 amoll Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
//line 33: method TBox3::BALL_CREATE(TBox3<T>)
CHECK(TBox3::BALL_CREATE(TBox3<T>))
//BAUSTELLE
RESULT
//line 39
CHECK(TBox3::TBox3())
Box3* box;
box = new Box3();
TEST_NOT_EQUAL(box, 0)
RESULT
Box3 box, box2;
Vector3 v1, v2, v3, v4;
float a = 1, b = 2, c = 3,
d = 6, e = 5, f = 4;
float a1, b1, c1, d1, e1, f1;
v1 = Vector3(1, 2, 3);
v2 = Vector3(6, 5, 4);
//line 246: method TBox3::TBox3(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz)
//also test for TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const
CHECK(TBox3::TBox3(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz))
box = Box3(a, b, c, d, e, f);
float a1, b1, c1, d1, e1, f1;
box.get(a1, b1, c1, d1, e1, f1);
TEST_REAL_EQUAL(a, a1)
TEST_REAL_EQUAL(b, b1)
TEST_REAL_EQUAL(c, c1)
TEST_REAL_EQUAL(d, d1)
TEST_REAL_EQUAL(e, e1)
TEST_REAL_EQUAL(f, f1)
RESULT
//line 230: method TBox3::TBox3(const TBox3<T>& box, bool /* deep */)
CHECK(TBox3::TBox3(const TBox3<T>& box, bool /* deep */))
box = Box3(v1, v2);
box2 = Box3(box);
float a1, b1, c1, d1, e1, f1;
box2.get(a1, b1, c1, d1, e1, f1);
TEST_REAL_EQUAL(a, a1)
TEST_REAL_EQUAL(b, b1)
TEST_REAL_EQUAL(c, c1)
TEST_REAL_EQUAL(d, d1)
TEST_REAL_EQUAL(e, e1)
TEST_REAL_EQUAL(f, f1)
RESULT
//line 237: method TBox3::TBox3(const TVector3<T>& a, const TVector3<T>& b)
CHECK(TBox3::TBox3(const TVector3<T>& a, const TVector3<T>& b))
box = Box3(v1, v2);
box.get(a1, b1, c1, d1, e1, f1);
TEST_REAL_EQUAL(a, a1)
TEST_REAL_EQUAL(b, b1)
TEST_REAL_EQUAL(c, c1)
TEST_REAL_EQUAL(d, d1)
TEST_REAL_EQUAL(e, e1)
TEST_REAL_EQUAL(f, f1)
RESULT
//line 147: method TBox3::getSurface() const
CHECK(TBox3::getSurface() const )
box = Box3(v1, v2);
TEST_REAL_EQUAL(box.getSurface(), 23)
RESULT
//line 152: method TBox3::getVolume() const
CHECK(TBox3::getVolume() const )
box = Box3(v1, v2);
TEST_REAL_EQUAL(box.getVolume(), 225)
RESULT
//line 157: method TBox3::getWidth() const
CHECK(TBox3::getWidth() const )
box = Box3(v1, v2);
TEST_REAL_EQUAL(box.getWidth(), 5)
RESULT
//line 162: method TBox3::getHeight() const
CHECK(TBox3::getHeight() const )
box = Box3(v1, v2);
TEST_REAL_EQUAL(box.getHeight(), 3)
RESULT
//line 167: method TBox3::getDepth() const
CHECK(TBox3::getDepth() const )
box = Box3(v1, v2);
TEST_REAL_EQUAL(box.getDepth(), 1)
RESULT
//line 174: method TBox3::join(const TBox3& box)
CHECK(TBox3::join(const TBox3& box))
box = Box3(v1, v2);
v3 = Vector3(101, 102, 103);
v4 = Vector3(104, 105, 106);
box2 = Box3(v3, v4);
box.join(box2);
box.get(a1, b1, c1, d1, e1, f1);
TEST_REAL_EQUAL(1, a1)
TEST_REAL_EQUAL(2, b1)
TEST_REAL_EQUAL(3, c1)
TEST_REAL_EQUAL(104, d1)
TEST_REAL_EQUAL(105, e1)
TEST_REAL_EQUAL(106, f1)
RESULT
//line 184: method TBox3::bool operator == (const TBox3& box) const
CHECK(TBox3::bool operator == (const TBox3& box) const )
box = Box3(v1, v2);
box2 = Box3(v3, v4);
TEST_EQUAL(box == box2, false)
box2 = Box3(v1, v2);
TEST_EQUAL(box == box2, true)
RESULT
//line 189: method TBox3::bool operator != (const TBox3& box) const
CHECK(TBox3::bool operator != (const TBox3& box) const )
box = Box3(v1, v2);
box2 = Box3(v3, v4);
TEST_EQUAL(box != box2, true)
box2 = Box3(v1, v2);
TEST_EQUAL(box != box2, false)
RESULT
//line 200: method TBox3::isValid() const
CHECK(TBox3::isValid() const )
box = Box3(v1, v2);
TEST_EQUAL(box.isValid(), true)
RESULT
//line 203: method TBox3::dump(std::ostream& s = std::cout, Size depth = 0) const
CHECK(TBox3::dump(std::ostream& s = std::cout, Size depth = 0) const )
//BAUSTELLE
RESULT
//line 254: method TBox3::set(const TBox3<T>& box, bool /* deep */)
CHECK(TBox3::set(const TBox3<T>& box, bool /* deep */))
box = Box3(v1, v2);
box2.set(box);
TEST_EQUAL(box == box2, true)
RESULT
//line 272: method TBox3::set(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz)
CHECK(TBox3::set(const T& ax, const T& ay, const T& az, const T& bx, const T& by, const T& bz))
box = Box3(v1, v2);
box2.set(1, 2, 3, 4, 5, 6);
TEST_EQUAL(box == box2, true)
RESULT
//line 289: method TBox3::get(TBox3<T>& box, bool deep) const
CHECK(TBox3::get(TBox3<T>& box, bool deep) const )
box = Box3(v1, v2);
box.get(box2);
TEST_EQUAL(box == box2, true)
RESULT
//line 304: method TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const
CHECK(TBox3::get(T& ax, T& ay, T& az, T& bx, T& by, T& bz) const )
box = Box3(v1, v2);
box.get(a1, b1, c1, d1, e1, f1);
box2.set(a1, b1, c1, d1, e1, f1);
TEST_EQUAL(box == box2, true)
RESULT
//line 424: method TBox3<T>::dump(std::ostream& s, Size depth) const
CHECK(TBox3<T>::dump(std::ostream& s, Size depth) const)
//BAUSTELLE
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>removed<commit_after><|endoftext|> |
<commit_before>#include <TypeTraits/TypeTraits.hpp>
#include <iostream>
int main()
{
std::cout <<
std::boolalpha <<
dl::ContainsType<int>(std::tuple<double, char, int, unsigned>{})
<< std::endl;
std::cout <<
std::boolalpha <<
dl::ContainsType<uint8_t>(std::tuple<double, char, int, unsigned>{})
<< std::endl;
}
<commit_msg>added static assert<commit_after>#include <TypeTraits/TypeTraits.hpp>
#include <iostream>
int main()
{
static_assert(
dl::ContainsType<int>(std::tuple<double, char, int, unsigned>{}),
"ContainsType didnt work");
std::cout <<
std::boolalpha <<
dl::ContainsType<int>(std::tuple<double, char, int, unsigned>{})
<< std::endl;
std::cout <<
std::boolalpha <<
dl::ContainsType<uint8_t>(std::tuple<double, char, int, unsigned>{})
<< std::endl;
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <ros/forwards.h>
#include <ros/single_subscriber_publisher.h>
#include <sensor_msgs/Image.h>
#include <image_transport/image_transport.h>
#include <visualization_msgs/Marker.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cv_bridge/cv_bridge.h>
#include <src/TagDetector.h>
#include <src/TagDetection.h>
#include <src/TagFamily.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <visualization_msgs/MarkerArray.h>
#include "yaml-cpp/yaml.h"
#include <sstream>
#include <fstream>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/make_shared.hpp>
#include "apriltags.h"
using namespace std;
// Functions
double GetTagSize(int tag_id)
{
boost::unordered_map<size_t, double>::iterator tag_sizes_it =
tag_sizes_.find(tag_id);
if(tag_sizes_it != tag_sizes_.end()) {
return tag_sizes_it->second;
} else {
return default_tag_size_;
}
}
Eigen::Matrix4d GetDetectionTransform(TagDetection detection)
{
double tag_size = GetTagSize(detection.id);
std::vector<cv::Point3f> object_pts;
std::vector<cv::Point2f> image_pts;
double tag_radius = tag_size/2.;
object_pts.push_back(cv::Point3f(-tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, tag_radius, 0));
object_pts.push_back(cv::Point3f(-tag_radius, tag_radius, 0));
image_pts.push_back(detection.p[0]);
image_pts.push_back(detection.p[1]);
image_pts.push_back(detection.p[2]);
image_pts.push_back(detection.p[3]);
cv::Matx33f intrinsics(camera_info_.K[0], 0, camera_info_.K[2],
0, camera_info_.K[4], camera_info_.K[5],
0, 0, 1);
cv::Mat rvec, tvec;
cv::Vec4f dist_param(0,0,0,0);
cv::solvePnP(object_pts, image_pts, intrinsics, dist_param,
rvec, tvec);
cv::Matx33d r;
cv::Rodrigues(rvec, r);
Eigen::Matrix3d rot;
rot << r(0,0), r(0,1), r(0,2),
r(1,0), r(1,1), r(1,2),
r(2,0), r(2,1), r(2,2);
Eigen::Matrix4d T;
T.topLeftCorner(3,3) = rot;
T.col(3).head(3) <<
tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);
T.row(3) << 0,0,0,1;
return T;
}
// Callback for camera info
void InfoCallback(const sensor_msgs::CameraInfoConstPtr& camera_info)
{
camera_info_ = (*camera_info);
has_camera_info_ = true;
}
// Callback for image data
void ImageCallback(const sensor_msgs::ImageConstPtr& msg )
{
if(!has_camera_info_){
ROS_WARN("No Camera Info Received Yet");
return;
}
// Get the image
cv_bridge::CvImagePtr subscribed_ptr;
try
{
subscribed_ptr = cv_bridge::toCvCopy(msg, "mono8");
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv::Mat subscribed_gray = subscribed_ptr->image;
cv::Mat tmp;
cv::Point2d opticalCenter(0.5*subscribed_gray.rows,
0.5*subscribed_gray.cols);
TagDetectionArray detections;
detector_->process(subscribed_gray, opticalCenter, detections);
visualization_msgs::MarkerArray marker_transforms;
if(viewer_)
{
subscribed_gray = family_->superimposeDetections(subscribed_gray,
detections);
}
for(unsigned int i = 0; i < detections.size(); ++i)
{
Eigen::Matrix4d pose = GetDetectionTransform(detections[i]);
// Get this info from earlier code, don't extract it again
Eigen::Matrix3d R = pose.block<3,3>(0,0);
Eigen::Quaternion<double> q(R);
visualization_msgs::Marker marker_transform;
marker_transform.header.frame_id = frame_;
marker_transform.header.stamp = ros::Time::now();
stringstream convert;
convert << "tag" << detections[i].id;
marker_transform.ns = convert.str().c_str();
marker_transform.id = detections[i].id;
marker_transform.type = visualization_msgs::Marker::ARROW;
//marker_transform.type = visualization_msgs::Marker::CUBE;
marker_transform.action = visualization_msgs::Marker::ADD;
marker_transform.pose.position.x = pose(0,3);
marker_transform.pose.position.y = pose(1,3);
marker_transform.pose.position.z = pose(2,3);
marker_transform.pose.orientation.x = q.x();
marker_transform.pose.orientation.y = q.y();
marker_transform.pose.orientation.z = q.z();
marker_transform.pose.orientation.w = q.w();
double tag_size = GetTagSize(detections[i].id);
marker_transform.scale.x = tag_size;
marker_transform.scale.y = tag_size;
marker_transform.scale.z = 0.01 * tag_size;
marker_transform.color.r = 1.0;
marker_transform.color.g = 0.0;
marker_transform.color.b = 1.0;
marker_transform.color.a = 1.0;
marker_transforms.markers.push_back(marker_transform);
}
marker_publisher_.publish(marker_transforms);
if(viewer_)
{
cv::imshow("AprilTags", subscribed_gray);
}
}
void ConnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Subscription detected! (%d subscribers)", subscribers);
if(subscribers && !running_)
{
ROS_DEBUG("New Subscribers, Connecting to Input Image Topic.");
ros::TransportHints ros_transport_hints(ros::TransportHints().tcpNoDelay());
image_transport::TransportHints image_transport_hint(image_transport::TransportHints(
"raw", ros_transport_hints, (*node_),
"image_transport"));
image_subscriber = (*image_).subscribe(
DEFAULT_IMAGE_TOPIC, 1, &ImageCallback,
image_transport_hint);
info_subscriber = (*node_).subscribe(
DEFAULT_CAMERA_INFO_TOPIC, 10, &InfoCallback);
running_ = true;
}
}
void DisconnectHandler()
{
}
void DisconnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Unsubscription detected! (%d subscribers)", subscribers);
if(!subscribers && running_)
{
ROS_DEBUG("No Subscribers, Disconnecting from Input Image Topic.");
image_subscriber.shutdown();
info_subscriber.shutdown();
running_ = false;
}
}
void GetParameterValues()
{
// Load node-wide configuration values.
node_->param("viewer", viewer_, 0);
node_->param("tag_family", tag_family_name_, DEFAULT_TAG_FAMILY);
node_->param("default_tag_size", default_tag_size_, DEFAULT_TAG_SIZE);
node_->param("tf_frame", frame_, DEFAULT_TF_FRAME);
// Load tag specific configuration values.
XmlRpc::XmlRpcValue tag_data;
node_->param("tag_data", tag_data, tag_data);
// Iterate through each tag in the configuration.
XmlRpc::XmlRpcValue::ValueStruct::iterator it;
for (it = tag_data.begin(); it != tag_data.end(); ++it)
{
// Retrieve the settings for the next tag.
int tag_id = boost::lexical_cast<int>(it->first);
XmlRpc::XmlRpcValue tag_values = it->second;
// Load all the settings for this tag.
if (tag_values.hasMember("size"))
{
tag_sizes_[tag_id] = static_cast<double>(tag_values["size"]);
ROS_DEBUG("Setting tag%d to size %f m.", tag_id, tag_sizes_[tag_id]);
}
}
}
void SetupPublisher()
{
ros::SubscriberStatusCallback connect_callback = &ConnectCallback;
ros::SubscriberStatusCallback disconnect_callback = &DisconnectCallback;
// Publisher
marker_publisher_ = node_->advertise<visualization_msgs::MarkerArray>(
DEFAULT_MARKER_TOPIC, 1, connect_callback,
disconnect_callback);
}
void InitializeTags()
{
tag_params.newQuadAlgorithm = 1;
family_ = new TagFamily(tag_family_name_);
detector_ = new TagDetector(*family_, tag_params);
}
void InitializeROSNode(int argc, char **argv)
{
ros::init(argc, argv, "apriltags");
node_ = boost::make_shared<ros::NodeHandle>("~");
image_ = boost::make_shared<image_transport::ImageTransport>(*node_);
}
int main(int argc, char **argv)
{
InitializeROSNode(argc,argv);
GetParameterValues();
SetupPublisher();
InitializeTags();
if(viewer_){
cvNamedWindow("AprilTags");
cvStartWindowThread();
}
ROS_INFO("AprilTags node started.");
running_ = false;
has_camera_info_ = false;
ros::spin();
ROS_INFO("AprilTags node stopped.");
//Destroying Stuff
cvDestroyWindow("AprilTags");
delete detector_;
delete family_;
return EXIT_SUCCESS;
}
<commit_msg>changing scale for a moment<commit_after>#include <ros/ros.h>
#include <ros/forwards.h>
#include <ros/single_subscriber_publisher.h>
#include <sensor_msgs/Image.h>
#include <image_transport/image_transport.h>
#include <visualization_msgs/Marker.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cv_bridge/cv_bridge.h>
#include <src/TagDetector.h>
#include <src/TagDetection.h>
#include <src/TagFamily.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <visualization_msgs/MarkerArray.h>
#include "yaml-cpp/yaml.h"
#include <sstream>
#include <fstream>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/make_shared.hpp>
#include "apriltags.h"
using namespace std;
// Functions
double GetTagSize(int tag_id)
{
boost::unordered_map<size_t, double>::iterator tag_sizes_it =
tag_sizes_.find(tag_id);
if(tag_sizes_it != tag_sizes_.end()) {
return tag_sizes_it->second;
} else {
return default_tag_size_;
}
}
Eigen::Matrix4d GetDetectionTransform(TagDetection detection)
{
double tag_size = GetTagSize(detection.id);
std::vector<cv::Point3f> object_pts;
std::vector<cv::Point2f> image_pts;
double tag_radius = tag_size/2.;
object_pts.push_back(cv::Point3f(-tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, tag_radius, 0));
object_pts.push_back(cv::Point3f(-tag_radius, tag_radius, 0));
image_pts.push_back(detection.p[0]);
image_pts.push_back(detection.p[1]);
image_pts.push_back(detection.p[2]);
image_pts.push_back(detection.p[3]);
cv::Matx33f intrinsics(camera_info_.K[0], 0, camera_info_.K[2],
0, camera_info_.K[4], camera_info_.K[5],
0, 0, 1);
cv::Mat rvec, tvec;
cv::Vec4f dist_param(0,0,0,0);
cv::solvePnP(object_pts, image_pts, intrinsics, dist_param,
rvec, tvec);
cv::Matx33d r;
cv::Rodrigues(rvec, r);
Eigen::Matrix3d rot;
rot << r(0,0), r(0,1), r(0,2),
r(1,0), r(1,1), r(1,2),
r(2,0), r(2,1), r(2,2);
Eigen::Matrix4d T;
T.topLeftCorner(3,3) = rot;
T.col(3).head(3) <<
tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);
T.row(3) << 0,0,0,1;
return T;
}
// Callback for camera info
void InfoCallback(const sensor_msgs::CameraInfoConstPtr& camera_info)
{
camera_info_ = (*camera_info);
has_camera_info_ = true;
}
// Callback for image data
void ImageCallback(const sensor_msgs::ImageConstPtr& msg )
{
if(!has_camera_info_){
ROS_WARN("No Camera Info Received Yet");
return;
}
// Get the image
cv_bridge::CvImagePtr subscribed_ptr;
try
{
subscribed_ptr = cv_bridge::toCvCopy(msg, "mono8");
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv::Mat subscribed_gray = subscribed_ptr->image;
cv::Mat tmp;
cv::Point2d opticalCenter(0.5*subscribed_gray.rows,
0.5*subscribed_gray.cols);
TagDetectionArray detections;
detector_->process(subscribed_gray, opticalCenter, detections);
visualization_msgs::MarkerArray marker_transforms;
if(viewer_)
{
subscribed_gray = family_->superimposeDetections(subscribed_gray,
detections);
}
for(unsigned int i = 0; i < detections.size(); ++i)
{
Eigen::Matrix4d pose = GetDetectionTransform(detections[i]);
// Get this info from earlier code, don't extract it again
Eigen::Matrix3d R = pose.block<3,3>(0,0);
Eigen::Quaternion<double> q(R);
visualization_msgs::Marker marker_transform;
marker_transform.header.frame_id = frame_;
marker_transform.header.stamp = ros::Time::now();
stringstream convert;
convert << "tag" << detections[i].id;
marker_transform.ns = convert.str().c_str();
marker_transform.id = detections[i].id;
marker_transform.type = visualization_msgs::Marker::ARROW;
//marker_transform.type = visualization_msgs::Marker::CUBE;
marker_transform.action = visualization_msgs::Marker::ADD;
marker_transform.pose.position.x = pose(0,3);
marker_transform.pose.position.y = pose(1,3);
marker_transform.pose.position.z = pose(2,3);
marker_transform.pose.orientation.x = q.x();
marker_transform.pose.orientation.y = q.y();
marker_transform.pose.orientation.z = q.z();
marker_transform.pose.orientation.w = q.w();
double tag_size = GetTagSize(detections[i].id);
/*
marker_transform.scale.x = tag_size;
marker_transform.scale.y = tag_size;
marker_transform.scale.z = 0.01 * tag_size;
*/
marker_transform.scale.x = 1.0;
marker_transform.scale.y = 1.0;
marker_transform.scale.z = 1.0;
marker_transform.color.r = 1.0;
marker_transform.color.g = 0.0;
marker_transform.color.b = 1.0;
marker_transform.color.a = 1.0;
marker_transforms.markers.push_back(marker_transform);
}
marker_publisher_.publish(marker_transforms);
if(viewer_)
{
cv::imshow("AprilTags", subscribed_gray);
}
}
void ConnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Subscription detected! (%d subscribers)", subscribers);
if(subscribers && !running_)
{
ROS_DEBUG("New Subscribers, Connecting to Input Image Topic.");
ros::TransportHints ros_transport_hints(ros::TransportHints().tcpNoDelay());
image_transport::TransportHints image_transport_hint(image_transport::TransportHints(
"raw", ros_transport_hints, (*node_),
"image_transport"));
image_subscriber = (*image_).subscribe(
DEFAULT_IMAGE_TOPIC, 1, &ImageCallback,
image_transport_hint);
info_subscriber = (*node_).subscribe(
DEFAULT_CAMERA_INFO_TOPIC, 10, &InfoCallback);
running_ = true;
}
}
void DisconnectHandler()
{
}
void DisconnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Unsubscription detected! (%d subscribers)", subscribers);
if(!subscribers && running_)
{
ROS_DEBUG("No Subscribers, Disconnecting from Input Image Topic.");
image_subscriber.shutdown();
info_subscriber.shutdown();
running_ = false;
}
}
void GetParameterValues()
{
// Load node-wide configuration values.
node_->param("viewer", viewer_, 0);
node_->param("tag_family", tag_family_name_, DEFAULT_TAG_FAMILY);
node_->param("default_tag_size", default_tag_size_, DEFAULT_TAG_SIZE);
node_->param("tf_frame", frame_, DEFAULT_TF_FRAME);
// Load tag specific configuration values.
XmlRpc::XmlRpcValue tag_data;
node_->param("tag_data", tag_data, tag_data);
// Iterate through each tag in the configuration.
XmlRpc::XmlRpcValue::ValueStruct::iterator it;
for (it = tag_data.begin(); it != tag_data.end(); ++it)
{
// Retrieve the settings for the next tag.
int tag_id = boost::lexical_cast<int>(it->first);
XmlRpc::XmlRpcValue tag_values = it->second;
// Load all the settings for this tag.
if (tag_values.hasMember("size"))
{
tag_sizes_[tag_id] = static_cast<double>(tag_values["size"]);
ROS_DEBUG("Setting tag%d to size %f m.", tag_id, tag_sizes_[tag_id]);
}
}
}
void SetupPublisher()
{
ros::SubscriberStatusCallback connect_callback = &ConnectCallback;
ros::SubscriberStatusCallback disconnect_callback = &DisconnectCallback;
// Publisher
marker_publisher_ = node_->advertise<visualization_msgs::MarkerArray>(
DEFAULT_MARKER_TOPIC, 1, connect_callback,
disconnect_callback);
}
void InitializeTags()
{
tag_params.newQuadAlgorithm = 1;
family_ = new TagFamily(tag_family_name_);
detector_ = new TagDetector(*family_, tag_params);
}
void InitializeROSNode(int argc, char **argv)
{
ros::init(argc, argv, "apriltags");
node_ = boost::make_shared<ros::NodeHandle>("~");
image_ = boost::make_shared<image_transport::ImageTransport>(*node_);
}
int main(int argc, char **argv)
{
InitializeROSNode(argc,argv);
GetParameterValues();
SetupPublisher();
InitializeTags();
if(viewer_){
cvNamedWindow("AprilTags");
cvStartWindowThread();
}
ROS_INFO("AprilTags node started.");
running_ = false;
has_camera_info_ = false;
ros::spin();
ROS_INFO("AprilTags node stopped.");
//Destroying Stuff
cvDestroyWindow("AprilTags");
delete detector_;
delete family_;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <ros/forwards.h>
#include <ros/single_subscriber_publisher.h>
#include <sensor_msgs/Image.h>
#include <image_transport/image_transport.h>
#include <visualization_msgs/Marker.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cv_bridge/cv_bridge.h>
#include <src/TagDetector.h>
#include <src/TagDetection.h>
#include <src/TagFamily.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <visualization_msgs/MarkerArray.h>
#include "yaml-cpp/yaml.h"
#include <sstream>
#include <fstream>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/make_shared.hpp>
#include "apriltags.h"
using namespace std;
// Functions
double GetTagSize(int tag_id)
{
boost::unordered_map<size_t, double>::iterator tag_sizes_it =
tag_sizes_.find(tag_id);
if(tag_sizes_it != tag_sizes_.end()) {
return tag_sizes_it->second;
} else {
return default_tag_size_;
}
}
Eigen::Matrix4d GetDetectionTransform(TagDetection detection)
{
double tag_size = GetTagSize(detection.id);
std::vector<cv::Point3f> object_pts;
std::vector<cv::Point2f> image_pts;
double tag_radius = tag_size/2.;
object_pts.push_back(cv::Point3f(-tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, tag_radius, 0));
object_pts.push_back(cv::Point3f(-tag_radius, tag_radius, 0));
image_pts.push_back(detection.p[0]);
image_pts.push_back(detection.p[1]);
image_pts.push_back(detection.p[2]);
image_pts.push_back(detection.p[3]);
cv::Matx33f intrinsics(camera_info_.K[0], 0, camera_info_.K[2],
0, camera_info_.K[4], camera_info_.K[5],
0, 0, 1);
cv::Mat rvec, tvec;
cv::Vec4f dist_param(0,0,0,0);
cv::solvePnP(object_pts, image_pts, intrinsics, dist_param,
rvec, tvec);
cv::Matx33d r;
cv::Rodrigues(rvec, r);
Eigen::Matrix3d rot;
rot << r(0,0), r(0,1), r(0,2),
r(1,0), r(1,1), r(1,2),
r(2,0), r(2,1), r(2,2);
Eigen::Matrix4d T;
T.topLeftCorner(3,3) = rot;
T.col(3).head(3) <<
tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);
T.row(3) << 0,0,0,1;
return T;
}
// Callback for camera info
void InfoCallback(const sensor_msgs::CameraInfoConstPtr& camera_info)
{
camera_info_ = (*camera_info);
has_camera_info_ = true;
}
// Callback for image data
void ImageCallback(const sensor_msgs::ImageConstPtr& msg )
{
if(!has_camera_info_){
ROS_WARN("No Camera Info Received Yet");
return;
}
// Get the image
cv_bridge::CvImagePtr subscribed_ptr;
try
{
subscribed_ptr = cv_bridge::toCvCopy(msg, "mono8");
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv::Mat subscribed_gray = subscribed_ptr->image;
cv::Mat tmp;
cv::Point2d opticalCenter(0.5*subscribed_gray.rows,
0.5*subscribed_gray.cols);
TagDetectionArray detections;
detector_->process(subscribed_gray, opticalCenter, detections);
visualization_msgs::MarkerArray marker_transforms;
if(viewer_)
{
subscribed_gray = family_->superimposeDetections(subscribed_gray,
detections);
}
for(unsigned int i = 0; i < detections.size(); ++i)
{
Eigen::Matrix4d pose = GetDetectionTransform(detections[i]);
// Get this info from earlier code, don't extract it again
Eigen::Matrix3d R = pose.block<3,3>(0,0);
Eigen::Quaternion<double> q(R);
visualization_msgs::Marker marker_transform;
marker_transform.header.frame_id = frame_;
marker_transform.header.stamp = ros::Time::now();
stringstream convert;
convert << "tag" << detections[i].id;
marker_transform.ns = convert.str().c_str();
marker_transform.id = detections[i].id;
marker_transform.type = visualization_msgs::Marker::ARROW;
//marker_transform.type = visualization_msgs::Marker::CUBE;
marker_transform.action = visualization_msgs::Marker::ADD;
marker_transform.pose.position.x = pose(0,3);
marker_transform.pose.position.y = pose(1,3);
marker_transform.pose.position.z = pose(2,3);
marker_transform.pose.orientation.x = q.x();
marker_transform.pose.orientation.y = q.y();
marker_transform.pose.orientation.z = q.z();
marker_transform.pose.orientation.w = q.w();
double tag_size = GetTagSize(detections[i].id);
/*
marker_transform.scale.x = tag_size;
marker_transform.scale.y = tag_size;
marker_transform.scale.z = 0.01 * tag_size;
*/
marker_transform.scale.x = tag_size;
marker_transform.scale.y = tag_size*10;
marker_transform.scale.z = tag_size*0.5;
marker_transform.color.r = 1.0;
marker_transform.color.g = 0.0;
marker_transform.color.b = 1.0;
marker_transform.color.a = 1.0;
marker_transforms.markers.push_back(marker_transform);
}
marker_publisher_.publish(marker_transforms);
if(viewer_)
{
cv::imshow("AprilTags", subscribed_gray);
}
}
void ConnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Subscription detected! (%d subscribers)", subscribers);
if(subscribers && !running_)
{
ROS_DEBUG("New Subscribers, Connecting to Input Image Topic.");
ros::TransportHints ros_transport_hints(ros::TransportHints().tcpNoDelay());
image_transport::TransportHints image_transport_hint(image_transport::TransportHints(
"raw", ros_transport_hints, (*node_),
"image_transport"));
image_subscriber = (*image_).subscribe(
DEFAULT_IMAGE_TOPIC, 1, &ImageCallback,
image_transport_hint);
info_subscriber = (*node_).subscribe(
DEFAULT_CAMERA_INFO_TOPIC, 10, &InfoCallback);
running_ = true;
}
}
void DisconnectHandler()
{
}
void DisconnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Unsubscription detected! (%d subscribers)", subscribers);
if(!subscribers && running_)
{
ROS_DEBUG("No Subscribers, Disconnecting from Input Image Topic.");
image_subscriber.shutdown();
info_subscriber.shutdown();
running_ = false;
}
}
void GetParameterValues()
{
// Load node-wide configuration values.
node_->param("viewer", viewer_, 0);
node_->param("tag_family", tag_family_name_, DEFAULT_TAG_FAMILY);
node_->param("default_tag_size", default_tag_size_, DEFAULT_TAG_SIZE);
node_->param("tf_frame", frame_, DEFAULT_TF_FRAME);
// Load tag specific configuration values.
XmlRpc::XmlRpcValue tag_data;
node_->param("tag_data", tag_data, tag_data);
// Iterate through each tag in the configuration.
XmlRpc::XmlRpcValue::ValueStruct::iterator it;
for (it = tag_data.begin(); it != tag_data.end(); ++it)
{
// Retrieve the settings for the next tag.
int tag_id = boost::lexical_cast<int>(it->first);
XmlRpc::XmlRpcValue tag_values = it->second;
// Load all the settings for this tag.
if (tag_values.hasMember("size"))
{
tag_sizes_[tag_id] = static_cast<double>(tag_values["size"]);
ROS_DEBUG("Setting tag%d to size %f m.", tag_id, tag_sizes_[tag_id]);
}
}
}
void SetupPublisher()
{
ros::SubscriberStatusCallback connect_callback = &ConnectCallback;
ros::SubscriberStatusCallback disconnect_callback = &DisconnectCallback;
// Publisher
marker_publisher_ = node_->advertise<visualization_msgs::MarkerArray>(
DEFAULT_MARKER_TOPIC, 1, connect_callback,
disconnect_callback);
}
void InitializeTags()
{
tag_params.newQuadAlgorithm = 1;
family_ = new TagFamily(tag_family_name_);
detector_ = new TagDetector(*family_, tag_params);
}
void InitializeROSNode(int argc, char **argv)
{
ros::init(argc, argv, "apriltags");
node_ = boost::make_shared<ros::NodeHandle>("~");
image_ = boost::make_shared<image_transport::ImageTransport>(*node_);
}
int main(int argc, char **argv)
{
InitializeROSNode(argc,argv);
GetParameterValues();
SetupPublisher();
InitializeTags();
if(viewer_){
cvNamedWindow("AprilTags");
cvStartWindowThread();
}
ROS_INFO("AprilTags node started.");
running_ = false;
has_camera_info_ = false;
ros::spin();
ROS_INFO("AprilTags node stopped.");
//Destroying Stuff
cvDestroyWindow("AprilTags");
delete detector_;
delete family_;
return EXIT_SUCCESS;
}
<commit_msg>testing sizes<commit_after>#include <ros/ros.h>
#include <ros/forwards.h>
#include <ros/single_subscriber_publisher.h>
#include <sensor_msgs/Image.h>
#include <image_transport/image_transport.h>
#include <visualization_msgs/Marker.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cv_bridge/cv_bridge.h>
#include <src/TagDetector.h>
#include <src/TagDetection.h>
#include <src/TagFamily.h>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <visualization_msgs/MarkerArray.h>
#include "yaml-cpp/yaml.h"
#include <sstream>
#include <fstream>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include <boost/make_shared.hpp>
#include "apriltags.h"
using namespace std;
// Functions
double GetTagSize(int tag_id)
{
boost::unordered_map<size_t, double>::iterator tag_sizes_it =
tag_sizes_.find(tag_id);
if(tag_sizes_it != tag_sizes_.end()) {
return tag_sizes_it->second;
} else {
return default_tag_size_;
}
}
Eigen::Matrix4d GetDetectionTransform(TagDetection detection)
{
double tag_size = GetTagSize(detection.id);
std::vector<cv::Point3f> object_pts;
std::vector<cv::Point2f> image_pts;
double tag_radius = tag_size/2.;
object_pts.push_back(cv::Point3f(-tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, -tag_radius, 0));
object_pts.push_back(cv::Point3f( tag_radius, tag_radius, 0));
object_pts.push_back(cv::Point3f(-tag_radius, tag_radius, 0));
image_pts.push_back(detection.p[0]);
cout << detection.p[0] << endl;
image_pts.push_back(detection.p[1]);
cout << detection.p[1] << endl;
image_pts.push_back(detection.p[2]);
cout << detection.p[2] << endl;
image_pts.push_back(detection.p[3]);
cout << detection.p[3] << endl;
cv::Matx33f intrinsics(camera_info_.K[0], 0, camera_info_.K[2],
0, camera_info_.K[4], camera_info_.K[5],
0, 0, 1);
cv::Mat rvec, tvec;
cv::Vec4f dist_param(0,0,0,0);
cv::solvePnP(object_pts, image_pts, intrinsics, dist_param,
rvec, tvec);
cv::Matx33d r;
cv::Rodrigues(rvec, r);
Eigen::Matrix3d rot;
rot << r(0,0), r(0,1), r(0,2),
r(1,0), r(1,1), r(1,2),
r(2,0), r(2,1), r(2,2);
Eigen::Matrix4d T;
T.topLeftCorner(3,3) = rot;
T.col(3).head(3) <<
tvec.at<double>(0), tvec.at<double>(1), tvec.at<double>(2);
T.row(3) << 0,0,0,1;
return T;
}
// Callback for camera info
void InfoCallback(const sensor_msgs::CameraInfoConstPtr& camera_info)
{
camera_info_ = (*camera_info);
has_camera_info_ = true;
}
// Callback for image data
void ImageCallback(const sensor_msgs::ImageConstPtr& msg )
{
if(!has_camera_info_){
ROS_WARN("No Camera Info Received Yet");
return;
}
// Get the image
cv_bridge::CvImagePtr subscribed_ptr;
try
{
subscribed_ptr = cv_bridge::toCvCopy(msg, "mono8");
}
catch(cv_bridge::Exception& e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
cv::Mat subscribed_gray = subscribed_ptr->image;
cv::Mat tmp;
cv::Point2d opticalCenter(0.5*subscribed_gray.rows,
0.5*subscribed_gray.cols);
TagDetectionArray detections;
detector_->process(subscribed_gray, opticalCenter, detections);
visualization_msgs::MarkerArray marker_transforms;
if(viewer_)
{
subscribed_gray = family_->superimposeDetections(subscribed_gray,
detections);
}
for(unsigned int i = 0; i < detections.size(); ++i)
{
Eigen::Matrix4d pose = GetDetectionTransform(detections[i]);
// Get this info from earlier code, don't extract it again
Eigen::Matrix3d R = pose.block<3,3>(0,0);
Eigen::Quaternion<double> q(R);
visualization_msgs::Marker marker_transform;
marker_transform.header.frame_id = frame_;
marker_transform.header.stamp = ros::Time::now();
stringstream convert;
convert << "tag" << detections[i].id;
marker_transform.ns = convert.str().c_str();
marker_transform.id = detections[i].id;
marker_transform.type = visualization_msgs::Marker::ARROW;
//marker_transform.type = visualization_msgs::Marker::CUBE;
marker_transform.action = visualization_msgs::Marker::ADD;
marker_transform.pose.position.x = pose(0,3);
marker_transform.pose.position.y = pose(1,3);
marker_transform.pose.position.z = pose(2,3);
marker_transform.pose.orientation.x = q.x();
marker_transform.pose.orientation.y = q.y();
marker_transform.pose.orientation.z = q.z();
marker_transform.pose.orientation.w = q.w();
double tag_size = GetTagSize(detections[i].id);
/*
marker_transform.scale.x = tag_size;
marker_transform.scale.y = tag_size;
marker_transform.scale.z = 0.01 * tag_size;
*/
marker_transform.scale.x = tag_size;
marker_transform.scale.y = tag_size*10;
marker_transform.scale.z = tag_size*0.5;
marker_transform.color.r = 1.0;
marker_transform.color.g = 0.0;
marker_transform.color.b = 1.0;
marker_transform.color.a = 1.0;
marker_transforms.markers.push_back(marker_transform);
}
marker_publisher_.publish(marker_transforms);
if(viewer_)
{
cv::imshow("AprilTags", subscribed_gray);
}
}
void ConnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Subscription detected! (%d subscribers)", subscribers);
if(subscribers && !running_)
{
ROS_DEBUG("New Subscribers, Connecting to Input Image Topic.");
ros::TransportHints ros_transport_hints(ros::TransportHints().tcpNoDelay());
image_transport::TransportHints image_transport_hint(image_transport::TransportHints(
"raw", ros_transport_hints, (*node_),
"image_transport"));
image_subscriber = (*image_).subscribe(
DEFAULT_IMAGE_TOPIC, 1, &ImageCallback,
image_transport_hint);
info_subscriber = (*node_).subscribe(
DEFAULT_CAMERA_INFO_TOPIC, 10, &InfoCallback);
running_ = true;
}
}
void DisconnectHandler()
{
}
void DisconnectCallback(const ros::SingleSubscriberPublisher& info)
{
// Check for subscribers.
uint32_t subscribers = marker_publisher_.getNumSubscribers();
ROS_DEBUG("Unsubscription detected! (%d subscribers)", subscribers);
if(!subscribers && running_)
{
ROS_DEBUG("No Subscribers, Disconnecting from Input Image Topic.");
image_subscriber.shutdown();
info_subscriber.shutdown();
running_ = false;
}
}
void GetParameterValues()
{
// Load node-wide configuration values.
node_->param("viewer", viewer_, 0);
node_->param("tag_family", tag_family_name_, DEFAULT_TAG_FAMILY);
node_->param("default_tag_size", default_tag_size_, DEFAULT_TAG_SIZE);
node_->param("tf_frame", frame_, DEFAULT_TF_FRAME);
// Load tag specific configuration values.
XmlRpc::XmlRpcValue tag_data;
node_->param("tag_data", tag_data, tag_data);
// Iterate through each tag in the configuration.
XmlRpc::XmlRpcValue::ValueStruct::iterator it;
for (it = tag_data.begin(); it != tag_data.end(); ++it)
{
// Retrieve the settings for the next tag.
int tag_id = boost::lexical_cast<int>(it->first);
XmlRpc::XmlRpcValue tag_values = it->second;
// Load all the settings for this tag.
if (tag_values.hasMember("size"))
{
tag_sizes_[tag_id] = static_cast<double>(tag_values["size"]);
ROS_DEBUG("Setting tag%d to size %f m.", tag_id, tag_sizes_[tag_id]);
}
}
}
void SetupPublisher()
{
ros::SubscriberStatusCallback connect_callback = &ConnectCallback;
ros::SubscriberStatusCallback disconnect_callback = &DisconnectCallback;
// Publisher
marker_publisher_ = node_->advertise<visualization_msgs::MarkerArray>(
DEFAULT_MARKER_TOPIC, 1, connect_callback,
disconnect_callback);
}
void InitializeTags()
{
tag_params.newQuadAlgorithm = 1;
family_ = new TagFamily(tag_family_name_);
detector_ = new TagDetector(*family_, tag_params);
}
void InitializeROSNode(int argc, char **argv)
{
ros::init(argc, argv, "apriltags");
node_ = boost::make_shared<ros::NodeHandle>("~");
image_ = boost::make_shared<image_transport::ImageTransport>(*node_);
}
int main(int argc, char **argv)
{
InitializeROSNode(argc,argv);
GetParameterValues();
SetupPublisher();
InitializeTags();
if(viewer_){
cvNamedWindow("AprilTags");
cvStartWindowThread();
}
ROS_INFO("AprilTags node started.");
running_ = false;
has_camera_info_ = false;
ros::spin();
ROS_INFO("AprilTags node stopped.");
//Destroying Stuff
cvDestroyWindow("AprilTags");
delete detector_;
delete family_;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// @(#)root/krb5auth:$Id$
// Author: Maarten Ballintijn 27/10/2003
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "TKSocket.h"
#include "TSocket.h"
#include "TError.h"
extern "C" {
// missing from "krb5.h"
extern int krb5_net_read(/*IN*/ krb5_context context, int fd,
/*OUT*/ char *buf,/*IN*/ int len);
extern int krb5_net_write(/*IN*/ krb5_context context, int fd,
const char *buf, int len);
}
ClassImp(TKSocket)
krb5_context TKSocket::fgContext = 0;
krb5_ccache TKSocket::fgCCDef = 0;
krb5_principal TKSocket::fgClient = 0;
//______________________________________________________________________________
TKSocket::TKSocket(TSocket *s)
: fSocket(s), fServer(0), fAuthContext(0)
{
// Constructor
}
//______________________________________________________________________________
TKSocket::~TKSocket()
{
// Destructor
krb5_free_principal(fgContext, fServer);
krb5_auth_con_free(fgContext, fAuthContext);
delete fSocket;
}
//______________________________________________________________________________
TKSocket *TKSocket::Connect(const char *server, Int_t port)
{
// Connect to 'server' on 'port'
Int_t rc;
if (fgContext == 0) {
rc = krb5_init_context(&fgContext);
if (rc != 0) {
::Error("TKSocket::Connect","while initializing krb5 (%d), %s",
rc, error_message(rc));
return 0;
}
rc = krb5_cc_default(fgContext, &fgCCDef);
if (rc != 0) {
::Error("TKSocket::Connect","while getting default credential cache (%d), %s",
rc, error_message(rc));
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient);
if (rc != 0) {
::Error("TKSocket::Connect","while getting client principal from %s (%d), %s",
krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc));
krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0;
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
}
TSocket *s = new TSocket(server, port);
if (!s->IsValid()) {
::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port);
delete s;
return 0;
}
TKSocket *ks = new TKSocket(s);
rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer);
if (rc != 0) {
::Error("TKSocket::Connect","while getting server principal (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
krb5_data cksum_data;
cksum_data.data = StrDup(server);
cksum_data.length = strlen(server);
krb5_error *err_ret;
krb5_ap_rep_enc_part *rep_ret;
int sock = ks->fSocket->GetDescriptor();
rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock,
(char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer,
AP_OPTS_MUTUAL_REQUIRED,
&cksum_data,
0, /* no creds, use ccache instead */
fgCCDef, &err_ret, &rep_ret, 0);
delete [] cksum_data.data;
if (rc != 0) {
::Error("TKSocket::Connect","while sendauth (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
return ks;
}
//______________________________________________________________________________
Int_t TKSocket::BlockRead(char *&buf, EEncoding &type)
{
// Read block on information from server. The result is stored in buf.
// The number of read bytes is returned; -1 is returned in case of error.
Int_t rc;
Desc_t desc;
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
type = static_cast<EEncoding>(ntohs(desc.fType));
krb5_data enc;
enc.length = ntohs(desc.fLength);
enc.data = new char[enc.length+1];
rc = krb5_net_read(fgContext, fd, enc.data, enc.length);
enc.data[enc.length] = 0;
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading data (%d), %s",
rc, error_message(rc));
return -1;
}
krb5_data out;
switch (type) {
case kNone:
buf = enc.data;
rc = enc.length;
break;
case kSafe:
rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0);
break;
case kPriv:
rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
if (type != kNone) {
// copy data to buffer that is new'ed
buf = new char[out.length+1];
memcpy(buf, out.data, out.length);
buf[out.length] = 0;
free(out.data);
delete [] enc.data;
rc = out.length;
}
return rc;
}
//______________________________________________________________________________
Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type)
{
// Block-send 'length' bytes to server from 'buf'.
Desc_t desc;
krb5_data in;
krb5_data enc;
Int_t rc;
in.data = const_cast<char*>(buf);
in.length = length;
switch (type) {
case kNone:
enc.data = in.data;
enc.length = in.length;
break;
case kSafe:
rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0);
break;
case kPriv:
rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
desc.fLength = htons(enc.length);
desc.fType = htons(type);
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc <= 0) {
Error("BlockWrite","writing descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length);
if (rc <= 0) {
Error("BlockWrite","writing data (%d), %s",
rc, error_message(rc));
return -1;
}
if (type != kNone) free(enc.data);
return rc;
}
<commit_msg>on OSX add missing krb5_net_read() and krb5_net_write() functions. Found them missing when switching to "-undefined error".<commit_after>// @(#)root/krb5auth:$Id$
// Author: Maarten Ballintijn 27/10/2003
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "TKSocket.h"
#include "TSocket.h"
#include "TError.h"
extern "C" {
// missing from "krb5.h"
extern int krb5_net_read(/*IN*/ krb5_context context, int fd,
/*OUT*/ char *buf,/*IN*/ int len);
extern int krb5_net_write(/*IN*/ krb5_context context, int fd,
const char *buf, int len);
}
#ifdef __APPLE__
#define SOCKET int
#define SOCKET_ERRNO errno
#define SOCKET_EINTR EINTR
#define SOCKET_READ(a,b,c) read(a,b,c)
#define SOCKET_WRITE(a,b,c) write(a,b,c)
/*
* lib/krb5/os/net_read.c
*
* Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
*/
/*
* krb5_net_read() reads from the file descriptor "fd" to the buffer
* "buf", until either 1) "len" bytes have been read or 2) cannot
* read anymore from "fd". It returns the number of bytes read
* or a read() error. (The calling interface is identical to
* read(2).)
*
* XXX must not use non-blocking I/O
*/
int krb5_net_read(krb5_context /*context*/, int fd, register char *buf, register int len)
{
int cc, len2 = 0;
do {
cc = SOCKET_READ((SOCKET)fd, buf, len);
if (cc < 0) {
if (SOCKET_ERRNO == SOCKET_EINTR)
continue;
/* XXX this interface sucks! */
errno = SOCKET_ERRNO;
return(cc); /* errno is already set */
} else if (cc == 0) {
return(len2);
} else {
buf += cc;
len2 += cc;
len -= cc;
}
} while (len > 0);
return(len2);
}
/*
* lib/krb5/os/net_write.c
*
* Copyright 1987, 1988, 1990 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*
*/
/*
* krb5_net_write() writes "len" bytes from "buf" to the file
* descriptor "fd". It returns the number of bytes written or
* a write() error. (The calling interface is identical to
* write(2).)
*
* XXX must not use non-blocking I/O
*/
int krb5_net_write(krb5_context /*context*/, int fd, register const char *buf, int len)
{
int cc;
register int wrlen = len;
do {
cc = SOCKET_WRITE((SOCKET)fd, buf, wrlen);
if (cc < 0) {
if (SOCKET_ERRNO == SOCKET_EINTR)
continue;
/* XXX this interface sucks! */
errno = SOCKET_ERRNO;
return(cc);
} else {
buf += cc;
wrlen -= cc;
}
} while (wrlen > 0);
return(len);
}
#endif
ClassImp(TKSocket)
krb5_context TKSocket::fgContext = 0;
krb5_ccache TKSocket::fgCCDef = 0;
krb5_principal TKSocket::fgClient = 0;
//______________________________________________________________________________
TKSocket::TKSocket(TSocket *s)
: fSocket(s), fServer(0), fAuthContext(0)
{
// Constructor
}
//______________________________________________________________________________
TKSocket::~TKSocket()
{
// Destructor
krb5_free_principal(fgContext, fServer);
krb5_auth_con_free(fgContext, fAuthContext);
delete fSocket;
}
//______________________________________________________________________________
TKSocket *TKSocket::Connect(const char *server, Int_t port)
{
// Connect to 'server' on 'port'
Int_t rc;
if (fgContext == 0) {
rc = krb5_init_context(&fgContext);
if (rc != 0) {
::Error("TKSocket::Connect","while initializing krb5 (%d), %s",
rc, error_message(rc));
return 0;
}
rc = krb5_cc_default(fgContext, &fgCCDef);
if (rc != 0) {
::Error("TKSocket::Connect","while getting default credential cache (%d), %s",
rc, error_message(rc));
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
rc = krb5_cc_get_principal(fgContext, fgCCDef, &fgClient);
if (rc != 0) {
::Error("TKSocket::Connect","while getting client principal from %s (%d), %s",
krb5_cc_get_name(fgContext,fgCCDef), rc, error_message(rc));
krb5_cc_close(fgContext,fgCCDef); fgCCDef = 0;
krb5_free_context(fgContext); fgContext = 0;
return 0;
}
}
TSocket *s = new TSocket(server, port);
if (!s->IsValid()) {
::SysError("TKSocket::Connect","Cannot connect to %s:%d", server, port);
delete s;
return 0;
}
TKSocket *ks = new TKSocket(s);
rc = krb5_sname_to_principal(fgContext, server, "host", KRB5_NT_SRV_HST, &ks->fServer);
if (rc != 0) {
::Error("TKSocket::Connect","while getting server principal (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
krb5_data cksum_data;
cksum_data.data = StrDup(server);
cksum_data.length = strlen(server);
krb5_error *err_ret;
krb5_ap_rep_enc_part *rep_ret;
int sock = ks->fSocket->GetDescriptor();
rc = krb5_sendauth(fgContext, &ks->fAuthContext, (krb5_pointer) &sock,
(char *)"KRB5_TCP_Python_v1.0", fgClient, ks->fServer,
AP_OPTS_MUTUAL_REQUIRED,
&cksum_data,
0, /* no creds, use ccache instead */
fgCCDef, &err_ret, &rep_ret, 0);
delete [] cksum_data.data;
if (rc != 0) {
::Error("TKSocket::Connect","while sendauth (%d), %s",
rc, error_message(rc));
delete ks;
return 0;
}
return ks;
}
//______________________________________________________________________________
Int_t TKSocket::BlockRead(char *&buf, EEncoding &type)
{
// Read block on information from server. The result is stored in buf.
// The number of read bytes is returned; -1 is returned in case of error.
Int_t rc;
Desc_t desc;
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_read(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
type = static_cast<EEncoding>(ntohs(desc.fType));
krb5_data enc;
enc.length = ntohs(desc.fLength);
enc.data = new char[enc.length+1];
rc = krb5_net_read(fgContext, fd, enc.data, enc.length);
enc.data[enc.length] = 0;
if (rc == 0) errno = ECONNABORTED;
if (rc <= 0) {
SysError("BlockRead","reading data (%d), %s",
rc, error_message(rc));
return -1;
}
krb5_data out;
switch (type) {
case kNone:
buf = enc.data;
rc = enc.length;
break;
case kSafe:
rc = krb5_rd_safe(fgContext, fAuthContext, &enc, &out, 0);
break;
case kPriv:
rc = krb5_rd_priv(fgContext, fAuthContext, &enc, &out, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
if (type != kNone) {
// copy data to buffer that is new'ed
buf = new char[out.length+1];
memcpy(buf, out.data, out.length);
buf[out.length] = 0;
free(out.data);
delete [] enc.data;
rc = out.length;
}
return rc;
}
//______________________________________________________________________________
Int_t TKSocket::BlockWrite(const char *buf, Int_t length, EEncoding type)
{
// Block-send 'length' bytes to server from 'buf'.
Desc_t desc;
krb5_data in;
krb5_data enc;
Int_t rc;
in.data = const_cast<char*>(buf);
in.length = length;
switch (type) {
case kNone:
enc.data = in.data;
enc.length = in.length;
break;
case kSafe:
rc = krb5_mk_safe(fgContext, fAuthContext, &in, &enc, 0);
break;
case kPriv:
rc = krb5_mk_priv(fgContext, fAuthContext, &in, &enc, 0);
break;
default:
Error("BlockWrite","unknown encoding type (%d)", type);
return -1;
}
desc.fLength = htons(enc.length);
desc.fType = htons(type);
Int_t fd = fSocket->GetDescriptor();
rc = krb5_net_write(fgContext, fd, (char *)&desc, sizeof(desc));
if (rc <= 0) {
Error("BlockWrite","writing descriptor (%d), %s",
rc, error_message(rc));
return -1;
}
rc = krb5_net_write(fgContext, fd, (char *)enc.data, enc.length);
if (rc <= 0) {
Error("BlockWrite","writing data (%d), %s",
rc, error_message(rc));
return -1;
}
if (type != kNone) free(enc.data);
return rc;
}
<|endoftext|> |
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.h"
#include <sys/types.h>
#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
namespace content {
SandboxBPFBasePolicyAndroid::SandboxBPFBasePolicyAndroid()
: SandboxBPFBasePolicy() {}
SandboxBPFBasePolicyAndroid::~SandboxBPFBasePolicyAndroid() {}
sandbox::ErrorCode SandboxBPFBasePolicyAndroid::EvaluateSyscall(
sandbox::SandboxBPF* sandbox,
int sysno) const {
bool override_and_allow = false;
switch (sysno) {
case __NR_epoll_pwait:
case __NR_flock:
case __NR_getpriority:
case __NR_ioctl:
case __NR_mremap:
// File system access cannot be restricted with seccomp-bpf on Android,
// since the JVM classloader and other Framework features require file
// access. It may be possible to restrict the filesystem with SELinux.
// Currently we rely on the app/service UID isolation to create a
// filesystem "sandbox".
#if !ARCH_CPU_ARM64
case __NR_open:
#endif
case __NR_openat:
case __NR_pread64:
case __NR_rt_sigtimedwait:
case __NR_setpriority:
case __NR_sigaltstack:
case __NR_ugetrlimit:
case __NR_uname:
override_and_allow = true;
break;
}
if (override_and_allow)
return sandbox::ErrorCode(sandbox::ErrorCode::ERR_ALLOWED);
return SandboxBPFBasePolicy::EvaluateSyscall(sandbox, sysno);
}
} // namespace content
<commit_msg>Fix compilation error of sandbox for Android x64 and mips<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/sandbox_linux/android/sandbox_bpf_base_policy_android.h"
#include <sys/types.h>
#include "sandbox/linux/seccomp-bpf/sandbox_bpf.h"
namespace content {
SandboxBPFBasePolicyAndroid::SandboxBPFBasePolicyAndroid()
: SandboxBPFBasePolicy() {}
SandboxBPFBasePolicyAndroid::~SandboxBPFBasePolicyAndroid() {}
sandbox::ErrorCode SandboxBPFBasePolicyAndroid::EvaluateSyscall(
sandbox::SandboxBPF* sandbox,
int sysno) const {
bool override_and_allow = false;
switch (sysno) {
case __NR_epoll_pwait:
case __NR_flock:
case __NR_getpriority:
case __NR_ioctl:
case __NR_mremap:
// File system access cannot be restricted with seccomp-bpf on Android,
// since the JVM classloader and other Framework features require file
// access. It may be possible to restrict the filesystem with SELinux.
// Currently we rely on the app/service UID isolation to create a
// filesystem "sandbox".
#if !ARCH_CPU_ARM64
case __NR_open:
#endif
case __NR_openat:
case __NR_pread64:
case __NR_rt_sigtimedwait:
case __NR_setpriority:
case __NR_sigaltstack:
#if defined(__i386__) || defined(__arm__)
case __NR_ugetrlimit:
#else
case __NR_getrlimit:
#endif
case __NR_uname:
override_and_allow = true;
break;
}
if (override_and_allow)
return sandbox::ErrorCode(sandbox::ErrorCode::ERR_ALLOWED);
return SandboxBPFBasePolicy::EvaluateSyscall(sandbox, sysno);
}
} // namespace content
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/PlatformSpecificFunctions.h"
TEST_GROUP(UtestShell)
{
TestTestingFixture fixture;
};
static void _failMethod()
{
FAIL("This test fails");
}
static void _passingTestMethod()
{
CHECK(true);
}
static void _passingCheckEqualTestMethod()
{
CHECK_EQUAL(1, 1);
}
static void _exitTestMethod()
{
TEST_EXIT;
FAIL("Should not get here");
}
static volatile double zero = 0.0;
TEST(UtestShell, compareDoubles)
{
double not_a_number = zero / zero;
double infinity = 1 / zero;
CHECK(doubles_equal(1.0, 1.001, 0.01));
CHECK(!doubles_equal(not_a_number, 1.001, 0.01));
CHECK(!doubles_equal(1.0, not_a_number, 0.01));
CHECK(!doubles_equal(1.0, 1.001, not_a_number));
CHECK(!doubles_equal(1.0, 1.1, 0.05));
CHECK(!doubles_equal(infinity, 1.0, 0.01));
CHECK(!doubles_equal(1.0, infinity, 0.01));
CHECK(doubles_equal(1.0, -1.0, infinity));
CHECK(doubles_equal(infinity, infinity, 0.01));
CHECK(doubles_equal(infinity, infinity, infinity));
double a = 1.2345678;
CHECK(doubles_equal(a, a, 0.000000001));
}
TEST(UtestShell, FailWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_passingCheckEqualTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)
{
CHECK(&fixture != NULLPTR);
}
TEST(UtestShell, MacrosUsedInSetup)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setSetup(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, MacrosUsedInTearDown)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, ExitLeavesQuietly)
{
fixture.setTestFunction(_exitTestMethod);
fixture.runAllTests();
LONGS_EQUAL(0, fixture.getFailureCount());
}
static int teardownCalled = 0;
static void _teardownMethod()
{
teardownCalled++;
}
TEST(UtestShell, TeardownCalledAfterTestFailure)
{
teardownCalled = 0;
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_teardownMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(1, teardownCalled);
}
static int stopAfterFailure = 0;
static void _stopAfterFailureMethod()
{
FAIL("fail");
stopAfterFailure++;
}
TEST(UtestShell, TestStopsAfterTestFailure)
{
IGNORE_ALL_LEAKS_IN_TEST();
stopAfterFailure = 0;
fixture.setTestFunction(_stopAfterFailureMethod);
fixture.runAllTests();
CHECK(fixture.hasTestFailed());
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
TEST(UtestShell, TestStopsAfterSetupFailure)
{
stopAfterFailure = 0;
fixture.setSetup(_stopAfterFailureMethod);
fixture.setTeardown(_stopAfterFailureMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
class defaultUtestShell: public UtestShell
{
};
TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods)
{
defaultUtestShell shell;
fixture.addTest(&shell);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.result_->getTestCount());
}
static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "Failed in separate process"));
}
TEST(UtestShell, RunInSeparateProcessTest)
{
UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process");
}
#if !CPPUTEST_HAVE_FORK
IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {}
#else
TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest)
{
fixture.setTestFunction(UtestShell::crash);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process - killed by signal");
/* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 */
CHECK(fixture.getOutput().contains("signal 11") || fixture.getOutput().contains("signal 4"));
}
#endif
#if CPPUTEST_USE_STD_CPP_LIB
static bool destructorWasCalledOnFailedTest = false;
static void _destructorCalledForLocalObjects()
{
SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest);
destructorWasCalledOnFailedTest = false;
FAIL("fail");
}
TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)
{
fixture.setTestFunction(_destructorCalledForLocalObjects);
fixture.runAllTests();
CHECK(destructorWasCalledOnFailedTest);
}
#endif
TEST_GROUP(IgnoredUtestShell)
{
TestTestingFixture fixture;
IgnoredUtestShell ignoredTest;
ExecFunctionTestShell normalUtestShell;
void setup() _override
{
fixture.addTest(&ignoredTest);
fixture.addTest(&normalUtestShell);
}
};
TEST(IgnoredUtestShell, doesIgnoreCount)
{
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose)
{
fixture.output_->verbose();
fixture.runAllTests();
fixture.assertPrintContains("IGNORE_TEST");
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount)
{
ignoredTest.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(3, fixture.getRunCount());
LONGS_EQUAL(0, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount)
{
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount)
{
normalUtestShell.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
ignoredTest.setRunIgnored();
fixture.runAllTests();
STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
fixture.runAllTests();
STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse)
{
CHECK_FALSE(ignoredTest.willRun());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue)
{
ignoredTest.setRunIgnored();
CHECK_TRUE(ignoredTest.willRun());
}
TEST_BASE(MyOwnTest)
{
MyOwnTest() :
inTest(false)
{
}
bool inTest;
void setup()
{
CHECK(!inTest);
inTest = true;
}
void teardown()
{
CHECK(inTest);
inTest = false;
}
};
TEST_GROUP_BASE(UtestMyOwn, MyOwnTest)
{
};
TEST(UtestMyOwn, test)
{
CHECK(inTest);
}
class NullParameterTest: public UtestShell
{
};
TEST(UtestMyOwn, NullParameters)
{
NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */
TestFilter emptyFilter;
CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter));
}
class AllocateAndDeallocateInConstructorAndDestructor
{
char* memory_;
char* morememory_;
public:
AllocateAndDeallocateInConstructorAndDestructor()
{
memory_ = new char[100];
morememory_ = NULLPTR;
}
void allocateMoreMemory()
{
morememory_ = new char[123];
}
~AllocateAndDeallocateInConstructorAndDestructor()
{
delete [] memory_;
delete [] morememory_;
}
};
TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)
{
AllocateAndDeallocateInConstructorAndDestructor dummy;
};
TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)
{
dummy.allocateMoreMemory();
}
static int getZero()
{
return 0;
}
static int getOne()
{
return 1;
}
TEST_GROUP(UtestShellPointerArrayTest)
{
UtestShell* test0;
UtestShell* test1;
UtestShell* test2;
void setup()
{
test0 = new IgnoredUtestShell();
test1 = new IgnoredUtestShell();
test2 = new IgnoredUtestShell();
test0->addTest(test1);
test1->addTest(test2);
}
void teardown()
{
delete test0;
delete test1;
delete test2;
}
};
TEST(UtestShellPointerArrayTest, empty)
{
UtestShellPointerArray tests(NULLPTR);
tests.shuffle(0);
CHECK(NULL == tests.getFirstTest());
}
TEST(UtestShellPointerArrayTest, testsAreInOrder)
{
UtestShellPointerArray tests(test0);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone)
{
UtestShellPointerArray tests(test0);
tests.relinkTestsInOrder();
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234)
{
UtestShellPointerArray tests(test0);
tests.shuffle(1234);
CHECK(tests.getFirstTest() != test0);
}
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero)
{
UT_PTR_SET(PlatformSpecificRand, getZero);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test1);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test0);
}
// swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test1);
}
TEST(UtestShellPointerArrayTest, reverse)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.reverse();
CHECK(tests.get(0) == test2);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test0);
}
<commit_msg>Crash methods better not run with address sanitizer<commit_after>/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestTestingFixture.h"
#include "CppUTest/PlatformSpecificFunctions.h"
TEST_GROUP(UtestShell)
{
TestTestingFixture fixture;
};
static void _failMethod()
{
FAIL("This test fails");
}
static void _passingTestMethod()
{
CHECK(true);
}
static void _passingCheckEqualTestMethod()
{
CHECK_EQUAL(1, 1);
}
static void _exitTestMethod()
{
TEST_EXIT;
FAIL("Should not get here");
}
static volatile double zero = 0.0;
TEST(UtestShell, compareDoubles)
{
double not_a_number = zero / zero;
double infinity = 1 / zero;
CHECK(doubles_equal(1.0, 1.001, 0.01));
CHECK(!doubles_equal(not_a_number, 1.001, 0.01));
CHECK(!doubles_equal(1.0, not_a_number, 0.01));
CHECK(!doubles_equal(1.0, 1.001, not_a_number));
CHECK(!doubles_equal(1.0, 1.1, 0.05));
CHECK(!doubles_equal(infinity, 1.0, 0.01));
CHECK(!doubles_equal(1.0, infinity, 0.01));
CHECK(doubles_equal(1.0, -1.0, infinity));
CHECK(doubles_equal(infinity, infinity, 0.01));
CHECK(doubles_equal(infinity, infinity, infinity));
double a = 1.2345678;
CHECK(doubles_equal(a, a, 0.000000001));
}
TEST(UtestShell, FailWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
TEST(UtestShell, PassedCheckEqualWillIncreaseTheAmountOfChecks)
{
fixture.setTestFunction(_passingCheckEqualTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getCheckCount());
}
IGNORE_TEST(UtestShell, IgnoreTestAccessingFixture)
{
CHECK(&fixture != NULLPTR);
}
TEST(UtestShell, MacrosUsedInSetup)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setSetup(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, MacrosUsedInTearDown)
{
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_failMethod);
fixture.setTestFunction(_passingTestMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
}
TEST(UtestShell, ExitLeavesQuietly)
{
fixture.setTestFunction(_exitTestMethod);
fixture.runAllTests();
LONGS_EQUAL(0, fixture.getFailureCount());
}
static int teardownCalled = 0;
static void _teardownMethod()
{
teardownCalled++;
}
TEST(UtestShell, TeardownCalledAfterTestFailure)
{
teardownCalled = 0;
IGNORE_ALL_LEAKS_IN_TEST();
fixture.setTeardown(_teardownMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(1, teardownCalled);
}
static int stopAfterFailure = 0;
static void _stopAfterFailureMethod()
{
FAIL("fail");
stopAfterFailure++;
}
TEST(UtestShell, TestStopsAfterTestFailure)
{
IGNORE_ALL_LEAKS_IN_TEST();
stopAfterFailure = 0;
fixture.setTestFunction(_stopAfterFailureMethod);
fixture.runAllTests();
CHECK(fixture.hasTestFailed());
LONGS_EQUAL(1, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
TEST(UtestShell, TestStopsAfterSetupFailure)
{
stopAfterFailure = 0;
fixture.setSetup(_stopAfterFailureMethod);
fixture.setTeardown(_stopAfterFailureMethod);
fixture.setTestFunction(_failMethod);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getFailureCount());
LONGS_EQUAL(0, stopAfterFailure);
}
class defaultUtestShell: public UtestShell
{
};
TEST(UtestShell, this_test_covers_the_UtestShell_createTest_and_Utest_testBody_methods)
{
defaultUtestShell shell;
fixture.addTest(&shell);
fixture.runAllTests();
LONGS_EQUAL(2, fixture.result_->getTestCount());
}
static void StubPlatformSpecificRunTestInASeperateProcess(UtestShell* shell, TestPlugin*, TestResult* result)
{
result->addFailure(TestFailure(shell, "Failed in separate process"));
}
TEST(UtestShell, RunInSeparateProcessTest)
{
UT_PTR_SET(PlatformSpecificRunTestInASeperateProcess, StubPlatformSpecificRunTestInASeperateProcess);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process");
}
#if !CPPUTEST_HAVE_FORK
IGNORE_TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest) {}
#else
#if !CPPUTEST_SANITIZE_ADDRESS
TEST(UtestShell, TestDefaultCrashMethodInSeparateProcessTest)
{
fixture.setTestFunction(UtestShell::crash);
fixture.registry_->setRunTestsInSeperateProcess();
fixture.runAllTests();
fixture.assertPrintContains("Failed in separate process - killed by signal");
/* Signal 11 usually happens, but with clang3.7 on Linux, it produced signal 4 */
CHECK(fixture.getOutput().contains("signal 11") || fixture.getOutput().contains("signal 4"));
}
#endif
#endif
#if CPPUTEST_USE_STD_CPP_LIB
static bool destructorWasCalledOnFailedTest = false;
static void _destructorCalledForLocalObjects()
{
SetBooleanOnDestructorCall pleaseCallTheDestructor(destructorWasCalledOnFailedTest);
destructorWasCalledOnFailedTest = false;
FAIL("fail");
}
TEST(UtestShell, DestructorIsCalledForLocalObjectsWhenTheTestFails)
{
fixture.setTestFunction(_destructorCalledForLocalObjects);
fixture.runAllTests();
CHECK(destructorWasCalledOnFailedTest);
}
#endif
TEST_GROUP(IgnoredUtestShell)
{
TestTestingFixture fixture;
IgnoredUtestShell ignoredTest;
ExecFunctionTestShell normalUtestShell;
void setup() _override
{
fixture.addTest(&ignoredTest);
fixture.addTest(&normalUtestShell);
}
};
TEST(IgnoredUtestShell, doesIgnoreCount)
{
fixture.runAllTests();
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, printsIGNORE_TESTwhenVerbose)
{
fixture.output_->verbose();
fixture.runAllTests();
fixture.assertPrintContains("IGNORE_TEST");
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenIncreaseRunCount)
{
ignoredTest.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(3, fixture.getRunCount());
LONGS_EQUAL(0, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenIncreaseIgnoredCount)
{
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedWillNotInfluenceNormalTestCount)
{
normalUtestShell.setRunIgnored();
fixture.runAllTests();
LONGS_EQUAL(2, fixture.getRunCount());
LONGS_EQUAL(1, fixture.getIgnoreCount());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenReturnTESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
ignoredTest.setRunIgnored();
fixture.runAllTests();
STRCMP_EQUAL("TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenReturnIGNORETESTInFormattedName)
{
ignoredTest.setGroupName("TestGroup");
ignoredTest.setTestName("TestName");
fixture.runAllTests();
STRCMP_EQUAL("IGNORE_TEST(TestGroup, TestName)", ignoredTest.getFormattedName().asCharString());
}
TEST(IgnoredUtestShell, runIgnoredOptionNotSpecifiedThenWillRunReturnFalse)
{
CHECK_FALSE(ignoredTest.willRun());
}
TEST(IgnoredUtestShell, runIgnoredOptionSpecifiedThenWillRunReturnTrue)
{
ignoredTest.setRunIgnored();
CHECK_TRUE(ignoredTest.willRun());
}
TEST_BASE(MyOwnTest)
{
MyOwnTest() :
inTest(false)
{
}
bool inTest;
void setup()
{
CHECK(!inTest);
inTest = true;
}
void teardown()
{
CHECK(inTest);
inTest = false;
}
};
TEST_GROUP_BASE(UtestMyOwn, MyOwnTest)
{
};
TEST(UtestMyOwn, test)
{
CHECK(inTest);
}
class NullParameterTest: public UtestShell
{
};
TEST(UtestMyOwn, NullParameters)
{
NullParameterTest nullTest; /* Bug fix tests for creating a test without a name, fix in SimpleString */
TestFilter emptyFilter;
CHECK(nullTest.shouldRun(&emptyFilter, &emptyFilter));
}
class AllocateAndDeallocateInConstructorAndDestructor
{
char* memory_;
char* morememory_;
public:
AllocateAndDeallocateInConstructorAndDestructor()
{
memory_ = new char[100];
morememory_ = NULLPTR;
}
void allocateMoreMemory()
{
morememory_ = new char[123];
}
~AllocateAndDeallocateInConstructorAndDestructor()
{
delete [] memory_;
delete [] morememory_;
}
};
TEST_GROUP(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks)
{
AllocateAndDeallocateInConstructorAndDestructor dummy;
};
TEST(CanHaveMemberVariablesInTestGroupThatAllocateMemoryWithoutCausingMemoryLeaks, testInTestGroupName)
{
dummy.allocateMoreMemory();
}
static int getZero()
{
return 0;
}
static int getOne()
{
return 1;
}
TEST_GROUP(UtestShellPointerArrayTest)
{
UtestShell* test0;
UtestShell* test1;
UtestShell* test2;
void setup()
{
test0 = new IgnoredUtestShell();
test1 = new IgnoredUtestShell();
test2 = new IgnoredUtestShell();
test0->addTest(test1);
test1->addTest(test2);
}
void teardown()
{
delete test0;
delete test1;
delete test2;
}
};
TEST(UtestShellPointerArrayTest, empty)
{
UtestShellPointerArray tests(NULLPTR);
tests.shuffle(0);
CHECK(NULL == tests.getFirstTest());
}
TEST(UtestShellPointerArrayTest, testsAreInOrder)
{
UtestShellPointerArray tests(test0);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, relinkingTestsWillKeepThemTheSameWhenNothingWasDone)
{
UtestShellPointerArray tests(test0);
tests.relinkTestsInOrder();
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test2);
}
TEST(UtestShellPointerArrayTest, firstTestisNotTheFirstTestWithSeed1234)
{
UtestShellPointerArray tests(test0);
tests.shuffle(1234);
CHECK(tests.getFirstTest() != test0);
}
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningZero)
{
UT_PTR_SET(PlatformSpecificRand, getZero);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test1);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test0);
}
// swaps with 4 mod 3 (1) then 4 mod 2 (0): 1, [2], [0] --> [1], [0], 2 --> 0, 1, 2
TEST(UtestShellPointerArrayTest, ShuffleListTestWithRandomAlwaysReturningOne)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.shuffle(3);
CHECK(tests.get(0) == test0);
CHECK(tests.get(1) == test2);
CHECK(tests.get(2) == test1);
}
TEST(UtestShellPointerArrayTest, reverse)
{
UT_PTR_SET(PlatformSpecificRand, getOne);
UtestShellPointerArray tests(test0);
tests.reverse();
CHECK(tests.get(0) == test2);
CHECK(tests.get(1) == test1);
CHECK(tests.get(2) == test0);
}
<|endoftext|> |
<commit_before>//
// interest-control.cpp
//
// Created by Peter Gusev on 09 June 2016.
// Copyright 2013-2016 Regents of the University of California
//
#include "interest-control.hpp"
#include <algorithm>
#include "frame-data.hpp"
#include "name-components.hpp"
#include "estimators.hpp"
#define DEVIATION_ALPHA 1.
using namespace ndnrtc;
using namespace ndnrtc::statistics;
const unsigned int InterestControl::MinPipelineSize = 6;
void InterestControl::StrategyDefault::getLimits(double rate,
boost::shared_ptr<DrdEstimator> drdEstimator,
unsigned int &lowerLimit, unsigned int &upperLimit)
{
int interestDemand = calculateDemand(rate,
drdEstimator->getOriginalAverage().value(),
drdEstimator->getOriginalAverage().deviation());
if (interestDemand < InterestControl::MinPipelineSize)
interestDemand = InterestControl::MinPipelineSize;
lowerLimit = interestDemand;
upperLimit = interestDemand * 8;
}
int InterestControl::StrategyDefault::calculateDemand(double rate, double drdAvgValue, double drdDeviation) const
{
int interestDemand = InterestControl::MinPipelineSize;
if (drdAvgValue > 0 )
{
double d = drdAvgValue + DEVIATION_ALPHA * drdDeviation;
double targetSamplePeriod = (rate > 0 ? 1000. / rate : 30);
interestDemand = (int)(ceil(d / targetSamplePeriod));
}
return interestDemand;
}
int InterestControl::StrategyDefault::burst(unsigned int currentLimit,
unsigned int lowerLimit, unsigned int upperLimit)
{
return (int)ceil((double)currentLimit / 2.);
}
int InterestControl::StrategyDefault::withhold(unsigned int currentLimit,
unsigned int lowerLimit, unsigned int upperLimit)
{
return -(int)round((double)(currentLimit - lowerLimit) / 2.);
}
//******************************************************************************
InterestControl::InterestControl(const boost::shared_ptr<DrdEstimator> &drdEstimator,
const boost::shared_ptr<statistics::StatisticsStorage> &storage,
boost::shared_ptr<IInterestControlStrategy> strategy)
: initialized_(false),
lowerLimit_(InterestControl::MinPipelineSize),
limit_(InterestControl::MinPipelineSize),
upperLimit_(10 * InterestControl::MinPipelineSize), pipeline_(0),
drdEstimator_(drdEstimator), sstorage_(storage), strategy_(strategy),
targetRate_(0.)
{
description_ = "interest-control";
}
InterestControl::~InterestControl()
{
}
void InterestControl::initialize(double rate, int pipelineLimit)
{
lowerLimit_ = InterestControl::MinPipelineSize;
upperLimit_ = std::max((int)upperLimit_, pipelineLimit);
changeLimitTo(pipelineLimit);
LogDebugC << "pipeline capacity: " << limit_ << std::endl;
}
void InterestControl::reset()
{
initialized_ = false;
limitSet_ = false;
pipeline_ = 0;
lowerLimit_ = InterestControl::MinPipelineSize;
limit_ = InterestControl::MinPipelineSize;
upperLimit_ = 30;
(*sstorage_)[Indicator::DW] = limit_;
(*sstorage_)[Indicator::W] = pipeline_;
}
bool InterestControl::decrement()
{
pipeline_--;
assert(pipeline_ >= 0);
LogDebugC << "▼dec " << snapshot() << std::endl;
(*sstorage_)[Indicator::W] = pipeline_;
return true;
}
bool InterestControl::increment()
{
if (pipeline_ >= (int)limit_)
return false;
pipeline_++;
LogDebugC << "▲inc " << snapshot() << std::endl;
(*sstorage_)[Indicator::W] = pipeline_;
return true;
}
bool InterestControl::burst()
{
if (initialized_)
{
int d = strategy_->burst(limit_, lowerLimit_, upperLimit_);
changeLimitTo(limit_ + d);
LogDebugC << "burst by " << d << " " << snapshot() << std::endl;
return true;
}
return false;
}
bool InterestControl::withhold()
{
if (initialized_)
{
int d = strategy_->withhold(limit_, lowerLimit_, upperLimit_);
if (d != 0)
{
changeLimitTo(limit_ + d);
LogDebugC << "withhold by " << -d << " " << snapshot() << std::endl;
}
return (d != 0);
}
return false;
}
void InterestControl::markLowerLimit(unsigned int lowerLimit)
{
LogDebugC << "marking lower limit " << lowerLimit << std::endl;
limitSet_ = true;
lowerLimit_ = lowerLimit;
setLimits();
}
void InterestControl::onCachedDrdUpdate()
{
/*ignored*/
}
void InterestControl::onOriginalDrdUpdate()
{
if (initialized_)
setLimits();
}
void InterestControl::onDrdUpdate()
{
// if (initialized_)
// setLimits();
}
void InterestControl::targetRateUpdate(double rate)
{
targetRate_ = rate;
initialized_ = true;
setLimits();
}
void InterestControl::setLimits()
{
unsigned int newLower = 0, newUpper = 0;
strategy_->getLimits(targetRate_, drdEstimator_,
newLower, newUpper);
LogTraceC << "deciding... rate " << targetRate_
<< " latest drd update: value " << drdEstimator_->getLatestUpdatedAverage().value()
<< " dev " << drdEstimator_->getLatestUpdatedAverage().deviation()
<< " (demand ~" << drdEstimator_->getLatestUpdatedAverage().value() / 1000. * targetRate_ << ")"
<< " newLower " << newLower << " (" << lowerLimit_
<< ") newUpper " << newUpper << " (" << upperLimit_ << ")"
<< std::endl;
if (lowerLimit_ != newLower ||
upperLimit_ != newUpper)
{
if (!limitSet_ || newLower > lowerLimit_)
lowerLimit_ = newLower;
upperLimit_ = newUpper;
if (limit_ < lowerLimit_)
changeLimitTo(lowerLimit_);
LogTraceC
<< "DRD orig: " << drdEstimator_->getOriginalEstimation()
<< " cach: " << drdEstimator_->getCachedEstimation()
<< " dGen: " << drdEstimator_->getGenerationDelayAverage().value()
<< ", set limits " << snapshot() << std::endl;
}
}
void InterestControl::changeLimitTo(unsigned int newLimit)
{
if (newLimit < lowerLimit_)
{
LogWarnC << "can't set limit ("
<< newLimit
<< ") lower than lower limit ("
<< lowerLimit_ << ")" << std::endl;
limit_ = lowerLimit_;
}
else if (newLimit > upperLimit_)
{
LogWarnC << "can't set limit ("
<< newLimit
<< ") higher than upper limit ("
<< upperLimit_ << ")" << std::endl;
limit_ = upperLimit_;
}
else
limit_ = newLimit;
(*sstorage_)[Indicator::DW] = limit_;
}
std::string
InterestControl::snapshot() const
{
std::stringstream ss;
ss << lowerLimit_ << "-" << upperLimit_ << "[";
for (int i = 1;
i <= std::max((int)limit_, (int)pipeline_); //(int)fmax((double)limit_, (double)pipeline_);
++i)
{
if (i > limit_)
ss << "|"; //"⥣";
else
{
if (i <= pipeline_)
ss << "+"; //"⬆︎";
else
ss << "-"; //"◻︎";
}
}
ss << "]" << pipeline_ << "-" << limit_ << " (" << room() << ")";
return ss.str();
}
<commit_msg>trying increased minimal pipeline size<commit_after>//
// interest-control.cpp
//
// Created by Peter Gusev on 09 June 2016.
// Copyright 2013-2016 Regents of the University of California
//
#include "interest-control.hpp"
#include <algorithm>
#include "frame-data.hpp"
#include "name-components.hpp"
#include "estimators.hpp"
#define DEVIATION_ALPHA 1.
using namespace ndnrtc;
using namespace ndnrtc::statistics;
const unsigned int InterestControl::MinPipelineSize = 8;
void InterestControl::StrategyDefault::getLimits(double rate,
boost::shared_ptr<DrdEstimator> drdEstimator,
unsigned int &lowerLimit, unsigned int &upperLimit)
{
int interestDemand = calculateDemand(rate,
drdEstimator->getOriginalAverage().value(),
drdEstimator->getOriginalAverage().deviation());
if (interestDemand < InterestControl::MinPipelineSize)
interestDemand = InterestControl::MinPipelineSize;
lowerLimit = interestDemand;
upperLimit = interestDemand * 8;
}
int InterestControl::StrategyDefault::calculateDemand(double rate, double drdAvgValue, double drdDeviation) const
{
int interestDemand = InterestControl::MinPipelineSize;
if (drdAvgValue > 0 )
{
double d = drdAvgValue + DEVIATION_ALPHA * drdDeviation;
double targetSamplePeriod = (rate > 0 ? 1000. / rate : 30);
interestDemand = (int)(ceil(d / targetSamplePeriod));
}
return interestDemand;
}
int InterestControl::StrategyDefault::burst(unsigned int currentLimit,
unsigned int lowerLimit, unsigned int upperLimit)
{
return (int)ceil((double)currentLimit / 2.);
}
int InterestControl::StrategyDefault::withhold(unsigned int currentLimit,
unsigned int lowerLimit, unsigned int upperLimit)
{
return -(int)round((double)(currentLimit - lowerLimit) / 2.);
}
//******************************************************************************
InterestControl::InterestControl(const boost::shared_ptr<DrdEstimator> &drdEstimator,
const boost::shared_ptr<statistics::StatisticsStorage> &storage,
boost::shared_ptr<IInterestControlStrategy> strategy)
: initialized_(false),
lowerLimit_(InterestControl::MinPipelineSize),
limit_(InterestControl::MinPipelineSize),
upperLimit_(10 * InterestControl::MinPipelineSize), pipeline_(0),
drdEstimator_(drdEstimator), sstorage_(storage), strategy_(strategy),
targetRate_(0.)
{
description_ = "interest-control";
}
InterestControl::~InterestControl()
{
}
void InterestControl::initialize(double rate, int pipelineLimit)
{
lowerLimit_ = InterestControl::MinPipelineSize;
upperLimit_ = std::max((int)upperLimit_, pipelineLimit);
changeLimitTo(pipelineLimit);
LogDebugC << "pipeline capacity: " << limit_ << std::endl;
}
void InterestControl::reset()
{
initialized_ = false;
limitSet_ = false;
pipeline_ = 0;
lowerLimit_ = InterestControl::MinPipelineSize;
limit_ = InterestControl::MinPipelineSize;
upperLimit_ = 30;
(*sstorage_)[Indicator::DW] = limit_;
(*sstorage_)[Indicator::W] = pipeline_;
}
bool InterestControl::decrement()
{
pipeline_--;
assert(pipeline_ >= 0);
LogDebugC << "▼dec " << snapshot() << std::endl;
(*sstorage_)[Indicator::W] = pipeline_;
return true;
}
bool InterestControl::increment()
{
if (pipeline_ >= (int)limit_)
return false;
pipeline_++;
LogDebugC << "▲inc " << snapshot() << std::endl;
(*sstorage_)[Indicator::W] = pipeline_;
return true;
}
bool InterestControl::burst()
{
if (initialized_)
{
int d = strategy_->burst(limit_, lowerLimit_, upperLimit_);
changeLimitTo(limit_ + d);
LogDebugC << "burst by " << d << " " << snapshot() << std::endl;
return true;
}
return false;
}
bool InterestControl::withhold()
{
if (initialized_)
{
int d = strategy_->withhold(limit_, lowerLimit_, upperLimit_);
if (d != 0)
{
changeLimitTo(limit_ + d);
LogDebugC << "withhold by " << -d << " " << snapshot() << std::endl;
}
return (d != 0);
}
return false;
}
void InterestControl::markLowerLimit(unsigned int lowerLimit)
{
LogDebugC << "marking lower limit " << lowerLimit << std::endl;
limitSet_ = true;
lowerLimit_ = lowerLimit;
setLimits();
}
void InterestControl::onCachedDrdUpdate()
{
/*ignored*/
}
void InterestControl::onOriginalDrdUpdate()
{
if (initialized_)
setLimits();
}
void InterestControl::onDrdUpdate()
{
// if (initialized_)
// setLimits();
}
void InterestControl::targetRateUpdate(double rate)
{
targetRate_ = rate;
initialized_ = true;
setLimits();
}
void InterestControl::setLimits()
{
unsigned int newLower = 0, newUpper = 0;
strategy_->getLimits(targetRate_, drdEstimator_,
newLower, newUpper);
LogTraceC << "deciding... rate " << targetRate_
<< " latest drd update: value " << drdEstimator_->getLatestUpdatedAverage().value()
<< " dev " << drdEstimator_->getLatestUpdatedAverage().deviation()
<< " (demand ~" << drdEstimator_->getLatestUpdatedAverage().value() / 1000. * targetRate_ << ")"
<< " newLower " << newLower << " (" << lowerLimit_
<< ") newUpper " << newUpper << " (" << upperLimit_ << ")"
<< std::endl;
if (lowerLimit_ != newLower ||
upperLimit_ != newUpper)
{
if (!limitSet_ || newLower > lowerLimit_)
lowerLimit_ = newLower;
upperLimit_ = newUpper;
if (limit_ < lowerLimit_)
changeLimitTo(lowerLimit_);
LogTraceC
<< "DRD orig: " << drdEstimator_->getOriginalEstimation()
<< " cach: " << drdEstimator_->getCachedEstimation()
<< " dGen: " << drdEstimator_->getGenerationDelayAverage().value()
<< ", set limits " << snapshot() << std::endl;
}
}
void InterestControl::changeLimitTo(unsigned int newLimit)
{
if (newLimit < lowerLimit_)
{
LogWarnC << "can't set limit ("
<< newLimit
<< ") lower than lower limit ("
<< lowerLimit_ << ")" << std::endl;
limit_ = lowerLimit_;
}
else if (newLimit > upperLimit_)
{
LogWarnC << "can't set limit ("
<< newLimit
<< ") higher than upper limit ("
<< upperLimit_ << ")" << std::endl;
limit_ = upperLimit_;
}
else
limit_ = newLimit;
(*sstorage_)[Indicator::DW] = limit_;
}
std::string
InterestControl::snapshot() const
{
std::stringstream ss;
ss << lowerLimit_ << "-" << upperLimit_ << "[";
for (int i = 1;
i <= std::max((int)limit_, (int)pipeline_); //(int)fmax((double)limit_, (double)pipeline_);
++i)
{
if (i > limit_)
ss << "|"; //"⥣";
else
{
if (i <= pipeline_)
ss << "+"; //"⬆︎";
else
ss << "-"; //"◻︎";
}
}
ss << "]" << pipeline_ << "-" << limit_ << " (" << room() << ")";
return ss.str();
}
<|endoftext|> |
<commit_before>/*
* esteid-browser-plugin - a browser plugin for Estonian EID card
*
* Copyright (C) 2010 Estonian Informatics Centre
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "basedialog.h"
#include <windows.h>
typedef BaseDialog::Connection Connection;
BaseDialog::BaseDialog(HINSTANCE hInst)
: m_hInst(hInst),
m_hWnd(NULL),
m_modalDialog(false)
{
}
BaseDialog::~BaseDialog()
{
}
Connection BaseDialog::connect(const ResponseSignal::slot_type& subscriber)
{
return signalResponse.connect(subscriber);
}
void BaseDialog::disconnect(Connection subscriber)
{
subscriber.disconnect();
}
/* static */ LRESULT CALLBACK BaseDialog::dialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
BaseDialog *dlg = reinterpret_cast<BaseDialog*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (!dlg) {
if (message == WM_INITDIALOG) {
dlg = reinterpret_cast<BaseDialog*>(lParam);
dlg->m_hWnd = hWnd;
SetWindowLongPtr(hWnd, GWLP_USERDATA, lParam);
} else {
return 0; // let system deal with message
}
}
// forward message to member function handler
return dlg->on_message(message, wParam, lParam);
}
LRESULT BaseDialog::on_message(UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) {
case WM_INITDIALOG:
return on_initdialog(wParam);
break;
case WM_COMMAND:
return on_command(wParam, lParam);
break;
case WM_NOTIFY:
return on_notify(wParam, lParam);
break;
case WM_CLOSE:
if (m_modalDialog) {
EndDialog(m_hWnd, wParam);
} else {
DestroyWindow(m_hWnd);
signalResponse(RESPONSE_CANCEL);
}
return TRUE;
break;
}
return FALSE;
}
LRESULT BaseDialog::on_notify(WPARAM wParam, LPARAM lParam)
{
return FALSE;
}
bool BaseDialog::doDialog(int resourceID)
{
HWND hParent = GetForegroundWindow();
m_modalDialog = false;
m_hWnd = CreateDialogParam(m_hInst, MAKEINTRESOURCE(resourceID), hParent, (DLGPROC)dialogProc,
reinterpret_cast<LPARAM>(this));
if (!m_hWnd)
return false;
ShowWindow(m_hWnd, SW_NORMAL);
return true;
}
int BaseDialog::doModalDialog(int resourceID)
{
HWND hParent = GetForegroundWindow();
m_modalDialog = true;
return DialogBoxParam(m_hInst, MAKEINTRESOURCE(resourceID), hParent, (DLGPROC)dialogProc,
reinterpret_cast<LPARAM>(this));
}
<commit_msg>esteid-browser-plugin: hook into basedialog events to process keyboard messages<commit_after>/*
* esteid-browser-plugin - a browser plugin for Estonian EID card
*
* Copyright (C) 2010 Estonian Informatics Centre
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "basedialog.h"
#include <windows.h>
typedef BaseDialog::Connection Connection;
BaseDialog::BaseDialog(HINSTANCE hInst)
: m_hInst(hInst),
m_hWnd(NULL),
m_modalDialog(false)
{
}
BaseDialog::~BaseDialog()
{
}
Connection BaseDialog::connect(const ResponseSignal::slot_type& subscriber)
{
return signalResponse.connect(subscriber);
}
void BaseDialog::disconnect(Connection subscriber)
{
subscriber.disconnect();
}
/* static */ LRESULT CALLBACK BaseDialog::dialogProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
BaseDialog *dlg = reinterpret_cast<BaseDialog*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
if (!dlg) {
if (message == WM_INITDIALOG) {
dlg = reinterpret_cast<BaseDialog*>(lParam);
dlg->m_hWnd = hWnd;
SetWindowLongPtr(hWnd, GWLP_USERDATA, lParam);
} else {
return 0; // let system deal with message
}
}
// forward message to member function handler
return dlg->on_message(message, wParam, lParam);
}
static HHOOK s_hHook = NULL;
static HWND s_hWnd = NULL;
LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
LPMSG lpMsg = reinterpret_cast<LPMSG>(lParam);
if (nCode >= 0 && wParam == PM_REMOVE &&
lpMsg->message >= WM_KEYFIRST &&
lpMsg->message <= WM_KEYLAST) {
if (IsWindow(s_hWnd) && IsDialogMessage(s_hWnd, lpMsg)) {
// The value returned from this hookproc is ignored, and it cannot
// be used to tell Windows the message has been handled. To avoid
// further processing, convert the message to WM_NULL before
// returning.
lpMsg->message = WM_NULL;
lpMsg->lParam = 0L;
lpMsg->wParam = 0;
}
}
return CallNextHookEx(s_hHook, nCode, wParam, lParam);
}
LRESULT BaseDialog::on_message(UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) {
case WM_INITDIALOG:
s_hWnd = m_hWnd;
s_hHook = SetWindowsHookEx(WH_GETMESSAGE, GetMsgProc, NULL, GetCurrentThreadId());
return on_initdialog(wParam);
break;
case WM_COMMAND:
return on_command(wParam, lParam);
break;
case WM_NOTIFY:
return on_notify(wParam, lParam);
break;
case WM_CLOSE:
if (m_modalDialog) {
EndDialog(m_hWnd, wParam);
} else {
DestroyWindow(m_hWnd);
signalResponse(RESPONSE_CANCEL);
}
return TRUE;
break;
case WM_DESTROY:
UnhookWindowsHookEx(s_hHook);
return FALSE;
break;
}
return FALSE;
}
LRESULT BaseDialog::on_notify(WPARAM wParam, LPARAM lParam)
{
return FALSE;
}
bool BaseDialog::doDialog(int resourceID)
{
HWND hParent = GetForegroundWindow();
m_modalDialog = false;
m_hWnd = CreateDialogParam(m_hInst, MAKEINTRESOURCE(resourceID), hParent, (DLGPROC)dialogProc,
reinterpret_cast<LPARAM>(this));
if (!m_hWnd)
return false;
ShowWindow(m_hWnd, SW_NORMAL);
return true;
}
int BaseDialog::doModalDialog(int resourceID)
{
HWND hParent = GetForegroundWindow();
m_modalDialog = true;
return DialogBoxParam(m_hInst, MAKEINTRESOURCE(resourceID), hParent, (DLGPROC)dialogProc,
reinterpret_cast<LPARAM>(this));
}
<|endoftext|> |
<commit_before>#include "coldstakedelegation.h"
#include "init.h"
#include "json_spirit.h"
json_spirit::Object CoinStakeDelegationResult::AddressesToJsonObject() const
{
json_spirit::Object result;
result.push_back(json_spirit::Pair("owner_address", ownerAddress.ToString()));
result.push_back(json_spirit::Pair("staker_address", stakerAddress.ToString()));
return result;
}
Result<CoinStakeDelegationResult, ColdStakeDelegationErrorCode>
CreateColdStakeDelegation(const std::string& stakeAddress, CAmount nValue,
const boost::optional<std::string>& ownerAddress, bool fForceExternalAddr,
bool fUseDelegated, bool fForceNotEnabled)
{
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!Params().IsColdStakingEnabled() && !fForceNotEnabled)
return Err(ColdStakingDisabled);
// Get Staking Address
CBitcoinAddress stakeAddr(stakeAddress);
CKeyID stakeKey;
if (!stakeAddr.IsValid())
return Err(InvalidStakerAddress);
if (!stakeAddr.GetKeyID(stakeKey))
return Err(StakerAddressPubKeyHashError);
// Get Amount
if (nValue < Params().MinColdStakingAmount())
return Err(InvalidAmount);
// Check amount
const CAmount currBalance =
pwalletMain->GetBalance() - (fUseDelegated ? 0 : pwalletMain->GetDelegatedBalance());
if (nValue > currBalance)
return Err(InsufficientBalance);
if (pwalletMain->IsLocked() || fWalletUnlockStakingOnly)
return Err(WalletLocked);
// Get Owner Address
CBitcoinAddress ownerAddr;
CKeyID ownerKey;
if (ownerAddress) {
// Address provided
ownerAddr.SetString(*ownerAddress);
if (!ownerAddr.IsValid())
return Err(InvalidOwnerAddress);
if (!ownerAddr.GetKeyID(ownerKey))
return Err(OwnerAddressPubKeyHashError);
// Check that the owner address belongs to this wallet, or fForceExternalAddr is true
if (!fForceExternalAddr && !pwalletMain->HaveKey(ownerKey)) {
return Err(OwnerAddressNotInWallet);
}
} else {
// Get new owner address from keypool
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
return Err(KeyPoolEmpty);
CKeyID keyID = newKey.GetID();
ownerAddr = CBitcoinAddress(keyID);
// set address book entry
if (pwalletMain) {
pwalletMain->SetAddressBookEntry(ownerAddr.Get(), "Delegator address");
}
if (!ownerAddr.GetKeyID(ownerKey))
return Err(GeneratedOwnerAddressPubKeyHashError);
}
CoinStakeDelegationResult result;
result.ownerAddress = ownerAddr;
result.stakerAddress = stakeAddr;
// Get P2CS script for addresses
result.scriptPubKey = GetScriptForStakeDelegation(stakeKey, ownerKey);
return Ok(result);
}
std::string ColdStakeDelegationErrorStr(const ColdStakeDelegationErrorCode errorCode)
{
switch (errorCode) {
case ColdStakingDisabled:
return "Cold Staking disabled. "
"You may force the stake delegation to true. "
"WARNING: If relayed before activation, this tx will be rejected resulting in a ban. ";
case InvalidStakerAddress:
return "Invalid staker address";
case StakerAddressPubKeyHashError:
return "Unable to get stake pubkey hash from stakingaddress";
case InvalidAmount:
return strprintf("Invalid amount. Min amount: %zd", Params().MinColdStakingAmount());
case InsufficientBalance:
return "Insufficient funds";
case WalletLocked:
return "Error: Please unlock the wallet first.";
case InvalidOwnerAddress:
return "Invalid neblio spending/owner address";
case OwnerAddressPubKeyHashError:
return "Unable to get spend pubkey hash from owneraddress";
case OwnerAddressNotInWallet:
return "The provided owneraddress is not present in this wallet.";
case KeyPoolEmpty:
return "Error: Keypool ran out, please call keypoolrefill first";
case GeneratedOwnerAddressPubKeyHashError:
return "Unable to get spend pubkey hash from owneraddress";
}
}
<commit_msg>Added defult case in ColdStakeDelegationErrorStr()<commit_after>#include "coldstakedelegation.h"
#include "init.h"
#include "json_spirit.h"
json_spirit::Object CoinStakeDelegationResult::AddressesToJsonObject() const
{
json_spirit::Object result;
result.push_back(json_spirit::Pair("owner_address", ownerAddress.ToString()));
result.push_back(json_spirit::Pair("staker_address", stakerAddress.ToString()));
return result;
}
Result<CoinStakeDelegationResult, ColdStakeDelegationErrorCode>
CreateColdStakeDelegation(const std::string& stakeAddress, CAmount nValue,
const boost::optional<std::string>& ownerAddress, bool fForceExternalAddr,
bool fUseDelegated, bool fForceNotEnabled)
{
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!Params().IsColdStakingEnabled() && !fForceNotEnabled)
return Err(ColdStakingDisabled);
// Get Staking Address
CBitcoinAddress stakeAddr(stakeAddress);
CKeyID stakeKey;
if (!stakeAddr.IsValid())
return Err(InvalidStakerAddress);
if (!stakeAddr.GetKeyID(stakeKey))
return Err(StakerAddressPubKeyHashError);
// Get Amount
if (nValue < Params().MinColdStakingAmount())
return Err(InvalidAmount);
// Check amount
const CAmount currBalance =
pwalletMain->GetBalance() - (fUseDelegated ? 0 : pwalletMain->GetDelegatedBalance());
if (nValue > currBalance)
return Err(InsufficientBalance);
if (pwalletMain->IsLocked() || fWalletUnlockStakingOnly)
return Err(WalletLocked);
// Get Owner Address
CBitcoinAddress ownerAddr;
CKeyID ownerKey;
if (ownerAddress) {
// Address provided
ownerAddr.SetString(*ownerAddress);
if (!ownerAddr.IsValid())
return Err(InvalidOwnerAddress);
if (!ownerAddr.GetKeyID(ownerKey))
return Err(OwnerAddressPubKeyHashError);
// Check that the owner address belongs to this wallet, or fForceExternalAddr is true
if (!fForceExternalAddr && !pwalletMain->HaveKey(ownerKey)) {
return Err(OwnerAddressNotInWallet);
}
} else {
// Get new owner address from keypool
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
return Err(KeyPoolEmpty);
CKeyID keyID = newKey.GetID();
ownerAddr = CBitcoinAddress(keyID);
// set address book entry
if (pwalletMain) {
pwalletMain->SetAddressBookEntry(ownerAddr.Get(), "Delegator address");
}
if (!ownerAddr.GetKeyID(ownerKey))
return Err(GeneratedOwnerAddressPubKeyHashError);
}
CoinStakeDelegationResult result;
result.ownerAddress = ownerAddr;
result.stakerAddress = stakeAddr;
// Get P2CS script for addresses
result.scriptPubKey = GetScriptForStakeDelegation(stakeKey, ownerKey);
return Ok(result);
}
std::string ColdStakeDelegationErrorStr(const ColdStakeDelegationErrorCode errorCode)
{
switch (errorCode) {
case ColdStakingDisabled:
return "Cold Staking disabled. "
"You may force the stake delegation to true. "
"WARNING: If relayed before activation, this tx will be rejected resulting in a ban. ";
case InvalidStakerAddress:
return "Invalid staker address";
case StakerAddressPubKeyHashError:
return "Unable to get stake pubkey hash from stakingaddress";
case InvalidAmount:
return strprintf("Invalid amount. Min amount: %zd", Params().MinColdStakingAmount());
case InsufficientBalance:
return "Insufficient funds";
case WalletLocked:
return "Error: Please unlock the wallet first.";
case InvalidOwnerAddress:
return "Invalid neblio spending/owner address";
case OwnerAddressPubKeyHashError:
return "Unable to get spend pubkey hash from owneraddress";
case OwnerAddressNotInWallet:
return "The provided owneraddress is not present in this wallet.";
case KeyPoolEmpty:
return "Error: Keypool ran out, please call keypoolrefill first";
case GeneratedOwnerAddressPubKeyHashError:
return "Unable to get spend pubkey hash from owneraddress";
}
return "Unknown error";
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <cstdlib>
#include <iostream>
#include <libbio/assert.hh>
#include <libbio/dispatch.hh>
#include <unistd.h>
#include "cmdline.h"
#include "create_variant_graph.hh"
namespace lb = libbio;
namespace v2m = vcf2multialign;
int main(int argc, char **argv)
{
#ifndef NDEBUG
std::cerr << "Assertions have been enabled." << std::endl;
#endif
gengetopt_args_info args_info;
if (0 != cmdline_parser(argc, argv, &args_info))
std::exit(EXIT_FAILURE);
if (args_info.show_invocation_given)
{
std::cerr << "Invocation:";
for (int i(0); i < argc; ++i)
std::cerr << ' ' << argv[i];
std::cerr << '\n';
}
std::ios_base::sync_with_stdio(false); // Don't use C style IO after calling cmdline_parser.
std::cin.tie(nullptr); // We don't require any input from the user.
if (args_info.minimum_bridge_length_arg < 0)
{
std::cerr << "Minimum bridge length must be non-negative.\n";
std::exit(EXIT_FAILURE);
}
if (! (args_info.minimum_bridge_length_arg <= SIZE_MAX))
{
std::cerr << "Minimum bridge length must be less than or equal to " << SIZE_MAX << ".\n";
std::exit(EXIT_FAILURE);
}
try
{
if (args_info.cut_by_overlap_start_given)
{
std::vector <std::string> field_names_for_filter_if_set(args_info.filter_fields_set_given);
for (std::size_t i(0); i < args_info.filter_fields_set_given; ++i)
field_names_for_filter_if_set[i] = args_info.filter_fields_set_arg[i];
v2m::create_variant_graph_single_pass(
args_info.reference_arg,
args_info.variants_arg,
args_info.output_arg,
args_info.log_arg,
args_info.minimum_bridge_length_arg,
args_info.reference_sequence_given ? args_info.reference_sequence_arg : nullptr,
args_info.chromosome_arg,
std::move(field_names_for_filter_if_set),
args_info.overwrite_flag
);
}
else if (args_info.cut_by_precalculated_given)
{
v2m::create_variant_graph_preprocessed(
args_info.reference_arg,
args_info.variants_arg,
args_info.cut_positions_arg,
args_info.output_arg,
args_info.reference_sequence_given ? args_info.reference_sequence_arg : nullptr,
args_info.overwrite_flag
);
}
else
{
std::cerr << "ERROR: No mode given.\n";
std::exit(EXIT_FAILURE);
}
}
catch (lb::assertion_failure_exception const &exc)
{
std::cerr << "Assertion failure: " << exc.what() << '\n';
boost::stacktrace::stacktrace const *st(boost::get_error_info <lb::traced>(exc));
if (st)
std::cerr << "Stack trace:\n" << *st << '\n';
throw exc;
}
dispatch_main();
// Not reached.
return EXIT_SUCCESS;
}
<commit_msg>Move exception handler from main()<commit_after>/*
* Copyright (c) 2019 Tuukka Norri
* This code is licensed under MIT license (see LICENSE for details).
*/
#include <cstdlib>
#include <iostream>
#include <libbio/assert.hh>
#include <libbio/dispatch.hh>
#include <unistd.h>
#include "cmdline.h"
#include "create_variant_graph.hh"
namespace lb = libbio;
namespace v2m = vcf2multialign;
namespace {
void do_process(gengetopt_args_info const &args_info)
{
if (args_info.minimum_bridge_length_arg < 0)
{
std::cerr << "Minimum bridge length must be non-negative.\n";
std::exit(EXIT_FAILURE);
}
if (! (args_info.minimum_bridge_length_arg <= SIZE_MAX))
{
std::cerr << "Minimum bridge length must be less than or equal to " << SIZE_MAX << ".\n";
std::exit(EXIT_FAILURE);
}
try
{
if (args_info.cut_by_overlap_start_given)
{
std::vector <std::string> field_names_for_filter_if_set(args_info.filter_fields_set_given);
for (std::size_t i(0); i < args_info.filter_fields_set_given; ++i)
field_names_for_filter_if_set[i] = args_info.filter_fields_set_arg[i];
v2m::create_variant_graph_single_pass(
args_info.reference_arg,
args_info.variants_arg,
args_info.output_arg,
args_info.log_arg,
args_info.minimum_bridge_length_arg,
args_info.reference_sequence_given ? args_info.reference_sequence_arg : nullptr,
args_info.chromosome_arg,
std::move(field_names_for_filter_if_set),
args_info.overwrite_flag
);
}
else if (args_info.cut_by_precalculated_given)
{
v2m::create_variant_graph_preprocessed(
args_info.reference_arg,
args_info.variants_arg,
args_info.cut_positions_arg,
args_info.output_arg,
args_info.reference_sequence_given ? args_info.reference_sequence_arg : nullptr,
args_info.overwrite_flag
);
}
else
{
std::cerr << "ERROR: No mode given.\n";
std::exit(EXIT_FAILURE);
}
}
catch (lb::assertion_failure_exception const &exc)
{
std::cerr << "Assertion failure: " << exc.what() << '\n';
boost::stacktrace::stacktrace const *st(boost::get_error_info <lb::traced>(exc));
if (st)
std::cerr << "Stack trace:\n" << *st << '\n';
throw exc;
}
}
}
int main(int argc, char **argv)
{
#ifndef NDEBUG
std::cerr << "Assertions have been enabled." << std::endl;
#endif
gengetopt_args_info args_info;
if (0 != cmdline_parser(argc, argv, &args_info))
std::exit(EXIT_FAILURE);
if (args_info.show_invocation_given)
{
std::cerr << "Invocation:";
for (int i(0); i < argc; ++i)
std::cerr << ' ' << argv[i];
std::cerr << '\n';
}
std::ios_base::sync_with_stdio(false); // Don't use C style IO after calling cmdline_parser.
std::cin.tie(nullptr); // We don't require any input from the user.
// The try-catch-block in do_process somehow messes up the call to dispatch_main
// resulting in “terminate called without an active exception” and thus cannot be located in main().
do_process(args_info);
dispatch_main();
// Not reached.
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdotxln.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2006-06-19 16:45:06 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#ifndef _UCBHELPER_CONTENT_HXX_
#include <ucbhelper/content.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX_
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UNOTOOLS_DATETIME_HXX_
#include <unotools/datetime.hxx>
#endif
#include "svdotext.hxx"
#include "svditext.hxx"
#include "svdmodel.hxx"
#include "svdio.hxx"
#include "editdata.hxx"
#ifndef SVX_LIGHT
#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif
#endif
#ifndef _SVXLINKMGR_HXX //autogen
#include <linkmgr.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#include <svtools/urihelper.hxx>
// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
#ifndef SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@ @@@@@ @@@@@@ @@@@@@ @@@@@@ @@ @@ @@@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@@@@@ @@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@ @@@ @@ @@
// @@@@ @@@@@ @@@@ @@ @@@@@@ @@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
// ImpSdrObjTextLink zur Verbindung von SdrTextObj und LinkManager
//
// Einem solchen Link merke ich mir als SdrObjUserData am Objekt. Im Gegensatz
// zum Grafik-Link werden die ObjektDaten jedoch kopiert (fuer Paint, etc.).
// Die Information ob das Objekt ein Link ist besteht genau darin, dass dem
// Objekt ein entsprechender UserData-Record angehaengt ist oder nicht.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
class ImpSdrObjTextLink: public ::sfx2::SvBaseLink
{
SdrTextObj* pSdrObj;
public:
ImpSdrObjTextLink( SdrTextObj* pObj1 )
: ::sfx2::SvBaseLink( ::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE ),
pSdrObj( pObj1 )
{}
virtual ~ImpSdrObjTextLink();
virtual void Closed();
virtual void DataChanged( const String& rMimeType,
const ::com::sun::star::uno::Any & rValue );
BOOL Connect() { return 0 != SvBaseLink::GetRealObject(); }
};
ImpSdrObjTextLink::~ImpSdrObjTextLink()
{
}
void ImpSdrObjTextLink::Closed()
{
if (pSdrObj )
{
// pLink des Objekts auf NULL setzen, da die Link-Instanz ja gerade destruiert wird.
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if (pData!=NULL) pData->pLink=NULL;
pSdrObj->ReleaseTextLink();
}
SvBaseLink::Closed();
}
void ImpSdrObjTextLink::DataChanged( const String& /*rMimeType*/,
const ::com::sun::star::uno::Any & /*rValue */)
{
FASTBOOL bForceReload=FALSE;
SdrModel* pModel = pSdrObj ? pSdrObj->GetModel() : 0;
SvxLinkManager* pLinkManager= pModel ? pModel->GetLinkManager() : 0;
if( pLinkManager )
{
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if( pData )
{
String aFile;
String aFilter;
pLinkManager->GetDisplayNames( this, 0,&aFile, 0, &aFilter );
if( !pData->aFileName.Equals( aFile ) ||
!pData->aFilterName.Equals( aFilter ))
{
pData->aFileName = aFile;
pData->aFilterName = aFilter;
pSdrObj->SetChanged();
bForceReload = TRUE;
}
}
}
if (pSdrObj )
pSdrObj->ReloadLinkedText( bForceReload );
}
#endif // SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@@ @@@@@@ @@@@@ @@@@@ @@@@ @@@@@@ @@@@
// @@ @@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@@ @@@@ @@ @@ @@@@ @@@@@ @@@@@ @@ @@ @@@@@@ @@ @@@@@@
// @@ @@ @@ @@@ @@@@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@@@@ @@ @@ @@ @@ @@ @@@@ @@@@@ @@@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TYPEINIT1(ImpSdrObjTextLinkUserData,SdrObjUserData);
ImpSdrObjTextLinkUserData::ImpSdrObjTextLinkUserData(SdrTextObj* pObj1):
SdrObjUserData(SdrInventor,SDRUSERDATA_OBJTEXTLINK,0),
pObj(pObj1),
pLink(NULL),
eCharSet(RTL_TEXTENCODING_DONTKNOW)
{
}
ImpSdrObjTextLinkUserData::~ImpSdrObjTextLinkUserData()
{
#ifndef SVX_LIGHT
delete pLink;
#endif
}
SdrObjUserData* ImpSdrObjTextLinkUserData::Clone(SdrObject* pObj1) const
{
ImpSdrObjTextLinkUserData* pData=new ImpSdrObjTextLinkUserData((SdrTextObj*)pObj1);
pData->aFileName =aFileName;
pData->aFilterName=aFilterName;
pData->aFileDate0 =aFileDate0;
pData->eCharSet =eCharSet;
pData->pLink=NULL;
return pData;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@@@ @@@@@ @@ @@ @@@@@@ @@@@ @@@@@ @@@@@@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@@@ @@@ @@ @@ @@ @@@@@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@
// @@ @@@@@ @@ @@ @@ @@@@ @@@@@ @@@@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
void SdrTextObj::SetTextLink(const String& rFileName, const String& rFilterName, rtl_TextEncoding eCharSet)
{
if(eCharSet == RTL_TEXTENCODING_DONTKNOW)
eCharSet = gsl_getSystemTextEncoding();
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
if (pData!=NULL) {
ReleaseTextLink();
}
pData=new ImpSdrObjTextLinkUserData(this);
pData->aFileName=rFileName;
pData->aFilterName=rFilterName;
pData->eCharSet=eCharSet;
InsertUserData(pData);
ImpLinkAnmeldung();
}
void SdrTextObj::ReleaseTextLink()
{
ImpLinkAbmeldung();
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData* pData=GetUserData(nNum);
if (pData->GetInventor()==SdrInventor && pData->GetId()==SDRUSERDATA_OBJTEXTLINK) {
DeleteUserData(nNum);
}
}
}
FASTBOOL SdrTextObj::ReloadLinkedText( FASTBOOL bForceLoad)
{
ImpSdrObjTextLinkUserData* pData = GetLinkUserData();
FASTBOOL bRet = TRUE;
if( pData )
{
::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();
DateTime aFileDT;
BOOL bExists = FALSE, bLoad = FALSE;
if( pBroker )
{
bExists = TRUE;
try
{
INetURLObject aURL( pData->aFileName );
DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
::ucb::Content aCnt( aURL.GetMainURL( INetURLObject::NO_DECODE ), ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );
::com::sun::star::uno::Any aAny( aCnt.getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DateModified" ) ) ) );
::com::sun::star::util::DateTime aDateTime;
aAny >>= aDateTime;
::utl::typeConvert( aDateTime, aFileDT );
}
catch( ... )
{
bExists = FALSE;
}
}
if( bExists )
{
if( bForceLoad )
bLoad = TRUE;
else
bLoad = ( aFileDT > pData->aFileDate0 );
if( bLoad )
{
bRet = LoadText( pData->aFileName, pData->aFilterName, pData->eCharSet );
}
pData->aFileDate0 = aFileDT;
}
}
return bRet;
}
FASTBOOL SdrTextObj::LoadText(const String& rFileName, const String& /*rFilterName*/, rtl_TextEncoding eCharSet)
{
INetURLObject aFileURL( rFileName );
BOOL bRet = FALSE;
if( aFileURL.GetProtocol() == INET_PROT_NOT_VALID )
{
String aFileURLStr;
if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( rFileName, aFileURLStr ) )
aFileURL = INetURLObject( aFileURLStr );
else
aFileURL.SetSmartURL( rFileName );
}
DBG_ASSERT( aFileURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( aFileURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ );
if( pIStm )
{
// #90477# pIStm->SetStreamCharSet( eCharSet );
pIStm->SetStreamCharSet(GetSOLoadTextEncoding(eCharSet, (sal_uInt16)pIStm->GetVersion()));
char cRTF[5];
cRTF[4] = 0;
pIStm->Read(cRTF, 5);
BOOL bRTF = cRTF[0] == '{' && cRTF[1] == '\\' && cRTF[2] == 'r' && cRTF[3] == 't' && cRTF[4] == 'f';
pIStm->Seek(0);
if( !pIStm->GetError() )
{
SetText( *pIStm, aFileURL.GetMainURL( INetURLObject::NO_DECODE ), bRTF ? EE_FORMAT_RTF : EE_FORMAT_TEXT );
bRet = TRUE;
}
delete pIStm;
}
return bRet;
}
ImpSdrObjTextLinkUserData* SdrTextObj::GetLinkUserData() const
{
ImpSdrObjTextLinkUserData* pData=NULL;
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0 && pData==NULL;) {
nNum--;
pData=(ImpSdrObjTextLinkUserData*)GetUserData(nNum);
if (pData->GetInventor()!=SdrInventor || pData->GetId()!=SDRUSERDATA_OBJTEXTLINK) {
pData=NULL;
}
}
return pData;
}
void SdrTextObj::ImpLinkAnmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink==NULL) { // Nicht 2x Anmelden
pData->pLink=new ImpSdrObjTextLink(this);
#ifdef GCC
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ?
&pData->aFilterName : (const String *)NULL,
(const String *)NULL);
#else
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ? &pData->aFilterName : NULL,NULL);
#endif
pData->pLink->Connect();
}
#endif // SVX_LIGHT
}
void SdrTextObj::ImpLinkAbmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink!=NULL) { // Nicht 2x Abmelden
// Bei Remove wird *pLink implizit deleted
pLinkManager->Remove( pData->pLink );
pData->pLink=NULL;
}
#endif // SVX_LIGHT
}
<commit_msg>INTEGRATION: CWS rt16 (1.11.86); FILE MERGED 2006/08/07 12:14:38 rt 1.11.86.1: #i68214# Remove empty file<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdotxln.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2006-08-29 14:42:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/localfilehelper.hxx>
#ifndef _UCBHELPER_CONTENT_HXX_
#include <ucbhelper/content.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX_
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UNOTOOLS_DATETIME_HXX_
#include <unotools/datetime.hxx>
#endif
#include "svdotext.hxx"
#include "svditext.hxx"
#include "svdmodel.hxx"
#include "editdata.hxx"
#ifndef SVX_LIGHT
#ifndef _LNKBASE_HXX //autogen
#include <sfx2/lnkbase.hxx>
#endif
#endif
#ifndef _SVXLINKMGR_HXX //autogen
#include <linkmgr.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#include <svtools/urihelper.hxx>
// #90477#
#ifndef _TOOLS_TENCCVT_HXX
#include <tools/tenccvt.hxx>
#endif
#ifndef SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@ @@@@@ @@@@@@ @@@@@@ @@@@@@ @@ @@ @@@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@@@@@ @@@@
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@ @@ @@ @@ @@ @@@ @@ @@
// @@@@ @@@@@ @@@@ @@ @@@@@@ @@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
// ImpSdrObjTextLink zur Verbindung von SdrTextObj und LinkManager
//
// Einem solchen Link merke ich mir als SdrObjUserData am Objekt. Im Gegensatz
// zum Grafik-Link werden die ObjektDaten jedoch kopiert (fuer Paint, etc.).
// Die Information ob das Objekt ein Link ist besteht genau darin, dass dem
// Objekt ein entsprechender UserData-Record angehaengt ist oder nicht.
//
////////////////////////////////////////////////////////////////////////////////////////////////////
class ImpSdrObjTextLink: public ::sfx2::SvBaseLink
{
SdrTextObj* pSdrObj;
public:
ImpSdrObjTextLink( SdrTextObj* pObj1 )
: ::sfx2::SvBaseLink( ::sfx2::LINKUPDATE_ONCALL, FORMAT_FILE ),
pSdrObj( pObj1 )
{}
virtual ~ImpSdrObjTextLink();
virtual void Closed();
virtual void DataChanged( const String& rMimeType,
const ::com::sun::star::uno::Any & rValue );
BOOL Connect() { return 0 != SvBaseLink::GetRealObject(); }
};
ImpSdrObjTextLink::~ImpSdrObjTextLink()
{
}
void ImpSdrObjTextLink::Closed()
{
if (pSdrObj )
{
// pLink des Objekts auf NULL setzen, da die Link-Instanz ja gerade destruiert wird.
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if (pData!=NULL) pData->pLink=NULL;
pSdrObj->ReleaseTextLink();
}
SvBaseLink::Closed();
}
void ImpSdrObjTextLink::DataChanged( const String& /*rMimeType*/,
const ::com::sun::star::uno::Any & /*rValue */)
{
FASTBOOL bForceReload=FALSE;
SdrModel* pModel = pSdrObj ? pSdrObj->GetModel() : 0;
SvxLinkManager* pLinkManager= pModel ? pModel->GetLinkManager() : 0;
if( pLinkManager )
{
ImpSdrObjTextLinkUserData* pData=pSdrObj->GetLinkUserData();
if( pData )
{
String aFile;
String aFilter;
pLinkManager->GetDisplayNames( this, 0,&aFile, 0, &aFilter );
if( !pData->aFileName.Equals( aFile ) ||
!pData->aFilterName.Equals( aFilter ))
{
pData->aFileName = aFile;
pData->aFilterName = aFilter;
pSdrObj->SetChanged();
bForceReload = TRUE;
}
}
}
if (pSdrObj )
pSdrObj->ReloadLinkedText( bForceReload );
}
#endif // SVX_LIGHT
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@ @@ @@ @@ @@ @@ @@ @@ @@@@@ @@@@@@ @@@@@ @@@@@ @@@@ @@@@@@ @@@@
// @@ @@ @@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@@ @@@@ @@ @@ @@@@ @@@@@ @@@@@ @@ @@ @@@@@@ @@ @@@@@@
// @@ @@ @@ @@@ @@@@@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@ @@
// @@@@@ @@ @@ @@ @@ @@ @@@@ @@@@@ @@@@@@ @@ @@ @@@@@ @@ @@ @@ @@ @@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
TYPEINIT1(ImpSdrObjTextLinkUserData,SdrObjUserData);
ImpSdrObjTextLinkUserData::ImpSdrObjTextLinkUserData(SdrTextObj* pObj1):
SdrObjUserData(SdrInventor,SDRUSERDATA_OBJTEXTLINK,0),
pObj(pObj1),
pLink(NULL),
eCharSet(RTL_TEXTENCODING_DONTKNOW)
{
}
ImpSdrObjTextLinkUserData::~ImpSdrObjTextLinkUserData()
{
#ifndef SVX_LIGHT
delete pLink;
#endif
}
SdrObjUserData* ImpSdrObjTextLinkUserData::Clone(SdrObject* pObj1) const
{
ImpSdrObjTextLinkUserData* pData=new ImpSdrObjTextLinkUserData((SdrTextObj*)pObj1);
pData->aFileName =aFileName;
pData->aFilterName=aFilterName;
pData->aFileDate0 =aFileDate0;
pData->eCharSet =eCharSet;
pData->pLink=NULL;
return pData;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//
// @@@@@@ @@@@@ @@ @@ @@@@@@ @@@@ @@@@@ @@@@@@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@@@ @@@ @@ @@ @@ @@@@@ @@
// @@ @@ @@@@@ @@ @@ @@ @@ @@ @@
// @@ @@ @@@ @@@ @@ @@ @@ @@ @@ @@ @@
// @@ @@@@@ @@ @@ @@ @@@@ @@@@@ @@@@
//
////////////////////////////////////////////////////////////////////////////////////////////////////
void SdrTextObj::SetTextLink(const String& rFileName, const String& rFilterName, rtl_TextEncoding eCharSet)
{
if(eCharSet == RTL_TEXTENCODING_DONTKNOW)
eCharSet = gsl_getSystemTextEncoding();
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
if (pData!=NULL) {
ReleaseTextLink();
}
pData=new ImpSdrObjTextLinkUserData(this);
pData->aFileName=rFileName;
pData->aFilterName=rFilterName;
pData->eCharSet=eCharSet;
InsertUserData(pData);
ImpLinkAnmeldung();
}
void SdrTextObj::ReleaseTextLink()
{
ImpLinkAbmeldung();
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0;) {
nNum--;
SdrObjUserData* pData=GetUserData(nNum);
if (pData->GetInventor()==SdrInventor && pData->GetId()==SDRUSERDATA_OBJTEXTLINK) {
DeleteUserData(nNum);
}
}
}
FASTBOOL SdrTextObj::ReloadLinkedText( FASTBOOL bForceLoad)
{
ImpSdrObjTextLinkUserData* pData = GetLinkUserData();
FASTBOOL bRet = TRUE;
if( pData )
{
::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();
DateTime aFileDT;
BOOL bExists = FALSE, bLoad = FALSE;
if( pBroker )
{
bExists = TRUE;
try
{
INetURLObject aURL( pData->aFileName );
DBG_ASSERT( aURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
::ucb::Content aCnt( aURL.GetMainURL( INetURLObject::NO_DECODE ), ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );
::com::sun::star::uno::Any aAny( aCnt.getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "DateModified" ) ) ) );
::com::sun::star::util::DateTime aDateTime;
aAny >>= aDateTime;
::utl::typeConvert( aDateTime, aFileDT );
}
catch( ... )
{
bExists = FALSE;
}
}
if( bExists )
{
if( bForceLoad )
bLoad = TRUE;
else
bLoad = ( aFileDT > pData->aFileDate0 );
if( bLoad )
{
bRet = LoadText( pData->aFileName, pData->aFilterName, pData->eCharSet );
}
pData->aFileDate0 = aFileDT;
}
}
return bRet;
}
FASTBOOL SdrTextObj::LoadText(const String& rFileName, const String& /*rFilterName*/, rtl_TextEncoding eCharSet)
{
INetURLObject aFileURL( rFileName );
BOOL bRet = FALSE;
if( aFileURL.GetProtocol() == INET_PROT_NOT_VALID )
{
String aFileURLStr;
if( ::utl::LocalFileHelper::ConvertPhysicalNameToURL( rFileName, aFileURLStr ) )
aFileURL = INetURLObject( aFileURLStr );
else
aFileURL.SetSmartURL( rFileName );
}
DBG_ASSERT( aFileURL.GetProtocol() != INET_PROT_NOT_VALID, "invalid URL" );
SvStream* pIStm = ::utl::UcbStreamHelper::CreateStream( aFileURL.GetMainURL( INetURLObject::NO_DECODE ), STREAM_READ );
if( pIStm )
{
// #90477# pIStm->SetStreamCharSet( eCharSet );
pIStm->SetStreamCharSet(GetSOLoadTextEncoding(eCharSet, (sal_uInt16)pIStm->GetVersion()));
char cRTF[5];
cRTF[4] = 0;
pIStm->Read(cRTF, 5);
BOOL bRTF = cRTF[0] == '{' && cRTF[1] == '\\' && cRTF[2] == 'r' && cRTF[3] == 't' && cRTF[4] == 'f';
pIStm->Seek(0);
if( !pIStm->GetError() )
{
SetText( *pIStm, aFileURL.GetMainURL( INetURLObject::NO_DECODE ), bRTF ? EE_FORMAT_RTF : EE_FORMAT_TEXT );
bRet = TRUE;
}
delete pIStm;
}
return bRet;
}
ImpSdrObjTextLinkUserData* SdrTextObj::GetLinkUserData() const
{
ImpSdrObjTextLinkUserData* pData=NULL;
USHORT nAnz=GetUserDataCount();
for (USHORT nNum=nAnz; nNum>0 && pData==NULL;) {
nNum--;
pData=(ImpSdrObjTextLinkUserData*)GetUserData(nNum);
if (pData->GetInventor()!=SdrInventor || pData->GetId()!=SDRUSERDATA_OBJTEXTLINK) {
pData=NULL;
}
}
return pData;
}
void SdrTextObj::ImpLinkAnmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink==NULL) { // Nicht 2x Anmelden
pData->pLink=new ImpSdrObjTextLink(this);
#ifdef GCC
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ?
&pData->aFilterName : (const String *)NULL,
(const String *)NULL);
#else
pLinkManager->InsertFileLink(*pData->pLink,OBJECT_CLIENT_FILE,pData->aFileName,
pData->aFilterName.Len() ? &pData->aFilterName : NULL,NULL);
#endif
pData->pLink->Connect();
}
#endif // SVX_LIGHT
}
void SdrTextObj::ImpLinkAbmeldung()
{
#ifndef SVX_LIGHT
ImpSdrObjTextLinkUserData* pData=GetLinkUserData();
SvxLinkManager* pLinkManager=pModel!=NULL ? pModel->GetLinkManager() : NULL;
if (pLinkManager!=NULL && pData!=NULL && pData->pLink!=NULL) { // Nicht 2x Abmelden
// Bei Remove wird *pLink implizit deleted
pLinkManager->Remove( pData->pLink );
pData->pLink=NULL;
}
#endif // SVX_LIGHT
}
<|endoftext|> |
<commit_before>/*
* Game.cpp
*
* Created on: 29 May 2014
* Author: Marco
*/
#include "Game.hpp"
GameDelta GameDelta::mergeDelta(const GameDelta &newDelta) const {
GameDelta delta(*this);
for (std::map<Entity, Position>::const_iterator it = newDelta.deltaPositions.begin();
it != newDelta.deltaPositions.end();
it++)
{
// add position updates
delta.deltaPositions[it->first] += (it->second);
}
for (std::map<Entity, Orientation>::const_iterator it = newDelta.deltaOrientations.begin();
it != newDelta.deltaOrientations.end();
it++)
{
delta.deltaOrientations[it->first] += (it->second);
}
return delta;
}
GameDelta::GameDelta(const GameDelta &src)
{
deltaPositions = src.deltaPositions;
deltaOrientations = src.deltaOrientations;
deltaBoundingBoxes = src.deltaBoundingBoxes;
deltaRenderObjects = src.deltaRenderObjects;
}
GameDelta::GameDelta(Entity entity, Position pos) :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects()
{
deltaPositions[entity] = pos;
}
GameDelta::GameDelta(Entity entity, Orientation orientation) :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects()
{
deltaOrientations[entity] = orientation;
}
GameDelta::GameDelta(Entity entity, BoundingBox bb) :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects()
{
deltaBoundingBoxes[entity] = bb;
}
GameDelta Game::loadMap(const Worldmap& world) const
{
GameDelta delta;
for (int y = 0; y < 42; y++) {
for (int x = 0; x < 42; x++) {
Block *block = world.getBlock(x, y);
Entity new_entity = Entity::newEntity();
delta = delta.mergeDelta(GameDelta(new_entity, Position(-1, x, y)));
delta = delta.mergeDelta(GameDelta(new_entity, Orientation(0)));
std::vector<std::string> textures;
int count = block->getTextures(textures);
for (int i = 0; i < count; i++) {
// create RenderObjects
}
}
return delta;
}
void Game::setup()
{
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
}
int Game::getCurrentPlayer()
{
return m_currentPlayer;
}
Entity Game::getPlayerByID(int id)
{
return m_players[id] ;
}
Game::Game() :
m_currentState(GameState()), m_currentPlayer(0)
{
// TODO Auto-generated constructor stub
}
Game::~Game() {
// TODO Auto-generated destructor stub
}
<commit_msg>fixed compile error after merge<commit_after>/*
* Game.cpp
*
* Created on: 29 May 2014
* Author: Marco
*/
#include "Game.hpp"
GameDelta GameDelta::mergeDelta(const GameDelta &newDelta) const {
GameDelta delta(*this);
for (std::map<Entity, Position>::const_iterator it = newDelta.deltaPositions.begin();
it != newDelta.deltaPositions.end();
it++)
{
// add position updates
delta.deltaPositions[it->first] += (it->second);
}
for (std::map<Entity, Orientation>::const_iterator it = newDelta.deltaOrientations.begin();
it != newDelta.deltaOrientations.end();
it++)
{
delta.deltaOrientations[it->first] += (it->second);
}
return delta;
}
GameDelta::GameDelta(const GameDelta &src)
{
deltaPositions = src.deltaPositions;
deltaOrientations = src.deltaOrientations;
deltaBoundingBoxes = src.deltaBoundingBoxes;
deltaRenderObjects = src.deltaRenderObjects;
}
GameDelta::GameDelta(Entity entity, Position pos) :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects()
{
deltaPositions[entity] = pos;
}
GameDelta::GameDelta(Entity entity, Orientation orientation) :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects()
{
deltaOrientations[entity] = orientation;
}
GameDelta::GameDelta(Entity entity, BoundingBox bb) :
deltaPositions(),
deltaOrientations(),
deltaBoundingBoxes(),
deltaRenderObjects()
{
deltaBoundingBoxes[entity] = bb;
}
GameDelta Game::loadMap(const Worldmap& world) const
{
GameDelta delta;
for (int y = 0; y < 42; y++) {
for (int x = 0; x < 42; x++) {
Block *block = world.getBlock(x, y);
Entity new_entity = Entity::newEntity();
delta = delta.mergeDelta(GameDelta(new_entity, Position(-1, x, y)));
delta = delta.mergeDelta(GameDelta(new_entity, Orientation(0)));
std::vector<std::string> textures;
int count = block->getTextures(textures);
for (int i = 0; i < count; i++) {
// create RenderObjects
}
}
}
return delta;
}
void Game::setup()
{
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
m_players.push_back(Entity::newEntity());
m_player_map.push_back(Worldmap(time(NULL), 60, 60, 5));
}
int Game::getCurrentPlayer()
{
return m_currentPlayer;
}
Entity Game::getPlayerByID(int id)
{
return m_players[id] ;
}
Game::Game() :
m_currentState(GameState()), m_currentPlayer(0)
{
// TODO Auto-generated constructor stub
}
Game::~Game() {
// TODO Auto-generated destructor stub
}
<|endoftext|> |
<commit_before>inline
cov_mat_kth::cov_mat_kth( const std::string in_path,
const std::string in_actionNames,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_segment_length
)
:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length)
{
actions.load( actionNames );
}
inline
void
cov_mat_kth::calculate( field<string> in_all_people, int in_dim )
{
all_people = in_all_people;
dim = in_dim;
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//all_people.print("people");
for (int sc = 1; sc<=1; ++sc) //scene
{
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
std::stringstream load_folder;
std::stringstream load_feat_video_i;
std::stringstream load_labels_video_i;
cout << "Loading.." << endl;
load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
//For one Video
cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act );
getchar();
}
}
}
}
inline
void
cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act )
{
mat mat_features_video_i;
vec lab_video_i;
mat_features_video_i.load( load_feat_video_i, raw_ascii );
lab_video_i.load( load_labels_video_i, raw_ascii );
int n_vec = lab_video_i.n_elem;
int last = lab_video_i( n_vec - 1 );
cout << last << endl;
int s = 0;
std::stringstream save_folder;
save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
for (int l=2; l<last-segment_length; l = l+4 )
{
running_stat_vec<rowvec> stat_seg(true);
//int k =0;
cout << " " << l;
for (int j=l; j<=segment_length+1; ++j)
{
//k++;
uvec indices = find(lab_video_i == j);
mat tmp_feat = mat_features_video_i.cols(indices);
//cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl;
for (int v=0; v < tmp_feat.n_cols; ++v)
{
vec sample = tmp_feat.col(v);
stat_seg (sample);
}
}
std::stringstream save_cov_seg;
save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
mat cov_seg_i = stat_seg.cov();
cov_seg_i.save( save_cov_seg.str(), raw_ascii );
s++;
}
std::stringstream save_seg;
vec total_seg;
total_seg.zeros(1);
total_seg( 0 ) = s;
save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.save( save_seg.str(), raw_ascii );
}
<commit_msg>First try<commit_after>inline
cov_mat_kth::cov_mat_kth( const std::string in_path,
const std::string in_actionNames,
const int in_scale_factor,
const int in_shift,
const int in_scene, //only for kth
const int in_segment_length
)
:path(in_path), actionNames(in_actionNames), scale_factor(in_scale_factor), shift(in_shift), scene(in_scene), segment_length(in_segment_length)
{
actions.load( actionNames );
}
inline
void
cov_mat_kth::calculate( field<string> in_all_people, int in_dim )
{
all_people = in_all_people;
dim = in_dim;
int n_actions = actions.n_rows;
int n_peo = all_people.n_rows;
//all_people.print("people");
for (int sc = 1; sc<=1; ++sc) //scene
{
for (int pe = 0; pe< n_peo; ++pe)
{
for (int act=0; act<n_actions; ++act)
{
std::stringstream load_folder;
std::stringstream load_feat_video_i;
std::stringstream load_labels_video_i;
cout << "Loading.." << endl;
load_folder << path << "/kth-features/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
load_feat_video_i << load_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
load_labels_video_i << load_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
//For one Video
cov_mat_kth::one_video(load_feat_video_i.str(), load_labels_video_i.str(), sc, pe, act );
//getchar();
}
}
}
}
inline
void
cov_mat_kth::one_video( std::string load_feat_video_i, std::string load_labels_video_i, int sc, int pe, int act )
{
mat mat_features_video_i;
vec lab_video_i;
mat_features_video_i.load( load_feat_video_i, raw_ascii );
lab_video_i.load( load_labels_video_i, raw_ascii );
int n_vec = lab_video_i.n_elem;
int last = lab_video_i( n_vec - 1 );
//cout << last << endl;
int s = 0;
std::stringstream save_folder;
save_folder << "./kth-cov-mat/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ;
for (int l=2; l<last-segment_length; l = l+4 )
{
running_stat_vec<rowvec> stat_seg(true);
//int k =0;
//cout << " " << l;
for (int j=l; j<=segment_length+1; ++j)
{
//k++;
uvec indices = find(lab_video_i == j);
mat tmp_feat = mat_features_video_i.cols(indices);
//cout << "row&col " << tmp_feat.n_rows << " & " << tmp_feat.n_cols << endl;
for (int v=0; v < tmp_feat.n_cols; ++v)
{
vec sample = tmp_feat.col(v);
stat_seg (sample);
}
}
std::stringstream save_cov_seg;
save_cov_seg << save_folder.str() << "/cov_seg" << s << "_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
mat cov_seg_i = stat_seg.cov();
cov_seg_i.save( save_cov_seg.str(), raw_ascii );
s++;
}
std::stringstream save_seg;
vec total_seg;
total_seg.zeros(1);
total_seg( 0 ) = s;
save_seg << save_folder.str() << "/num_seg_"<< all_people (pe) << "_" << actions(act) << "_dim" << dim << ".dat";
total_seg.save( save_seg.str(), raw_ascii );
}
<|endoftext|> |
<commit_before><commit_msg>CID#1103739 unintialized members<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: callnk.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-19 00:08:16 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FMTCNTNT_HXX //autogen
#include <fmtcntnt.hxx>
#endif
#ifndef _TXATBASE_HXX //autogen
#include <txatbase.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _VISCRS_HXX
#include <viscrs.hxx>
#endif
#ifndef _CALLNK_HXX
#include <callnk.hxx>
#endif
#ifndef _CRSRSH_HXX
#include <crsrsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _TXTFRM_HXX
#include <txtfrm.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _FLYFRM_HXX
#include <flyfrm.hxx>
#endif
SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// SPoint-Werte vom aktuellen Cursor merken
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
if( ND_TEXTNODE & nNdTyp )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// eine Sonderbehandlung fuer die SwFeShell: diese setzt beim Loeschen
// der Kopf-/Fusszeile, Fussnoten den Cursor auf NULL (Node + Content)
// steht der Cursor auf keinem CntntNode, wird sich das im NdType
// gespeichert.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.bCallChgLnk ) // siehe ctor
return ;
// wird ueber Nodes getravellt, Formate ueberpruefen und im neuen
// Node wieder anmelden
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
USHORT nNdWhich = pCNd->GetNodeType();
ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// melde die Shell beim akt. Node als abhaengig an, dadurch koennen
// alle Attribut-Aenderungen ueber den Link weiter gemeldet werden.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
/* immer, wenn zwischen Nodes gesprungen wird, kann es
* vorkommen, das neue Attribute gelten; die Text-Attribute.
* Es muesste also festgestellt werden, welche Attribute
* jetzt gelten; das kann auch gleich der Handler machen
*/
rShell.CallChgLnk();
}
else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// nur wenn mit Left/right getravellt, dann Text-Hints pruefen
// und sich nicht der Frame geaendert hat (Spalten!)
if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & Sele
++nCmp;
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
USHORT n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// nur Start oder Start und Ende gleich, dann immer
// beim Ueberlaufen von Start callen
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// hat das Attribut einen Bereich und dieser nicht leer
else if( pEnd && nStart < *pEnd &&
// dann teste, ob ueber Start/Ende getravellt wurde
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
}
else
/* wenn mit Home/End/.. mehr als 1 Zeichen getravellt, dann
* immer den ChgLnk rufen, denn es kann hier nicht
* festgestellt werden, was sich geaendert; etwas kann
* veraendert sein.
*/
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
ASSERT( pIndex, "Fly ohne Cntnt" );
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
/*---------------------------------------------------------------------*/
SwChgLinkFlag::SwChgLinkFlag( SwCrsrShell& rShell )
: rCrsrShell( rShell ), bOldFlag( rShell.bCallChgLnk ), nLeftFrmPos( 0 )
{
rCrsrShell.bCallChgLnk = FALSE;
if( bOldFlag && !rCrsrShell.pTblCrsr )
{
SwNode* pNd = rCrsrShell.pCurCrsr->GetNode();
if( ND_TEXTNODE & pNd->GetNodeType() )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)*pNd,
rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(),
!rCrsrShell.ActionPend() );
}
}
SwChgLinkFlag::~SwChgLinkFlag()
{
rCrsrShell.bCallChgLnk = bOldFlag;
if( bOldFlag && !rCrsrShell.pTblCrsr )
{
// die Spalten Ueberwachung brauchen wir immer!!!
SwNode* pNd = rCrsrShell.pCurCrsr->GetNode();
if( ND_TEXTNODE & pNd->GetNodeType() &&
nLeftFrmPos != SwCallLink::GetFrm( (SwTxtNode&)*pNd,
rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(),
!rCrsrShell.ActionPend() ))
{
/* immer, wenn zwischen Frames gesprungen wird, gelten
* neue Attribute. Es muesste also festgestellt werden, welche
* Attribute jetzt gelten; das kann gleich der Handler machen.
* Diesen direkt rufen !!!
*/
rCrsrShell.aChgLnk.Call( &rCrsrShell );
rCrsrShell.bChgCallFlag = FALSE; // Flag zuruecksetzen
}
}
}
<commit_msg>DTOR: scriptchanges must call the changelink<commit_after>/*************************************************************************
*
* $RCSfile: callnk.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: jp $ $Date: 2000-11-15 13:42:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FMTCNTNT_HXX //autogen
#include <fmtcntnt.hxx>
#endif
#ifndef _TXATBASE_HXX //autogen
#include <txatbase.hxx>
#endif
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _VISCRS_HXX
#include <viscrs.hxx>
#endif
#ifndef _CALLNK_HXX
#include <callnk.hxx>
#endif
#ifndef _CRSRSH_HXX
#include <crsrsh.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _TXTFRM_HXX
#include <txtfrm.hxx>
#endif
#ifndef _NDTXT_HXX
#include <ndtxt.hxx>
#endif
#ifndef _FLYFRM_HXX
#include <flyfrm.hxx>
#endif
#ifndef _BREAKIT_HXX
#include <breakit.hxx>
#endif
SwCallLink::SwCallLink( SwCrsrShell & rSh, ULONG nAktNode, xub_StrLen nAktCntnt,
BYTE nAktNdTyp, long nLRPos )
: rShell( rSh ), nNode( nAktNode ), nCntnt( nAktCntnt ),
nNdTyp( nAktNdTyp ), nLeftFrmPos( nLRPos )
{
}
SwCallLink::SwCallLink( SwCrsrShell & rSh )
: rShell( rSh )
{
// SPoint-Werte vom aktuellen Cursor merken
SwPaM* pCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwNode& rNd = pCrsr->GetPoint()->nNode.GetNode();
nNode = rNd.GetIndex();
nCntnt = pCrsr->GetPoint()->nContent.GetIndex();
nNdTyp = rNd.GetNodeType();
if( ND_TEXTNODE & nNdTyp )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)rNd, nCntnt,
!rShell.ActionPend() );
else
{
nLeftFrmPos = 0;
// eine Sonderbehandlung fuer die SwFeShell: diese setzt beim Loeschen
// der Kopf-/Fusszeile, Fussnoten den Cursor auf NULL (Node + Content)
// steht der Cursor auf keinem CntntNode, wird sich das im NdType
// gespeichert.
if( ND_CONTENTNODE & nNdTyp )
nNdTyp = 0;
}
}
SwCallLink::~SwCallLink()
{
if( !nNdTyp || !rShell.bCallChgLnk ) // siehe ctor
return ;
// wird ueber Nodes getravellt, Formate ueberpruefen und im neuen
// Node wieder anmelden
SwPaM* pCurCrsr = rShell.IsTableMode() ? rShell.GetTblCrs() : rShell.GetCrsr();
SwCntntNode * pCNd = pCurCrsr->GetCntntNode();
if( !pCNd )
return;
xub_StrLen nCmp, nAktCntnt = pCurCrsr->GetPoint()->nContent.GetIndex();
USHORT nNdWhich = pCNd->GetNodeType();
ULONG nAktNode = pCurCrsr->GetPoint()->nNode.GetIndex();
// melde die Shell beim akt. Node als abhaengig an, dadurch koennen
// alle Attribut-Aenderungen ueber den Link weiter gemeldet werden.
pCNd->Add( &rShell );
if( nNdTyp != nNdWhich || nNode != nAktNode )
{
/* immer, wenn zwischen Nodes gesprungen wird, kann es
* vorkommen, das neue Attribute gelten; die Text-Attribute.
* Es muesste also festgestellt werden, welche Attribute
* jetzt gelten; das kann auch gleich der Handler machen
*/
rShell.CallChgLnk();
}
else if( rShell.aChgLnk.IsSet() && ND_TEXTNODE == nNdWhich &&
nCntnt != nAktCntnt )
{
// nur wenn mit Left/right getravellt, dann Text-Hints pruefen
// und sich nicht der Frame geaendert hat (Spalten!)
if( nLeftFrmPos == SwCallLink::GetFrm( (SwTxtNode&)*pCNd, nAktCntnt,
!rShell.ActionPend() ) &&
(( nCmp = nCntnt ) + 1 == nAktCntnt || // Right
nCntnt -1 == ( nCmp = nAktCntnt )) ) // Left
{
if ( ((SwTxtNode*)pCNd)->HasHints() )
{
if( nCmp == nAktCntnt && pCurCrsr->HasMark() ) // left & Sele
++nCmp;
const SwpHints &rHts = ((SwTxtNode*)pCNd)->GetSwpHints();
USHORT n;
xub_StrLen nStart;
const xub_StrLen *pEnd;
for( n = 0; n < rHts.Count(); n++ )
{
const SwTxtAttr* pHt = rHts[ n ];
pEnd = pHt->GetEnd();
nStart = *pHt->GetStart();
// nur Start oder Start und Ende gleich, dann immer
// beim Ueberlaufen von Start callen
if( ( !pEnd || ( nStart == *pEnd ) ) &&
( nStart == nCntnt || nStart == nAktCntnt) )
{
rShell.CallChgLnk();
return;
}
// hat das Attribut einen Bereich und dieser nicht leer
else if( pEnd && nStart < *pEnd &&
// dann teste, ob ueber Start/Ende getravellt wurde
( nStart == nCmp ||
( pHt->DontExpand() ? nCmp == *pEnd-1
: nCmp == *pEnd ) ))
{
rShell.CallChgLnk();
return;
}
nStart = 0;
}
}
if( pBreakIt->xBreak.is() )
{
const String& rTxt = ((SwTxtNode*)pCNd)->GetTxt();
if( pBreakIt->xBreak->getScriptType( rTxt, nCntnt )
!= pBreakIt->xBreak->getScriptType( rTxt, nAktCntnt ))
{
rShell.CallChgLnk();
return;
}
}
}
else
/* wenn mit Home/End/.. mehr als 1 Zeichen getravellt, dann
* immer den ChgLnk rufen, denn es kann hier nicht
* festgestellt werden, was sich geaendert; etwas kann
* veraendert sein.
*/
rShell.CallChgLnk();
}
const SwFrm* pFrm;
const SwFlyFrm *pFlyFrm;
if( !rShell.ActionPend() && 0 != ( pFrm = pCNd->GetFrm(0,0,FALSE) ) &&
0 != ( pFlyFrm = pFrm->FindFlyFrm() ) && !rShell.IsTableMode() )
{
const SwNodeIndex* pIndex = pFlyFrm->GetFmt()->GetCntnt().GetCntntIdx();
ASSERT( pIndex, "Fly ohne Cntnt" );
const SwNode& rStNd = pIndex->GetNode();
if( rStNd.EndOfSectionNode()->StartOfSectionIndex() > nNode ||
nNode > rStNd.EndOfSectionIndex() )
rShell.GetFlyMacroLnk().Call( (void*)pFlyFrm->GetFmt() );
}
}
long SwCallLink::GetFrm( SwTxtNode& rNd, xub_StrLen nCntPos, BOOL bCalcFrm )
{
SwTxtFrm* pFrm = (SwTxtFrm*)rNd.GetFrm(0,0,bCalcFrm), *pNext = pFrm;
if ( pFrm && !pFrm->IsHiddenNow() )
{
if( pFrm->HasFollow() )
while( 0 != ( pNext = (SwTxtFrm*)pFrm->GetFollow() ) &&
nCntPos >= pNext->GetOfst() )
pFrm = pNext;
return pFrm->Frm().Left();
}
return 0;
}
/*---------------------------------------------------------------------*/
SwChgLinkFlag::SwChgLinkFlag( SwCrsrShell& rShell )
: rCrsrShell( rShell ), bOldFlag( rShell.bCallChgLnk ), nLeftFrmPos( 0 )
{
rCrsrShell.bCallChgLnk = FALSE;
if( bOldFlag && !rCrsrShell.pTblCrsr )
{
SwNode* pNd = rCrsrShell.pCurCrsr->GetNode();
if( ND_TEXTNODE & pNd->GetNodeType() )
nLeftFrmPos = SwCallLink::GetFrm( (SwTxtNode&)*pNd,
rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(),
!rCrsrShell.ActionPend() );
}
}
SwChgLinkFlag::~SwChgLinkFlag()
{
rCrsrShell.bCallChgLnk = bOldFlag;
if( bOldFlag && !rCrsrShell.pTblCrsr )
{
// die Spalten Ueberwachung brauchen wir immer!!!
SwNode* pNd = rCrsrShell.pCurCrsr->GetNode();
if( ND_TEXTNODE & pNd->GetNodeType() &&
nLeftFrmPos != SwCallLink::GetFrm( (SwTxtNode&)*pNd,
rCrsrShell.pCurCrsr->GetPoint()->nContent.GetIndex(),
!rCrsrShell.ActionPend() ))
{
/* immer, wenn zwischen Frames gesprungen wird, gelten
* neue Attribute. Es muesste also festgestellt werden, welche
* Attribute jetzt gelten; das kann gleich der Handler machen.
* Diesen direkt rufen !!!
*/
rCrsrShell.aChgLnk.Call( &rCrsrShell );
rCrsrShell.bChgCallFlag = FALSE; // Flag zuruecksetzen
}
}
}
<|endoftext|> |
<commit_before><commit_msg>fdo#66145: revert change to CopyMasterHeader<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: porexp.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: vg $ $Date: 2003-04-01 09:57:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PRECOMPILED
#include "core_pch.hxx"
#endif
#pragma hdrstop
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx> // SwViewOptions
#endif
#ifndef _SW_PORTIONHANDLER_HXX
#include <SwPortionHandler.hxx>
#endif
#ifndef _INFTXT_HXX
#include <inftxt.hxx>
#endif
#ifndef _POREXP_HXX
#include <porexp.hxx>
#endif
#ifndef _PORLAY_HXX
#include <porlay.hxx>
#endif
/*************************************************************************
* class SwExpandPortion
*************************************************************************/
xub_StrLen SwExpandPortion::GetCrsrOfst( const MSHORT nOfst ) const
{ return SwLinePortion::GetCrsrOfst( nOfst ); }
/*************************************************************************
* virtual SwExpandPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwExpandPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
rTxt.Erase();
// Nicht etwa: return 0 != rTxt.Len();
// Weil: leere Felder ersetzen CH_TXTATR gegen einen Leerstring
return sal_True;
}
/*************************************************************************
* virtual SwExpandPortion::HandlePortion()
*************************************************************************/
void SwExpandPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString;
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* virtual SwExpandPortion::GetTxtSize()
*************************************************************************/
SwPosSize SwExpandPortion::GetTxtSize( const SwTxtSizeInfo &rInf ) const
{
SwTxtSlot aDiffTxt( &rInf, this );
return rInf.GetTxtSize();
}
/*************************************************************************
* virtual SwExpandPortion::Format()
*************************************************************************/
// 5010: Exp und Tabs
sal_Bool SwExpandPortion::Format( SwTxtFormatInfo &rInf )
{
SwTxtSlotLen aDiffTxt( &rInf, this );
const xub_StrLen nFullLen = rInf.GetLen();
// So komisch es aussieht, die Abfrage auf GetLen() muss wegen der
// ExpandPortions _hinter_ aDiffTxt (vgl. SoftHyphs)
// sal_False returnen wegen SetFull ...
if( !nFullLen )
{
// nicht Init(), weil wir Hoehe und Ascent brauchen
Width(0);
return sal_False;
}
return SwTxtPortion::Format( rInf );
}
/*************************************************************************
* virtual SwExpandPortion::Paint()
*************************************************************************/
void SwExpandPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
SwTxtSlotLen aDiffTxt( &rInf, this );
rInf.DrawBackBrush( *this );
// do we have to repaint a post it portion?
if( rInf.OnWin() && pPortion && !pPortion->Width() )
pPortion->PrePaint( rInf, this );
// The contents of field portions is not considered during the
// calculation of the directions. Therefore we let vcl handle
// the calculation by removing the BIDI_STRONG_FLAG temporarily.
SwLayoutModeModifier aLayoutModeModifier( *rInf.GetOut() );
aLayoutModeModifier.SetAuto();
rInf.DrawText( *this, rInf.GetLen(), sal_False );
}
/*************************************************************************
* class SwBlankPortion
*************************************************************************/
SwLinePortion *SwBlankPortion::Compress() { return this; }
/*************************************************************************
* SwBlankPortion::MayUnderFlow()
*************************************************************************/
// 5497: Es gibt schon Gemeinheiten auf der Welt...
// Wenn eine Zeile voll mit HardBlanks ist und diese ueberlaeuft,
// dann duerfen keine Underflows generiert werden!
// Komplikationen bei Flys...
MSHORT SwBlankPortion::MayUnderFlow( const SwTxtFormatInfo &rInf,
xub_StrLen nIdx, sal_Bool bUnderFlow ) const
{
if( rInf.StopUnderFlow() )
return 0;
const SwLinePortion *pPos = rInf.GetRoot();
if( pPos->GetPortion() )
pPos = pPos->GetPortion();
while( pPos && pPos->IsBlankPortion() )
pPos = pPos->GetPortion();
if( !pPos || !rInf.GetIdx() || ( !pPos->GetLen() && pPos == rInf.GetRoot() ) )
return 0; // Nur noch BlankPortions unterwegs
// Wenn vor uns ein Blank ist, brauchen wir kein Underflow ausloesen,
// wenn hinter uns ein Blank ist, brauchen wir kein Underflow weiterreichen
if( bUnderFlow && CH_BLANK == rInf.GetTxt().GetChar( nIdx + 1) )
return 0;
if( nIdx && !((SwTxtFormatInfo&)rInf).GetFly() )
{
while( pPos && !pPos->IsFlyPortion() )
pPos = pPos->GetPortion();
if( !pPos )
{
//Hier wird ueberprueft, ob es in dieser Zeile noch sinnvolle Umbrueche
//gibt, Blanks oder Felder etc., wenn nicht, kein Underflow.
//Wenn Flys im Spiel sind, lassen wir das Underflow trotzdem zu.
xub_StrLen nBlank = nIdx;
while( --nBlank > rInf.GetLineStart() )
{
const xub_Unicode cCh = rInf.GetChar( nBlank );
if( CH_BLANK == cCh ||
(( CH_TXTATR_BREAKWORD == cCh || CH_TXTATR_INWORD == cCh )
&& rInf.HasHint( nBlank ) ) )
break;
}
if( nBlank <= rInf.GetLineStart() )
return 0;
}
}
xub_Unicode cCh;
if( nIdx < 2 || CH_BLANK == (cCh = rInf.GetChar( nIdx - 1 )) )
return 1;
if( CH_BREAK == cCh )
return 0;
return 2;
}
/*************************************************************************
* virtual SwBlankPortion::FormatEOL()
*************************************************************************/
// Format end of Line
void SwBlankPortion::FormatEOL( SwTxtFormatInfo &rInf )
{
MSHORT nMay = MayUnderFlow( rInf, rInf.GetIdx() - nLineLength, sal_True );
if( nMay )
{
if( nMay > 1 )
{
if( rInf.GetLast() == this )
rInf.SetLast( FindPrevPortion( rInf.GetRoot() ) );
rInf.X( rInf.X() - PrtWidth() );
rInf.SetIdx( rInf.GetIdx() - GetLen() );
}
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
}
/*************************************************************************
* virtual SwBlankPortion::Format()
*************************************************************************/
// 7771: UnderFlows weiterreichen und selbst ausloesen!
sal_Bool SwBlankPortion::Format( SwTxtFormatInfo &rInf )
{
const sal_Bool bFull = rInf.IsUnderFlow() || SwExpandPortion::Format( rInf );
if( bFull && MayUnderFlow( rInf, rInf.GetIdx(), rInf.IsUnderFlow() ) )
{
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
return bFull;
}
/*************************************************************************
* virtual SwBlankPortion::Paint()
*************************************************************************/
void SwBlankPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( !bMulti ) // No gray background for multiportion brackets
rInf.DrawViewOpt( *this, POR_BLANK );
SwExpandPortion::Paint( rInf );
}
/*************************************************************************
* virtual SwBlankPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwBlankPortion::GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const
{
rTxt = cChar;
return sal_True;
}
/*************************************************************************
* virtual SwBlankPortion::HandlePortion()
*************************************************************************/
void SwBlankPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString( cChar );
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* class SwPostItsPortion
*************************************************************************/
SwPostItsPortion::SwPostItsPortion( sal_Bool bScrpt )
: nViewWidth(0), bScript( bScrpt )
{
nLineLength = 1;
SetWhichPor( POR_POSTITS );
}
void SwPostItsPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( rInf.OnWin() && Width() )
rInf.DrawPostIts( *this, IsScript() );
}
KSHORT SwPostItsPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const
{
// Nicht zu fassen: PostIts sind immer zu sehen.
return rInf.OnWin() ?
(KSHORT)rInf.GetOpt().GetPostItsWidth( rInf.GetOut() ) : 0;
}
/*************************************************************************
* virtual SwPostItsPortion::Format()
*************************************************************************/
sal_Bool SwPostItsPortion::Format( SwTxtFormatInfo &rInf )
{
sal_Bool bRet = SwLinePortion::Format( rInf );
// 32749: PostIts sollen keine Auswirkung auf Zeilenhoehe etc. haben
SetAscent( 1 );
Height( 1 );
return bRet;
}
/*************************************************************************
* virtual SwPostItsPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwPostItsPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
if( rInf.OnWin() && rInf.GetOpt().IsPostIts() )
rTxt = ' ';
else
rTxt.Erase();
return sal_True;
}
<commit_msg>INTEGRATION: CWS os8 (1.9.138); FILE MERGED 2003/04/07 22:11:37 os 1.9.138.2: RESYNC: (1.9-1.10); FILE MERGED 2003/04/03 07:11:37 os 1.9.138.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
*
* $RCSfile: porexp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2003-04-17 14:28:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx> // SwViewOptions
#endif
#ifndef _SW_PORTIONHANDLER_HXX
#include <SwPortionHandler.hxx>
#endif
#ifndef _INFTXT_HXX
#include <inftxt.hxx>
#endif
#ifndef _POREXP_HXX
#include <porexp.hxx>
#endif
#ifndef _PORLAY_HXX
#include <porlay.hxx>
#endif
/*************************************************************************
* class SwExpandPortion
*************************************************************************/
xub_StrLen SwExpandPortion::GetCrsrOfst( const MSHORT nOfst ) const
{ return SwLinePortion::GetCrsrOfst( nOfst ); }
/*************************************************************************
* virtual SwExpandPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwExpandPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
rTxt.Erase();
// Nicht etwa: return 0 != rTxt.Len();
// Weil: leere Felder ersetzen CH_TXTATR gegen einen Leerstring
return sal_True;
}
/*************************************************************************
* virtual SwExpandPortion::HandlePortion()
*************************************************************************/
void SwExpandPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString;
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* virtual SwExpandPortion::GetTxtSize()
*************************************************************************/
SwPosSize SwExpandPortion::GetTxtSize( const SwTxtSizeInfo &rInf ) const
{
SwTxtSlot aDiffTxt( &rInf, this );
return rInf.GetTxtSize();
}
/*************************************************************************
* virtual SwExpandPortion::Format()
*************************************************************************/
// 5010: Exp und Tabs
sal_Bool SwExpandPortion::Format( SwTxtFormatInfo &rInf )
{
SwTxtSlotLen aDiffTxt( &rInf, this );
const xub_StrLen nFullLen = rInf.GetLen();
// So komisch es aussieht, die Abfrage auf GetLen() muss wegen der
// ExpandPortions _hinter_ aDiffTxt (vgl. SoftHyphs)
// sal_False returnen wegen SetFull ...
if( !nFullLen )
{
// nicht Init(), weil wir Hoehe und Ascent brauchen
Width(0);
return sal_False;
}
return SwTxtPortion::Format( rInf );
}
/*************************************************************************
* virtual SwExpandPortion::Paint()
*************************************************************************/
void SwExpandPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
SwTxtSlotLen aDiffTxt( &rInf, this );
rInf.DrawBackBrush( *this );
// do we have to repaint a post it portion?
if( rInf.OnWin() && pPortion && !pPortion->Width() )
pPortion->PrePaint( rInf, this );
// The contents of field portions is not considered during the
// calculation of the directions. Therefore we let vcl handle
// the calculation by removing the BIDI_STRONG_FLAG temporarily.
SwLayoutModeModifier aLayoutModeModifier( *rInf.GetOut() );
aLayoutModeModifier.SetAuto();
rInf.DrawText( *this, rInf.GetLen(), sal_False );
}
/*************************************************************************
* class SwBlankPortion
*************************************************************************/
SwLinePortion *SwBlankPortion::Compress() { return this; }
/*************************************************************************
* SwBlankPortion::MayUnderFlow()
*************************************************************************/
// 5497: Es gibt schon Gemeinheiten auf der Welt...
// Wenn eine Zeile voll mit HardBlanks ist und diese ueberlaeuft,
// dann duerfen keine Underflows generiert werden!
// Komplikationen bei Flys...
MSHORT SwBlankPortion::MayUnderFlow( const SwTxtFormatInfo &rInf,
xub_StrLen nIdx, sal_Bool bUnderFlow ) const
{
if( rInf.StopUnderFlow() )
return 0;
const SwLinePortion *pPos = rInf.GetRoot();
if( pPos->GetPortion() )
pPos = pPos->GetPortion();
while( pPos && pPos->IsBlankPortion() )
pPos = pPos->GetPortion();
if( !pPos || !rInf.GetIdx() || ( !pPos->GetLen() && pPos == rInf.GetRoot() ) )
return 0; // Nur noch BlankPortions unterwegs
// Wenn vor uns ein Blank ist, brauchen wir kein Underflow ausloesen,
// wenn hinter uns ein Blank ist, brauchen wir kein Underflow weiterreichen
if( bUnderFlow && CH_BLANK == rInf.GetTxt().GetChar( nIdx + 1) )
return 0;
if( nIdx && !((SwTxtFormatInfo&)rInf).GetFly() )
{
while( pPos && !pPos->IsFlyPortion() )
pPos = pPos->GetPortion();
if( !pPos )
{
//Hier wird ueberprueft, ob es in dieser Zeile noch sinnvolle Umbrueche
//gibt, Blanks oder Felder etc., wenn nicht, kein Underflow.
//Wenn Flys im Spiel sind, lassen wir das Underflow trotzdem zu.
xub_StrLen nBlank = nIdx;
while( --nBlank > rInf.GetLineStart() )
{
const xub_Unicode cCh = rInf.GetChar( nBlank );
if( CH_BLANK == cCh ||
(( CH_TXTATR_BREAKWORD == cCh || CH_TXTATR_INWORD == cCh )
&& rInf.HasHint( nBlank ) ) )
break;
}
if( nBlank <= rInf.GetLineStart() )
return 0;
}
}
xub_Unicode cCh;
if( nIdx < 2 || CH_BLANK == (cCh = rInf.GetChar( nIdx - 1 )) )
return 1;
if( CH_BREAK == cCh )
return 0;
return 2;
}
/*************************************************************************
* virtual SwBlankPortion::FormatEOL()
*************************************************************************/
// Format end of Line
void SwBlankPortion::FormatEOL( SwTxtFormatInfo &rInf )
{
MSHORT nMay = MayUnderFlow( rInf, rInf.GetIdx() - nLineLength, sal_True );
if( nMay )
{
if( nMay > 1 )
{
if( rInf.GetLast() == this )
rInf.SetLast( FindPrevPortion( rInf.GetRoot() ) );
rInf.X( rInf.X() - PrtWidth() );
rInf.SetIdx( rInf.GetIdx() - GetLen() );
}
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
}
/*************************************************************************
* virtual SwBlankPortion::Format()
*************************************************************************/
// 7771: UnderFlows weiterreichen und selbst ausloesen!
sal_Bool SwBlankPortion::Format( SwTxtFormatInfo &rInf )
{
const sal_Bool bFull = rInf.IsUnderFlow() || SwExpandPortion::Format( rInf );
if( bFull && MayUnderFlow( rInf, rInf.GetIdx(), rInf.IsUnderFlow() ) )
{
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
return bFull;
}
/*************************************************************************
* virtual SwBlankPortion::Paint()
*************************************************************************/
void SwBlankPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( !bMulti ) // No gray background for multiportion brackets
rInf.DrawViewOpt( *this, POR_BLANK );
SwExpandPortion::Paint( rInf );
}
/*************************************************************************
* virtual SwBlankPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwBlankPortion::GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const
{
rTxt = cChar;
return sal_True;
}
/*************************************************************************
* virtual SwBlankPortion::HandlePortion()
*************************************************************************/
void SwBlankPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString( cChar );
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* class SwPostItsPortion
*************************************************************************/
SwPostItsPortion::SwPostItsPortion( sal_Bool bScrpt )
: nViewWidth(0), bScript( bScrpt )
{
nLineLength = 1;
SetWhichPor( POR_POSTITS );
}
void SwPostItsPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( rInf.OnWin() && Width() )
rInf.DrawPostIts( *this, IsScript() );
}
KSHORT SwPostItsPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const
{
// Nicht zu fassen: PostIts sind immer zu sehen.
return rInf.OnWin() ?
(KSHORT)rInf.GetOpt().GetPostItsWidth( rInf.GetOut() ) : 0;
}
/*************************************************************************
* virtual SwPostItsPortion::Format()
*************************************************************************/
sal_Bool SwPostItsPortion::Format( SwTxtFormatInfo &rInf )
{
sal_Bool bRet = SwLinePortion::Format( rInf );
// 32749: PostIts sollen keine Auswirkung auf Zeilenhoehe etc. haben
SetAscent( 1 );
Height( 1 );
return bRet;
}
/*************************************************************************
* virtual SwPostItsPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwPostItsPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
if( rInf.OnWin() && rInf.GetOpt().IsPostIts() )
rTxt = ' ';
else
rTxt.Erase();
return sal_True;
}
<|endoftext|> |
<commit_before><commit_msg>coverity#704930 Dereference after null check<commit_after><|endoftext|> |
<commit_before>#include "core.hpp"
#include <http_backend.hpp>
#include <requestparams.hpp>
#include <glibmm.h>
namespace Davix{
//
// Main entry point
//
CoreInterface* davix_context_create(){
return static_cast<CoreInterface*>(new Core(new NEONSessionFactory() ));
}
}
extern "C"{
// initialization
__attribute__((constructor))
void core_init(){
if (!g_thread_get_initialized())
g_thread_init(NULL);
Glib::init();
}
davix_sess_t davix_session_new(GError ** err){
try{
Davix::CoreInterface* comp = static_cast<Davix::CoreInterface*>(new Davix::Core(new Davix::NEONSessionFactory() ));
return (davix_sess_t) comp;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_session_new"), ENOSYS, "unexpected error");
}
return NULL;
}
int davix_stat(davix_sess_t sess, const char* url, struct stat * st, GError** err){
g_return_val_if_fail(sess != NULL,-1);
try{
Davix::CoreInterface* comp = static_cast<Davix::CoreInterface*>(sess);
comp->stat(url, st);
return 0;
}catch(Glib::Error & e){
if(err)
*err= g_error_copy(e.gobj());
}catch(std::exception & e){
g_set_error(err, g_quark_from_string("davix_stat"), EINVAL, "unexcepted error %s", e.what());
}
return -1;
}
int davix_params_set_auth_callback(davix_params_t params, davix_auth_callback call, void* userdata, GError** err){
g_return_val_if_fail(params != NULL, -1);
int ret = -1;
try{
Davix::RequestParams* p = (Davix::RequestParams*)(params);
p->set_authentification_controller(userdata, call);
ret = 0;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_params_set_auth_callback"), EINVAL, "unexpected error");
}
return ret;
}
int davix_params_set_ssl_check(davix_params_t params, gboolean ssl_check, GError** err){
g_return_val_if_fail(params != NULL, -1);
int ret = -1;
try{
Davix::RequestParams* p = (Davix::RequestParams*)(params);
p->set_ssl_ca_check(ssl_check);
ret = 0;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_set_auth_callback"), EINVAL, "unexpected error");
}
return ret;
}
int davix_set_default_session_params(davix_sess_t sess, davix_params_t params, GError ** err){
g_return_val_if_fail(params != NULL && sess != NULL , -1);
int ret = -1;
try{
Davix::RequestParams* p = (Davix::RequestParams*)(params);
Davix::CoreInterface* comp = static_cast<Davix::CoreInterface*>(sess);
comp->getSessionFactory()->set_parameters(*p);
ret = 0;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_set_auth_callback"), EINVAL, "unexpected error");
}
return ret;
}
void davix_session_free(davix_sess_t sess){
if(sess != NULL)
delete static_cast<Davix::CoreInterface*>(sess);
}
davix_params_t davix_params_new(){
return (struct davix_request_params*) new Davix::RequestParams();
}
davix_params_t davix_params_copy(davix_params_t p){
return (struct davix_request_params*) new Davix::RequestParams(*(Davix::RequestParams*) p);
}
void davix_params_free(davix_params_t p){
if(p){
delete (Davix::RequestParams*) p;
}
}
}
<commit_msg>g_thread_get_initialized not available in SL5 :(<commit_after>#include "core.hpp"
#include <http_backend.hpp>
#include <requestparams.hpp>
#include <glibmm.h>
#include <glib.h>
namespace Davix{
//
// Main entry point
//
CoreInterface* davix_context_create(){
return static_cast<CoreInterface*>(new Core(new NEONSessionFactory() ));
}
}
extern "C"{
// initialization
__attribute__((constructor))
void core_init(){
if (!g_thread_supported())
g_thread_init(NULL);
Glib::init();
}
davix_sess_t davix_session_new(GError ** err){
try{
Davix::CoreInterface* comp = static_cast<Davix::CoreInterface*>(new Davix::Core(new Davix::NEONSessionFactory() ));
return (davix_sess_t) comp;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_session_new"), ENOSYS, "unexpected error");
}
return NULL;
}
int davix_stat(davix_sess_t sess, const char* url, struct stat * st, GError** err){
g_return_val_if_fail(sess != NULL,-1);
try{
Davix::CoreInterface* comp = static_cast<Davix::CoreInterface*>(sess);
comp->stat(url, st);
return 0;
}catch(Glib::Error & e){
if(err)
*err= g_error_copy(e.gobj());
}catch(std::exception & e){
g_set_error(err, g_quark_from_string("davix_stat"), EINVAL, "unexcepted error %s", e.what());
}
return -1;
}
int davix_params_set_auth_callback(davix_params_t params, davix_auth_callback call, void* userdata, GError** err){
g_return_val_if_fail(params != NULL, -1);
int ret = -1;
try{
Davix::RequestParams* p = (Davix::RequestParams*)(params);
p->set_authentification_controller(userdata, call);
ret = 0;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_params_set_auth_callback"), EINVAL, "unexpected error");
}
return ret;
}
int davix_params_set_ssl_check(davix_params_t params, gboolean ssl_check, GError** err){
g_return_val_if_fail(params != NULL, -1);
int ret = -1;
try{
Davix::RequestParams* p = (Davix::RequestParams*)(params);
p->set_ssl_ca_check(ssl_check);
ret = 0;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_set_auth_callback"), EINVAL, "unexpected error");
}
return ret;
}
int davix_set_default_session_params(davix_sess_t sess, davix_params_t params, GError ** err){
g_return_val_if_fail(params != NULL && sess != NULL , -1);
int ret = -1;
try{
Davix::RequestParams* p = (Davix::RequestParams*)(params);
Davix::CoreInterface* comp = static_cast<Davix::CoreInterface*>(sess);
comp->getSessionFactory()->set_parameters(*p);
ret = 0;
}catch(Glib::Error & e){
if(err)
g_error_copy(e.gobj());
}catch(...){
g_set_error(err, g_quark_from_string("davix_set_auth_callback"), EINVAL, "unexpected error");
}
return ret;
}
void davix_session_free(davix_sess_t sess){
if(sess != NULL)
delete static_cast<Davix::CoreInterface*>(sess);
}
davix_params_t davix_params_new(){
return (struct davix_request_params*) new Davix::RequestParams();
}
davix_params_t davix_params_copy(davix_params_t p){
return (struct davix_request_params*) new Davix::RequestParams(*(Davix::RequestParams*) p);
}
void davix_params_free(davix_params_t p){
if(p){
delete (Davix::RequestParams*) p;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>fix higher debug levels<commit_after><|endoftext|> |
<commit_before>#include <LuaContext.hpp>
#include <gtest/gtest.h>
TEST(AdvancedReadWrite, WritingVariant) {
LuaContext context;
boost::variant<int,std::string> val{std::string{"test"}};
context.writeVariable("a", val);
EXPECT_EQ("test", context.readVariable<std::string>("a"));
}
TEST(AdvancedReadWrite, ReadingVariant) {
LuaContext context;
context.writeVariable("a", "test");
const auto val = context.readVariable<boost::variant<bool,int,std::string>>("a");
EXPECT_EQ(2, val.which());
EXPECT_EQ("test", boost::get<std::string>(val));
}
TEST(AdvancedReadWrite, VariantError) {
LuaContext context;
context.writeVariable("a", "test");
EXPECT_THROW((context.readVariable<boost::variant<bool,int,bool*>>("a")), LuaContext::WrongTypeException);
}
TEST(AdvancedReadWrite, ReadingOptional) {
LuaContext context;
context.writeVariable("a", 3);
EXPECT_EQ(3, context.readVariable<boost::optional<int>>("a").get());
EXPECT_FALSE(context.readVariable<boost::optional<int>>("b").is_initialized());
}
TEST(AdvancedReadWrite, EmptyArray) {
LuaContext context;
context.writeVariable("a", LuaContext::EmptyArray);
EXPECT_EQ("table", context.executeCode<std::string>("return type(a)"));
}
TEST(AdvancedReadWrite, ReadInsideArrays) {
LuaContext context;
context.executeCode("a = { 12, 34 }");
EXPECT_EQ(12, context.readVariable<int>("a", 1));
EXPECT_EQ(34, context.readVariable<int>("a", 2));
}
TEST(AdvancedReadWrite, WriteVariableInsideArrays) {
LuaContext context;
context.executeCode("a = { 1, {} }");
context.writeVariable("a", 1, 34);
context.writeVariable("a", 2, "test", 14);
EXPECT_EQ(34, context.readVariable<int>("a", 1));
EXPECT_EQ(14, context.readVariable<int>("a", 2, "test"));
}
TEST(AdvancedReadWrite, WriteFunctionInsideArrays) {
LuaContext context;
context.executeCode("a = { 1, {} }");
context.writeFunction<int (int)>("a", 1, [](int x) { return x + 1; });
context.writeFunction("a", 2, "test", [](int x) { return x * 2; });
EXPECT_EQ(34, context.executeCode<int>("local f = a[1]; return f(33)"));
EXPECT_EQ(14, context.executeCode<int>("local f = a[2].test; return f(7)"));
}
TEST(AdvancedReadWrite, WritingVectors) {
LuaContext context;
context.writeVariable("a", std::vector<std::string>{"hello", "world"});
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", 2));
const auto val = context.readVariable<std::map<int,std::string>>("a");
EXPECT_EQ("hello", val.at(1));
EXPECT_EQ("world", val.at(2));
}
TEST(AdvancedReadWrite, VectorOfPairs) {
LuaContext context;
context.writeVariable("a", std::vector<std::pair<int,std::string>>{
{ 1, "hello" },
{ -23, "world" }
});
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", -23));
const auto val = context.readVariable<std::vector<std::pair<int,std::string>>>("a");
EXPECT_TRUE(val[0].first == 1 || val[0].first == -23);
EXPECT_TRUE(val[1].first == 1 || val[1].first == -23);
EXPECT_TRUE(val[0].second == "hello" || val[0].second == "world");
EXPECT_TRUE(val[1].second == "hello" || val[1].second == "world");
}
TEST(AdvancedReadWrite, Maps) {
LuaContext context;
context.writeVariable("a", std::map<int,std::string>{
{ 1, "hello" },
{ -23, "world" }
});
context.executeCode("b = { \"hello\", \"world\" }");
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", -23));
EXPECT_EQ("hello", context.readVariable<std::string>("b", 1));
EXPECT_EQ("world", context.readVariable<std::string>("b", 2));
const auto val = context.readVariable<std::map<int,std::string>>("a");
EXPECT_EQ("hello", val.at(1));
EXPECT_EQ("world", val.at(-23));
const auto b = context.readVariable<std::map<int,std::string>>("b");
EXPECT_EQ("hello", b.at(1));
EXPECT_EQ("world", b.at(2));
}
TEST(AdvancedReadWrite, UnorderedMaps) {
LuaContext context;
context.writeVariable("a", std::unordered_map<int,std::string>{
{ 1, "hello" },
{ -23, "world" }
});
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", -23));
const auto val = context.readVariable<std::unordered_map<int,std::string>>("a");
EXPECT_EQ("hello", val.at(1));
EXPECT_EQ("world", val.at(-23));
}
TEST(AdvancedReadWrite, WritingOptionals) {
LuaContext context;
context.writeVariable("a", boost::optional<int>{});
context.writeVariable("b", boost::optional<int>{12});
EXPECT_EQ("nil", context.executeCode<std::string>("return type(a)"));
EXPECT_EQ("number", context.executeCode<std::string>("return type(b)"));
EXPECT_EQ(12, context.executeCode<int>("return b"));
}
TEST(AdvancedReadWrite, AdvancedExample) {
LuaContext context;
context.writeVariable("a",
std::vector< std::pair< boost::variant<int,std::string>, boost::variant<bool,float> >>
{
{ "test", true },
{ 2, 6.4f },
{ "hello", 1.f },
{ "world", -7.6f },
{ 18, false }
}
);
EXPECT_EQ(true, context.executeCode<bool>("return a.test"));
EXPECT_DOUBLE_EQ(6.4f, context.executeCode<float>("return a[2]"));
EXPECT_DOUBLE_EQ(-7.6f, context.readVariable<float>("a", "world"));
}
<commit_msg>Added wrong optional type reading test<commit_after>#include <LuaContext.hpp>
#include <gtest/gtest.h>
TEST(AdvancedReadWrite, WritingVariant) {
LuaContext context;
boost::variant<int,std::string> val{std::string{"test"}};
context.writeVariable("a", val);
EXPECT_EQ("test", context.readVariable<std::string>("a"));
}
TEST(AdvancedReadWrite, ReadingVariant) {
LuaContext context;
context.writeVariable("a", "test");
const auto val = context.readVariable<boost::variant<bool,int,std::string>>("a");
EXPECT_EQ(2, val.which());
EXPECT_EQ("test", boost::get<std::string>(val));
}
TEST(AdvancedReadWrite, VariantError) {
LuaContext context;
context.writeVariable("a", "test");
EXPECT_THROW((context.readVariable<boost::variant<bool,int,bool*>>("a")), LuaContext::WrongTypeException);
}
TEST(AdvancedReadWrite, ReadingOptional) {
LuaContext context;
context.writeVariable("a", 3);
context.writeVariable("b", "test");
EXPECT_EQ(3, context.readVariable<boost::optional<int>>("a").get());
EXPECT_THROW(context.readVariable<boost::optional<int>>("b"), LuaContext::WrongTypeException);
EXPECT_FALSE(context.readVariable<boost::optional<int>>("c").is_initialized());
}
TEST(AdvancedReadWrite, EmptyArray) {
LuaContext context;
context.writeVariable("a", LuaContext::EmptyArray);
EXPECT_EQ("table", context.executeCode<std::string>("return type(a)"));
}
TEST(AdvancedReadWrite, ReadInsideArrays) {
LuaContext context;
context.executeCode("a = { 12, 34 }");
EXPECT_EQ(12, context.readVariable<int>("a", 1));
EXPECT_EQ(34, context.readVariable<int>("a", 2));
}
TEST(AdvancedReadWrite, WriteVariableInsideArrays) {
LuaContext context;
context.executeCode("a = { 1, {} }");
context.writeVariable("a", 1, 34);
context.writeVariable("a", 2, "test", 14);
EXPECT_EQ(34, context.readVariable<int>("a", 1));
EXPECT_EQ(14, context.readVariable<int>("a", 2, "test"));
}
TEST(AdvancedReadWrite, WriteFunctionInsideArrays) {
LuaContext context;
context.executeCode("a = { 1, {} }");
context.writeFunction<int (int)>("a", 1, [](int x) { return x + 1; });
context.writeFunction("a", 2, "test", [](int x) { return x * 2; });
EXPECT_EQ(34, context.executeCode<int>("local f = a[1]; return f(33)"));
EXPECT_EQ(14, context.executeCode<int>("local f = a[2].test; return f(7)"));
}
TEST(AdvancedReadWrite, WritingVectors) {
LuaContext context;
context.writeVariable("a", std::vector<std::string>{"hello", "world"});
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", 2));
const auto val = context.readVariable<std::map<int,std::string>>("a");
EXPECT_EQ("hello", val.at(1));
EXPECT_EQ("world", val.at(2));
}
TEST(AdvancedReadWrite, VectorOfPairs) {
LuaContext context;
context.writeVariable("a", std::vector<std::pair<int,std::string>>{
{ 1, "hello" },
{ -23, "world" }
});
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", -23));
const auto val = context.readVariable<std::vector<std::pair<int,std::string>>>("a");
EXPECT_TRUE(val[0].first == 1 || val[0].first == -23);
EXPECT_TRUE(val[1].first == 1 || val[1].first == -23);
EXPECT_TRUE(val[0].second == "hello" || val[0].second == "world");
EXPECT_TRUE(val[1].second == "hello" || val[1].second == "world");
}
TEST(AdvancedReadWrite, Maps) {
LuaContext context;
context.writeVariable("a", std::map<int,std::string>{
{ 1, "hello" },
{ -23, "world" }
});
context.executeCode("b = { \"hello\", \"world\" }");
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", -23));
EXPECT_EQ("hello", context.readVariable<std::string>("b", 1));
EXPECT_EQ("world", context.readVariable<std::string>("b", 2));
const auto val = context.readVariable<std::map<int,std::string>>("a");
EXPECT_EQ("hello", val.at(1));
EXPECT_EQ("world", val.at(-23));
const auto b = context.readVariable<std::map<int,std::string>>("b");
EXPECT_EQ("hello", b.at(1));
EXPECT_EQ("world", b.at(2));
}
TEST(AdvancedReadWrite, UnorderedMaps) {
LuaContext context;
context.writeVariable("a", std::unordered_map<int,std::string>{
{ 1, "hello" },
{ -23, "world" }
});
EXPECT_EQ("hello", context.readVariable<std::string>("a", 1));
EXPECT_EQ("world", context.readVariable<std::string>("a", -23));
const auto val = context.readVariable<std::unordered_map<int,std::string>>("a");
EXPECT_EQ("hello", val.at(1));
EXPECT_EQ("world", val.at(-23));
}
TEST(AdvancedReadWrite, WritingOptionals) {
LuaContext context;
context.writeVariable("a", boost::optional<int>{});
context.writeVariable("b", boost::optional<int>{12});
EXPECT_EQ("nil", context.executeCode<std::string>("return type(a)"));
EXPECT_EQ("number", context.executeCode<std::string>("return type(b)"));
EXPECT_EQ(12, context.executeCode<int>("return b"));
}
TEST(AdvancedReadWrite, AdvancedExample) {
LuaContext context;
context.writeVariable("a",
std::vector< std::pair< boost::variant<int,std::string>, boost::variant<bool,float> >>
{
{ "test", true },
{ 2, 6.4f },
{ "hello", 1.f },
{ "world", -7.6f },
{ 18, false }
}
);
EXPECT_EQ(true, context.executeCode<bool>("return a.test"));
EXPECT_DOUBLE_EQ(6.4f, context.executeCode<float>("return a[2]"));
EXPECT_DOUBLE_EQ(-7.6f, context.readVariable<float>("a", "world"));
}
<|endoftext|> |
<commit_before>#include <ctime>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"
static const int WIDTH = 800;
static const int HEIGHT = 600;
static const int FPS = 10;
static const int DEVICE = 0;
static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭
static const std::string FILE_EXTENTION = ".jpg";//拡張子
static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小
Camera::Camera()
{
capture.cap(DEVICE);
if (!capture.isOpened())
{
std::cout<<"capture is note opened"<<std::endl;
}
capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT);
capture.set(CV_CAP_PROP_FPS,FPS);
}
Camera::~Camera()
{
capture.release();
}
Camera::takePhoto()
{
makeTimePath();
cv::Mat frame;
do
{
capture>>frame;
} while(frame.empty());
input = frame;
imwrite(timePath+FILE_EXTENTION,src);
}
//時間を元にtimePathを作る
int Camera::makeTimePath(void)
{
time_t timer;//時刻を受け取る変数
struct tm *timeptr;//日時を集めた構造体ポインタ
char buffer[80];
time(&timer);//現在時刻の取得
timeptr = localtime(&timer);//ポインタ
strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入
std::string str(buffer);
timePath = DIRECTORY_PATH+str;
return 0;
}
//ノイズ除去
cv::Mat Camera::rmNoize(cv::Mat src)
{
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
return src;
}
int Camera::binarize()
{
cv::Mat hsv;
cv::Mat hsv_filtered15 ;//画像の初期化
cv::Mat hsv_filtered180;//画像の初期化
cv::cvtColor(input, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);
cv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
cv::add(hsv_filtered15,hsv_filtered180,hsv);
output = rmNoise(hsv);
imwrite(timePath+"BINARY"+FILE_EXTENTION,output);
return 0;
}
//二値化した画像から1の面積を抽出
double Camera::countArea()
{
double Area = output.rows*output.cols;//全ピクセル数
double redCount = 0; //赤色を認識したピクセルの数
redCount = cv::countNonZero(output);//赤色部分の面積を計算
double percentage = 0; //割合
percentage = (redCount / Area)*100;//割合を計算
std::cout<<"面積のPercentageは%"<<percentage<<std::endl;
return percentage;
}
//二値化画像のcenterを角度で返す
double Camera::getCenter()
{
cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入
double mc = mu.m10 / mu.m00;//重心のx座標
double center = (mc - output.cols / 2) * AOV / output.cols;//正規化
std::cout<<"重心の位置は"<<center<<std::endl;
return center;
}
<commit_msg>debug<commit_after>#include <ctime>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "camera.hpp"
static const int WIDTH = 800;
static const int HEIGHT = 600;
static const int FPS = 10;
static const int DEVICE = 0;
static const std::string DIRECTORY_PATH = "/home/pi/Pictures/";//pathの先頭
static const std::string FILE_EXTENTION = ".jpg";//拡張子
static const int AOV = 62.2;//ANGLE OF VIEW
//明度について
static const int MAX_VALUE = 255;//明るさ最大
static const int NO_VALUE = 0;//明るさ最小
Camera::Camera()
{
capture.open(DEVICE);
if (!capture.isOpened())
{
std::cout<<"capture is note opened"<<std::endl;
}
capture.set(CV_CAP_PROP_FRAME_WIDTH,WIDTH);
capture.set(CV_CAP_PROP_FRAME_HEIGHT,HEIGHT);
capture.set(CV_CAP_PROP_FPS,FPS);
}
Camera::~Camera()
{
capture.release();
}
int Camera::takePhoto()
{
makeTimePath();
cv::Mat frame;
do
{
capture>>frame;
} while(frame.empty());
input = frame;
imwrite(timePath+FILE_EXTENTION,input);
return 0;
}
//時間を元にtimePathを作る
int Camera::makeTimePath(void)
{
time_t timer;//時刻を受け取る変数
struct tm *timeptr;//日時を集めた構造体ポインタ
char buffer[80];
time(&timer);//現在時刻の取得
timeptr = localtime(&timer);//ポインタ
strftime(buffer, sizeof(buffer), "%Y%m%d-%H%M%S", timeptr);//日時を文字列に変換してsに代入
std::string str(buffer);
timePath = DIRECTORY_PATH+str;
return 0;
}
//ノイズ除去
cv::Mat Camera::rmNoize(cv::Mat src)
{
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),10);//縮小処理
cv::dilate(src,src,cv::Mat(),cv::Point(-1, -1),25);//膨張処理
cv::erode(src,src,cv::Mat(),cv::Point(-1, -1),15);//縮小処理
return src;
}
int Camera::binarize()
{
cv::Mat hsv;
cv::Mat hsv_filtered15 ;//画像の初期化
cv::Mat hsv_filtered180;//画像の初期化
cv::cvtColor(input, hsv, CV_BGR2HSV);//入力画像(src)をhsv色空間(dst)に変換
//inRange(入力画像,下界画像,上界画像,出力画像)
//「HSV」は、色を色相(Hue)・彩度(Saturation)・明度(Value)
cv::inRange(hsv, cv::Scalar(0, 70, 60), cv::Scalar(2, 255, MAX_VALUE), hsv_filtered15);
cv::inRange(hsv, cv::Scalar(160, 70, 60), cv::Scalar(180, 255, MAX_VALUE), hsv_filtered180);
cv::add(hsv_filtered15,hsv_filtered180,hsv);
output = rmNoise(hsv);
imwrite(timePath+"BINARY"+FILE_EXTENTION,output);
return 0;
}
//二値化した画像から1の面積を抽出
double Camera::countArea()
{
double Area = output.rows*output.cols;//全ピクセル数
double redCount = 0; //赤色を認識したピクセルの数
redCount = cv::countNonZero(output);//赤色部分の面積を計算
double percentage = 0; //割合
percentage = (redCount / Area)*100;//割合を計算
std::cout<<"面積のPercentageは%"<<percentage<<std::endl;
return percentage;
}
//二値化画像のcenterを角度で返す
double Camera::getCenter()
{
cv::Moments mu = cv::moments(output, false);//重心の計算結果をmuに代入
double mc = mu.m10 / mu.m00;//重心のx座標
double center = (mc - output.cols / 2) * AOV / output.cols;//正規化
std::cout<<"重心の位置は"<<center<<std::endl;
return center;
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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 "ply_loader.h"
#include <list>
namespace embree
{
namespace SceneGraph
{
/*! PLY type */
struct Type {
enum Tag { PTY_CHAR, PTY_UCHAR, PTY_SHORT, PTY_USHORT, PTY_INT, PTY_UINT, PTY_FLOAT, PTY_DOUBLE, PTY_LIST, PTY_NONE } ty, index, data;
Type() : ty(PTY_NONE), index(PTY_NONE), data(PTY_NONE) {}
Type(Tag ty) : ty(ty), index(PTY_NONE), data(PTY_NONE) {}
Type(Tag ty, Tag index, Tag data) : ty(ty), index(index), data(data) {}
};
/*! an element stored in the PLY file, such as vertex, face, etc. */
struct Element {
std::string name;
size_t size; /// number of data items of the element
std::vector<std::string> properties; /// list of all properties of the element (e.g. x, y, z) (not strictly necessary)
std::map<std::string,Type> type; /// mapping of property name to type
std::map<std::string,std::vector<float> > data; /// data array properties (all represented as floats)
std::map<std::string,std::vector<std::vector<size_t> > > list; /// list properties (integer lists supported only)
};
/*! mesh structure that reflects the PLY file format */
struct Mesh {
std::vector<std::string> order; /// order of all elements in file (not strictly necessary)
std::map<std::string,Element> elements; /// all elements of the file, e.g. vertex, face, ...
};
/* returns the size of a type in bytes */
size_t sizeOfType(Type::Tag ty)
{
switch (ty) {
case Type::PTY_CHAR : return 1;
case Type::PTY_UCHAR : return 1;
case Type::PTY_SHORT : return 2;
case Type::PTY_USHORT : return 2;
case Type::PTY_INT : return 4;
case Type::PTY_UINT : return 4;
case Type::PTY_FLOAT : return 4;
case Type::PTY_DOUBLE : return 8;
default : throw std::runtime_error("invalid type");
}
}
/* compute the type of a string */
Type::Tag typeTagOfString(const std::string& ty) {
if (ty == "char") return Type::PTY_CHAR;
if (ty == "int8") return Type::PTY_CHAR;
if (ty == "uchar") return Type::PTY_UCHAR;
if (ty == "uint8") return Type::PTY_UCHAR;
if (ty == "short") return Type::PTY_SHORT;
if (ty == "int16") return Type::PTY_SHORT;
if (ty == "ushort") return Type::PTY_USHORT;
if (ty == "uint16") return Type::PTY_USHORT;
if (ty == "int") return Type::PTY_INT;
if (ty == "int32") return Type::PTY_INT;
if (ty == "uint") return Type::PTY_UINT;
if (ty == "uint32") return Type::PTY_UINT;
if (ty == "float") return Type::PTY_FLOAT;
if (ty == "float32") return Type::PTY_FLOAT;
if (ty == "double") return Type::PTY_DOUBLE;
throw std::runtime_error("invalid type " + ty);
return Type::PTY_NONE;
}
/* compute the type of a string */
std::string stringOfTypeTag(Type::Tag ty) {
if (ty == Type::PTY_CHAR) return "char";
if (ty == Type::PTY_UCHAR) return "uchar";
if (ty == Type::PTY_SHORT) return "short";
if (ty == Type::PTY_USHORT) return "ushort";
if (ty == Type::PTY_INT) return "int";
if (ty == Type::PTY_UINT) return "uint";
if (ty == Type::PTY_FLOAT) return "float";
if (ty == Type::PTY_DOUBLE) return "double";
if (ty == Type::PTY_LIST) return "list";
throw std::runtime_error("invalid type");
return "";
}
/* compute the type of a string */
std::string stringOfType(Type ty) {
if (ty.ty == Type::PTY_LIST) return "list " + stringOfTypeTag(ty.index) + " " + stringOfTypeTag(ty.data);
else return stringOfTypeTag(ty.ty);
}
/* PLY parser class */
struct PlyParser
{
std::fstream fs;
Mesh mesh;
Ref<SceneGraph::Node> scene;
/* storage format of data in file */
enum Format { ASCII, BINARY_BIG_ENDIAN, BINARY_LITTLE_ENDIAN } format;
/* constructor parses the input stream */
PlyParser(const FileName& fileName) : format(ASCII)
{
/* open file */
fs.open (fileName.c_str(), std::fstream::in | std::fstream::binary);
if (!fs.is_open()) throw std::runtime_error("cannot open file : " + fileName.str());
/* check for file signature */
std::string signature; getline(fs,signature);
if (signature != "ply") throw std::runtime_error("invalid PLY file signature: " + signature);
/* read header */
std::list<std::string> header;
while (true) {
std::string line; getline(fs,line);
if (line == "end_header") break;
if (line.find_first_of('#') == 0) continue;
if (line == "") continue;
header.push_back(line);
}
/* parse header */
parseHeader(header);
/* now parse all elements */
for (std::vector<std::string>::iterator i = mesh.order.begin(); i!=mesh.order.end(); i++)
parseElementData(mesh.elements[*i]);
/* create triangle mesh */
scene = import();
}
/* parse the PLY header */
void parseHeader(std::list<std::string>& header)
{
while (!header.empty())
{
std::stringstream line(header.front());
header.pop_front();
std::string tag; line >> tag;
/* ignore comments */
if (tag == "comment") {
}
/* parse format */
else if (tag == "format")
{
std::string fmt; line >> fmt;
if (fmt == "ascii") format = ASCII;
else if (fmt == "binary_big_endian") format = BINARY_BIG_ENDIAN;
else if (fmt == "binary_little_endian") format = BINARY_LITTLE_ENDIAN;
else throw std::runtime_error("invalid PLY file format: " + fmt);
std::string version; line >> version;
if (version != "1.0") throw std::runtime_error("invalid PLY file version: " + version);
}
/* parse end of header tag */
else if (tag == "end_header")
break;
/* parse elements */
else if (tag == "element") parseElementDescr(line,header);
/* report unknown tags */
else throw std::runtime_error("unknown tag in PLY file: " + tag);
}
}
/* parses a PLY element description */
void parseElementDescr(std::stringstream& cin, std::list<std::string>& header)
{
Element elt;
std::string name; cin >> name;
size_t num; cin >> num;
mesh.order.push_back(name);
elt.name = name;
elt.size = num;
/* parse all properties */
while (!header.empty())
{
std::stringstream line(header.front());
std::string tag; line >> tag;
if (tag != "property") break;
header.pop_front();
Type ty = parseType(line);
std::string name; line >> name;
elt.type[name] = ty;
elt.properties.push_back(name);
}
mesh.elements[name] = elt;
}
/* parses a PLY type */
Type parseType(std::stringstream& cin)
{
std::string ty; cin >> ty;
if (ty == "list") {
std::string ty0; cin >> ty0;
std::string ty1; cin >> ty1;
return Type(Type::PTY_LIST,typeTagOfString(ty0),typeTagOfString(ty1));
} else return Type(typeTagOfString(ty));
}
/* parses data of a PLY element */
void parseElementData(Element& elt)
{
/* allocate data for all properties */
for (std::vector<std::string>::iterator i=elt.properties.begin(); i!=elt.properties.end(); i++) {
if (elt.type[*i].ty == Type::PTY_LIST) elt.list[*i] = std::vector<std::vector<size_t> >();
else elt.data[*i] = std::vector<float>();
}
/* parse all elements */
for (size_t e=0; e<elt.size; e++)
{
/* load all properties of the element */
for (std::vector<std::string>::iterator i=elt.properties.begin(); i!=elt.properties.end(); i++) {
Type ty = elt.type[*i];
if (ty.ty == Type::PTY_LIST) loadPropertyList(elt.list[*i],ty.index,ty.data);
else loadPropertyData(elt.data[*i],ty.ty);
}
}
}
/* load bytes from file and take care of little and big endian encoding */
void readBytes(void* dst, int num) {
if (format == BINARY_LITTLE_ENDIAN) fs.read((char*)dst,num);
else if (format == BINARY_BIG_ENDIAN) for (int i=0; i<num; i++) fs.read((char*)dst+num-i-1,1);
else throw std::runtime_error("internal error on PLY loader");
}
int read_ascii_int () { int i; fs >> i; return i; }
float read_ascii_float() { float f; fs >> f; return f; }
signed char read_char () { if (format == ASCII) return read_ascii_int(); signed char r = 0; readBytes(&r,1); return r; }
unsigned char read_uchar () { if (format == ASCII) return read_ascii_int(); unsigned char r = 0; readBytes(&r,1); return r; }
signed short read_short () { if (format == ASCII) return read_ascii_int(); signed short r = 0; readBytes(&r,2); return r; }
unsigned short read_ushort() { if (format == ASCII) return read_ascii_int(); unsigned short r = 0; readBytes(&r,2); return r; }
signed int read_int () { if (format == ASCII) return read_ascii_int(); signed int r = 0; readBytes(&r,4); return r; }
unsigned int read_uint () { if (format == ASCII) return read_ascii_int(); unsigned int r = 0; readBytes(&r,4); return r; }
float read_float () { if (format == ASCII) return read_ascii_float(); float r = 0; readBytes(&r,4); return r; }
double read_double() { if (format == ASCII) return read_ascii_float(); double r = 0; readBytes(&r,8); return r; }
/* load an integer type */
size_t loadInteger(Type::Tag ty)
{
switch (ty) {
case Type::PTY_CHAR : return read_char(); break;
case Type::PTY_UCHAR : return read_uchar(); break;
case Type::PTY_SHORT : return read_short(); break;
case Type::PTY_USHORT : return read_ushort(); break;
case Type::PTY_INT : return read_int(); break;
case Type::PTY_UINT : return read_uint(); break;
default : throw std::runtime_error("invalid type"); return 0;
}
}
/* load a list */
void loadPropertyList(std::vector<std::vector<size_t> >& vec,Type::Tag index_ty,Type::Tag data_ty)
{
std::vector<size_t> lst;
size_t num = loadInteger(index_ty);
for (size_t i=0; i<num; i++) lst.push_back(loadInteger(data_ty));
vec.push_back(lst);
}
/* load a data element */
void loadPropertyData(std::vector<float>& vec, Type::Tag ty)
{
switch (ty) {
case Type::PTY_CHAR : vec.push_back(float(read_char())); break;
case Type::PTY_UCHAR : vec.push_back(float(read_uchar())); break;
case Type::PTY_SHORT : vec.push_back(float(read_short())); break;
case Type::PTY_USHORT : vec.push_back(float(read_ushort())); break;
case Type::PTY_INT : vec.push_back(float(read_int())); break;
case Type::PTY_UINT : vec.push_back(float(read_uint())); break;
case Type::PTY_FLOAT : vec.push_back(float(read_float())); break;
case Type::PTY_DOUBLE : vec.push_back(float(read_double())); break;
default : throw std::runtime_error("invalid type");
}
}
Ref<SceneGraph::Node> import()
{
Material objmtl; new (&objmtl) OBJMaterial;
Ref<SceneGraph::MaterialNode> material = new SceneGraph::MaterialNode(objmtl);
Ref<SceneGraph::TriangleMeshNode> mesh_o = new SceneGraph::TriangleMeshNode(material,1);
/* convert all vertices */
const Element& vertices = mesh.elements.find("vertex")->second;
const std::vector<float>& posx = vertices.data.find("x")->second;
const std::vector<float>& posy = vertices.data.find("y")->second;
const std::vector<float>& posz = vertices.data.find("z")->second;
mesh_o->positions[0].resize(vertices.size);
for (size_t i=0; i<vertices.size; i++) {
mesh_o->positions[0][i].x = posx[i];
mesh_o->positions[0][i].y = posy[i];
mesh_o->positions[0][i].z = posz[i];
}
/* convert all faces */
const Element& faces = mesh.elements.find("face")->second;
const std::vector<std::vector<size_t> >& polygons = faces.list.find("vertex_indices")->second;
for (size_t j=0; j<polygons.size(); j++)
{
const std::vector<size_t>& face = polygons[j];
if (face.size() < 3) continue;
/* triangulate the face with a triangle fan */
size_t i0 = face[0], i1 = 0, i2 = face[1];
for (size_t k=2; k<face.size(); k++) {
i1 = i2; i2 = face[k];
mesh_o->triangles.push_back(SceneGraph::TriangleMeshNode::Triangle((unsigned int)i0, (unsigned int)i1, (unsigned int)i2));
}
}
return mesh_o.dynamicCast<SceneGraph::Node>();
}
};
Ref<Node> loadPLY(const FileName& fileName) {
return PlyParser(fileName).scene;
}
}
}
<commit_msg>bugfix in ply_loader.cpp<commit_after>// ======================================================================== //
// Copyright 2009-2016 Intel Corporation //
// //
// 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 "ply_loader.h"
#include <list>
namespace embree
{
namespace SceneGraph
{
/*! PLY type */
struct Type {
enum Tag { PTY_CHAR, PTY_UCHAR, PTY_SHORT, PTY_USHORT, PTY_INT, PTY_UINT, PTY_FLOAT, PTY_DOUBLE, PTY_LIST, PTY_NONE } ty, index, data;
Type() : ty(PTY_NONE), index(PTY_NONE), data(PTY_NONE) {}
Type(Tag ty) : ty(ty), index(PTY_NONE), data(PTY_NONE) {}
Type(Tag ty, Tag index, Tag data) : ty(ty), index(index), data(data) {}
};
/*! an element stored in the PLY file, such as vertex, face, etc. */
struct Element {
std::string name;
size_t size; /// number of data items of the element
std::vector<std::string> properties; /// list of all properties of the element (e.g. x, y, z) (not strictly necessary)
std::map<std::string,Type> type; /// mapping of property name to type
std::map<std::string,std::vector<float> > data; /// data array properties (all represented as floats)
std::map<std::string,std::vector<std::vector<size_t> > > list; /// list properties (integer lists supported only)
};
/*! mesh structure that reflects the PLY file format */
struct Mesh {
std::vector<std::string> order; /// order of all elements in file (not strictly necessary)
std::map<std::string,Element> elements; /// all elements of the file, e.g. vertex, face, ...
};
/* returns the size of a type in bytes */
size_t sizeOfType(Type::Tag ty)
{
switch (ty) {
case Type::PTY_CHAR : return 1;
case Type::PTY_UCHAR : return 1;
case Type::PTY_SHORT : return 2;
case Type::PTY_USHORT : return 2;
case Type::PTY_INT : return 4;
case Type::PTY_UINT : return 4;
case Type::PTY_FLOAT : return 4;
case Type::PTY_DOUBLE : return 8;
default : throw std::runtime_error("invalid type");
}
}
/* compute the type of a string */
Type::Tag typeTagOfString(const std::string& ty) {
if (ty == "char") return Type::PTY_CHAR;
if (ty == "int8") return Type::PTY_CHAR;
if (ty == "uchar") return Type::PTY_UCHAR;
if (ty == "uint8") return Type::PTY_UCHAR;
if (ty == "short") return Type::PTY_SHORT;
if (ty == "int16") return Type::PTY_SHORT;
if (ty == "ushort") return Type::PTY_USHORT;
if (ty == "uint16") return Type::PTY_USHORT;
if (ty == "int") return Type::PTY_INT;
if (ty == "int32") return Type::PTY_INT;
if (ty == "uint") return Type::PTY_UINT;
if (ty == "uint32") return Type::PTY_UINT;
if (ty == "float") return Type::PTY_FLOAT;
if (ty == "float32") return Type::PTY_FLOAT;
if (ty == "double") return Type::PTY_DOUBLE;
throw std::runtime_error("invalid type " + ty);
return Type::PTY_NONE;
}
/* compute the type of a string */
std::string stringOfTypeTag(Type::Tag ty) {
if (ty == Type::PTY_CHAR) return "char";
if (ty == Type::PTY_UCHAR) return "uchar";
if (ty == Type::PTY_SHORT) return "short";
if (ty == Type::PTY_USHORT) return "ushort";
if (ty == Type::PTY_INT) return "int";
if (ty == Type::PTY_UINT) return "uint";
if (ty == Type::PTY_FLOAT) return "float";
if (ty == Type::PTY_DOUBLE) return "double";
if (ty == Type::PTY_LIST) return "list";
throw std::runtime_error("invalid type");
return "";
}
/* compute the type of a string */
std::string stringOfType(Type ty) {
if (ty.ty == Type::PTY_LIST) return "list " + stringOfTypeTag(ty.index) + " " + stringOfTypeTag(ty.data);
else return stringOfTypeTag(ty.ty);
}
/* PLY parser class */
struct PlyParser
{
std::fstream fs;
Mesh mesh;
Ref<SceneGraph::Node> scene;
/* storage format of data in file */
enum Format { ASCII, BINARY_BIG_ENDIAN, BINARY_LITTLE_ENDIAN } format;
/* constructor parses the input stream */
PlyParser(const FileName& fileName) : format(ASCII)
{
/* open file */
fs.open (fileName.c_str(), std::fstream::in | std::fstream::binary);
if (!fs.is_open()) throw std::runtime_error("cannot open file : " + fileName.str());
/* check for file signature */
std::string signature; getline(fs,signature);
if (signature != "ply") throw std::runtime_error("invalid PLY file signature: " + signature);
/* read header */
std::list<std::string> header;
while (true) {
std::string line; getline(fs,line);
if (line == "end_header") break;
if (line.find_first_of('#') == 0) continue;
if (line == "") continue;
header.push_back(line);
}
/* parse header */
parseHeader(header);
/* now parse all elements */
for (std::vector<std::string>::iterator i = mesh.order.begin(); i!=mesh.order.end(); i++)
parseElementData(mesh.elements[*i]);
/* create triangle mesh */
scene = import();
}
/* parse the PLY header */
void parseHeader(std::list<std::string>& header)
{
while (!header.empty())
{
std::stringstream line(header.front());
header.pop_front();
std::string tag; line >> tag;
/* ignore comments */
if (tag == "comment") {
}
/* parse format */
else if (tag == "format")
{
std::string fmt; line >> fmt;
if (fmt == "ascii") format = ASCII;
else if (fmt == "binary_big_endian") format = BINARY_BIG_ENDIAN;
else if (fmt == "binary_little_endian") format = BINARY_LITTLE_ENDIAN;
else throw std::runtime_error("invalid PLY file format: " + fmt);
std::string version; line >> version;
if (version != "1.0") throw std::runtime_error("invalid PLY file version: " + version);
}
/* parse end of header tag */
else if (tag == "end_header")
break;
/* parse elements */
else if (tag == "element") parseElementDescr(line,header);
/* report unknown tags */
else throw std::runtime_error("unknown tag in PLY file: " + tag);
}
}
/* parses a PLY element description */
void parseElementDescr(std::stringstream& cin, std::list<std::string>& header)
{
Element elt;
std::string name; cin >> name;
size_t num; cin >> num;
mesh.order.push_back(name);
elt.name = name;
elt.size = num;
/* parse all properties */
while (!header.empty())
{
std::stringstream line(header.front());
std::string tag; line >> tag;
if (tag != "property") break;
header.pop_front();
Type ty = parseType(line);
std::string name; line >> name;
elt.type[name] = ty;
elt.properties.push_back(name);
}
mesh.elements[name] = elt;
}
/* parses a PLY type */
Type parseType(std::stringstream& cin)
{
std::string ty; cin >> ty;
if (ty == "list") {
std::string ty0; cin >> ty0;
std::string ty1; cin >> ty1;
return Type(Type::PTY_LIST,typeTagOfString(ty0),typeTagOfString(ty1));
} else return Type(typeTagOfString(ty));
}
/* parses data of a PLY element */
void parseElementData(Element& elt)
{
/* allocate data for all properties */
for (std::vector<std::string>::iterator i=elt.properties.begin(); i!=elt.properties.end(); i++) {
if (elt.type[*i].ty == Type::PTY_LIST) elt.list[*i] = std::vector<std::vector<size_t> >();
else elt.data[*i] = std::vector<float>();
}
/* parse all elements */
for (size_t e=0; e<elt.size; e++)
{
/* load all properties of the element */
for (std::vector<std::string>::iterator i=elt.properties.begin(); i!=elt.properties.end(); i++) {
Type ty = elt.type[*i];
if (ty.ty == Type::PTY_LIST) loadPropertyList(elt.list[*i],ty.index,ty.data);
else loadPropertyData(elt.data[*i],ty.ty);
}
}
}
/* load bytes from file and take care of little and big endian encoding */
void readBytes(void* dst, int num) {
if (format == BINARY_LITTLE_ENDIAN) fs.read((char*)dst,num);
else if (format == BINARY_BIG_ENDIAN) for (int i=0; i<num; i++) fs.read((char*)dst+num-i-1,1);
else throw std::runtime_error("internal error on PLY loader");
}
int read_ascii_int () { int i; fs >> i; return i; }
float read_ascii_float() { float f; fs >> f; return f; }
signed char read_char () { if (format == ASCII) return read_ascii_int(); signed char r = 0; readBytes(&r,1); return r; }
unsigned char read_uchar () { if (format == ASCII) return read_ascii_int(); unsigned char r = 0; readBytes(&r,1); return r; }
signed short read_short () { if (format == ASCII) return read_ascii_int(); signed short r = 0; readBytes(&r,2); return r; }
unsigned short read_ushort() { if (format == ASCII) return read_ascii_int(); unsigned short r = 0; readBytes(&r,2); return r; }
signed int read_int () { if (format == ASCII) return read_ascii_int(); signed int r = 0; readBytes(&r,4); return r; }
unsigned int read_uint () { if (format == ASCII) return read_ascii_int(); unsigned int r = 0; readBytes(&r,4); return r; }
float read_float () { if (format == ASCII) return read_ascii_float(); float r = 0; readBytes(&r,4); return r; }
double read_double() { if (format == ASCII) return read_ascii_float(); double r = 0; readBytes(&r,8); return r; }
/* load an integer type */
size_t loadInteger(Type::Tag ty)
{
switch (ty) {
case Type::PTY_CHAR : return read_char(); break;
case Type::PTY_UCHAR : return read_uchar(); break;
case Type::PTY_SHORT : return read_short(); break;
case Type::PTY_USHORT : return read_ushort(); break;
case Type::PTY_INT : return read_int(); break;
case Type::PTY_UINT : return read_uint(); break;
default : throw std::runtime_error("invalid type"); return 0;
}
}
/* load a list */
void loadPropertyList(std::vector<std::vector<size_t> >& vec,Type::Tag index_ty,Type::Tag data_ty)
{
std::vector<size_t> lst;
size_t num = loadInteger(index_ty);
for (size_t i=0; i<num; i++) lst.push_back(loadInteger(data_ty));
vec.push_back(lst);
}
/* load a data element */
void loadPropertyData(std::vector<float>& vec, Type::Tag ty)
{
switch (ty) {
case Type::PTY_CHAR : vec.push_back(float(read_char())); break;
case Type::PTY_UCHAR : vec.push_back(float(read_uchar())); break;
case Type::PTY_SHORT : vec.push_back(float(read_short())); break;
case Type::PTY_USHORT : vec.push_back(float(read_ushort())); break;
case Type::PTY_INT : vec.push_back(float(read_int())); break;
case Type::PTY_UINT : vec.push_back(float(read_uint())); break;
case Type::PTY_FLOAT : vec.push_back(float(read_float())); break;
case Type::PTY_DOUBLE : vec.push_back(float(read_double())); break;
default : throw std::runtime_error("invalid type");
}
}
Ref<SceneGraph::Node> import()
{
Material objmtl; new (&objmtl) OBJMaterial;
Ref<SceneGraph::MaterialNode> material = new SceneGraph::MaterialNode(objmtl);
Ref<SceneGraph::TriangleMeshNode> mesh_o = new SceneGraph::TriangleMeshNode(material,1);
/* convert all vertices */
const Element& vertices = mesh.elements.at("vertex");
const std::vector<float>& posx = vertices.data.at("x");
const std::vector<float>& posy = vertices.data.at("y");
const std::vector<float>& posz = vertices.data.at("z");
mesh_o->positions[0].resize(vertices.size);
for (size_t i=0; i<vertices.size; i++) {
mesh_o->positions[0][i].x = posx[i];
mesh_o->positions[0][i].y = posy[i];
mesh_o->positions[0][i].z = posz[i];
}
/* convert all faces */
const Element& faces = mesh.elements.at("face");
const std::vector<std::vector<size_t> >& polygons = faces.list.at("vertex_indices");
for (size_t j=0; j<polygons.size(); j++)
{
const std::vector<size_t>& face = polygons[j];
if (face.size() < 3) continue;
/* triangulate the face with a triangle fan */
size_t i0 = face[0], i1 = 0, i2 = face[1];
for (size_t k=2; k<face.size(); k++) {
i1 = i2; i2 = face[k];
mesh_o->triangles.push_back(SceneGraph::TriangleMeshNode::Triangle((unsigned int)i0, (unsigned int)i1, (unsigned int)i2));
}
}
return mesh_o.dynamicCast<SceneGraph::Node>();
}
};
Ref<Node> loadPLY(const FileName& fileName) {
return PlyParser(fileName).scene;
}
}
}
<|endoftext|> |
<commit_before>/// \file
/// \ingroup tutorial_ntuple
/// \notebook
/// Convert LHCb run 1 open data from a TTree to RNTuple.
/// This tutorial illustrates data conversion for a simple, tabular data model.
/// For reading, the tutorial shows the use of an ntuple View, which selectively accesses specific fields.
/// If a view is used for reading, there is no need to define the data model as an RNTupleModel first.
/// The advantage of a view is that it directly accesses RNTuple's data buffers without making an additional
/// memory copy.
///
/// \macro_image
/// \macro_code
///
/// \date April 2019
/// \author The ROOT Team
// NOTE: The RNTuple classes are experimental at this point.
// Functionality, interface, and data format is still subject to changes.
// Do not use for real data!
// Until C++ runtime modules are universally used, we explicitly load the ntuple library. Otherwise
// triggering autoloading from the use of templated types would require an exhaustive enumeration
// of "all" template instances in the LinkDef file.
R__LOAD_LIBRARY(ROOTNTuple)
#include <ROOT/RField.hxx>
#include <ROOT/RNTuple.hxx>
#include <ROOT/RNTupleModel.hxx>
#include <TBranch.h>
#include <TCanvas.h>
#include <TFile.h>
#include <TH1F.h>
#include <TLeaf.h>
#include <TTree.h>
#include <cassert>
#include <memory>
#include <vector>
// Import classes from experimental namespace for the time being
using RNTupleModel = ROOT::Experimental::RNTupleModel;
using RFieldBase = ROOT::Experimental::Detail::RFieldBase;
using RNTupleReader = ROOT::Experimental::RNTupleReader;
using RNTupleWriter = ROOT::Experimental::RNTupleWriter;
constexpr char const* kTreeFileName = "http://root.cern.ch/files/LHCb/lhcb_B2HHH_MagnetUp.root";
constexpr char const* kNTupleFileName = "ntpl003_lhcbOpenData.root";
void Convert() {
std::unique_ptr<TFile> f(TFile::Open(kTreeFileName));
assert(f && ! f->IsZombie());
// Get a unique pointer to an empty RNTuple model
auto model = RNTupleModel::Create();
// We create RNTuple fields based on the types found in the TTree
// This simple approach only works for trees with simple branches and only one leaf per branch
auto tree = f->Get<TTree>("DecayTree");
for (auto b : TRangeDynCast<TBranch>(*tree->GetListOfBranches())) {
// The dynamic cast to TBranch should never fail for GetListOfBranches()
assert(b);
// We assume every branch has a single leaf
TLeaf *l = static_cast<TLeaf*>(b->GetListOfLeaves()->First());
// Create an ntuple field with the same name and type than the tree branch
auto field = RFieldBase::Create(l->GetName(), l->GetTypeName());
std::cout << "Convert leaf " << l->GetName() << " [" << l->GetTypeName() << "]"
<< " --> " << "field " << field->GetName() << " [" << field->GetType() << "]" << std::endl;
// Hand over ownership of the field to the ntuple model. This will also create a memory location attached
// to the model's default entry, that will be used to place the data supposed to be written
model->AddField(std::move(field));
// We connect the model's default entry's memory location for the new field to the branch, so that we can
// fill the ntuple with the data read from the TTree
void *fieldDataPtr = model->GetDefaultEntry()->GetValue(l->GetName()).GetRawPtr();
tree->SetBranchAddress(b->GetName(), fieldDataPtr);
}
// The new ntuple takes ownership of the model
auto ntuple = RNTupleWriter::Recreate(std::move(model), "DecayTree", kNTupleFileName);
auto nEntries = tree->GetEntries();
for (decltype(nEntries) i = 0; i < nEntries; ++i) {
tree->GetEntry(i);
ntuple->Fill();
if (i && i % 100000 == 0)
std::cout << "Wrote " << i << " entries" << std::endl;
}
}
void ntpl003_lhcbOpenData()
{
Convert();
// Create histogram of the flight distance
// We open the ntuple without specifiying an explicit model first, but instead use a view on the field we are
// interested in
auto ntuple = RNTupleReader::Open("DecayTree", kNTupleFileName);
// The view wraps a read-only double value and accesses directly the ntuple's data buffers
auto viewFlightDistance = ntuple->GetView<double>("B_FlightDistance");
auto c = new TCanvas("c", "B Flight Distance", 200, 10, 700, 500);
TH1F h("h", "B Flight Distance", 200, 0, 140);
h.SetFillColor(48);
for (auto i : ntuple->GetEntryRange()) {
// Note that we do not load an entry in this loop, i.e. we avoid the memory copy of loading the data into
// the memory location given by the entry
h.Fill(viewFlightDistance(i));
}
h.DrawCopy();
}
<commit_msg>[ntuple] Fix-up tutorial after RFieldBase::Create() interface change<commit_after>/// \file
/// \ingroup tutorial_ntuple
/// \notebook
/// Convert LHCb run 1 open data from a TTree to RNTuple.
/// This tutorial illustrates data conversion for a simple, tabular data model.
/// For reading, the tutorial shows the use of an ntuple View, which selectively accesses specific fields.
/// If a view is used for reading, there is no need to define the data model as an RNTupleModel first.
/// The advantage of a view is that it directly accesses RNTuple's data buffers without making an additional
/// memory copy.
///
/// \macro_image
/// \macro_code
///
/// \date April 2019
/// \author The ROOT Team
// NOTE: The RNTuple classes are experimental at this point.
// Functionality, interface, and data format is still subject to changes.
// Do not use for real data!
// Until C++ runtime modules are universally used, we explicitly load the ntuple library. Otherwise
// triggering autoloading from the use of templated types would require an exhaustive enumeration
// of "all" template instances in the LinkDef file.
R__LOAD_LIBRARY(ROOTNTuple)
#include <ROOT/RField.hxx>
#include <ROOT/RNTuple.hxx>
#include <ROOT/RNTupleModel.hxx>
#include <TBranch.h>
#include <TCanvas.h>
#include <TFile.h>
#include <TH1F.h>
#include <TLeaf.h>
#include <TTree.h>
#include <cassert>
#include <memory>
#include <vector>
// Import classes from experimental namespace for the time being
using RNTupleModel = ROOT::Experimental::RNTupleModel;
using RFieldBase = ROOT::Experimental::Detail::RFieldBase;
using RNTupleReader = ROOT::Experimental::RNTupleReader;
using RNTupleWriter = ROOT::Experimental::RNTupleWriter;
constexpr char const* kTreeFileName = "http://root.cern.ch/files/LHCb/lhcb_B2HHH_MagnetUp.root";
constexpr char const* kNTupleFileName = "ntpl003_lhcbOpenData.root";
void Convert() {
std::unique_ptr<TFile> f(TFile::Open(kTreeFileName));
assert(f && ! f->IsZombie());
// Get a unique pointer to an empty RNTuple model
auto model = RNTupleModel::Create();
// We create RNTuple fields based on the types found in the TTree
// This simple approach only works for trees with simple branches and only one leaf per branch
auto tree = f->Get<TTree>("DecayTree");
for (auto b : TRangeDynCast<TBranch>(*tree->GetListOfBranches())) {
// The dynamic cast to TBranch should never fail for GetListOfBranches()
assert(b);
// We assume every branch has a single leaf
TLeaf *l = static_cast<TLeaf*>(b->GetListOfLeaves()->First());
// Create an ntuple field with the same name and type than the tree branch
auto field = RFieldBase::Create(l->GetName(), l->GetTypeName()).Unwrap();
std::cout << "Convert leaf " << l->GetName() << " [" << l->GetTypeName() << "]"
<< " --> " << "field " << field->GetName() << " [" << field->GetType() << "]" << std::endl;
// Hand over ownership of the field to the ntuple model. This will also create a memory location attached
// to the model's default entry, that will be used to place the data supposed to be written
model->AddField(std::move(field));
// We connect the model's default entry's memory location for the new field to the branch, so that we can
// fill the ntuple with the data read from the TTree
void *fieldDataPtr = model->GetDefaultEntry()->GetValue(l->GetName()).GetRawPtr();
tree->SetBranchAddress(b->GetName(), fieldDataPtr);
}
// The new ntuple takes ownership of the model
auto ntuple = RNTupleWriter::Recreate(std::move(model), "DecayTree", kNTupleFileName);
auto nEntries = tree->GetEntries();
for (decltype(nEntries) i = 0; i < nEntries; ++i) {
tree->GetEntry(i);
ntuple->Fill();
if (i && i % 100000 == 0)
std::cout << "Wrote " << i << " entries" << std::endl;
}
}
void ntpl003_lhcbOpenData()
{
Convert();
// Create histogram of the flight distance
// We open the ntuple without specifiying an explicit model first, but instead use a view on the field we are
// interested in
auto ntuple = RNTupleReader::Open("DecayTree", kNTupleFileName);
// The view wraps a read-only double value and accesses directly the ntuple's data buffers
auto viewFlightDistance = ntuple->GetView<double>("B_FlightDistance");
auto c = new TCanvas("c", "B Flight Distance", 200, 10, 700, 500);
TH1F h("h", "B Flight Distance", 200, 0, 140);
h.SetFillColor(48);
for (auto i : ntuple->GetEntryRange()) {
// Note that we do not load an entry in this loop, i.e. we avoid the memory copy of loading the data into
// the memory location given by the entry
h.Fill(viewFlightDistance(i));
}
h.DrawCopy();
}
<|endoftext|> |
<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "Timer.h"
#include "Cond.h"
#include "config.h"
#include "include/Context.h"
#define dout(x) if (x <= g_conf.debug_timer) *_dout << dbeginl << g_clock.now() << " TIMER "
#define derr(x) if (x <= g_conf.debug_timer) *_derr << dbeginl << g_clock.now() << " TIMER "
#define DBL 10
#include <signal.h>
#include <sys/time.h>
#include <math.h>
// single global instance
Timer g_timer;
/**** thread solution *****/
bool Timer::get_next_due(utime_t& when)
{
if (scheduled.empty()) {
return false;
} else {
map< utime_t, set<Context*> >::iterator it = scheduled.begin();
when = it->first;
return true;
}
}
void Timer::timer_entry()
{
lock.Lock();
utime_t now = g_clock.now();
while (!thread_stop) {
// any events due?
utime_t next;
bool next_due = get_next_due(next);
if (next_due) {
dout(10) << "get_next_due - " << next << dendl;
} else {
dout(10) << "get_next_due - nothing scheduled" << dendl;
}
if (next_due && now >= next) {
// move to pending list
list<Context*> pending;
map< utime_t, set<Context*> >::iterator it = scheduled.begin();
while (it != scheduled.end()) {
if (it->first > now) break;
utime_t t = it->first;
dout(DBL) << "queueing event(s) scheduled at " << t << dendl;
for (set<Context*>::iterator cit = it->second.begin();
cit != it->second.end();
cit++) {
pending.push_back(*cit);
event_times.erase(*cit);
num_event--;
}
map< utime_t, set<Context*> >::iterator previt = it;
it++;
scheduled.erase(previt);
}
if (!pending.empty()) {
sleeping = false;
lock.Unlock();
{
// make sure we're not holding any locks while we do callbacks
// make the callbacks myself.
for (list<Context*>::iterator cit = pending.begin();
cit != pending.end();
cit++) {
dout(DBL) << "start callback " << *cit << dendl;
(*cit)->finish(0);
dout(DBL) << "finish callback " << *cit << dendl;
delete *cit;
}
pending.clear();
assert(pending.empty());
}
lock.Lock();
}
now = g_clock.now();
dout(DBL) << "looping at " << now << dendl;
}
else {
// sleep
if (next_due) {
dout(DBL) << "sleeping until " << next << dendl;
timed_sleep = true;
sleeping = true;
timeout_cond.WaitUntil(lock, next); // wait for waker or time
now = g_clock.now();
dout(DBL) << "kicked or timed out at " << now << dendl;
} else {
dout(DBL) << "sleeping" << dendl;
timed_sleep = false;
sleeping = true;
sleep_cond.Wait(lock); // wait for waker
now = g_clock.now();
dout(DBL) << "kicked at " << now << dendl;
}
}
}
lock.Unlock();
}
/**
* Timer bits
*/
void Timer::register_timer()
{
if (timer_thread.is_started()) {
if (sleeping) {
dout(DBL) << "register_timer kicking thread" << dendl;
if (timed_sleep)
timeout_cond.SignalAll();
else
sleep_cond.SignalAll();
} else {
dout(DBL) << "register_timer doing nothing; thread is awake" << dendl;
// it's probably doing callbacks.
}
} else {
dout(DBL) << "register_timer starting thread" << dendl;
timer_thread.create();
}
}
void Timer::cancel_timer()
{
// clear my callback pointers
if (timer_thread.is_started()) {
dout(10) << "setting thread_stop flag" << dendl;
lock.Lock();
thread_stop = true;
if (timed_sleep)
timeout_cond.SignalAll();
else
sleep_cond.SignalAll();
lock.Unlock();
dout(10) << "waiting for thread to finish" << dendl;
void *ptr;
timer_thread.join(&ptr);
dout(10) << "thread finished, exit code " << ptr << dendl;
}
}
/*
* schedule
*/
void Timer::add_event_after(double seconds,
Context *callback)
{
utime_t when = g_clock.now();
when += seconds;
add_event_at(when, callback);
}
void Timer::add_event_at(utime_t when,
Context *callback)
{
lock.Lock();
dout(DBL) << "add_event " << callback << " at " << when << dendl;
// insert
scheduled[when].insert(callback);
assert(event_times.count(callback) == 0);
event_times[callback] = when;
num_event++;
// make sure i wake up on time
register_timer();
lock.Unlock();
}
bool Timer::cancel_event(Context *callback)
{
lock.Lock();
dout(DBL) << "cancel_event " << callback << dendl;
if (!event_times.count(callback)) {
dout(DBL) << "cancel_event " << callback << " isn't scheduled (probably executing)" << dendl;
lock.Unlock();
return false; // wasn't scheduled.
}
utime_t tp = event_times[callback];
event_times.erase(callback);
assert(scheduled.count(tp));
assert(scheduled[tp].count(callback));
scheduled[tp].erase(callback);
if (scheduled[tp].empty())
scheduled.erase(tp);
lock.Unlock();
// delete the canceled event.
delete callback;
return true;
}
// -------------------------------
void SafeTimer::add_event_after(double seconds, Context *c)
{
assert(lock.is_locked());
Context *w = new EventWrapper(this, c);
dout(DBL) << "SafeTimer.add_event_after wrapping " << c << " with " << w << dendl;
scheduled[c] = w;
g_timer.add_event_after(seconds, w);
}
void SafeTimer::add_event_at(utime_t when, Context *c)
{
assert(lock.is_locked());
Context *w = new EventWrapper(this, c);
dout(DBL) << "SafeTimer.add_event_at wrapping " << c << " with " << w << dendl;
scheduled[c] = w;
g_timer.add_event_at(when, w);
}
void SafeTimer::EventWrapper::finish(int r)
{
timer->lock.Lock();
if (timer->scheduled.count(actual)) {
// still scheduled. execute.
actual->finish(r);
timer->scheduled.erase(actual);
} else {
// i was canceled.
assert(timer->canceled.count(actual));
}
// did i get canceled?
// (this can happen even if i just executed above. e.g., i may have canceled myself.)
if (timer->canceled.count(actual)) {
timer->canceled.erase(actual);
timer->cond.Signal();
}
// delete the original event
delete actual;
timer->lock.Unlock();
}
void SafeTimer::cancel_event(Context *c)
{
assert(lock.is_locked());
assert(scheduled.count(c));
if (g_timer.cancel_event(scheduled[c])) {
// hosed wrapper. hose original event too.
delete c;
} else {
// clean up later.
canceled[c] = scheduled[c];
}
scheduled.erase(c);
}
void SafeTimer::cancel_all()
{
assert(lock.is_locked());
while (!scheduled.empty())
cancel_event(scheduled.begin()->first);
}
void SafeTimer::join()
{
assert(lock.is_locked());
assert(scheduled.empty());
if (!canceled.empty()) {
while (!canceled.empty()) {
// wait
dout(2) << "SafeTimer.join waiting for " << canceled.size() << " to join: " << canceled << dendl;
cond.Wait(lock);
}
dout(2) << "SafeTimer.join done" << dendl;
}
}
SafeTimer::~SafeTimer()
{
if (!scheduled.empty() && !canceled.empty()) {
derr(0) << "SafeTimer.~SafeTimer " << scheduled.size() << " events scheduled, "
<< canceled.size() << " canceled but unflushed"
<< dendl;
}
}
<commit_msg>timer debug crap<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab
/*
* Ceph - scalable distributed file system
*
* Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
*
* This is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software
* Foundation. See file COPYING.
*
*/
#include "Timer.h"
#include "Cond.h"
#include "config.h"
#include "include/Context.h"
#define dout(x) if (x <= g_conf.debug_timer) *_dout << dbeginl << g_clock.now() << " TIMER "
#define derr(x) if (x <= g_conf.debug_timer) *_derr << dbeginl << g_clock.now() << " TIMER "
#define DBL 10
#include <signal.h>
#include <sys/time.h>
#include <math.h>
// single global instance
Timer g_timer;
/**** thread solution *****/
bool Timer::get_next_due(utime_t& when)
{
if (scheduled.empty()) {
return false;
} else {
map< utime_t, set<Context*> >::iterator it = scheduled.begin();
when = it->first;
return true;
}
}
void Timer::timer_entry()
{
lock.Lock();
utime_t now = g_clock.now();
while (!thread_stop) {
dout(10) << "at top" << dendl;
// any events due?
utime_t next;
bool next_due = get_next_due(next);
if (next_due) {
dout(10) << "get_next_due - " << next << dendl;
} else {
dout(10) << "get_next_due - nothing scheduled" << dendl;
}
if (next_due && now >= next) {
// move to pending list
list<Context*> pending;
map< utime_t, set<Context*> >::iterator it = scheduled.begin();
while (it != scheduled.end()) {
if (it->first > now) break;
utime_t t = it->first;
dout(DBL) << "queueing event(s) scheduled at " << t << dendl;
for (set<Context*>::iterator cit = it->second.begin();
cit != it->second.end();
cit++) {
pending.push_back(*cit);
event_times.erase(*cit);
num_event--;
}
map< utime_t, set<Context*> >::iterator previt = it;
it++;
scheduled.erase(previt);
}
if (!pending.empty()) {
sleeping = false;
lock.Unlock();
{
// make sure we're not holding any locks while we do callbacks
// make the callbacks myself.
for (list<Context*>::iterator cit = pending.begin();
cit != pending.end();
cit++) {
dout(DBL) << "start callback " << *cit << dendl;
(*cit)->finish(0);
dout(DBL) << "finish callback " << *cit << dendl;
delete *cit;
}
pending.clear();
assert(pending.empty());
}
lock.Lock();
}
now = g_clock.now();
dout(DBL) << "looping at " << now << dendl;
}
else {
// sleep
if (next_due) {
dout(DBL) << "sleeping until " << next << dendl;
timed_sleep = true;
sleeping = true;
timeout_cond.WaitUntil(lock, next); // wait for waker or time
now = g_clock.now();
dout(DBL) << "kicked or timed out at " << now << dendl;
} else {
dout(DBL) << "sleeping" << dendl;
timed_sleep = false;
sleeping = true;
sleep_cond.Wait(lock); // wait for waker
now = g_clock.now();
dout(DBL) << "kicked at " << now << dendl;
}
dout(10) << "in brace" << dendl;
}
dout(10) << "at bottom" << dendl;
}
lock.Unlock();
}
/**
* Timer bits
*/
void Timer::register_timer()
{
if (timer_thread.is_started()) {
if (sleeping) {
dout(DBL) << "register_timer kicking thread" << dendl;
if (timed_sleep)
timeout_cond.SignalAll();
else
sleep_cond.SignalAll();
} else {
dout(DBL) << "register_timer doing nothing; thread is awake" << dendl;
// it's probably doing callbacks.
}
} else {
dout(DBL) << "register_timer starting thread" << dendl;
timer_thread.create();
}
}
void Timer::cancel_timer()
{
// clear my callback pointers
if (timer_thread.is_started()) {
dout(10) << "setting thread_stop flag" << dendl;
lock.Lock();
thread_stop = true;
if (timed_sleep)
timeout_cond.SignalAll();
else
sleep_cond.SignalAll();
lock.Unlock();
dout(10) << "waiting for thread to finish" << dendl;
void *ptr;
timer_thread.join(&ptr);
dout(10) << "thread finished, exit code " << ptr << dendl;
}
}
/*
* schedule
*/
void Timer::add_event_after(double seconds,
Context *callback)
{
utime_t when = g_clock.now();
when += seconds;
add_event_at(when, callback);
}
void Timer::add_event_at(utime_t when,
Context *callback)
{
lock.Lock();
dout(DBL) << "add_event " << callback << " at " << when << dendl;
// insert
scheduled[when].insert(callback);
assert(event_times.count(callback) == 0);
event_times[callback] = when;
num_event++;
// make sure i wake up on time
register_timer();
lock.Unlock();
}
bool Timer::cancel_event(Context *callback)
{
lock.Lock();
dout(DBL) << "cancel_event " << callback << dendl;
if (!event_times.count(callback)) {
dout(DBL) << "cancel_event " << callback << " isn't scheduled (probably executing)" << dendl;
lock.Unlock();
return false; // wasn't scheduled.
}
utime_t tp = event_times[callback];
event_times.erase(callback);
assert(scheduled.count(tp));
assert(scheduled[tp].count(callback));
scheduled[tp].erase(callback);
if (scheduled[tp].empty())
scheduled.erase(tp);
lock.Unlock();
// delete the canceled event.
delete callback;
return true;
}
// -------------------------------
void SafeTimer::add_event_after(double seconds, Context *c)
{
assert(lock.is_locked());
Context *w = new EventWrapper(this, c);
dout(DBL) << "SafeTimer.add_event_after wrapping " << c << " with " << w << dendl;
scheduled[c] = w;
g_timer.add_event_after(seconds, w);
}
void SafeTimer::add_event_at(utime_t when, Context *c)
{
assert(lock.is_locked());
Context *w = new EventWrapper(this, c);
dout(DBL) << "SafeTimer.add_event_at wrapping " << c << " with " << w << dendl;
scheduled[c] = w;
g_timer.add_event_at(when, w);
}
void SafeTimer::EventWrapper::finish(int r)
{
timer->lock.Lock();
if (timer->scheduled.count(actual)) {
// still scheduled. execute.
actual->finish(r);
timer->scheduled.erase(actual);
} else {
// i was canceled.
assert(timer->canceled.count(actual));
}
// did i get canceled?
// (this can happen even if i just executed above. e.g., i may have canceled myself.)
if (timer->canceled.count(actual)) {
timer->canceled.erase(actual);
timer->cond.Signal();
}
// delete the original event
delete actual;
timer->lock.Unlock();
}
void SafeTimer::cancel_event(Context *c)
{
assert(lock.is_locked());
assert(scheduled.count(c));
if (g_timer.cancel_event(scheduled[c])) {
// hosed wrapper. hose original event too.
delete c;
} else {
// clean up later.
canceled[c] = scheduled[c];
}
scheduled.erase(c);
}
void SafeTimer::cancel_all()
{
assert(lock.is_locked());
while (!scheduled.empty())
cancel_event(scheduled.begin()->first);
}
void SafeTimer::join()
{
assert(lock.is_locked());
assert(scheduled.empty());
if (!canceled.empty()) {
while (!canceled.empty()) {
// wait
dout(2) << "SafeTimer.join waiting for " << canceled.size() << " to join: " << canceled << dendl;
cond.Wait(lock);
}
dout(2) << "SafeTimer.join done" << dendl;
}
}
SafeTimer::~SafeTimer()
{
if (!scheduled.empty() && !canceled.empty()) {
derr(0) << "SafeTimer.~SafeTimer " << scheduled.size() << " events scheduled, "
<< canceled.size() << " canceled but unflushed"
<< dendl;
}
}
<|endoftext|> |
<commit_before>/*
module: terra-incognita
synopsis: ICFP 2006 contest postmission
author: heisenbug
copyright: 2006 terraincognita team
*/
#include <algorithm>
#include <iostream>
// Alternative (PseudoJIT) Universal Machine
struct d2cObject
{
const d2cObject& d2cClass;
private: d2cObject(void); // no impl.
};
struct d2cCell : d2cObject
{
unsigned data;
};
struct DylanVector : d2cObject
{
size_t size;
d2cCell arr[];
};
typedef void (*Fun)(void);
void Halt(Fun* array0, unsigned (®s)[10])
{
std::cerr << "Halting.\n" << std::endl;
}
typedef typeof(Halt) *Instruct;
#define genC(NAME, A, B) NAME<A, B, 0>, NAME<A, B, 1>, NAME<A, B, 2>, NAME<A, B, 3>, NAME<A, B, 4>, NAME<A, B, 5>, NAME<A, B, 6>, NAME<A, B, 7>
#define genB(NAME, A) genC(NAME, A, 0), genC(NAME, A, 1), genC(NAME, A, 2), genC(NAME, A, 3), genC(NAME, A, 4), genC(NAME, A, 5), genC(NAME, A, 6), genC(NAME, A, 7)
#define genA(NAME) genB(NAME, 0), genB(NAME, 1), genB(NAME, 2), genB(NAME, 3), genB(NAME, 4), genB(NAME, 5), genB(NAME, 6), genB(NAME, 7)
template <int A, int B, int C>
void Cond(Fun* array0, unsigned (®s)[10])
{
if (regs[C])
regs[A] = regs[B];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Index(Fun* array0, unsigned (®s)[10])
{
regs[A] = reinterpret_cast<unsigned*>(regs[B])[regs[C]];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Add(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] + regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Mul(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] * regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Div(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] / regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Nand(Fun* array0, unsigned (®s)[10])
{
regs[A] = ~(regs[B] & regs[C]);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
void Compiler(Fun* array0, unsigned (®s)[10])
{
DylanVector& v(*reinterpret_cast<DylanVector*>(regs[8]));
ptrdiff_t offset = array0 - reinterpret_cast<Fun*>(regs[9]);
unsigned platter = v.arr[offset].data;
std::cerr << std::hex <<"platter: " << platter << std::dec << std::endl;
Instruct compiled;
switch (platter >> 28)
{
case 0:
{
static Instruct const movers[8 * 8 * 8] = { genA(Cond) };
compiled = movers[platter & 0x1FF];
break;
};
case 1:
{
static Instruct const indexers[8 * 8 * 8] = { genA(Index) };
compiled = indexers[platter & 0x1FF];
break;
};
case 3:
{
static Instruct const adders[8 * 8 * 8] = { genA(Add) };
compiled = adders[platter & 0x1FF];
break;
};
case 4:
{
static Instruct const multipliers[8 * 8 * 8] = { genA(Mul) };
compiled = multipliers[platter & 0x1FF];
break;
};
case 5:
{
static Instruct const dividers[8 * 8 * 8] = { genA(Div) };
compiled = dividers[platter & 0x1FF];
break;
};
case 6:
{
static Instruct const nanders[8 * 8 * 8] = { genA(Nand) };
compiled = nanders[platter & 0x1FF];
break;
};
case 7:
compiled = Halt;
break;
};
array0[0] = reinterpret_cast<Fun>(compiled);
compiled(array0, regs);
}
Fun fillWithCompiler(const d2cCell&)
{
std::cerr << "fillWithCompiler." << std::endl;
return reinterpret_cast<Fun>(Compiler);
}
extern "C" void* enterUM(void* dylancookie, const struct DylanVector& v)
{
Fun* jitted = new Fun[v.size];
std::transform(v.arr, v.arr + v.size, jitted, fillWithCompiler);
unsigned regs[10] = { 0, 0, 0, 0, 0, 0, 0, 0, unsigned(&v), unsigned(jitted)};
reinterpret_cast<Instruct>(*jitted)(jitted, regs);
return dylancookie;
}
int main(void)
{
std::cerr << "main." << std::endl;
DylanVector& v(*(DylanVector*)new char[100]);
v.size = 2;
v.arr[0].data = (3 << 28) | (5 << 6) | (3 << 3) | 1; // Add: A = 5, B = 3, C = 1
v.arr[1].data = 7 << 28; // Halt
enterUM(NULL, v);
}
<commit_msg> use a copy of the dylan vector suitably manufactured for the JIT<commit_after>/*
module: terra-incognita
synopsis: ICFP 2006 contest postmission
author: heisenbug
copyright: 2006 terraincognita team
*/
#include <algorithm>
#include <iostream>
// Alternative (PseudoJIT) Universal Machine
typedef void (*Fun)(void);
void Halt(Fun* array0, unsigned (®s)[10])
{
std::cerr << "Halting.\n" << std::endl;
}
typedef typeof(Halt) *Instruct;
#define genC(NAME, A, B) NAME<A, B, 0>, NAME<A, B, 1>, NAME<A, B, 2>, NAME<A, B, 3>, NAME<A, B, 4>, NAME<A, B, 5>, NAME<A, B, 6>, NAME<A, B, 7>
#define genB(NAME, A) genC(NAME, A, 0), genC(NAME, A, 1), genC(NAME, A, 2), genC(NAME, A, 3), genC(NAME, A, 4), genC(NAME, A, 5), genC(NAME, A, 6), genC(NAME, A, 7)
#define genA(NAME) genB(NAME, 0), genB(NAME, 1), genB(NAME, 2), genB(NAME, 3), genB(NAME, 4), genB(NAME, 5), genB(NAME, 6), genB(NAME, 7)
template <int A, int B, int C>
void Cond(Fun* array0, unsigned (®s)[10])
{
if (regs[C])
regs[A] = regs[B];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Index(Fun* array0, unsigned (®s)[10])
{
const unsigned* arr(reinterpret_cast<unsigned*>(regs[B]));
regs[A] = arr ? arr[regs[C]] : reinterpret_cast<unsigned*>(regs[8])[regs[C]];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Add(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] + regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Mul(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] * regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Div(Fun* array0, unsigned (®s)[10])
{
regs[A] = regs[B] / regs[C];
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
template <int A, int B, int C>
void Nand(Fun* array0, unsigned (®s)[10])
{
regs[A] = ~(regs[B] & regs[C]);
++array0;
(*reinterpret_cast<Instruct*>(array0))(array0, regs);
}
void Compiler(Fun* array0, unsigned (®s)[10])
{
unsigned* v(reinterpret_cast<unsigned*>(regs[8]));
ptrdiff_t offset = array0 - reinterpret_cast<Fun*>(regs[9]);
unsigned platter = v[offset];
std::cerr << std::hex <<"platter: " << platter << std::dec << std::endl;
Instruct compiled;
switch (platter >> 28)
{
case 0:
{
static Instruct const movers[8 * 8 * 8] = { genA(Cond) };
compiled = movers[platter & 0x1FF];
break;
};
case 1:
{
static Instruct const indexers[8 * 8 * 8] = { genA(Index) };
compiled = indexers[platter & 0x1FF];
break;
};
case 3:
{
static Instruct const adders[8 * 8 * 8] = { genA(Add) };
compiled = adders[platter & 0x1FF];
break;
};
case 4:
{
static Instruct const multipliers[8 * 8 * 8] = { genA(Mul) };
compiled = multipliers[platter & 0x1FF];
break;
};
case 5:
{
static Instruct const dividers[8 * 8 * 8] = { genA(Div) };
compiled = dividers[platter & 0x1FF];
break;
};
case 6:
{
static Instruct const nanders[8 * 8 * 8] = { genA(Nand) };
compiled = nanders[platter & 0x1FF];
break;
};
case 7:
compiled = Halt;
break;
};
array0[0] = reinterpret_cast<Fun>(compiled);
compiled(array0, regs);
}
struct d2cObject
{
const d2cObject& d2cClass;
private: d2cObject(void); // no impl.
};
struct d2cCell : d2cObject
{
unsigned data;
};
struct DylanVector : d2cObject
{
size_t size;
d2cCell arr[];
};
Fun fillWithCompiler(const d2cCell&)
{
std::cerr << "fillWithCompiler." << std::endl;
return reinterpret_cast<Fun>(Compiler);
}
unsigned justCopy(const d2cCell& c)
{
std::cerr << "justCopy." << std::endl;
return c.data;
}
extern "C" void* enterUM(void* dylancookie, const struct DylanVector& v)
{
unsigned* copy = new unsigned[v.size];
std::transform(v.arr, v.arr + v.size, copy, justCopy);
Fun* jitted = new Fun[v.size];
std::transform(v.arr, v.arr + v.size, jitted, fillWithCompiler);
unsigned regs[10] = { 0, 0, 0, 0, 0, 0, 0, 0, unsigned(copy), unsigned(jitted)};
reinterpret_cast<Instruct>(*jitted)(jitted, regs);
return dylancookie;
}
int main(void)
{
std::cerr << "main." << std::endl;
DylanVector& v(*(DylanVector*)new char[100]);
v.size = 2;
v.arr[0].data = (3 << 28) | (5 << 6) | (3 << 3) | 1; // Add: A = 5, B = 3, C = 1
v.arr[1].data = 7 << 28; // Halt
enterUM(NULL, v);
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
class StaticUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void hexConversions();
void providers();
void capabilities();
void secureMemory();
private:
QCA::Initializer* m_init;
};
void StaticUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
#include "../fixpaths.include"
}
void StaticUnitTest::cleanupTestCase()
{
delete m_init;
}
void StaticUnitTest::hexConversions()
{
QByteArray test(10, 'a');
QCOMPARE( QCA::arrayToHex(test), QString("61616161616161616161") );
test.fill('b');
test[7] = 0x00;
QCOMPARE( test == QCA::hexToArray(QString("62626262626262006262")), true );
QCA::SecureArray testArray(10);
//testArray.fill( 'a' );
for (int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x61;
}
QCOMPARE( QCA::arrayToHex( testArray.toByteArray() ), QString( "61616161616161616161" ) );
//testArray.fill( 'b' );
for (int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x62;
}
testArray[6] = 0x00;
QCOMPARE( testArray == QCA::hexToArray(QString("62626262626200626262")), true );
QCOMPARE( testArray == QCA::hexToArray( QCA::arrayToHex( testArray.toByteArray() ) ), true );
testArray[9] = 0x00;
QCOMPARE( testArray == QCA::hexToArray( QCA::arrayToHex( testArray.toByteArray() ) ), true );
}
void StaticUnitTest::capabilities()
{
// capabilities are reported as a list - that is a problem for
// doing a direct comparison, since they change
// We try to work around that using contains()
QStringList supportedCapabilities = QCA::supportedFeatures();
QCOMPARE( supportedCapabilities.contains("random"), (QBool)true );
QCOMPARE( supportedCapabilities.contains("sha1"), (QBool)true );
QCOMPARE( supportedCapabilities.contains("sha0"), (QBool)true );
QCOMPARE( supportedCapabilities.contains("md2"),(QBool) true );
QCOMPARE( supportedCapabilities.contains("md4"), (QBool)true );
QCOMPARE( supportedCapabilities.contains("md5"), (QBool)true );
QCOMPARE( supportedCapabilities.contains("ripemd160"), (QBool)true );
QStringList defaultCapabilities = QCA::defaultFeatures();
QCOMPARE( defaultCapabilities.contains("random"), (QBool)true );
QCOMPARE( QCA::isSupported("random"), true );
QCOMPARE( QCA::isSupported("sha0"), true );
QCOMPARE( QCA::isSupported("sha0,sha1"), true );
QCOMPARE( QCA::isSupported("md2,md4,md5"), true );
QCOMPARE( QCA::isSupported("md5"), true );
QCOMPARE( QCA::isSupported("ripemd160"), true );
QCOMPARE( QCA::isSupported("sha256,sha384,sha512"), true );
QCOMPARE( QCA::isSupported("nosuchfeature"), false );
QString caps( "random,sha1,md5,ripemd160");
QStringList capList;
capList = caps.split( "," );
QCOMPARE( QCA::isSupported(capList), true );
capList.append("noSuch");
QCOMPARE( QCA::isSupported(capList), false );
capList.clear();
capList.append("noSuch");
QCOMPARE( QCA::isSupported(capList), false );
}
void StaticUnitTest::secureMemory()
{
// this should be reliably true
QCOMPARE( QCA::haveSecureMemory(), true );
}
void StaticUnitTest::providers()
{
// providers are obviously variable, this might be a bit brittle
QStringList providerNames;
QCA::scanForPlugins();
QCA::ProviderList qcaProviders = QCA::providers();
for (int i = 0; i < qcaProviders.size(); ++i) {
providerNames.append( qcaProviders[i]->name() );
}
QCOMPARE( providerNames.contains("qca-ossl"), (QBool)true );
QCOMPARE( providerNames.contains("qca-gcrypt"), (QBool)true );
QCOMPARE( providerNames.contains("qca-nss"), (QBool)true );
QCOMPARE( providerNames.contains("qca-pkcs11"), (QBool)true );
QCOMPARE( providerNames.contains("qca-gnupg"), (QBool)true );
QCOMPARE( providerNames.contains("qca-botan"), (QBool)true );
QCA::setProviderPriority("qca-ossl", 4);
QCA::setProviderPriority("qca-botan", 2);
QCOMPARE( QCA::providerPriority( "qca-ossl"), 4 );
QCOMPARE( QCA::providerPriority( "qca-gcrypt"), 0 );
QCOMPARE( QCA::providerPriority( "qca-botan"), 2 );
QCA::setProviderPriority("qca-ossl", 3);
// reuse last
QCA::setProviderPriority("qca-botan", -1);
QCOMPARE( QCA::providerPriority( "qca-botan"), 3 );
QCA::unloadAllPlugins();
}
QTEST_MAIN(StaticUnitTest)
#include "staticunittest.moc"
<commit_msg>Reduce the scope of the unit testing, in order to make the tests less brittle.<commit_after>/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* 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 AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
class StaticUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void hexConversions();
void capabilities();
void secureMemory();
private:
QCA::Initializer* m_init;
};
void StaticUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
#include "../fixpaths.include"
}
void StaticUnitTest::cleanupTestCase()
{
delete m_init;
}
void StaticUnitTest::hexConversions()
{
QByteArray test(10, 'a');
QCOMPARE( QCA::arrayToHex(test), QString("61616161616161616161") );
test.fill('b');
test[7] = 0x00;
QCOMPARE( test == QCA::hexToArray(QString("62626262626262006262")), true );
QCA::SecureArray testArray(10);
//testArray.fill( 'a' );
for (int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x61;
}
QCOMPARE( QCA::arrayToHex( testArray.toByteArray() ), QString( "61616161616161616161" ) );
//testArray.fill( 'b' );
for (int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x62;
}
testArray[6] = 0x00;
QCOMPARE( testArray == QCA::hexToArray(QString("62626262626200626262")), true );
QCOMPARE( testArray == QCA::hexToArray( QCA::arrayToHex( testArray.toByteArray() ) ), true );
testArray[9] = 0x00;
QCOMPARE( testArray == QCA::hexToArray( QCA::arrayToHex( testArray.toByteArray() ) ), true );
}
void StaticUnitTest::capabilities()
{
// capabilities are reported as a list - that is a problem for
// doing a direct comparison, since they change
// We try to work around that using contains()
QStringList defaultCapabilities = QCA::defaultFeatures();
QVERIFY( defaultCapabilities.contains("random") );
QVERIFY( defaultCapabilities.contains("sha1") );
QVERIFY( defaultCapabilities.contains("md5") );
QStringList capList;
capList << "random" << "sha1";
QCOMPARE( QCA::isSupported(capList), true );
capList.append("noSuch");
QCOMPARE( QCA::isSupported(capList), false );
capList.clear();
capList.append("noSuch");
QCOMPARE( QCA::isSupported(capList), false );
}
void StaticUnitTest::secureMemory()
{
// this should be reliably true
QCOMPARE( QCA::haveSecureMemory(), true );
}
QTEST_MAIN(StaticUnitTest)
#include "staticunittest.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, Nagoya University
* 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 Autoware 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 "state_machine.h"
namespace state_machine
{
void StateTrafficLightStop::update(StateContext *context)
{
if (context->getLightColor() == TrafficLight::GREEN)
context->setState(StateMoveForward::create());
}
void StateMoveForward::update(StateContext *context)
{
if (context->getLightColor() == TrafficLight::RED)
context->setState(StateTrafficLightStop::create());
if(context->getChangeFlag() == ChangeFlag::right || context->getChangeFlag() == ChangeFlag::left)
context->setState(StateLaneChange::create());
}
void StateLaneChange::update(StateContext *context)
{
if(context->getChangeFlag() == ChangeFlag::straight)
context->setState(StateMoveForward::create());
}
void StateStopSignStop::update(StateContext *context)
{
// stop sign stop
}
} // state_machine<commit_msg>Add update function<commit_after>/*
* Copyright (c) 2015, Nagoya University
* 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 Autoware 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 "state_machine.h"
namespace state_machine
{
void StateTrafficLightStop::update(StateContext *context)
{
if (context->getLightColor() == TrafficLight::GREEN)
context->setState(StateMoveForward::create());
}
void StateMoveForward::update(StateContext *context)
{
if (context->getLightColor() == TrafficLight::RED)
context->setState(StateTrafficLightStop::create());
if(context->getChangeFlag() == ChangeFlag::right || context->getChangeFlag() == ChangeFlag::left)
context->setState(StateLaneChange::create());
}
void StateLaneChange::update(StateContext *context)
{
if(context->getChangeFlag() == ChangeFlag::straight)
context->setState(StateMoveForward::create());
}
void StateStopSignStop::update(StateContext *context)
{
// stop sign stop
}
void StateMissionComplete::update(StateContext *context)
{
// Mission complete
}
void StateEmergency::update(StateContext *context)
{
// Emergency
}
} // state_machine<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "ECSE/SetSystem.h"
#include "TestUtils.h"
// Test SetSystem because System is lacking features for a reasonable test
class DummySystem : public ECSE::SetSystem
{
public:
explicit DummySystem()
: SetSystem(nullptr)
{ }
bool passChecks = true;
protected:
bool checkRequirements(const ECSE::Entity&) const override
{
return passChecks;
}
};
class SystemTest : public ::testing::Test
{
public:
DummySystem system;
};
TEST_F(SystemTest, TestInspect)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "One entity should be added";
ASSERT_TRUE(entities.find(&e) != entities.end()) << "Same entity should be added";
}
TEST_F(SystemTest, TestInspectTwice)
{
ECSE::Entity e;
system.inspectEntity(e);
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Entity should only be added once";
}
TEST_F(SystemTest, TestAddTwice)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Entity should only be added once";
}
TEST_F(SystemTest, TestAddMultiple)
{
ECSE::Entity added[5];
for (auto& e : added)
{
system.inspectEntity(e);
}
system.advance();
auto entities = system.getEntities();
for (ECSE::Entity &e : added)
{
ASSERT_TRUE(contains(entities, &e)) << "Entity should have been added";
}
}
TEST_F(SystemTest, TestRemove)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
system.markToRemove(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(0, entities.size()) << "Entity should be removed";
}
TEST_F(SystemTest, TestMarkToRemoveTwice)
{
ECSE::Entity e1;
ECSE::Entity e2;
system.inspectEntity(e1);
system.inspectEntity(e2);
system.advance();
system.markToRemove(e1);
system.markToRemove(e1);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Only one entity should be removed";
ASSERT_EQ(&e2, *entities.begin()) << "Only first entity should be removed";
}
TEST_F(SystemTest, TestRemoveTwice)
{
ECSE::Entity e1;
ECSE::Entity e2;
system.inspectEntity(e1);
system.inspectEntity(e2);
system.advance();
system.markToRemove(e1);
system.advance();
system.markToRemove(e1);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Only one entity should be removed";
ASSERT_EQ(&e2, *entities.begin()) << "Only first entity should be removed";
}
TEST_F(SystemTest, TestRemoveMultiple)
{
ECSE::Entity added[5];
for (auto& e : added)
{
system.inspectEntity(e);
}
system.advance();
system.markToRemove(added[1]);
system.markToRemove(added[4]);
system.advance();
auto entities = system.getEntities();
ASSERT_TRUE(contains(entities, &added[0])) << "Entity should not have been removed";
ASSERT_FALSE(contains(entities, &added[1])) << "Entity should have been removed";
ASSERT_TRUE(contains(entities, &added[2])) << "Entity should not have been removed";
ASSERT_TRUE(contains(entities, &added[3])) << "Entity should not have been removed";
ASSERT_FALSE(contains(entities, &added[4])) << "Entity should have been removed";
}<commit_msg>Added testing for system.hasEntity and used it more frequently<commit_after>#include "gtest/gtest.h"
#include "ECSE/SetSystem.h"
#include "TestUtils.h"
// Test SetSystem because System is lacking features for a reasonable test
class DummySystem : public ECSE::SetSystem
{
public:
explicit DummySystem()
: SetSystem(nullptr)
{ }
bool passChecks = true;
protected:
bool checkRequirements(const ECSE::Entity&) const override
{
return passChecks;
}
};
class SystemTest : public ::testing::Test
{
public:
DummySystem system;
};
TEST_F(SystemTest, TestInspect)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "One entity should be added";
ASSERT_TRUE(system.hasEntity(e)) << "Same entity should be added";
}
TEST_F(SystemTest, TestInspectFailRequirements)
{
ECSE::Entity e;
system.passChecks = false;
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_TRUE(entities.empty()) << "Entity should not be added";
ASSERT_FALSE(system.hasEntity(e)) << "Same entity should not be added";
}
TEST_F(SystemTest, TestInspectTwice)
{
ECSE::Entity e;
system.inspectEntity(e);
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Entity should only be added once";
ASSERT_TRUE(system.hasEntity(e)) << "Same entity should be added";
}
TEST_F(SystemTest, TestAddTwice)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
system.inspectEntity(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Entity should only be added once";
ASSERT_TRUE(system.hasEntity(e)) << "Same entity should be added";
}
TEST_F(SystemTest, TestAddMultiple)
{
ECSE::Entity added[5];
for (auto& e : added)
{
system.inspectEntity(e);
}
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(5, entities.size()) << "Entities should be added";
for (ECSE::Entity &e : added)
{
ASSERT_TRUE(system.hasEntity(e)) << "Entity should have been added";
}
}
TEST_F(SystemTest, TestHasEntity)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
ASSERT_TRUE(system.hasEntity(e)) << "Entity was added but hasEntity returned false";
}
TEST_F(SystemTest, TestHasEntityFalse)
{
ECSE::Entity e;
ASSERT_FALSE(system.hasEntity(e)) << "Entity was not added but hasEntity returned true";
}
TEST_F(SystemTest, TestRemove)
{
ECSE::Entity e;
system.inspectEntity(e);
system.advance();
system.markToRemove(e);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(0, entities.size()) << "Entity should be removed";
}
TEST_F(SystemTest, TestMarkToRemoveTwice)
{
ECSE::Entity e1;
ECSE::Entity e2;
system.inspectEntity(e1);
system.inspectEntity(e2);
system.advance();
system.markToRemove(e1);
system.markToRemove(e1);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Only one entity should be removed";
ASSERT_TRUE(system.hasEntity(e2)) << "Only first entity should be removed";
}
TEST_F(SystemTest, TestRemoveTwice)
{
ECSE::Entity e1;
ECSE::Entity e2;
system.inspectEntity(e1);
system.inspectEntity(e2);
system.advance();
system.markToRemove(e1);
system.advance();
system.markToRemove(e1);
system.advance();
auto entities = system.getEntities();
ASSERT_EQ(1, entities.size()) << "Only one entity should be removed";
ASSERT_TRUE(system.hasEntity(e2)) << "Only first entity should be removed";
}
TEST_F(SystemTest, TestRemoveMultiple)
{
ECSE::Entity added[5];
for (auto& e : added)
{
system.inspectEntity(e);
}
system.advance();
system.markToRemove(added[1]);
system.markToRemove(added[4]);
system.advance();
auto entities = system.getEntities();
ASSERT_TRUE(system.hasEntity(added[0])) << "Entity should not have been removed";
ASSERT_FALSE(system.hasEntity(added[1])) << "Entity should have been removed";
ASSERT_TRUE(system.hasEntity(added[2])) << "Entity should not have been removed";
ASSERT_TRUE(system.hasEntity(added[3])) << "Entity should not have been removed";
ASSERT_FALSE(system.hasEntity(added[4])) << "Entity should have been removed";
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <type_traits>
#include "TestDataSet.hpp"
#include <nix/hdf5/Selection.hpp>
using namespace nix; //quick fix for now
using namespace nix::hdf5;
unsigned int & TestDataSet::open_mode()
{
static unsigned int openMode = H5F_ACC_TRUNC;
return openMode;
}
void TestDataSet::setUp() {
unsigned int &openMode = open_mode();
h5file = H5::H5File("test_dataset.h5", openMode);
if (openMode == H5F_ACC_TRUNC) {
h5group = h5file.createGroup("charon");
} else {
h5group = h5file.openGroup("charon");
}
openMode = H5F_ACC_RDWR;
}
void TestDataSet::testNDSize() {
NDSize a = {23, 42, 1982};
typedef typename NDSize::value_type value_type;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), a[2]);
CPPUNIT_ASSERT_THROW(a[3], std::out_of_range);
a++;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(24), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(43), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1983), a[2]);
a--;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), a[2]);
a += 13;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(36), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(55), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1995), a[2]);
a -= 13;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), a[2]);
NDSize b = {19, 1940, 18};
NDSize c = a + b;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), c[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), c[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(2000), c[2]);
NDSize d = c - b;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), d[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), d[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), d[2]);
NDSize f = {1, 2, 3, 4};
CPPUNIT_ASSERT_THROW(a + f, std::out_of_range);
NDSize g(f.size(), 0);
g += f;
CPPUNIT_ASSERT(g == f);
CPPUNIT_ASSERT(g != a);
NDSize h = b / b;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1), h[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1), h[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1), h[2]);
NDSize j(h.size(), static_cast<value_type>(333));
NDSize k = h * j;
CPPUNIT_ASSERT(j == k);
size_t dp = j.dot(h);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(999), dp);
NDSize s = {3, 4};
dp = s.dot(s);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(25), dp);
}
void TestDataSet::testChunkGuessing() {
NDSize dims = {1024, 1024};
NDSize chunks = DataSet::guessChunking(dims, DataType::Double);
CPPUNIT_ASSERT_EQUAL(chunks[0], 64ULL);
CPPUNIT_ASSERT_EQUAL(chunks[1], 64ULL);
}
void TestDataSet::testBasic() {
NDSize dims = {4, 6};
NDSize chunks = DataSet::guessChunking(dims, DataType::Double);
NDSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDouble", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[4][6]);
int values = 0;
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
A[i][j] = values++;
ds.write(A);
array_type B(boost::extents[1][1]);
ds.read(B, true);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
//** check for setExtent()
array_type C(boost::extents[8][12]);
values = 0;
for(index i = 0; i != 8; ++i)
for(index j = 0; j != 12; ++j)
C[i][j] = values++;
dims[0] = 8;
dims[1] = 12;
ds.setExtent(dims);
ds.write(C);
array_type E(boost::extents[8][12]);
ds.read(E);
for(index i = 0; i != 8; ++i)
for(index j = 0; j != 12; ++j)
CPPUNIT_ASSERT_EQUAL(C[i][j], E[i][j]);
NDSize newSize = {4, 6};
ds.setExtent(newSize);
NDSize newDSSize = ds.size();
CPPUNIT_ASSERT_EQUAL(newSize, newDSSize);
array_type F(boost::extents[4][6]);
ds.read(F);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(E[i][j], F[i][j]);
//***
DataSet ds2 = DataSet::create(h5group, "dsDouble2", A);
ds2.write(A);
array_type D(boost::extents[1][1]);
ds2.read(D, true);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], D[i][j]);
}
void TestDataSet::testSelection() {
NDSize dims = {15, 15};
NDSize chunks = DataSet::guessChunking(dims, DataType::Double);
NDSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDoubleSelection", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[5][5]);
int values = 1;
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
A[i][j] = values++;
Selection memSelection(A);
Selection fileSelection = ds.createSelection();
NDSize fileCount(dims.size());
NDSize fileStart(dims.size());
fileCount.fill(5ULL);
fileStart.fill(5ULL);
fileSelection.select(fileCount, fileStart);
NDSize boundsStart(dims.size());
NDSize boundsEnd(dims.size());
fileSelection.bounds(boundsStart, boundsEnd);
NDSize boundsSize = fileSelection.size();
ds.write(A, fileSelection, memSelection);
array_type B(boost::extents[5][5]);
ds.read(B, fileSelection); //NB: no mem-selection
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
NDSSize offset(dims.size(), 5);
fileSelection.offset(offset);
ds.write(A, fileSelection);
array_type C(boost::extents[5][5]);
ds.read(C, fileSelection, true);
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], C[i][j]);
}
/* helper functions vor testValueIO */
template<typename T>
void test_val_generic(H5::Group &h5group, const T &test_value)
{
std::vector<nix::Value> values = {nix::Value(test_value), nix::Value(test_value)};
nix::NDSize size = {1};
nix::NDSize maxsize = {H5S_UNLIMITED};
nix::NDSize chunks = nix::hdf5::DataSet::guessChunking(size, values[0].type());
H5::DataType fileType = nix::hdf5::DataSet::fileTypeForValue(values[0].type());
nix::hdf5::DataSet ds = nix::hdf5::DataSet::create(h5group, typeid(T).name(), fileType, size, &maxsize, &chunks);
ds.write(values);
std::vector<nix::Value> checkValues;
ds.read(checkValues);
CPPUNIT_ASSERT_EQUAL(values.size(), checkValues.size());
for (size_t i = 0; i < values.size(); ++i) {
CPPUNIT_ASSERT_EQUAL(values[i].get<T>(), checkValues[i].get<T>());
}
}
void TestDataSet::testValueIO() {
test_val_generic(h5group, true);
test_val_generic(h5group, 42);
test_val_generic(h5group, 42U);
test_val_generic(h5group, std::string("String Value"));
}
void TestDataSet::testNDArrayIO()
{
nix::NDSize dims({5, 5});
nix::NDArray A(nix::DataType::Double, dims);
int values = 0;
for(size_t i = 0; i != 5; ++i)
for(size_t j = 0; j != 5; ++j)
A.set<double>({i,j}, values++);
DataSet ds = nix::hdf5::DataSet::create(h5group, "NArray5x5", A);
ds.write(A);
nix::NDArray Atest(nix::DataType::Double, dims);
ds.read(Atest);
for(size_t i = 0; i != 5; ++i)
for(size_t j = 0; j != 5; ++j)
CPPUNIT_ASSERT_DOUBLES_EQUAL(A.get<double>({i,j}),
Atest.get<double>({i,j}),
std::numeric_limits<double>::epsilon());
//**
dims = {3, 4, 5};
NDArray B(nix::DataType::Double, dims);
values = 0;
for(size_t i = 0; i != dims[0]; ++i)
for(size_t j = 0; j != dims[1]; ++j)
for(size_t k = 0; k != dims[2]; ++k)
B.set<double>({i,j,k}, values++);
ds = nix::hdf5::DataSet::create(h5group, "NDArray3x4x5", B);
ds.write(B);
nix::NDArray Btest(nix::DataType::Double, dims);
ds.read(Btest);
for(size_t i = 0; i != dims[0]; ++i)
for(size_t j = 0; j != dims[1]; ++j)
for(size_t k = 0; k != dims[2]; ++k)
CPPUNIT_ASSERT_DOUBLES_EQUAL(B.get<double>({i,j,k}),
Btest.get<double>({i,j,k}),
std::numeric_limits<double>::epsilon());
}
void TestDataSet::tearDown() {
h5group.close();
h5file.close();
}
<commit_msg>[win32] TestDataSet: VS2013 doesn't like typename in typedef<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <type_traits>
#include "TestDataSet.hpp"
#include <nix/hdf5/Selection.hpp>
using namespace nix; //quick fix for now
using namespace nix::hdf5;
unsigned int & TestDataSet::open_mode()
{
static unsigned int openMode = H5F_ACC_TRUNC;
return openMode;
}
void TestDataSet::setUp() {
unsigned int &openMode = open_mode();
h5file = H5::H5File("test_dataset.h5", openMode);
if (openMode == H5F_ACC_TRUNC) {
h5group = h5file.createGroup("charon");
} else {
h5group = h5file.openGroup("charon");
}
openMode = H5F_ACC_RDWR;
}
void TestDataSet::testNDSize() {
NDSize a = {23, 42, 1982};
#ifndef _WIN32
typedef typename NDSize::value_type value_type;
#else
typedef NDSize::value_type value_type;
#endif
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), a[2]);
CPPUNIT_ASSERT_THROW(a[3], std::out_of_range);
a++;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(24), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(43), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1983), a[2]);
a--;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), a[2]);
a += 13;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(36), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(55), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1995), a[2]);
a -= 13;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), a[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), a[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), a[2]);
NDSize b = {19, 1940, 18};
NDSize c = a + b;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), c[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), c[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(2000), c[2]);
NDSize d = c - b;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(23), d[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(42), d[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1982), d[2]);
NDSize f = {1, 2, 3, 4};
CPPUNIT_ASSERT_THROW(a + f, std::out_of_range);
NDSize g(f.size(), 0);
g += f;
CPPUNIT_ASSERT(g == f);
CPPUNIT_ASSERT(g != a);
NDSize h = b / b;
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1), h[0]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1), h[1]);
CPPUNIT_ASSERT_EQUAL(static_cast<value_type>(1), h[2]);
NDSize j(h.size(), static_cast<value_type>(333));
NDSize k = h * j;
CPPUNIT_ASSERT(j == k);
size_t dp = j.dot(h);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(999), dp);
NDSize s = {3, 4};
dp = s.dot(s);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(25), dp);
}
void TestDataSet::testChunkGuessing() {
NDSize dims = {1024, 1024};
NDSize chunks = DataSet::guessChunking(dims, DataType::Double);
CPPUNIT_ASSERT_EQUAL(chunks[0], 64ULL);
CPPUNIT_ASSERT_EQUAL(chunks[1], 64ULL);
}
void TestDataSet::testBasic() {
NDSize dims = {4, 6};
NDSize chunks = DataSet::guessChunking(dims, DataType::Double);
NDSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDouble", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[4][6]);
int values = 0;
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
A[i][j] = values++;
ds.write(A);
array_type B(boost::extents[1][1]);
ds.read(B, true);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
//** check for setExtent()
array_type C(boost::extents[8][12]);
values = 0;
for(index i = 0; i != 8; ++i)
for(index j = 0; j != 12; ++j)
C[i][j] = values++;
dims[0] = 8;
dims[1] = 12;
ds.setExtent(dims);
ds.write(C);
array_type E(boost::extents[8][12]);
ds.read(E);
for(index i = 0; i != 8; ++i)
for(index j = 0; j != 12; ++j)
CPPUNIT_ASSERT_EQUAL(C[i][j], E[i][j]);
NDSize newSize = {4, 6};
ds.setExtent(newSize);
NDSize newDSSize = ds.size();
CPPUNIT_ASSERT_EQUAL(newSize, newDSSize);
array_type F(boost::extents[4][6]);
ds.read(F);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(E[i][j], F[i][j]);
//***
DataSet ds2 = DataSet::create(h5group, "dsDouble2", A);
ds2.write(A);
array_type D(boost::extents[1][1]);
ds2.read(D, true);
for(index i = 0; i != 4; ++i)
for(index j = 0; j != 6; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], D[i][j]);
}
void TestDataSet::testSelection() {
NDSize dims = {15, 15};
NDSize chunks = DataSet::guessChunking(dims, DataType::Double);
NDSize maxdims(dims.size());
maxdims.fill(H5S_UNLIMITED);
DataSet ds = DataSet::create(h5group, "dsDoubleSelection", DataType::Double, dims, &maxdims, &chunks);
typedef boost::multi_array<double, 2> array_type;
typedef array_type::index index;
array_type A(boost::extents[5][5]);
int values = 1;
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
A[i][j] = values++;
Selection memSelection(A);
Selection fileSelection = ds.createSelection();
NDSize fileCount(dims.size());
NDSize fileStart(dims.size());
fileCount.fill(5ULL);
fileStart.fill(5ULL);
fileSelection.select(fileCount, fileStart);
NDSize boundsStart(dims.size());
NDSize boundsEnd(dims.size());
fileSelection.bounds(boundsStart, boundsEnd);
NDSize boundsSize = fileSelection.size();
ds.write(A, fileSelection, memSelection);
array_type B(boost::extents[5][5]);
ds.read(B, fileSelection); //NB: no mem-selection
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], B[i][j]);
NDSSize offset(dims.size(), 5);
fileSelection.offset(offset);
ds.write(A, fileSelection);
array_type C(boost::extents[5][5]);
ds.read(C, fileSelection, true);
for(index i = 0; i != 5; ++i)
for(index j = 0; j != 5; ++j)
CPPUNIT_ASSERT_EQUAL(A[i][j], C[i][j]);
}
/* helper functions vor testValueIO */
template<typename T>
void test_val_generic(H5::Group &h5group, const T &test_value)
{
std::vector<nix::Value> values = {nix::Value(test_value), nix::Value(test_value)};
nix::NDSize size = {1};
nix::NDSize maxsize = {H5S_UNLIMITED};
nix::NDSize chunks = nix::hdf5::DataSet::guessChunking(size, values[0].type());
H5::DataType fileType = nix::hdf5::DataSet::fileTypeForValue(values[0].type());
nix::hdf5::DataSet ds = nix::hdf5::DataSet::create(h5group, typeid(T).name(), fileType, size, &maxsize, &chunks);
ds.write(values);
std::vector<nix::Value> checkValues;
ds.read(checkValues);
CPPUNIT_ASSERT_EQUAL(values.size(), checkValues.size());
for (size_t i = 0; i < values.size(); ++i) {
CPPUNIT_ASSERT_EQUAL(values[i].get<T>(), checkValues[i].get<T>());
}
}
void TestDataSet::testValueIO() {
test_val_generic(h5group, true);
test_val_generic(h5group, 42);
test_val_generic(h5group, 42U);
test_val_generic(h5group, std::string("String Value"));
}
void TestDataSet::testNDArrayIO()
{
nix::NDSize dims({5, 5});
nix::NDArray A(nix::DataType::Double, dims);
int values = 0;
for(size_t i = 0; i != 5; ++i)
for(size_t j = 0; j != 5; ++j)
A.set<double>({i,j}, values++);
DataSet ds = nix::hdf5::DataSet::create(h5group, "NArray5x5", A);
ds.write(A);
nix::NDArray Atest(nix::DataType::Double, dims);
ds.read(Atest);
for(size_t i = 0; i != 5; ++i)
for(size_t j = 0; j != 5; ++j)
CPPUNIT_ASSERT_DOUBLES_EQUAL(A.get<double>({i,j}),
Atest.get<double>({i,j}),
std::numeric_limits<double>::epsilon());
//**
dims = {3, 4, 5};
NDArray B(nix::DataType::Double, dims);
values = 0;
for(size_t i = 0; i != dims[0]; ++i)
for(size_t j = 0; j != dims[1]; ++j)
for(size_t k = 0; k != dims[2]; ++k)
B.set<double>({i,j,k}, values++);
ds = nix::hdf5::DataSet::create(h5group, "NDArray3x4x5", B);
ds.write(B);
nix::NDArray Btest(nix::DataType::Double, dims);
ds.read(Btest);
for(size_t i = 0; i != dims[0]; ++i)
for(size_t j = 0; j != dims[1]; ++j)
for(size_t k = 0; k != dims[2]; ++k)
CPPUNIT_ASSERT_DOUBLES_EQUAL(B.get<double>({i,j,k}),
Btest.get<double>({i,j,k}),
std::numeric_limits<double>::epsilon());
}
void TestDataSet::tearDown() {
h5group.close();
h5file.close();
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/** @file AliFMDRawReader.cxx
@author Christian Holm Christensen <cholm@nbi.dk>
@date Mon Mar 27 12:45:23 2006
@brief Class to read raw data
@ingroup FMD_rec
*/
//____________________________________________________________________
//
// Class to read ADC values from a AliRawReader object.
//
// This class uses the AliFMDRawStreamer class to read the ALTRO
// formatted data.
//
// +-------+
// | TTask |
// +-------+
// ^
// |
// +-----------------+ <<references>> +--------------+
// | AliFMDRawReader |<>----------------| AliRawReader |
// +-----------------+ +--------------+
// | ^
// | <<uses>> |
// V |
// +-----------------+ <<uses>> |
// | AliFMDRawStream |------------------------+
// +-----------------+
// |
// V
// +----------------+
// | AliAltroStream |
// +----------------+
//
// #include <AliLog.h> // ALILOG_H
#include "AliFMDDebug.h" // Better debug macros
#include "AliFMDParameters.h" // ALIFMDPARAMETERS_H
#include "AliFMDDigit.h" // ALIFMDDIGIT_H
#include "AliFMDRawStream.h" // ALIFMDRAWSTREAM_H
// #include "AliRawReader.h" // ALIRAWREADER_H
#include "AliFMDRawReader.h" // ALIFMDRAWREADER_H
// #include "AliFMDAltroIO.h" // ALIFMDALTROIO_H
// #include <TArrayI.h> // ROOT_TArrayI
#include <TTree.h> // ROOT_TTree
#include <TClonesArray.h> // ROOT_TClonesArray
// #include <iostream>
// #include <iomanip>
//____________________________________________________________________
ClassImp(AliFMDRawReader)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliFMDRawReader::AliFMDRawReader(AliRawReader* reader, TTree* tree)
: TTask("FMDRawReader", "Reader of Raw ADC values from the FMD"),
fTree(tree),
fReader(reader),
fSampleRate(1)
{
// Default CTOR
}
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read the data
TClonesArray* array = new TClonesArray("AliFMDDigit");
if (!fTree) {
AliError("No tree");
return;
}
fTree->Branch("FMD", &array);
ReadAdcs(array);
Int_t nWrite = fTree->Fill();
AliFMDDebug(1, ("Got a grand total of %d digits, wrote %d bytes to tree",
array->GetEntries(), nWrite));
}
#if 1
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
AliFMDRawStream input(fReader);
AliFMDDebug(5, ("Setting old RCU format and 7 word headers"));
input.SetOldRCUFormat(!pars->HasRcuTrailer());
input.SetShortDataHeader(!pars->HasCompleteHeader());
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 14+5;
UInt_t ddl = 0;
UInt_t rate = 0;
UInt_t last = 0;
UInt_t hwaddr = 0;
// Data array is approx twice the size needed.
UShort_t data[2048];
Bool_t isGood = kTRUE;
while (isGood) {
isGood = input.ReadChannel(ddl, hwaddr, last, data);
if (!isGood) break;
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to get detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
preSamp = pars->GetPreSamples(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntriesFast();
Short_t curStr = str + stripMin + (i-preSamp) / rate;
if ((curStr-str) > stripMax) {
// AliInfo(Form("timebin %4d -> (%3d+%3d+(%4d-%d)/%d) -> %d",
// i, str, stripMin, i, preSamp, rate, curStr));
// AliError(Form("Current strip is %3d (0x%04x,0x%03x,%4d) "
// "but DB says max is %3d (rate=%d)",
// curStr, ddl, hwaddr, i, str+stripMax, rate));
// Garbage timebins - ignore
continue;
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0),
(rate >= 4 ? data[i+3] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
if (rate >= 4) i++;
}
}
return kTRUE;
}
#else
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
// Select FMD DDL's
fReader->Select("FMD");
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 0;
do {
UChar_t* cdata;
if (!fReader->ReadNextData(cdata)) break;
size_t nchar = fReader->GetDataSize();
UShort_t ddl = fReader->GetDDLID();
UShort_t rate = 0;
AliFMDDebug(1, ("Reading %d bytes (%d 10bit words) from %d",
nchar, nchar * 8 / 10, ddl));
// Make a stream to read from
std::string str((char*)(cdata), nchar);
std::istringstream s(str);
// Prep the reader class.
AliFMDAltroReader r(s);
// Data array is approx twice the size needed.
UShort_t data[2048], hwaddr, last;
while (r.ReadChannel(hwaddr, last, data) > 0) {
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntries();
UShort_t curStr = str + stripMin + i / rate;
if ((curStr-str) > stripMax) {
AliError(Form("Current strip is %d but DB says max is %d",
curStr, stripMax));
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
}
if (r.IsBof()) break;
}
} while (true);
return kTRUE;
}
// This is the old method, for comparison. It's really ugly, and far
// too convoluted.
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read raw data into the digits array
// if (!fReader->ReadHeader()) {
// Error("ReadAdcs", "Couldn't read header");
// return;
// }
Int_t n = 0;
TClonesArray* array = new TClonesArray("AliFMDDigit");
fTree->Branch("FMD", &array);
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
fSampleRate = pars->GetSampleRate(0);
// Use AliAltroRawStream to read the ALTRO format. No need to
// reinvent the wheel :-)
AliFMDRawStream input(fReader, fSampleRate);
// Select FMD DDL's
fReader->Select("FMD");
Int_t oldDDL = -1;
Int_t count = 0;
UShort_t detector = 1; // Must be one here
UShort_t oldDetector = 0;
Bool_t next = kTRUE;
// local Cache
TArrayI counts(10);
counts.Reset(-1);
// Loop over data in file
while (next) {
next = input.Next();
count++;
Int_t ddl = fReader->GetDDLID();
AliFMDDebug(10, ("Current DDL is %d", ddl));
if (ddl != oldDDL || input.IsNewStrip() || !next) {
// Make a new digit, if we have some data (oldDetector == 0,
// means that we haven't really read anything yet - that is,
// it's the first time we get here).
if (oldDetector > 0) {
// Got a new strip.
AliFMDDebug(10, ("Add a new strip: FMD%d%c[%2d,%3d] "
"(current: FMD%d%c[%2d,%3d])",
oldDetector, input.PrevRing(),
input.PrevSector() , input.PrevStrip(),
detector , input.Ring(), input.Sector(),
input.Strip()));
new ((*array)[n]) AliFMDDigit(oldDetector,
input.PrevRing(),
input.PrevSector(),
input.PrevStrip(),
counts[0], counts[1], counts[2]);
n++;
#if 0
AliFMDDigit* digit =
static_cast<AliFMDDigit*>(fFMD->Digits()->
UncheckedAt(fFMD->GetNdigits()-1));
#endif
}
if (!next) {
AliFMDDebug(10, ("Read %d channels for FMD%d",
count + 1, detector));
break;
}
// If we got a new DDL, it means we have a new detector.
if (ddl != oldDDL) {
if (detector != 0)
AliFMDDebug(10, ("Read %d channels for FMD%d", count + 1, detector));
// Reset counts, and update the DDL cache
count = 0;
oldDDL = ddl;
// Check that we're processing a FMD detector
Int_t detId = fReader->GetDetectorID();
if (detId != (AliDAQ::DetectorID("FMD"))) {
AliError(Form("Detector ID %d != %d",
detId, (AliDAQ::DetectorID("FMD"))));
break;
}
// Figure out what detector we're deling with
oldDetector = detector;
switch (ddl) {
case 0: detector = 1; break;
case 1: detector = 2; break;
case 2: detector = 3; break;
default:
AliError(Form("Unknown DDL 0x%x for FMD", ddl));
return;
}
AliFMDDebug(10, ("Reading ADCs for 0x%x - That is FMD%d",
fReader->GetEquipmentId(), detector));
}
counts.Reset(-1);
}
counts[input.Sample()] = input.Count();
AliFMDDebug(10, ("ADC of FMD%d%c[%2d,%3d] += %d",
detector, input.Ring(), input.Sector(),
input.Strip(), input.Count()));
oldDetector = detector;
}
fTree->Fill();
return;
}
#endif
//____________________________________________________________________
//
// EOF
//
<commit_msg>Changed call to TClonesArray::GetEntries() to TClonesArray::GetEntriesFast() for performance<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
/** @file AliFMDRawReader.cxx
@author Christian Holm Christensen <cholm@nbi.dk>
@date Mon Mar 27 12:45:23 2006
@brief Class to read raw data
@ingroup FMD_rec
*/
//____________________________________________________________________
//
// Class to read ADC values from a AliRawReader object.
//
// This class uses the AliFMDRawStreamer class to read the ALTRO
// formatted data.
//
// +-------+
// | TTask |
// +-------+
// ^
// |
// +-----------------+ <<references>> +--------------+
// | AliFMDRawReader |<>----------------| AliRawReader |
// +-----------------+ +--------------+
// | ^
// | <<uses>> |
// V |
// +-----------------+ <<uses>> |
// | AliFMDRawStream |------------------------+
// +-----------------+
// |
// V
// +----------------+
// | AliAltroStream |
// +----------------+
//
// #include <AliLog.h> // ALILOG_H
#include "AliFMDDebug.h" // Better debug macros
#include "AliFMDParameters.h" // ALIFMDPARAMETERS_H
#include "AliFMDDigit.h" // ALIFMDDIGIT_H
#include "AliFMDRawStream.h" // ALIFMDRAWSTREAM_H
// #include "AliRawReader.h" // ALIRAWREADER_H
#include "AliFMDRawReader.h" // ALIFMDRAWREADER_H
// #include "AliFMDAltroIO.h" // ALIFMDALTROIO_H
// #include <TArrayI.h> // ROOT_TArrayI
#include <TTree.h> // ROOT_TTree
#include <TClonesArray.h> // ROOT_TClonesArray
// #include <iostream>
// #include <iomanip>
//____________________________________________________________________
ClassImp(AliFMDRawReader)
#if 0
; // This is here to keep Emacs for indenting the next line
#endif
//____________________________________________________________________
AliFMDRawReader::AliFMDRawReader(AliRawReader* reader, TTree* tree)
: TTask("FMDRawReader", "Reader of Raw ADC values from the FMD"),
fTree(tree),
fReader(reader),
fSampleRate(1)
{
// Default CTOR
}
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read the data
TClonesArray* array = new TClonesArray("AliFMDDigit");
if (!fTree) {
AliError("No tree");
return;
}
fTree->Branch("FMD", &array);
ReadAdcs(array);
Int_t nWrite = fTree->Fill();
AliFMDDebug(1, ("Got a grand total of %d digits, wrote %d bytes to tree",
array->GetEntriesFast(), nWrite));
}
#if 1
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
AliFMDRawStream input(fReader);
AliFMDDebug(5, ("Setting old RCU format and 7 word headers"));
input.SetOldRCUFormat(!pars->HasRcuTrailer());
input.SetShortDataHeader(!pars->HasCompleteHeader());
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 14+5;
UInt_t ddl = 0;
UInt_t rate = 0;
UInt_t last = 0;
UInt_t hwaddr = 0;
// Data array is approx twice the size needed.
UShort_t data[2048];
Bool_t isGood = kTRUE;
while (isGood) {
isGood = input.ReadChannel(ddl, hwaddr, last, data);
if (!isGood) break;
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to get detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
preSamp = pars->GetPreSamples(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntriesFast();
Short_t curStr = str + stripMin + (i-preSamp) / rate;
if ((curStr-str) > stripMax) {
// AliInfo(Form("timebin %4d -> (%3d+%3d+(%4d-%d)/%d) -> %d",
// i, str, stripMin, i, preSamp, rate, curStr));
// AliError(Form("Current strip is %3d (0x%04x,0x%03x,%4d) "
// "but DB says max is %3d (rate=%d)",
// curStr, ddl, hwaddr, i, str+stripMax, rate));
// Garbage timebins - ignore
continue;
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0),
(rate >= 4 ? data[i+3] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
if (rate >= 4) i++;
}
}
return kTRUE;
}
#else
//____________________________________________________________________
Bool_t
AliFMDRawReader::ReadAdcs(TClonesArray* array)
{
// Read raw data into the digits array, using AliFMDAltroReader.
if (!array) {
AliError("No TClonesArray passed");
return kFALSE;
}
// if (!fReader->ReadHeader()) {
// AliError("Couldn't read header");
// return kFALSE;
// }
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
// Select FMD DDL's
fReader->Select("FMD");
UShort_t stripMin = 0;
UShort_t stripMax = 127;
UShort_t preSamp = 0;
do {
UChar_t* cdata;
if (!fReader->ReadNextData(cdata)) break;
size_t nchar = fReader->GetDataSize();
UShort_t ddl = fReader->GetDDLID();
UShort_t rate = 0;
AliFMDDebug(1, ("Reading %d bytes (%d 10bit words) from %d",
nchar, nchar * 8 / 10, ddl));
// Make a stream to read from
std::string str((char*)(cdata), nchar);
std::istringstream s(str);
// Prep the reader class.
AliFMDAltroReader r(s);
// Data array is approx twice the size needed.
UShort_t data[2048], hwaddr, last;
while (r.ReadChannel(hwaddr, last, data) > 0) {
AliFMDDebug(5, ("Read channel 0x%x of size %d", hwaddr, last));
UShort_t det, sec, str;
Char_t ring;
if (!pars->Hardware2Detector(ddl, hwaddr, det, ring, sec, str)) {
AliError(Form("Failed to detector id from DDL %d "
"and hardware address 0x%x", ddl, hwaddr));
continue;
}
rate = pars->GetSampleRate(det, ring, sec, str);
stripMin = pars->GetMinStrip(det, ring, sec, str);
stripMax = pars->GetMaxStrip(det, ring, sec, str);
AliFMDDebug(5, ("DDL 0x%04x, address 0x%03x maps to FMD%d%c[%2d,%3d]",
ddl, hwaddr, det, ring, sec, str));
// Loop over the `timebins', and make the digits
for (size_t i = 0; i < last; i++) {
if (i < preSamp) continue;
Int_t n = array->GetEntries();
UShort_t curStr = str + stripMin + i / rate;
if ((curStr-str) > stripMax) {
AliError(Form("Current strip is %d but DB says max is %d",
curStr, stripMax));
}
AliFMDDebug(5, ("making digit for FMD%d%c[%2d,%3d] from sample %4d",
det, ring, sec, curStr, i));
new ((*array)[n]) AliFMDDigit(det, ring, sec, curStr, data[i],
(rate >= 2 ? data[i+1] : 0),
(rate >= 3 ? data[i+2] : 0));
if (rate >= 2) i++;
if (rate >= 3) i++;
}
if (r.IsBof()) break;
}
} while (true);
return kTRUE;
}
// This is the old method, for comparison. It's really ugly, and far
// too convoluted.
//____________________________________________________________________
void
AliFMDRawReader::Exec(Option_t*)
{
// Read raw data into the digits array
// if (!fReader->ReadHeader()) {
// Error("ReadAdcs", "Couldn't read header");
// return;
// }
Int_t n = 0;
TClonesArray* array = new TClonesArray("AliFMDDigit");
fTree->Branch("FMD", &array);
// Get sample rate
AliFMDParameters* pars = AliFMDParameters::Instance();
fSampleRate = pars->GetSampleRate(0);
// Use AliAltroRawStream to read the ALTRO format. No need to
// reinvent the wheel :-)
AliFMDRawStream input(fReader, fSampleRate);
// Select FMD DDL's
fReader->Select("FMD");
Int_t oldDDL = -1;
Int_t count = 0;
UShort_t detector = 1; // Must be one here
UShort_t oldDetector = 0;
Bool_t next = kTRUE;
// local Cache
TArrayI counts(10);
counts.Reset(-1);
// Loop over data in file
while (next) {
next = input.Next();
count++;
Int_t ddl = fReader->GetDDLID();
AliFMDDebug(10, ("Current DDL is %d", ddl));
if (ddl != oldDDL || input.IsNewStrip() || !next) {
// Make a new digit, if we have some data (oldDetector == 0,
// means that we haven't really read anything yet - that is,
// it's the first time we get here).
if (oldDetector > 0) {
// Got a new strip.
AliFMDDebug(10, ("Add a new strip: FMD%d%c[%2d,%3d] "
"(current: FMD%d%c[%2d,%3d])",
oldDetector, input.PrevRing(),
input.PrevSector() , input.PrevStrip(),
detector , input.Ring(), input.Sector(),
input.Strip()));
new ((*array)[n]) AliFMDDigit(oldDetector,
input.PrevRing(),
input.PrevSector(),
input.PrevStrip(),
counts[0], counts[1], counts[2]);
n++;
#if 0
AliFMDDigit* digit =
static_cast<AliFMDDigit*>(fFMD->Digits()->
UncheckedAt(fFMD->GetNdigits()-1));
#endif
}
if (!next) {
AliFMDDebug(10, ("Read %d channels for FMD%d",
count + 1, detector));
break;
}
// If we got a new DDL, it means we have a new detector.
if (ddl != oldDDL) {
if (detector != 0)
AliFMDDebug(10, ("Read %d channels for FMD%d", count + 1, detector));
// Reset counts, and update the DDL cache
count = 0;
oldDDL = ddl;
// Check that we're processing a FMD detector
Int_t detId = fReader->GetDetectorID();
if (detId != (AliDAQ::DetectorID("FMD"))) {
AliError(Form("Detector ID %d != %d",
detId, (AliDAQ::DetectorID("FMD"))));
break;
}
// Figure out what detector we're deling with
oldDetector = detector;
switch (ddl) {
case 0: detector = 1; break;
case 1: detector = 2; break;
case 2: detector = 3; break;
default:
AliError(Form("Unknown DDL 0x%x for FMD", ddl));
return;
}
AliFMDDebug(10, ("Reading ADCs for 0x%x - That is FMD%d",
fReader->GetEquipmentId(), detector));
}
counts.Reset(-1);
}
counts[input.Sample()] = input.Count();
AliFMDDebug(10, ("ADC of FMD%d%c[%2d,%3d] += %d",
detector, input.Ring(), input.Sector(),
input.Strip(), input.Count()));
oldDetector = detector;
}
fTree->Fill();
return;
}
#endif
//____________________________________________________________________
//
// EOF
//
<|endoftext|> |
<commit_before>#include <chrono>
#include <limits>
#include <sstream>
#include "Tools/Perf/common/hard_decide.h"
#include "Tools/Exception/exception.hpp"
#include "Tools/Math/utils.h"
#include "Decoder_LDPC_BP_flooding_Gallager_B.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
template <typename B, typename R>
Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::Decoder_LDPC_BP_flooding_Gallager_B(const int K, const int N, const int n_ite, const tools::Sparse_matrix &_H,
const std::vector<unsigned> &info_bits_pos, const bool enable_syndrome,
const int syndrome_depth, const int n_frames)
: Decoder (K, N, n_frames, 1 ),
Decoder_SIHO_HIHO<B,R>(K, N, n_frames, 1 ),
Decoder_LDPC_BP (K, N, n_ite, _H, enable_syndrome, syndrome_depth),
info_bits_pos (info_bits_pos ),
HY_N (N ),
V_N (N ),
chk_to_var (this->H.get_n_connections(), 0 ),
var_to_chk (this->H.get_n_connections(), 0 ),
transpose (this->H.get_n_connections() )
{
const std::string name = "Decoder_LDPC_BP_flooding_Gallager_B";
this->set_name(name);
std::vector<unsigned char> connections(this->H.get_n_rows(), 0);
const auto &chk_to_var_id = this->H.get_col_to_rows();
const auto &var_to_chk_id = this->H.get_row_to_cols();
auto k = 0;
for (auto i = 0; i < (int)chk_to_var_id.size(); i++)
{
for (auto j = 0; j < (int)chk_to_var_id[i].size(); j++)
{
auto var_id = chk_to_var_id[i][j];
auto branch_id = 0;
for (auto ii = 0; ii < (int)var_id; ii++)
branch_id += (int)var_to_chk_id[ii].size();
branch_id += connections[var_id];
connections[var_id]++;
if (connections[var_id] > (int)var_to_chk_id[var_id].size())
{
std::stringstream message;
message << "'connections[var_id]' has to be equal or smaller than 'var_to_chk_id[var_id].size()' "
<< "('var_id' = " << var_id << ", 'connections[var_id]' = " << connections[var_id]
<< ", 'var_to_chk_id[var_id].size()' = " << var_to_chk_id[var_id].size() << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
transpose[k] = branch_id;
k++;
}
}
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const int frame_id)
{
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(Y_N);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
for (auto i = 0; i < this->K; i++)
V_K[i] = (B)this->V_N[this->info_bits_pos[i]];
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::decode, d_decod);
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const int frame_id)
{
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(Y_N);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
std::copy(this->V_N.begin(), this->V_N.begin() + this->N, V_N);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_siho(const R *Y_N, B *V_K, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
tools::hard_decide(Y_N, HY_N.data(), this->N);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(HY_N.data());
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
for (auto i = 0; i < this->K; i++)
V_K[i] = (B)this->V_N[this->info_bits_pos[i]];
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::load, d_load);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::decode, d_decod);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
tools::hard_decide(Y_N, HY_N.data(), this->N);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(HY_N.data());
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
std::copy(this->V_N.begin(), this->V_N.begin() + this->N, V_N);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::load, d_load);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode(const B *Y_N)
{
auto ite = 0;
for (; ite < this->n_ite; ite++)
{
this->_initialize_var_to_chk(Y_N, chk_to_var, var_to_chk, ite == 0);
this->_decode_single_ite(var_to_chk, chk_to_var);
if (this->enable_syndrome && ite != this->n_ite -1)
{
// for the K variable nodes (make a majority vote with the entering messages)
this->_make_majority_vote(Y_N, this->V_N);
if (this->check_syndrome_hard(this->V_N.data()))
break;
}
}
if (ite == this->n_ite)
this->_make_majority_vote(Y_N, this->V_N);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_initialize_var_to_chk(const B *Y_N, const std::vector<int8_t> &chk_to_var, std::vector<int8_t> &var_to_chk,
const bool first_ite)
{
auto chk_to_var_ptr = chk_to_var.data();
auto var_to_chk_ptr = var_to_chk.data();
// for each variable nodes
const auto n_var_nodes = (int)this->H.get_n_rows();
for (auto v = 0; v < n_var_nodes; v++)
{
const auto var_degree = (int)this->H.get_row_to_cols()[v].size();
const auto cur_state = (B)1 - (Y_N[v] + Y_N[v]);
if (first_ite)
{
for (auto c = 0; c < var_degree; c++)
var_to_chk_ptr[c] = (int8_t)cur_state;
}
else
{
auto sum = cur_state;
for (auto c = 0; c < var_degree; c++)
sum += chk_to_var_ptr[c];
for (auto c = 0; c < var_degree; c++)
{
auto message = sum;
message -= chk_to_var_ptr[c];
const auto sign = std::signbit(message) ? -1 : 1;
const auto t = (B)1; // threshold for a majority voting decoding
message = (sign * message) < t ? cur_state : sign;
var_to_chk_ptr[c] = (int8_t)message;
}
}
chk_to_var_ptr += var_degree;
var_to_chk_ptr += var_degree;
}
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_single_ite(const std::vector<int8_t> &var_to_chk, std::vector<int8_t> &chk_to_var)
{
auto transpose_ptr = this->transpose.data();
// for each check nodes
const auto n_chk_nodes = (int)this->H.get_n_cols();
for (auto c = 0; c < n_chk_nodes; c++)
{
const auto chk_degree = (int)this->H.get_col_to_rows()[c].size();
auto acc = 1;
for (auto v = 0; v < chk_degree; v++)
acc *= var_to_chk[transpose_ptr[v]];
for (auto v = 0; v < chk_degree; v++)
chk_to_var[transpose_ptr[v]] = acc * var_to_chk[transpose_ptr[v]];
transpose_ptr += chk_degree;
}
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_make_majority_vote(const B *Y_N, std::vector<int8_t> &V_N)
{
auto chk_to_var_ptr = this->chk_to_var.data();
// for the K variable nodes (make a majority vote with the entering messages)
const auto n_var_nodes = (int)this->H.get_n_rows();
for (auto v = 0; v < n_var_nodes; v++)
{
const auto var_degree = (int)this->H.get_row_to_cols()[v].size();
const auto cur_state = (B)1 - (Y_N[v] + Y_N[v]);
auto count = cur_state;
for (auto c = 0; c < var_degree; c++)
count += chk_to_var_ptr[c];
// take the hard decision
V_N[v] = count ? std::signbit(count) : Y_N[v];
chk_to_var_ptr += var_degree;
}
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef AFF3CT_MULTI_PREC
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_8,Q_8>;
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_16,Q_16>;
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_32,Q_32>;
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Fix the Gallager B<commit_after>#include <chrono>
#include <numeric>
#include <limits>
#include <sstream>
#include "Tools/Perf/common/hard_decide.h"
#include "Tools/Exception/exception.hpp"
#include "Tools/Math/utils.h"
#include "Decoder_LDPC_BP_flooding_Gallager_B.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
template <typename B, typename R>
Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::Decoder_LDPC_BP_flooding_Gallager_B(const int K, const int N, const int n_ite, const tools::Sparse_matrix &_H,
const std::vector<unsigned> &info_bits_pos, const bool enable_syndrome,
const int syndrome_depth, const int n_frames)
: Decoder (K, N, n_frames, 1 ),
Decoder_SIHO_HIHO<B,R>(K, N, n_frames, 1 ),
Decoder_LDPC_BP (K, N, n_ite, _H, enable_syndrome, syndrome_depth),
info_bits_pos (info_bits_pos ),
HY_N (N ),
V_N (N ),
chk_to_var (this->H.get_n_connections(), 0 ),
var_to_chk (this->H.get_n_connections(), 0 ),
transpose (this->H.get_n_connections() )
{
const std::string name = "Decoder_LDPC_BP_flooding_Gallager_B";
this->set_name(name);
std::vector<unsigned char> connections(this->H.get_n_rows(), 0);
const auto &chk_to_var_id = this->H.get_col_to_rows();
const auto &var_to_chk_id = this->H.get_row_to_cols();
auto k = 0;
for (auto i = 0; i < (int)chk_to_var_id.size(); i++)
{
for (auto j = 0; j < (int)chk_to_var_id[i].size(); j++)
{
auto var_id = chk_to_var_id[i][j];
auto branch_id = 0;
for (auto ii = 0; ii < (int)var_id; ii++)
branch_id += (int)var_to_chk_id[ii].size();
branch_id += connections[var_id];
connections[var_id]++;
if (connections[var_id] > (int)var_to_chk_id[var_id].size())
{
std::stringstream message;
message << "'connections[var_id]' has to be equal or smaller than 'var_to_chk_id[var_id].size()' "
<< "('var_id' = " << var_id << ", 'connections[var_id]' = " << connections[var_id]
<< ", 'var_to_chk_id[var_id].size()' = " << var_to_chk_id[var_id].size() << ").";
throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
}
transpose[k] = branch_id;
k++;
}
}
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const int frame_id)
{
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(Y_N);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
for (auto i = 0; i < this->K; i++)
V_K[i] = (B)this->V_N[this->info_bits_pos[i]];
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::decode, d_decod);
// (*this)[dec::tsk::decode_hiho].update_timer(dec::tm::decode_hiho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const int frame_id)
{
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(Y_N);
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
std::copy(this->V_N.begin(), this->V_N.begin() + this->N, V_N);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_hiho_cw].update_timer(dec::tm::decode_hiho_cw::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_siho(const R *Y_N, B *V_K, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
tools::hard_decide(Y_N, HY_N.data(), this->N);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(HY_N.data());
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
for (auto i = 0; i < this->K; i++)
V_K[i] = (B)this->V_N[this->info_bits_pos[i]];
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::load, d_load);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::decode, d_decod);
// (*this)[dec::tsk::decode_siho].update_timer(dec::tm::decode_siho::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const int frame_id)
{
// auto t_load = std::chrono::steady_clock::now(); // ---------------------------------------------------------- LOAD
tools::hard_decide(Y_N, HY_N.data(), this->N);
// auto d_load = std::chrono::steady_clock::now() - t_load;
// auto t_decod = std::chrono::steady_clock::now(); // -------------------------------------------------------- DECODE
this->_decode(HY_N.data());
// auto d_decod = std::chrono::steady_clock::now() - t_decod;
// auto t_store = std::chrono::steady_clock::now(); // --------------------------------------------------------- STORE
std::copy(this->V_N.begin(), this->V_N.begin() + this->N, V_N);
// auto d_store = std::chrono::steady_clock::now() - t_store;
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::load, d_load);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::decode, d_decod);
// (*this)[dec::tsk::decode_siho_cw].update_timer(dec::tm::decode_siho_cw::store, d_store);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode(const B *Y_N)
{
auto ite = 0;
for (; ite < this->n_ite; ite++)
{
this->_initialize_var_to_chk(Y_N, chk_to_var, var_to_chk, ite == 0);
this->_decode_single_ite(var_to_chk, chk_to_var);
if (this->enable_syndrome && ite != this->n_ite -1)
{
// for the K variable nodes (make a majority vote with the entering messages)
this->_make_majority_vote(Y_N, this->V_N);
if (this->check_syndrome_hard(this->V_N.data()))
break;
}
}
if (ite == this->n_ite)
this->_make_majority_vote(Y_N, this->V_N);
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_initialize_var_to_chk(const B *Y_N, const std::vector<int8_t> &chk_to_var, std::vector<int8_t> &var_to_chk,
const bool first_ite)
{
auto chk_to_var_ptr = chk_to_var.data();
auto var_to_chk_ptr = var_to_chk.data();
// for each variable nodes
const auto n_var_nodes = (int)this->H.get_n_rows();
for (auto v = 0; v < n_var_nodes; v++)
{
const auto var_degree = (int)this->H.get_row_to_cols()[v].size();
const auto cur_state = (int8_t)Y_N[v];
if (first_ite)
{
std::fill(var_to_chk_ptr, var_to_chk_ptr + var_degree, cur_state);
}
else
{
const auto sum = std::accumulate(chk_to_var_ptr, chk_to_var_ptr + var_degree, (int)0);
const auto n_ones = sum + cur_state;
const auto n_zero = var_degree - sum;
const auto n_z_m_o = n_zero - n_ones;
// majority vote on each node
for (auto c = 0; c < var_degree; c++)
{
const auto diff = n_z_m_o + chk_to_var_ptr[c];
var_to_chk_ptr[c] = diff == 0 ? cur_state : (int8_t)std::signbit(diff);
}
}
chk_to_var_ptr += var_degree;
var_to_chk_ptr += var_degree;
}
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_decode_single_ite(const std::vector<int8_t> &var_to_chk, std::vector<int8_t> &chk_to_var)
{
auto transpose_ptr = this->transpose.data();
// for each check nodes
const auto n_chk_nodes = (int)this->H.get_n_cols();
for (auto c = 0; c < n_chk_nodes; c++)
{
const auto chk_degree = (int)this->H.get_col_to_rows()[c].size();
auto acc = 0;
for (auto v = 0; v < chk_degree; v++)
acc ^= var_to_chk[transpose_ptr[v]];
for (auto v = 0; v < chk_degree; v++)
chk_to_var[transpose_ptr[v]] = acc ^ var_to_chk[transpose_ptr[v]];
transpose_ptr += chk_degree;
}
}
template <typename B, typename R>
void Decoder_LDPC_BP_flooding_Gallager_B<B,R>
::_make_majority_vote(const B *Y_N, std::vector<int8_t> &V_N)
{
auto chk_to_var_ptr = this->chk_to_var.data();
// for the K variable nodes (make a majority vote with the entering messages)
const auto n_var_nodes = (int)this->H.get_n_rows();
for (auto v = 0; v < n_var_nodes; v++)
{
const auto var_degree = (int)this->H.get_row_to_cols()[v].size();
const auto cur_state = Y_N[v];
const auto sum = std::accumulate(chk_to_var_ptr, chk_to_var_ptr + var_degree, (int)0);
const auto n_ones = sum + cur_state;
const auto n_zero = var_degree - sum;
const auto n_z_m_o = n_zero - n_ones;
// take the hard decision
V_N[v] = n_z_m_o == 0 ? cur_state : std::signbit(n_z_m_o);
chk_to_var_ptr += var_degree;
}
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef AFF3CT_MULTI_PREC
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_8,Q_8>;
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_16,Q_16>;
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_32,Q_32>;
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_LDPC_BP_flooding_Gallager_B<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|> |
<commit_before>/*
* Copyright © 2012 Felix Höfling, Peter Colberg
*
* This file is part of HALMD.
*
* HALMD 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.
*
* 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/>.
*/
#define BOOST_TEST_MODULE host_vector
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <boost/iterator/counting_iterator.hpp>
#include <vector>
#include <cuda_wrapper/cuda_wrapper.hpp>
struct set_map_host {
set_map_host()
{
CUDA_CALL( cudaSetDeviceFlags(cudaDeviceMapHost) );
}
};
BOOST_GLOBAL_FIXTURE( set_map_host )
/**
* test mapping of page-locked host memory into device memory
*
* use calls to CUDA library without referencing cuda_wrapper
*/
BOOST_AUTO_TEST_CASE( mapped_host_memory_pure )
{
int N = 10000;
size_t size = N * sizeof(int);
int* a_h; cudaHostAlloc((void **)&a_h, size, cudaHostAllocMapped);
int* a_d; cudaHostGetDevicePointer((void **)&a_d, (void *)a_h, 0);
for (int i = 0; i < N; ++i) {
a_h[i] = i;
}
BOOST_TEST_MESSAGE("device → device: copy mapped host memory to device-only memory");
int* b_d; cudaMalloc((void **)&b_d, size);
cudaMemcpy(b_d, a_d, size, cudaMemcpyDeviceToDevice);
BOOST_TEST_MESSAGE("device → host: copy device-only memory to conventional host memory");
int* b_h = (int*)malloc(size);
cudaMemcpy(b_h, b_d, size, cudaMemcpyDeviceToHost);
// check data integrity
BOOST_CHECK_EQUAL_COLLECTIONS( a_h, a_h + N, b_h, b_h + N );
BOOST_TEST_MESSAGE("device → host: copy mapped host memory from device to conventional host memory");
cudaMemcpy(b_h, a_d, size, cudaMemcpyDeviceToHost);
// check data integrity
BOOST_CHECK_EQUAL_COLLECTIONS( a_h, a_h + N, b_h, b_h + N );
// free memory
cudaFree(a_h);
cudaFree(b_d);
free(b_h);
}
/**
* test mapping of page-locked host memory into device memory
*/
BOOST_AUTO_TEST_CASE( mapped_host_memory )
{
BOOST_TEST_MESSAGE("allocate and fill page-locked host memory");
cuda::host::vector<int> h_i(10000);
std::copy(
boost::counting_iterator<int>(0)
, boost::counting_iterator<int>(h_i.size())
, h_i.begin()
);
BOOST_TEST_MESSAGE("device → device: copy mapped host memory to device-only memory");
cuda::vector<int> g_i(h_i.size());
BOOST_CHECK(
g_i.end() == cuda::copy(h_i.gbegin(), h_i.gend(), g_i.begin())
);
BOOST_TEST_MESSAGE("device → host: copy device-only memory to conventional host memory");
std::vector<int> v_j(g_i.size());
BOOST_CHECK(
v_j.end() == cuda::copy(g_i.begin(), g_i.end(), v_j.begin())
);
// check data integrity
BOOST_CHECK_EQUAL_COLLECTIONS(
v_j.begin(), v_j.end()
, boost::counting_iterator<int>(0)
, boost::counting_iterator<int>(v_j.size())
);
BOOST_CHECK_EQUAL_COLLECTIONS(
h_i.begin(), h_i.end(), v_j.begin(), v_j.end()
);
BOOST_TEST_MESSAGE("device → host: copy mapped host memory from device to conventional host memory");
BOOST_CHECK(
v_j.end() == cuda::copy(h_i.gbegin(), h_i.gend(), v_j.begin())
);
// check data integrity
BOOST_CHECK_EQUAL_COLLECTIONS(
v_j.begin(), v_j.end()
, boost::counting_iterator<int>(0)
, boost::counting_iterator<int>(v_j.size())
);
}
<commit_msg>host::vector test: purge mapped_host_memory_pure<commit_after>/*
* Copyright © 2012 Felix Höfling, Peter Colberg
*
* This file is part of HALMD.
*
* HALMD 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.
*
* 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/>.
*/
#define BOOST_TEST_MODULE host_vector
#include <boost/test/unit_test.hpp>
#include <algorithm>
#include <boost/iterator/counting_iterator.hpp>
#include <vector>
#include <cuda_wrapper/cuda_wrapper.hpp>
struct set_map_host {
set_map_host()
{
CUDA_CALL( cudaSetDeviceFlags(cudaDeviceMapHost) );
}
};
BOOST_GLOBAL_FIXTURE( set_map_host )
/**
* test mapping of page-locked host memory into device memory
*/
BOOST_AUTO_TEST_CASE( mapped_host_memory )
{
BOOST_TEST_MESSAGE("allocate and fill page-locked host memory");
cuda::host::vector<int> h_i(10000);
std::copy(
boost::counting_iterator<int>(0)
, boost::counting_iterator<int>(h_i.size())
, h_i.begin()
);
BOOST_TEST_MESSAGE("device → device: copy mapped host memory to device-only memory");
cuda::vector<int> g_i(h_i.size());
BOOST_CHECK(
g_i.end() == cuda::copy(h_i.gbegin(), h_i.gend(), g_i.begin())
);
BOOST_TEST_MESSAGE("device → host: copy device-only memory to conventional host memory");
std::vector<int> v_j(g_i.size());
BOOST_CHECK(
v_j.end() == cuda::copy(g_i.begin(), g_i.end(), v_j.begin())
);
// check data integrity
BOOST_CHECK_EQUAL_COLLECTIONS(
v_j.begin(), v_j.end()
, boost::counting_iterator<int>(0)
, boost::counting_iterator<int>(v_j.size())
);
BOOST_CHECK_EQUAL_COLLECTIONS(
h_i.begin(), h_i.end(), v_j.begin(), v_j.end()
);
BOOST_TEST_MESSAGE("device → host: copy mapped host memory from device to conventional host memory");
BOOST_CHECK(
v_j.end() == cuda::copy(h_i.gbegin(), h_i.gend(), v_j.begin())
);
// check data integrity
BOOST_CHECK_EQUAL_COLLECTIONS(
v_j.begin(), v_j.end()
, boost::counting_iterator<int>(0)
, boost::counting_iterator<int>(v_j.size())
);
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
// work around "uninitialized" warnings and give that option some testing
#define EIGEN_INITIALIZE_MATRICES_BY_ZERO
#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif
// #ifndef EIGEN_DONT_VECTORIZE
// #define EIGEN_DONT_VECTORIZE // SSE intrinsics aren't designed to allow mixing types
// #endif
#include "main.h"
using namespace std;
template<int SizeAtCompileType> void mixingtypes(int size = SizeAtCompileType)
{
typedef std::complex<float> CF;
typedef std::complex<double> CD;
typedef Matrix<float, SizeAtCompileType, SizeAtCompileType> Mat_f;
typedef Matrix<double, SizeAtCompileType, SizeAtCompileType> Mat_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, SizeAtCompileType> Mat_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, SizeAtCompileType> Mat_cd;
typedef Matrix<float, SizeAtCompileType, 1> Vec_f;
typedef Matrix<double, SizeAtCompileType, 1> Vec_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, 1> Vec_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, 1> Vec_cd;
Mat_f mf = Mat_f::Random(size,size);
Mat_d md = mf.template cast<double>();
Mat_cf mcf = Mat_cf::Random(size,size);
Mat_cd mcd = mcf.template cast<complex<double> >();
Vec_f vf = Vec_f::Random(size,1);
Vec_d vd = vf.template cast<double>();
Vec_cf vcf = Vec_cf::Random(size,1);
Vec_cd vcd = vcf.template cast<complex<double> >();
float sf = internal::random<float>();
double sd = internal::random<double>();
complex<float> scf = internal::random<complex<float> >();
complex<double> scd = internal::random<complex<double> >();
mf+mf;
VERIFY_RAISES_ASSERT(mf+md);
VERIFY_RAISES_ASSERT(mf+mcf);
VERIFY_RAISES_ASSERT(vf=vd);
VERIFY_RAISES_ASSERT(vf+=vd);
VERIFY_RAISES_ASSERT(mcd=md);
// check scalar products
VERIFY_IS_APPROX(vcf * sf , vcf * complex<float>(sf));
VERIFY_IS_APPROX(sd * vcd, complex<double>(sd) * vcd);
VERIFY_IS_APPROX(vf * scf , vf.template cast<complex<float> >() * scf);
VERIFY_IS_APPROX(scd * vd, scd * vd.template cast<complex<double> >());
// check dot product
vf.dot(vf);
#if 0 // we get other compilation errors here than just static asserts
VERIFY_RAISES_ASSERT(vd.dot(vf));
#endif
VERIFY_RAISES_ASSERT(vcf.dot(vf)); // yeah eventually we should allow this but i'm too lazy to make that change now in Dot.h
// especially as that might be rewritten as cwise product .sum() which would make that automatic.
// check diagonal product
VERIFY_IS_APPROX(vf.asDiagonal() * mcf, vf.template cast<complex<float> >().asDiagonal() * mcf);
VERIFY_IS_APPROX(vcd.asDiagonal() * md, vcd.asDiagonal() * md.template cast<complex<double> >());
VERIFY_IS_APPROX(mcf * vf.asDiagonal(), mcf * vf.template cast<complex<float> >().asDiagonal());
VERIFY_IS_APPROX(md * vcd.asDiagonal(), md.template cast<complex<double> >() * vcd.asDiagonal());
// vd.asDiagonal() * mf; // does not even compile
// vcd.asDiagonal() * mf; // does not even compile
// check inner product
VERIFY_IS_APPROX((vf.transpose() * vcf).value(), (vf.template cast<complex<float> >().transpose() * vcf).value());
// check outer product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
// coeff wise product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
Mat_cd mcd2 = mcd;
VERIFY_IS_APPROX(mcd.array() *= md.array(), mcd2.array() *= md.array().template cast<std::complex<double> >());
// check matrix-matrix products
VERIFY_IS_APPROX(sd*md*mcd, (sd*md).template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(sd*mcd*md, sd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(scd*md*mcd, scd*md.template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*mcd*md, scd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(sf*mf*mcf, sf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(sf*mcf*mf, sf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(scf*mf*mcf, scf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(scf*mcf*mf, scf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(sf*mf*vcf, (sf*mf).template cast<CF>().eval()*vcf);
VERIFY_IS_APPROX(scf*mf*vcf,(scf*mf.template cast<CF>()).eval()*vcf);
VERIFY_IS_APPROX(sf*mcf*vf, sf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(scf*mcf*vf,scf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(sf*vcf.adjoint()*mf, sf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(scf*vcf.adjoint()*mf, scf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(sf*vf.adjoint()*mcf, sf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(scf*vf.adjoint()*mcf, scf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(sd*md*vcd, (sd*md).template cast<CD>().eval()*vcd);
VERIFY_IS_APPROX(scd*md*vcd,(scd*md.template cast<CD>()).eval()*vcd);
VERIFY_IS_APPROX(sd*mcd*vd, sd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*mcd*vd,scd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vcd.adjoint()*md, sd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*vcd.adjoint()*md, scd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vd.adjoint()*mcd, sd*vd.adjoint().template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*vd.adjoint()*mcd, scd*vd.adjoint().template cast<CD>().eval()*mcd);
}
void test_mixingtypes()
{
CALL_SUBTEST_1(mixingtypes<3>());
CALL_SUBTEST_2(mixingtypes<4>());
CALL_SUBTEST_3(mixingtypes<Dynamic>(internal::random<int>(1,310)));
}
<commit_msg>fix mixingtypes unit test<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
// work around "uninitialized" warnings and give that option some testing
#define EIGEN_INITIALIZE_MATRICES_BY_ZERO
#ifndef EIGEN_NO_STATIC_ASSERT
#define EIGEN_NO_STATIC_ASSERT // turn static asserts into runtime asserts in order to check them
#endif
// #ifndef EIGEN_DONT_VECTORIZE
// #define EIGEN_DONT_VECTORIZE // SSE intrinsics aren't designed to allow mixing types
// #endif
#include "main.h"
using namespace std;
template<int SizeAtCompileType> void mixingtypes(int size = SizeAtCompileType)
{
typedef std::complex<float> CF;
typedef std::complex<double> CD;
typedef Matrix<float, SizeAtCompileType, SizeAtCompileType> Mat_f;
typedef Matrix<double, SizeAtCompileType, SizeAtCompileType> Mat_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, SizeAtCompileType> Mat_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, SizeAtCompileType> Mat_cd;
typedef Matrix<float, SizeAtCompileType, 1> Vec_f;
typedef Matrix<double, SizeAtCompileType, 1> Vec_d;
typedef Matrix<std::complex<float>, SizeAtCompileType, 1> Vec_cf;
typedef Matrix<std::complex<double>, SizeAtCompileType, 1> Vec_cd;
Mat_f mf = Mat_f::Random(size,size);
Mat_d md = mf.template cast<double>();
Mat_cf mcf = Mat_cf::Random(size,size);
Mat_cd mcd = mcf.template cast<complex<double> >();
Vec_f vf = Vec_f::Random(size,1);
Vec_d vd = vf.template cast<double>();
Vec_cf vcf = Vec_cf::Random(size,1);
Vec_cd vcd = vcf.template cast<complex<double> >();
float sf = internal::random<float>();
double sd = internal::random<double>();
complex<float> scf = internal::random<complex<float> >();
complex<double> scd = internal::random<complex<double> >();
mf+mf;
VERIFY_RAISES_ASSERT(mf+md);
VERIFY_RAISES_ASSERT(mf+mcf);
VERIFY_RAISES_ASSERT(vf=vd);
VERIFY_RAISES_ASSERT(vf+=vd);
VERIFY_RAISES_ASSERT(mcd=md);
// check scalar products
VERIFY_IS_APPROX(vcf * sf , vcf * complex<float>(sf));
VERIFY_IS_APPROX(sd * vcd, complex<double>(sd) * vcd);
VERIFY_IS_APPROX(vf * scf , vf.template cast<complex<float> >() * scf);
VERIFY_IS_APPROX(scd * vd, scd * vd.template cast<complex<double> >());
// check dot product
vf.dot(vf);
#if 0 // we get other compilation errors here than just static asserts
VERIFY_RAISES_ASSERT(vd.dot(vf));
#endif
VERIFY_IS_APPROX(vcf.dot(vf), vcf.dot(vf.template cast<complex<float> >()));
// check diagonal product
VERIFY_IS_APPROX(vf.asDiagonal() * mcf, vf.template cast<complex<float> >().asDiagonal() * mcf);
VERIFY_IS_APPROX(vcd.asDiagonal() * md, vcd.asDiagonal() * md.template cast<complex<double> >());
VERIFY_IS_APPROX(mcf * vf.asDiagonal(), mcf * vf.template cast<complex<float> >().asDiagonal());
VERIFY_IS_APPROX(md * vcd.asDiagonal(), md.template cast<complex<double> >() * vcd.asDiagonal());
// vd.asDiagonal() * mf; // does not even compile
// vcd.asDiagonal() * mf; // does not even compile
// check inner product
VERIFY_IS_APPROX((vf.transpose() * vcf).value(), (vf.template cast<complex<float> >().transpose() * vcf).value());
// check outer product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
// coeff wise product
VERIFY_IS_APPROX((vf * vcf.transpose()).eval(), (vf.template cast<complex<float> >() * vcf.transpose()).eval());
Mat_cd mcd2 = mcd;
VERIFY_IS_APPROX(mcd.array() *= md.array(), mcd2.array() *= md.array().template cast<std::complex<double> >());
// check matrix-matrix products
VERIFY_IS_APPROX(sd*md*mcd, (sd*md).template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(sd*mcd*md, sd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(scd*md*mcd, scd*md.template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*mcd*md, scd*mcd*md.template cast<CD>());
VERIFY_IS_APPROX(sf*mf*mcf, sf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(sf*mcf*mf, sf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(scf*mf*mcf, scf*mf.template cast<CF>()*mcf);
VERIFY_IS_APPROX(scf*mcf*mf, scf*mcf*mf.template cast<CF>());
VERIFY_IS_APPROX(sf*mf*vcf, (sf*mf).template cast<CF>().eval()*vcf);
VERIFY_IS_APPROX(scf*mf*vcf,(scf*mf.template cast<CF>()).eval()*vcf);
VERIFY_IS_APPROX(sf*mcf*vf, sf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(scf*mcf*vf,scf*mcf*vf.template cast<CF>());
VERIFY_IS_APPROX(sf*vcf.adjoint()*mf, sf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(scf*vcf.adjoint()*mf, scf*vcf.adjoint()*mf.template cast<CF>().eval());
VERIFY_IS_APPROX(sf*vf.adjoint()*mcf, sf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(scf*vf.adjoint()*mcf, scf*vf.adjoint().template cast<CF>().eval()*mcf);
VERIFY_IS_APPROX(sd*md*vcd, (sd*md).template cast<CD>().eval()*vcd);
VERIFY_IS_APPROX(scd*md*vcd,(scd*md.template cast<CD>()).eval()*vcd);
VERIFY_IS_APPROX(sd*mcd*vd, sd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*mcd*vd,scd*mcd*vd.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vcd.adjoint()*md, sd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(scd*vcd.adjoint()*md, scd*vcd.adjoint()*md.template cast<CD>().eval());
VERIFY_IS_APPROX(sd*vd.adjoint()*mcd, sd*vd.adjoint().template cast<CD>().eval()*mcd);
VERIFY_IS_APPROX(scd*vd.adjoint()*mcd, scd*vd.adjoint().template cast<CD>().eval()*mcd);
}
void test_mixingtypes()
{
CALL_SUBTEST_1(mixingtypes<3>());
CALL_SUBTEST_2(mixingtypes<4>());
CALL_SUBTEST_3(mixingtypes<Dynamic>(internal::random<int>(1,310)));
}
<|endoftext|> |
<commit_before>/** @file */
#include "configparse.h"
/**
* Loads a configuration file and parses it.
*/
void WMConfig::load()
{
// This is meant to help out the unit tests, which would otherwise have
// 'reset()' calls sprinkled about
reset();
std::string config_path = get_config_path();
const char *c_filename = const_cast<const char*>(config_path.c_str());
ini_parse(c_filename, &WMConfig::config_parser, this);
}
/**
* Resets the configuration - this is used mostly for testing purposes.
*/
void WMConfig::reset()
{
shell.assign("/usr/bin/xterm");
num_desktops = 5;
icon_width = 75;
icon_height = 20;
border_width = 4;
show_icons = true;
log_mask = LOG_UPTO(LOG_WARNING);
hotkey = HK_MOUSE;
key_commands.reset();
classactions.clear();
}
/**
* Gets the path to the configuration file. This is a virtual method so that
* unit tests can override this to present a dummy configuration file.
*/
std::string WMConfig::get_config_path() const
{
std::string homedir(std::getenv("HOME"));
homedir += "/.config/smallwm";
return homedir;
}
/**
* A callback for the inih library, which handles a singular key-value pair.
*
* @param user The WMConfig object this parser belongs to (necessary because
* this API has to be called from C).
* @param c_section The section name the option is found under.
* @param c_name The name of the configuration option.
* @param c_value The value of the configuration option.
*/
int WMConfig::config_parser(void *user, const char *c_section,
const char *c_name, const char *c_value)
{
WMConfig *self = static_cast<WMConfig*>(user);
const std::string section(c_section);
const std::string name(c_name);
const std::string value(c_value);
if (section == std::string("smallwm"))
{
if (name == std::string("log-level"))
{
#define SYSLOG_MACRO_CHECK(level) do {\
if (value == std::string(#level)) \
self->log_mask = LOG_UPTO(LOG_##level); \
} while (0);
SYSLOG_MACRO_CHECK(EMERG);
SYSLOG_MACRO_CHECK(ALERT);
SYSLOG_MACRO_CHECK(CRIT);
SYSLOG_MACRO_CHECK(ERR);
SYSLOG_MACRO_CHECK(WARNING);
SYSLOG_MACRO_CHECK(NOTICE);
SYSLOG_MACRO_CHECK(INFO);
SYSLOG_MACRO_CHECK(DEBUG);
#undef SYSLOG_MACRO_CHECK
}
else if (name == std::string("hotkey-mode"))
{
if (value == std::string("focus"))
self->hotkey = HK_FOCUS;
else if (value == std::string("mouse"))
self->hotkey = HK_MOUSE;
else
self->hotkey = HK_MOUSE;
}
else if (name == std::string("shell"))
{
if (value.size() > 0)
self->shell = value;
}
else if (name == std::string("desktops"))
{
unsigned long long old_value = self->num_desktops;
self->num_desktops = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("icon-width"))
{
Dimension old_value = self->icon_width;
self->icon_width = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("icon-height"))
{
Dimension old_value = self->icon_height;
self->icon_height = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("border-width"))
{
Dimension old_value = self->border_width;
self->border_width = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("icon-icons"))
{
bool old_value = self->show_icons;
self->show_icons =
try_parse_ulong(value.c_str(),
static_cast<unsigned long>(old_value)) != 0;
}
}
else if (section == std::string("actions"))
{
ClassActions action;
// Make sure not to butcher the value inside the contained string, to
// make sure that the destructor doesn't do anything weird
char *copied_value = strdup(value.c_str());
// All the configuration options are separated by commas
char *option = strtok(copied_value, ",");
// Catch an empty configuration setting (which returns NULL) before it
// gets into the loop below, which will cause a crash. However, we still
// have to assign the empty ClassAction, so we can't just return here.
if (option == static_cast<char*>(0))
goto set_actions;
// The configuration values are stripped of spaces
char *stripped;
int opt_length;
do
{
opt_length = std::strlen(option);
stripped = new char[opt_length];
strip_string(option, " \n\r\t", stripped);
if (!strcmp(stripped, "stick"))
{
action.actions |= ACT_STICK;
}
else if (!strcmp(stripped, "maximize"))
{
action.actions |= ACT_MAXIMIZE;
}
else if (!strcmp(stripped, "snap:left"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_LEFT;
}
else if (!strcmp(stripped, "snap:right"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_RIGHT;
}
else if (!strcmp(stripped, "snap:top"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_TOP;
}
else if (!strcmp(stripped, "snap:bottom"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_BOTTOM;
}
else if (!strncmp(stripped, "layer:", 6))
{
Layer layer = strtoul(stripped + 6, NULL, 0);
if (layer >= MIN_LAYER && layer <= MAX_LAYER)
{
action.actions |= ACT_SETLAYER;
action.layer = layer;
}
}
else if (!strncmp(stripped, "xpos:", 5))
{
double relative_x = strtod(stripped + 5, NULL) / 100.0;
if (relative_x > 0.0 && relative_x < 1.0)
{
action.actions |= ACT_MOVE_X;
action.relative_x = relative_x;
}
}
else if (!strncmp(stripped, "ypos:", 5))
{
double relative_y = strtod(stripped + 5, NULL) / 100.0;
if (relative_y > 0.0 && relative_y < 1.0)
{
action.actions |= ACT_MOVE_Y;
action.relative_y = relative_y;
}
}
delete[] stripped;
} while((option = strtok(NULL, ",")));
set_actions:
self->classactions[name] = action;
}
// All of the keyboard bindings are handled here - see configparse.h, and
// more specifically KeyboardConfig.
else if (section == std::string("keyboard"))
{
KeyboardConfig &kb_config = self->key_commands;
KeyboardAction action = kb_config.action_names[name];
bool uses_secondary_action = (value[0] == '!');
std::string key_value = value;
if (uses_secondary_action)
key_value.erase(0, 1);
KeySym key = XStringToKeysym(key_value.c_str());
// Fail if the key is not recognized by Xlib
if (key == NoSymbol)
return 0;
KeyBinding binding(key, uses_secondary_action);
// If this new binding is in use by another entry, then fail
if (kb_config.binding_to_action[binding] != INVALID_ACTION)
return 0;
// If an old binding exists for this action, then remove it
KeyBinding old_binding = kb_config.action_to_binding[action];
if (old_binding.first != NoSymbol)
kb_config.binding_to_action.erase(old_binding);
kb_config.action_to_binding[action] = binding;
kb_config.binding_to_action[binding] = action;
}
return 0;
}
<commit_msg>i don't like xterm, gnome-terminal is better.<commit_after>/** @file */
#include "configparse.h"
/**
* Loads a configuration file and parses it.
*/
void WMConfig::load()
{
// This is meant to help out the unit tests, which would otherwise have
// 'reset()' calls sprinkled about
reset();
std::string config_path = get_config_path();
const char *c_filename = const_cast<const char*>(config_path.c_str());
ini_parse(c_filename, &WMConfig::config_parser, this);
}
/**
* Resets the configuration - this is used mostly for testing purposes.
*/
void WMConfig::reset()
{
shell.assign("/usr/bin/gnome-terminal");
num_desktops = 5;
icon_width = 75;
icon_height = 20;
border_width = 4;
show_icons = true;
log_mask = LOG_UPTO(LOG_WARNING);
hotkey = HK_MOUSE;
key_commands.reset();
classactions.clear();
}
/**
* Gets the path to the configuration file. This is a virtual method so that
* unit tests can override this to present a dummy configuration file.
*/
std::string WMConfig::get_config_path() const
{
std::string homedir(std::getenv("HOME"));
homedir += "/.config/smallwm";
return homedir;
}
/**
* A callback for the inih library, which handles a singular key-value pair.
*
* @param user The WMConfig object this parser belongs to (necessary because
* this API has to be called from C).
* @param c_section The section name the option is found under.
* @param c_name The name of the configuration option.
* @param c_value The value of the configuration option.
*/
int WMConfig::config_parser(void *user, const char *c_section,
const char *c_name, const char *c_value)
{
WMConfig *self = static_cast<WMConfig*>(user);
const std::string section(c_section);
const std::string name(c_name);
const std::string value(c_value);
if (section == std::string("smallwm"))
{
if (name == std::string("log-level"))
{
#define SYSLOG_MACRO_CHECK(level) do {\
if (value == std::string(#level)) \
self->log_mask = LOG_UPTO(LOG_##level); \
} while (0);
SYSLOG_MACRO_CHECK(EMERG);
SYSLOG_MACRO_CHECK(ALERT);
SYSLOG_MACRO_CHECK(CRIT);
SYSLOG_MACRO_CHECK(ERR);
SYSLOG_MACRO_CHECK(WARNING);
SYSLOG_MACRO_CHECK(NOTICE);
SYSLOG_MACRO_CHECK(INFO);
SYSLOG_MACRO_CHECK(DEBUG);
#undef SYSLOG_MACRO_CHECK
}
else if (name == std::string("hotkey-mode"))
{
if (value == std::string("focus"))
self->hotkey = HK_FOCUS;
else if (value == std::string("mouse"))
self->hotkey = HK_MOUSE;
else
self->hotkey = HK_MOUSE;
}
else if (name == std::string("shell"))
{
if (value.size() > 0)
self->shell = value;
}
else if (name == std::string("desktops"))
{
unsigned long long old_value = self->num_desktops;
self->num_desktops = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("icon-width"))
{
Dimension old_value = self->icon_width;
self->icon_width = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("icon-height"))
{
Dimension old_value = self->icon_height;
self->icon_height = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("border-width"))
{
Dimension old_value = self->border_width;
self->border_width = try_parse_ulong_nonzero(value.c_str(), old_value);
}
else if (name == std::string("icon-icons"))
{
bool old_value = self->show_icons;
self->show_icons =
try_parse_ulong(value.c_str(),
static_cast<unsigned long>(old_value)) != 0;
}
}
else if (section == std::string("actions"))
{
ClassActions action;
// Make sure not to butcher the value inside the contained string, to
// make sure that the destructor doesn't do anything weird
char *copied_value = strdup(value.c_str());
// All the configuration options are separated by commas
char *option = strtok(copied_value, ",");
// Catch an empty configuration setting (which returns NULL) before it
// gets into the loop below, which will cause a crash. However, we still
// have to assign the empty ClassAction, so we can't just return here.
if (option == static_cast<char*>(0))
goto set_actions;
// The configuration values are stripped of spaces
char *stripped;
int opt_length;
do
{
opt_length = std::strlen(option);
stripped = new char[opt_length];
strip_string(option, " \n\r\t", stripped);
if (!strcmp(stripped, "stick"))
{
action.actions |= ACT_STICK;
}
else if (!strcmp(stripped, "maximize"))
{
action.actions |= ACT_MAXIMIZE;
}
else if (!strcmp(stripped, "snap:left"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_LEFT;
}
else if (!strcmp(stripped, "snap:right"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_RIGHT;
}
else if (!strcmp(stripped, "snap:top"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_TOP;
}
else if (!strcmp(stripped, "snap:bottom"))
{
action.actions |= ACT_SNAP;
action.snap = DIR_BOTTOM;
}
else if (!strncmp(stripped, "layer:", 6))
{
Layer layer = strtoul(stripped + 6, NULL, 0);
if (layer >= MIN_LAYER && layer <= MAX_LAYER)
{
action.actions |= ACT_SETLAYER;
action.layer = layer;
}
}
else if (!strncmp(stripped, "xpos:", 5))
{
double relative_x = strtod(stripped + 5, NULL) / 100.0;
if (relative_x > 0.0 && relative_x < 1.0)
{
action.actions |= ACT_MOVE_X;
action.relative_x = relative_x;
}
}
else if (!strncmp(stripped, "ypos:", 5))
{
double relative_y = strtod(stripped + 5, NULL) / 100.0;
if (relative_y > 0.0 && relative_y < 1.0)
{
action.actions |= ACT_MOVE_Y;
action.relative_y = relative_y;
}
}
delete[] stripped;
} while((option = strtok(NULL, ",")));
set_actions:
self->classactions[name] = action;
}
// All of the keyboard bindings are handled here - see configparse.h, and
// more specifically KeyboardConfig.
else if (section == std::string("keyboard"))
{
KeyboardConfig &kb_config = self->key_commands;
KeyboardAction action = kb_config.action_names[name];
bool uses_secondary_action = (value[0] == '!');
std::string key_value = value;
if (uses_secondary_action)
key_value.erase(0, 1);
KeySym key = XStringToKeysym(key_value.c_str());
// Fail if the key is not recognized by Xlib
if (key == NoSymbol)
return 0;
KeyBinding binding(key, uses_secondary_action);
// If this new binding is in use by another entry, then fail
if (kb_config.binding_to_action[binding] != INVALID_ACTION)
return 0;
// If an old binding exists for this action, then remove it
KeyBinding old_binding = kb_config.action_to_binding[action];
if (old_binding.first != NoSymbol)
kb_config.binding_to_action.erase(old_binding);
kb_config.action_to_binding[action] = binding;
kb_config.binding_to_action[binding] = action;
}
return 0;
}
<|endoftext|> |
<commit_before>c27f0d86-2e4c-11e5-9284-b827eb9e62be<commit_msg>c283fec2-2e4c-11e5-9284-b827eb9e62be<commit_after>c283fec2-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e15f55ca-2e4d-11e5-9284-b827eb9e62be<commit_msg>e1645aa2-2e4d-11e5-9284-b827eb9e62be<commit_after>e1645aa2-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>dc87a678-2e4e-11e5-9284-b827eb9e62be<commit_msg>dc8cc72a-2e4e-11e5-9284-b827eb9e62be<commit_after>dc8cc72a-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>20dfbf24-2e4d-11e5-9284-b827eb9e62be<commit_msg>20e4ad90-2e4d-11e5-9284-b827eb9e62be<commit_after>20e4ad90-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>1e04d436-2e4f-11e5-9284-b827eb9e62be<commit_msg>1e09d9e0-2e4f-11e5-9284-b827eb9e62be<commit_after>1e09d9e0-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e72682f4-2e4c-11e5-9284-b827eb9e62be<commit_msg>e72b752a-2e4c-11e5-9284-b827eb9e62be<commit_after>e72b752a-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>8521d710-2e4d-11e5-9284-b827eb9e62be<commit_msg>8526dd14-2e4d-11e5-9284-b827eb9e62be<commit_after>8526dd14-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fff0199c-2e4e-11e5-9284-b827eb9e62be<commit_msg>fff51352-2e4e-11e5-9284-b827eb9e62be<commit_after>fff51352-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>09789566-2e4f-11e5-9284-b827eb9e62be<commit_msg>097da7ea-2e4f-11e5-9284-b827eb9e62be<commit_after>097da7ea-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>55319f12-2e4e-11e5-9284-b827eb9e62be<commit_msg>5536d536-2e4e-11e5-9284-b827eb9e62be<commit_after>5536d536-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>7117f538-2e4d-11e5-9284-b827eb9e62be<commit_msg>711d4920-2e4d-11e5-9284-b827eb9e62be<commit_after>711d4920-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>fa7c34b6-2e4c-11e5-9284-b827eb9e62be<commit_msg>fa812de0-2e4c-11e5-9284-b827eb9e62be<commit_after>fa812de0-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>37bf320e-2e4f-11e5-9284-b827eb9e62be<commit_msg>37c43574-2e4f-11e5-9284-b827eb9e62be<commit_after>37c43574-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ed76c858-2e4c-11e5-9284-b827eb9e62be<commit_msg>ed7bc27c-2e4c-11e5-9284-b827eb9e62be<commit_after>ed7bc27c-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>ee0a8556-2e4d-11e5-9284-b827eb9e62be<commit_msg>ee0f83b2-2e4d-11e5-9284-b827eb9e62be<commit_after>ee0f83b2-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>a5382a30-2e4e-11e5-9284-b827eb9e62be<commit_msg>a53d44d4-2e4e-11e5-9284-b827eb9e62be<commit_after>a53d44d4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e5097902-2e4e-11e5-9284-b827eb9e62be<commit_msg>e50ea332-2e4e-11e5-9284-b827eb9e62be<commit_after>e50ea332-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>28eddf66-2e4d-11e5-9284-b827eb9e62be<commit_msg>28f2d228-2e4d-11e5-9284-b827eb9e62be<commit_after>28f2d228-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>1cfdadb6-2e4e-11e5-9284-b827eb9e62be<commit_msg>1d02b950-2e4e-11e5-9284-b827eb9e62be<commit_after>1d02b950-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>9b06730a-2e4e-11e5-9284-b827eb9e62be<commit_msg>9b0ba26c-2e4e-11e5-9284-b827eb9e62be<commit_after>9b0ba26c-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>680f988c-2e4e-11e5-9284-b827eb9e62be<commit_msg>681497c4-2e4e-11e5-9284-b827eb9e62be<commit_after>681497c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>d698fe7e-2e4e-11e5-9284-b827eb9e62be<commit_msg>d69e1210-2e4e-11e5-9284-b827eb9e62be<commit_after>d69e1210-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>30dbfa32-2e4d-11e5-9284-b827eb9e62be<commit_msg>30e50910-2e4d-11e5-9284-b827eb9e62be<commit_after>30e50910-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>e6dae446-2e4e-11e5-9284-b827eb9e62be<commit_msg>e6e00f66-2e4e-11e5-9284-b827eb9e62be<commit_after>e6e00f66-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>76f34740-2e4e-11e5-9284-b827eb9e62be<commit_msg>76f850b4-2e4e-11e5-9284-b827eb9e62be<commit_after>76f850b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>94aa7106-2e4d-11e5-9284-b827eb9e62be<commit_msg>94af7a70-2e4d-11e5-9284-b827eb9e62be<commit_after>94af7a70-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>4bf8b188-2e4e-11e5-9284-b827eb9e62be<commit_msg>4bfdc5ec-2e4e-11e5-9284-b827eb9e62be<commit_after>4bfdc5ec-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>7020fbb0-2e4e-11e5-9284-b827eb9e62be<commit_msg>7025f5d4-2e4e-11e5-9284-b827eb9e62be<commit_after>7025f5d4-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>00b80e34-2e4f-11e5-9284-b827eb9e62be<commit_msg>00bd0e8e-2e4f-11e5-9284-b827eb9e62be<commit_after>00bd0e8e-2e4f-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>edf7ece4-2e4c-11e5-9284-b827eb9e62be<commit_msg>edfcd952-2e4c-11e5-9284-b827eb9e62be<commit_after>edfcd952-2e4c-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>0e799756-2e4d-11e5-9284-b827eb9e62be<commit_msg>0e7e9382-2e4d-11e5-9284-b827eb9e62be<commit_after>0e7e9382-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>09fe8da8-2e4d-11e5-9284-b827eb9e62be<commit_msg>0a039726-2e4d-11e5-9284-b827eb9e62be<commit_after>0a039726-2e4d-11e5-9284-b827eb9e62be<|endoftext|> |
<commit_before>da196ee4-2e4e-11e5-9284-b827eb9e62be<commit_msg>da1e6e3a-2e4e-11e5-9284-b827eb9e62be<commit_after>da1e6e3a-2e4e-11e5-9284-b827eb9e62be<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.