text
stringlengths 54
60.6k
|
---|
<commit_before>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2010 FURUHASHI Sadayuki
//
// 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.
//
#ifndef MSGPACK_OBJECT_HPP__
#define MSGPACK_OBJECT_HPP__
#include "object.h"
#include "pack.hpp"
#include "zone.hpp"
#include <string.h>
#include <stdexcept>
#include <typeinfo>
#include <limits>
#include <ostream>
namespace msgpack {
class type_error : public std::bad_cast { };
namespace type {
enum object_type {
NIL = MSGPACK_OBJECT_NIL,
BOOLEAN = MSGPACK_OBJECT_BOOLEAN,
POSITIVE_INTEGER = MSGPACK_OBJECT_POSITIVE_INTEGER,
NEGATIVE_INTEGER = MSGPACK_OBJECT_NEGATIVE_INTEGER,
DOUBLE = MSGPACK_OBJECT_DOUBLE,
RAW = MSGPACK_OBJECT_RAW,
ARRAY = MSGPACK_OBJECT_ARRAY,
MAP = MSGPACK_OBJECT_MAP,
};
}
struct object;
struct object_kv;
struct object_array {
uint32_t size;
object* ptr;
};
struct object_map {
uint32_t size;
object_kv* ptr;
};
struct object_raw {
uint32_t size;
const char* ptr;
};
struct object {
union union_type {
bool boolean;
uint64_t u64;
int64_t i64;
double dec;
object_array array;
object_map map;
object_raw raw;
object_raw ref; // obsolete
};
type::object_type type;
union_type via;
bool is_nil() const { return type == type::NIL; }
template <typename T>
T as() const;
template <typename T>
void convert(T* v) const;
object();
object(msgpack_object o);
template <typename T>
explicit object(const T& v);
template <typename T>
object(const T& v, zone* z);
template <typename T>
object& operator=(const T& v);
operator msgpack_object() const;
struct with_zone;
private:
struct implicit_type;
public:
implicit_type convert() const;
};
struct object_kv {
object key;
object val;
};
struct object::with_zone : object {
with_zone(msgpack::zone* zone) : zone(zone) { }
msgpack::zone* zone;
private:
with_zone();
};
class managed_object : public object, private zone {
public:
managed_object() { }
~managed_object() { }
public:
zone& get_zone() { return *(zone*)this; }
const zone& get_zone() const { return *(const zone*)this; }
private:
managed_object(const managed_object&);
};
bool operator==(const object x, const object y);
bool operator!=(const object x, const object y);
template <typename T>
bool operator==(const object x, const T& y);
template <typename T>
bool operator==(const T& y, const object x);
template <typename T>
bool operator!=(const object x, const T& y);
template <typename T>
bool operator!=(const T& y, const object x);
std::ostream& operator<< (std::ostream& s, const object o);
// serialize operator
template <typename Stream, typename T>
packer<Stream>& operator<< (packer<Stream>& o, const T& v);
// convert operator
template <typename T>
T& operator>> (object o, T& v);
// deconvert operator
template <typename T>
void operator<< (object::with_zone& o, const T& v);
struct object::implicit_type {
implicit_type(object o) : obj(o) { }
~implicit_type() { }
template <typename T>
operator T() { return obj.as<T>(); }
private:
object obj;
};
// obsolete
template <typename Type>
class define : public Type {
public:
typedef Type msgpack_type;
typedef define<Type> define_type;
define() {}
define(const msgpack_type& v) : msgpack_type(v) {}
template <typename Packer>
void msgpack_pack(Packer& o) const
{
o << static_cast<const msgpack_type&>(*this);
}
void msgpack_unpack(object o)
{
o >> static_cast<msgpack_type&>(*this);
}
};
template <typename Stream>
template <typename T>
inline packer<Stream>& packer<Stream>::pack(const T& v)
{
*this << v;
return *this;
}
inline object& operator>> (object o, object& v)
{
v = o;
return v;
}
template <typename T>
inline T& operator>> (object o, T& v)
{
v.msgpack_unpack(o.convert());
return v;
}
template <typename Stream, typename T>
inline packer<Stream>& operator<< (packer<Stream>& o, const T& v)
{
v.msgpack_pack(o);
return o;
}
template <typename T>
void operator<< (object::with_zone& o, const T& v)
{
v.msgpack_object(static_cast<object*>(&o), o.zone);
}
inline bool operator==(const object x, const object y)
{
return msgpack_object_equal(x, y);
}
template <typename T>
inline bool operator==(const object x, const T& y)
try {
return x == object(y);
} catch (msgpack::type_error&) {
return false;
}
inline bool operator!=(const object x, const object y)
{ return !(x == y); }
template <typename T>
inline bool operator==(const T& y, const object x)
{ return x == y; }
template <typename T>
inline bool operator!=(const object x, const T& y)
{ return !(x == y); }
template <typename T>
inline bool operator!=(const T& y, const object x)
{ return x != y; }
inline object::implicit_type object::convert() const
{
return implicit_type(*this);
}
template <typename T>
inline void object::convert(T* v) const
{
*this >> *v;
}
template <typename T>
inline T object::as() const
{
T v;
convert(&v);
return v;
}
inline object::object()
{
type = type::NIL;
}
template <typename T>
inline object::object(const T& v)
{
*this << v;
}
template <typename T>
inline object& object::operator=(const T& v)
{
*this = object(v);
return *this;
}
template <typename T>
object::object(const T& v, zone* z)
{
with_zone oz(z);
oz << v;
type = oz.type;
via = oz.via;
}
inline object::object(msgpack_object o)
{
// FIXME beter way?
::memcpy(this, &o, sizeof(o));
}
inline void operator<< (object& o, msgpack_object v)
{
// FIXME beter way?
::memcpy(&o, &v, sizeof(v));
}
inline object::operator msgpack_object() const
{
// FIXME beter way?
msgpack_object obj;
::memcpy(&obj, this, sizeof(obj));
return obj;
}
// obsolete
template <typename T>
inline void convert(T& v, object o)
{
o.convert(&v);
}
// obsolete
template <typename Stream, typename T>
inline void pack(packer<Stream>& o, const T& v)
{
o.pack(v);
}
// obsolete
template <typename Stream, typename T>
inline void pack_copy(packer<Stream>& o, T v)
{
pack(o, v);
}
template <typename Stream>
packer<Stream>& operator<< (packer<Stream>& o, const object& v)
{
switch(v.type) {
case type::NIL:
o.pack_nil();
return o;
case type::BOOLEAN:
if(v.via.boolean) {
o.pack_true();
} else {
o.pack_false();
}
return o;
case type::POSITIVE_INTEGER:
o.pack_uint64(v.via.u64);
return o;
case type::NEGATIVE_INTEGER:
o.pack_int64(v.via.i64);
return o;
case type::DOUBLE:
o.pack_double(v.via.dec);
return o;
case type::RAW:
o.pack_raw(v.via.raw.size);
o.pack_raw_body(v.via.raw.ptr, v.via.raw.size);
return o;
case type::ARRAY:
o.pack_array(v.via.array.size);
for(object* p(v.via.array.ptr),
* const pend(v.via.array.ptr + v.via.array.size);
p < pend; ++p) {
o << *p;
}
return o;
case type::MAP:
o.pack_map(v.via.map.size);
for(object_kv* p(v.via.map.ptr),
* const pend(v.via.map.ptr + v.via.map.size);
p < pend; ++p) {
o << p->key;
o << p->val;
}
return o;
default:
throw type_error();
}
}
} // namespace msgpack
#include "msgpack/type.hpp"
#endif /* msgpack/object.hpp */
<commit_msg>fixed previous commit<commit_after>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2010 FURUHASHI Sadayuki
//
// 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.
//
#ifndef MSGPACK_OBJECT_HPP__
#define MSGPACK_OBJECT_HPP__
#include "object.h"
#include "pack.hpp"
#include "zone.hpp"
#include <string.h>
#include <stdexcept>
#include <typeinfo>
#include <limits>
#include <ostream>
namespace msgpack {
class type_error : public std::bad_cast { };
namespace type {
enum object_type {
NIL = MSGPACK_OBJECT_NIL,
BOOLEAN = MSGPACK_OBJECT_BOOLEAN,
POSITIVE_INTEGER = MSGPACK_OBJECT_POSITIVE_INTEGER,
NEGATIVE_INTEGER = MSGPACK_OBJECT_NEGATIVE_INTEGER,
DOUBLE = MSGPACK_OBJECT_DOUBLE,
RAW = MSGPACK_OBJECT_RAW,
ARRAY = MSGPACK_OBJECT_ARRAY,
MAP = MSGPACK_OBJECT_MAP,
};
}
struct object;
struct object_kv;
struct object_array {
uint32_t size;
object* ptr;
};
struct object_map {
uint32_t size;
object_kv* ptr;
};
struct object_raw {
uint32_t size;
const char* ptr;
};
struct object {
union union_type {
bool boolean;
uint64_t u64;
int64_t i64;
double dec;
object_array array;
object_map map;
object_raw raw;
object_raw ref; // obsolete
};
type::object_type type;
union_type via;
bool is_nil() const { return type == type::NIL; }
template <typename T>
T as() const;
template <typename T>
void convert(T* v) const;
object();
object(msgpack_object o);
template <typename T>
explicit object(const T& v);
template <typename T>
object(const T& v, zone* z);
template <typename T>
object& operator=(const T& v);
operator msgpack_object() const;
struct with_zone;
private:
struct implicit_type;
public:
implicit_type convert() const;
};
struct object_kv {
object key;
object val;
};
struct object::with_zone : object {
with_zone(msgpack::zone* zone) : zone(zone) { }
msgpack::zone* zone;
private:
with_zone();
};
bool operator==(const object x, const object y);
bool operator!=(const object x, const object y);
template <typename T>
bool operator==(const object x, const T& y);
template <typename T>
bool operator==(const T& y, const object x);
template <typename T>
bool operator!=(const object x, const T& y);
template <typename T>
bool operator!=(const T& y, const object x);
std::ostream& operator<< (std::ostream& s, const object o);
// serialize operator
template <typename Stream, typename T>
packer<Stream>& operator<< (packer<Stream>& o, const T& v);
// convert operator
template <typename T>
T& operator>> (object o, T& v);
// deconvert operator
template <typename T>
void operator<< (object::with_zone& o, const T& v);
struct object::implicit_type {
implicit_type(object o) : obj(o) { }
~implicit_type() { }
template <typename T>
operator T() { return obj.as<T>(); }
private:
object obj;
};
// obsolete
template <typename Type>
class define : public Type {
public:
typedef Type msgpack_type;
typedef define<Type> define_type;
define() {}
define(const msgpack_type& v) : msgpack_type(v) {}
template <typename Packer>
void msgpack_pack(Packer& o) const
{
o << static_cast<const msgpack_type&>(*this);
}
void msgpack_unpack(object o)
{
o >> static_cast<msgpack_type&>(*this);
}
};
template <typename Stream>
template <typename T>
inline packer<Stream>& packer<Stream>::pack(const T& v)
{
*this << v;
return *this;
}
inline object& operator>> (object o, object& v)
{
v = o;
return v;
}
template <typename T>
inline T& operator>> (object o, T& v)
{
v.msgpack_unpack(o.convert());
return v;
}
template <typename Stream, typename T>
inline packer<Stream>& operator<< (packer<Stream>& o, const T& v)
{
v.msgpack_pack(o);
return o;
}
template <typename T>
void operator<< (object::with_zone& o, const T& v)
{
v.msgpack_object(static_cast<object*>(&o), o.zone);
}
inline bool operator==(const object x, const object y)
{
return msgpack_object_equal(x, y);
}
template <typename T>
inline bool operator==(const object x, const T& y)
try {
return x == object(y);
} catch (msgpack::type_error&) {
return false;
}
inline bool operator!=(const object x, const object y)
{ return !(x == y); }
template <typename T>
inline bool operator==(const T& y, const object x)
{ return x == y; }
template <typename T>
inline bool operator!=(const object x, const T& y)
{ return !(x == y); }
template <typename T>
inline bool operator!=(const T& y, const object x)
{ return x != y; }
inline object::implicit_type object::convert() const
{
return implicit_type(*this);
}
template <typename T>
inline void object::convert(T* v) const
{
*this >> *v;
}
template <typename T>
inline T object::as() const
{
T v;
convert(&v);
return v;
}
inline object::object()
{
type = type::NIL;
}
template <typename T>
inline object::object(const T& v)
{
*this << v;
}
template <typename T>
inline object& object::operator=(const T& v)
{
*this = object(v);
return *this;
}
template <typename T>
object::object(const T& v, zone* z)
{
with_zone oz(z);
oz << v;
type = oz.type;
via = oz.via;
}
inline object::object(msgpack_object o)
{
// FIXME beter way?
::memcpy(this, &o, sizeof(o));
}
inline void operator<< (object& o, msgpack_object v)
{
// FIXME beter way?
::memcpy(&o, &v, sizeof(v));
}
inline object::operator msgpack_object() const
{
// FIXME beter way?
msgpack_object obj;
::memcpy(&obj, this, sizeof(obj));
return obj;
}
// obsolete
template <typename T>
inline void convert(T& v, object o)
{
o.convert(&v);
}
// obsolete
template <typename Stream, typename T>
inline void pack(packer<Stream>& o, const T& v)
{
o.pack(v);
}
// obsolete
template <typename Stream, typename T>
inline void pack_copy(packer<Stream>& o, T v)
{
pack(o, v);
}
template <typename Stream>
packer<Stream>& operator<< (packer<Stream>& o, const object& v)
{
switch(v.type) {
case type::NIL:
o.pack_nil();
return o;
case type::BOOLEAN:
if(v.via.boolean) {
o.pack_true();
} else {
o.pack_false();
}
return o;
case type::POSITIVE_INTEGER:
o.pack_uint64(v.via.u64);
return o;
case type::NEGATIVE_INTEGER:
o.pack_int64(v.via.i64);
return o;
case type::DOUBLE:
o.pack_double(v.via.dec);
return o;
case type::RAW:
o.pack_raw(v.via.raw.size);
o.pack_raw_body(v.via.raw.ptr, v.via.raw.size);
return o;
case type::ARRAY:
o.pack_array(v.via.array.size);
for(object* p(v.via.array.ptr),
* const pend(v.via.array.ptr + v.via.array.size);
p < pend; ++p) {
o << *p;
}
return o;
case type::MAP:
o.pack_map(v.via.map.size);
for(object_kv* p(v.via.map.ptr),
* const pend(v.via.map.ptr + v.via.map.size);
p < pend; ++p) {
o << p->key;
o << p->val;
}
return o;
default:
throw type_error();
}
}
} // namespace msgpack
#include "msgpack/type.hpp"
#endif /* msgpack/object.hpp */
<|endoftext|> |
<commit_before>// This software is part of OpenMono, see http://developer.openmono.com
// and is available under the MIT license, see LICENSE.txt
#include "mono_power_management.h"
#include "application_context_interface.h"
//#include "consoles.h"
#include <project.h>
#ifdef DEVICE_SERIAL
#include <serial_usb_api.h>
extern char serial_usbuart_is_powered;
#endif
using namespace mono::power;
bool MonoPowerManagement::__RTCFired = false;
MonoPowerManagement::MonoPowerManagement()
{
//Confgure the VAUX power to be 3V3 and ENABLED
mbed::DigitalOut vauxSel(VAUX_SEL, 1); // Select 3V3 for Vaux
mbed::DigitalOut vauxEn(VAUX_EN, 1); // Enable Vaux
batteryLowFlag = batteryEmptyFlag = false;
powerAwarenessQueue = NULL;
PowerSystem = &powerSubsystem;
PowerSystem->BatteryLowHandler.attach<MonoPowerManagement>(this, &MonoPowerManagement::systemLowBattery);
PowerSystem->BatteryEmptyHandler.attach<MonoPowerManagement>(this, &MonoPowerManagement::systemEmptyBattery);
singleShot = false;
IApplicationContext::Instance->RunLoop->addDynamicTask(this);
#ifdef DEVICE_SERIAL
// if mbed device serial exists, enable if usb powered
serial_usbuart_is_powered = PowerSystem->IsUSBCharging();
#endif
//turn on peripherals
PowerSystem->setPowerFence(false);
}
void MonoPowerManagement::EnterSleep(bool skipAwarenessQueues)
{
if (!skipAwarenessQueues)
processSleepAwarenessQueue();
PowerSystem->onSystemEnterSleep();
powerSubsystem.setPowerFence(true);
powerSubsystem.powerOffUnused();
powerDownMCUPeripherals();
//CyILO_Start1K(); // make sure the 1K ILO Osc is running
//CyMasterClk_SetSource(CY_MASTER_SOURCE_IMO);
bool wakeup = false;
while(wakeup == false)
{
wakeup = true; //wake up by defualt
CyPmSaveClocks();
__RTCFired = false;
CyPmSleep(PM_SLEEP_TIME_NONE, PM_SLEEP_SRC_PICU | PM_SLEEP_SRC_CTW);
//CyPmHibernate();
CyPmRestoreClocks();
//int status = CyPmReadStatus(CY_PM_CTW_INT);
if (__RTCFired)
{
wakeup = false;
__RTCFired = false;
}
}
//CyMasterClk_SetSource(CY_MASTER_SOURCE_PLL);
//CyGlobalIntEnable;
powerUpMCUPeripherals();
PowerSystem->onSystemWakeFromSleep();
powerSubsystem.setPowerFence(false);
//mono::defaultSerial.printf("Wake up! Restore clocks and read status regs: 0x%x\r\n", status);
if (!skipAwarenessQueues)
processWakeAwarenessQueue();
}
void MonoPowerManagement::taskHandler()
{
if (batteryLowFlag)
{
batteryLowFlag = false;
IPowerManagement::processBatteryLowAwarenessQueue();
}
}
void MonoPowerManagement::processResetAwarenessQueue()
{
IPowerManagement::processResetAwarenessQueue();
}
void MonoPowerManagement::setupMCUPeripherals()
{
// set all PORT 0 (Exp. conn. to res pull down)
CY_SET_REG8(CYREG_PRT0_DM0, 0x00);
CY_SET_REG8(CYREG_PRT0_DM1, 0x00);
CY_SET_REG8(CYREG_PRT0_DM2, 0x00);
// set all PORT 1 (Exp. conn. to res pull down)
CY_SET_REG8(CYREG_PRT1_DM0, 0x00);
CY_SET_REG8(CYREG_PRT1_DM1, 0x00);
CY_SET_REG8(CYREG_PRT1_DM2, 0x00);
// set all PORT 2 (RP spi to res pull down)
// set PRT2_2 as OD, drives low
CY_SET_REG8(CYREG_PRT2_DM0, 0x00);
CY_SET_REG8(CYREG_PRT2_DM1, 0x00);
CY_SET_REG8(CYREG_PRT2_DM2, 0x00);
// set all PORT 3 (TFT to res pull down)
CY_SET_REG8(CYREG_PRT3_DM0, 0x00);
CY_SET_REG8(CYREG_PRT3_DM1, 0x00);
CY_SET_REG8(CYREG_PRT3_DM2, 0x00);
// set all PORT 4 (exp. conn to res pull down)
CY_SET_REG8(CYREG_PRT4_DM0, 0x00);
CY_SET_REG8(CYREG_PRT4_DM1, 0x00);
CY_SET_REG8(CYREG_PRT4_DM2, 0x00);
// set all PORT 5 (switches and inputs, to res pull down)
// set PRT5_0 as OD drives low
CY_SET_REG8(CYREG_PRT5_DM0, 0x00);
CY_SET_REG8(CYREG_PRT5_DM1, 0x00);
CY_SET_REG8(CYREG_PRT5_DM2, 0x00);
// set all PORT 6 (TFT conn. to res pull down)
CY_SET_REG8(CYREG_PRT6_DM0, 0x00);
CY_SET_REG8(CYREG_PRT6_DM1, 0x00);
CY_SET_REG8(CYREG_PRT6_DM2, 0x00);
// set all PORT 12 (misc. to res pull down)
//set PRT12_5 as OD, drives low
CY_SET_REG8(CYREG_PRT12_DM0, 0x00);
CY_SET_REG8(CYREG_PRT12_DM1, 0x00);
CY_SET_REG8(CYREG_PRT12_DM2, 0x00);
//CY_SET_REG8(CYREG_PRT12_SIO_CFG, 0x00); // SIO non-reg output
CY_SET_REG8(CYREG_PRT15_DM0, 0x00);
CY_SET_REG8(CYREG_PRT15_DM1, 0x00);
CY_SET_REG8(CYREG_PRT15_DM2, 0x00);
// SW USER must be weak pull up in sleep!
CyPins_SetPinDriveMode(USER_SW, CY_PINS_DM_RES_UP);
// Vaux must be strong low in sleep! (Turns off Vaux power)
mbed::DigitalOut vauxEn(VAUX_EN, 0);
// VauxSel must set to 3V3 in sleep mode
mbed::DigitalOut vauxSel(VAUX_SEL, 1);
//Power INT res pull up in sleep
CyPins_SetPinDriveMode(nIRQ, CY_PINS_DM_RES_UP);
}
void MonoPowerManagement::powerDownMCUPeripherals()
{
PWM_Sleep();
// SPI_SD_Sleep();
SPI1_Sleep();
// SPI_RP_Sleep();
ADC_SAR_1_Sleep();
// I2C_Sleep();
I2C_Sleep();
#ifdef DEVICE_SERIAL
if (serial_usbuart_is_started())
{
// USBUART_SaveConfig();
// USBUART_Suspend();
USBUART_Stop();
serial_usbuart_stopped();
}
#endif
saveDMRegisters();
setupMCUPeripherals();
}
void MonoPowerManagement::powerUpMCUPeripherals()
{
restoreDMRegisters();
// Restore 3V3 on Vaux
mbed::DigitalOut vauxSel(VAUX_SEL, 1);
mbed::DigitalOut vauxEn(VAUX_EN, 1);
#ifdef DEVICE_SERIAL
serial_usbuart_stopped();
#endif
PWM_Wakeup();
I2C_Wakeup();
SPI1_Wakeup();
ADC_SAR_1_Wakeup();
}
void MonoPowerManagement::saveDMRegisters()
{
uint8_t cnt = 0;
saveDMPort(CYREG_PRT0_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT1_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT2_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT3_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT4_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT5_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT6_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT12_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT15_DM0, DriveModeRegisters+(cnt++)*3);
}
void MonoPowerManagement::restoreDMRegisters()
{
uint8_t cnt = 0;
restoreDMPort(CYREG_PRT0_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT1_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT2_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT3_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT4_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT5_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT6_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT12_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT15_DM0, DriveModeRegisters+(cnt++)*3);
}
void MonoPowerManagement::saveDMPort(uint32_t regAddrOffset, uint8_t destOffset[])
{
destOffset[0] = CY_GET_REG8(regAddrOffset);
destOffset[1] = CY_GET_REG8(regAddrOffset+1);
destOffset[2] = CY_GET_REG8(regAddrOffset+2);
}
void MonoPowerManagement::restoreDMPort(uint32_t regAddrOffset, uint8_t srcOffset[])
{
CY_SET_REG8(regAddrOffset, srcOffset[0]);
CY_SET_REG8(regAddrOffset+1, srcOffset[1]);
CY_SET_REG8(regAddrOffset+2, srcOffset[2]);
}
/// MARK: Power Sub-System Battery callbacks
void MonoPowerManagement::systemLowBattery()
{
batteryLowFlag = true;
}
void MonoPowerManagement::systemEmptyBattery()
{
//batteryEmptyFlag = true;
while (!PowerSystem->IsPowerOk())
{
debug("Sleep until power is OK!\t\n");
EnterSleep();
}
IApplicationContext::SoftwareResetToApplication();
}
<commit_msg>Set J_TIP to defaults to res. pull down<commit_after>// This software is part of OpenMono, see http://developer.openmono.com
// and is available under the MIT license, see LICENSE.txt
#include "mono_power_management.h"
#include "application_context_interface.h"
//#include "consoles.h"
#include <project.h>
#ifdef DEVICE_SERIAL
#include <serial_usb_api.h>
extern char serial_usbuart_is_powered;
#endif
using namespace mono::power;
bool MonoPowerManagement::__RTCFired = false;
MonoPowerManagement::MonoPowerManagement()
{
//Confgure the VAUX power to be 3V3 and ENABLED
mbed::DigitalOut vauxSel(VAUX_SEL, 1); // Select 3V3 for Vaux
mbed::DigitalOut vauxEn(VAUX_EN, 1); // Enable Vaux
// The J_TIP to PullDown and low
CyPins_SetPinDriveMode(J_TIP, CY_PINS_DM_RES_UP);
CyPins_ClearPin(J_TIP);
batteryLowFlag = batteryEmptyFlag = false;
powerAwarenessQueue = NULL;
PowerSystem = &powerSubsystem;
PowerSystem->BatteryLowHandler.attach<MonoPowerManagement>(this, &MonoPowerManagement::systemLowBattery);
PowerSystem->BatteryEmptyHandler.attach<MonoPowerManagement>(this, &MonoPowerManagement::systemEmptyBattery);
singleShot = false;
IApplicationContext::Instance->RunLoop->addDynamicTask(this);
#ifdef DEVICE_SERIAL
// if mbed device serial exists, enable if usb powered
serial_usbuart_is_powered = PowerSystem->IsUSBCharging();
#endif
//turn on peripherals
PowerSystem->setPowerFence(false);
}
void MonoPowerManagement::EnterSleep(bool skipAwarenessQueues)
{
if (!skipAwarenessQueues)
processSleepAwarenessQueue();
PowerSystem->onSystemEnterSleep();
powerSubsystem.setPowerFence(true);
powerSubsystem.powerOffUnused();
powerDownMCUPeripherals();
bool wakeup = false;
while(wakeup == false)
{
wakeup = true; //wake up by defualt
CyPmSaveClocks();
__RTCFired = false;
CyPmSleep(PM_SLEEP_TIME_NONE, PM_SLEEP_SRC_PICU | PM_SLEEP_SRC_CTW);
CyPmRestoreClocks();
if (__RTCFired)
{
wakeup = false;
__RTCFired = false;
}
}
powerUpMCUPeripherals();
PowerSystem->onSystemWakeFromSleep();
powerSubsystem.setPowerFence(false);
if (!skipAwarenessQueues)
processWakeAwarenessQueue();
}
void MonoPowerManagement::taskHandler()
{
if (batteryLowFlag)
{
batteryLowFlag = false;
IPowerManagement::processBatteryLowAwarenessQueue();
}
}
void MonoPowerManagement::processResetAwarenessQueue()
{
IPowerManagement::processResetAwarenessQueue();
}
void MonoPowerManagement::setupMCUPeripherals()
{
// set all PORT 0 (Exp. conn. to res high impedance)
CY_SET_REG8(CYREG_PRT0_DM0, 0x00);
CY_SET_REG8(CYREG_PRT0_DM1, 0x00);
CY_SET_REG8(CYREG_PRT0_DM2, 0x00);
// set all PORT 1 (Exp. conn. to res high impedance)
CY_SET_REG8(CYREG_PRT1_DM0, 0x00);
CY_SET_REG8(CYREG_PRT1_DM1, 0x00);
CY_SET_REG8(CYREG_PRT1_DM2, 0x00);
// set all PORT 2 (RP spi to res high impedance)
// set PRT2_2 as OD, drives low
CY_SET_REG8(CYREG_PRT2_DM0, 0x00);
CY_SET_REG8(CYREG_PRT2_DM1, 0x00);
CY_SET_REG8(CYREG_PRT2_DM2, 0x00);
// set all PORT 3 (TFT to res high impedance)
CY_SET_REG8(CYREG_PRT3_DM0, 0x00);
CY_SET_REG8(CYREG_PRT3_DM1, 0x00);
CY_SET_REG8(CYREG_PRT3_DM2, 0x00);
// set all PORT 4 (exp. conn to res high impedance)
CY_SET_REG8(CYREG_PRT4_DM0, 0x00);
CY_SET_REG8(CYREG_PRT4_DM1, 0x00);
CY_SET_REG8(CYREG_PRT4_DM2, 0x00);
// set all PORT 5 (switches and inputs, to res high impedance)
// set PRT5_0 as OD drives low
CY_SET_REG8(CYREG_PRT5_DM0, 0x00);
CY_SET_REG8(CYREG_PRT5_DM1, 0x00);
CY_SET_REG8(CYREG_PRT5_DM2, 0x00);
// set all PORT 6 (TFT conn. to res high impedance)
CY_SET_REG8(CYREG_PRT6_DM0, 0x00);
CY_SET_REG8(CYREG_PRT6_DM1, 0x00);
CY_SET_REG8(CYREG_PRT6_DM2, 0x00);
// set all PORT 12 (misc. to res high impedance)
// set J_TIP to Res. PullDown
CY_SET_REG8(CYREG_PRT12_DM0, 0x08);
CY_SET_REG8(CYREG_PRT12_DM1, 0x08);
CY_SET_REG8(CYREG_PRT12_DM2, 0x00);
CY_SET_REG8(CYREG_PRT15_DM0, 0x00);
CY_SET_REG8(CYREG_PRT15_DM1, 0x00);
CY_SET_REG8(CYREG_PRT15_DM2, 0x00);
// SW USER must be weak pull up in sleep!
CyPins_SetPinDriveMode(USER_SW, CY_PINS_DM_RES_UP);
// Vaux must be strong low in sleep! (Turns off Vaux power)
mbed::DigitalOut vauxEn(VAUX_EN, 0);
// VauxSel must set to 3V3 in sleep mode
mbed::DigitalOut vauxSel(VAUX_SEL, 1);
//Power INT res pull up in sleep - so the power interrupt still works
CyPins_SetPinDriveMode(nIRQ, CY_PINS_DM_RES_UP);
}
void MonoPowerManagement::powerDownMCUPeripherals()
{
PWM_Sleep();
SPI1_Sleep();
ADC_SAR_1_Sleep();
I2C_Sleep();
#ifdef DEVICE_SERIAL
if (serial_usbuart_is_started())
{
// USBUART_SaveConfig();
// USBUART_Suspend();
USBUART_Stop();
serial_usbuart_stopped();
}
#endif
saveDMRegisters();
setupMCUPeripherals();
}
void MonoPowerManagement::powerUpMCUPeripherals()
{
restoreDMRegisters();
// Restore 3V3 on Vaux
mbed::DigitalOut vauxSel(VAUX_SEL, 1);
mbed::DigitalOut vauxEn(VAUX_EN, 1);
#ifdef DEVICE_SERIAL
serial_usbuart_stopped();
#endif
PWM_Wakeup();
I2C_Wakeup();
SPI1_Wakeup();
ADC_SAR_1_Wakeup();
}
void MonoPowerManagement::saveDMRegisters()
{
uint8_t cnt = 0;
saveDMPort(CYREG_PRT0_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT1_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT2_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT3_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT4_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT5_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT6_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT12_DM0, DriveModeRegisters+(cnt++)*3);
saveDMPort(CYREG_PRT15_DM0, DriveModeRegisters+(cnt++)*3);
}
void MonoPowerManagement::restoreDMRegisters()
{
uint8_t cnt = 0;
restoreDMPort(CYREG_PRT0_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT1_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT2_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT3_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT4_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT5_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT6_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT12_DM0, DriveModeRegisters+(cnt++)*3);
restoreDMPort(CYREG_PRT15_DM0, DriveModeRegisters+(cnt++)*3);
}
void MonoPowerManagement::saveDMPort(uint32_t regAddrOffset, uint8_t destOffset[])
{
destOffset[0] = CY_GET_REG8(regAddrOffset);
destOffset[1] = CY_GET_REG8(regAddrOffset+1);
destOffset[2] = CY_GET_REG8(regAddrOffset+2);
}
void MonoPowerManagement::restoreDMPort(uint32_t regAddrOffset, uint8_t srcOffset[])
{
CY_SET_REG8(regAddrOffset, srcOffset[0]);
CY_SET_REG8(regAddrOffset+1, srcOffset[1]);
CY_SET_REG8(regAddrOffset+2, srcOffset[2]);
}
/// MARK: Power Sub-System Battery callbacks
void MonoPowerManagement::systemLowBattery()
{
batteryLowFlag = true;
}
void MonoPowerManagement::systemEmptyBattery()
{
//batteryEmptyFlag = true;
while (!PowerSystem->IsPowerOk())
{
debug("Sleep until power is OK!\t\n");
EnterSleep();
}
IApplicationContext::SoftwareResetToApplication();
}
<|endoftext|> |
<commit_before>#pragma once
#include "eval.hh"
#define LocalNoInline(f) static f __attribute__((noinline)); f
#define LocalNoInlineNoReturn(f) static f __attribute__((noinline, noreturn)); f
namespace nix {
LocalNoInlineNoReturn(void throwEvalError(const char * s))
{
throw EvalError(s);
}
LocalNoInlineNoReturn(void throwTypeError(const char * s, const string & s2))
{
throw TypeError(format(s) % s2);
}
void EvalState::forceValue(Value & v)
{
if (v.type == tThunk) {
ValueType saved = v.type;
try {
v.type = tBlackhole;
//checkInterrupt();
v.thunk.expr->eval(*this, *v.thunk.env, v);
} catch (Error & e) {
v.type = saved;
throw;
}
}
else if (v.type == tApp)
callFunction(*v.app.left, *v.app.right, v);
else if (v.type == tBlackhole)
throwEvalError("infinite recursion encountered");
}
inline void EvalState::forceAttrs(Value & v)
{
forceValue(v);
if (v.type != tAttrs)
throwTypeError("value is %1% while an attribute set was expected", showType(v));
}
inline void EvalState::forceList(Value & v)
{
forceValue(v);
if (v.type != tList)
throwTypeError("value is %1% while a list was expected", showType(v));
}
}
<commit_msg>Make sure that thunks are restored properly if an exception occurs<commit_after>#pragma once
#include "eval.hh"
#define LocalNoInline(f) static f __attribute__((noinline)); f
#define LocalNoInlineNoReturn(f) static f __attribute__((noinline, noreturn)); f
namespace nix {
LocalNoInlineNoReturn(void throwEvalError(const char * s))
{
throw EvalError(s);
}
LocalNoInlineNoReturn(void throwTypeError(const char * s, const string & s2))
{
throw TypeError(format(s) % s2);
}
void EvalState::forceValue(Value & v)
{
if (v.type == tThunk) {
Env * env = v.thunk.env;
Expr * expr = v.thunk.expr;
try {
v.type = tBlackhole;
//checkInterrupt();
expr->eval(*this, *env, v);
} catch (Error & e) {
v.type = tThunk;
v.thunk.env = env;
v.thunk.expr = expr;
throw;
}
}
else if (v.type == tApp)
callFunction(*v.app.left, *v.app.right, v);
else if (v.type == tBlackhole)
throwEvalError("infinite recursion encountered");
}
inline void EvalState::forceAttrs(Value & v)
{
forceValue(v);
if (v.type != tAttrs)
throwTypeError("value is %1% while an attribute set was expected", showType(v));
}
inline void EvalState::forceList(Value & v)
{
forceValue(v);
if (v.type != tList)
throwTypeError("value is %1% while a list was expected", showType(v));
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Buck Baskin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <quirkd/libsemi_static_map.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
#include <nav_msgs/GetMap.h>
#include <sensor_msgs/image_encodings.h>
namespace quirkd
{
SemiStaticMap::SemiStaticMap(ros::NodeHandle nh) : n_(nh), it_(n_)
{
alert_pub_ = n_.advertise<quirkd::AlertArray>("/quirkd/alert_array/notification", 1);
laser_sub_ = n_.subscribe("/base_scan", 1, &SemiStaticMap::laserScanCB, this);
ROS_INFO("WaitForService(\"static_map\");");
ros::service::waitForService("static_map");
static_map_client_ = n_.serviceClient<nav_msgs::GetMap>("static_map");
ROS_INFO("WaitForService(\"dynamic_map\");");
ros::service::waitForService("dynamic_map");
dynamic_map_client_ = n_.serviceClient<nav_msgs::GetMap>("dynamic_map");
static_image_pub_ = it_.advertise("/quirkd/test/static_image", 1);
dynamic_image_pub_ = it_.advertise("/quirkd/test/dynamic_image", 1);
visualization_pub_ = it_.advertise("/quirkd/test/visualization", 1);
}
SemiStaticMap::~SemiStaticMap()
{
ROS_INFO("Destroying SemiStaticMap");
}
void SemiStaticMap::laserScanCB(const sensor_msgs::LaserScan msg)
{
ROS_INFO("Laser Scan Callback");
last_data = msg;
try
{
ROS_INFO("Waiting for transform");
tf_.waitForTransform("/map", "/base_laser_link", ros::Time::now(), ros::Duration(3.0));
tf_.lookupTransform("/map", "/base_laser_link", ros::Time::now(), last_tf);
ROS_INFO("tf success for /map to /base_laser_link");
}
catch (tf::TransformException& ex)
{
ROS_WARN("tf fetch failed. %s", ex.what());
}
}
void SemiStaticMap::update()
{
quirkd::Alert alert;
alert.level = 0;
alert.min_x = 0;
alert.max_x = 1;
alert.min_y = 0;
alert.max_y = 1;
updateAlertPerimeter(&alert, last_data, last_tf);
ROS_INFO("Update Data Processor");
nav_msgs::GetMap srv;
cv_bridge::CvImagePtr static_image;
cv_bridge::CvImagePtr dynamic_image;
if (static_map_client_.call(srv))
{
ROS_DEBUG("Successfull call static map");
nav_msgs::OccupancyGrid og = srv.response.map;
static_image = quirkd::imagep::gridToCroppedCvImage(&og, &alert);
static_image_pub_.publish(static_image->toImageMsg());
}
else
{
ROS_WARN("Failed to get static map");
}
if (dynamic_map_client_.call(srv))
{
ROS_DEBUG("Successfull call dynamic map");
nav_msgs::OccupancyGrid og = srv.response.map;
dynamic_image = quirkd::imagep::gridToCroppedCvImage(&og, &alert);
dynamic_image_pub_.publish(dynamic_image->toImageMsg());
}
else
{
ROS_WARN("Failed to get dynamic map");
dynamic_image = static_image;
}
// two images (static (base) image and dynamic image)
// perimeter encoded as part of the alert and images aligned to alert perimeter
// use a single method that captures preprocessing and quantification
quirkd::AlertArray aa;
aa.alerts = quirkd::imagep::measureDifference(*static_image, *dynamic_image, &alert, &visualization_pub_);
ROS_INFO("PUBLISHING %d alerts", (int)(aa.alerts.size()));
alert_pub_.publish(aa);
}
void SemiStaticMap::updateAlertPerimeter(quirkd::Alert* alert, const sensor_msgs::LaserScan scan,
const tf::StampedTransform tf)
{
double base_x = tf.getOrigin().x();
double base_y = tf.getOrigin().y();
double r, p, base_heading;
tf::Matrix3x3 m(tf.getRotation());
m.getRPY(r, p, base_heading);
double scan_min = base_heading + scan.angle_min;
double scan_inc = scan.angle_increment;
double heading = scan_min;
alert->min_x = base_x;
alert->max_x = base_x;
alert->min_y = base_y;
alert->max_y = base_y;
double live_x, live_y;
for (int i = 0; i < scan.ranges.size(); i++)
{
double dist = scan.ranges[i];
live_x = base_x + dist * cos(heading);
live_y = base_y + dist * sin(heading);
alert->min_x = std::min(live_x, double(alert->min_x));
alert->max_x = std::max(live_x, double(alert->max_x));
alert->min_y = std::min(live_y, double(alert->min_y));
alert->max_y = std::max(live_y, double(alert->max_y));
heading += scan_inc;
}
double padding = 0.5;
alert->min_x += -padding;
alert->min_y += -padding;
alert->max_x += padding;
alert->max_y += padding;
}
} // namespace quirkd
<commit_msg>Fix compile error in libsemi_static_map<commit_after>/*
* Copyright 2017 Buck Baskin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <quirkd/libsemi_static_map.h>
#include <math.h>
#include <stdint.h>
#include <stdbool.h>
#include <nav_msgs/GetMap.h>
#include <sensor_msgs/image_encodings.h>
namespace quirkd
{
SemiStaticMap::SemiStaticMap(ros::NodeHandle nh) : n_(nh), it_(n_)
{
alert_pub_ = n_.advertise<quirkd::AlertArray>("/quirkd/alert_array/notification", 1);
laser_sub_ = n_.subscribe("/base_scan", 1, &SemiStaticMap::laserScanCB, this);
ROS_INFO("WaitForService(\"static_map\");");
ros::service::waitForService("static_map");
static_map_client_ = n_.serviceClient<nav_msgs::GetMap>("static_map");
ROS_INFO("WaitForService(\"dynamic_map\");");
ros::service::waitForService("dynamic_map");
dynamic_map_client_ = n_.serviceClient<nav_msgs::GetMap>("dynamic_map");
static_image_pub_ = it_.advertise("/quirkd/test/static_image", 1);
dynamic_image_pub_ = it_.advertise("/quirkd/test/dynamic_image", 1);
visualization_pub_ = it_.advertise("/quirkd/test/visualization", 1);
}
SemiStaticMap::~SemiStaticMap()
{
ROS_INFO("Destroying SemiStaticMap");
}
void SemiStaticMap::laserScanCB(const sensor_msgs::LaserScan msg)
{
ROS_INFO("Laser Scan Callback");
last_data = msg;
try
{
ROS_INFO("Waiting for transform");
tf_.waitForTransform("/map", "/base_laser_link", ros::Time::now(), ros::Duration(3.0));
tf_.lookupTransform("/map", "/base_laser_link", ros::Time::now(), last_tf);
ROS_INFO("tf success for /map to /base_laser_link");
}
catch (tf::TransformException& ex)
{
ROS_WARN("tf fetch failed. %s", ex.what());
}
}
void SemiStaticMap::update()
{
quirkd::Alert alert;
alert.level = 0;
alert.min_x = 0;
alert.max_x = 1;
alert.min_y = 0;
alert.max_y = 1;
ROS_INFO("Update Data Processor");
}
void SemiStaticMap::updateAlertPerimeter(quirkd::Alert* alert, const sensor_msgs::LaserScan scan,
const tf::StampedTransform tf)
{
double base_x = tf.getOrigin().x();
double base_y = tf.getOrigin().y();
double r, p, base_heading;
tf::Matrix3x3 m(tf.getRotation());
m.getRPY(r, p, base_heading);
double scan_min = base_heading + scan.angle_min;
double scan_inc = scan.angle_increment;
double heading = scan_min;
alert->min_x = base_x;
alert->max_x = base_x;
alert->min_y = base_y;
alert->max_y = base_y;
double live_x, live_y;
for (int i = 0; i < scan.ranges.size(); i++)
{
double dist = scan.ranges[i];
live_x = base_x + dist * cos(heading);
live_y = base_y + dist * sin(heading);
alert->min_x = std::min(live_x, double(alert->min_x));
alert->max_x = std::max(live_x, double(alert->max_x));
alert->min_y = std::min(live_y, double(alert->min_y));
alert->max_y = std::max(live_y, double(alert->max_y));
heading += scan_inc;
}
double padding = 0.5;
alert->min_x += -padding;
alert->min_y += -padding;
alert->max_x += padding;
alert->max_y += padding;
}
} // namespace quirkd
<|endoftext|> |
<commit_before>#include <iostream>
#include <future>
#include <utility>
#include "user-thread.hpp"
namespace mymain {
using namespace orks::userthread;
WorkerManager wm {1};
}
template <typename Fn>
void exec_thread(void* func_obj) {
(*static_cast<Fn*>(func_obj))();
delete static_cast<Fn*>(func_obj);
}
// return: std::future<auto>
template <typename Fn>
auto create_thread(Fn fn){
std::promise<decltype(fn())> promise;
auto future = promise.get_future();
// TODO INVOKE(DECAY_COPY(std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...)
auto fn0 = [promise = std::move(promise), fn]() mutable {
promise.set_value(fn());
};
using Fn0 = decltype(fn0);
mymain::wm.start_thread(exec_thread<Fn0>, new Fn0(std::move(fn0)));
return future;
}
long fibo(long n) {
std::cout << "fibo(" << n << ")" << std::endl;
if (n==0 || n==1) {
return n;
}
auto future = create_thread([n](){return fibo(n-1);});
auto n2 = fibo(n-2);
for(; future.wait_for(std::chrono::seconds(0)) != std::future_status::ready;) {
std::cout << "wait fibo(" << n << "-1)" << std::endl;
mymain::wm.scheduling_yield();
}
return n2 + future.get();
}
void fibo_main(void*){
std::cout << "fibo(20) must be 6765. answer: " << fibo(20) << std::endl;
}
int main() {
mymain::wm.start_main_thread(fibo_main, nullptr);
}<commit_msg>Fix parallel number of sample/fibo.cpp: 1->4<commit_after>#include <iostream>
#include <future>
#include <utility>
#include "user-thread.hpp"
namespace mymain {
using namespace orks::userthread;
WorkerManager wm {4};
}
template <typename Fn>
void exec_thread(void* func_obj) {
(*static_cast<Fn*>(func_obj))();
delete static_cast<Fn*>(func_obj);
}
// return: std::future<auto>
template <typename Fn>
auto create_thread(Fn fn){
std::promise<decltype(fn())> promise;
auto future = promise.get_future();
// TODO INVOKE(DECAY_COPY(std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...)
auto fn0 = [promise = std::move(promise), fn]() mutable {
promise.set_value(fn());
};
using Fn0 = decltype(fn0);
mymain::wm.start_thread(exec_thread<Fn0>, new Fn0(std::move(fn0)));
return future;
}
long fibo(long n) {
std::cout << "fibo(" << n << ")" << std::endl;
if (n==0 || n==1) {
return n;
}
auto future = create_thread([n](){return fibo(n-1);});
auto n2 = fibo(n-2);
for(; future.wait_for(std::chrono::seconds(0)) != std::future_status::ready;) {
std::cout << "wait fibo(" << n << "-1)" << std::endl;
mymain::wm.scheduling_yield();
}
return n2 + future.get();
}
void fibo_main(void*){
std::cout << "fibo(20) must be 6765. answer: " << fibo(20) << std::endl;
}
int main() {
mymain::wm.start_main_thread(fibo_main, nullptr);
}<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*
* This module forks a watchdog process that listens on
* a pipe and prints a stackstrace into syslog, when cvmfs
* fails.
*
* Also, it handles getting and setting the maximum number of file descriptors.
*/
#include "cvmfs_config.h"
#include "monitor.h"
#include <signal.h>
#include <sys/resource.h>
#include <execinfo.h>
#ifdef __APPLE__
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
#include <time.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include "platform.h"
#include "util.h"
#include "logging.h"
#include "smalloc.h"
using namespace std; // NOLINT
namespace monitor {
const unsigned kMinOpenFiles = 8192; /**< minmum threshold for the maximum
number of open files */
const unsigned kMaxBacktrace = 64; /**< reported stracktrace depth */
const unsigned kSignalHandlerStacksize = 2*1024*1024; /**< 2 MB */
string *cache_dir_ = NULL;
string *process_name_ = NULL;
bool spawned_ = false;
unsigned max_open_files_;
int pipe_wd_[2];
platform_spinlock lock_handler_;
stack_t sighandler_stack_;
/**
* Signal handler for bad things. Send debug information to watchdog.
*/
static void SendTrace(int signal,
siginfo_t *siginfo __attribute__((unused)),
void *context)
{
int send_errno = errno;
if (platform_spinlock_trylock(&lock_handler_) != 0) {
// Concurrent call, wait for the first one to exit the process
while (true) {}
}
char cflow = 'S';
if (write(pipe_wd_[1], &cflow, 1) != 1)
_exit(1);
// write the occured signal
if (write(pipe_wd_[1], &signal, sizeof(signal)) != sizeof(signal))
_exit(1);
// write the last error number
if (write(pipe_wd_[1], &send_errno, sizeof(send_errno)) != sizeof(send_errno))
_exit(1);
// write the PID
pid_t pid = getpid();
if (write(pipe_wd_[1], &pid, sizeof(pid_t)) != sizeof(pid_t))
_exit(1);
// write the exe path
const char *exe_path = platform_getexepath();
const size_t exe_path_length = strlen(exe_path) + 1; // null termination
if (write(pipe_wd_[1], &exe_path_length, sizeof(size_t)) != sizeof(size_t))
_exit(1);
if (write(pipe_wd_[1], exe_path, exe_path_length) != (int)exe_path_length)
_exit(1);
cflow = 'Q';
(void)write(pipe_wd_[1], &cflow, 1);
// do not die before the stack trace was generated
// kill -9 <pid> will finish this
while(true) {}
_exit(1);
}
/**
* Log a string to syslog and into $cachedir/stacktrace.
* We expect ideally nothing to be logged, so that file is created on demand.
*/
static void LogEmergency(string msg) {
char ctime_buffer[32];
FILE *fp = fopen((*cache_dir_ + "/stacktrace." + *process_name_).c_str(),
"a");
if (fp) {
time_t now = time(NULL);
msg += "\nTimestamp: " + string(ctime_r(&now, ctime_buffer));
if (fwrite(&msg[0], 1, msg.length(), fp) != msg.length())
msg += " (failed to report into log file in cache directory)";
fclose(fp);
} else {
msg += " (failed to open log file in cache directory)";
}
LogCvmfs(kLogMonitor, kLogSyslog, "%s", msg.c_str());
}
/**
* Uses an external shell and gdb to create a full stack trace of the dying
* cvmfs client. The same shell is used to force-quit the client afterwards.
*/
static string GenerateStackTraceAndKill(const string &exe_path, const pid_t pid) {
int retval;
int fd_stdin;
int fd_stdout;
int fd_stderr;
retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);
assert(retval);
// Let the shell execute the stacktrace extraction script
const string bt_cmd = "/etc/cvmfs/gdb-stacktrace.sh " + exe_path + " " +
StringifyInt(pid) + "\n";
WritePipe(fd_stdin, bt_cmd.data(), bt_cmd.length());
// give the dying cvmfs client the finishing stroke
const string kill_cmd = "kill -9 " + StringifyInt(pid) + "\n";
WritePipe(fd_stdin, kill_cmd.data(), kill_cmd.length());
// close the standard in to close the shell
close(fd_stdin);
// read the stack trace from the stdout of our shell
const int bytes_at_a_time = 2;
char *read_buffer = NULL;
int buffer_size = 0;
int buffer_offset = 0;
int chars_io;
while (1) {
if (buffer_offset + bytes_at_a_time > buffer_size) {
buffer_size = bytes_at_a_time + buffer_size * 2;
read_buffer = (char*)realloc(read_buffer, buffer_size);
assert (read_buffer);
}
chars_io = read(fd_stdout,
read_buffer + buffer_offset,
bytes_at_a_time);
if (chars_io <= 0) break;
buffer_offset += chars_io;
}
if (chars_io < 0) {
return "failed to read stack traces";
}
// close the pipes to the shell
close(fd_stderr);
close(fd_stdout);
// good bye...
return read_buffer;
}
/**
* Generates useful information from the backtrace log in the pipe.
*/
static string ReportStacktrace() {
string debug = "--\n";
int recv_signal;
if (read(pipe_wd_[0], &recv_signal, sizeof(recv_signal)) <
int(sizeof(recv_signal)))
{
return "failure while reading signal number";
}
debug += "Signal: " + StringifyInt(recv_signal);
int recv_errno;
if (read(pipe_wd_[0], &recv_errno, sizeof(recv_errno)) <
int(sizeof(recv_errno)))
{
return "failure while reading errno";
}
debug += ", errno: " + StringifyInt(errno);
debug += ", version: " + string(VERSION);
pid_t pid;
if (read(pipe_wd_[0], &pid, sizeof(pid_t)) < int(sizeof(pid_t))) {
return "failure while reading PID";
}
debug += ", PID: " + StringifyInt(pid) + "\n";
size_t exe_path_length;
if (read(pipe_wd_[0], &exe_path_length, sizeof(size_t)) < int(sizeof(size_t))) {
return "failure while reading length of exe path";
}
char exe_path[kMaxPathLength];
if (read(pipe_wd_[0], exe_path, exe_path_length) < int(exe_path_length)) {
return "failure while reading executable path";
}
std::string s_exe_path(exe_path);
debug += "Executable path: " + s_exe_path + "\n";
debug += GenerateStackTraceAndKill(s_exe_path, pid);
return debug;
}
/**
* Listens on the pipe and logs the stacktrace or quits silently.
*/
static void Watchdog() {
char cflow;
int num_read;
while ((num_read = read(pipe_wd_[0], &cflow, 1)) > 0) {
if (cflow == 'S') {
const string debug = ReportStacktrace();
LogEmergency(debug);
} else if (cflow == 'Q') {
break;
} else {
LogEmergency("unexpected error");
break;
}
}
if (num_read <= 0) LogEmergency("unexpected termination");
close(pipe_wd_[0]);
}
bool Init(const string &cache_dir, const std::string &process_name,
const bool check_max_open_files)
{
monitor::cache_dir_ = new string(cache_dir);
monitor::process_name_ = new string(process_name);
if (platform_spinlock_init(&lock_handler_, 0) != 0) return false;
/* check number of open files */
if (check_max_open_files) {
unsigned int soft_limit = 0;
int hard_limit = 0;
struct rlimit rpl;
memset(&rpl, 0, sizeof(rpl));
getrlimit(RLIMIT_NOFILE, &rpl);
soft_limit = rpl.rlim_cur;
#ifdef __APPLE__
hard_limit = sysconf(_SC_OPEN_MAX);
if (hard_limit < 0) {
LogCvmfs(kLogMonitor, kLogStdout, "Warning: could not retrieve "
"hard limit for the number of open files");
}
#else
hard_limit = rpl.rlim_max;
#endif
if (soft_limit < kMinOpenFiles) {
LogCvmfs(kLogMonitor, kLogSyslog | kLogDebug,
"Warning: current limits for number of open files are "
"(%lu/%lu)\n"
"CernVM-FS is likely to run out of file descriptors, "
"set ulimit -n to at least %lu",
soft_limit, hard_limit, kMinOpenFiles);
}
max_open_files_ = soft_limit;
} else {
max_open_files_ = 0;
}
// Dummy call to backtrace to load library
void *unused = NULL;
backtrace(&unused, 1);
if (!unused) return false;
return true;
}
void Fini() {
// Reset signal handlers
if (spawned_) {
signal(SIGQUIT, SIG_DFL);
signal(SIGILL, SIG_DFL);
signal(SIGABRT, SIG_DFL);
signal(SIGFPE, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGBUS, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
signal(SIGXFSZ, SIG_DFL);
free(sighandler_stack_.ss_sp);
sighandler_stack_.ss_size = 0;
}
delete process_name_;
delete cache_dir_;
process_name_ = NULL;
cache_dir_ = NULL;
if (spawned_) {
char quit = 'Q';
(void)write(pipe_wd_[1], &quit, 1);
close(pipe_wd_[1]);
}
platform_spinlock_destroy(&lock_handler_);
}
/**
* Fork watchdog.
*/
void Spawn() {
MakePipe(pipe_wd_);
pid_t pid;
int statloc;
switch (pid = fork()) {
case -1: abort();
case 0:
// Double fork to avoid zombie
switch (fork()) {
case -1: exit(1);
case 0: {
close(pipe_wd_[1]);
Daemonize();
Watchdog();
exit(0);
}
default:
exit(0);
}
default:
close(pipe_wd_[0]);
if (waitpid(pid, &statloc, 0) != pid) abort();
if (!WIFEXITED(statloc) || WEXITSTATUS(statloc)) abort();
}
// Extra stack for signal handlers
int stack_size = kSignalHandlerStacksize; // 2 MB
sighandler_stack_.ss_sp = smalloc(stack_size);
sighandler_stack_.ss_size = stack_size;
sighandler_stack_.ss_flags = 0;
if (sigaltstack(&sighandler_stack_, NULL) != 0)
abort();
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = SendTrace;
sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
sigfillset(&sa.sa_mask);
if (sigaction(SIGQUIT, &sa, NULL) ||
sigaction(SIGILL, &sa, NULL) ||
sigaction(SIGABRT, &sa, NULL) ||
sigaction(SIGFPE, &sa, NULL) ||
sigaction(SIGSEGV, &sa, NULL) ||
sigaction(SIGBUS, &sa, NULL) ||
sigaction(SIGPIPE, &sa, NULL) ||
sigaction(SIGXFSZ, &sa, NULL))
{
abort();
}
spawned_ = true;
}
unsigned GetMaxOpenFiles() {
return max_open_files_;
}
} // namespace monitor
<commit_msg>use kill system call to kill cvmfs client<commit_after>/**
* This file is part of the CernVM File System.
*
* This module forks a watchdog process that listens on
* a pipe and prints a stackstrace into syslog, when cvmfs
* fails.
*
* Also, it handles getting and setting the maximum number of file descriptors.
*/
#include "cvmfs_config.h"
#include "monitor.h"
#include <signal.h>
#include <sys/resource.h>
#include <execinfo.h>
#ifdef __APPLE__
#include <sys/ucontext.h>
#else
#include <ucontext.h>
#endif
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
#include <time.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include "platform.h"
#include "util.h"
#include "logging.h"
#include "smalloc.h"
using namespace std; // NOLINT
namespace monitor {
const unsigned kMinOpenFiles = 8192; /**< minmum threshold for the maximum
number of open files */
const unsigned kMaxBacktrace = 64; /**< reported stracktrace depth */
const unsigned kSignalHandlerStacksize = 2*1024*1024; /**< 2 MB */
string *cache_dir_ = NULL;
string *process_name_ = NULL;
bool spawned_ = false;
unsigned max_open_files_;
int pipe_wd_[2];
platform_spinlock lock_handler_;
stack_t sighandler_stack_;
/**
* Signal handler for bad things. Send debug information to watchdog.
*/
static void SendTrace(int signal,
siginfo_t *siginfo __attribute__((unused)),
void *context)
{
int send_errno = errno;
if (platform_spinlock_trylock(&lock_handler_) != 0) {
// Concurrent call, wait for the first one to exit the process
while (true) {}
}
char cflow = 'S';
if (write(pipe_wd_[1], &cflow, 1) != 1)
_exit(1);
// write the occured signal
if (write(pipe_wd_[1], &signal, sizeof(signal)) != sizeof(signal))
_exit(1);
// write the last error number
if (write(pipe_wd_[1], &send_errno, sizeof(send_errno)) != sizeof(send_errno))
_exit(1);
// write the PID
pid_t pid = getpid();
if (write(pipe_wd_[1], &pid, sizeof(pid_t)) != sizeof(pid_t))
_exit(1);
// write the exe path
const char *exe_path = platform_getexepath();
const size_t exe_path_length = strlen(exe_path) + 1; // null termination
if (write(pipe_wd_[1], &exe_path_length, sizeof(size_t)) != sizeof(size_t))
_exit(1);
if (write(pipe_wd_[1], exe_path, exe_path_length) != (int)exe_path_length)
_exit(1);
cflow = 'Q';
(void)write(pipe_wd_[1], &cflow, 1);
// do not die before the stack trace was generated
// kill -9 <pid> will finish this
while(true) {}
_exit(1);
}
/**
* Log a string to syslog and into $cachedir/stacktrace.
* We expect ideally nothing to be logged, so that file is created on demand.
*/
static void LogEmergency(string msg) {
char ctime_buffer[32];
FILE *fp = fopen((*cache_dir_ + "/stacktrace." + *process_name_).c_str(),
"a");
if (fp) {
time_t now = time(NULL);
msg += "\nTimestamp: " + string(ctime_r(&now, ctime_buffer));
if (fwrite(&msg[0], 1, msg.length(), fp) != msg.length())
msg += " (failed to report into log file in cache directory)";
fclose(fp);
} else {
msg += " (failed to open log file in cache directory)";
}
LogCvmfs(kLogMonitor, kLogSyslog, "%s", msg.c_str());
}
/**
* Uses an external shell and gdb to create a full stack trace of the dying
* cvmfs client. The same shell is used to force-quit the client afterwards.
*/
static string GenerateStackTraceAndKill(const string &exe_path, const pid_t pid) {
int retval;
int fd_stdin;
int fd_stdout;
int fd_stderr;
retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);
assert(retval);
// Let the shell execute the stacktrace extraction script
const string bt_cmd = "/etc/cvmfs/gdb-stacktrace.sh " + exe_path + " " +
StringifyInt(pid) + "\n";
WritePipe(fd_stdin, bt_cmd.data(), bt_cmd.length());
// give the dying cvmfs client the finishing stroke
string result = "";
if (kill(pid, SIGKILL) != 0) {
result += "Failed to kill cvmfs client!\n\n";
}
// close the standard in to close the shell
close(fd_stdin);
// read the stack trace from the stdout of our shell
const int bytes_at_a_time = 2;
char *read_buffer = NULL;
int buffer_size = 0;
int buffer_offset = 0;
int chars_io;
while (1) {
if (buffer_offset + bytes_at_a_time > buffer_size) {
buffer_size = bytes_at_a_time + buffer_size * 2;
read_buffer = (char*)realloc(read_buffer, buffer_size);
assert (read_buffer);
}
chars_io = read(fd_stdout,
read_buffer + buffer_offset,
bytes_at_a_time);
if (chars_io <= 0) break;
buffer_offset += chars_io;
}
// close the pipes to the shell
close(fd_stderr);
close(fd_stdout);
// good bye...
if (chars_io < 0) {
result += "failed to read stack traces";
return result;
} else {
return result + read_buffer;
}
}
/**
* Generates useful information from the backtrace log in the pipe.
*/
static string ReportStacktrace() {
string debug = "--\n";
int recv_signal;
if (read(pipe_wd_[0], &recv_signal, sizeof(recv_signal)) <
int(sizeof(recv_signal)))
{
return "failure while reading signal number";
}
debug += "Signal: " + StringifyInt(recv_signal);
int recv_errno;
if (read(pipe_wd_[0], &recv_errno, sizeof(recv_errno)) <
int(sizeof(recv_errno)))
{
return "failure while reading errno";
}
debug += ", errno: " + StringifyInt(errno);
debug += ", version: " + string(VERSION);
pid_t pid;
if (read(pipe_wd_[0], &pid, sizeof(pid_t)) < int(sizeof(pid_t))) {
return "failure while reading PID";
}
debug += ", PID: " + StringifyInt(pid) + "\n";
size_t exe_path_length;
if (read(pipe_wd_[0], &exe_path_length, sizeof(size_t)) < int(sizeof(size_t))) {
return "failure while reading length of exe path";
}
char exe_path[kMaxPathLength];
if (read(pipe_wd_[0], exe_path, exe_path_length) < int(exe_path_length)) {
return "failure while reading executable path";
}
std::string s_exe_path(exe_path);
debug += "Executable path: " + s_exe_path + "\n";
debug += GenerateStackTraceAndKill(s_exe_path, pid);
return debug;
}
/**
* Listens on the pipe and logs the stacktrace or quits silently.
*/
static void Watchdog() {
char cflow;
int num_read;
while ((num_read = read(pipe_wd_[0], &cflow, 1)) > 0) {
if (cflow == 'S') {
const string debug = ReportStacktrace();
LogEmergency(debug);
} else if (cflow == 'Q') {
break;
} else {
LogEmergency("unexpected error");
break;
}
}
if (num_read <= 0) LogEmergency("unexpected termination");
close(pipe_wd_[0]);
}
bool Init(const string &cache_dir, const std::string &process_name,
const bool check_max_open_files)
{
monitor::cache_dir_ = new string(cache_dir);
monitor::process_name_ = new string(process_name);
if (platform_spinlock_init(&lock_handler_, 0) != 0) return false;
/* check number of open files */
if (check_max_open_files) {
unsigned int soft_limit = 0;
int hard_limit = 0;
struct rlimit rpl;
memset(&rpl, 0, sizeof(rpl));
getrlimit(RLIMIT_NOFILE, &rpl);
soft_limit = rpl.rlim_cur;
#ifdef __APPLE__
hard_limit = sysconf(_SC_OPEN_MAX);
if (hard_limit < 0) {
LogCvmfs(kLogMonitor, kLogStdout, "Warning: could not retrieve "
"hard limit for the number of open files");
}
#else
hard_limit = rpl.rlim_max;
#endif
if (soft_limit < kMinOpenFiles) {
LogCvmfs(kLogMonitor, kLogSyslog | kLogDebug,
"Warning: current limits for number of open files are "
"(%lu/%lu)\n"
"CernVM-FS is likely to run out of file descriptors, "
"set ulimit -n to at least %lu",
soft_limit, hard_limit, kMinOpenFiles);
}
max_open_files_ = soft_limit;
} else {
max_open_files_ = 0;
}
// Dummy call to backtrace to load library
void *unused = NULL;
backtrace(&unused, 1);
if (!unused) return false;
return true;
}
void Fini() {
// Reset signal handlers
if (spawned_) {
signal(SIGQUIT, SIG_DFL);
signal(SIGILL, SIG_DFL);
signal(SIGABRT, SIG_DFL);
signal(SIGFPE, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGBUS, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
signal(SIGXFSZ, SIG_DFL);
free(sighandler_stack_.ss_sp);
sighandler_stack_.ss_size = 0;
}
delete process_name_;
delete cache_dir_;
process_name_ = NULL;
cache_dir_ = NULL;
if (spawned_) {
char quit = 'Q';
(void)write(pipe_wd_[1], &quit, 1);
close(pipe_wd_[1]);
}
platform_spinlock_destroy(&lock_handler_);
}
/**
* Fork watchdog.
*/
void Spawn() {
MakePipe(pipe_wd_);
pid_t pid;
int statloc;
switch (pid = fork()) {
case -1: abort();
case 0:
// Double fork to avoid zombie
switch (fork()) {
case -1: exit(1);
case 0: {
close(pipe_wd_[1]);
Daemonize();
Watchdog();
exit(0);
}
default:
exit(0);
}
default:
close(pipe_wd_[0]);
if (waitpid(pid, &statloc, 0) != pid) abort();
if (!WIFEXITED(statloc) || WEXITSTATUS(statloc)) abort();
}
// Extra stack for signal handlers
int stack_size = kSignalHandlerStacksize; // 2 MB
sighandler_stack_.ss_sp = smalloc(stack_size);
sighandler_stack_.ss_size = stack_size;
sighandler_stack_.ss_flags = 0;
if (sigaltstack(&sighandler_stack_, NULL) != 0)
abort();
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_sigaction = SendTrace;
sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
sigfillset(&sa.sa_mask);
if (sigaction(SIGQUIT, &sa, NULL) ||
sigaction(SIGILL, &sa, NULL) ||
sigaction(SIGABRT, &sa, NULL) ||
sigaction(SIGFPE, &sa, NULL) ||
sigaction(SIGSEGV, &sa, NULL) ||
sigaction(SIGBUS, &sa, NULL) ||
sigaction(SIGPIPE, &sa, NULL) ||
sigaction(SIGXFSZ, &sa, NULL))
{
abort();
}
spawned_ = true;
}
unsigned GetMaxOpenFiles() {
return max_open_files_;
}
} // namespace monitor
<|endoftext|> |
<commit_before>#include "vvMainWindow.h"
#include "ui_vvMainWindow.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqAutoLoadPluginXMLBehavior.h"
#include "pqCommandLineOptionsBehavior.h"
#include "pqCrashRecoveryBehavior.h"
#include "pqInterfaceTracker.h"
#include "pqObjectBuilder.h"
#include "pqPersistentMainWindowStateBehavior.h"
#include "pqQtMessageHandlerBehavior.h"
#include "pqRenderView.h"
#include "pqStandardViewModules.h"
#include "vtkPVPlugin.h"
#include "vvLoadDataReaction.h"
#include "vvSelectionReaction.h"
// Declare the plugin to load.
PV_PLUGIN_IMPORT_INIT(VelodyneHDLPlugin);
class vvMainWindow::pqInternals
{
public:
Ui::vvMainWindow Ui;
pqInternals(vvMainWindow* window)
{
this->Ui.setupUi(window);
this->paraviewInit(window);
this->setupUi(window);
}
private:
void paraviewInit(vvMainWindow* window)
{
pqApplicationCore* core = pqApplicationCore::instance();
// Register ParaView interfaces.
pqInterfaceTracker* pgm = core->interfaceTracker();
pgm->addInterface(new pqStandardViewModules(pgm));
// Define application behaviors.
new pqAutoLoadPluginXMLBehavior(window);
new pqCommandLineOptionsBehavior(window);
new pqCrashRecoveryBehavior(window);
new pqPersistentMainWindowStateBehavior(window);
new pqQtMessageHandlerBehavior(window);
// Connect to builtin server.
pqObjectBuilder* builder = core->getObjectBuilder();
pqServer* server = builder->createServer(pqServerResource("builtin:"));
pqActiveObjects::instance().setActiveServer(server);
// Create a default view.
pqView* view = builder->createView(pqRenderView::renderViewType(),
server);
pqActiveObjects::instance().setActiveView(view);
window->setCentralWidget(view->getWidget());
}
void setupUi(vvMainWindow* window)
{
new vvLoadDataReaction(this->Ui.action_Open);
new vvSelectionReaction(vvSelectionReaction::SURFACE_POINTS,
this->Ui.actionSelect_Visible_Points);
new vvSelectionReaction(vvSelectionReaction::ALL_POINTS,
this->Ui.actionSelect_All_Points);
}
};
//-----------------------------------------------------------------------------
vvMainWindow::vvMainWindow() : Internals (new vvMainWindow::pqInternals(this))
{
PV_PLUGIN_IMPORT(VelodyneHDLPlugin);
}
//-----------------------------------------------------------------------------
vvMainWindow::~vvMainWindow()
{
delete this->Internals;
this->Internals = NULL;
}
//-----------------------------------------------------------------------------
<commit_msg>Hide center axes<commit_after>#include "vvMainWindow.h"
#include "ui_vvMainWindow.h"
#include "pqActiveObjects.h"
#include "pqApplicationCore.h"
#include "pqAutoLoadPluginXMLBehavior.h"
#include "pqCommandLineOptionsBehavior.h"
#include "pqCrashRecoveryBehavior.h"
#include "pqInterfaceTracker.h"
#include "pqObjectBuilder.h"
#include "pqPersistentMainWindowStateBehavior.h"
#include "pqQtMessageHandlerBehavior.h"
#include "pqRenderView.h"
#include "pqStandardViewModules.h"
#include "vtkPVPlugin.h"
#include "vtkSMPropertyHelper.h"
#include "vvLoadDataReaction.h"
#include "vvSelectionReaction.h"
// Declare the plugin to load.
PV_PLUGIN_IMPORT_INIT(VelodyneHDLPlugin);
class vvMainWindow::pqInternals
{
public:
Ui::vvMainWindow Ui;
pqInternals(vvMainWindow* window)
{
this->Ui.setupUi(window);
this->paraviewInit(window);
this->setupUi(window);
}
private:
void paraviewInit(vvMainWindow* window)
{
pqApplicationCore* core = pqApplicationCore::instance();
// Register ParaView interfaces.
pqInterfaceTracker* pgm = core->interfaceTracker();
pgm->addInterface(new pqStandardViewModules(pgm));
// Define application behaviors.
new pqAutoLoadPluginXMLBehavior(window);
new pqCommandLineOptionsBehavior(window);
new pqCrashRecoveryBehavior(window);
new pqPersistentMainWindowStateBehavior(window);
new pqQtMessageHandlerBehavior(window);
// Connect to builtin server.
pqObjectBuilder* builder = core->getObjectBuilder();
pqServer* server = builder->createServer(pqServerResource("builtin:"));
pqActiveObjects::instance().setActiveServer(server);
// Create a default view.
pqView* view = builder->createView(pqRenderView::renderViewType(),
server);
vtkSMPropertyHelper(view->getProxy(),"CenterAxesVisibility").Set(0);
// MultiSamples doesn't work, we need to set that up before registering the proxy.
vtkSMPropertyHelper(view->getProxy(),"MultiSamples").Set(4);
view->getProxy()->UpdateVTKObjects();
pqActiveObjects::instance().setActiveView(view);
window->setCentralWidget(view->getWidget());
}
void setupUi(vvMainWindow* window)
{
new vvLoadDataReaction(this->Ui.action_Open);
new vvSelectionReaction(vvSelectionReaction::SURFACE_POINTS,
this->Ui.actionSelect_Visible_Points);
new vvSelectionReaction(vvSelectionReaction::ALL_POINTS,
this->Ui.actionSelect_All_Points);
}
};
//-----------------------------------------------------------------------------
vvMainWindow::vvMainWindow() : Internals (new vvMainWindow::pqInternals(this))
{
PV_PLUGIN_IMPORT(VelodyneHDLPlugin);
}
//-----------------------------------------------------------------------------
vvMainWindow::~vvMainWindow()
{
delete this->Internals;
this->Internals = NULL;
}
//-----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>#include "qcsv2matrix.h"
#include <iostream>
#include <QDateTime>
/**
* @brief QCSV2MATRIX::QCSV2MATRIX
*/
QCSV2MATRIX::QCSV2MATRIX() :
noHeader(false),
lastLine(false),
unique(false),
csvSeperator(";"),
mtxSeperator(";"),
minColumns(-1),
mtxFileName(""),
csvFileName("")
{
}
bool QCSV2MATRIX::convert(const QFile& sourceCSVFile, const QFile &sourceMTXFile, const QString& csvSeperator, const QString& mtxSeperator, const QList<int>& rawColumns, const QList<int>& ignoreColumns, const QList<int>& dtColumns, const QString& dtFormat = "", const int& minColumns = -1, const bool& noHeader = false, const bool& lastLine = false, const bool& unique = false)
{
// Initialise CSV reader
QFile csvFile(sourceCSVFile.fileName());
if (!csvFile.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QTextStream csvStream(&csvFile);
// Initialise MTX writer
QFile mtxFile(sourceMTXFile.fileName());
if(!mtxFile.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream mtxStream(&mtxFile);
// Init variables
int lineCount = 0;
int uniqueValue = 0;
QString prevLine;
QString header;
QList<QMap<QString, int>* > columnLegends;
QList<int> copyColumns(rawColumns);
copyColumns.append(dtColumns);
// Loop through file
while (!csvStream.atEnd())
{
QString line = csvStream.readLine();
// Skip empty lines
if(line.isEmpty())
continue;
// Process header
if((lineCount == 0) && !lastLine && !noHeader)
{
header = line;
++lineCount;
continue;
}
// Process previous line
if(!prevLine.isEmpty())
{
QStringList columnList = prevLine.split(csvSeperator);
QString mtxLine = "";
int processed = 0;
for(int index = 0; index < columnList.size(); ++index)
{
// Check if this is an ignoreColumn (if yes ignore)
if(ignoreColumns.contains(index))
continue;
QString columnValue = columnList.at(index);
// Check if we need to extend the columnLegends
if(processed >= columnLegends.size())
{
QMap<QString, int> *msi = new QMap<QString, int>;
columnLegends.append(msi);
// Check if this should be a raw column
if(stringIsNumber(columnValue))
{
// Add this number in the rawColumns list
copyColumns.append(processed);
}
}
// Check if this is a raw column
if(!copyColumns.contains(processed))
{
if(!columnLegends.at(processed)->contains(columnValue))
{
QMap<QString, int> * tmpLegend = columnLegends[processed];
int value;
if(unique)
{
value = uniqueValue;
++uniqueValue;
}
else
{
value = tmpLegend->size();
}
tmpLegend->insert(columnValue, value);
}
columnValue.setNum(columnLegends.at(processed)->value(columnValue));
}
// Check if this is a date-time column that should be converted to unix time
if(dtColumns.contains(processed))
{
QDateTime dt = QDateTime::fromString(columnValue, dtFormat);
columnValue = "";
columnValue = QString::number(dt.toMSecsSinceEpoch());
}
// The columnValue is prepared for the mtx
if(processed > 0)
mtxLine += mtxSeperator;
mtxLine += columnValue;
++processed;
}
// Extend the number of columns to satisfy minColumns
for(;processed < minColumns; ++processed)
{
mtxLine += mtxSeperator;
}
// Write the line to file
mtxStream << mtxLine << "\n";
}
// Go to next line
prevLine = line;
++lineCount;
}
if(lastLine)
{
header = prevLine;
}
else
{
//process last line
std::cout << "WARN: the current implementation does not process the last line with these settings!" << std::endl;
}
std::cout << "WARN: the current implementation does not adjust the header to remove ignored columns!" << std::endl;
// Close the files neatly
csvFile.close();
mtxFile.close();
// Serialise the legends and headers
// Initialise Header writer
QFile headerFile(sourceMTXFile.fileName() + ".header");
if(!headerFile.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream headerStream(&headerFile);
// Header and legend
headerStream << "\\ Header and legend information for the matrix file: " << sourceMTXFile.fileName() << "\n";
QStringList headerList = header.split(csvSeperator);
QString newHeader;
int processed = 0;
for(int index = 0; index < headerList.size(); ++index)
{
// Check if this is an ignoreColumn (if yes ignore)
if(ignoreColumns.contains(index))
continue;
headerStream << "Column " << processed << ": " << headerList.at(index) << "\n";
headerStream << "Legend: \t";
QMap<QString, int> *tmpLegend;
tmpLegend = columnLegends.at(processed);
QMap<QString, int>::const_iterator i = tmpLegend->constBegin();
while (i != tmpLegend->constEnd()) {
headerStream << "\n" << "\t" << i.value() << "\t" << i.key();
++i;
}
headerStream << "\n" ;
++processed;
}
headerFile.close();
return true;
}
bool QCSV2MATRIX::stringIsNumber(const QString &str)
{
bool ok;
str.toDouble(&ok);
return ok;
}
<commit_msg>added support for empty csv columns (previously added to the map and represented with a value, now left empty)<commit_after>#include "qcsv2matrix.h"
#include <iostream>
#include <QDateTime>
/**
* @brief QCSV2MATRIX::QCSV2MATRIX
*/
QCSV2MATRIX::QCSV2MATRIX() :
noHeader(false),
lastLine(false),
unique(false),
csvSeperator(";"),
mtxSeperator(";"),
minColumns(-1),
mtxFileName(""),
csvFileName("")
{
}
bool QCSV2MATRIX::convert(const QFile& sourceCSVFile, const QFile &sourceMTXFile, const QString& csvSeperator, const QString& mtxSeperator, const QList<int>& rawColumns, const QList<int>& ignoreColumns, const QList<int>& dtColumns, const QString& dtFormat = "", const int& minColumns = -1, const bool& noHeader = false, const bool& lastLine = false, const bool& unique = false)
{
// Initialise CSV reader
QFile csvFile(sourceCSVFile.fileName());
if (!csvFile.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QTextStream csvStream(&csvFile);
// Initialise MTX writer
QFile mtxFile(sourceMTXFile.fileName());
if(!mtxFile.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream mtxStream(&mtxFile);
// Init variables
int lineCount = 0;
int uniqueValue = 0;
QString prevLine;
QString header;
QList<QMap<QString, int>* > columnLegends;
QList<int> copyColumns(rawColumns);
copyColumns.append(dtColumns);
// Loop through file
while (!csvStream.atEnd())
{
QString line = csvStream.readLine();
// Skip empty lines
if(line.isEmpty())
continue;
// Process header
if((lineCount == 0) && !lastLine && !noHeader)
{
header = line;
++lineCount;
continue;
}
// Process previous line
if(!prevLine.isEmpty())
{
QStringList columnList = prevLine.split(csvSeperator);
QString mtxLine = "";
int processed = 0;
for(int index = 0; index < columnList.size(); ++index)
{
// Check if this is an ignoreColumn (if yes ignore)
if(ignoreColumns.contains(index))
continue;
QString columnValue = columnList.at(index);
// Check if we need to extend the columnLegends
if(processed >= columnLegends.size())
{
QMap<QString, int> *msi = new QMap<QString, int>;
columnLegends.append(msi);
// Check if this should be a raw column
if(stringIsNumber(columnValue))
{
// Add this number in the rawColumns list
copyColumns.append(processed);
}
}
// Check if the value is not empty
if(!columnValue.isEmpty())
{
// Check if this is a raw column
if(!copyColumns.contains(processed))
{
// Make sure that this columnValue exists in the Legend
if(!columnLegends.at(processed)->contains(columnValue))
{
QMap<QString, int> * tmpLegend = columnLegends[processed];
int value;
if(unique)
{
value = uniqueValue;
++uniqueValue;
}
else
{
value = tmpLegend->size();
}
tmpLegend->insert(columnValue, value);
}
// Convert the columnValue
columnValue.setNum(columnLegends.at(processed)->value(columnValue));
}
// Check if this is a date-time column that should be converted to unix time
if(dtColumns.contains(processed))
{
QDateTime dt = QDateTime::fromString(columnValue, dtFormat);
columnValue = "";
columnValue = QString::number(dt.toMSecsSinceEpoch());
}
}
// The columnValue is prepared for the mtx
if(processed > 0)
mtxLine += mtxSeperator;
mtxLine += columnValue;
++processed;
}
// Extend the number of columns to satisfy minColumns
for(;processed < minColumns; ++processed)
{
mtxLine += mtxSeperator;
}
// Write the line to file
mtxStream << mtxLine << "\n";
}
// Go to next line
prevLine = line;
++lineCount;
}
if(lastLine)
{
header = prevLine;
}
else
{
//process last line
std::cout << "WARN: the current implementation does not process the last line with these settings!" << std::endl;
}
std::cout << "WARN: the current implementation does not adjust the header to remove ignored columns!" << std::endl;
// Close the files neatly
csvFile.close();
mtxFile.close();
// Serialise the legends and headers
// Initialise Header writer
QFile headerFile(sourceMTXFile.fileName() + ".header");
if(!headerFile.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
QTextStream headerStream(&headerFile);
// Header and legend
headerStream << "\\ Header and legend information for the matrix file: " << sourceMTXFile.fileName() << "\n";
QStringList headerList = header.split(csvSeperator);
QString newHeader;
int processed = 0;
for(int index = 0; index < headerList.size(); ++index)
{
// Check if this is an ignoreColumn (if yes ignore)
if(ignoreColumns.contains(index))
continue;
headerStream << "Column " << processed << ": " << headerList.at(index) << "\n";
headerStream << "Legend: \t";
QMap<QString, int> *tmpLegend;
tmpLegend = columnLegends.at(processed);
QMap<QString, int>::const_iterator i = tmpLegend->constBegin();
while (i != tmpLegend->constEnd()) {
headerStream << "\n" << "\t" << i.value() << "\t" << i.key();
++i;
}
headerStream << "\n" ;
++processed;
}
headerFile.close();
return true;
}
bool QCSV2MATRIX::stringIsNumber(const QString &str)
{
bool ok;
str.toDouble(&ok);
return ok;
}
<|endoftext|> |
<commit_before>/**
* This file is part of the CernVM File System.
*/
#include <string>
#include "cvmfs_config.h"
#include "../logging.h"
#include "../monitor.h"
#include "../swissknife.h"
#include "../util/posix.h"
#include "../util/string.h"
#include "reactor.h"
static const char *kDefaultReceiverLogDir = "/var/log/cvmfs_receiver/";
swissknife::ParameterList MakeParameterList() {
swissknife::ParameterList params;
params.push_back(
swissknife::Parameter::Optional('i', "File descriptor to use for input"));
params.push_back(swissknife::Parameter::Optional(
'o', "File descriptor to use for output"));
params.push_back(swissknife::Parameter::Optional(
'w', "Watchdog stacktrace output dir, "
"use without parameter to disable watchdog. "
"Default: " + std::string(kDefaultReceiverLogDir)));
return params;
}
bool ReadCmdLineArguments(int argc, char** argv,
const swissknife::ParameterList& params,
swissknife::ArgumentList* arguments) {
// parse the command line arguments for the Command
optind = 1;
std::string option_string = "";
for (unsigned j = 0; j < params.size(); ++j) {
option_string.push_back(params[j].key());
if (!params[j].switch_only()) option_string.push_back(':');
}
int c;
while ((c = getopt(argc, argv, option_string.c_str())) != -1) {
bool valid_option = false;
for (unsigned j = 0; j < params.size(); ++j) {
if (c == params[j].key()) {
valid_option = true;
(*arguments)[c].Reset();
if (!params[j].switch_only()) {
(*arguments)[c].Reset(new std::string(optarg));
}
break;
}
}
if (!valid_option) {
LogCvmfs(kLogReceiver, kLogSyslog,
"CVMFS gateway services receiver component. Usage:");
for (size_t i = 0; i < params.size(); ++i) {
LogCvmfs(kLogReceiver, kLogSyslog, " \"%c\" - %s", params[i].key(),
params[i].description().c_str());
}
return false;
}
}
for (size_t j = 0; j < params.size(); ++j) {
if (!params[j].optional()) {
if (arguments->find(params[j].key()) == arguments->end()) {
LogCvmfs(kLogReceiver, kLogSyslogErr, "parameter -%c missing",
params[j].key());
return false;
}
}
}
return true;
}
int main(int argc, char** argv) {
swissknife::ArgumentList arguments;
if (!ReadCmdLineArguments(argc, argv, MakeParameterList(), &arguments)) {
return 1;
}
SetLogSyslogFacility(1);
SetLogSyslogShowPID(true);
int fdin = 0;
int fdout = 1;
std::string watchdog_out_dir = kDefaultReceiverLogDir;
if (arguments.find('i') != arguments.end()) {
fdin = std::atoi(arguments.find('i')->second->c_str());
}
if (arguments.find('o') != arguments.end()) {
fdout = std::atoi(arguments.find('o')->second->c_str());
}
if (arguments.find('w') != arguments.end()) {
watchdog_out_dir = *arguments.find('w')->second;
}
// Spawn monitoring process (watchdog)
Watchdog *watchdog = NULL;
if (watchdog_out_dir != "") {
if (!MkdirDeep(watchdog_out_dir, 0755)) {
LogCvmfs(kLogReceiver, kLogSyslogErr | kLogStderr,
"Failed to create stacktrace directory: %s",
watchdog_out_dir.c_str());
return 1;
}
std::string timestamp = GetGMTimestamp("%Y.%m.%d-%H.%M.%S");
watchdog = Watchdog::Create(watchdog_out_dir + "/stacktrace." + timestamp);
if (watchdog == NULL) {
LogCvmfs(kLogReceiver, kLogSyslogErr | kLogStderr,
"Failed to initialize watchdog");
return 1;
}
watchdog->Spawn();
}
LogCvmfs(kLogReceiver, kLogSyslog, "CVMFS receiver started");
receiver::Reactor reactor(fdin, fdout);
if (!reactor.Run()) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"Error running CVMFS Receiver event loop");
delete watchdog;
return 1;
}
LogCvmfs(kLogReceiver, kLogSyslog, "CVMFS receiver finished");
delete watchdog;
return 0;
}
<commit_msg>manage exception at high level in the receiver<commit_after>/**
* This file is part of the CernVM File System.
*/
#include <string>
#include "cvmfs_config.h"
#include "../logging.h"
#include "../monitor.h"
#include "../swissknife.h"
#include "../util/exception.h"
#include "../util/posix.h"
#include "../util/string.h"
#include "reactor.h"
static const char *kDefaultReceiverLogDir = "/var/log/cvmfs_receiver/";
swissknife::ParameterList MakeParameterList() {
swissknife::ParameterList params;
params.push_back(
swissknife::Parameter::Optional('i', "File descriptor to use for input"));
params.push_back(swissknife::Parameter::Optional(
'o', "File descriptor to use for output"));
params.push_back(swissknife::Parameter::Optional(
'w', "Watchdog stacktrace output dir, "
"use without parameter to disable watchdog. "
"Default: " + std::string(kDefaultReceiverLogDir)));
return params;
}
bool ReadCmdLineArguments(int argc, char** argv,
const swissknife::ParameterList& params,
swissknife::ArgumentList* arguments) {
// parse the command line arguments for the Command
optind = 1;
std::string option_string = "";
for (unsigned j = 0; j < params.size(); ++j) {
option_string.push_back(params[j].key());
if (!params[j].switch_only()) option_string.push_back(':');
}
int c;
while ((c = getopt(argc, argv, option_string.c_str())) != -1) {
bool valid_option = false;
for (unsigned j = 0; j < params.size(); ++j) {
if (c == params[j].key()) {
valid_option = true;
(*arguments)[c].Reset();
if (!params[j].switch_only()) {
(*arguments)[c].Reset(new std::string(optarg));
}
break;
}
}
if (!valid_option) {
LogCvmfs(kLogReceiver, kLogSyslog,
"CVMFS gateway services receiver component. Usage:");
for (size_t i = 0; i < params.size(); ++i) {
LogCvmfs(kLogReceiver, kLogSyslog, " \"%c\" - %s", params[i].key(),
params[i].description().c_str());
}
return false;
}
}
for (size_t j = 0; j < params.size(); ++j) {
if (!params[j].optional()) {
if (arguments->find(params[j].key()) == arguments->end()) {
LogCvmfs(kLogReceiver, kLogSyslogErr, "parameter -%c missing",
params[j].key());
return false;
}
}
}
return true;
}
int main(int argc, char** argv) {
swissknife::ArgumentList arguments;
if (!ReadCmdLineArguments(argc, argv, MakeParameterList(), &arguments)) {
return 1;
}
SetLogSyslogFacility(1);
SetLogSyslogShowPID(true);
int fdin = 0;
int fdout = 1;
std::string watchdog_out_dir = kDefaultReceiverLogDir;
if (arguments.find('i') != arguments.end()) {
fdin = std::atoi(arguments.find('i')->second->c_str());
}
if (arguments.find('o') != arguments.end()) {
fdout = std::atoi(arguments.find('o')->second->c_str());
}
if (arguments.find('w') != arguments.end()) {
watchdog_out_dir = *arguments.find('w')->second;
}
// Spawn monitoring process (watchdog)
Watchdog *watchdog = NULL;
if (watchdog_out_dir != "") {
if (!MkdirDeep(watchdog_out_dir, 0755)) {
LogCvmfs(kLogReceiver, kLogSyslogErr | kLogStderr,
"Failed to create stacktrace directory: %s",
watchdog_out_dir.c_str());
return 1;
}
std::string timestamp = GetGMTimestamp("%Y.%m.%d-%H.%M.%S");
watchdog = Watchdog::Create(watchdog_out_dir + "/stacktrace." + timestamp);
if (watchdog == NULL) {
LogCvmfs(kLogReceiver, kLogSyslogErr | kLogStderr,
"Failed to initialize watchdog");
return 1;
}
watchdog->Spawn();
}
LogCvmfs(kLogReceiver, kLogSyslog, "CVMFS receiver started");
receiver::Reactor reactor(fdin, fdout);
try {
if (!reactor.Run()) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"Error running CVMFS Receiver event loop");
delete watchdog;
return 1;
}
} catch (const ECvmfsException& e) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"Runtime error during CVMFS Receiver event loop.\n"
"%s",
e.what());
delete watchdog;
return 2;
} catch (...) {
LogCvmfs(kLogReceiver, kLogSyslogErr,
"Unknow error during CVMFS Receiver event loop.\n");
delete watchdog;
return 3;
}
LogCvmfs(kLogReceiver, kLogSyslog, "CVMFS receiver finished");
delete watchdog;
return 0;
}
<|endoftext|> |
<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
#include "../include/librealsense2/rs.hpp"
#include "../include/librealsense2/rsutil.h"
#include "proc/synthetic-stream.h"
#include "proc/occlusion-filter.h"
//#include "../../common/tiny-profiler.h"
#include <vector>
#include <cmath>
namespace librealsense
{
occlusion_filter::occlusion_filter() : _occlusion_filter(occlusion_monotonic_scan) , _occlusion_scanning(horizontal)
{
}
void occlusion_filter::set_texel_intrinsics(const rs2_intrinsics& in)
{
_texels_intrinsics = in;
_texels_depth.resize(_texels_intrinsics.value().width*_texels_intrinsics.value().height);
}
void occlusion_filter::process(float3* points, float2* uv_map, const std::vector<float2> & pix_coord, const rs2::depth_frame& depth) const
{
switch (_occlusion_filter)
{
case occlusion_none:
break;
case occlusion_monotonic_scan:
monotonic_heuristic_invalidation(points, uv_map, pix_coord, depth);
break;
default:
throw std::runtime_error(to_string() << "Unsupported occlusion filter type " << _occlusion_filter << " requested");
break;
}
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// Return the gretest common divisor of a
// and b which lie in the given range.
int maxDivisorRange(int a, int b, int l, int h)
{
int g = gcd(a, b);
int res = g;
// Loop from 1 to sqrt(GCD(a, b).
for (int i = l; i * i <= g && i <= h; i++)
if ((g % i == 0) && (g / i) < h)
{
res = g / i;
break;
}
return res;
}
template<size_t SIZE>
void rotate_image_optimized(byte* dest[], const byte* source, int width, int height)
{
auto width_out = height;
auto height_out = width;
auto out = dest[0];
auto buffer_size = maxDivisorRange(height, width, 1, ROTATION_BUFFER_SIZE);
byte *buffer = new byte[buffer_size * buffer_size * SIZE];
for (int i = 0; i < height; i = i + buffer_size)
{
for (int j = 0; j < width; j = j + buffer_size)
{
for (int ii = 0; ii < buffer_size; ii++) {
for (int jj = 0; jj < buffer_size; jj++) {
auto source_index = (j + jj + (width * (i + ii))) * SIZE; // capture a buffer from source
memcpy((void*)(buffer + buffer_size* (buffer_size - jj - 1) + (buffer_size - ii - 1) * SIZE), &source[source_index], SIZE);
}
}
for (int ii = 0; ii < buffer_size; ii++) { // copy buffer to out
auto out_index = ((height - (i + buffer_size - 1) - 1) + (width - (j + buffer_size - 1) - 1 + ii) * height) * SIZE;
memcpy(&out[out_index], (buffer + ii), SIZE * buffer_size);
}
}
}
}
// IMPORTANT! This implementation is based on the assumption that the RGB sensor is positioned strictly to the left of the depth sensor.
// namely D415/D435 and SR300. The implementation WILL NOT work properly for different setups
// Heuristic occlusion invalidation algorithm:
// - Use the uv texels calculated when projecting depth to color
// - Scan each line from left to right and check the the U coordinate in the mapping is raising monotonically.
// - The occlusion is designated as U coordinate for a given pixel is less than the U coordinate of the predecessing pixel.
// - The UV mapping for the occluded pixel is reset to (0,0). Later on the (0,0) coordinate in the texture map is overwritten
// with a invalidation color such as black/magenta according to the purpose (production/debugging)
void occlusion_filter::monotonic_heuristic_invalidation(float3* points, float2* uv_map, const std::vector<float2>& pix_coord, const rs2::depth_frame& depth) const
{
float occZTh = 0.1f; //meters
int occDilationSz = 1;
auto points_width = _depth_intrinsics->width;
auto points_height = _depth_intrinsics->height;
auto pixels_ptr = pix_coord.data();
auto points_ptr = points;
auto uv_map_ptr = uv_map;
float maxInLine = -1;
float maxZ = 0;
if (_occlusion_scanning == horizontal)
{
for( size_t y = 0; y < points_height; ++y )
{
maxInLine = -1;
maxZ = 0;
int occDilationLeft = 0;
for( size_t x = 0; x < points_width; ++x )
{
if( points_ptr->z )
{
// Occlusion detection
if( pixels_ptr->x < maxInLine
|| ( pixels_ptr->x == maxInLine && ( points_ptr->z - maxZ ) > occZTh ) )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft = occDilationSz;
}
else
{
maxInLine = pixels_ptr->x;
maxZ = points_ptr->z;
if( occDilationLeft > 0 )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft--;
}
}
}
++points_ptr;
++uv_map_ptr;
++pixels_ptr;
}
}
}
else if (_occlusion_scanning == vertical)
{
auto rotated_depth_width = _depth_intrinsics->height;
auto rotated_depth_height = _depth_intrinsics->width;
auto depth_ptr = (byte*)(depth.get_data());
std::vector< byte > alloc( depth.get_bytes_per_pixel() * points_width * points_height );
byte* depth_planes[1];
depth_planes[0] = alloc.data();
rotate_image_optimized<2>(depth_planes, (const byte*)(depth.get_data()), points_width, points_height);
// scan depth frame after rotation: check if there is a noticed jump between adjacen pixels in Z-axis (depth), it means there could be occlusion.
// save suspected points and run occlusion-invalidation vertical scan only on them
// after rotation : height = points_width , width = points_height
for (int i = 0; i < rotated_depth_height; i++)
{
for (int j = 0; j < rotated_depth_width; j++)
{
// before depth frame rotation: occlusion detected in the positive direction of Y
// after rotation : scan from right to left (positive direction of X) to detect occlusion
// compare depth each pixel only with the pixel on its right (i,j+1)
auto index = (j + (rotated_depth_width * i));
auto uv_index = ((rotated_depth_height - i - 1) + (rotated_depth_width - j - 1) * rotated_depth_height);
auto index_right = index + 1;
uint16_t* diff_depth_ptr = (uint16_t*)depth_planes[0];
uint16_t diff_right = abs((uint16_t)(*(diff_depth_ptr + index)) - (uint16_t)(*(diff_depth_ptr + index_right)));
float scaled_threshold = DEPTH_OCCLUSION_THRESHOLD / _depth_units;
if (diff_right > scaled_threshold)
{
points_ptr = points + uv_index;
uv_map_ptr = uv_map + uv_index;
if (j >= VERTICAL_SCAN_WINDOW_SIZE) {
maxInLine = (uv_map_ptr - 1 * points_width)->y;
for (size_t y = 0; y <= VERTICAL_SCAN_WINDOW_SIZE; ++y)
{
if (((uv_map_ptr + y * points_width)->y < maxInLine))
{
*(points_ptr + y * points_width) = { 0.f, 0.f };
}
else
{
break;
}
}
}
}
}
}
}
}
// Prepare texture map without occlusion that for every texture coordinate there no more than one depth point that is mapped to it
// i.e. for every (u,v) map coordinate we select the depth point with minimum Z. all other points that are mapped to this texel will be invalidated
// Algo input data:
// Vector of 3D [xyz] coordinates of depth_width*depth_height size
// Vector of 2D [i,j] coordinates where the val[i,j] stores the texture coordinate (s,t) for the corresponding (i,j) pixel in depth frame
// Algo intermediate data:
// Vector of depth values (floats) in size of the mapped texture (different from depth width*height) where
// each (i,j) cell holds the minimal Z among all the depth pixels that are mapped to the specific texel
void occlusion_filter::comprehensive_invalidation(float3* points, float2* uv_map, const std::vector<float2> & pix_coord) const
{
auto depth_points = points;
auto mapped_pix = pix_coord.data();
size_t mapped_tex_width = _texels_intrinsics->width;
size_t mapped_tex_height = _texels_intrinsics->height;
size_t points_width = _depth_intrinsics->width;
size_t points_height = _depth_intrinsics->height;
static const float z_threshold = 0.05f; // Compensate for temporal noise when comparing Z values
// Clear previous data
memset((void*)(_texels_depth.data()), 0, _texels_depth.size() * sizeof(float));
// Pass1 -generate texels mapping with minimal depth for each texel involved
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] < 0.0001f) || ((_texels_depth[texel_index] + z_threshold) > depth_points->z))
{
_texels_depth[texel_index] = depth_points->z;
}
}
++depth_points;
++mapped_pix;
}
}
mapped_pix = pix_coord.data();
depth_points = points;
auto uv_ptr = uv_map;
// Pass2 -invalidate depth texels with occlusion traits
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] > 0.0001f) && ((_texels_depth[texel_index] + z_threshold) < depth_points->z))
{
*uv_ptr = { 0.f, 0.f };
}
}
++depth_points;
++mapped_pix;
++uv_ptr;
}
}
}
}
<commit_msg>L515 occlusion filter fix<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2018 Intel Corporation. All Rights Reserved.
#include "../include/librealsense2/rs.hpp"
#include "../include/librealsense2/rsutil.h"
#include "proc/synthetic-stream.h"
#include "proc/occlusion-filter.h"
//#include "../../common/tiny-profiler.h"
#include <vector>
#include <cmath>
namespace librealsense
{
occlusion_filter::occlusion_filter() : _occlusion_filter(occlusion_monotonic_scan) , _occlusion_scanning(horizontal)
{
}
void occlusion_filter::set_texel_intrinsics(const rs2_intrinsics& in)
{
_texels_intrinsics = in;
_texels_depth.resize(_texels_intrinsics.value().width*_texels_intrinsics.value().height);
}
void occlusion_filter::process(float3* points, float2* uv_map, const std::vector<float2> & pix_coord, const rs2::depth_frame& depth) const
{
switch (_occlusion_filter)
{
case occlusion_none:
break;
case occlusion_monotonic_scan:
monotonic_heuristic_invalidation(points, uv_map, pix_coord, depth);
break;
default:
throw std::runtime_error(to_string() << "Unsupported occlusion filter type " << _occlusion_filter << " requested");
break;
}
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// Return the greatest common divisor of a
// and b which lie in the given range.
int maxDivisorRange(int a, int b, int lo, int hi)
{
if (lo > hi)
{
int tmp = lo;
lo = hi;
hi = tmp;
}
int g = gcd(a, b);
int res = g;
// Loop from 1 to sqrt(GCD(a, b).
for (int i = lo; i * i <= g && i <= hi; i++)
if ((g % i == 0) && (g / i) < hi)
{
res = g / i;
break;
}
return res;
}
template<size_t SIZE>
void rotate_image_optimized(byte* dest[], const byte* source, int width, int height)
{
auto width_out = height;
auto height_out = width;
auto out = dest[0];
auto buffer_size = maxDivisorRange(height, width, 1, ROTATION_BUFFER_SIZE);
std::vector<byte> buffer(buffer_size * buffer_size * SIZE);
for (int i = 0; i < height; i = i + buffer_size)
{
for (int j = 0; j < width; j = j + buffer_size)
{
for (int ii = 0; ii < buffer_size; ii++) {
for (int jj = 0; jj < buffer_size; jj++) {
auto source_index = (j + jj + (width * (i + ii))) * SIZE; // capture a buffer from source
memcpy((void*)&(buffer[buffer_size * (buffer_size - jj - 1) + (buffer_size - ii - 1) * SIZE]), &source[source_index], SIZE);
}
}
for (int ii = 0; ii < buffer_size; ii++) { // copy buffer to out
auto out_index = ((height - (i + buffer_size - 1) - 1) + (width - (j + buffer_size - 1) - 1 + ii) * height) * SIZE;
memcpy(&out[out_index], &(buffer[ii]), SIZE * buffer_size);
}
}
}
}
// IMPORTANT! This implementation is based on the assumption that the RGB sensor is positioned strictly to the left of the depth sensor.
// namely D415/D435 and SR300. The implementation WILL NOT work properly for different setups
// Heuristic occlusion invalidation algorithm:
// - Use the uv texels calculated when projecting depth to color
// - Scan each line from left to right and check the the U coordinate in the mapping is raising monotonically.
// - The occlusion is designated as U coordinate for a given pixel is less than the U coordinate of the predecessing pixel.
// - The UV mapping for the occluded pixel is reset to (0,0). Later on the (0,0) coordinate in the texture map is overwritten
// with a invalidation color such as black/magenta according to the purpose (production/debugging)
void occlusion_filter::monotonic_heuristic_invalidation(float3* points, float2* uv_map, const std::vector<float2>& pix_coord, const rs2::depth_frame& depth) const
{
float occZTh = 0.1f; //meters
int occDilationSz = 1;
auto points_width = _depth_intrinsics->width;
auto points_height = _depth_intrinsics->height;
auto pixels_ptr = pix_coord.data();
auto points_ptr = points;
auto uv_map_ptr = uv_map;
float maxInLine = -1;
float maxZ = 0;
if (_occlusion_scanning == horizontal)
{
for( size_t y = 0; y < points_height; ++y )
{
maxInLine = -1;
maxZ = 0;
int occDilationLeft = 0;
for( size_t x = 0; x < points_width; ++x )
{
if( points_ptr->z )
{
// Occlusion detection
if( pixels_ptr->x < maxInLine
|| ( pixels_ptr->x == maxInLine && ( points_ptr->z - maxZ ) > occZTh ) )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft = occDilationSz;
}
else
{
maxInLine = pixels_ptr->x;
maxZ = points_ptr->z;
if( occDilationLeft > 0 )
{
*points_ptr = { 0, 0, 0 };
occDilationLeft--;
}
}
}
++points_ptr;
++uv_map_ptr;
++pixels_ptr;
}
}
}
else if (_occlusion_scanning == vertical)
{
auto rotated_depth_width = _depth_intrinsics->height;
auto rotated_depth_height = _depth_intrinsics->width;
auto depth_ptr = (byte*)(depth.get_data());
std::vector< byte > alloc( depth.get_bytes_per_pixel() * points_width * points_height );
byte* depth_planes[1];
depth_planes[0] = alloc.data();
rotate_image_optimized<2>(depth_planes, (const byte*)(depth.get_data()), points_width, points_height);
// scan depth frame after rotation: check if there is a noticed jump between adjacen pixels in Z-axis (depth), it means there could be occlusion.
// save suspected points and run occlusion-invalidation vertical scan only on them
// after rotation : height = points_width , width = points_height
for (int i = 0; i < rotated_depth_height; i++)
{
for (int j = 0; j < rotated_depth_width; j++)
{
// before depth frame rotation: occlusion detected in the positive direction of Y
// after rotation : scan from right to left (positive direction of X) to detect occlusion
// compare depth each pixel only with the pixel on its right (i,j+1)
auto index = (j + (rotated_depth_width * i));
auto uv_index = ((rotated_depth_height - i - 1) + (rotated_depth_width - j - 1) * rotated_depth_height);
auto index_right = index + 1;
uint16_t* diff_depth_ptr = (uint16_t*)depth_planes[0];
uint16_t diff_right = abs((uint16_t)(*(diff_depth_ptr + index)) - (uint16_t)(*(diff_depth_ptr + index_right)));
float scaled_threshold = DEPTH_OCCLUSION_THRESHOLD / _depth_units;
if (diff_right > scaled_threshold)
{
points_ptr = points + uv_index;
uv_map_ptr = uv_map + uv_index;
if (j >= VERTICAL_SCAN_WINDOW_SIZE) {
maxInLine = (uv_map_ptr - 1 * points_width)->y;
for (size_t y = 0; y <= VERTICAL_SCAN_WINDOW_SIZE; ++y)
{
if (((uv_map_ptr + y * points_width)->y < maxInLine))
{
*(points_ptr + y * points_width) = { 0.f, 0.f };
}
else
{
break;
}
}
}
}
}
}
}
}
// Prepare texture map without occlusion that for every texture coordinate there no more than one depth point that is mapped to it
// i.e. for every (u,v) map coordinate we select the depth point with minimum Z. all other points that are mapped to this texel will be invalidated
// Algo input data:
// Vector of 3D [xyz] coordinates of depth_width*depth_height size
// Vector of 2D [i,j] coordinates where the val[i,j] stores the texture coordinate (s,t) for the corresponding (i,j) pixel in depth frame
// Algo intermediate data:
// Vector of depth values (floats) in size of the mapped texture (different from depth width*height) where
// each (i,j) cell holds the minimal Z among all the depth pixels that are mapped to the specific texel
void occlusion_filter::comprehensive_invalidation(float3* points, float2* uv_map, const std::vector<float2> & pix_coord) const
{
auto depth_points = points;
auto mapped_pix = pix_coord.data();
size_t mapped_tex_width = _texels_intrinsics->width;
size_t mapped_tex_height = _texels_intrinsics->height;
size_t points_width = _depth_intrinsics->width;
size_t points_height = _depth_intrinsics->height;
static const float z_threshold = 0.05f; // Compensate for temporal noise when comparing Z values
// Clear previous data
memset((void*)(_texels_depth.data()), 0, _texels_depth.size() * sizeof(float));
// Pass1 -generate texels mapping with minimal depth for each texel involved
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] < 0.0001f) || ((_texels_depth[texel_index] + z_threshold) > depth_points->z))
{
_texels_depth[texel_index] = depth_points->z;
}
}
++depth_points;
++mapped_pix;
}
}
mapped_pix = pix_coord.data();
depth_points = points;
auto uv_ptr = uv_map;
// Pass2 -invalidate depth texels with occlusion traits
for (size_t i = 0; i < points_height; i++)
{
for (size_t j = 0; j < points_width; j++)
{
if ((depth_points->z > 0.0001f) &&
(mapped_pix->x > 0.f) && (mapped_pix->x < mapped_tex_width) &&
(mapped_pix->y > 0.f) && (mapped_pix->y < mapped_tex_height))
{
size_t texel_index = (size_t)(mapped_pix->y)*mapped_tex_width + (size_t)(mapped_pix->x);
if ((_texels_depth[texel_index] > 0.0001f) && ((_texels_depth[texel_index] + z_threshold) < depth_points->z))
{
*uv_ptr = { 0.f, 0.f };
}
}
++depth_points;
++mapped_pix;
++uv_ptr;
}
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swdbtoolsclient.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-09 02:13:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SWDBTOOLSCLIENT_HXX
#define _SWDBTOOLSCLIENT_HXX
#ifndef CONNECTIVITY_VIRTUAL_DBTOOLS_HXX
#include <connectivity/virtualdbtools.hxx>
#endif
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_MODULE_H_
#include <osl/module.h>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif
/* -----------------------------30.08.2001 11:01------------------------------
Client to use the dbtools library as load-on-call
---------------------------------------------------------------------------*/
class SW_DLLPUBLIC SwDbtoolsClient
{
private:
::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools;
::rtl::Reference< ::connectivity::simple::IDataAccessTypeConversion > m_xAccessTypeConversion;
::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory;
SW_DLLPRIVATE static void registerClient();
SW_DLLPRIVATE static void revokeClient();
SW_DLLPRIVATE void getFactory();
SW_DLLPRIVATE ::rtl::Reference< ::connectivity::simple::IDataAccessTools > getDataAccessTools();
SW_DLLPRIVATE ::rtl::Reference< ::connectivity::simple::IDataAccessTypeConversion > getAccessTypeConversion();
public:
SwDbtoolsClient();
~SwDbtoolsClient();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource(
const ::rtl::OUString& _rsRegisteredName,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory
);
sal_Int32 getDefaultNumberFormat(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColumn,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatTypes >& _rxTypes,
const ::com::sun::star::lang::Locale& _rLocale
);
::rtl::OUString getValue(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxColumn,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter>& _rxFormatter,
const ::com::sun::star::lang::Locale& _rLocale,
const ::com::sun::star::util::Date& _rNullDate
);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.1202); FILE MERGED 2008/04/01 15:56:20 thb 1.4.1202.3: #i85898# Stripping all external header guards 2008/04/01 12:53:34 thb 1.4.1202.2: #i85898# Stripping all external header guards 2008/03/31 16:52:42 rt 1.4.1202.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: swdbtoolsclient.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 _SWDBTOOLSCLIENT_HXX
#define _SWDBTOOLSCLIENT_HXX
#include <connectivity/virtualdbtools.hxx>
#include <osl/mutex.hxx>
#include <osl/module.h>
#include "swdllapi.h"
/* -----------------------------30.08.2001 11:01------------------------------
Client to use the dbtools library as load-on-call
---------------------------------------------------------------------------*/
class SW_DLLPUBLIC SwDbtoolsClient
{
private:
::rtl::Reference< ::connectivity::simple::IDataAccessTools > m_xDataAccessTools;
::rtl::Reference< ::connectivity::simple::IDataAccessTypeConversion > m_xAccessTypeConversion;
::rtl::Reference< ::connectivity::simple::IDataAccessToolsFactory > m_xDataAccessFactory;
SW_DLLPRIVATE static void registerClient();
SW_DLLPRIVATE static void revokeClient();
SW_DLLPRIVATE void getFactory();
SW_DLLPRIVATE ::rtl::Reference< ::connectivity::simple::IDataAccessTools > getDataAccessTools();
SW_DLLPRIVATE ::rtl::Reference< ::connectivity::simple::IDataAccessTypeConversion > getAccessTypeConversion();
public:
SwDbtoolsClient();
~SwDbtoolsClient();
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDataSource > getDataSource(
const ::rtl::OUString& _rsRegisteredName,
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory
);
sal_Int32 getDefaultNumberFormat(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColumn,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatTypes >& _rxTypes,
const ::com::sun::star::lang::Locale& _rLocale
);
::rtl::OUString getValue(
const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxColumn,
const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter>& _rxFormatter,
const ::com::sun::star::lang::Locale& _rLocale,
const ::com::sun::star::util::Date& _rNullDate
);
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grfsh.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-09-27 12:02:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SWGRFSH_HXX
#define _SWGRFSH_HXX
#include "frmsh.hxx"
class SwGrfShell: public SwBaseShell
{
public:
SFX_DECL_INTERFACE(SW_GRFSHELL)
void Execute(SfxRequest &);
void ExecAttr(SfxRequest &);
void GetAttrState(SfxItemSet &);
SwGrfShell(SwView &rView);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.242); FILE MERGED 2008/03/31 16:58:32 rt 1.4.242.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: grfsh.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 _SWGRFSH_HXX
#define _SWGRFSH_HXX
#include "frmsh.hxx"
class SwGrfShell: public SwBaseShell
{
public:
SFX_DECL_INTERFACE(SW_GRFSHELL)
void Execute(SfxRequest &);
void ExecAttr(SfxRequest &);
void GetAttrState(SfxItemSet &);
SwGrfShell(SwView &rView);
};
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 - Franz Detro
*
* Some real world test program for motor control
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "ev3dev.h"
#include <thread>
#include <chrono>
#include <iostream>
#include <fstream>
#ifndef NO_LINUX_HEADERS
#include <unistd.h>
#include <fcntl.h>
#include <linux/input.h>
#define KEY_RELEASE 0
#define KEY_PRESS 1
#define KEY_REPEAT 2
#endif
using namespace std;
using namespace ev3dev;
class control
{
public:
control();
~control();
void drive(int speed, int time=0);
void turn(int direction);
void stop();
void reset();
bool initialized() const;
void terminate_on_key();
void panic_if_touched();
void remote_loop();
void drive_autonomously();
void terminate() { _terminate = true; }
protected:
large_motor _motor_left;
large_motor _motor_right;
infrared_sensor _sensor_ir;
touch_sensor _sensor_touch;
enum state
{
state_idle,
state_driving,
state_turning
};
state _state;
bool _terminate;
};
control::control() :
_motor_left(OUTPUT_B),
_motor_right(OUTPUT_C),
_state(state_idle),
_terminate(false)
{
}
control::~control()
{
reset();
}
void control::drive(int speed, int time)
{
_motor_left.set_duty_cycle_sp(-speed);
_motor_right.set_duty_cycle_sp(-speed);
_state = state_driving;
if (time > 0)
{
_motor_left .set_time_sp(time).run_timed();
_motor_right.set_time_sp(time).run_timed();
while (_motor_left.state().count("running") || _motor_right.state().count("running"))
this_thread::sleep_for(chrono::milliseconds(10));
_state = state_idle;
}
else
{
_motor_left.run_forever();
_motor_right.run_forever();
}
}
void control::turn(int direction)
{
if (_state != state_idle)
stop();
if (direction == 0)
return;
_state = state_turning;
_motor_left. set_position_sp( direction).set_duty_cycle_sp(50).run_to_rel_pos();
_motor_right.set_position_sp(-direction).set_duty_cycle_sp(50).run_to_rel_pos();
while (_motor_left.state().count("running") || _motor_right.state().count("running"))
this_thread::sleep_for(chrono::milliseconds(10));
_state = state_idle;
}
void control::stop()
{
_motor_left .stop();
_motor_right.stop();
_state = state_idle;
}
void control::reset()
{
if (_motor_left.connected())
_motor_left.reset();
if (_motor_right.connected())
_motor_right.reset();
_state = state_idle;
}
bool control::initialized() const
{
return (_motor_left .connected() &&
_motor_right.connected() &&
_sensor_ir .connected());
}
void control::terminate_on_key()
{
#ifndef NO_LINUX_HEADERS
thread t([&] () {
int fd = open("/dev/input/by-path/platform-gpio-keys.0-event", O_RDONLY);
if (fd < 0)
{
cout << "Couldn't open platform-gpio-keys device!" << endl;
return;
}
input_event ev;
while (true)
{
size_t rb = read(fd, &ev, sizeof(ev));
if (rb < sizeof(input_event))
continue;
if ((ev.type == EV_KEY) /*&& (ev.value == KEY_PRESS)*/)
{
terminate();
return;
}
}
});
t.detach();
#endif
}
void control::panic_if_touched()
{
if (!_sensor_touch.connected())
{
cout << "no touch sensor found!" << endl;
return;
}
thread t([&] () {
while (!_terminate) {
if (_sensor_touch.value())
{
terminate();
reset();
break;
}
this_thread::sleep_for(chrono::milliseconds(100));
}
});
t.detach();
}
void control::remote_loop()
{
remote_control r(_sensor_ir);
if (!r.connected())
{
cout << "no infrared sensor found!" << endl;
return;
}
const int speed = 70;
const int ninety_degrees = 260;
r.on_red_up = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
drive(speed);
}
else
stop();
};
r.on_red_down = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
drive(-speed);
}
else
stop();
};
r.on_blue_up = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
turn(-ninety_degrees);
}
};
r.on_blue_down = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
turn(ninety_degrees);
}
};
r.on_beacon = [&] (bool state)
{
if (state)
terminate();
};
while (!_terminate)
{
if (!r.process())
{
this_thread::sleep_for(chrono::milliseconds(10));
}
}
reset();
}
void control::drive_autonomously()
{
if (!_sensor_ir.connected())
{
cout << "no infrared sensor found!" << endl;
return;
}
_sensor_ir.set_mode(infrared_sensor::mode_ir_prox);
while (!_terminate)
{
int distance = _sensor_ir.value();
if (distance <= 0)
{
// panic
terminate();
reset();
break;
}
else if (distance >= 20)
{
if (_state != state_driving)
drive(75);
this_thread::sleep_for(chrono::milliseconds(10));
}
else
{
stop();
int direction = 100;
int start_distance = distance;
while (distance <= 40)
{
turn(direction);
distance = _sensor_ir.value();
if (distance < start_distance)
{
if (direction < 0)
{
drive(-70, 1000);
}
else
{
direction = -200;
}
}
}
}
}
}
int main()
{
control c;
if (c.initialized())
{
c.terminate_on_key(); // we terminate if a button is pressed
c.panic_if_touched(); // we panic if the touch sensor is triggered
// change mode to 1 to get IR remote mode
int mode = 2;
if (mode == 1)
{
cout << "ensure that channel 1 is selected on your remote control." << endl << endl
<< "upper red button - forward" << endl
<< "lower red button - backward" << endl
<< "upper blue button - left" << endl
<< "lower blue button - right" << endl
<< "middle button - exit" << endl << endl;
c.remote_loop();
}
else if (mode == 2)
{
cout << "touch the sensor or press a button to stop." << endl << endl;
c.drive_autonomously();
}
}
else
{
cout << "you need to connect an infrared sensor and large motors to ports B and C!" << endl;
return 1;
}
return 0;
}
<commit_msg>Use speed_sp instead of duty_cycle_sp in drive-test.cpp<commit_after>/*
* Copyright (c) 2014 - Franz Detro
*
* Some real world test program for motor control
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "ev3dev.h"
#include <thread>
#include <chrono>
#include <iostream>
#include <fstream>
#ifndef NO_LINUX_HEADERS
#include <unistd.h>
#include <fcntl.h>
#include <linux/input.h>
#define KEY_RELEASE 0
#define KEY_PRESS 1
#define KEY_REPEAT 2
#endif
using namespace std;
using namespace ev3dev;
class control
{
public:
control();
~control();
void drive(int speed, int time=0);
void turn(int direction);
void stop();
void reset();
bool initialized() const;
void terminate_on_key();
void panic_if_touched();
void remote_loop();
void drive_autonomously();
void terminate() { _terminate = true; }
protected:
large_motor _motor_left;
large_motor _motor_right;
infrared_sensor _sensor_ir;
touch_sensor _sensor_touch;
enum state
{
state_idle,
state_driving,
state_turning
};
state _state;
bool _terminate;
};
control::control() :
_motor_left(OUTPUT_B),
_motor_right(OUTPUT_C),
_state(state_idle),
_terminate(false)
{
}
control::~control()
{
reset();
}
void control::drive(int speed, int time)
{
_motor_left.set_speed_sp(-speed);
_motor_right.set_speed_sp(-speed);
_state = state_driving;
if (time > 0)
{
_motor_left .set_time_sp(time).run_timed();
_motor_right.set_time_sp(time).run_timed();
while (_motor_left.state().count("running") || _motor_right.state().count("running"))
this_thread::sleep_for(chrono::milliseconds(10));
_state = state_idle;
}
else
{
_motor_left.run_forever();
_motor_right.run_forever();
}
}
void control::turn(int direction)
{
if (_state != state_idle)
stop();
if (direction == 0)
return;
_state = state_turning;
_motor_left. set_position_sp( direction).set_speed_sp(500).run_to_rel_pos();
_motor_right.set_position_sp(-direction).set_speed_sp(500).run_to_rel_pos();
while (_motor_left.state().count("running") || _motor_right.state().count("running"))
this_thread::sleep_for(chrono::milliseconds(10));
_state = state_idle;
}
void control::stop()
{
_motor_left .stop();
_motor_right.stop();
_state = state_idle;
}
void control::reset()
{
if (_motor_left.connected())
_motor_left.reset();
if (_motor_right.connected())
_motor_right.reset();
_state = state_idle;
}
bool control::initialized() const
{
return (_motor_left .connected() &&
_motor_right.connected() &&
_sensor_ir .connected());
}
void control::terminate_on_key()
{
#ifndef NO_LINUX_HEADERS
thread t([&] () {
int fd = open("/dev/input/by-path/platform-gpio-keys.0-event", O_RDONLY);
if (fd < 0)
{
cout << "Couldn't open platform-gpio-keys device!" << endl;
return;
}
input_event ev;
while (true)
{
size_t rb = read(fd, &ev, sizeof(ev));
if (rb < sizeof(input_event))
continue;
if ((ev.type == EV_KEY) /*&& (ev.value == KEY_PRESS)*/)
{
terminate();
return;
}
}
});
t.detach();
#endif
}
void control::panic_if_touched()
{
if (!_sensor_touch.connected())
{
cout << "no touch sensor found!" << endl;
return;
}
thread t([&] () {
while (!_terminate) {
if (_sensor_touch.value())
{
terminate();
reset();
break;
}
this_thread::sleep_for(chrono::milliseconds(100));
}
});
t.detach();
}
void control::remote_loop()
{
remote_control r(_sensor_ir);
if (!r.connected())
{
cout << "no infrared sensor found!" << endl;
return;
}
const int speed = 700;
const int ninety_degrees = 260;
r.on_red_up = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
drive(speed);
}
else
stop();
};
r.on_red_down = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
drive(-speed);
}
else
stop();
};
r.on_blue_up = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
turn(-ninety_degrees);
}
};
r.on_blue_down = [&] (bool state)
{
if (state)
{
if (_state == state_idle)
turn(ninety_degrees);
}
};
r.on_beacon = [&] (bool state)
{
if (state)
terminate();
};
while (!_terminate)
{
if (!r.process())
{
this_thread::sleep_for(chrono::milliseconds(10));
}
}
reset();
}
void control::drive_autonomously()
{
if (!_sensor_ir.connected())
{
cout << "no infrared sensor found!" << endl;
return;
}
_sensor_ir.set_mode(infrared_sensor::mode_ir_prox);
while (!_terminate)
{
int distance = _sensor_ir.value();
if (distance <= 0)
{
// panic
terminate();
reset();
break;
}
else if (distance >= 20)
{
if (_state != state_driving)
drive(750);
this_thread::sleep_for(chrono::milliseconds(10));
}
else
{
stop();
int direction = 100;
int start_distance = distance;
while (distance <= 40)
{
turn(direction);
distance = _sensor_ir.value();
if (distance < start_distance)
{
if (direction < 0)
{
drive(-700, 1000);
}
else
{
direction = -200;
}
}
}
}
}
}
int main()
{
control c;
if (c.initialized())
{
c.terminate_on_key(); // we terminate if a button is pressed
c.panic_if_touched(); // we panic if the touch sensor is triggered
// change mode to 1 to get IR remote mode
int mode = 2;
if (mode == 1)
{
cout << "ensure that channel 1 is selected on your remote control." << endl << endl
<< "upper red button - forward" << endl
<< "lower red button - backward" << endl
<< "upper blue button - left" << endl
<< "lower blue button - right" << endl
<< "middle button - exit" << endl << endl;
c.remote_loop();
}
else if (mode == 2)
{
cout << "touch the sensor or press a button to stop." << endl << endl;
c.drive_autonomously();
}
}
else
{
cout << "you need to connect an infrared sensor and large motors to ports B and C!" << endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2016-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventBaseManager.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
#include "eden/fs/service/gen-cpp2/EdenService.h"
#include "watchman.h"
#include "QueryableView.h"
using facebook::eden::EdenServiceAsyncClient;
namespace watchman {
namespace {
folly::SocketAddress getEdenServerSocketAddress() {
folly::SocketAddress addr;
// In the future, eden will need to provide a well-supported way to locate
// this socket, as the "local" path component here is a FB-specific default.
auto path = folly::to<std::string>(getenv("HOME"), "/local/.eden/socket");
addr.setFromPath(path);
return addr;
}
/** Create a thrift client that will connect to the eden server associated
* with the current user. */
std::unique_ptr<EdenServiceAsyncClient> getEdenClient(
folly::EventBase* eb = folly::EventBaseManager::get()->getEventBase()) {
return folly::make_unique<EdenServiceAsyncClient>(
apache::thrift::HeaderClientChannel::newChannel(
apache::thrift::async::TAsyncSocket::newSocket(
eb, getEdenServerSocketAddress())));
}
class EdenView : public QueryableView {
w_string root_path_;
public:
explicit EdenView(w_root_t* root) {
root_path_ = root->root_path;
}
bool timeGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
bool suffixGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
/** Walks files that match the supplied set of paths */
bool pathGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
bool globGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
bool allFilesGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
ClockPosition getMostRecentRootNumberAndTickValue() const override {
return ClockPosition();
}
w_string getCurrentClockString() const override {
return ClockPosition().toClockString();
}
uint32_t getLastAgeOutTickValue() const override {
return 0;
}
time_t getLastAgeOutTimeStamp() const override {
return 0;
}
void ageOut(w_perf_t& sample, std::chrono::seconds minAge) override {}
bool doAnyOfTheseFilesExist(
const std::vector<w_string>& fileNames) const override {
return false;
}
void startThreads(const std::shared_ptr<w_root_t>& root) override {}
void signalThreads() override {}
const w_string& getName() const override {
static w_string name("eden");
return name;
}
std::shared_future<void> waitUntilReadyToQuery(
const std::shared_ptr<w_root_t>& root) override {
std::promise<void> p;
p.set_value();
return p.get_future();
}
};
std::shared_ptr<watchman::QueryableView> detectEden(w_root_t* root) {
// This is mildly ghetto, but the way we figure out if the intended path
// is on an eden mount is to ask eden to stat the root of that mount;
// if it throws then it is not an eden mount.
auto client = getEdenClient();
std::vector<::facebook::eden::FileInformationOrError> info;
static const std::vector<std::string> paths{""};
client->sync_getFileInformation(
info, std::string(root->root_path.data(), root->root_path.size()), paths);
return std::make_shared<EdenView>(root);
}
} // anon namespace
static WatcherRegistry
reg("eden", detectEden, 100 /* prefer eden above others */);
} // watchman namespace
<commit_msg>Codemod folly::make_unique to std::make_unique<commit_after>/* Copyright 2016-present Facebook, Inc.
* Licensed under the Apache License, Version 2.0 */
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventBaseManager.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
#include "eden/fs/service/gen-cpp2/EdenService.h"
#include "watchman.h"
#include "QueryableView.h"
using facebook::eden::EdenServiceAsyncClient;
namespace watchman {
namespace {
folly::SocketAddress getEdenServerSocketAddress() {
folly::SocketAddress addr;
// In the future, eden will need to provide a well-supported way to locate
// this socket, as the "local" path component here is a FB-specific default.
auto path = folly::to<std::string>(getenv("HOME"), "/local/.eden/socket");
addr.setFromPath(path);
return addr;
}
/** Create a thrift client that will connect to the eden server associated
* with the current user. */
std::unique_ptr<EdenServiceAsyncClient> getEdenClient(
folly::EventBase* eb = folly::EventBaseManager::get()->getEventBase()) {
return std::make_unique<EdenServiceAsyncClient>(
apache::thrift::HeaderClientChannel::newChannel(
apache::thrift::async::TAsyncSocket::newSocket(
eb, getEdenServerSocketAddress())));
}
class EdenView : public QueryableView {
w_string root_path_;
public:
explicit EdenView(w_root_t* root) {
root_path_ = root->root_path;
}
bool timeGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
bool suffixGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
/** Walks files that match the supplied set of paths */
bool pathGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
bool globGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
bool allFilesGenerator(
w_query* query,
struct w_query_ctx* ctx,
int64_t* num_walked) const override {
return false;
}
ClockPosition getMostRecentRootNumberAndTickValue() const override {
return ClockPosition();
}
w_string getCurrentClockString() const override {
return ClockPosition().toClockString();
}
uint32_t getLastAgeOutTickValue() const override {
return 0;
}
time_t getLastAgeOutTimeStamp() const override {
return 0;
}
void ageOut(w_perf_t& sample, std::chrono::seconds minAge) override {}
bool doAnyOfTheseFilesExist(
const std::vector<w_string>& fileNames) const override {
return false;
}
void startThreads(const std::shared_ptr<w_root_t>& root) override {}
void signalThreads() override {}
const w_string& getName() const override {
static w_string name("eden");
return name;
}
std::shared_future<void> waitUntilReadyToQuery(
const std::shared_ptr<w_root_t>& root) override {
std::promise<void> p;
p.set_value();
return p.get_future();
}
};
std::shared_ptr<watchman::QueryableView> detectEden(w_root_t* root) {
// This is mildly ghetto, but the way we figure out if the intended path
// is on an eden mount is to ask eden to stat the root of that mount;
// if it throws then it is not an eden mount.
auto client = getEdenClient();
std::vector<::facebook::eden::FileInformationOrError> info;
static const std::vector<std::string> paths{""};
client->sync_getFileInformation(
info, std::string(root->root_path.data(), root->root_path.size()), paths);
return std::make_shared<EdenView>(root);
}
} // anon namespace
static WatcherRegistry
reg("eden", detectEden, 100 /* prefer eden above others */);
} // watchman namespace
<|endoftext|> |
<commit_before>#include "list.hpp"
void ScreenList::init(Uint8 pMode) {
setMode(pMode);
imageSize = 32;
imageMarginTop = 2;
imageMarginRight = 4;
titleMarginBottom = 1;
textMarginBottom = 4;
options.length = 0;
options.offsetX = 0.;
options.offsetY = 0.;
options.selectetIdx = 0;
calcScrollbar();
}
void ScreenList::calcScrollbar() {
Uint8 sliderWidth = 16;
Uint8 sliderHeight = 16;
float rangeStepSize = (surface->h - (5 + sliderHeight)) /
(options.lengthY - surface->h);
float stepPos = rangeStepSize * options.offsetY * -1;
rectScrollBarSlider.x = surface->w - 19;
rectScrollBarSlider.y = 2 + (int)stepPos;
rectScrollBarSlider.w = sliderWidth;
rectScrollBarSlider.h = sliderHeight;
rectScrollBar.x = surface->w - 21;
rectScrollBar.y = 0;
rectScrollBar.w = 20;
rectScrollBar.h = surface->h - 1;
}
void ScreenList::showScrollbar() {
calcScrollbar();
rectangleRGBA(
surface, rectScrollBar.x, rectScrollBar.y,
rectScrollBar.x + rectScrollBar.w, rectScrollBar.y + rectScrollBar.h,
255, 255, 255, 255
);
boxRGBA(
surface,
rectScrollBarSlider.x, rectScrollBarSlider.y,
rectScrollBarSlider.x + rectScrollBarSlider.w,
rectScrollBarSlider.y + rectScrollBarSlider.h,
255, 255, 255, 255
);
}
void ScreenList::scroll(bool up, float valY) {
if (up == true) {
if (options.offsetY + valY <= 0)
options.offsetY += valY;
else
options.offsetY = 0;
} else {
if (options.offsetY - valY >= -1 * (options.lengthY - surface->h))
options.offsetY -= valY;
else
options.offsetY = -1 * (options.lengthY - surface->h);
}
}
bool ScreenList::sliderActive(Uint16 x, Uint16 y) {
if (x >= rectScrollBar.x && y >= rectScrollBar.y &&
x <= rectScrollBar.x + rectScrollBar.w &&
y <= rectScrollBar.y + rectScrollBar.h) {
return true;
}
return false;
}
void ScreenList::moveSlider(Uint16 screenY) {
float rangeStepSize = surface->h / (options.lengthY - surface->h);
options.offsetY = screenY / rangeStepSize * -1;
}
void ScreenList::setMode(Uint8 pMode) {
mode = pMode;
}
Uint8 ScreenList::getMode() {
return mode;
}
void ScreenList::setEntries(Lists *lists) {
if (mode == LIST_MODE_EDITOR_TERRAIN) {
options.length = lists->terrainLength;
} else if (mode == LIST_MODE_EDITOR_ITEMS) {
options.length = lists->itemsLength;
} else if (mode == LIST_MODE_GAME_BUILDINGS) {
options.length = lists->buildingsLength;
}
entries = new stScreenListEntry[options.length];
int i;
string imageFile;
for (i = 0; i < options.length; i++) {
entries[i].title.setFontSize(18);
entries[i].text.setFontSize(16);
if (mode == LIST_MODE_EDITOR_TERRAIN) {
entries[i].title.set(lists->terrain[i].title);
entries[i].text.set(lists->terrain[i].description);
imageFile = "images/terrain/" + lists->terrain[i].name + "_" +
to_string(imageSize) + ".png";
} else if (mode == LIST_MODE_EDITOR_ITEMS) {
entries[i].title.set(lists->items[i].title);
entries[i].text.set(lists->items[i].description);
imageFile = "images/items/" + lists->items[i].name + "_" +
to_string(imageSize) + ".png";
} else if (mode == LIST_MODE_GAME_BUILDINGS) {
entries[i].title.set(lists->buildings[i].title);
entries[i].text.set(lists->buildings[i].description);
imageFile = "images/buildings/" + lists->buildings[i].name + "_" +
to_string(imageSize) + ".png";
}
entries[i].image = loadImage(imageFile);
}
options.lengthY = options.length *
(entries[0].title.getHeight() + titleMarginBottom +
entries[0].text.getHeight() + textMarginBottom);
}
void ScreenList::show() {
Uint16 i;
int entryPosX, entryPosY;
entryPosX = options.offsetX;
entryPosY = options.offsetY;
SDL_Rect offset;
for (i = 0; i < options.length; i++) {
offset.x = entryPosX;
offset.y = entryPosY;
if (options.selectetIdx == i) {
boxRGBA(
surface,
offset.x, offset.y,
offset.x + surface->w - 22,
offset.y + entries[i].title.getHeight() + entries[i].text.getHeight(),
0, 120, 180, 255
);
}
if (entries[i].image != NULL) {
offset.y = entryPosY + imageMarginTop;
apply(offset.x, offset.y, entries[i].image);
offset.x += imageSize + imageMarginRight;
} else {
offset.x = entryPosX;
}
offset.y = entryPosY;
apply(offset.x, offset.y, entries[i].title.get());
entryPosY += entries[i].title.getHeight() + titleMarginBottom;
offset.y = entryPosY;
apply(offset.x, offset.y, entries[i].text.get());
entryPosY += entries[i].text.getHeight() + textMarginBottom;
offset.y = entryPosY;
}
}
void ScreenList::selectEntry(Uint16 screenY) {
Uint16 entryHeight = entries[0].title.getHeight() + titleMarginBottom +
entries[0].text.getHeight() + textMarginBottom;
options.selectetIdx = (-1 * options.offsetY + screenY) / entryHeight;
}
Uint16 ScreenList::getSelectedIdx() {
return options.selectetIdx;
}
void ScreenList::unset() {
int i;
for (i = 0; i < options.length; i++) {
entries[i].title.unset();
entries[i].text.unset();
}
delete[] entries;
}
<commit_msg>free list entry images<commit_after>#include "list.hpp"
void ScreenList::init(Uint8 pMode) {
setMode(pMode);
imageSize = 32;
imageMarginTop = 2;
imageMarginRight = 4;
titleMarginBottom = 1;
textMarginBottom = 4;
options.length = 0;
options.offsetX = 0.;
options.offsetY = 0.;
options.selectetIdx = 0;
calcScrollbar();
}
void ScreenList::calcScrollbar() {
Uint8 sliderWidth = 16;
Uint8 sliderHeight = 16;
float rangeStepSize = (surface->h - (5 + sliderHeight)) /
(options.lengthY - surface->h);
float stepPos = rangeStepSize * options.offsetY * -1;
rectScrollBarSlider.x = surface->w - 19;
rectScrollBarSlider.y = 2 + (int)stepPos;
rectScrollBarSlider.w = sliderWidth;
rectScrollBarSlider.h = sliderHeight;
rectScrollBar.x = surface->w - 21;
rectScrollBar.y = 0;
rectScrollBar.w = 20;
rectScrollBar.h = surface->h - 1;
}
void ScreenList::showScrollbar() {
calcScrollbar();
rectangleRGBA(
surface, rectScrollBar.x, rectScrollBar.y,
rectScrollBar.x + rectScrollBar.w, rectScrollBar.y + rectScrollBar.h,
255, 255, 255, 255
);
boxRGBA(
surface,
rectScrollBarSlider.x, rectScrollBarSlider.y,
rectScrollBarSlider.x + rectScrollBarSlider.w,
rectScrollBarSlider.y + rectScrollBarSlider.h,
255, 255, 255, 255
);
}
void ScreenList::scroll(bool up, float valY) {
if (up == true) {
if (options.offsetY + valY <= 0)
options.offsetY += valY;
else
options.offsetY = 0;
} else {
if (options.offsetY - valY >= -1 * (options.lengthY - surface->h))
options.offsetY -= valY;
else
options.offsetY = -1 * (options.lengthY - surface->h);
}
}
bool ScreenList::sliderActive(Uint16 x, Uint16 y) {
if (x >= rectScrollBar.x && y >= rectScrollBar.y &&
x <= rectScrollBar.x + rectScrollBar.w &&
y <= rectScrollBar.y + rectScrollBar.h) {
return true;
}
return false;
}
void ScreenList::moveSlider(Uint16 screenY) {
float rangeStepSize = surface->h / (options.lengthY - surface->h);
options.offsetY = screenY / rangeStepSize * -1;
}
void ScreenList::setMode(Uint8 pMode) {
mode = pMode;
}
Uint8 ScreenList::getMode() {
return mode;
}
void ScreenList::setEntries(Lists *lists) {
if (mode == LIST_MODE_EDITOR_TERRAIN) {
options.length = lists->terrainLength;
} else if (mode == LIST_MODE_EDITOR_ITEMS) {
options.length = lists->itemsLength;
} else if (mode == LIST_MODE_GAME_BUILDINGS) {
options.length = lists->buildingsLength;
}
entries = new stScreenListEntry[options.length];
int i;
string imageFile;
for (i = 0; i < options.length; i++) {
entries[i].title.setFontSize(18);
entries[i].text.setFontSize(16);
if (mode == LIST_MODE_EDITOR_TERRAIN) {
entries[i].title.set(lists->terrain[i].title);
entries[i].text.set(lists->terrain[i].description);
imageFile = "images/terrain/" + lists->terrain[i].name + "_" +
to_string(imageSize) + ".png";
} else if (mode == LIST_MODE_EDITOR_ITEMS) {
entries[i].title.set(lists->items[i].title);
entries[i].text.set(lists->items[i].description);
imageFile = "images/items/" + lists->items[i].name + "_" +
to_string(imageSize) + ".png";
} else if (mode == LIST_MODE_GAME_BUILDINGS) {
entries[i].title.set(lists->buildings[i].title);
entries[i].text.set(lists->buildings[i].description);
imageFile = "images/buildings/" + lists->buildings[i].name + "_" +
to_string(imageSize) + ".png";
}
entries[i].image = loadImage(imageFile);
}
options.lengthY = options.length *
(entries[0].title.getHeight() + titleMarginBottom +
entries[0].text.getHeight() + textMarginBottom);
}
void ScreenList::show() {
Uint16 i;
int entryPosX, entryPosY;
entryPosX = options.offsetX;
entryPosY = options.offsetY;
SDL_Rect offset;
for (i = 0; i < options.length; i++) {
offset.x = entryPosX;
offset.y = entryPosY;
if (options.selectetIdx == i) {
boxRGBA(
surface,
offset.x, offset.y,
offset.x + surface->w - 22,
offset.y + entries[i].title.getHeight() + entries[i].text.getHeight(),
0, 120, 180, 255
);
}
if (entries[i].image != NULL) {
offset.y = entryPosY + imageMarginTop;
apply(offset.x, offset.y, entries[i].image);
offset.x += imageSize + imageMarginRight;
} else {
offset.x = entryPosX;
}
offset.y = entryPosY;
apply(offset.x, offset.y, entries[i].title.get());
entryPosY += entries[i].title.getHeight() + titleMarginBottom;
offset.y = entryPosY;
apply(offset.x, offset.y, entries[i].text.get());
entryPosY += entries[i].text.getHeight() + textMarginBottom;
offset.y = entryPosY;
}
}
void ScreenList::selectEntry(Uint16 screenY) {
Uint16 entryHeight = entries[0].title.getHeight() + titleMarginBottom +
entries[0].text.getHeight() + textMarginBottom;
options.selectetIdx = (-1 * options.offsetY + screenY) / entryHeight;
}
Uint16 ScreenList::getSelectedIdx() {
return options.selectetIdx;
}
void ScreenList::unset() {
int i;
for (i = 0; i < options.length; i++) {
entries[i].title.unset();
entries[i].text.unset();
free(entries[i].image);
}
delete[] entries;
}
<|endoftext|> |
<commit_before>//
// ex13_17.cpp
// Exercise 13.17
//
// Created by pezy on 1/15/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Write versions of numbered and f corresponding to the previous three
// exercises
// and check whether you correctly predicted the output.
//
// For 13.14
#include <iostream>
class numbered {
public:
numbered()
{
static int unique = 10;
mysn = unique++;
}
int mysn;
};
void f(numbered s)
{
std::cout << s.mysn << std::endl;
}
int main()
{
numbered a, b = a, c = b;
f(a);
f(b);
f(c);
}
// output
// 10
// 10
// 10
<commit_msg>Update ex13_17_1.cpp<commit_after>//
// ex13_17.cpp
// Exercise 13.17
//
// For 13.14
//
#include <iostream>
using namespace std;
class numbered {
public:
numbered()
{
static int unique=10;
mysn=unique++;
}
int mysn;
};
void f(numbered s)
{
cout<<s.mysn<<endl;
}
int main()
{
numbered a, b=a, c=b;
f(a); f(b); f(c);
}
// output
// 10
// 10
// 10
<|endoftext|> |
<commit_before>#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char ** argv)
{
std::ifstream input{argv[1]};
std::string line;
std::getline(input, line);
while(input)
{
std::for_each(std::begin(line), std::end(line), [](char c) {
std::cout << static_cast<char>(std::tolower(c));
});
std::cout << '\n';
std::getline(input, line);
}
return 0;
}
<commit_msg>Use transform instead of for_each<commit_after>#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char ** argv)
{
std::ifstream input{argv[1]};
std::string line;
std::getline(input, line);
while(input)
{
std::transform(std::begin(line), std::end(line), std::begin(line), [](char c) {
return static_cast<char>(std::tolower(c));
});
std::cout << line << '\n';
std::getline(input, line);
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* main.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <mparisdiaz@gmail.com>
* Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <signal.h>
#include <execinfo.h>
#include "MediaServerServiceHandler.hpp"
#include <protocol/TBinaryProtocol.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
#include <server/TNonblockingServer.h>
#include <concurrency/PosixThreadFactory.h>
#include <concurrency/ThreadManager.h>
#include "media_config.hpp"
#include <glibmm.h>
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <version.hpp>
#include "log.hpp"
#include "httpendpointserver.hpp"
#define GST_DEFAULT_NAME "media_server"
GST_DEBUG_CATEGORY (GST_CAT_DEFAULT);
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;
using namespace ::kurento;
using boost::shared_ptr;
using namespace boost::filesystem;
using ::kurento::MediaServerServiceHandler;
using ::Glib::KeyFile;
using ::Glib::KeyFileFlags;
static std::string serverAddress, httpEPServerAddress;
static gint serverServicePort, httpEPServerServicePort;
GstSDPMessage *sdpPattern;
KmsHttpEPServer *httpepserver;
Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (true);
static TNonblockingServer *p_server = NULL;
static gchar *conf_file;
static GOptionEntry entries[] = {
{
"conf-file", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, "Configuration file",
NULL
},
{NULL}
};
static void
create_media_server_service ()
{
shared_ptr < MediaServerServiceHandler >
handler (new MediaServerServiceHandler () );
shared_ptr < TProcessor >
processor (new MediaServerServiceProcessor (handler) );
shared_ptr < TProtocolFactory >
protocolFactory (new TBinaryProtocolFactory () );
shared_ptr < PosixThreadFactory > threadFactory (new PosixThreadFactory () );
shared_ptr < ThreadManager > threadManager =
ThreadManager::newSimpleThreadManager (15);
threadManager->threadFactory (threadFactory);
threadManager->start ();
TNonblockingServer server (processor, protocolFactory, serverServicePort, threadManager);
p_server = &server;
GST_INFO ("Starting MediaServerService");
kill (getppid(), SIGCONT);
server.serve ();
GST_INFO ("MediaServerService stopped finishing thread");
throw Glib::Thread::Exit ();
}
static void
check_port (int port)
{
if (port <= 0 || port > G_MAXUSHORT)
throw Glib::KeyFileError (Glib::KeyFileError::PARSE, "Invalid value");
}
static void
set_default_media_server_config ()
{
GST_WARNING ("Setting default configuration for media server. "
"Using IP address: %s, port: %d. "
"No codecs support will be available with default configuration.",
MEDIA_SERVER_ADDRESS, MEDIA_SERVER_SERVICE_PORT);
serverAddress = MEDIA_SERVER_ADDRESS;
serverServicePort = MEDIA_SERVER_SERVICE_PORT;
}
static void
set_default_http_ep_server_config ()
{
GST_WARNING ("Setting default configuration for http end point server. "
"Using IP address: %s, port: %d. ",
HTTP_EP_SERVER_ADDRESS, HTTP_EP_SERVER_SERVICE_PORT);
httpEPServerAddress = HTTP_EP_SERVER_ADDRESS;
httpEPServerServicePort = HTTP_EP_SERVER_SERVICE_PORT;
}
static void
set_default_config ()
{
set_default_media_server_config ();
set_default_http_ep_server_config();
}
static gchar *
read_entire_file (const gchar *file_name)
{
gchar *data;
long f_size;
FILE *fp;
fp = fopen (file_name, "r");
if (fp == NULL) {
return NULL;
}
fseek (fp, 0, SEEK_END);
f_size = ftell (fp);
fseek (fp, 0, SEEK_SET);
data = (gchar *) g_malloc0 (f_size);
fread (data, 1, f_size, fp);
fclose (fp);
return data;
}
static GstSDPMessage *
load_sdp_pattern (Glib::KeyFile &configFile, const std::string &confFileName)
{
GstSDPResult result;
GstSDPMessage *sdp_pattern = NULL;
gchar *sdp_pattern_text;
std::string sdp_pattern_file_name;
GST_DEBUG ("Load SDP Pattern");
result = gst_sdp_message_new (&sdp_pattern);
if (result != GST_SDP_OK) {
GST_ERROR ("Error creating sdp message");
return NULL;
}
sdp_pattern_file_name = configFile.get_string (SERVER_GROUP, SDP_PATTERN_KEY);
boost::filesystem::path p (confFileName.c_str () );
sdp_pattern_file_name.insert (0, "/");
sdp_pattern_file_name.insert (0, p.parent_path ().c_str() );
sdp_pattern_text = read_entire_file (sdp_pattern_file_name.c_str () );
if (sdp_pattern_text == NULL) {
GST_ERROR ("Error reading SDP pattern file");
gst_sdp_message_free (sdp_pattern);
return NULL;
}
result = gst_sdp_message_parse_buffer ( (const guint8 *) sdp_pattern_text, -1, sdp_pattern);
g_free (sdp_pattern_text);
if (result != GST_SDP_OK) {
GST_ERROR ("Error parsing SDP config pattern");
gst_sdp_message_free (sdp_pattern);
return NULL;
}
return sdp_pattern;
}
static void
configure_kurento_media_server (KeyFile &configFile, const std::string &file_name)
{
gint port;
gchar *sdpMessageText = NULL;
try {
serverAddress = configFile.get_string (SERVER_GROUP,
MEDIA_SERVER_ADDRESS_KEY);
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default address %s to media server",
MEDIA_SERVER_ADDRESS);
serverAddress = MEDIA_SERVER_ADDRESS;
}
try {
port = configFile.get_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY);
check_port (port);
serverServicePort = port;
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default port %d to media server",
MEDIA_SERVER_SERVICE_PORT);
serverServicePort = MEDIA_SERVER_SERVICE_PORT;
}
try {
sdpPattern = load_sdp_pattern (configFile, file_name);
GST_DEBUG ("SDP: \n%s", sdpMessageText = gst_sdp_message_as_text (sdpPattern) );
g_free (sdpMessageText);
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Wrong codec configuration, communication won't be possible");
}
}
static void
configure_http_ep_server (KeyFile &configFile)
{
gint port;
try {
httpEPServerAddress = configFile.get_string (HTTP_EP_SERVER_GROUP,
HTTP_EP_SERVER_ADDRESS_KEY);
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default address %s to http end point server",
HTTP_EP_SERVER_ADDRESS);
httpEPServerAddress = HTTP_EP_SERVER_ADDRESS;
}
try {
port = configFile.get_integer (HTTP_EP_SERVER_GROUP, HTTP_EP_SERVER_SERVICE_PORT_KEY);
check_port (port);
httpEPServerServicePort = port;
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default port %d to http end point server",
HTTP_EP_SERVER_SERVICE_PORT);
httpEPServerServicePort = HTTP_EP_SERVER_SERVICE_PORT;
}
}
static void
load_config (const std::string &file_name)
{
KeyFile configFile;
GST_INFO ("Reading configuration from: %s", file_name.c_str () );
/* Try to load configuration file */
try {
if (!configFile.load_from_file (file_name,
KeyFileFlags::KEY_FILE_KEEP_COMMENTS |
KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS) ) {
GST_WARNING ("Can not load configuration file %s", file_name.c_str () );
set_default_config ();
return;
}
} catch (Glib::Error ex) {
GST_ERROR ("Error loading configuration: %s", ex.what ().c_str () );
set_default_config ();
return;
}
/* parse options so as to configure servers */
configure_kurento_media_server (configFile, file_name);
configure_http_ep_server (configFile);
GST_INFO ("Configuration loaded successfully");
}
static void
initialiseExecutableName (char *exe, int size)
{
char link[1024];
int len;
snprintf (link, sizeof (link), "/proc/%d/exe", getpid () );
len = readlink (link, exe, size);
if (len == -1) {
fprintf (stderr, "ERROR GETTING NAME\n");
exit (1);
}
exe[len] = '\0';
}
static const char *
getExecutableName ()
{
static char *exe = NULL;
static char aux[1024];
if (exe == NULL) {
initialiseExecutableName (aux, sizeof (aux) );
exe = aux;
}
return exe;
}
static bool
quit_loop ()
{
loop->quit ();
return FALSE;
}
static void
bt_sighandler (int sig, siginfo_t *info, gpointer data)
{
void *trace[35];
char **messages = (char **) NULL;
int i, trace_size = 0;
// ucontext_t *uc = (ucontext_t *)data;
/* Do something useful with siginfo_t */
if (sig == SIGSEGV) {
printf ("Got signal %d, faulty address is %p\n", sig,
(gpointer) info->si_addr);
} else if (sig == SIGKILL || sig == SIGINT) {
/* since we connect to a signal handler, asynchronous management might */
/* might happen so we need to set an idle handler to exit the main loop */
/* in the mainloop context. */
Glib::RefPtr<Glib::IdleSource> idle_source = Glib::IdleSource::create ();
idle_source->connect (sigc::ptr_fun (&quit_loop) );
idle_source->attach (loop->get_context() );
return;
} else {
printf ("Got signal %d\n", sig);
}
trace_size = backtrace (trace, 35);
/* overwrite sigaction with caller's address */
//trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];
messages = backtrace_symbols (trace, trace_size);
/* skip first stack frame (points here) */
g_print ("\t[bt] Execution path:\n");
for (i = 1; i < trace_size; ++i) {
g_print ("\t[bt] #%d %s\n", i, messages[i]);
char syscom[256];
gchar **strs;
const gchar *exe;
strs = g_strsplit (messages[i], "(", 2);
if (strs[1] == NULL)
exe = getExecutableName ();
else
exe = strs[0];
sprintf (syscom, "echo -n \"\t[bt]\t\t\"; addr2line %p -s -e %s",
trace[i], exe);
g_strfreev (strs);
system (syscom);
}
if (sig == SIGPIPE) {
GST_DEBUG ("Ignore sigpipe");
} else {
exit (sig);
}
}
static void
http_server_start_cb (KmsHttpEPServer *self, GError *err)
{
if (err != NULL) {
GST_ERROR ("Http server could not start. Reason: %s", err->message);
loop->quit ();
return;
}
GST_DEBUG ("HttpEPServer started. Setting up thrift server service.");
/* Created thread not used for joining because of a bug in thrift */
sigc::slot < void >ss = sigc::ptr_fun (&create_media_server_service);
Glib::Thread::create (ss, true);
}
int
main (int argc, char **argv)
{
GError *error = NULL;
GOptionContext *context;
struct sigaction sa;
context = g_option_context_new ("");
g_option_context_add_main_entries (context, entries, NULL);
g_option_context_add_group (context, gst_init_get_option_group () );
if (!g_option_context_parse (context, &argc, &argv, &error) ) {
GST_ERROR ("option parsing failed: %s\n", error->message);
exit (1);
}
g_option_context_free (context);
gst_init (&argc, &argv);
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
/* Install our signal handler */
sa.sa_sigaction = /*(void (*)(int, siginfo*, gpointer)) */ bt_sighandler;
sigemptyset (&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_SIGINFO;
sigaction (SIGSEGV, &sa, NULL);
sigaction (SIGPIPE, &sa, NULL);
sigaction (SIGINT, &sa, NULL);
sigaction (SIGKILL, &sa, NULL);
Glib::thread_init ();
GST_INFO ("Kmsc version: %s", get_version () );
if (!conf_file)
load_config (DEFAULT_CONFIG_FILE);
else
load_config ( (std::string) conf_file);
/* Start Http End Point Server */
GST_DEBUG ("Starting Http ens point server.");
httpepserver = kms_http_ep_server_new (
KMS_HTTP_EP_SERVER_PORT, httpEPServerServicePort,
KMS_HTTP_EP_SERVER_INTERFACE, httpEPServerAddress.c_str(), NULL);
kms_http_ep_server_start (httpepserver, http_server_start_cb);
loop->run ();
/* Stop Http End Point Server and destroy it */
kms_http_ep_server_stop (httpepserver);
g_object_unref (G_OBJECT (httpepserver) );
return 0;
}
<commit_msg>Fig typo in debug message<commit_after>/*
* main.cpp - Kurento Media Server
*
* Copyright (C) 2013 Kurento
* Contact: Miguel París Díaz <mparisdiaz@gmail.com>
* Contact: José Antonio Santos Cadenas <santoscadenas@kurento.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <signal.h>
#include <execinfo.h>
#include "MediaServerServiceHandler.hpp"
#include <protocol/TBinaryProtocol.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
#include <server/TNonblockingServer.h>
#include <concurrency/PosixThreadFactory.h>
#include <concurrency/ThreadManager.h>
#include "media_config.hpp"
#include <glibmm.h>
#include <fstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <version.hpp>
#include "log.hpp"
#include "httpendpointserver.hpp"
#define GST_DEFAULT_NAME "media_server"
GST_DEBUG_CATEGORY (GST_CAT_DEFAULT);
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;
using namespace ::kurento;
using boost::shared_ptr;
using namespace boost::filesystem;
using ::kurento::MediaServerServiceHandler;
using ::Glib::KeyFile;
using ::Glib::KeyFileFlags;
static std::string serverAddress, httpEPServerAddress;
static gint serverServicePort, httpEPServerServicePort;
GstSDPMessage *sdpPattern;
KmsHttpEPServer *httpepserver;
Glib::RefPtr<Glib::MainLoop> loop = Glib::MainLoop::create (true);
static TNonblockingServer *p_server = NULL;
static gchar *conf_file;
static GOptionEntry entries[] = {
{
"conf-file", 'f', 0, G_OPTION_ARG_FILENAME, &conf_file, "Configuration file",
NULL
},
{NULL}
};
static void
create_media_server_service ()
{
shared_ptr < MediaServerServiceHandler >
handler (new MediaServerServiceHandler () );
shared_ptr < TProcessor >
processor (new MediaServerServiceProcessor (handler) );
shared_ptr < TProtocolFactory >
protocolFactory (new TBinaryProtocolFactory () );
shared_ptr < PosixThreadFactory > threadFactory (new PosixThreadFactory () );
shared_ptr < ThreadManager > threadManager =
ThreadManager::newSimpleThreadManager (15);
threadManager->threadFactory (threadFactory);
threadManager->start ();
TNonblockingServer server (processor, protocolFactory, serverServicePort, threadManager);
p_server = &server;
GST_INFO ("Starting MediaServerService");
kill (getppid(), SIGCONT);
server.serve ();
GST_INFO ("MediaServerService stopped finishing thread");
throw Glib::Thread::Exit ();
}
static void
check_port (int port)
{
if (port <= 0 || port > G_MAXUSHORT)
throw Glib::KeyFileError (Glib::KeyFileError::PARSE, "Invalid value");
}
static void
set_default_media_server_config ()
{
GST_WARNING ("Setting default configuration for media server. "
"Using IP address: %s, port: %d. "
"No codecs support will be available with default configuration.",
MEDIA_SERVER_ADDRESS, MEDIA_SERVER_SERVICE_PORT);
serverAddress = MEDIA_SERVER_ADDRESS;
serverServicePort = MEDIA_SERVER_SERVICE_PORT;
}
static void
set_default_http_ep_server_config ()
{
GST_WARNING ("Setting default configuration for http end point server. "
"Using IP address: %s, port: %d. ",
HTTP_EP_SERVER_ADDRESS, HTTP_EP_SERVER_SERVICE_PORT);
httpEPServerAddress = HTTP_EP_SERVER_ADDRESS;
httpEPServerServicePort = HTTP_EP_SERVER_SERVICE_PORT;
}
static void
set_default_config ()
{
set_default_media_server_config ();
set_default_http_ep_server_config();
}
static gchar *
read_entire_file (const gchar *file_name)
{
gchar *data;
long f_size;
FILE *fp;
fp = fopen (file_name, "r");
if (fp == NULL) {
return NULL;
}
fseek (fp, 0, SEEK_END);
f_size = ftell (fp);
fseek (fp, 0, SEEK_SET);
data = (gchar *) g_malloc0 (f_size);
fread (data, 1, f_size, fp);
fclose (fp);
return data;
}
static GstSDPMessage *
load_sdp_pattern (Glib::KeyFile &configFile, const std::string &confFileName)
{
GstSDPResult result;
GstSDPMessage *sdp_pattern = NULL;
gchar *sdp_pattern_text;
std::string sdp_pattern_file_name;
GST_DEBUG ("Load SDP Pattern");
result = gst_sdp_message_new (&sdp_pattern);
if (result != GST_SDP_OK) {
GST_ERROR ("Error creating sdp message");
return NULL;
}
sdp_pattern_file_name = configFile.get_string (SERVER_GROUP, SDP_PATTERN_KEY);
boost::filesystem::path p (confFileName.c_str () );
sdp_pattern_file_name.insert (0, "/");
sdp_pattern_file_name.insert (0, p.parent_path ().c_str() );
sdp_pattern_text = read_entire_file (sdp_pattern_file_name.c_str () );
if (sdp_pattern_text == NULL) {
GST_ERROR ("Error reading SDP pattern file");
gst_sdp_message_free (sdp_pattern);
return NULL;
}
result = gst_sdp_message_parse_buffer ( (const guint8 *) sdp_pattern_text, -1, sdp_pattern);
g_free (sdp_pattern_text);
if (result != GST_SDP_OK) {
GST_ERROR ("Error parsing SDP config pattern");
gst_sdp_message_free (sdp_pattern);
return NULL;
}
return sdp_pattern;
}
static void
configure_kurento_media_server (KeyFile &configFile, const std::string &file_name)
{
gint port;
gchar *sdpMessageText = NULL;
try {
serverAddress = configFile.get_string (SERVER_GROUP,
MEDIA_SERVER_ADDRESS_KEY);
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default address %s to media server",
MEDIA_SERVER_ADDRESS);
serverAddress = MEDIA_SERVER_ADDRESS;
}
try {
port = configFile.get_integer (SERVER_GROUP, MEDIA_SERVER_SERVICE_PORT_KEY);
check_port (port);
serverServicePort = port;
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default port %d to media server",
MEDIA_SERVER_SERVICE_PORT);
serverServicePort = MEDIA_SERVER_SERVICE_PORT;
}
try {
sdpPattern = load_sdp_pattern (configFile, file_name);
GST_DEBUG ("SDP: \n%s", sdpMessageText = gst_sdp_message_as_text (sdpPattern) );
g_free (sdpMessageText);
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Wrong codec configuration, communication won't be possible");
}
}
static void
configure_http_ep_server (KeyFile &configFile)
{
gint port;
try {
httpEPServerAddress = configFile.get_string (HTTP_EP_SERVER_GROUP,
HTTP_EP_SERVER_ADDRESS_KEY);
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default address %s to http end point server",
HTTP_EP_SERVER_ADDRESS);
httpEPServerAddress = HTTP_EP_SERVER_ADDRESS;
}
try {
port = configFile.get_integer (HTTP_EP_SERVER_GROUP, HTTP_EP_SERVER_SERVICE_PORT_KEY);
check_port (port);
httpEPServerServicePort = port;
} catch (Glib::KeyFileError err) {
GST_ERROR ("%s", err.what ().c_str () );
GST_WARNING ("Setting default port %d to http end point server",
HTTP_EP_SERVER_SERVICE_PORT);
httpEPServerServicePort = HTTP_EP_SERVER_SERVICE_PORT;
}
}
static void
load_config (const std::string &file_name)
{
KeyFile configFile;
GST_INFO ("Reading configuration from: %s", file_name.c_str () );
/* Try to load configuration file */
try {
if (!configFile.load_from_file (file_name,
KeyFileFlags::KEY_FILE_KEEP_COMMENTS |
KeyFileFlags::KEY_FILE_KEEP_TRANSLATIONS) ) {
GST_WARNING ("Can not load configuration file %s", file_name.c_str () );
set_default_config ();
return;
}
} catch (Glib::Error ex) {
GST_ERROR ("Error loading configuration: %s", ex.what ().c_str () );
set_default_config ();
return;
}
/* parse options so as to configure servers */
configure_kurento_media_server (configFile, file_name);
configure_http_ep_server (configFile);
GST_INFO ("Configuration loaded successfully");
}
static void
initialiseExecutableName (char *exe, int size)
{
char link[1024];
int len;
snprintf (link, sizeof (link), "/proc/%d/exe", getpid () );
len = readlink (link, exe, size);
if (len == -1) {
fprintf (stderr, "ERROR GETTING NAME\n");
exit (1);
}
exe[len] = '\0';
}
static const char *
getExecutableName ()
{
static char *exe = NULL;
static char aux[1024];
if (exe == NULL) {
initialiseExecutableName (aux, sizeof (aux) );
exe = aux;
}
return exe;
}
static bool
quit_loop ()
{
loop->quit ();
return FALSE;
}
static void
bt_sighandler (int sig, siginfo_t *info, gpointer data)
{
void *trace[35];
char **messages = (char **) NULL;
int i, trace_size = 0;
// ucontext_t *uc = (ucontext_t *)data;
/* Do something useful with siginfo_t */
if (sig == SIGSEGV) {
printf ("Got signal %d, faulty address is %p\n", sig,
(gpointer) info->si_addr);
} else if (sig == SIGKILL || sig == SIGINT) {
/* since we connect to a signal handler, asynchronous management might */
/* might happen so we need to set an idle handler to exit the main loop */
/* in the mainloop context. */
Glib::RefPtr<Glib::IdleSource> idle_source = Glib::IdleSource::create ();
idle_source->connect (sigc::ptr_fun (&quit_loop) );
idle_source->attach (loop->get_context() );
return;
} else {
printf ("Got signal %d\n", sig);
}
trace_size = backtrace (trace, 35);
/* overwrite sigaction with caller's address */
//trace[1] = (void *) uc->uc_mcontext.gregs[REG_EIP];
messages = backtrace_symbols (trace, trace_size);
/* skip first stack frame (points here) */
g_print ("\t[bt] Execution path:\n");
for (i = 1; i < trace_size; ++i) {
g_print ("\t[bt] #%d %s\n", i, messages[i]);
char syscom[256];
gchar **strs;
const gchar *exe;
strs = g_strsplit (messages[i], "(", 2);
if (strs[1] == NULL)
exe = getExecutableName ();
else
exe = strs[0];
sprintf (syscom, "echo -n \"\t[bt]\t\t\"; addr2line %p -s -e %s",
trace[i], exe);
g_strfreev (strs);
system (syscom);
}
if (sig == SIGPIPE) {
GST_DEBUG ("Ignore sigpipe");
} else {
exit (sig);
}
}
static void
http_server_start_cb (KmsHttpEPServer *self, GError *err)
{
if (err != NULL) {
GST_ERROR ("Http server could not start. Reason: %s", err->message);
loop->quit ();
return;
}
GST_DEBUG ("HttpEPServer started. Setting up thrift server service.");
/* Created thread not used for joining because of a bug in thrift */
sigc::slot < void >ss = sigc::ptr_fun (&create_media_server_service);
Glib::Thread::create (ss, true);
}
int
main (int argc, char **argv)
{
GError *error = NULL;
GOptionContext *context;
struct sigaction sa;
context = g_option_context_new ("");
g_option_context_add_main_entries (context, entries, NULL);
g_option_context_add_group (context, gst_init_get_option_group () );
if (!g_option_context_parse (context, &argc, &argv, &error) ) {
GST_ERROR ("option parsing failed: %s\n", error->message);
exit (1);
}
g_option_context_free (context);
gst_init (&argc, &argv);
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
/* Install our signal handler */
sa.sa_sigaction = /*(void (*)(int, siginfo*, gpointer)) */ bt_sighandler;
sigemptyset (&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_SIGINFO;
sigaction (SIGSEGV, &sa, NULL);
sigaction (SIGPIPE, &sa, NULL);
sigaction (SIGINT, &sa, NULL);
sigaction (SIGKILL, &sa, NULL);
Glib::thread_init ();
GST_INFO ("Kmsc version: %s", get_version () );
if (!conf_file)
load_config (DEFAULT_CONFIG_FILE);
else
load_config ( (std::string) conf_file);
/* Start Http End Point Server */
GST_DEBUG ("Starting Http end point server.");
httpepserver = kms_http_ep_server_new (
KMS_HTTP_EP_SERVER_PORT, httpEPServerServicePort,
KMS_HTTP_EP_SERVER_INTERFACE, httpEPServerAddress.c_str(), NULL);
kms_http_ep_server_start (httpepserver, http_server_start_cb);
loop->run ();
/* Stop Http End Point Server and destroy it */
kms_http_ep_server_stop (httpepserver);
g_object_unref (G_OBJECT (httpepserver) );
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "numpy.hpp"
#include <cstring>
Eigen::MatrixXf loadFloatFromNumpy(const std::string& filename)
{
std::vector<int> shape;
std::vector<float> data;
aoba::LoadArrayFromNumpy(filename, shape, data);
Eigen::MatrixXf mat(shape[1], shape[0]);
std::size_t size = sizeof(float) * shape[0] * shape[1];
memcpy(mat.data(), data.data(), size);
mat.transposeInPlace();
return mat;
}
Eigen::MatrixXb loadBoolFromNumpy(const std::string& filename)
{
std::vector<int> shape;
std::vector<char> data;
aoba::LoadArrayFromNumpy<char>(filename, shape, data);
Eigen::MatrixXb mat(shape[1], shape[0]);
std::size_t size = sizeof(char) * shape[0] * shape[1];
memcpy(mat.data(), data.data(), size);
mat.transposeInPlace();
return mat;
}
void loadMaps(const json& settings, MapData& mapData)
{
for (std::string mapName : settings["maps"])
{
std::string path = settings["mapPath"];
std::string prefix = path + "/" + mapName;
Map m;
m.start = loadBoolFromNumpy(prefix + "_start.npy");
m.finish = loadBoolFromNumpy(prefix + "_end.npy");
m.occupancy = loadBoolFromNumpy(prefix + "_occupancy.npy");
std::cout << m.occupancy << std::endl;
m.flowx = loadFloatFromNumpy(prefix + "_flowx.npy");
m.flowy = loadFloatFromNumpy(prefix + "_flowy.npy");
m.endDistance = loadFloatFromNumpy(prefix + "_enddist.npy");
m.wallDistance = loadFloatFromNumpy(prefix + "_walldist.npy");
m.wallNormalx = loadFloatFromNumpy(prefix + "_wnormx.npy");
m.wallNormaly = loadFloatFromNumpy(prefix + "_wnormy.npy");
//TODO build json structure
mapData.maps.push_back(std::move(m));
}
}
<commit_msg>remove print map<commit_after>#pragma once
#include "numpy.hpp"
#include <cstring>
Eigen::MatrixXf loadFloatFromNumpy(const std::string& filename)
{
std::vector<int> shape;
std::vector<float> data;
aoba::LoadArrayFromNumpy(filename, shape, data);
Eigen::MatrixXf mat(shape[1], shape[0]);
std::size_t size = sizeof(float) * shape[0] * shape[1];
memcpy(mat.data(), data.data(), size);
mat.transposeInPlace();
return mat;
}
Eigen::MatrixXb loadBoolFromNumpy(const std::string& filename)
{
std::vector<int> shape;
std::vector<char> data;
aoba::LoadArrayFromNumpy<char>(filename, shape, data);
Eigen::MatrixXb mat(shape[1], shape[0]);
std::size_t size = sizeof(char) * shape[0] * shape[1];
memcpy(mat.data(), data.data(), size);
mat.transposeInPlace();
return mat;
}
void loadMaps(const json& settings, MapData& mapData)
{
for (std::string mapName : settings["maps"])
{
std::string path = settings["mapPath"];
std::string prefix = path + "/" + mapName;
Map m;
m.start = loadBoolFromNumpy(prefix + "_start.npy");
m.finish = loadBoolFromNumpy(prefix + "_end.npy");
m.occupancy = loadBoolFromNumpy(prefix + "_occupancy.npy");
m.flowx = loadFloatFromNumpy(prefix + "_flowx.npy");
m.flowy = loadFloatFromNumpy(prefix + "_flowy.npy");
m.endDistance = loadFloatFromNumpy(prefix + "_enddist.npy");
m.wallDistance = loadFloatFromNumpy(prefix + "_walldist.npy");
m.wallNormalx = loadFloatFromNumpy(prefix + "_wnormx.npy");
m.wallNormaly = loadFloatFromNumpy(prefix + "_wnormy.npy");
//TODO build json structure
mapData.maps.push_back(std::move(m));
}
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "CoreJobTest.h"
#include "CoreJob.h"
#include "move_only.h"
#include <boost/thread.hpp>
TEST_F(CoreJobTest, VerifySimpleProperties) {
AutoRequired<CoreJob> jb;
ASSERT_FALSE(m_create->IsInitiated()) << "CoreJob reported it could receive events before its enclosing context was created";
// Create a thread which will delay for acceptance, and then quit:
boost::thread t([this] {
m_create->DelayUntilInitiated();
});
// Verify that this thread doesn't back out right away:
ASSERT_FALSE(t.try_join_for(boost::chrono::milliseconds(10))) << "CoreJob did not block a client who was waiting for its readiness to accept dispatchers";
// Now start the context and verify that certain properties changed as anticipated:
m_create->Initiate();
ASSERT_TRUE(m_create->DelayUntilInitiated()) << "CoreJob did not correctly delay for dispatch acceptance";
// Verify that the blocked thread has become unblocked and quits properly:
ASSERT_TRUE(t.try_join_for(boost::chrono::seconds(1))) << "CoreJob did not correctly signal a blocked thread that it was ready to accept dispatchers";
}
TEST_F(CoreJobTest, VerifySimpleSubmission) {
AutoRequired<CoreJob> jb;
auto myFlag = std::make_shared<bool>(false);
*jb += [myFlag] {
*myFlag = true;
};
// Kickoff, signal for a shutdown to take place, and then verify the flag
AutoCurrentContext ctxt;
ctxt->Initiate();
ctxt->SignalShutdown(true);
ASSERT_TRUE(*myFlag) << "CoreJob did not properly execute its thread";
}
TEST_F(CoreJobTest, VerifyTeardown) {
AutoRequired<CoreJob> job;
AutoCurrentContext ctxt;
bool check1 = false;
bool check2 = false;
bool check3 = false;
*job += [&check1] {
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
check1 = true;
};
*job += [&check2] {
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
check2 = true;
};
ctxt->Initiate();
*job += [&check3] {
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
check3 = true;
};
ctxt->SignalShutdown(true);
EXPECT_TRUE(check1) << "Lambda 1 didn't finish";
EXPECT_TRUE(check2) << "Lambda 2 didn't finish";
EXPECT_TRUE(check3) << "Lambda 3 didn't finish";
}
struct SimpleListen:
virtual EventReceiver
{
SimpleListen():
m_flag(false)
{}
void SetFlag(){m_flag=true;}
bool m_flag;
};
TEST_F(CoreJobTest, VerifyNoEventReceivers){
AutoCreateContext ctxt1;
CurrentContextPusher pshr1(ctxt1);
AutoFired<SimpleListen> fire;
ctxt1->Initiate();
AutoCreateContext ctxt2;
CurrentContextPusher pshr2(ctxt2);
AutoRequired<SimpleListen> listener;
ASSERT_FALSE(listener->m_flag) << "Flag was initialized improperly";
fire(&SimpleListen::SetFlag)();
EXPECT_FALSE(listener->m_flag) << "Lister recived event event though it wasn't initiated";
}
class CanOnlyMove {
public:
CanOnlyMove(){}
~CanOnlyMove(){}
CanOnlyMove(const CanOnlyMove& derp) = delete;
CanOnlyMove(CanOnlyMove&& derp){}
};
TEST_F(CoreJobTest, MoveOnly){
CanOnlyMove move;
//CanOnlyMove derp = move; //error
MoveOnly<CanOnlyMove> mo(std::move(move));
MoveOnly<CanOnlyMove> first = mo;
//MoveOnly<CanOnlyMove> second = mo; //error
}
TEST_F(CoreJobTest, AbandonedDispatchers) {
auto v = std::make_shared<bool>(false);
AutoRequired<CoreJob> cj;
*cj += [v] { *v = true; };
// Graceful shutdown on our enclosing context without starting it:
AutoCurrentContext()->SignalShutdown(true);
// Verify that all lambdas on the CoreThread got called as expected:
ASSERT_FALSE(*v) << "Lambdas attached to a CoreJob should not be executed when the enclosing context is terminated without being started";
}
TEST_F(CoreJobTest, RecursiveAdd) {
bool first = false;
bool second = false;
bool third = false;
AutoRequired<CoreJob> cj;
AutoCurrentContext()->Initiate();
*cj += [&first,&second,&third, &cj] {
first = true;
*cj += [&first,&second,&third,&cj] {
second = true;
*cj += [&first,&second,&third,&cj] {
third = true;
};
cj->Stop(true);
};
};
cj->Wait();
// Verify that all lambdas on the CoreThread got called as expected:
EXPECT_TRUE(first) << "Appended lambda didn't set value";
EXPECT_TRUE(second) << "Appended lambda didn't set value";
EXPECT_TRUE(third) << "Appended lambda didn't set value";
}
TEST_F(CoreJobTest, RaceCondition) {
for (int i=0; i<5; i++) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<CoreJob> cj;
ctxt->Initiate();
bool first = false;
bool second = false;
*cj += [&first] {
first = true;
};
boost::this_thread::sleep(boost::posix_time::milliseconds(i));
*cj += [&second, &cj] {
second = true;
};
ctxt->SignalShutdown(true);
ASSERT_TRUE(first) << "Failed after set value in lambda";
ASSERT_TRUE(second) << "Failed to set value when delayed " << i << " milliseconds";
}
}
TEST_F(CoreJobTest, CorrectlyAssignedCurrentContext) {
AutoCurrentContext()->Initiate();
AutoRequired<CoreJob> job;
std::shared_ptr<CoreContext> ctxt;
*job += [&ctxt] { ctxt = AutoCurrentContext(); };
*job += [job] { job->Stop(true); };
ASSERT_TRUE(job->WaitFor(boost::chrono::seconds(5)));
// Now verify that the job was run in the right thread context:
ASSERT_EQ(AutoCurrentContext(), ctxt) << "Job lambda was not run with the correct CoreContext current";
}<commit_msg>Adding a dacl to the server-side named pipe<commit_after>#include "stdafx.h"
#include "CoreJobTest.h"
#include "CoreJob.h"
#include "move_only.h"
#include <boost/thread.hpp>
TEST_F(CoreJobTest, VerifySimpleProperties) {
AutoRequired<CoreJob> jb;
ASSERT_FALSE(m_create->IsInitiated()) << "CoreJob reported it could receive events before its enclosing context was created";
// Create a thread which will delay for acceptance, and then quit:
boost::thread t([this] {
m_create->DelayUntilInitiated();
});
// Verify that this thread doesn't back out right away:
ASSERT_FALSE(t.try_join_for(boost::chrono::milliseconds(10))) << "CoreJob did not block a client who was waiting for its readiness to accept dispatchers";
// Now start the context and verify that certain properties changed as anticipated:
m_create->Initiate();
ASSERT_TRUE(m_create->DelayUntilInitiated()) << "CoreJob did not correctly delay for dispatch acceptance";
// Verify that the blocked thread has become unblocked and quits properly:
ASSERT_TRUE(t.try_join_for(boost::chrono::seconds(1))) << "CoreJob did not correctly signal a blocked thread that it was ready to accept dispatchers";
}
TEST_F(CoreJobTest, VerifySimpleSubmission) {
AutoRequired<CoreJob> jb;
auto myFlag = std::make_shared<bool>(false);
*jb += [myFlag] {
*myFlag = true;
};
// Kickoff, signal for a shutdown to take place, and then verify the flag
AutoCurrentContext ctxt;
ctxt->Initiate();
ctxt->SignalShutdown(true);
ASSERT_TRUE(*myFlag) << "CoreJob did not properly execute its thread";
}
TEST_F(CoreJobTest, VerifyTeardown) {
AutoRequired<CoreJob> job;
AutoCurrentContext ctxt;
bool check1 = false;
bool check2 = false;
bool check3 = false;
*job += [&check1] {
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
check1 = true;
};
*job += [&check2] {
boost::this_thread::sleep(boost::posix_time::milliseconds(200));
check2 = true;
};
ctxt->Initiate();
*job += [&check3] {
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
check3 = true;
};
ctxt->SignalShutdown(true);
EXPECT_TRUE(check1) << "Lambda 1 didn't finish";
EXPECT_TRUE(check2) << "Lambda 2 didn't finish";
EXPECT_TRUE(check3) << "Lambda 3 didn't finish";
}
struct SimpleListen:
virtual EventReceiver
{
SimpleListen():
m_flag(false)
{}
void SetFlag(){m_flag=true;}
bool m_flag;
};
TEST_F(CoreJobTest, VerifyNoEventReceivers){
AutoCreateContext ctxt1;
CurrentContextPusher pshr1(ctxt1);
AutoFired<SimpleListen> fire;
ctxt1->Initiate();
AutoCreateContext ctxt2;
CurrentContextPusher pshr2(ctxt2);
AutoRequired<SimpleListen> listener;
ASSERT_FALSE(listener->m_flag) << "Flag was initialized improperly";
fire(&SimpleListen::SetFlag)();
EXPECT_FALSE(listener->m_flag) << "Lister recived event event though it wasn't initiated";
}
class CanOnlyMove {
public:
CanOnlyMove(){}
~CanOnlyMove(){}
CanOnlyMove(const CanOnlyMove& derp) = delete;
CanOnlyMove(CanOnlyMove&& derp){}
};
TEST_F(CoreJobTest, MoveOnly){
CanOnlyMove move;
//CanOnlyMove derp = move; //error
MoveOnly<CanOnlyMove> mo(std::move(move));
MoveOnly<CanOnlyMove> first = mo;
//MoveOnly<CanOnlyMove> second = mo; //error
}
TEST_F(CoreJobTest, AbandonedDispatchers) {
auto v = std::make_shared<bool>(false);
AutoRequired<CoreJob> cj;
*cj += [v] { *v = true; };
// Graceful shutdown on our enclosing context without starting it:
AutoCurrentContext()->SignalShutdown(true);
// Verify that all lambdas on the CoreThread got called as expected:
ASSERT_FALSE(*v) << "Lambdas attached to a CoreJob should not be executed when the enclosing context is terminated without being started";
}
TEST_F(CoreJobTest, RecursiveAdd) {
bool first = false;
bool second = false;
bool third = false;
AutoRequired<CoreJob> cj;
AutoCurrentContext()->Initiate();
*cj += [&first,&second,&third, &cj] {
first = true;
*cj += [&first,&second,&third,&cj] {
second = true;
*cj += [&first,&second,&third,&cj] {
third = true;
};
cj->Stop(true);
};
};
cj->Wait();
// Verify that all lambdas on the CoreThread got called as expected:
EXPECT_TRUE(first) << "Appended lambda didn't set value";
EXPECT_TRUE(second) << "Appended lambda didn't set value";
EXPECT_TRUE(third) << "Appended lambda didn't set value";
}
TEST_F(CoreJobTest, RaceCondition) {
for (int i=0; i<5; i++) {
AutoCreateContext ctxt;
CurrentContextPusher pshr(ctxt);
AutoRequired<CoreJob> cj;
ctxt->Initiate();
bool first = false;
bool second = false;
*cj += [&first] {
first = true;
};
boost::this_thread::sleep(boost::posix_time::milliseconds(i));
*cj += [&second, &cj] {
second = true;
};
ctxt->SignalShutdown(true);
ASSERT_TRUE(first) << "Failed after set value in lambda";
ASSERT_TRUE(second) << "Failed to set value when delayed " << i << " milliseconds";
}
}
TEST_F(CoreJobTest, CorrectlyAssignedCurrentContext) {
AutoCurrentContext()->Initiate();
AutoRequired<CoreJob> job;
std::shared_ptr<CoreContext> ctxt;
*job += [&ctxt] { ctxt = AutoCurrentContext(); };
*job += [job] { job->Stop(true); };
ASSERT_TRUE(job->WaitFor(boost::chrono::seconds(5)));
// Now verify that the job was run in the right thread context:
ASSERT_EQ(AutoCurrentContext(), ctxt) << "Job lambda was not run with the correct CoreContext current";
}
TEST_F(CoreJobTest, RecursiveDeadlock) {
// Create a CoreJob which will wait for a bit. Then, delegate its deletion responsibility to the thread
// itself, a
AutoCreateContext ctxt;
AutoRequired<CoreJob> cj(ctxt);
*cj += [] {
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
};
}<|endoftext|> |
<commit_before>/*
Auto away-presence setter-class
Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "autoaway.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountSet>
#include <KDebug>
#include <KIdleTime>
#include <KConfig>
#include <KConfigGroup>
#include <KTp/global-presence.h>
AutoAway::AutoAway(KTp::GlobalPresence* globalPresence, QObject* parent)
: TelepathyKDEDModulePlugin(globalPresence, parent),
m_awayTimeoutId(-1),
m_extAwayTimeoutId(-1)
{
readConfig();
connect(KIdleTime::instance(), SIGNAL(timeoutReached(int)),
this, SLOT(timeoutReached(int)));
connect(KIdleTime::instance(), SIGNAL(resumingFromIdle()),
this, SLOT(backFromIdle()));
}
AutoAway::~AutoAway()
{
}
QString AutoAway::pluginName() const
{
return QString::fromLatin1("auto-away");
}
void AutoAway::timeoutReached(int id)
{
if (!isEnabled()) {
return;
}
KIdleTime::instance()->catchNextResumeEvent();
if (id == m_awayTimeoutId) {
if (m_globalPresence->currentPresence().type() != Tp::Presence::away().type() &&
m_globalPresence->currentPresence().type() != Tp::Presence::xa().type() &&
m_globalPresence->currentPresence().type() != Tp::Presence::hidden().type()) {
m_awayMessage.replace(QLatin1String("%time"), QDateTime::currentDateTimeUtc().toString(QLatin1String("hh:mm:ss (%t)")), Qt::CaseInsensitive);
setRequestedPresence(Tp::Presence::away(m_awayMessage));
setActive(true);
}
} else if (id == m_extAwayTimeoutId) {
if (m_globalPresence->currentPresence().type() == Tp::Presence::away().type()) {
m_xaMessage.replace(QLatin1String("%time"), QDateTime::currentDateTimeUtc().toString(QLatin1String("hh:mm:ss (%t)")), Qt::CaseInsensitive);
setRequestedPresence(Tp::Presence::xa(m_xaMessage));
setActive(true);
}
}
}
void AutoAway::backFromIdle()
{
kDebug();
setActive(false);
}
void AutoAway::readConfig()
{
KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String("ktelepathyrc"));
config.data()->reparseConfiguration();
KConfigGroup kdedConfig = config->group("KDED");
bool autoAwayEnabled = kdedConfig.readEntry("autoAwayEnabled", true);
bool autoXAEnabled = kdedConfig.readEntry("autoXAEnabled", true);
m_awayMessage = kdedConfig.readEntry(QLatin1String("awayMessage"), QString());
m_xaMessage = kdedConfig.readEntry(QLatin1String("xaMessage"), QString());
//remove all our timeouts and only readd them if auto-away is enabled
//WARNING: can't use removeAllTimeouts because this runs inside KDED, it would remove other KDED timeouts as well
KIdleTime::instance()->removeIdleTimeout(m_awayTimeoutId);
KIdleTime::instance()->removeIdleTimeout(m_extAwayTimeoutId);
if (autoAwayEnabled) {
int awayTime = kdedConfig.readEntry("awayAfter", 5);
m_awayTimeoutId = KIdleTime::instance()->addIdleTimeout(awayTime * 60 * 1000);
setEnabled(true);
} else {
setEnabled(false);
}
if (autoAwayEnabled && autoXAEnabled) {
int xaTime = kdedConfig.readEntry("xaAfter", 15);
m_extAwayTimeoutId = KIdleTime::instance()->addIdleTimeout(xaTime * 60 * 1000);
}
}
void AutoAway::onSettingsChanged()
{
readConfig();
}
<commit_msg>Do not go auto away if offline<commit_after>/*
Auto away-presence setter-class
Copyright (C) 2011 Martin Klapetek <martin.klapetek@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "autoaway.h"
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountSet>
#include <KDebug>
#include <KIdleTime>
#include <KConfig>
#include <KConfigGroup>
#include <KTp/global-presence.h>
AutoAway::AutoAway(KTp::GlobalPresence* globalPresence, QObject* parent)
: TelepathyKDEDModulePlugin(globalPresence, parent),
m_awayTimeoutId(-1),
m_extAwayTimeoutId(-1)
{
readConfig();
connect(KIdleTime::instance(), SIGNAL(timeoutReached(int)),
this, SLOT(timeoutReached(int)));
connect(KIdleTime::instance(), SIGNAL(resumingFromIdle()),
this, SLOT(backFromIdle()));
}
AutoAway::~AutoAway()
{
}
QString AutoAway::pluginName() const
{
return QString::fromLatin1("auto-away");
}
void AutoAway::timeoutReached(int id)
{
if (!isEnabled()) {
return;
}
KIdleTime::instance()->catchNextResumeEvent();
if (id == m_awayTimeoutId) {
if (m_globalPresence->currentPresence().type() != Tp::Presence::away().type() &&
m_globalPresence->currentPresence().type() != Tp::Presence::xa().type() &&
m_globalPresence->currentPresence().type() != Tp::Presence::hidden().type() &&
m_globalPresence->currentPresence().type() != Tp::Presence::offline().type()) {
m_awayMessage.replace(QLatin1String("%time"), QDateTime::currentDateTimeUtc().toString(QLatin1String("hh:mm:ss (%t)")), Qt::CaseInsensitive);
setRequestedPresence(Tp::Presence::away(m_awayMessage));
setActive(true);
}
} else if (id == m_extAwayTimeoutId) {
if (m_globalPresence->currentPresence().type() == Tp::Presence::away().type()) {
m_xaMessage.replace(QLatin1String("%time"), QDateTime::currentDateTimeUtc().toString(QLatin1String("hh:mm:ss (%t)")), Qt::CaseInsensitive);
setRequestedPresence(Tp::Presence::xa(m_xaMessage));
setActive(true);
}
}
}
void AutoAway::backFromIdle()
{
kDebug();
setActive(false);
}
void AutoAway::readConfig()
{
KSharedConfigPtr config = KSharedConfig::openConfig(QLatin1String("ktelepathyrc"));
config.data()->reparseConfiguration();
KConfigGroup kdedConfig = config->group("KDED");
bool autoAwayEnabled = kdedConfig.readEntry("autoAwayEnabled", true);
bool autoXAEnabled = kdedConfig.readEntry("autoXAEnabled", true);
m_awayMessage = kdedConfig.readEntry(QLatin1String("awayMessage"), QString());
m_xaMessage = kdedConfig.readEntry(QLatin1String("xaMessage"), QString());
//remove all our timeouts and only readd them if auto-away is enabled
//WARNING: can't use removeAllTimeouts because this runs inside KDED, it would remove other KDED timeouts as well
KIdleTime::instance()->removeIdleTimeout(m_awayTimeoutId);
KIdleTime::instance()->removeIdleTimeout(m_extAwayTimeoutId);
if (autoAwayEnabled) {
int awayTime = kdedConfig.readEntry("awayAfter", 5);
m_awayTimeoutId = KIdleTime::instance()->addIdleTimeout(awayTime * 60 * 1000);
setEnabled(true);
} else {
setEnabled(false);
}
if (autoAwayEnabled && autoXAEnabled) {
int xaTime = kdedConfig.readEntry("xaAfter", 15);
m_extAwayTimeoutId = KIdleTime::instance()->addIdleTimeout(xaTime * 60 * 1000);
}
}
void AutoAway::onSettingsChanged()
{
readConfig();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* 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 copyright holders 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.
*/
// modified (rewritten) 05/20/05 by Dan Gibson to accomimdate FASTER
// >32 bit set sizes
#include <cstdio>
#include "base/misc.hh"
#include "mem/ruby/common/Set.hh"
#include "mem/ruby/system/System.hh"
Set::Set()
{
m_p_nArray = NULL;
m_nArrayLen = 0;
m_nSize = 0;
}
Set::Set(const Set& obj)
{
m_p_nArray = NULL;
setSize(obj.m_nSize);
// copy from the host to this array
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] = obj.m_p_nArray[i];
}
Set::Set(int size)
{
m_p_nArray = NULL;
m_nArrayLen = 0;
m_nSize = 0;
if (size > 0)
setSize(size);
}
Set::~Set()
{
if (m_p_nArray && m_p_nArray != &m_p_nArray_Static[0])
delete [] m_p_nArray;
m_p_nArray = NULL;
}
void
Set::clearExcess()
{
// now just ensure that no bits over the maximum size were set
#ifdef _LP64
long mask = 0x7FFFFFFFFFFFFFFF;
#else
long mask = 0x7FFFFFFF;
#endif
// the number of populated spaces in the higest-order array slot
// is: m_nSize % LONG_BITS, so the uppermost LONG_BITS -
// m_nSize%64 bits should be cleared
if ((m_nSize % LONG_BITS) != 0) {
for (int j = 0; j < 64 - (m_nSize & INDEX_MASK); j++) {
m_p_nArray[m_nArrayLen - 1] &= mask;
mask = mask >> 1;
}
}
}
/*
* This function should set all the bits in the current set that are
* already set in the parameter set
*/
void
Set::addSet(const Set& set)
{
assert(getSize()==set.getSize());
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] |= set.m_p_nArray[i];
}
/*
* This function should randomly assign 1 to the bits in the set--it
* should not clear the bits bits first, though?
*/
void
Set::addRandom()
{
for (int i = 0; i < m_nArrayLen; i++) {
// this ensures that all 32 bits are subject to random effects,
// as RAND_MAX typically = 0x7FFFFFFF
m_p_nArray[i] |= random() ^ (random() << 4);
}
clearExcess();
}
/*
* This function clears bits that are =1 in the parameter set
*/
void
Set::removeSet(const Set& set)
{
assert(m_nSize == set.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] &= ~set.m_p_nArray[i];
}
/*
* this function sets all bits in the set
*/
void
Set::broadcast()
{
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] = -1; // note that -1 corresponds to all 1's in 2's comp.
clearExcess();
}
/*
* This function returns the population count of 1's in the set
*/
int
Set::count() const
{
int counter = 0;
long mask;
for (int i = 0; i < m_nArrayLen; i++) {
mask = (long)0x01;
for (int j = 0; j < LONG_BITS; j++) {
// FIXME - significant performance loss when array
// population << LONG_BITS
if ((m_p_nArray[i] & mask) != 0) {
counter++;
}
mask = mask << 1;
}
}
return counter;
}
/*
* This function checks for set equality
*/
bool
Set::isEqual(const Set& set) const
{
assert(m_nSize == set.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
if (m_p_nArray[i] != set.m_p_nArray[i])
return false;
return true;
}
/*
* This function returns the NodeID (int) of the least set bit
*/
NodeID
Set::smallestElement() const
{
assert(count() > 0);
long x;
for (int i = 0; i < m_nArrayLen; i++) {
if (m_p_nArray[i] != 0) {
// the least-set bit must be in here
x = m_p_nArray[i];
for (int j = 0; j < LONG_BITS; j++) {
if (x & (unsigned long)1) {
return LONG_BITS * i + j;
}
x = x >> 1;
}
panic("No smallest element of an empty set.");
}
}
panic("No smallest element of an empty set.");
}
/*
* this function returns true iff all bits are set
*/
bool
Set::isBroadcast() const
{
// check the fully-loaded words by equal to 0xffffffff
// only the last word may not be fully loaded, it is not
// fully loaded iff m_nSize % 32 or 64 !=0 => fully loaded iff
// m_nSize % 32 or 64 == 0
int max = (m_nSize % LONG_BITS) == 0 ? m_nArrayLen : m_nArrayLen - 1;
for (int i = 0; i < max; i++) {
if (m_p_nArray[i] != -1) {
return false;
}
}
// now check the last word, which may not be fully loaded
long mask = 1;
for (int j = 0; j < (m_nSize % LONG_BITS); j++) {
if ((mask & m_p_nArray[m_nArrayLen-1]) == 0) {
return false;
}
mask = mask << 1;
}
return true;
}
/*
* this function returns true iff no bits are set
*/
bool
Set::isEmpty() const
{
// here we can simply check if all = 0, since we ensure
// that "extra slots" are all zero
for (int i = 0; i < m_nArrayLen ; i++)
if (m_p_nArray[i])
return false;
return true;
}
// returns the logical OR of "this" set and orSet
Set
Set::OR(const Set& orSet) const
{
Set result(m_nSize);
assert(m_nSize == orSet.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
result.m_p_nArray[i] = m_p_nArray[i] | orSet.m_p_nArray[i];
return result;
}
// returns the logical AND of "this" set and andSet
Set
Set::AND(const Set& andSet) const
{
Set result(m_nSize);
assert(m_nSize == andSet.m_nSize);
for (int i = 0; i < m_nArrayLen; i++) {
result.m_p_nArray[i] = m_p_nArray[i] & andSet.m_p_nArray[i];
}
return result;
}
/*
* Returns false if a bit is set in the parameter set that is NOT set
* in this set
*/
bool
Set::isSuperset(const Set& test) const
{
assert(m_nSize == test.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
if (((test.m_p_nArray[i] & m_p_nArray[i]) | ~test.m_p_nArray[i]) != -1)
return false;
return true;
}
void
Set::setSize(int size)
{
m_nSize = size;
m_nArrayLen = (m_nSize + LONG_BITS - 1) / LONG_BITS;
// decide whether to use dynamic or static alloction
if (m_nArrayLen <= NUMBER_WORDS_PER_SET) {
// constant defined in RubySystem.hh
// its OK to use the static allocation, and it will
// probably be faster (as m_nArrayLen is already in the
// cache and they will probably share the same cache line)
// if switching from dyanamic to static allocation (which
// is probably rare, but why not be complete?), must delete
// the dynamically allocated space
if (m_p_nArray && m_p_nArray != &m_p_nArray_Static[0])
delete [] m_p_nArray;
m_p_nArray = &m_p_nArray_Static[0];
} else {
// can't use static allocation...simply not enough room
// so dynamically allocate some space
if (m_p_nArray && m_p_nArray != &m_p_nArray_Static[0])
delete [] m_p_nArray;
m_p_nArray = new long[m_nArrayLen];
}
clear();
}
Set&
Set::operator=(const Set& obj)
{
if (this != &obj) {
// resize this item
setSize(obj.getSize());
// copy the elements from obj to this
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] = obj.m_p_nArray[i];
}
return *this;
}
void
Set::print(std::ostream& out) const
{
if (!m_p_nArray) {
out << "[Set {Empty}]";
return;
}
char buff[24];
out << "[Set (" << m_nSize << ") 0x ";
for (int i = m_nArrayLen - 1; i >= 0; i--) {
#ifdef _LP64
sprintf(buff,"0x %016llX ", (long long)m_p_nArray[i]);
#else
sprintf(buff,"%08X ", m_p_nArray[i]);
#endif // __32BITS__
out << buff;
}
out << " ]";
}
<commit_msg>Ruby: Fix Set::print for 32-bit hosts<commit_after>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* 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 copyright holders 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.
*/
// modified (rewritten) 05/20/05 by Dan Gibson to accomimdate FASTER
// >32 bit set sizes
#include <cstdio>
#include "base/misc.hh"
#include "mem/ruby/common/Set.hh"
#include "mem/ruby/system/System.hh"
Set::Set()
{
m_p_nArray = NULL;
m_nArrayLen = 0;
m_nSize = 0;
}
Set::Set(const Set& obj)
{
m_p_nArray = NULL;
setSize(obj.m_nSize);
// copy from the host to this array
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] = obj.m_p_nArray[i];
}
Set::Set(int size)
{
m_p_nArray = NULL;
m_nArrayLen = 0;
m_nSize = 0;
if (size > 0)
setSize(size);
}
Set::~Set()
{
if (m_p_nArray && m_p_nArray != &m_p_nArray_Static[0])
delete [] m_p_nArray;
m_p_nArray = NULL;
}
void
Set::clearExcess()
{
// now just ensure that no bits over the maximum size were set
#ifdef _LP64
long mask = 0x7FFFFFFFFFFFFFFF;
#else
long mask = 0x7FFFFFFF;
#endif
// the number of populated spaces in the higest-order array slot
// is: m_nSize % LONG_BITS, so the uppermost LONG_BITS -
// m_nSize%64 bits should be cleared
if ((m_nSize % LONG_BITS) != 0) {
for (int j = 0; j < 64 - (m_nSize & INDEX_MASK); j++) {
m_p_nArray[m_nArrayLen - 1] &= mask;
mask = mask >> 1;
}
}
}
/*
* This function should set all the bits in the current set that are
* already set in the parameter set
*/
void
Set::addSet(const Set& set)
{
assert(getSize()==set.getSize());
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] |= set.m_p_nArray[i];
}
/*
* This function should randomly assign 1 to the bits in the set--it
* should not clear the bits bits first, though?
*/
void
Set::addRandom()
{
for (int i = 0; i < m_nArrayLen; i++) {
// this ensures that all 32 bits are subject to random effects,
// as RAND_MAX typically = 0x7FFFFFFF
m_p_nArray[i] |= random() ^ (random() << 4);
}
clearExcess();
}
/*
* This function clears bits that are =1 in the parameter set
*/
void
Set::removeSet(const Set& set)
{
assert(m_nSize == set.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] &= ~set.m_p_nArray[i];
}
/*
* this function sets all bits in the set
*/
void
Set::broadcast()
{
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] = -1; // note that -1 corresponds to all 1's in 2's comp.
clearExcess();
}
/*
* This function returns the population count of 1's in the set
*/
int
Set::count() const
{
int counter = 0;
long mask;
for (int i = 0; i < m_nArrayLen; i++) {
mask = (long)0x01;
for (int j = 0; j < LONG_BITS; j++) {
// FIXME - significant performance loss when array
// population << LONG_BITS
if ((m_p_nArray[i] & mask) != 0) {
counter++;
}
mask = mask << 1;
}
}
return counter;
}
/*
* This function checks for set equality
*/
bool
Set::isEqual(const Set& set) const
{
assert(m_nSize == set.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
if (m_p_nArray[i] != set.m_p_nArray[i])
return false;
return true;
}
/*
* This function returns the NodeID (int) of the least set bit
*/
NodeID
Set::smallestElement() const
{
assert(count() > 0);
long x;
for (int i = 0; i < m_nArrayLen; i++) {
if (m_p_nArray[i] != 0) {
// the least-set bit must be in here
x = m_p_nArray[i];
for (int j = 0; j < LONG_BITS; j++) {
if (x & (unsigned long)1) {
return LONG_BITS * i + j;
}
x = x >> 1;
}
panic("No smallest element of an empty set.");
}
}
panic("No smallest element of an empty set.");
}
/*
* this function returns true iff all bits are set
*/
bool
Set::isBroadcast() const
{
// check the fully-loaded words by equal to 0xffffffff
// only the last word may not be fully loaded, it is not
// fully loaded iff m_nSize % 32 or 64 !=0 => fully loaded iff
// m_nSize % 32 or 64 == 0
int max = (m_nSize % LONG_BITS) == 0 ? m_nArrayLen : m_nArrayLen - 1;
for (int i = 0; i < max; i++) {
if (m_p_nArray[i] != -1) {
return false;
}
}
// now check the last word, which may not be fully loaded
long mask = 1;
for (int j = 0; j < (m_nSize % LONG_BITS); j++) {
if ((mask & m_p_nArray[m_nArrayLen-1]) == 0) {
return false;
}
mask = mask << 1;
}
return true;
}
/*
* this function returns true iff no bits are set
*/
bool
Set::isEmpty() const
{
// here we can simply check if all = 0, since we ensure
// that "extra slots" are all zero
for (int i = 0; i < m_nArrayLen ; i++)
if (m_p_nArray[i])
return false;
return true;
}
// returns the logical OR of "this" set and orSet
Set
Set::OR(const Set& orSet) const
{
Set result(m_nSize);
assert(m_nSize == orSet.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
result.m_p_nArray[i] = m_p_nArray[i] | orSet.m_p_nArray[i];
return result;
}
// returns the logical AND of "this" set and andSet
Set
Set::AND(const Set& andSet) const
{
Set result(m_nSize);
assert(m_nSize == andSet.m_nSize);
for (int i = 0; i < m_nArrayLen; i++) {
result.m_p_nArray[i] = m_p_nArray[i] & andSet.m_p_nArray[i];
}
return result;
}
/*
* Returns false if a bit is set in the parameter set that is NOT set
* in this set
*/
bool
Set::isSuperset(const Set& test) const
{
assert(m_nSize == test.m_nSize);
for (int i = 0; i < m_nArrayLen; i++)
if (((test.m_p_nArray[i] & m_p_nArray[i]) | ~test.m_p_nArray[i]) != -1)
return false;
return true;
}
void
Set::setSize(int size)
{
m_nSize = size;
m_nArrayLen = (m_nSize + LONG_BITS - 1) / LONG_BITS;
// decide whether to use dynamic or static alloction
if (m_nArrayLen <= NUMBER_WORDS_PER_SET) {
// constant defined in RubySystem.hh
// its OK to use the static allocation, and it will
// probably be faster (as m_nArrayLen is already in the
// cache and they will probably share the same cache line)
// if switching from dyanamic to static allocation (which
// is probably rare, but why not be complete?), must delete
// the dynamically allocated space
if (m_p_nArray && m_p_nArray != &m_p_nArray_Static[0])
delete [] m_p_nArray;
m_p_nArray = &m_p_nArray_Static[0];
} else {
// can't use static allocation...simply not enough room
// so dynamically allocate some space
if (m_p_nArray && m_p_nArray != &m_p_nArray_Static[0])
delete [] m_p_nArray;
m_p_nArray = new long[m_nArrayLen];
}
clear();
}
Set&
Set::operator=(const Set& obj)
{
if (this != &obj) {
// resize this item
setSize(obj.getSize());
// copy the elements from obj to this
for (int i = 0; i < m_nArrayLen; i++)
m_p_nArray[i] = obj.m_p_nArray[i];
}
return *this;
}
void
Set::print(std::ostream& out) const
{
if (!m_p_nArray) {
out << "[Set {Empty}]";
return;
}
char buff[24];
out << "[Set (" << m_nSize << ")";
for (int i = m_nArrayLen - 1; i >= 0; i--) {
csprintf(buff," 0x%08X", m_p_nArray[i]);
out << buff;
}
out << " ]";
}
<|endoftext|> |
<commit_before>#include <gflags/gflags.h>
DEFINE_int32(minion_port, 7900, "minion listen port");
DEFINE_string(jobid, "", "the job id that minion works on");
DEFINE_string(nexus_addr, "", "nexus server list");
DEFINE_string(master_nexus_path, "/shuttle/master", "master address on nexus");
DEFINE_string(work_mode, "map", "there are 3 kinds: map, reduce, map-only");
DEFINE_bool(kill_task, false, "kill unfinished task");
DEFINE_int32(suspend_time, 60, "suspend time in seconds when receive suspend op");
DEFINE_int32(max_minions, 43, "max number of minions at one machine");
DEFINE_int64(flow_limit_10gb, 384L * 1024 * 1024, "the limit of network traffic for 10gb machine, default is 384M");
DEFINE_int64(flow_limit_1gb, 84L * 1024 * 1024, "the limit of network traffic for 1gb machine, default is 64M");
<commit_msg>adjust default value of max_minions<commit_after>#include <gflags/gflags.h>
DEFINE_int32(minion_port, 7900, "minion listen port");
DEFINE_string(jobid, "", "the job id that minion works on");
DEFINE_string(nexus_addr, "", "nexus server list");
DEFINE_string(master_nexus_path, "/shuttle/master", "master address on nexus");
DEFINE_string(work_mode, "map", "there are 3 kinds: map, reduce, map-only");
DEFINE_bool(kill_task, false, "kill unfinished task");
DEFINE_int32(suspend_time, 60, "suspend time in seconds when receive suspend op");
DEFINE_int32(max_minions, 25, "max number of minions at one machine");
DEFINE_int64(flow_limit_10gb, 384L * 1024 * 1024, "the limit of network traffic for 10gb machine, default is 384M");
DEFINE_int64(flow_limit_1gb, 84L * 1024 * 1024, "the limit of network traffic for 1gb machine, default is 64M");
<|endoftext|> |
<commit_before>/*
* SIV Mode Encryption
* (C) 2013 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/siv.h>
#include <botan/cmac.h>
#include <botan/ctr.h>
#include <botan/parsing.h>
#include <botan/internal/xor_buf.h>
#include <algorithm>
#include <iostream>
#include <botan/hex.h>
namespace Botan {
SIV_Mode::SIV_Mode(BlockCipher* cipher) :
m_name(cipher->name() + "/SIV"),
m_ctr(new CTR_BE(cipher->clone())),
m_cmac(new CMAC(cipher))
{
}
void SIV_Mode::clear()
{
m_ctr.reset();
m_nonce.clear();
m_msg_buf.clear();
m_ad_macs.clear();
}
std::string SIV_Mode::name() const
{
return m_name;
}
bool SIV_Mode::valid_nonce_length(size_t) const
{
return true;
}
size_t SIV_Mode::update_granularity() const
{
/*
This value does not particularly matter as regardless SIV_Mode::update
buffers all input, so in theory this could be 1. However as for instance
Transformation_Filter creates update_granularity() byte buffers, use a
somewhat large size to avoid bouncing on a tiny buffer.
*/
return 128;
}
Key_Length_Specification SIV_Mode::key_spec() const
{
return m_cmac->key_spec().multiple(2);
}
void SIV_Mode::key_schedule(const byte key[], size_t length)
{
const size_t keylen = length / 2;
m_cmac->set_key(key, keylen);
m_ctr->set_key(key + keylen, keylen);
m_ad_macs.clear();
}
void SIV_Mode::set_associated_data_n(size_t n, const byte ad[], size_t length)
{
if(n >= m_ad_macs.size())
m_ad_macs.resize(n+1);
m_ad_macs[n] = m_cmac->process(ad, length);
}
secure_vector<byte> SIV_Mode::start(const byte nonce[], size_t nonce_len)
{
if(!valid_nonce_length(nonce_len))
throw Invalid_IV_Length(name(), nonce_len);
if(nonce_len)
m_nonce = m_cmac->process(nonce, nonce_len);
else
m_nonce.clear();
m_msg_buf.clear();
return secure_vector<byte>();
}
void SIV_Mode::update(secure_vector<byte>& buffer, size_t offset)
{
BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
const size_t sz = buffer.size() - offset;
byte* buf = &buffer[offset];
m_msg_buf.insert(m_msg_buf.end(), buf, buf + sz);
buffer.resize(offset); // truncate msg
}
secure_vector<byte> SIV_Mode::S2V(const byte* text, size_t text_len)
{
const byte zero[16] = { 0 };
secure_vector<byte> V = cmac().process(zero, 16);
for(size_t i = 0; i != m_ad_macs.size(); ++i)
{
V = CMAC::poly_double(V, 0x87);
V ^= m_ad_macs[i];
}
if(m_nonce.size())
{
V = CMAC::poly_double(V, 0x87);
V ^= m_nonce;
}
if(text_len < 16)
{
V = CMAC::poly_double(V, 0x87);
xor_buf(&V[0], text, text_len);
V[text_len] ^= 0x80;
return cmac().process(V);
}
cmac().update(text, text_len - 16);
xor_buf(&V[0], &text[text_len - 16], 16);
cmac().update(V);
return cmac().final();
}
void SIV_Mode::set_ctr_iv(secure_vector<byte> V)
{
V[8] &= 0x7F;
V[12] &= 0x7F;
ctr().set_iv(&V[0], V.size());
}
void SIV_Encryption::finish(secure_vector<byte>& buffer, size_t offset)
{
BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
secure_vector<byte> V = S2V(&buffer[offset], buffer.size() - offset);
buffer.insert(buffer.begin() + offset, V.begin(), V.end());
set_ctr_iv(V);
ctr().cipher1(&buffer[offset + V.size()], buffer.size() - offset - V.size());
}
void SIV_Decryption::finish(secure_vector<byte>& buffer, size_t offset)
{
BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
const size_t sz = buffer.size() - offset;
BOTAN_ASSERT(sz >= tag_size(), "We have the tag");
secure_vector<byte> V(&buffer[offset], &buffer[offset + 16]);
set_ctr_iv(V);
ctr().cipher(&buffer[offset + V.size()],
&buffer[offset],
buffer.size() - offset - V.size());
secure_vector<byte> T = S2V(&buffer[offset], buffer.size() - offset - V.size());
if(T != V)
throw Integrity_Failure("SIV tag check failed");
buffer.resize(buffer.size() - tag_size());
}
}
<commit_msg>Remove debug headers<commit_after>/*
* SIV Mode Encryption
* (C) 2013 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/siv.h>
#include <botan/cmac.h>
#include <botan/ctr.h>
#include <botan/parsing.h>
#include <botan/internal/xor_buf.h>
#include <algorithm>
namespace Botan {
SIV_Mode::SIV_Mode(BlockCipher* cipher) :
m_name(cipher->name() + "/SIV"),
m_ctr(new CTR_BE(cipher->clone())),
m_cmac(new CMAC(cipher))
{
}
void SIV_Mode::clear()
{
m_ctr.reset();
m_nonce.clear();
m_msg_buf.clear();
m_ad_macs.clear();
}
std::string SIV_Mode::name() const
{
return m_name;
}
bool SIV_Mode::valid_nonce_length(size_t) const
{
return true;
}
size_t SIV_Mode::update_granularity() const
{
/*
This value does not particularly matter as regardless SIV_Mode::update
buffers all input, so in theory this could be 1. However as for instance
Transformation_Filter creates update_granularity() byte buffers, use a
somewhat large size to avoid bouncing on a tiny buffer.
*/
return 128;
}
Key_Length_Specification SIV_Mode::key_spec() const
{
return m_cmac->key_spec().multiple(2);
}
void SIV_Mode::key_schedule(const byte key[], size_t length)
{
const size_t keylen = length / 2;
m_cmac->set_key(key, keylen);
m_ctr->set_key(key + keylen, keylen);
m_ad_macs.clear();
}
void SIV_Mode::set_associated_data_n(size_t n, const byte ad[], size_t length)
{
if(n >= m_ad_macs.size())
m_ad_macs.resize(n+1);
m_ad_macs[n] = m_cmac->process(ad, length);
}
secure_vector<byte> SIV_Mode::start(const byte nonce[], size_t nonce_len)
{
if(!valid_nonce_length(nonce_len))
throw Invalid_IV_Length(name(), nonce_len);
if(nonce_len)
m_nonce = m_cmac->process(nonce, nonce_len);
else
m_nonce.clear();
m_msg_buf.clear();
return secure_vector<byte>();
}
void SIV_Mode::update(secure_vector<byte>& buffer, size_t offset)
{
BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
const size_t sz = buffer.size() - offset;
byte* buf = &buffer[offset];
m_msg_buf.insert(m_msg_buf.end(), buf, buf + sz);
buffer.resize(offset); // truncate msg
}
secure_vector<byte> SIV_Mode::S2V(const byte* text, size_t text_len)
{
const byte zero[16] = { 0 };
secure_vector<byte> V = cmac().process(zero, 16);
for(size_t i = 0; i != m_ad_macs.size(); ++i)
{
V = CMAC::poly_double(V, 0x87);
V ^= m_ad_macs[i];
}
if(m_nonce.size())
{
V = CMAC::poly_double(V, 0x87);
V ^= m_nonce;
}
if(text_len < 16)
{
V = CMAC::poly_double(V, 0x87);
xor_buf(&V[0], text, text_len);
V[text_len] ^= 0x80;
return cmac().process(V);
}
cmac().update(text, text_len - 16);
xor_buf(&V[0], &text[text_len - 16], 16);
cmac().update(V);
return cmac().final();
}
void SIV_Mode::set_ctr_iv(secure_vector<byte> V)
{
V[8] &= 0x7F;
V[12] &= 0x7F;
ctr().set_iv(&V[0], V.size());
}
void SIV_Encryption::finish(secure_vector<byte>& buffer, size_t offset)
{
BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
secure_vector<byte> V = S2V(&buffer[offset], buffer.size() - offset);
buffer.insert(buffer.begin() + offset, V.begin(), V.end());
set_ctr_iv(V);
ctr().cipher1(&buffer[offset + V.size()], buffer.size() - offset - V.size());
}
void SIV_Decryption::finish(secure_vector<byte>& buffer, size_t offset)
{
BOTAN_ASSERT(buffer.size() >= offset, "Offset is sane");
buffer.insert(buffer.begin() + offset, msg_buf().begin(), msg_buf().end());
const size_t sz = buffer.size() - offset;
BOTAN_ASSERT(sz >= tag_size(), "We have the tag");
secure_vector<byte> V(&buffer[offset], &buffer[offset + 16]);
set_ctr_iv(V);
ctr().cipher(&buffer[offset + V.size()],
&buffer[offset],
buffer.size() - offset - V.size());
secure_vector<byte> T = S2V(&buffer[offset], buffer.size() - offset - V.size());
if(T != V)
throw Integrity_Failure("SIV tag check failed");
buffer.resize(buffer.size() - tag_size());
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2015-2016 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_geom_hpp__
#define __se3_geom_hpp__
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/spatial/force.hpp"
#include "pinocchio/spatial/motion.hpp"
#include "pinocchio/spatial/inertia.hpp"
#include "pinocchio/spatial/fcl-pinocchio-conversions.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/multibody/joint/joint-variant.hpp"
#include <iostream>
#include <hpp/fcl/collision_object.h>
#include <hpp/fcl/collision.h>
#include <hpp/fcl/distance.h>
#include <map>
#include <list>
#include <utility>
namespace se3
{
// Result of distance computation between two CollisionObject.
struct DistanceResult
{
typedef Model::Index Index;
DistanceResult(fcl::DistanceResult dist_fcl, const Index co1, const Index co2)
: fcl_distance_result(dist_fcl), object1(co1), object2(co2)
{}
// Get distance between objects
double distance () const { return fcl_distance_result.min_distance; }
// Get closest point on inner object in global frame,
Eigen::Vector3d closestPointInner () const { return toVector3d(fcl_distance_result.nearest_points [0]); }
// Get closest point on outer object in global frame,
Eigen::Vector3d closestPointOuter () const { return toVector3d(fcl_distance_result.nearest_points [1]); }
bool operator == (const DistanceResult & other) const
{
return (distance() == other.distance()
&& closestPointInner() == other.closestPointInner()
&& closestPointOuter() == other.closestPointOuter()
&& object1 == other.object1
&& object2 == other.object2);
}
fcl::DistanceResult fcl_distance_result;
/// Index of the first colision object
Index object1;
/// Index of the second colision object
Index object2;
}; // struct DistanceResult
struct GeometryModel
{
typedef Model::Index Index;
Index ngeom;
std::vector<fcl::CollisionObject> collision_objects;
std::vector<std::string> geom_names;
std::vector<Index> geom_parents; // Joint parent of body <i>, denoted <li> (li==parents[i])
std::vector<SE3> geometryPlacement; // Position of geometry object in parent joint's frame
std::map < Index, std::list<Index> > innerObjects; // Associate a list of CollisionObjects to a given joint Id
std::map < Index, std::list<Index> > outerObjects; // Associate a list of CollisionObjects to a given joint Id
GeometryModel()
: ngeom(0)
, collision_objects()
, geom_names(0)
, geom_parents(0)
, geometryPlacement(0)
, innerObjects()
, outerObjects()
{
}
~GeometryModel() {};
Index addGeomObject( Index parent,const fcl::CollisionObject & co, const SE3 & placement, const std::string & geoName = "");
Index getGeomId( const std::string & name ) const;
bool existGeomName( const std::string & name ) const;
const std::string& getGeomName( Index index ) const;
void addInnerObject(Index joint, Index inner_object);
void addOutterObject(Index joint, Index outer_object);
friend std::ostream& operator<<(std::ostream& os, const GeometryModel& model_geom);
};
struct GeometryData
{
typedef Model::Index Index;
typedef std::pair<Index,Index> CollisionPair_t;
typedef std::vector<CollisionPair_t> CollisionPairsVector_t;
const Data & data_ref;
const GeometryModel & model_geom;
std::vector<se3::SE3> oMg;
std::vector<fcl::Transform3f> oMg_fcl;
CollisionPairsVector_t collision_pairs;
Index nCollisionPairs;
std::vector < DistanceResult > distances;
std::vector < bool > collisions;
GeometryData(const Data & data, const GeometryModel & model_geom)
: data_ref(data)
, model_geom(model_geom)
, oMg(model_geom.ngeom)
, oMg_fcl(model_geom.ngeom)
, collision_pairs()
, nCollisionPairs(0)
, distances()
, collisions()
{
initializeListOfCollisionPairs();
distances.resize(nCollisionPairs, DistanceResult( fcl::DistanceResult(), 0, 0) );
collisions.resize(nCollisionPairs, false );
}
~GeometryData() {};
void addCollisionPair (const Index co1, const Index co2);
void addCollisionPair (const CollisionPair_t & pair);
void removeCollisionPair (const Index co1, const Index co2);
void removeCollisionPair (const CollisionPair_t& pair);
///
/// \brief Check if a CollisionPair given by the index of the two colliding geometries exists in collision_pairs.
/// See also findCollisitionPair(const Index co1, const Index co2).
///
/// \param[in] co1 Index of the first colliding geometry.
/// \param[in] co2 Index of the second colliding geometry.
///
/// \return True if the CollisionPair exists, false otherwise.
///
bool existCollisionPair (const Index co1, const Index co2) const ;
///
/// \brief Check if a CollisionPair given by the index of the two colliding geometries exists in collision_pairs.
/// See also findCollisitionPair(const CollisionPair_t & pair).
///
/// \param[in] pair The CollisionPair.
///
/// \return True if the CollisionPair exists, false otherwise.
///
bool existCollisionPair (const CollisionPair_t & pair) const;
///
/// \brief Return the index in collision_pairs of a CollisionPair given by the index of the two colliding geometries.
///
/// \param[in] co1 Index of the first colliding geometry.
/// \param[in] co2 Index of the second colliding geometry.
///
/// \return The index of the collision pair in collision_pairs.
///
Index findCollisionPair (const Index co1, const Index co2) const;
///
/// \brief Return the index of a given CollisionPair in collision_pairs.
///
/// \param[in] pair The CollisionPair.
///
/// \return The index of the CollisionPair in collision_pairs.
///
Index findCollisionPair (const CollisionPair_t & pair) const;
void fillAllPairsAsCollisions();
void desactivateCollisionPairs();
void initializeListOfCollisionPairs();
bool collide(const Index co1, const Index co2) const;
fcl::DistanceResult computeDistance(const Index co1, const Index co2) const;
void resetDistances();
std::vector < DistanceResult > distanceResults(); //TODO : to keep or not depending of public or not for distances
void displayCollisionPairs() const
{
for (std::vector<CollisionPair_t>::const_iterator it = collision_pairs.begin(); it != collision_pairs.end(); ++it)
{
std::cout << it-> first << "\t" << it->second << std::endl;
}
}
friend std::ostream& operator<<(std::ostream& os, const GeometryData& data_geom);
};
} // namespace se3
/* --- Details -------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------- */
#include "pinocchio/multibody/geometry.hxx"
#endif // ifndef __se3_geom_hpp__
<commit_msg>[C++] Remove accessor distanceResults - not necessary<commit_after>//
// Copyright (c) 2015-2016 CNRS
//
// This file is part of Pinocchio
// Pinocchio 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.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_geom_hpp__
#define __se3_geom_hpp__
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/spatial/force.hpp"
#include "pinocchio/spatial/motion.hpp"
#include "pinocchio/spatial/inertia.hpp"
#include "pinocchio/spatial/fcl-pinocchio-conversions.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/multibody/joint/joint-variant.hpp"
#include <iostream>
#include <hpp/fcl/collision_object.h>
#include <hpp/fcl/collision.h>
#include <hpp/fcl/distance.h>
#include <map>
#include <list>
#include <utility>
namespace se3
{
// Result of distance computation between two CollisionObject.
struct DistanceResult
{
typedef Model::Index Index;
DistanceResult(fcl::DistanceResult dist_fcl, const Index co1, const Index co2)
: fcl_distance_result(dist_fcl), object1(co1), object2(co2)
{}
// Get distance between objects
double distance () const { return fcl_distance_result.min_distance; }
// Get closest point on inner object in global frame,
Eigen::Vector3d closestPointInner () const { return toVector3d(fcl_distance_result.nearest_points [0]); }
// Get closest point on outer object in global frame,
Eigen::Vector3d closestPointOuter () const { return toVector3d(fcl_distance_result.nearest_points [1]); }
bool operator == (const DistanceResult & other) const
{
return (distance() == other.distance()
&& closestPointInner() == other.closestPointInner()
&& closestPointOuter() == other.closestPointOuter()
&& object1 == other.object1
&& object2 == other.object2);
}
fcl::DistanceResult fcl_distance_result;
/// Index of the first colision object
Index object1;
/// Index of the second colision object
Index object2;
}; // struct DistanceResult
struct GeometryModel
{
typedef Model::Index Index;
Index ngeom;
std::vector<fcl::CollisionObject> collision_objects;
std::vector<std::string> geom_names;
std::vector<Index> geom_parents; // Joint parent of body <i>, denoted <li> (li==parents[i])
std::vector<SE3> geometryPlacement; // Position of geometry object in parent joint's frame
std::map < Index, std::list<Index> > innerObjects; // Associate a list of CollisionObjects to a given joint Id
std::map < Index, std::list<Index> > outerObjects; // Associate a list of CollisionObjects to a given joint Id
GeometryModel()
: ngeom(0)
, collision_objects()
, geom_names(0)
, geom_parents(0)
, geometryPlacement(0)
, innerObjects()
, outerObjects()
{
}
~GeometryModel() {};
Index addGeomObject( Index parent,const fcl::CollisionObject & co, const SE3 & placement, const std::string & geoName = "");
Index getGeomId( const std::string & name ) const;
bool existGeomName( const std::string & name ) const;
const std::string& getGeomName( Index index ) const;
void addInnerObject(Index joint, Index inner_object);
void addOutterObject(Index joint, Index outer_object);
friend std::ostream& operator<<(std::ostream& os, const GeometryModel& model_geom);
};
struct GeometryData
{
typedef Model::Index Index;
typedef std::pair<Index,Index> CollisionPair_t;
typedef std::vector<CollisionPair_t> CollisionPairsVector_t;
const Data & data_ref;
const GeometryModel & model_geom;
std::vector<se3::SE3> oMg;
std::vector<fcl::Transform3f> oMg_fcl;
CollisionPairsVector_t collision_pairs;
Index nCollisionPairs;
std::vector < DistanceResult > distances;
std::vector < bool > collisions;
GeometryData(const Data & data, const GeometryModel & model_geom)
: data_ref(data)
, model_geom(model_geom)
, oMg(model_geom.ngeom)
, oMg_fcl(model_geom.ngeom)
, collision_pairs()
, nCollisionPairs(0)
, distances()
, collisions()
{
initializeListOfCollisionPairs();
distances.resize(nCollisionPairs, DistanceResult( fcl::DistanceResult(), 0, 0) );
collisions.resize(nCollisionPairs, false );
}
~GeometryData() {};
void addCollisionPair (const Index co1, const Index co2);
void addCollisionPair (const CollisionPair_t & pair);
void removeCollisionPair (const Index co1, const Index co2);
void removeCollisionPair (const CollisionPair_t& pair);
///
/// \brief Check if a CollisionPair given by the index of the two colliding geometries exists in collision_pairs.
/// See also findCollisitionPair(const Index co1, const Index co2).
///
/// \param[in] co1 Index of the first colliding geometry.
/// \param[in] co2 Index of the second colliding geometry.
///
/// \return True if the CollisionPair exists, false otherwise.
///
bool existCollisionPair (const Index co1, const Index co2) const ;
///
/// \brief Check if a CollisionPair given by the index of the two colliding geometries exists in collision_pairs.
/// See also findCollisitionPair(const CollisionPair_t & pair).
///
/// \param[in] pair The CollisionPair.
///
/// \return True if the CollisionPair exists, false otherwise.
///
bool existCollisionPair (const CollisionPair_t & pair) const;
///
/// \brief Return the index in collision_pairs of a CollisionPair given by the index of the two colliding geometries.
///
/// \param[in] co1 Index of the first colliding geometry.
/// \param[in] co2 Index of the second colliding geometry.
///
/// \return The index of the collision pair in collision_pairs.
///
Index findCollisionPair (const Index co1, const Index co2) const;
///
/// \brief Return the index of a given CollisionPair in collision_pairs.
///
/// \param[in] pair The CollisionPair.
///
/// \return The index of the CollisionPair in collision_pairs.
///
Index findCollisionPair (const CollisionPair_t & pair) const;
void fillAllPairsAsCollisions();
void desactivateCollisionPairs();
void initializeListOfCollisionPairs();
bool collide(const Index co1, const Index co2) const;
fcl::DistanceResult computeDistance(const Index co1, const Index co2) const;
void resetDistances();
void displayCollisionPairs() const
{
for (std::vector<CollisionPair_t>::const_iterator it = collision_pairs.begin(); it != collision_pairs.end(); ++it)
{
std::cout << it-> first << "\t" << it->second << std::endl;
}
}
friend std::ostream& operator<<(std::ostream& os, const GeometryData& data_geom);
};
} // namespace se3
/* --- Details -------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------- */
/* --- Details -------------------------------------------------------------- */
#include "pinocchio/multibody/geometry.hxx"
#endif // ifndef __se3_geom_hpp__
<|endoftext|> |
<commit_before>#include "common.hpp"
#include "panel.hpp"
#include <chrono>
#include <ctime>
#include <unistd.h>
#include <cairo/cairo-ft.h>
#include <freetype2/ft2build.h>
#include "../proto/wayfire-shell-client.h"
void panel_redraw(void *data, wl_callback*, uint32_t)
{
wayfire_panel *panel = (wayfire_panel*) data;
panel->render_frame();
}
void output_created_cb(void *data, wayfire_shell *wayfire_shell, uint32_t output,
uint32_t width, uint32_t height)
{
wayfire_panel *panel = (wayfire_panel*) data;
panel->create_panel(output, width, height);
}
static const struct wl_callback_listener frame_listener = {
panel_redraw
};
static const struct wayfire_shell_listener shell_listener = {
.output_created = output_created_cb
};
wayfire_panel::wayfire_panel()
{
wayfire_shell_add_listener(display.wfshell, &shell_listener, this);
}
void wayfire_panel::create_panel(uint32_t output, uint32_t _width, uint32_t _height)
{
width = _width;
/* TODO: should take font size into account */
height = 1.3 * font_size;
this->output = output;
window = create_window(width, this->height);
cr = cairo_create(window->cairo_surface);
const char * filename =
"/usr/share/fonts/dejavu/DejaVuSerif.ttf";
FT_Library value;
auto status = FT_Init_FreeType(&value);
if (status != 0) {
std::cerr << "failed to open freetype library" << std::endl;
exit (EXIT_FAILURE);
}
FT_Face face;
status = FT_New_Face (value, filename, 0, &face);
if (status != 0) {
std::cerr << "Error opening font file " << filename << std::endl;
exit (EXIT_FAILURE);
}
font = cairo_ft_font_face_create_for_ft_face (face, 0);
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); /* blank to white */
cairo_set_font_size(cr, font_size);
cairo_set_font_face(cr, font);
animation.dy = -5;
animation.target_y = hidden_height - height;
animation.start_y = 0;
animation.current_y = animation.start_y;
repaint_callback = nullptr;
render_frame();
//wayfire_shell_reserve(display.wfshell, output, WAYFIRE_SHELL_PANEL_POSITION_UP, width, hidden_height);
wayfire_shell_add_panel(display.wfshell, output, window->surface);
window->pointer_enter = std::bind(std::mem_fn(&wayfire_panel::on_enter), this);
window->pointer_leave = std::bind(std::mem_fn(&wayfire_panel::on_leave), this);
}
void wayfire_panel::toggle_animation()
{
std::swap(animation.target_y, animation.start_y);
animation.dy *= -1;
}
void wayfire_panel::on_enter()
{
toggle_animation();
add_callback(false);
}
void wayfire_panel::on_leave()
{
toggle_animation();
}
void render_rounded_rectangle(cairo_t *cr, int x, int y, int width, int height, double radius,
double r, double g, double b, double a)
{
double degrees = M_PI / 180.0;
cairo_new_sub_path (cr);
cairo_arc (cr, x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees);
cairo_arc (cr, x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees);
cairo_arc (cr, x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees);
cairo_arc (cr, x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
cairo_close_path (cr);
cairo_set_source_rgba(cr, r, g, b, a);
cairo_fill_preserve(cr);
}
void wayfire_panel::add_callback(bool swapped)
{
if (repaint_callback)
wl_callback_destroy(repaint_callback);
repaint_callback = wl_surface_frame(window->surface);
wl_callback_add_listener(repaint_callback, &frame_listener, this);
if (!swapped)
wl_surface_commit(window->surface);
}
const std::string months[] = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
void wayfire_panel::render_frame()
{
set_active_window(window);
using std::chrono::system_clock;
time_t now = system_clock::to_time_t(system_clock::now());
auto time = std::localtime(&now);
std::string time_string = std::to_string(time->tm_mday) + " " +
months[time->tm_mon] + " " + std::to_string(time->tm_hour) +
":" + std::to_string(time->tm_min);
if (animation.current_y != animation.target_y) {
animation.current_y += animation.dy;
wayfire_shell_configure_panel(display.wfshell, output,
window->surface, 0, animation.current_y);
}
bool should_swap = false;
if (time_string != this->current_text && animation.current_y > hidden_height - (int)height) {
render_rounded_rectangle(cr, 0, 0, width, height, 7, 0.117, 0.137, 0.152, 1);
double x = 5, y = 20;
cairo_set_source_rgb(cr, 0.91, 0.918, 0.965); /* blank to white */
cairo_move_to(cr, x, y);
cairo_show_text(cr, time_string.c_str());
should_swap = true;
}
current_text = time_string;
//std::cout << animation.current_y << std::endl;
if (animation.current_y != hidden_height - (int)height)
add_callback(should_swap);
if (should_swap)
cairo_gl_surface_swapbuffers(window->cairo_surface);
}
<commit_msg>Panel: render text in the center<commit_after>#include "common.hpp"
#include "panel.hpp"
#include <chrono>
#include <ctime>
#include <unistd.h>
#include <cairo/cairo-ft.h>
#include <freetype2/ft2build.h>
#include "../proto/wayfire-shell-client.h"
void panel_redraw(void *data, wl_callback*, uint32_t)
{
wayfire_panel *panel = (wayfire_panel*) data;
panel->render_frame();
}
void output_created_cb(void *data, wayfire_shell *wayfire_shell, uint32_t output,
uint32_t width, uint32_t height)
{
wayfire_panel *panel = (wayfire_panel*) data;
panel->create_panel(output, width, height);
}
static const struct wl_callback_listener frame_listener = {
panel_redraw
};
static const struct wayfire_shell_listener shell_listener = {
.output_created = output_created_cb
};
wayfire_panel::wayfire_panel()
{
wayfire_shell_add_listener(display.wfshell, &shell_listener, this);
}
void wayfire_panel::create_panel(uint32_t output, uint32_t _width, uint32_t _height)
{
width = _width;
/* TODO: should take font size into account */
height = 1.3 * font_size;
this->output = output;
window = create_window(width, this->height);
cr = cairo_create(window->cairo_surface);
const char * filename =
"/usr/share/fonts/dejavu/DejaVuSerif.ttf";
FT_Library value;
auto status = FT_Init_FreeType(&value);
if (status != 0) {
std::cerr << "failed to open freetype library" << std::endl;
exit (EXIT_FAILURE);
}
FT_Face face;
status = FT_New_Face (value, filename, 0, &face);
if (status != 0) {
std::cerr << "Error opening font file " << filename << std::endl;
exit (EXIT_FAILURE);
}
font = cairo_ft_font_face_create_for_ft_face (face, 0);
cairo_set_source_rgb(cr, 1.0, 1.0, 1.0); /* blank to white */
cairo_set_font_size(cr, font_size);
cairo_set_font_face(cr, font);
animation.dy = -5;
animation.target_y = hidden_height - height;
animation.start_y = 0;
animation.current_y = animation.start_y;
repaint_callback = nullptr;
render_frame();
//wayfire_shell_reserve(display.wfshell, output, WAYFIRE_SHELL_PANEL_POSITION_UP, width, hidden_height);
wayfire_shell_add_panel(display.wfshell, output, window->surface);
window->pointer_enter = std::bind(std::mem_fn(&wayfire_panel::on_enter), this);
window->pointer_leave = std::bind(std::mem_fn(&wayfire_panel::on_leave), this);
}
void wayfire_panel::toggle_animation()
{
std::swap(animation.target_y, animation.start_y);
animation.dy *= -1;
}
void wayfire_panel::on_enter()
{
toggle_animation();
add_callback(false);
}
void wayfire_panel::on_leave()
{
toggle_animation();
}
void render_rounded_rectangle(cairo_t *cr, int x, int y, int width, int height, double radius,
double r, double g, double b, double a)
{
double degrees = M_PI / 180.0;
cairo_new_sub_path (cr);
cairo_arc (cr, x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees);
cairo_arc (cr, x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees);
cairo_arc (cr, x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees);
cairo_arc (cr, x + radius, y + radius, radius, 180 * degrees, 270 * degrees);
cairo_close_path (cr);
cairo_set_source_rgba(cr, r, g, b, a);
cairo_fill_preserve(cr);
}
void wayfire_panel::add_callback(bool swapped)
{
if (repaint_callback)
wl_callback_destroy(repaint_callback);
repaint_callback = wl_surface_frame(window->surface);
wl_callback_add_listener(repaint_callback, &frame_listener, this);
if (!swapped)
wl_surface_commit(window->surface);
}
const std::string months[] = {
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
void wayfire_panel::render_frame()
{
set_active_window(window);
using std::chrono::system_clock;
time_t now = system_clock::to_time_t(system_clock::now());
auto time = std::localtime(&now);
std::string time_string = std::to_string(time->tm_mday) + " " +
months[time->tm_mon] + " " + std::to_string(time->tm_hour) +
":" + std::to_string(time->tm_min);
if (animation.current_y != animation.target_y) {
animation.current_y += animation.dy;
wayfire_shell_configure_panel(display.wfshell, output,
window->surface, 0, animation.current_y);
}
bool should_swap = false;
if (time_string != this->current_text && animation.current_y > hidden_height - (int)height) {
render_rounded_rectangle(cr, 0, 0, width, height, 7, 0.117, 0.137, 0.152, 1);
cairo_text_extents_t te;
cairo_text_extents(cr, time_string.c_str(), &te);
double x = 5, y = 20;
cairo_set_source_rgb(cr, 0.91, 0.918, 0.965); /* blank to white */
x = (width - te.width) / 2;
cairo_move_to(cr, x, y);
cairo_show_text(cr, time_string.c_str());
should_swap = true;
}
current_text = time_string;
//std::cout << animation.current_y << std::endl;
if (animation.current_y != hidden_height - (int)height)
add_callback(should_swap);
if (should_swap)
cairo_gl_surface_swapbuffers(window->cairo_surface);
}
<|endoftext|> |
<commit_before>#include "shaderlab/Node.h"
#include "shaderlab/PinType.h"
#include "shaderlab/ShaderAdapter.h"
#include <blueprint/Pin.h>
#include <blueprint/BackendAdapter.h>
#include <blueprint/PropDescImpl.h>
#include <shadergraph/VarType.h>
#include <shadergraph/Variant.h>
#include <shadergraph/ValueImpl.h>
#include <shadergraph/Block.h>
namespace
{
auto back2front = [](const dag::Node<shadergraph::Variant>::Port& back) -> bp::PinDesc
{
bp::PinDesc front;
front.type = shaderlab::ShaderAdapter::TypeBackToFront(back.var.type.type, 1);
const_cast<shadergraph::Block::Port&>(back).var.full_name = back.var.type.name;
front.name = back.var.full_name;
return front;
};
}
namespace shaderlab
{
Node::Node(const std::string& title)
: bp::Node(title)
{
}
void Node::Init(const shadergraph::Block& block)
{
// pins
bp::BackendAdapter<shadergraph::Variant>
trans("shadergraph", back2front);
trans.InitNodePins(*this, block);
// props
InitProps(block.GetVariants());
}
void Node::Init(const std::string& name)
{
// pins
bp::BackendAdapter<shadergraph::Variant>
trans("shadergraph", back2front);
trans.InitNodePins(*this, name);
// props
rttr::type t = rttr::type::get_by_name("shadergraph::" + name);
if (t.is_valid())
{
rttr::variant var = t.create();
assert(var.is_valid());
auto method_vars = t.get_method("GetVariants");
assert(method_vars.is_valid());
auto var_vars = method_vars.invoke(var);
assert(var_vars.is_valid()
&& var_vars.is_type<std::vector<shadergraph::Variant>>());
auto& vars = var_vars.get_value<std::vector<shadergraph::Variant>>();
InitProps(vars);
}
}
void Node::InitProps(const std::vector<shadergraph::Variant>& vars)
{
for (auto& v : vars)
{
if (v.type != shadergraph::VarType::Uniform) {
continue;
}
bp::Variant var;
var.name = v.name;
auto u_var = std::static_pointer_cast<shadergraph::UniformVal>(v.val)->var;
switch (u_var.type)
{
case shadergraph::VarType::Bool:
var.type = bp::VarType::Bool;
var.b = std::static_pointer_cast<shadergraph::BoolVal>(u_var.val)->x;
break;
case shadergraph::VarType::Int:
var.type = bp::VarType::Int;
var.i = std::static_pointer_cast<shadergraph::IntVal>(u_var.val)->x;
break;
case shadergraph::VarType::Float:
var.type = bp::VarType::Float;
var.f = std::static_pointer_cast<shadergraph::FloatVal>(u_var.val)->x;
break;
case shadergraph::VarType::Float2:
{
var.type = bp::VarType::Float2;
auto src = std::static_pointer_cast<shadergraph::Float2Val>(u_var.val);
memcpy(var.f2, src->xy, sizeof(var.f2));
}
break;
case shadergraph::VarType::Float3:
{
var.type = bp::VarType::Float3;
auto src = std::static_pointer_cast<shadergraph::Float3Val>(u_var.val);
memcpy(var.f3, src->xyz, sizeof(var.f3));
}
break;
case shadergraph::VarType::Float4:
{
var.type = bp::VarType::Float4;
auto src = std::static_pointer_cast<shadergraph::Float4Val>(u_var.val);
memcpy(var.f4, src->xyzw, sizeof(var.f4));
}
break;
case shadergraph::VarType::Array:
{
// todo
}
break;
default:
assert(0);
}
bp::Node::Property prop;
prop.var = var;
for (auto& d : std::static_pointer_cast<shadergraph::UniformVal>(v.val)->desc)
{
switch (d->GetType())
{
case shadergraph::ParserProp::Type::Enum:
{
auto src = std::static_pointer_cast<shadergraph::PropEnum>(d);
auto dst = std::make_shared<bp::PropEnum>();
dst->types = src->types;
prop.descs.push_back(dst);
}
break;
}
}
m_props.push_back(prop);
}
}
}<commit_msg>[FIXED] check nullptr<commit_after>#include "shaderlab/Node.h"
#include "shaderlab/PinType.h"
#include "shaderlab/ShaderAdapter.h"
#include <blueprint/Pin.h>
#include <blueprint/BackendAdapter.h>
#include <blueprint/PropDescImpl.h>
#include <shadergraph/VarType.h>
#include <shadergraph/Variant.h>
#include <shadergraph/ValueImpl.h>
#include <shadergraph/Block.h>
namespace
{
auto back2front = [](const dag::Node<shadergraph::Variant>::Port& back) -> bp::PinDesc
{
bp::PinDesc front;
front.type = shaderlab::ShaderAdapter::TypeBackToFront(back.var.type.type, 1);
const_cast<shadergraph::Block::Port&>(back).var.full_name = back.var.type.name;
front.name = back.var.full_name;
return front;
};
}
namespace shaderlab
{
Node::Node(const std::string& title)
: bp::Node(title)
{
}
void Node::Init(const shadergraph::Block& block)
{
// pins
bp::BackendAdapter<shadergraph::Variant>
trans("shadergraph", back2front);
trans.InitNodePins(*this, block);
// props
InitProps(block.GetVariants());
}
void Node::Init(const std::string& name)
{
// pins
bp::BackendAdapter<shadergraph::Variant>
trans("shadergraph", back2front);
trans.InitNodePins(*this, name);
// props
rttr::type t = rttr::type::get_by_name("shadergraph::" + name);
if (t.is_valid())
{
rttr::variant var = t.create();
assert(var.is_valid());
auto method_vars = t.get_method("GetVariants");
assert(method_vars.is_valid());
auto var_vars = method_vars.invoke(var);
assert(var_vars.is_valid()
&& var_vars.is_type<std::vector<shadergraph::Variant>>());
auto& vars = var_vars.get_value<std::vector<shadergraph::Variant>>();
InitProps(vars);
}
}
void Node::InitProps(const std::vector<shadergraph::Variant>& vars)
{
for (auto& v : vars)
{
if (v.type != shadergraph::VarType::Uniform) {
continue;
}
bp::Variant var;
var.name = v.name;
auto u_var = std::static_pointer_cast<shadergraph::UniformVal>(v.val)->var;
switch (u_var.type)
{
case shadergraph::VarType::Bool:
var.type = bp::VarType::Bool;
if (u_var.val) {
var.b = std::static_pointer_cast<shadergraph::BoolVal>(u_var.val)->x;
}
break;
case shadergraph::VarType::Int:
var.type = bp::VarType::Int;
if (u_var.val) {
var.i = std::static_pointer_cast<shadergraph::IntVal>(u_var.val)->x;
}
break;
case shadergraph::VarType::Float:
var.type = bp::VarType::Float;
if (u_var.val) {
var.f = std::static_pointer_cast<shadergraph::FloatVal>(u_var.val)->x;
}
break;
case shadergraph::VarType::Float2:
{
var.type = bp::VarType::Float2;
if (u_var.val) {
auto src = std::static_pointer_cast<shadergraph::Float2Val>(u_var.val);
memcpy(var.f2, src->xy, sizeof(var.f2));
}
}
break;
case shadergraph::VarType::Float3:
{
var.type = bp::VarType::Float3;
if (u_var.val) {
auto src = std::static_pointer_cast<shadergraph::Float3Val>(u_var.val);
memcpy(var.f3, src->xyz, sizeof(var.f3));
}
}
break;
case shadergraph::VarType::Float4:
{
var.type = bp::VarType::Float4;
if (u_var.val) {
auto src = std::static_pointer_cast<shadergraph::Float4Val>(u_var.val);
memcpy(var.f4, src->xyzw, sizeof(var.f4));
}
}
break;
case shadergraph::VarType::Array:
{
// todo
}
break;
default:
assert(0);
}
bp::Node::Property prop;
prop.var = var;
for (auto& d : std::static_pointer_cast<shadergraph::UniformVal>(v.val)->desc)
{
switch (d->GetType())
{
case shadergraph::ParserProp::Type::Enum:
{
auto src = std::static_pointer_cast<shadergraph::PropEnum>(d);
auto dst = std::make_shared<bp::PropEnum>();
dst->types = src->types;
prop.descs.push_back(dst);
}
break;
}
}
m_props.push_back(prop);
}
}
}<|endoftext|> |
<commit_before>///
/// @file CpuInfo.cpp
/// @brief Get the CPUs cache sizes in bytes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/CpuInfo.hpp>
#include <cstddef>
#include <string>
#include <vector>
#if defined(_WIN32)
#include <windows.h>
#elif defined(__APPLE__)
#include <sys/types.h>
#include <sys/sysctl.h>
#else // all other OSes
#include <array>
#include <cstdio>
#include <memory>
using namespace std;
namespace {
string getCacheStr(const char* filename)
{
shared_ptr<FILE> file(
fopen(filename, "r"), fclose);
array<char, 64> buffer;
string cacheStr;
if (file)
{
while (!feof(file.get()))
{
if (fgets(buffer.data(), buffer.size(), file.get()))
cacheStr += buffer.data();
}
}
return cacheStr;
}
size_t getCacheSize(const char* filename)
{
size_t cacheSize = 0;
string cacheStr = getCacheStr(filename);
size_t pos = cacheStr.find_first_of("0123456789");
if (pos != string::npos)
{
// first character after number
size_t idx = 0;
cacheSize = stol(cacheStr.substr(pos), &idx);
if (idx < cacheStr.size())
{
// Last character may be:
// 'K' = kilobytes
// 'M' = megabytes
// 'G' = gigabytes
if (cacheStr[idx] == 'K')
cacheSize *= 1024;
if (cacheStr[idx] == 'M')
cacheSize *= 1024 * 1024;
if (cacheStr[idx] == 'G')
cacheSize *= 1024 * 1024 * 1024;
}
}
return cacheSize;
}
} // namespace
#endif
using namespace std;
namespace primesieve {
CpuInfo::CpuInfo()
: l1CacheSize_(0),
l2CacheSize_(0),
l3CacheSize_(0)
{
initCache();
}
size_t CpuInfo::l1CacheSize() const
{
return l1CacheSize_;
}
size_t CpuInfo::l2CacheSize() const
{
return l2CacheSize_;
}
size_t CpuInfo::l3CacheSize() const
{
return l3CacheSize_;
}
#if defined(__APPLE__)
void CpuInfo::initCache()
{
size_t l1Length = sizeof(l1CacheSize_);
size_t l2Length = sizeof(l2CacheSize_);
size_t l3Length = sizeof(l3CacheSize_);
sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0);
sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0);
sysctlbyname("hw.l3cachesize" , &l3CacheSize_, &l3Length, NULL, 0);
}
#elif defined(_WIN32)
typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
void CpuInfo::initCache()
{
LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
if (glpi)
{
DWORD bytes = 0;
glpi(0, &bytes);
size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);
glpi(info.data(), &bytes);
for (size_t i = 0; i < size; i++)
{
if (info[i].Relationship == RelationCache)
{
if (info[i].Cache.Level == 1)
l1CacheSize_ = info[i].Cache.Size;
if (info[i].Cache.Level == 2)
l2CacheSize_ = info[i].Cache.Size;
if (info[i].Cache.Level == 3)
l3CacheSize_ = info[i].Cache.Size;
}
}
}
}
#else
/// This works on Linux, we also use this for
/// all unkown OSes, it might work.
///
void CpuInfo::initCache()
{
l1CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index0/size");
l2CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index2/size");
l3CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index3/size");
}
#endif
/// Singleton
const CpuInfo cpuInfo;
} // namespace
<commit_msg>Use __has_include on macOS<commit_after>///
/// @file CpuInfo.cpp
/// @brief Get the CPUs cache sizes in bytes.
///
/// Copyright (C) 2017 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/CpuInfo.hpp>
#include <cstddef>
#include <string>
#include <vector>
#if defined(__APPLE__) && \
(!defined(__has_include) || \
(__has_include(<sys/types.h>) && \
__has_include(<sys/sysctl.h>)))
#define APPLE_SYSCTL
#endif
#if defined(_WIN32)
#include <windows.h>
#elif defined(APPLE_SYSCTL)
#include <sys/types.h>
#include <sys/sysctl.h>
#else // all other OSes
#include <array>
#include <cstdio>
#include <memory>
using namespace std;
namespace {
string getCacheStr(const char* filename)
{
shared_ptr<FILE> file(
fopen(filename, "r"), fclose);
array<char, 64> buffer;
string cacheStr;
if (file)
{
while (!feof(file.get()))
{
if (fgets(buffer.data(), buffer.size(), file.get()))
cacheStr += buffer.data();
}
}
return cacheStr;
}
size_t getCacheSize(const char* filename)
{
size_t cacheSize = 0;
string cacheStr = getCacheStr(filename);
size_t pos = cacheStr.find_first_of("0123456789");
if (pos != string::npos)
{
// first character after number
size_t idx = 0;
cacheSize = stol(cacheStr.substr(pos), &idx);
if (idx < cacheStr.size())
{
// Last character may be:
// 'K' = kilobytes
// 'M' = megabytes
// 'G' = gigabytes
if (cacheStr[idx] == 'K')
cacheSize *= 1024;
if (cacheStr[idx] == 'M')
cacheSize *= 1024 * 1024;
if (cacheStr[idx] == 'G')
cacheSize *= 1024 * 1024 * 1024;
}
}
return cacheSize;
}
} // namespace
#endif
using namespace std;
namespace primesieve {
CpuInfo::CpuInfo()
: l1CacheSize_(0),
l2CacheSize_(0),
l3CacheSize_(0)
{
initCache();
}
size_t CpuInfo::l1CacheSize() const
{
return l1CacheSize_;
}
size_t CpuInfo::l2CacheSize() const
{
return l2CacheSize_;
}
size_t CpuInfo::l3CacheSize() const
{
return l3CacheSize_;
}
#if defined(APPLE_SYSCTL)
void CpuInfo::initCache()
{
size_t l1Length = sizeof(l1CacheSize_);
size_t l2Length = sizeof(l2CacheSize_);
size_t l3Length = sizeof(l3CacheSize_);
sysctlbyname("hw.l1dcachesize", &l1CacheSize_, &l1Length, NULL, 0);
sysctlbyname("hw.l2cachesize" , &l2CacheSize_, &l2Length, NULL, 0);
sysctlbyname("hw.l3cachesize" , &l3CacheSize_, &l3Length, NULL, 0);
}
#elif defined(_WIN32)
typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD);
void CpuInfo::initCache()
{
LPFN_GLPI glpi = (LPFN_GLPI) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
if (glpi)
{
DWORD bytes = 0;
glpi(0, &bytes);
size_t size = bytes / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
vector<SYSTEM_LOGICAL_PROCESSOR_INFORMATION> info(size);
glpi(info.data(), &bytes);
for (size_t i = 0; i < size; i++)
{
if (info[i].Relationship == RelationCache)
{
if (info[i].Cache.Level == 1)
l1CacheSize_ = info[i].Cache.Size;
if (info[i].Cache.Level == 2)
l2CacheSize_ = info[i].Cache.Size;
if (info[i].Cache.Level == 3)
l3CacheSize_ = info[i].Cache.Size;
}
}
}
}
#else
/// This works on Linux, we also use this for
/// all unkown OSes, it might work.
///
void CpuInfo::initCache()
{
l1CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index0/size");
l2CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index2/size");
l3CacheSize_ = getCacheSize("/sys/devices/system/cpu/cpu0/cache/index3/size");
}
#endif
/// Singleton
const CpuInfo cpuInfo;
} // namespace
<|endoftext|> |
<commit_before>#include "ball.h"
#include <nds.h>
/**
* @param ball b
* @return void
*/
void moveBall(ball *b) {
b.box.pos.x += b.direction.x;
b.box.pos.y += b.direction.y;
// horizontal collision
if (b.box.pos.x <= 0 || b.box.pos.x >= SCREEN_WIDTH) {
b.direction.x *= -1;
}
// vertical collision
if (b.box.pos.y <= 0 || b.box.pos.y >= SCREEN_HEIGHT) {
b.direction.y *= -1;
}
}
<commit_msg>fixed pointer-issue<commit_after>#include "ball.h"
#include <nds.h>
/**
* @param ball b
* @return void
*/
void moveBall(ball *b) {
b->box.pos.x += b->direction.x;
b->box.pos.y += b->direction.y;
// horizontal collision
if (b->box.pos.x <= 0 || b->box.pos.x >= SCREEN_WIDTH) {
b->direction.x *= -1;
}
// vertical collision
if (b->box.pos.y <= 0 || b->box.pos.y >= SCREEN_HEIGHT) {
b->direction.y *= -1;
}
}
<|endoftext|> |
<commit_before>#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "guiutil.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include <QApplication>
#include <QClipboard>
#include <QMessageBox>
#include <QLocale>
#include <QDebug>
#include <QMessageBox>
SendCoinsDialog::SendCoinsDialog(QWidget *parent, const QString &address) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->payTo->setPlaceholderText(tr("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
GUIUtil::setupAddressWidget(ui->payTo, this);
// Set initial send-to address if provided
if(!address.isEmpty())
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
bool valid;
QString payAmount = ui->payAmount->text();
QString label;
qint64 payAmountParsed;
valid = GUIUtil::parseMoney(payAmount, &payAmountParsed);
if(!valid || payAmount.isEmpty())
{
QMessageBox::warning(this, tr("Send Coins"),
tr("Must fill in an amount to pay."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
// Add address to address book under label, if specified
label = ui->addAsLabel->text();
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1 BTC to %2 (%3)?").arg(GUIUtil::formatMoney(payAmountParsed), label, ui->payTo->text()),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
return;
}
switch(model->sendCoins(ui->payTo->text(), payAmountParsed, label))
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recepient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
ui->payTo->setFocus();
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
ui->payAmount->setFocus();
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("Amount exceeds your balance"),
QMessageBox::Ok, QMessageBox::Ok);
ui->payAmount->setFocus();
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("Total exceeds your balance when the %1 transaction fee is included").
arg(GUIUtil::formatMoney(model->getOptionsModel()->getTransactionFee())),
QMessageBox::Ok, QMessageBox::Ok);
ui->payAmount->setFocus();
break;
case WalletModel::OK:
accept();
break;
}
}
void SendCoinsDialog::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsDialog::on_addressBookButton_clicked()
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsDialog::on_buttonBox_rejected()
{
reject();
}
void SendCoinsDialog::on_payTo_textChanged(const QString &address)
{
ui->addAsLabel->setText(model->labelForAddress(address));
}
void SendCoinsDialog::clear()
{
ui->payTo->setText(QString());
ui->addAsLabel->setText(QString());
ui->payAmount->setText(QString());
ui->payTo->setFocus();
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
<commit_msg>send coins dialog: make sure send button remain default button (triggered with enter)<commit_after>#include "sendcoinsdialog.h"
#include "ui_sendcoinsdialog.h"
#include "walletmodel.h"
#include "guiutil.h"
#include "addressbookpage.h"
#include "optionsmodel.h"
#include <QApplication>
#include <QClipboard>
#include <QMessageBox>
#include <QLocale>
#include <QDebug>
#include <QMessageBox>
SendCoinsDialog::SendCoinsDialog(QWidget *parent, const QString &address) :
QDialog(parent),
ui(new Ui::SendCoinsDialog),
model(0)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->payTo->setPlaceholderText(tr("Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)"));
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
GUIUtil::setupAddressWidget(ui->payTo, this);
// Set initial send-to address if provided
if(!address.isEmpty())
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
}
void SendCoinsDialog::setModel(WalletModel *model)
{
this->model = model;
}
SendCoinsDialog::~SendCoinsDialog()
{
delete ui;
}
void SendCoinsDialog::on_sendButton_clicked()
{
bool valid;
QString payAmount = ui->payAmount->text();
QString label;
qint64 payAmountParsed;
valid = GUIUtil::parseMoney(payAmount, &payAmountParsed);
if(!valid || payAmount.isEmpty())
{
QMessageBox::warning(this, tr("Send Coins"),
tr("Must fill in an amount to pay."),
QMessageBox::Ok, QMessageBox::Ok);
return;
}
// Add address to address book under label, if specified
label = ui->addAsLabel->text();
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
tr("Are you sure you want to send %1 BTC to %2 (%3)?").arg(GUIUtil::formatMoney(payAmountParsed), label, ui->payTo->text()),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval != QMessageBox::Yes)
{
return;
}
switch(model->sendCoins(ui->payTo->text(), payAmountParsed, label))
{
case WalletModel::InvalidAddress:
QMessageBox::warning(this, tr("Send Coins"),
tr("The recepient address is not valid, please recheck."),
QMessageBox::Ok, QMessageBox::Ok);
ui->payTo->setFocus();
break;
case WalletModel::InvalidAmount:
QMessageBox::warning(this, tr("Send Coins"),
tr("The amount to pay must be larger than 0."),
QMessageBox::Ok, QMessageBox::Ok);
ui->payAmount->setFocus();
break;
case WalletModel::AmountExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("Amount exceeds your balance"),
QMessageBox::Ok, QMessageBox::Ok);
ui->payAmount->setFocus();
break;
case WalletModel::AmountWithFeeExceedsBalance:
QMessageBox::warning(this, tr("Send Coins"),
tr("Total exceeds your balance when the %1 transaction fee is included").
arg(GUIUtil::formatMoney(model->getOptionsModel()->getTransactionFee())),
QMessageBox::Ok, QMessageBox::Ok);
ui->payAmount->setFocus();
break;
case WalletModel::OK:
accept();
break;
}
}
void SendCoinsDialog::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsDialog::on_addressBookButton_clicked()
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsDialog::on_buttonBox_rejected()
{
reject();
}
void SendCoinsDialog::on_payTo_textChanged(const QString &address)
{
ui->addAsLabel->setText(model->labelForAddress(address));
}
void SendCoinsDialog::clear()
{
ui->payTo->setText(QString());
ui->addAsLabel->setText(QString());
ui->payAmount->setText(QString());
ui->payTo->setFocus();
ui->sendButton->setDefault(true);
}
void SendCoinsDialog::reject()
{
clear();
}
void SendCoinsDialog::accept()
{
clear();
}
<|endoftext|> |
<commit_before>#include "icg_common.h"
#include "trackball/trackball.h"
#include "grid/grid.h"
#include "framebuffer/FrameBuffer.h"
#include "fullscreenquad/FullScreenQuad.h"
#ifdef WITH_ANTTWEAKBAR
#include <AntTweakBar.h>
TwBar *bar;
#endif
using namespace std;
Grid grid;
int WIDTH = 800;
int HEIGHT = 600;
mat4 projection_matrix;
mat4 view_matrix;
mat4 trackball_matrix;
Trackball trackball;
// Texture for noise
GLuint height_map;
// Texture for color
GLuint color;
const float HEIGHT_MAP_HEIGHT = 300;
const float HEIGHT_MAP_WIDTH = 300;
FrameBuffer fb(WIDTH, HEIGHT);
FullScreenQuad fullScreenQuad;
// Constants
const float kZoomFactor = 2;
// Used to store old values in computation
mat4 old_trackball_matrix;
mat4 old_view_matrix;
float zoom_start_y;
mat4 OrthographicProjection(float left, float right, float bottom, float top, float near, float far){
assert(right > left);
assert(far > near);
assert(top > bottom);
mat4 ortho = mat4::Zero();
ortho(0, 0) = 2.0f / (right - left);
ortho(1, 1) = 2.0f / (top - bottom);
ortho(2, 2) = -2.0f / (far - near);
ortho(3, 3) = 1.0f;
ortho(1, 3) = -(right + left) / (right - left);
ortho(2, 3) = -(top + bottom) / (top - bottom);
ortho(2, 3) = -(far + near) / (far - near);
return ortho;
}
mat4 PerspectiveProjection(float fovy, float aspect, float near, float far){
mat4 projection = mat4::Identity();
float top = near * tan(1.0f / 2.0f * fovy);
float right = aspect * top;
projection <<
near / right, 0.0f, 0.0f, 0.0f,
0.0f, near / top, 0.0f, 0.0f,
0.0f, 0.0f, (far + near) / (near - far), 2 * far*near / (near - far),
0.0f, 0.0f, -1.0f, 0.0f;
return projection;
}
mat4 LookAt(vec3 eye, vec3 center, vec3 up) {
vec3 z_cam = (eye - center).normalized();
vec3 x_cam = up.cross(z_cam).normalized();
vec3 y_cam = z_cam.cross(x_cam);
mat3 R;
R.col(0) = x_cam;
R.col(1) = y_cam;
R.col(2) = z_cam;
mat4 look_at = mat4::Zero();
look_at.block(0, 0, 3, 3) = R.transpose();
look_at(3, 3) = 1.0f;
look_at.block(0, 3, 3, 1) = -R.transpose() * (eye);
return look_at;
}
// Gets called when the windows is resized.
void resize_callback(int width, int height) {
WIDTH = width;
HEIGHT = height;
std::cout << "Window has been resized to " << WIDTH << "x" << HEIGHT << "." << std::endl;
glViewport(0, 0, WIDTH, HEIGHT);
GLfloat top = 1.0f;
GLfloat right = (GLfloat)WIDTH / HEIGHT * top;
//projection_matrix = OrthographicProjection(-right, right, -top, top, -10.0, 10.0f);
projection_matrix = PerspectiveProjection(45.0f, (GLfloat)WIDTH / HEIGHT, 0.1f, 100.0f);
}
void init(){
// Sets background color.
glClearColor(/*gray*/ .937, .937, .937, /*solid*/1.0);
// Enable depth test.
glEnable(GL_DEPTH_TEST);
// view_matrix = LookAt(vec3(2.0f, 2.0f, 4.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
view_matrix = Eigen::Affine3f(Eigen::Translation3f(0.0f, 0.0f, -4.0f)).matrix();
trackball_matrix = mat4::Identity();
height_map = fb.init();
//GLuint color;
// Initialize height_map properties
glGenTextures(1, &color);
glBindTexture(GL_TEXTURE_2D, color);
glfwLoadTexture2D("grid/texture1D.tga", 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
grid.init();
// Create fullScreenQuad on which we'll draw the noise
fullScreenQuad.init();
check_error_gl();
}
// Gets called for every frame.
void display(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw a quad on the ground.
mat4 quad_model_matrix = mat4::Identity();
///--- Render to FB
fb.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
fullScreenQuad.draw();
fb.unbind();
glViewport(0, 0, WIDTH, HEIGHT);
grid.setColor(&color);
grid.setHeightMap(&height_map);
grid.draw(trackball_matrix * quad_model_matrix, view_matrix, projection_matrix);
}
void cleanup(){
#ifdef WITH_ANTTWEAKBAR
TwTerminate();
#endif
}
// Transforms glfw screen coordinates into normalized OpenGL coordinates.
vec2 transform_screen_coords(int x, int y) {
return vec2(2.0f * (float)x / WIDTH - 1.0f,
1.0f - 2.0f * (float)y / HEIGHT);
}
void mouse_button(int button, int action) {
// Rotation
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
int x_i, y_i;
glfwGetMousePos(&x_i, &y_i);
vec2 p = transform_screen_coords(x_i, y_i);
trackball.begin_drag(p.x(), p.y());
// Store the current state of the model matrix.
old_trackball_matrix = trackball_matrix;
}
// Zoom
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
// Get 2-d vector of the mouse position on screen in range [-1, 1]
int x_i, y_i;
glfwGetMousePos(&x_i, &y_i);
vec2 p = transform_screen_coords(x_i, y_i);
// Store y value & current state of the view matrix
zoom_start_y = p[1];
old_view_matrix = view_matrix;
}
}
void mouse_pos(int x, int y) {
// Rotation
if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
vec2 p = transform_screen_coords(x, y);
// Compute the new trackball_matrix
trackball_matrix = trackball.drag(p[0], p[1]) * old_trackball_matrix;
}
// Zoom
if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) {
// Get position on screen
vec2 p = transform_screen_coords(x, y);
// Zoom proportional to the distance
float zoom = p[1] - zoom_start_y;
// Apply it to translate the view matrix along the z-axis
view_matrix = old_view_matrix * Eigen::Affine3f(Eigen::Translation3f(vec3(0.0f, 0.0f, zoom))).matrix();
}
}
int main(int, char**){
glfwInitWindowSize(WIDTH, HEIGHT);
glfwCreateWindow("Trackball");
glfwDisplayFunc(display);
glfwSetWindowSizeCallback(&resize_callback);
glfwSetMouseButtonCallback(mouse_button);
glfwSetMousePosCallback(mouse_pos);
init();
glfwMainLoop();
cleanup();
return EXIT_SUCCESS;
}
<commit_msg>twbar<commit_after>#include "icg_common.h"
#include "trackball/trackball.h"
#include "grid/grid.h"
#include "framebuffer/FrameBuffer.h"
#include "fullscreenquad/FullScreenQuad.h"
#ifdef WITH_ANTTWEAKBAR
#include <AntTweakBar.h>
TwBar *bar;
#endif
using namespace std;
Grid grid;
int WIDTH = 800;
int HEIGHT = 600;
mat4 projection_matrix;
mat4 view_matrix;
mat4 trackball_matrix;
Trackball trackball;
// Texture for noise
GLuint height_map;
// Texture for color
GLuint color;
const float HEIGHT_MAP_HEIGHT = 300;
const float HEIGHT_MAP_WIDTH = 300;
FrameBuffer fb(WIDTH, HEIGHT);
FullScreenQuad fullScreenQuad;
// Constants
const float kZoomFactor = 2;
// Used to store old values in computation
mat4 old_trackball_matrix;
mat4 old_view_matrix;
float zoom_start_y;
mat4 OrthographicProjection(float left, float right, float bottom, float top, float near, float far){
assert(right > left);
assert(far > near);
assert(top > bottom);
mat4 ortho = mat4::Zero();
ortho(0, 0) = 2.0f / (right - left);
ortho(1, 1) = 2.0f / (top - bottom);
ortho(2, 2) = -2.0f / (far - near);
ortho(3, 3) = 1.0f;
ortho(1, 3) = -(right + left) / (right - left);
ortho(2, 3) = -(top + bottom) / (top - bottom);
ortho(2, 3) = -(far + near) / (far - near);
return ortho;
}
mat4 PerspectiveProjection(float fovy, float aspect, float near, float far){
mat4 projection = mat4::Identity();
float top = near * tan(1.0f / 2.0f * fovy);
float right = aspect * top;
projection <<
near / right, 0.0f, 0.0f, 0.0f,
0.0f, near / top, 0.0f, 0.0f,
0.0f, 0.0f, (far + near) / (near - far), 2 * far*near / (near - far),
0.0f, 0.0f, -1.0f, 0.0f;
return projection;
}
mat4 LookAt(vec3 eye, vec3 center, vec3 up) {
vec3 z_cam = (eye - center).normalized();
vec3 x_cam = up.cross(z_cam).normalized();
vec3 y_cam = z_cam.cross(x_cam);
mat3 R;
R.col(0) = x_cam;
R.col(1) = y_cam;
R.col(2) = z_cam;
mat4 look_at = mat4::Zero();
look_at.block(0, 0, 3, 3) = R.transpose();
look_at(3, 3) = 1.0f;
look_at.block(0, 3, 3, 1) = -R.transpose() * (eye);
return look_at;
}
// Gets called when the windows is resized.
void resize_callback(int width, int height) {
WIDTH = width;
HEIGHT = height;
std::cout << "Window has been resized to " << WIDTH << "x" << HEIGHT << "." << std::endl;
glViewport(0, 0, WIDTH, HEIGHT);
GLfloat top = 1.0f;
GLfloat right = (GLfloat)WIDTH / HEIGHT * top;
//projection_matrix = OrthographicProjection(-right, right, -top, top, -10.0, 10.0f);
projection_matrix = PerspectiveProjection(45.0f, (GLfloat)WIDTH / HEIGHT, 0.1f, 100.0f);
}
void init(){
// Sets background color.
glClearColor(/*gray*/ .937, .937, .937, /*solid*/1.0);
// Enable depth test.
glEnable(GL_DEPTH_TEST);
// view_matrix = LookAt(vec3(2.0f, 2.0f, 4.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
view_matrix = Eigen::Affine3f(Eigen::Translation3f(0.0f, 0.0f, -4.0f)).matrix();
trackball_matrix = mat4::Identity();
height_map = fb.init();
//GLuint color;
// Initialize height_map properties
glGenTextures(1, &color);
glBindTexture(GL_TEXTURE_2D, color);
glfwLoadTexture2D("grid/texture1D.tga", 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
grid.init();
// Create fullScreenQuad on which we'll draw the noise
fullScreenQuad.init();
// Dummy variables that will be deleted and replaced by the ones used
// in our program
int a = 0;
bool vs = true;
bool gs = true;
bool fs = true;
float scale = 1.5f;
#ifdef WITH_ANTTWEAKBAR
// Noise
typedef enum { PERLIN, PERLIN2, PERLIN3, PERLIN4 } Noises;
Noises noise = PERLIN;
TwEnumVal noisesEV[] = { { PERLIN, "PERLIN" }, { PERLIN2, "PERLIN2" }, { PERLIN3, "PERLIN3" }, { PERLIN4, "PERLIN4" } };
TwType noiseType;
// Texture
typedef enum { TEXTURE, TEXTURE2, TEXTURE3, TEXTURE4 } Textures;
Textures texture = TEXTURE;
TwEnumVal texturesEV[] = { { TEXTURE, "TEXTURE" }, { TEXTURE2, "TEXTURE2" }, { TEXTURE3, "TEXTURE3" }, { TEXTURE4, "TEXTURE4" } };
TwType textureType;
TwInit(TW_OPENGL_CORE, NULL);
TwWindowSize(WIDTH, HEIGHT);
bar = TwNewBar("Settings");
TwAddVarRW(bar, "vs", TW_TYPE_BOOLCPP, &vs, " group='Shaders' label='vertex' key=v help='Toggle vertex shader.' ");
TwAddVarRW(bar, "gs", TW_TYPE_BOOLCPP, &gs, " group='Shaders' label='geometry' key=g help='Toggle geometry shader.' ");
TwAddVarRW(bar, "fs", TW_TYPE_BOOLCPP, &fs, " group='Shaders' label='fragment' key=f help='Toggle fragment shader.' ");
TwAddVarRW(bar, "scale", TW_TYPE_FLOAT, &scale, " min=0 max=100 step=0.5 label='Height scale' ");
noiseType = TwDefineEnum("NoiseType", noisesEV, 4);
TwAddVarRW(bar, "Noise", noiseType, &noise, NULL);
textureType = TwDefineEnum("TextureType", texturesEV, 4);
TwAddVarRW(bar, "Texture", textureType, &texture, NULL);
// Callbacks are handled by the functions OnMousePos, OnMouseButton, etc...
#endif
//check_error_gl();
}
// Gets called for every frame.
void display(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Draw a quad on the ground.
mat4 quad_model_matrix = mat4::Identity();
///--- Render to FB
fb.bind();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
fullScreenQuad.draw();
fb.unbind();
glViewport(0, 0, WIDTH, HEIGHT);
grid.setColor(&color);
grid.setHeightMap(&height_map);
grid.draw(trackball_matrix * quad_model_matrix, view_matrix, projection_matrix);
#ifdef WITH_ANTTWEAKBAR
TwDraw();
#endif
}
void cleanup(){
#ifdef WITH_ANTTWEAKBAR
TwTerminate();
#endif
}
// Transforms glfw screen coordinates into normalized OpenGL coordinates.
vec2 transform_screen_coords(int x, int y) {
return vec2(2.0f * (float)x / WIDTH - 1.0f,
1.0f - 2.0f * (float)y / HEIGHT);
}
void mouse_button(int button, int action) {
// Rotation
if (button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
int x_i, y_i;
glfwGetMousePos(&x_i, &y_i);
vec2 p = transform_screen_coords(x_i, y_i);
trackball.begin_drag(p.x(), p.y());
// Store the current state of the model matrix.
old_trackball_matrix = trackball_matrix;
}
// Zoom
if (button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS) {
// Get 2-d vector of the mouse position on screen in range [-1, 1]
int x_i, y_i;
glfwGetMousePos(&x_i, &y_i);
vec2 p = transform_screen_coords(x_i, y_i);
// Store y value & current state of the view matrix
zoom_start_y = p[1];
old_view_matrix = view_matrix;
}
}
void mouse_pos(int x, int y) {
// Rotation
if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) {
vec2 p = transform_screen_coords(x, y);
// Compute the new trackball_matrix
trackball_matrix = trackball.drag(p[0], p[1]) * old_trackball_matrix;
}
// Zoom
if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS) {
// Get position on screen
vec2 p = transform_screen_coords(x, y);
// Zoom proportional to the distance
float zoom = p[1] - zoom_start_y;
// Apply it to translate the view matrix along the z-axis
view_matrix = old_view_matrix * Eigen::Affine3f(Eigen::Translation3f(vec3(0.0f, 0.0f, zoom))).matrix();
}
}
// Callback function called by GLFW when a mouse button is clicked
void GLFWCALL OnMouseButton(int glfwButton, int glfwAction)
{
if (!TwEventMouseButtonGLFW(glfwButton, glfwAction)) // Send event to AntTweakBar
{
// Event not handled by AntTweakBar, we handle it ourselves
mouse_button(glfwButton, glfwAction);
}
}
// Callback function called by GLFW when mouse has moved
void GLFWCALL OnMousePos(int mouseX, int mouseY)
{
if (!TwEventMousePosGLFW(mouseX, mouseY)) // Send event to AntTweakBar
{
mouse_pos(mouseX, mouseY);
}
}
// Callback function called by GLFW on mouse wheel event
void GLFWCALL OnMouseWheel(int pos)
{
if (!TwEventMouseWheelGLFW(pos)) // Send event to AntTweakBar
{
// Nothing for the moment
}
}
// Callback function called by GLFW on key event
void GLFWCALL OnKey(int glfwKey, int glfwAction)
{
if (!TwEventKeyGLFW(glfwKey, glfwAction)) // Send event to AntTweakBar
{
if (glfwKey == GLFW_KEY_ESC && glfwAction == GLFW_PRESS) // Want to quit?
glfwCloseWindow();
else
{
// Nothing for the moment
}
}
}
// Callback function called by GLFW on char event
void GLFWCALL OnChar(int glfwChar, int glfwAction)
{
if (!TwEventCharGLFW(glfwChar, glfwAction)) // Send event to AntTweakBar
{
// Nothing for the moment
}
}
// Callback function called by GLFW when window size changes
void GLFWCALL OnWindowSize(int width, int height)
{
// Send the new window size to AntTweakBar
TwWindowSize(width, height);
resize_callback(width, height);
}
int main(int, char**){
glfwInitWindowSize(WIDTH, HEIGHT);
glfwCreateWindow("Terrain");
glfwDisplayFunc(display);
glfwSetWindowSizeCallback(OnWindowSize);
glfwSetMouseButtonCallback(OnMouseButton);
glfwSetMousePosCallback(OnMousePos);
glfwSetMouseWheelCallback(OnMouseWheel);
glfwSetKeyCallback(OnKey);
glfwSetCharCallback(OnChar);
init();
glfwMainLoop();
cleanup();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/* ------------------------------------------------------------------------
Windows NT Service class library
Copyright Abandoned 1998 Irena Pancirov - Irnet Snc
This file is public domain and comes with NO WARRANTY of any kind
-------------------------------------------------------------------------- */
#include <windows.h>
#include <process.h>
#include <stdio.h>
#include "nt_servc.h"
static NTService *pService;
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
NTService::NTService()
{
bOsNT = FALSE;
//service variables
ServiceName = NULL;
hExitEvent = 0;
bPause = FALSE;
bRunning = FALSE;
hThreadHandle = 0;
fpServiceThread = NULL;
//time-out variables
nStartTimeOut = 15000;
nStopTimeOut = 86400000;
nPauseTimeOut = 5000;
nResumeTimeOut = 5000;
//install variables
dwDesiredAccess = SERVICE_ALL_ACCESS;
dwServiceType = SERVICE_WIN32_OWN_PROCESS;
dwStartType = SERVICE_AUTO_START;
dwErrorControl = SERVICE_ERROR_NORMAL;
szLoadOrderGroup = NULL;
lpdwTagID = NULL;
szDependencies = NULL;
my_argc = 0;
my_argv = NULL;
hShutdownEvent = 0;
nError = 0;
dwState = 0;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
NTService::~NTService()
{
if (ServiceName != NULL) delete[] ServiceName;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::GetOS()
{
bOsNT = FALSE;
memset(&osVer, 0, sizeof(OSVERSIONINFO));
osVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&osVer))
{
if (osVer.dwPlatformId == VER_PLATFORM_WIN32_NT)
bOsNT = TRUE;
}
return bOsNT;
}
/* ------------------------------------------------------------------------
Init() Registers the main service thread with the service manager
ServiceThread - pointer to the main programs entry function
when the service is started
-------------------------------------------------------------------------- */
long NTService::Init(LPCSTR szInternName,void *ServiceThread)
{
pService = this;
fpServiceThread = (THREAD_FC)ServiceThread;
ServiceName = new char[lstrlen(szInternName)+1];
lstrcpy(ServiceName,szInternName);
SERVICE_TABLE_ENTRY stb[] =
{
{ (char *)szInternName,(LPSERVICE_MAIN_FUNCTION) ServiceMain} ,
{ NULL, NULL }
};
return StartServiceCtrlDispatcher(stb); //register with the Service Manager
}
/* ------------------------------------------------------------------------
Install() - Installs the service with Service manager
nError values:
0 success
1 Can't open the Service manager
2 Failed to create service
-------------------------------------------------------------------------- */
BOOL NTService::Install(int startType, LPCSTR szInternName,
LPCSTR szDisplayName,
LPCSTR szFullPath, LPCSTR szAccountName,
LPCSTR szPassword)
{
BOOL ret_val=FALSE;
SC_HANDLE newService, scm;
if (!SeekStatus(szInternName,1))
return FALSE;
char szFilePath[_MAX_PATH];
GetModuleFileName(NULL, szFilePath, sizeof(szFilePath));
// open a connection to the SCM
if (!(scm = OpenSCManager(0, 0,SC_MANAGER_CREATE_SERVICE)))
printf("Failed to install the service (Couldn't open the SCM)\n");
else // Install the new service
{
if (!(newService=
CreateService(scm,
szInternName,
szDisplayName,
dwDesiredAccess,//default: SERVICE_ALL_ACCESS
dwServiceType, //default: SERVICE_WIN32_OWN_PROCESS
//default: SERVICE_AUTOSTART
(startType == 1 ? SERVICE_AUTO_START :
SERVICE_DEMAND_START),
dwErrorControl, //default: SERVICE_ERROR_NORMAL
szFullPath, //exec full path
szLoadOrderGroup, //default: NULL
lpdwTagID, //default: NULL
szDependencies, //default: NULL
szAccountName, //default: NULL
szPassword))) //default: NULL
printf("Failed to install the service (Couldn't create service)\n");
else
{
printf("Service successfully installed.\n");
CloseServiceHandle(newService);
ret_val=TRUE; // Everything went ok
}
CloseServiceHandle(scm);
}
return ret_val;
}
/* ------------------------------------------------------------------------
Remove() - Removes the service
nError values:
0 success
1 Can't open the Service manager
2 Failed to locate service
3 Failed to delete service
-------------------------------------------------------------------------- */
BOOL NTService::Remove(LPCSTR szInternName)
{
BOOL ret_value=FALSE;
SC_HANDLE service, scm;
if (!SeekStatus(szInternName,0))
return FALSE;
nError=0;
// open a connection to the SCM
if (!(scm = OpenSCManager(0, 0,SC_MANAGER_CREATE_SERVICE)))
{
printf("Failed to remove the service (Couldn't open the SCM)\n");
}
else
{
if ((service = OpenService(scm,szInternName, DELETE)))
{
if (!DeleteService(service))
printf("Failed to remove the service\n");
else
{
printf("Service successfully removed.\n");
ret_value=TRUE; // everything went ok
}
CloseServiceHandle(service);
}
else
printf("Failed to remove the service (Couldn't open the service)\n");
CloseServiceHandle(scm);
}
return ret_value;
}
/* ------------------------------------------------------------------------
Stop() - this function should be called before the app. exits to stop
the service
-------------------------------------------------------------------------- */
void NTService::Stop(void)
{
SetStatus(SERVICE_STOP_PENDING,NO_ERROR, 0, 1, 60000);
StopService();
SetStatus(SERVICE_STOPPED, NO_ERROR, 0, 1, 1000);
}
/* ------------------------------------------------------------------------
ServiceMain() - This is the function that is called from the
service manager to start the service
-------------------------------------------------------------------------- */
void NTService::ServiceMain(DWORD argc, LPTSTR *argv)
{
// registration function
if (!(pService->hServiceStatusHandle =
RegisterServiceCtrlHandler(pService->ServiceName,
(LPHANDLER_FUNCTION)
NTService::ServiceCtrlHandler)))
goto error;
// notify SCM of progress
if (!pService->SetStatus(SERVICE_START_PENDING,NO_ERROR, 0, 1, 8000))
goto error;
// create the exit event
if (!(pService->hExitEvent = CreateEvent (0, TRUE, FALSE,0)))
goto error;
if (!pService->SetStatus(SERVICE_START_PENDING,NO_ERROR, 0, 3,
pService->nStartTimeOut))
goto error;
// save start arguments
pService->my_argc=argc;
pService->my_argv=argv;
// start the service
if (!pService->StartService())
goto error;
// Check that the service is now running.
if (!pService->SetStatus(SERVICE_RUNNING,NO_ERROR, 0, 0, 0))
goto error;
// wait for exit event
WaitForSingleObject (pService->hExitEvent, INFINITE);
// wait for thread to exit
if (WaitForSingleObject (pService->hThreadHandle, INFINITE) == WAIT_TIMEOUT)
CloseHandle(pService->hThreadHandle);
pService->Exit(0);
return;
error:
pService->Exit(GetLastError());
return;
}
/* ------------------------------------------------------------------------
StartService() - starts the appliaction thread
-------------------------------------------------------------------------- */
BOOL NTService::StartService()
{
// Start the real service's thread (application)
if (!(hThreadHandle = (HANDLE) _beginthread((THREAD_FC)fpServiceThread,0,
(void *) this)))
return FALSE;
bRunning = TRUE;
return TRUE;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::StopService()
{
bRunning=FALSE;
// Set the event for application
if (hShutdownEvent)
SetEvent(hShutdownEvent);
// Set the event for ServiceMain
SetEvent(hExitEvent);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::PauseService()
{
bPause = TRUE;
SuspendThread(hThreadHandle);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::ResumeService()
{
bPause=FALSE;
ResumeThread(hThreadHandle);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::SetStatus (DWORD dwCurrentState,DWORD dwWin32ExitCode,
DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
DWORD dwWaitHint)
{
BOOL bRet;
SERVICE_STATUS serviceStatus;
dwState=dwCurrentState;
serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwCurrentState = dwCurrentState;
if (dwCurrentState == SERVICE_START_PENDING)
serviceStatus.dwControlsAccepted = 0; //don't accept control events
else
serviceStatus.dwControlsAccepted = (SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE |
SERVICE_ACCEPT_SHUTDOWN);
// if a specific exit code is defined,set up the win32 exit code properly
if (dwServiceSpecificExitCode == 0)
serviceStatus.dwWin32ExitCode = dwWin32ExitCode;
else
serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
serviceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;
serviceStatus.dwCheckPoint = dwCheckPoint;
serviceStatus.dwWaitHint = dwWaitHint;
// Pass the status to the Service Manager
if (!(bRet=SetServiceStatus (hServiceStatusHandle, &serviceStatus)))
StopService();
return bRet;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::ServiceCtrlHandler(DWORD ctrlCode)
{
DWORD dwState;
if (!pService)
return;
dwState=pService->dwState; // get current state
switch(ctrlCode) {
#ifdef NOT_USED /* do we need this ? */
case SERVICE_CONTROL_PAUSE:
if (pService->bRunning && ! pService->bPause)
{
dwState = SERVICE_PAUSED;
pService->SetStatus(SERVICE_PAUSE_PENDING,NO_ERROR, 0, 1,
pService->nPauseTimeOut);
pService->PauseService();
}
break;
case SERVICE_CONTROL_CONTINUE:
if (pService->bRunning && pService->bPause)
{
dwState = SERVICE_RUNNING;
pService->SetStatus(SERVICE_CONTINUE_PENDING,NO_ERROR, 0, 1,
pService->nResumeTimeOut);
pService->ResumeService();
}
break;
#endif
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
dwState = SERVICE_STOP_PENDING;
pService->SetStatus(SERVICE_STOP_PENDING,NO_ERROR, 0, 1,
pService->nStopTimeOut);
pService->StopService();
break;
default:
pService->SetStatus(dwState, NO_ERROR,0, 0, 0);
break;
}
//pService->SetStatus(dwState, NO_ERROR,0, 0, 0);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::Exit(DWORD error)
{
if (hExitEvent)
CloseHandle(hExitEvent);
// Send a message to the scm to tell that we stop
if (hServiceStatusHandle)
SetStatus(SERVICE_STOPPED, error,0, 0, 0);
// If the thread has started kill it ???
// if (hThreadHandle) CloseHandle(hThreadHandle);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::SeekStatus(LPCSTR szInternName, int OperationType)
{
BOOL ret_value=FALSE;
SC_HANDLE service, scm;
// open a connection to the SCM
if (!(scm = OpenSCManager(0, 0,SC_MANAGER_CREATE_SERVICE)))
{
DWORD ret_error=GetLastError();
if (ret_error == ERROR_ACCESS_DENIED)
{
printf("Install/Remove of the Service Denied!\n");
if(!is_super_user())
printf("That operation should be made by an user with Administrator privileges!\n");
}
else
printf("There is a problem for to open the Service Control Manager!\n");
}
else
{
if (OperationType == 1)
{
/* an install operation */
if ((service = OpenService(scm,szInternName, SERVICE_ALL_ACCESS )))
{
LPQUERY_SERVICE_CONFIG ConfigBuf;
DWORD dwSize;
ConfigBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 4096);
printf("The service already exists!\n");
if (QueryServiceConfig(service,ConfigBuf,4096,&dwSize))
printf("The current server installed: %s\n",
ConfigBuf->lpBinaryPathName);
LocalFree(ConfigBuf);
CloseServiceHandle(service);
}
else
ret_value=TRUE;
}
else
{
/* a remove operation */
if (!(service = OpenService(scm,szInternName, SERVICE_ALL_ACCESS )))
printf("The service doesn't exists!\n");
else
{
SERVICE_STATUS ss;
memset(&ss, 0, sizeof(ss));
if (QueryServiceStatus(service,&ss))
{
DWORD dwState = ss.dwCurrentState;
if (dwState == SERVICE_RUNNING)
printf("Failed to remove the service because the service is running\nStop the service and try again\n");
else if (dwState == SERVICE_STOP_PENDING)
printf("\
Failed to remove the service because the service is in stop pending state!\n\
Wait 30 seconds and try again.\n\
If this condition persist, reboot the machine and try again\n");
else
ret_value= TRUE;
}
CloseServiceHandle(service);
}
}
CloseServiceHandle(scm);
}
return ret_value;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::IsService(LPCSTR ServiceName)
{
BOOL ret_value=FALSE;
SC_HANDLE service, scm;
if (scm = OpenSCManager(0, 0,SC_MANAGER_ENUMERATE_SERVICE))
{
if ((service = OpenService(scm,ServiceName, SERVICE_ALL_ACCESS )))
{
ret_value=TRUE;
CloseServiceHandle(service);
}
CloseServiceHandle(scm);
}
return ret_value;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::got_service_option(char **argv, char *service_option)
{
char *option;
for (option= argv[1]; *option; option++)
if (!strcmp(option, service_option))
return TRUE;
return FALSE;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::is_super_user()
{
HANDLE hAccessToken;
UCHAR InfoBuffer[1024];
PTOKEN_GROUPS ptgGroups=(PTOKEN_GROUPS)InfoBuffer;
DWORD dwInfoBufferSize;
PSID psidAdministrators;
SID_IDENTIFIER_AUTHORITY siaNtAuthority = SECURITY_NT_AUTHORITY;
UINT x;
BOOL ret_value=FALSE;
if(!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE,&hAccessToken ))
{
if(GetLastError() != ERROR_NO_TOKEN)
return FALSE;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hAccessToken))
return FALSE;
}
ret_value= GetTokenInformation(hAccessToken,TokenGroups,InfoBuffer,
1024, &dwInfoBufferSize);
CloseHandle(hAccessToken);
if(!ret_value )
return FALSE;
if(!AllocateAndInitializeSid(&siaNtAuthority, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&psidAdministrators))
return FALSE;
ret_value = FALSE;
for(x=0;x<ptgGroups->GroupCount;x++)
{
if( EqualSid(psidAdministrators, ptgGroups->Groups[x].Sid) )
{
ret_value = TRUE;
break;
}
}
FreeSid(psidAdministrators);
return ret_value;
}
<commit_msg>Fix error msg. Bug #681<commit_after>/* ------------------------------------------------------------------------
Windows NT Service class library
Copyright Abandoned 1998 Irena Pancirov - Irnet Snc
This file is public domain and comes with NO WARRANTY of any kind
-------------------------------------------------------------------------- */
#include <windows.h>
#include <process.h>
#include <stdio.h>
#include "nt_servc.h"
static NTService *pService;
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
NTService::NTService()
{
bOsNT = FALSE;
//service variables
ServiceName = NULL;
hExitEvent = 0;
bPause = FALSE;
bRunning = FALSE;
hThreadHandle = 0;
fpServiceThread = NULL;
//time-out variables
nStartTimeOut = 15000;
nStopTimeOut = 86400000;
nPauseTimeOut = 5000;
nResumeTimeOut = 5000;
//install variables
dwDesiredAccess = SERVICE_ALL_ACCESS;
dwServiceType = SERVICE_WIN32_OWN_PROCESS;
dwStartType = SERVICE_AUTO_START;
dwErrorControl = SERVICE_ERROR_NORMAL;
szLoadOrderGroup = NULL;
lpdwTagID = NULL;
szDependencies = NULL;
my_argc = 0;
my_argv = NULL;
hShutdownEvent = 0;
nError = 0;
dwState = 0;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
NTService::~NTService()
{
if (ServiceName != NULL) delete[] ServiceName;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::GetOS()
{
bOsNT = FALSE;
memset(&osVer, 0, sizeof(OSVERSIONINFO));
osVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if (GetVersionEx(&osVer))
{
if (osVer.dwPlatformId == VER_PLATFORM_WIN32_NT)
bOsNT = TRUE;
}
return bOsNT;
}
/* ------------------------------------------------------------------------
Init() Registers the main service thread with the service manager
ServiceThread - pointer to the main programs entry function
when the service is started
-------------------------------------------------------------------------- */
long NTService::Init(LPCSTR szInternName,void *ServiceThread)
{
pService = this;
fpServiceThread = (THREAD_FC)ServiceThread;
ServiceName = new char[lstrlen(szInternName)+1];
lstrcpy(ServiceName,szInternName);
SERVICE_TABLE_ENTRY stb[] =
{
{ (char *)szInternName,(LPSERVICE_MAIN_FUNCTION) ServiceMain} ,
{ NULL, NULL }
};
return StartServiceCtrlDispatcher(stb); //register with the Service Manager
}
/* ------------------------------------------------------------------------
Install() - Installs the service with Service manager
nError values:
0 success
1 Can't open the Service manager
2 Failed to create service
-------------------------------------------------------------------------- */
BOOL NTService::Install(int startType, LPCSTR szInternName,
LPCSTR szDisplayName,
LPCSTR szFullPath, LPCSTR szAccountName,
LPCSTR szPassword)
{
BOOL ret_val=FALSE;
SC_HANDLE newService, scm;
if (!SeekStatus(szInternName,1))
return FALSE;
char szFilePath[_MAX_PATH];
GetModuleFileName(NULL, szFilePath, sizeof(szFilePath));
// open a connection to the SCM
if (!(scm = OpenSCManager(0, 0,SC_MANAGER_CREATE_SERVICE)))
printf("Failed to install the service (Couldn't open the SCM)\n");
else // Install the new service
{
if (!(newService=
CreateService(scm,
szInternName,
szDisplayName,
dwDesiredAccess,//default: SERVICE_ALL_ACCESS
dwServiceType, //default: SERVICE_WIN32_OWN_PROCESS
//default: SERVICE_AUTOSTART
(startType == 1 ? SERVICE_AUTO_START :
SERVICE_DEMAND_START),
dwErrorControl, //default: SERVICE_ERROR_NORMAL
szFullPath, //exec full path
szLoadOrderGroup, //default: NULL
lpdwTagID, //default: NULL
szDependencies, //default: NULL
szAccountName, //default: NULL
szPassword))) //default: NULL
printf("Failed to install the service (Couldn't create service)\n");
else
{
printf("Service successfully installed.\n");
CloseServiceHandle(newService);
ret_val=TRUE; // Everything went ok
}
CloseServiceHandle(scm);
}
return ret_val;
}
/* ------------------------------------------------------------------------
Remove() - Removes the service
nError values:
0 success
1 Can't open the Service manager
2 Failed to locate service
3 Failed to delete service
-------------------------------------------------------------------------- */
BOOL NTService::Remove(LPCSTR szInternName)
{
BOOL ret_value=FALSE;
SC_HANDLE service, scm;
if (!SeekStatus(szInternName,0))
return FALSE;
nError=0;
// open a connection to the SCM
if (!(scm = OpenSCManager(0, 0,SC_MANAGER_CREATE_SERVICE)))
{
printf("Failed to remove the service (Couldn't open the SCM)\n");
}
else
{
if ((service = OpenService(scm,szInternName, DELETE)))
{
if (!DeleteService(service))
printf("Failed to remove the service\n");
else
{
printf("Service successfully removed.\n");
ret_value=TRUE; // everything went ok
}
CloseServiceHandle(service);
}
else
printf("Failed to remove the service (Couldn't open the service)\n");
CloseServiceHandle(scm);
}
return ret_value;
}
/* ------------------------------------------------------------------------
Stop() - this function should be called before the app. exits to stop
the service
-------------------------------------------------------------------------- */
void NTService::Stop(void)
{
SetStatus(SERVICE_STOP_PENDING,NO_ERROR, 0, 1, 60000);
StopService();
SetStatus(SERVICE_STOPPED, NO_ERROR, 0, 1, 1000);
}
/* ------------------------------------------------------------------------
ServiceMain() - This is the function that is called from the
service manager to start the service
-------------------------------------------------------------------------- */
void NTService::ServiceMain(DWORD argc, LPTSTR *argv)
{
// registration function
if (!(pService->hServiceStatusHandle =
RegisterServiceCtrlHandler(pService->ServiceName,
(LPHANDLER_FUNCTION)
NTService::ServiceCtrlHandler)))
goto error;
// notify SCM of progress
if (!pService->SetStatus(SERVICE_START_PENDING,NO_ERROR, 0, 1, 8000))
goto error;
// create the exit event
if (!(pService->hExitEvent = CreateEvent (0, TRUE, FALSE,0)))
goto error;
if (!pService->SetStatus(SERVICE_START_PENDING,NO_ERROR, 0, 3,
pService->nStartTimeOut))
goto error;
// save start arguments
pService->my_argc=argc;
pService->my_argv=argv;
// start the service
if (!pService->StartService())
goto error;
// Check that the service is now running.
if (!pService->SetStatus(SERVICE_RUNNING,NO_ERROR, 0, 0, 0))
goto error;
// wait for exit event
WaitForSingleObject (pService->hExitEvent, INFINITE);
// wait for thread to exit
if (WaitForSingleObject (pService->hThreadHandle, INFINITE) == WAIT_TIMEOUT)
CloseHandle(pService->hThreadHandle);
pService->Exit(0);
return;
error:
pService->Exit(GetLastError());
return;
}
/* ------------------------------------------------------------------------
StartService() - starts the appliaction thread
-------------------------------------------------------------------------- */
BOOL NTService::StartService()
{
// Start the real service's thread (application)
if (!(hThreadHandle = (HANDLE) _beginthread((THREAD_FC)fpServiceThread,0,
(void *) this)))
return FALSE;
bRunning = TRUE;
return TRUE;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::StopService()
{
bRunning=FALSE;
// Set the event for application
if (hShutdownEvent)
SetEvent(hShutdownEvent);
// Set the event for ServiceMain
SetEvent(hExitEvent);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::PauseService()
{
bPause = TRUE;
SuspendThread(hThreadHandle);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::ResumeService()
{
bPause=FALSE;
ResumeThread(hThreadHandle);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::SetStatus (DWORD dwCurrentState,DWORD dwWin32ExitCode,
DWORD dwServiceSpecificExitCode, DWORD dwCheckPoint,
DWORD dwWaitHint)
{
BOOL bRet;
SERVICE_STATUS serviceStatus;
dwState=dwCurrentState;
serviceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
serviceStatus.dwCurrentState = dwCurrentState;
if (dwCurrentState == SERVICE_START_PENDING)
serviceStatus.dwControlsAccepted = 0; //don't accept control events
else
serviceStatus.dwControlsAccepted = (SERVICE_ACCEPT_STOP |
SERVICE_ACCEPT_PAUSE_CONTINUE |
SERVICE_ACCEPT_SHUTDOWN);
// if a specific exit code is defined,set up the win32 exit code properly
if (dwServiceSpecificExitCode == 0)
serviceStatus.dwWin32ExitCode = dwWin32ExitCode;
else
serviceStatus.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR;
serviceStatus.dwServiceSpecificExitCode = dwServiceSpecificExitCode;
serviceStatus.dwCheckPoint = dwCheckPoint;
serviceStatus.dwWaitHint = dwWaitHint;
// Pass the status to the Service Manager
if (!(bRet=SetServiceStatus (hServiceStatusHandle, &serviceStatus)))
StopService();
return bRet;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::ServiceCtrlHandler(DWORD ctrlCode)
{
DWORD dwState;
if (!pService)
return;
dwState=pService->dwState; // get current state
switch(ctrlCode) {
#ifdef NOT_USED /* do we need this ? */
case SERVICE_CONTROL_PAUSE:
if (pService->bRunning && ! pService->bPause)
{
dwState = SERVICE_PAUSED;
pService->SetStatus(SERVICE_PAUSE_PENDING,NO_ERROR, 0, 1,
pService->nPauseTimeOut);
pService->PauseService();
}
break;
case SERVICE_CONTROL_CONTINUE:
if (pService->bRunning && pService->bPause)
{
dwState = SERVICE_RUNNING;
pService->SetStatus(SERVICE_CONTINUE_PENDING,NO_ERROR, 0, 1,
pService->nResumeTimeOut);
pService->ResumeService();
}
break;
#endif
case SERVICE_CONTROL_SHUTDOWN:
case SERVICE_CONTROL_STOP:
dwState = SERVICE_STOP_PENDING;
pService->SetStatus(SERVICE_STOP_PENDING,NO_ERROR, 0, 1,
pService->nStopTimeOut);
pService->StopService();
break;
default:
pService->SetStatus(dwState, NO_ERROR,0, 0, 0);
break;
}
//pService->SetStatus(dwState, NO_ERROR,0, 0, 0);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
void NTService::Exit(DWORD error)
{
if (hExitEvent)
CloseHandle(hExitEvent);
// Send a message to the scm to tell that we stop
if (hServiceStatusHandle)
SetStatus(SERVICE_STOPPED, error,0, 0, 0);
// If the thread has started kill it ???
// if (hThreadHandle) CloseHandle(hThreadHandle);
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::SeekStatus(LPCSTR szInternName, int OperationType)
{
BOOL ret_value=FALSE;
SC_HANDLE service, scm;
// open a connection to the SCM
if (!(scm = OpenSCManager(0, 0,SC_MANAGER_CREATE_SERVICE)))
{
DWORD ret_error=GetLastError();
if (ret_error == ERROR_ACCESS_DENIED)
{
printf("Install/Remove of the Service Denied!\n");
if(!is_super_user())
printf("That operation should be made by an user with Administrator privileges!\n");
}
else
printf("There is a problem for to open the Service Control Manager!\n");
}
else
{
if (OperationType == 1)
{
/* an install operation */
if ((service = OpenService(scm,szInternName, SERVICE_ALL_ACCESS )))
{
LPQUERY_SERVICE_CONFIG ConfigBuf;
DWORD dwSize;
ConfigBuf = (LPQUERY_SERVICE_CONFIG) LocalAlloc(LPTR, 4096);
printf("The service already exists!\n");
if (QueryServiceConfig(service,ConfigBuf,4096,&dwSize))
printf("The current server installed: %s\n",
ConfigBuf->lpBinaryPathName);
LocalFree(ConfigBuf);
CloseServiceHandle(service);
}
else
ret_value=TRUE;
}
else
{
/* a remove operation */
if (!(service = OpenService(scm,szInternName, SERVICE_ALL_ACCESS )))
printf("The service doesn't exist!\n");
else
{
SERVICE_STATUS ss;
memset(&ss, 0, sizeof(ss));
if (QueryServiceStatus(service,&ss))
{
DWORD dwState = ss.dwCurrentState;
if (dwState == SERVICE_RUNNING)
printf("Failed to remove the service because the service is running\nStop the service and try again\n");
else if (dwState == SERVICE_STOP_PENDING)
printf("\
Failed to remove the service because the service is in stop pending state!\n\
Wait 30 seconds and try again.\n\
If this condition persist, reboot the machine and try again\n");
else
ret_value= TRUE;
}
CloseServiceHandle(service);
}
}
CloseServiceHandle(scm);
}
return ret_value;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::IsService(LPCSTR ServiceName)
{
BOOL ret_value=FALSE;
SC_HANDLE service, scm;
if (scm = OpenSCManager(0, 0,SC_MANAGER_ENUMERATE_SERVICE))
{
if ((service = OpenService(scm,ServiceName, SERVICE_ALL_ACCESS )))
{
ret_value=TRUE;
CloseServiceHandle(service);
}
CloseServiceHandle(scm);
}
return ret_value;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::got_service_option(char **argv, char *service_option)
{
char *option;
for (option= argv[1]; *option; option++)
if (!strcmp(option, service_option))
return TRUE;
return FALSE;
}
/* ------------------------------------------------------------------------
-------------------------------------------------------------------------- */
BOOL NTService::is_super_user()
{
HANDLE hAccessToken;
UCHAR InfoBuffer[1024];
PTOKEN_GROUPS ptgGroups=(PTOKEN_GROUPS)InfoBuffer;
DWORD dwInfoBufferSize;
PSID psidAdministrators;
SID_IDENTIFIER_AUTHORITY siaNtAuthority = SECURITY_NT_AUTHORITY;
UINT x;
BOOL ret_value=FALSE;
if(!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE,&hAccessToken ))
{
if(GetLastError() != ERROR_NO_TOKEN)
return FALSE;
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hAccessToken))
return FALSE;
}
ret_value= GetTokenInformation(hAccessToken,TokenGroups,InfoBuffer,
1024, &dwInfoBufferSize);
CloseHandle(hAccessToken);
if(!ret_value )
return FALSE;
if(!AllocateAndInitializeSid(&siaNtAuthority, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&psidAdministrators))
return FALSE;
ret_value = FALSE;
for(x=0;x<ptgGroups->GroupCount;x++)
{
if( EqualSid(psidAdministrators, ptgGroups->Groups[x].Sid) )
{
ret_value = TRUE;
break;
}
}
FreeSid(psidAdministrators);
return ret_value;
}
<|endoftext|> |
<commit_before>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen 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 details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include <errno.h>
#include <poll.h>
#include <sstream>
#include <thread>
#include "ingen/Configuration.hpp"
#include "ingen/Module.hpp"
#include "ingen/World.hpp"
#include "raul/Socket.hpp"
#include "../server/Engine.hpp"
#include "../server/EventWriter.hpp"
#include "SocketListener.hpp"
#include "SocketServer.hpp"
namespace Ingen {
namespace Server {
void
SocketListener::ingen_listen(Engine* engine,
Raul::Socket* unix_sock,
Raul::Socket* net_sock)
{
Ingen::World* world = engine->world();
const std::string unix_path(world->conf().option("socket").ptr<char>());
// Bind UNIX socket
const Raul::URI unix_uri(unix_scheme + unix_path);
if (!unix_sock->bind(unix_uri) || !unix_sock->listen()) {
world->log().error("Failed to create UNIX socket\n");
unix_sock->close();
} else {
world->log().info(fmt("Listening on socket %1%\n") % unix_uri);
}
// Bind TCP socket
const int port = world->conf().option("engine-port").get<int32_t>();
std::ostringstream ss;
ss << "tcp://localhost:";
ss << port;
if (!net_sock->bind(Raul::URI(ss.str())) || !net_sock->listen()) {
world->log().error("Failed to create TCP socket\n");
net_sock->close();
} else {
world->log().info(fmt("Listening on TCP port %1%\n") % port);
}
if (unix_sock->fd() == -1 && net_sock->fd() == -1) {
return; // No sockets to listen to, exit thread
}
struct pollfd pfds[2];
int nfds = 0;
if (unix_sock->fd() != -1) {
pfds[nfds].fd = unix_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
if (net_sock->fd() != -1) {
pfds[nfds].fd = net_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
while (true) {
// Wait for input to arrive at a socket
const int ret = poll(pfds, nfds, -1);
if (ret == -1) {
world->log().error(fmt("Poll error: %1%\n") % strerror(errno));
break;
} else if (ret == 0) {
world->log().warn("Poll returned with no data\n");
continue;
} else if ((pfds[0].revents & POLLHUP) || pfds[1].revents & POLLHUP) {
break;
}
if (pfds[0].revents & POLLIN) {
SPtr<Raul::Socket> conn = unix_sock->accept();
if (conn) {
new SocketServer(*world, *engine, conn);
}
}
if (pfds[1].revents & POLLIN) {
SPtr<Raul::Socket> conn = net_sock->accept();
if (conn) {
new SocketServer(*world, *engine, conn);
}
}
}
}
} // namespace Server
} // namespace Ingen
<commit_msg>Listen for TCP connections on all interfaces.<commit_after>/*
This file is part of Ingen.
Copyright 2007-2015 David Robillard <http://drobilla.net/>
Ingen 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 any later version.
Ingen 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 details.
You should have received a copy of the GNU Affero General Public License
along with Ingen. If not, see <http://www.gnu.org/licenses/>.
*/
#include <errno.h>
#include <poll.h>
#include <sstream>
#include <thread>
#include "ingen/Configuration.hpp"
#include "ingen/Module.hpp"
#include "ingen/World.hpp"
#include "raul/Socket.hpp"
#include "../server/Engine.hpp"
#include "../server/EventWriter.hpp"
#include "SocketListener.hpp"
#include "SocketServer.hpp"
namespace Ingen {
namespace Server {
void
SocketListener::ingen_listen(Engine* engine,
Raul::Socket* unix_sock,
Raul::Socket* net_sock)
{
Ingen::World* world = engine->world();
const std::string unix_path(world->conf().option("socket").ptr<char>());
// Bind UNIX socket
const Raul::URI unix_uri(unix_scheme + unix_path);
if (!unix_sock->bind(unix_uri) || !unix_sock->listen()) {
world->log().error("Failed to create UNIX socket\n");
unix_sock->close();
} else {
world->log().info(fmt("Listening on socket %1%\n") % unix_uri);
}
// Bind TCP socket
const int port = world->conf().option("engine-port").get<int32_t>();
std::ostringstream ss;
ss << "tcp://*:" << port;
if (!net_sock->bind(Raul::URI(ss.str())) || !net_sock->listen()) {
world->log().error("Failed to create TCP socket\n");
net_sock->close();
} else {
world->log().info(fmt("Listening on TCP port %1%\n") % port);
}
if (unix_sock->fd() == -1 && net_sock->fd() == -1) {
return; // No sockets to listen to, exit thread
}
struct pollfd pfds[2];
int nfds = 0;
if (unix_sock->fd() != -1) {
pfds[nfds].fd = unix_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
if (net_sock->fd() != -1) {
pfds[nfds].fd = net_sock->fd();
pfds[nfds].events = POLLIN;
pfds[nfds].revents = 0;
++nfds;
}
while (true) {
// Wait for input to arrive at a socket
const int ret = poll(pfds, nfds, -1);
if (ret == -1) {
world->log().error(fmt("Poll error: %1%\n") % strerror(errno));
break;
} else if (ret == 0) {
world->log().warn("Poll returned with no data\n");
continue;
} else if ((pfds[0].revents & POLLHUP) || pfds[1].revents & POLLHUP) {
break;
}
if (pfds[0].revents & POLLIN) {
SPtr<Raul::Socket> conn = unix_sock->accept();
if (conn) {
new SocketServer(*world, *engine, conn);
}
}
if (pfds[1].revents & POLLIN) {
SPtr<Raul::Socket> conn = net_sock->accept();
if (conn) {
new SocketServer(*world, *engine, conn);
}
}
}
}
} // namespace Server
} // namespace Ingen
<|endoftext|> |
<commit_before>#include <json.h>
bool logIn(char* json, const int fd)
{
std::string log = recieveFrom(fd);
std::string password = recieveFrom(fd);
bool logged=false;
Json::Value usersInfos;
Json::Reader infosReader;
if(parsingSuccess)
{
if("NULL"!=usersInfos.get(log, "NULL")) // vérifie si le compte existe
{
if(usersInfos[log]==password)
{
logged=true;
std::string message="Authentification réussie, bienvenue "+log;
sendTo(fd, message);
}
}
}
return logged;
}
bool signUp(char* json, const int fd) // reçoit un json avec l'ensemble des infos des users
{
bool signedUp=false;
std::string log = recieveFrom(fd);
std::string password = recieveFrom(fd);
Json::Value usersInfos;
Json::Reader infosReader;
bool parsingSuccess=infoReader.parse(json, usersInfos);
if(parsingSuccess)
{
if("NULL"==usersInfos.get(log, "NULL"))
{
signedUp=true;
usersInfos[log]=password; //enregistre le nouveau compte
std::string message="Inscription réussie, bienvenue "+log;
sendTo(fd, message);
}
}
return signedUp;
}
<commit_msg>[code] New prototype (2) for fct logIn and signUp<commit_after>//#include <json.h> module json à coder
bool logIn(char * message, pthread_t * thread, JsonObject * usersInfos) // usersInfo est un pointeur vers un json contenant l'ensemble des log et password connus
{
bool logged=false;
char * reponseMessage;
JsonObject json(message); // classe JsonObject à définir dans le module
JsonObject reponse;
char * userName=json.get("userName");
if(usersInfo.get(userName)!="~") // ~ étant une valeur sentinelle renvoyée quand l'élément cherché n'est pas dans le json, et utilisée ici pour vérifier si le userName est correct
{
if(usersInfos.get(userName)==json.get(password)) // le password
{
logged=true;
reponseMessage="blablabla"; //à définir plus tard
thread.send_message("user.login", reponseMessage);
}
else
{
reponseMessage="blablabla2"; //à définir plus tard
thread.send_message("user.login", reponseMessage);
}
}
else
{
reponseMessage="blablabla3"; //à définir plus tard
thread.send_message("user.login", reponseMessage);
}
return logged;
}
bool signUp(char* message, pthread_t * thread, JsonObject * usersInfo) // reçoit un json avec l'ensemble des infos des users
{
bool signedUp=false;
std::string log = recieveFrom(fd);
std::string password = recieveFrom(fd);
Json::Value usersInfos;
Json::Reader infosReader;
bool parsingSuccess=infoReader.parse(json, usersInfos);
if(parsingSuccess)
{
if("NULL"==usersInfos.get(log, "NULL"))
{
signedUp=true;
usersInfos[log]=password; //enregistre le nouveau compte
std::string message="Inscription réussie, bienvenue "+log;
sendTo(fd, message);
}
}
return signedUp;
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief ファイラー・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/monograph.hpp"
#include "common/sdc_io.hpp"
namespace graphics {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ファイラー・クラス
@param[in] SDC_IO SDC I/O クラスの型
@param[in] BITMAP ビットマップの型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class SDC_IO, class BITMAP>
class filer {
SDC_IO& sdc_;
BITMAP& bitmap_;
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] sdc sdc_io クラス参照
@param[in] bitmap ビットマップ・クラス参照
*/
//-----------------------------------------------------------------//
filer(SDC_IO& sdc, BITMAP& bitmap) : sdc_(sdc), bitmap_(bitmap) { }
//-----------------------------------------------------------------//
/*!
@brief サービス 表示、毎フレーム呼ぶ
*/
//-----------------------------------------------------------------//
void service() {
}
};
}
<commit_msg>fix stack<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief ビットマップ・グラフィックス用ファイル選択クラス
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/monograph.hpp"
#include "common/sdc_io.hpp"
namespace graphics {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ファイラー・クラス
@param[in] SDC_IO SDC I/O クラスの型
@param[in] BITMAP ビットマップの型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class SDC_IO, class BITMAP>
class filer {
SDC_IO& sdc_;
BITMAP& bitmap_;
const char* root_;
uint16_t file_num_;
uint16_t file_pos_;
bool enable_;
struct option_t {
BITMAP& bmp;
int16_t y;
option_t(BITMAP& bitmap) : bmp(bitmap), y(0) { }
};
static void dir_(const char* fname, const FILINFO* fi, bool dir, void* option) {
option_t* t = reinterpret_cast<option_t*>(option);
if(t->y < 0 || t->y >= static_cast<int16_t>(t->bmp.get_height())) return;
t->bmp.draw_text(0, t->y, fname);
t->y += t->bmp.get_kfont_height();
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
@param[in] sdc sdc_io クラス参照
@param[in] bitmap ビットマップ・クラス参照
*/
//-----------------------------------------------------------------//
filer(SDC_IO& sdc, BITMAP& bitmap) : sdc_(sdc), bitmap_(bitmap),
root_(nullptr), file_num_(0), file_pos_(0),
enable_(false) { }
//-----------------------------------------------------------------//
/*!
@brief 表示許可の取得
@return 表示許可状態
*/
//-----------------------------------------------------------------//
bool get_enable() const { return enable_; }
//-----------------------------------------------------------------//
/*!
@brief 表示許可
@param[in] ena 不許可の場合「false」
*/
//-----------------------------------------------------------------//
void enable(bool ena = true) { enable_ = ena; }
//-----------------------------------------------------------------//
/*!
@brief ルート・ディレクトリーを設定
@param[in] root ルート・パス
*/
//-----------------------------------------------------------------//
void set_root(const char* root) {
root_ = root;
file_num_ = sdc_.dir_loop(root, nullptr, true);
file_pos_ = 0;
}
//-----------------------------------------------------------------//
/*!
@brief サービス 表示、毎フレーム呼ぶ
*/
//-----------------------------------------------------------------//
void service() {
option_t opt(bitmap_);
if(!enable_) return;
if(root_ == nullptr) return;
if(file_num_ == 0) return;
sdc_.dir_loop(root_, dir_, true, &opt);
}
};
}
<|endoftext|> |
<commit_before>#include <COSTerm.h>
#include <COSProcess.h>
#include <COSErr.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
extern "C" {
# include "termios.h"
extern int tgetent(char *, char *);
extern int tgetnum(char *);
}
#include "sys/ioctl.h"
#define HAS_POSIX_OPENPT 1
static const char *
color_xterm_colors[] = {
"[0m" , /* White */
"[31m", /* Red */
"[32m", /* Green */
"[33m", /* Yellow */
"[34m", /* Blue */
"[35m", /* Magenta */
"[36m", /* Cyan */
};
static const char *
normal_xterm_colors[] = {
"[0m", /* Normal */
"[4m", /* Underline */
"[1m", /* Bold */
"[1m", /* Bold */
"[7m", /* Invert */
"[0m", /* Normal */
"[7m", /* Invert */
};
static const char *
hp_colors[] = {
"&v0S", /* Whitel */
"&v1S", /* Red */
"&v2S", /* Green */
"&v3S", /* Yellow */
"&v4S", /* Blue */
"&v5S", /* Magenta */
"&v6S", /* Cyan */
};
const char **COSTerm::colors_ = nullptr;
std::string
COSTerm::
getTerminalName(int fd)
{
char *tty_name = ttyname(fd);
if (! tty_name)
return "";
return tty_name;
}
std::string
COSTerm::
getTerminalPath()
{
char *tty_name = ctermid(0);
if (! tty_name)
return "";
return tty_name;
}
pid_t
COSTerm::
getTerminalProcessGroupId(int fd)
{
std::string tty_name = getTerminalName(fd);
return getTerminalProcessGroupId(tty_name);
}
pid_t
COSTerm::
getTerminalProcessGroupId(const std::string &term)
{
int fd = open(term.c_str(), O_RDWR);
if (fd < 0) {
fd = open(term.c_str(), O_RDONLY);
if (fd < 0)
return -1;
}
pid_t id;
#ifdef NEVER
int error = ioctl(fd, TIOCGPGRP, (char *) &id);
#else
id = tcgetpgrp(fd);
#endif
close(fd);
return id;
}
pid_t
COSTerm::
getTerminalSessionId(int fd)
{
int tfd = getTerminalId(fd);
if (tfd < 0) return -1;
#ifdef COS_HAS_TCGETSID
pid_t id = tcgetsid(tfd);
#else
pid_t id = COSProcess::getSessionId(tcgetpgrp(tfd));
#endif
close(fd);
return id;
}
int
COSTerm::
getTerminalId(int fd)
{
std::string tty_name = getTerminalName(fd);
int tfd = open(tty_name.c_str(), O_RDWR);
if (tfd < 0) {
tfd = open(tty_name.c_str(), O_RDONLY);
if (tfd < 0)
return -1;
}
return tfd;
}
bool
COSTerm::
getCharSize(int *rows, int *cols)
{
if (isatty(STDIN_FILENO)) {
if (getCharSize(STDIN_FILENO, rows, cols))
return true;
}
#ifdef CURSES
WINDOW *w;
use_env(false);
w = initscr();
endwin();
*rows = LINES;
*cols = COLS;
#else
*rows = 60;
*cols = 0;
char *columns;
if ((columns = getenv("COLUMNS")) != nullptr)
*cols = atoi(columns);
if (*cols == 0)
*cols = COSTerm::getNumColumns();
if (*cols == 0)
*cols = 80;
#endif
return false;
}
bool
COSTerm::
getCharSize(int fd, int *rows, int *cols)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
*rows = ts.ws_row;
*cols = ts.ws_col;
return true;
}
bool
COSTerm::
setCharSize(int fd, int rows, int cols)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
if (ts.ws_col != 0)
ts.ws_xpixel = cols*(ts.ws_xpixel/ts.ws_col);
if (ts.ws_row != 0)
ts.ws_ypixel = rows*(ts.ws_ypixel/ts.ws_row);
ts.ws_row = rows;
ts.ws_col = cols;
ioctl(fd, TIOCSWINSZ, (char *) &ts);
return true;
}
bool
COSTerm::
getPixelSize(int *width, int *height)
{
int fd = COSTerm::getTerminalId();
if (fd < 0)
return false;
return getPixelSize(fd, width, height);
}
bool
COSTerm::
getPixelSize(int fd, int *width, int *height)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
*width = ts.ws_xpixel;
*height = ts.ws_ypixel;
return true;
}
bool
COSTerm::
setPixelSize(int fd, int width, int height)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
if (ts.ws_xpixel != 0)
ts.ws_row = (width *ts.ws_col)/ts.ws_xpixel;
if (ts.ws_ypixel != 0)
ts.ws_col = (height*ts.ws_row)/ts.ws_ypixel;
ts.ws_xpixel = width;
ts.ws_ypixel = height;
ioctl(fd, TIOCSWINSZ, (char *) &ts);
return true;
}
int
COSTerm::
getNumColumns()
{
static char term_buffer[2048];
const char *term;
if ((term = getenv("TERM")) == nullptr)
term = "vt100";
int no = tgetent(term_buffer, (char *) term);
if (no <= 0)
return 0;
int cols = tgetnum((char *) "cols");
return cols;
}
const char *
COSTerm::
getColorStr(int color)
{
if (color < 0 || color > 6)
return "";
const char **colors = getColorStrs();
return colors[color];
}
const char **
COSTerm::
getColorStrs()
{
if (! colors_) {
const char *term;
if ((term = getenv("TERM")) == nullptr)
term = "vt100";
if (strcmp(term, "xterm" ) == 0 ||
strcmp(term, "xterm-color") == 0) {
bool colored = true;
char *color_xterm;
if ((color_xterm = getenv( "COLOR_XTERM")) == nullptr &&
(color_xterm = getenv("COLOUR_XTERM")) == nullptr)
colored = false;
if (colored)
colors_ = color_xterm_colors;
else
colors_ = normal_xterm_colors;
}
else if (strncmp(term, "hp", 2) == 0)
colors_ = hp_colors;
else
colors_ = normal_xterm_colors;
}
return colors_;
}
bool
COSTerm::
cgets(std::string &buf)
{
FILE *tty;
std::string tty_name = COSTerm::getTerminalName(STDIN_FILENO);
if (! (tty = fopen(tty_name.c_str(), "w+")))
return false;
/* get attributes on the input tty and set them to new settings */
struct termios init, newsettings;
tcgetattr(fileno(stdin), &init);
newsettings = init;
newsettings.c_lflag &= ~(ICANON | ECHO);
newsettings.c_cc[VMIN ] = 1;
newsettings.c_cc[VTIME] = 0;
if (tcsetattr(fileno(stdin), TCSANOW, &newsettings) != 0)
return -1;
int c;
for (;;) {
c = getc(stdin);
if ((c == '\n') || (c == '\r') || (c == EOF))
break;
if ((c == '\b') || (c == 0x7f)) {
if (buf.size() > 0) {
buf = buf.substr(0, buf.size() - 1);
fputs("\b \b", stdout);
}
else
putc('\a', stdout);
continue;
}
fputc(c, stdout);
buf += char(c);
}
tcsetattr(fileno(tty), TCSANOW, &init);
fflush(tty);
fclose(tty);
printf("\n");
return true;
}
//-------
bool
COSTerm::
openMasterPty(int *fd, std::string &slaveName)
{
// Open Master Pseudo Terminal
#if HAS_POSIX_OPENPT
*fd = posix_openpt(O_RDWR | O_NOCTTY);
#elif HAS_GETPT
*fd = getpt();
#elif HAS_PTMX
*fd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
#elif BSD_TERM
// TODO: need new pty name here. For BSD this will by names:
// /dev/pty<X><Y> where <X> is [p-za-e] and <Y> is [0-9a-f]
static char xchars[] = "pqrstuvwxyzabcde";
static uint num_xchars = sizeof(xchars);
static char ychars[] = "0123456789abcdef";
static uint num_ychars = sizeof(ychars);
static char bsd_pty[] = "/dev/ptyxy";
static char bsd_tty[] = "/dev/ttyxy";
for (uint x = 0; x < num_xchars; ++x) {
bsd_pty[8] = xchars[x];
bsd_tty[8] = xchars[x];
for (uint y = 0; y < num_ychars; ++y) {
bsd_pty[9] = ychars[y];
bsd_tty[9] = ychars[y];
*fd = open(bsd_pty, O_RDWR | O_NOCTTY);
if (*fd == -1) {
if (errno == ENOENT) break;
continue;
}
if (*fd >= 0) break;
}
}
#else
return false;
#endif
if (*fd == -1)
return false;
//----
#ifndef BSD_TERM
// Ensure Terminal has process permission (needed to make portable)
if (grantpt(*fd) == -1) {
closeNoError(*fd); *fd = -1;
return false;
}
//----
// Finished setup so we now must unlock slave to use
if (unlockpt(*fd) == -1) {
closeNoError(*fd); *fd = -1;
return false;
}
//----
char *ptr = ptsname(*fd);
if (! ptr) {
closeNoError(*fd); *fd = -1;
return false;
}
slaveName = ptr;
#else
slaveName = bsd_tty;
#endif
return true;
}
bool
COSTerm::
ptyFork(int *mfd, std::string &slaveName, pid_t *childPid)
{
*mfd = 0;
*childPid = 0;
if (! openMasterPty(mfd, slaveName))
return false;
*childPid = fork();
if (*childPid == -1) { // failed
closeNoError(*mfd);
return false;
}
// ---- parent ----
if (*childPid != 0)
return true;
// ---- child ----
// master pty not needed
close(*mfd);
// start new session (child loses controlling terminal)
if (setsid() == -1)
COSErr::exit("ptyFork: setsid");
// Becomes controlling tty
int sfd = open(slaveName.c_str(), O_RDWR);
if (sfd == -1)
COSErr::exit("ptyFork: open-slave");
#ifdef TIOCSCTTY
// Acquire controlling tty on BSD
if (ioctl(sfd, TIOCSCTTY, 0) == -1)
COSErr::exit("ptyFork:ioctl-TIOCSCTTY");
#endif
// Duplicate pty slave to be child's stdin, stdout, and stderr
if (dup2(sfd, STDIN_FILENO ) != STDIN_FILENO ) COSErr::exit("ptyFork:dup2-STDIN_FILENO");
if (dup2(sfd, STDOUT_FILENO) != STDOUT_FILENO) COSErr::exit("ptyFork:dup2-STDOUT_FILENO");
if (dup2(sfd, STDERR_FILENO) != STDERR_FILENO) COSErr::exit("ptyFork:dup2-STDERR_FILENO");
// No longer need pty slave (don't close if equal to stdin, stdout or stderr
if (sfd > STDERR_FILENO)
closeNoError(sfd);
return true;
}
//-------
void
COSTerm::
closeNoError(int fd)
{
int saveErrno = errno;
(void) close(fd);
errno = saveErrno;
}
<commit_msg>new files<commit_after>#include <COSTerm.h>
#include <COSProcess.h>
#include <COSErr.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <fcntl.h>
extern "C" {
# include "termios.h"
extern int tgetent(char *, char *);
extern int tgetnum(char *);
}
#include "sys/ioctl.h"
#define HAS_POSIX_OPENPT 1
static const char *
color_xterm_colors[] = {
"[0m" , /* White */
"[31m", /* Red */
"[32m", /* Green */
"[33m", /* Yellow */
"[34m", /* Blue */
"[35m", /* Magenta */
"[36m", /* Cyan */
};
static const char *
normal_xterm_colors[] = {
"[0m", /* Normal */
"[4m", /* Underline */
"[1m", /* Bold */
"[1m", /* Bold */
"[7m", /* Invert */
"[0m", /* Normal */
"[7m", /* Invert */
};
static const char *
hp_colors[] = {
"&v0S", /* Whitel */
"&v1S", /* Red */
"&v2S", /* Green */
"&v3S", /* Yellow */
"&v4S", /* Blue */
"&v5S", /* Magenta */
"&v6S", /* Cyan */
};
const char **COSTerm::colors_ = nullptr;
std::string
COSTerm::
getTerminalName(int fd)
{
char *tty_name = ttyname(fd);
if (! tty_name)
return "";
return tty_name;
}
std::string
COSTerm::
getTerminalPath()
{
char *tty_name = ctermid(0);
if (! tty_name)
return "";
return tty_name;
}
pid_t
COSTerm::
getTerminalProcessGroupId(int fd)
{
std::string tty_name = getTerminalName(fd);
return getTerminalProcessGroupId(tty_name);
}
pid_t
COSTerm::
getTerminalProcessGroupId(const std::string &term)
{
int fd = open(term.c_str(), O_RDWR);
if (fd < 0) {
fd = open(term.c_str(), O_RDONLY);
if (fd < 0)
return -1;
}
pid_t id;
#ifdef NEVER
int error = ioctl(fd, TIOCGPGRP, (char *) &id);
#else
id = tcgetpgrp(fd);
#endif
close(fd);
return id;
}
pid_t
COSTerm::
getTerminalSessionId(int fd)
{
int tfd = getTerminalId(fd);
if (tfd < 0) return -1;
#ifdef COS_HAS_TCGETSID
pid_t id = tcgetsid(tfd);
#else
pid_t id = COSProcess::getSessionId(tcgetpgrp(tfd));
#endif
close(fd);
return id;
}
int
COSTerm::
getTerminalId(int fd)
{
std::string tty_name = getTerminalName(fd);
int tfd = open(tty_name.c_str(), O_RDWR);
if (tfd < 0) {
tfd = open(tty_name.c_str(), O_RDONLY);
if (tfd < 0)
return -1;
}
return tfd;
}
bool
COSTerm::
getCharSize(int *rows, int *cols)
{
if (isatty(STDIN_FILENO)) {
if (getCharSize(STDIN_FILENO, rows, cols))
return true;
}
#ifdef CURSES
WINDOW *w;
use_env(false);
w = initscr();
endwin();
*rows = LINES;
*cols = COLS;
#else
*rows = 60;
*cols = 0;
char *columns;
if ((columns = getenv("COLUMNS")) != nullptr)
*cols = atoi(columns);
if (*cols == 0)
*cols = COSTerm::getNumColumns();
if (*cols == 0)
*cols = 80;
#endif
return false;
}
bool
COSTerm::
getCharSize(int fd, int *rows, int *cols)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
*rows = ts.ws_row;
*cols = ts.ws_col;
return true;
}
bool
COSTerm::
setCharSize(int fd, int rows, int cols)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
if (ts.ws_col != 0)
ts.ws_xpixel = cols*(ts.ws_xpixel/ts.ws_col);
if (ts.ws_row != 0)
ts.ws_ypixel = rows*(ts.ws_ypixel/ts.ws_row);
ts.ws_row = rows;
ts.ws_col = cols;
ioctl(fd, TIOCSWINSZ, (char *) &ts);
return true;
}
bool
COSTerm::
getPixelSize(int *width, int *height)
{
int fd = COSTerm::getTerminalId();
if (fd < 0)
return false;
return getPixelSize(fd, width, height);
}
bool
COSTerm::
getPixelSize(int fd, int *width, int *height)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
*width = ts.ws_xpixel;
*height = ts.ws_ypixel;
return true;
}
bool
COSTerm::
setPixelSize(int fd, int width, int height)
{
struct winsize ts;
if (ioctl(fd, TIOCGWINSZ, &ts) == -1)
return false;
if (ts.ws_xpixel != 0)
ts.ws_row = (width *ts.ws_col)/ts.ws_xpixel;
if (ts.ws_ypixel != 0)
ts.ws_col = (height*ts.ws_row)/ts.ws_ypixel;
ts.ws_xpixel = width;
ts.ws_ypixel = height;
ioctl(fd, TIOCSWINSZ, (char *) &ts);
return true;
}
int
COSTerm::
getNumColumns()
{
static char term_buffer[2048];
const char *term;
if ((term = getenv("TERM")) == nullptr)
term = "vt100";
int no = tgetent(term_buffer, (char *) term);
if (no <= 0)
return 0;
int cols = tgetnum((char *) "cols");
return cols;
}
const char *
COSTerm::
getColorStr(int color)
{
if (color < 0 || color > 6)
return "";
const char **colors = getColorStrs();
return colors[color];
}
const char **
COSTerm::
getColorStrs()
{
if (! colors_) {
const char *term;
if ((term = getenv("TERM")) == nullptr)
term = "vt100";
if (strcmp(term, "xterm" ) == 0 ||
strcmp(term, "xterm-color" ) == 0 ||
strcmp(term, "xterm-256color") == 0) {
bool colored = true;
char *color_xterm;
if ((color_xterm = getenv( "COLOR_XTERM")) == nullptr &&
(color_xterm = getenv("COLOUR_XTERM")) == nullptr)
colored = false;
if (colored)
colors_ = color_xterm_colors;
else
colors_ = normal_xterm_colors;
}
else if (strncmp(term, "hp", 2) == 0)
colors_ = hp_colors;
else
colors_ = normal_xterm_colors;
}
return colors_;
}
bool
COSTerm::
cgets(std::string &buf)
{
FILE *tty;
std::string tty_name = COSTerm::getTerminalName(STDIN_FILENO);
if (! (tty = fopen(tty_name.c_str(), "w+")))
return false;
/* get attributes on the input tty and set them to new settings */
struct termios init, newsettings;
tcgetattr(fileno(stdin), &init);
newsettings = init;
newsettings.c_lflag &= ~(ICANON | ECHO);
newsettings.c_cc[VMIN ] = 1;
newsettings.c_cc[VTIME] = 0;
if (tcsetattr(fileno(stdin), TCSANOW, &newsettings) != 0)
return -1;
int c;
for (;;) {
c = getc(stdin);
if ((c == '\n') || (c == '\r') || (c == EOF))
break;
if ((c == '\b') || (c == 0x7f)) {
if (buf.size() > 0) {
buf = buf.substr(0, buf.size() - 1);
fputs("\b \b", stdout);
}
else
putc('\a', stdout);
continue;
}
fputc(c, stdout);
buf += char(c);
}
tcsetattr(fileno(tty), TCSANOW, &init);
fflush(tty);
fclose(tty);
printf("\n");
return true;
}
//-------
bool
COSTerm::
openMasterPty(int *fd, std::string &slaveName)
{
// Open Master Pseudo Terminal
#if HAS_POSIX_OPENPT
*fd = posix_openpt(O_RDWR | O_NOCTTY);
#elif HAS_GETPT
*fd = getpt();
#elif HAS_PTMX
*fd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
#elif BSD_TERM
// TODO: need new pty name here. For BSD this will by names:
// /dev/pty<X><Y> where <X> is [p-za-e] and <Y> is [0-9a-f]
static char xchars[] = "pqrstuvwxyzabcde";
static uint num_xchars = sizeof(xchars);
static char ychars[] = "0123456789abcdef";
static uint num_ychars = sizeof(ychars);
static char bsd_pty[] = "/dev/ptyxy";
static char bsd_tty[] = "/dev/ttyxy";
for (uint x = 0; x < num_xchars; ++x) {
bsd_pty[8] = xchars[x];
bsd_tty[8] = xchars[x];
for (uint y = 0; y < num_ychars; ++y) {
bsd_pty[9] = ychars[y];
bsd_tty[9] = ychars[y];
*fd = open(bsd_pty, O_RDWR | O_NOCTTY);
if (*fd == -1) {
if (errno == ENOENT) break;
continue;
}
if (*fd >= 0) break;
}
}
#else
return false;
#endif
if (*fd == -1)
return false;
//----
#ifndef BSD_TERM
// Ensure Terminal has process permission (needed to make portable)
if (grantpt(*fd) == -1) {
closeNoError(*fd); *fd = -1;
return false;
}
//----
// Finished setup so we now must unlock slave to use
if (unlockpt(*fd) == -1) {
closeNoError(*fd); *fd = -1;
return false;
}
//----
char *ptr = ptsname(*fd);
if (! ptr) {
closeNoError(*fd); *fd = -1;
return false;
}
slaveName = ptr;
#else
slaveName = bsd_tty;
#endif
return true;
}
bool
COSTerm::
ptyFork(int *mfd, std::string &slaveName, pid_t *childPid)
{
*mfd = 0;
*childPid = 0;
if (! openMasterPty(mfd, slaveName))
return false;
*childPid = fork();
if (*childPid == -1) { // failed
closeNoError(*mfd);
return false;
}
// ---- parent ----
if (*childPid != 0)
return true;
// ---- child ----
// master pty not needed
close(*mfd);
// start new session (child loses controlling terminal)
if (setsid() == -1)
COSErr::exit("ptyFork: setsid");
// Becomes controlling tty
int sfd = open(slaveName.c_str(), O_RDWR);
if (sfd == -1)
COSErr::exit("ptyFork: open-slave");
#ifdef TIOCSCTTY
// Acquire controlling tty on BSD
if (ioctl(sfd, TIOCSCTTY, 0) == -1)
COSErr::exit("ptyFork:ioctl-TIOCSCTTY");
#endif
// Duplicate pty slave to be child's stdin, stdout, and stderr
if (dup2(sfd, STDIN_FILENO ) != STDIN_FILENO ) COSErr::exit("ptyFork:dup2-STDIN_FILENO");
if (dup2(sfd, STDOUT_FILENO) != STDOUT_FILENO) COSErr::exit("ptyFork:dup2-STDOUT_FILENO");
if (dup2(sfd, STDERR_FILENO) != STDERR_FILENO) COSErr::exit("ptyFork:dup2-STDERR_FILENO");
// No longer need pty slave (don't close if equal to stdin, stdout or stderr
if (sfd > STDERR_FILENO)
closeNoError(sfd);
return true;
}
//-------
void
COSTerm::
closeNoError(int fd)
{
int saveErrno = errno;
(void) close(fd);
errno = saveErrno;
}
<|endoftext|> |
<commit_before>/*
* JsonicControlPolicyParamLoader.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com> 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "JsonicControlPolicyParamLoader.h"
#include "PolicyParams.h"
#include <fstream>
#include <lib/json_spirit/json_spirit.h>
#include <lib/json_spirit/json_spirit_stream_reader.h>
#include <boost/filesystem.hpp>
#include <opencog/guile/load-file.h>
#include <opencog/util/files.h>
#include <opencog/util/misc.h>
#include <opencog/util/Config.h>
using namespace opencog;
/**
* Constructor for JsonicControlPolicyParamLoader
*
* @param as the atomspace where the rules' BindLink are loaded into
* @param conf_path path to the .json file
*/
JsonicControlPolicyParamLoader::JsonicControlPolicyParamLoader(AtomSpace* as,
string conf_path)
: as_(as), conf_path_(conf_path)
{
cur_read_rule_ = NULL;
attention_alloc_ = false;
scm_eval_ = SchemeEval::get_evaluator(as_);
}
/**
* Destructor for JsonicControlPolicyParamLoader
*/
JsonicControlPolicyParamLoader::~JsonicControlPolicyParamLoader()
{
// delete all dynamically allocated Rule object
for (Rule* r : rules_)
delete r;
}
/**
* The main method for actually loading the config file.
*
* The .json file is not loaded until this method is called.
*/
void JsonicControlPolicyParamLoader::load_config()
{
try {
ifstream is(get_working_path(conf_path_));
Stream_reader<ifstream, Value> reader(is);
Value value;
while (reader.read_next(value))
read_json(value);
set_disjunct_rules();
} catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
}
/**
* Get the max iteration value set in the .json
*
* @return the maximum iteration size
*/
int JsonicControlPolicyParamLoader::get_max_iter()
{
return max_iter_;
}
/**
* Get all rules defined in the control policy config.
*
* @return a vector of Rule*
*/
vector<Rule*> &JsonicControlPolicyParamLoader::get_rules()
{
return rules_;
}
/**
* Get whether to use attentional focus.
*
* For controlling whether to look only for atoms in the attentional focus or
* the entire atomspace.
*
* @return true to use attentional focus, false otherwise
*/
bool JsonicControlPolicyParamLoader::get_attention_alloc()
{
return attention_alloc_;
}
/**
* Helper class for reading json value of type Array.
*
* @param v a json Value
* @param lev the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_array(const Value &v, int lev)
{
const Array& a = v.get_array();
for (Array::size_type i = 0; i < a.size(); ++i)
read_json(a[i], lev + 1);
}
/**
* Helper class for reading json value of type Object.
*
* @param v a json Value
* @param lev the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_obj(const Value &v, int lev)
{
const Object& o = v.get_obj();
for (Object::size_type i = 0; i < o.size(); ++i) {
const Pair& p = o[i];
auto key = p.name_;
Value value = p.value_;
if (key == RULES) {
read_json(value, lev + 1);
} else if (key == RULE_NAME) {
cur_read_rule_ = new Rule(Handle::UNDEFINED);
// the rule name is actually a scheme variable on the same name
cur_read_rule_->set_name(value.get_value<string>());
rules_.push_back(cur_read_rule_); // XXX take care of pointers
} else if (key == FILE_PATH) {
load_scm_file_relative(*as_, value.get_value<string>(),
DEFAULT_MODULE_PATHS);
// resolve the scheme variable to get the BindLink
Handle rule_handle = scm_eval_->eval_h(cur_read_rule_->get_name());
cur_read_rule_->set_handle(rule_handle);
} else if (key == PRIORITY) {
cur_read_rule_->set_cost(value.get_value<int>());
} else if (key == CATEGORY) {
cur_read_rule_->set_category(value.get_value<string>());
} else if (key == ATTENTION_ALLOC) {
attention_alloc_ = value.get_value<bool>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else if (key == MUTEX_RULES and value.type() != null_type) {
const Array& a = value.get_array();
for (Array::size_type i = 0; i < a.size(); ++i) {
rule_mutex_map_[cur_read_rule_].push_back(a[i].get_value<string>());
}
} else if (key == MAX_ITER) {
max_iter_ = value.get_value<int>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else {
read_json(value, lev + 1);
}
}
}
/**
* Helper class for reading a json Value of any type.
*
* Mostly for calling helper method for each type.
*
* @param v a json Value
* @param level the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_json(const Value &v,
int level /* = -1*/)
{
switch (v.type())
{
case obj_type:
read_obj(v, level + 1);
break;
case array_type:
read_array(v, level + 1);
break;
case str_type:
break;
case bool_type:
break;
case int_type:
break;
case real_type:
break;
case null_type:
read_null(v, level + 1);
break;
default:
break;
}
}
/**
* Helper class for reading json value of type null.
*
* @param v a json Value
* @param lev the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_null(const Value &v, int lev)
{
}
/**
* XXX FIXME What is this method for?
*/
template<typename> void JsonicControlPolicyParamLoader::read_primitive(
const Value &v, int lev)
{
}
/**
* sets the disjunct rules
*
* XXX FIXME What is this method for?
*/
void JsonicControlPolicyParamLoader::set_disjunct_rules(void)
{
}
/**
* Get a single Rule of a specific name.
*
* @param name the name of the Rule
* @return pointer to a Rule object if found, nullptr otherwise
*/
Rule* JsonicControlPolicyParamLoader::get_rule(const string& name)
{
for (Rule* r : rules_) {
if (r->get_name() == name)
return r;
}
return nullptr;
}
/**
* Resolve which search path actually contain the file.
*
* Look throught each path in search_paths and check if file of filename
* exists.
*
* @param filename the name or sub-path to a file
* @param search_paths a vector of paths to look
* @return a successful path
*/
const string JsonicControlPolicyParamLoader::get_working_path(
const string& filename, vector<string> search_paths)
{
if (search_paths.empty())
search_paths = DEFAULT_MODULE_PATHS;
for (auto search_path : search_paths) {
boost::filesystem::path modulePath(search_path);
modulePath /= filename;
logger().debug("Searching path %s", modulePath.string().c_str());
if (boost::filesystem::exists(modulePath))
return modulePath.string();
}
throw RuntimeException(TRACE_INFO, "%s could not be found",
filename.c_str());
}
/**
* Get the set of mutually exclusive rules defined in the control policy file
*
* XXX What is this?
*
* @return a vector of a vector of Rule*
*/
vector<vector<Rule*> > JsonicControlPolicyParamLoader::get_mutex_sets()
{
return mutex_sets_;
}
<commit_msg>Anoher sarch path tweak<commit_after>/*
* JsonicControlPolicyParamLoader.cc
*
* Copyright (C) 2015 Misgana Bayetta
*
* Author: Misgana Bayetta <misgana.bayetta@gmail.com> 2015
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "JsonicControlPolicyParamLoader.h"
#include "PolicyParams.h"
#include <fstream>
#include <lib/json_spirit/json_spirit.h>
#include <lib/json_spirit/json_spirit_stream_reader.h>
#include <boost/filesystem.hpp>
#include <opencog/guile/load-file.h>
#include <opencog/util/files.h>
#include <opencog/util/misc.h>
#include <opencog/util/Config.h>
using namespace opencog;
/**
* Constructor for JsonicControlPolicyParamLoader
*
* @param as the atomspace where the rules' BindLink are loaded into
* @param conf_path path to the .json file
*/
JsonicControlPolicyParamLoader::JsonicControlPolicyParamLoader(AtomSpace* as,
string conf_path)
: as_(as), conf_path_(conf_path)
{
cur_read_rule_ = NULL;
attention_alloc_ = false;
scm_eval_ = SchemeEval::get_evaluator(as_);
}
/**
* Destructor for JsonicControlPolicyParamLoader
*/
JsonicControlPolicyParamLoader::~JsonicControlPolicyParamLoader()
{
// delete all dynamically allocated Rule object
for (Rule* r : rules_)
delete r;
}
/**
* The main method for actually loading the config file.
*
* The .json file is not loaded until this method is called.
*/
void JsonicControlPolicyParamLoader::load_config()
{
try {
ifstream is(get_working_path(conf_path_));
Stream_reader<ifstream, Value> reader(is);
Value value;
while (reader.read_next(value))
read_json(value);
set_disjunct_rules();
} catch (std::ios_base::failure& e) {
std::cerr << e.what() << '\n';
}
}
/**
* Get the max iteration value set in the .json
*
* @return the maximum iteration size
*/
int JsonicControlPolicyParamLoader::get_max_iter()
{
return max_iter_;
}
/**
* Get all rules defined in the control policy config.
*
* @return a vector of Rule*
*/
vector<Rule*> &JsonicControlPolicyParamLoader::get_rules()
{
return rules_;
}
/**
* Get whether to use attentional focus.
*
* For controlling whether to look only for atoms in the attentional focus or
* the entire atomspace.
*
* @return true to use attentional focus, false otherwise
*/
bool JsonicControlPolicyParamLoader::get_attention_alloc()
{
return attention_alloc_;
}
/**
* Helper class for reading json value of type Array.
*
* @param v a json Value
* @param lev the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_array(const Value &v, int lev)
{
const Array& a = v.get_array();
for (Array::size_type i = 0; i < a.size(); ++i)
read_json(a[i], lev + 1);
}
/**
* Helper class for reading json value of type Object.
*
* @param v a json Value
* @param lev the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_obj(const Value &v, int lev)
{
const Object& o = v.get_obj();
for (Object::size_type i = 0; i < o.size(); ++i) {
const Pair& p = o[i];
auto key = p.name_;
Value value = p.value_;
if (key == RULES) {
read_json(value, lev + 1);
} else if (key == RULE_NAME) {
cur_read_rule_ = new Rule(Handle::UNDEFINED);
// the rule name is actually a scheme variable on the same name
cur_read_rule_->set_name(value.get_value<string>());
rules_.push_back(cur_read_rule_); // XXX take care of pointers
} else if (key == FILE_PATH) {
load_scm_file_relative(*as_, value.get_value<string>(),
DEFAULT_MODULE_PATHS);
// resolve the scheme variable to get the BindLink
Handle rule_handle = scm_eval_->eval_h(cur_read_rule_->get_name());
cur_read_rule_->set_handle(rule_handle);
} else if (key == PRIORITY) {
cur_read_rule_->set_cost(value.get_value<int>());
} else if (key == CATEGORY) {
cur_read_rule_->set_category(value.get_value<string>());
} else if (key == ATTENTION_ALLOC) {
attention_alloc_ = value.get_value<bool>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else if (key == MUTEX_RULES and value.type() != null_type) {
const Array& a = value.get_array();
for (Array::size_type i = 0; i < a.size(); ++i) {
rule_mutex_map_[cur_read_rule_].push_back(a[i].get_value<string>());
}
} else if (key == MAX_ITER) {
max_iter_ = value.get_value<int>();
} else if (key == LOG_LEVEL) {
log_level_ = value.get_value<string>();
} else {
read_json(value, lev + 1);
}
}
}
/**
* Helper class for reading a json Value of any type.
*
* Mostly for calling helper method for each type.
*
* @param v a json Value
* @param level the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_json(const Value &v,
int level /* = -1*/)
{
switch (v.type())
{
case obj_type:
read_obj(v, level + 1);
break;
case array_type:
read_array(v, level + 1);
break;
case str_type:
break;
case bool_type:
break;
case int_type:
break;
case real_type:
break;
case null_type:
read_null(v, level + 1);
break;
default:
break;
}
}
/**
* Helper class for reading json value of type null.
*
* @param v a json Value
* @param lev the depth level of the json Value
*/
void JsonicControlPolicyParamLoader::read_null(const Value &v, int lev)
{
}
/**
* XXX FIXME What is this method for?
*/
template<typename> void JsonicControlPolicyParamLoader::read_primitive(
const Value &v, int lev)
{
}
/**
* sets the disjunct rules
*
* XXX FIXME What is this method for?
*/
void JsonicControlPolicyParamLoader::set_disjunct_rules(void)
{
}
/**
* Get a single Rule of a specific name.
*
* @param name the name of the Rule
* @return pointer to a Rule object if found, nullptr otherwise
*/
Rule* JsonicControlPolicyParamLoader::get_rule(const string& name)
{
for (Rule* r : rules_) {
if (r->get_name() == name)
return r;
}
return nullptr;
}
/**
* Resolve which search path actually contain the file.
*
* Look throught each path in search_paths and check if file of filename
* exists.
*
* @param filename the name or sub-path to a file
* @param search_paths a vector of paths to look
* @return a successful path
*/
const string JsonicControlPolicyParamLoader::get_working_path(
const string& filename, vector<string> search_paths)
{
if (search_paths.empty()) {
// Sometimes paths are given without the "opencog" part.
// Also check the build directory for autogen'ed files.
// XXX This is fairly tacky/broken, and needs a better fix.
for (auto p : DEFAULT_MODULE_PATHS) {
search_paths.push_back(p);
search_paths.push_back(p + "/opencog");
search_paths.push_back(p + "/build");
search_paths.push_back(p + "/build/opencog");
}
}
for (auto search_path : search_paths) {
boost::filesystem::path modulePath(search_path);
modulePath /= filename;
logger().debug("Searching path %s", modulePath.string().c_str());
if (boost::filesystem::exists(modulePath))
return modulePath.string();
}
throw RuntimeException(TRACE_INFO, "%s could not be found",
filename.c_str());
}
/**
* Get the set of mutually exclusive rules defined in the control policy file
*
* XXX What is this?
*
* @return a vector of a vector of Rule*
*/
vector<vector<Rule*> > JsonicControlPolicyParamLoader::get_mutex_sets()
{
return mutex_sets_;
}
<|endoftext|> |
<commit_before>#include "CamShift.h"
#include "OpenCV.h"
#include "Matrix.h"
#define CHANNEL_HUE 0
#define CHANNEL_SATURATION 1
#define CHANNEL_VALUE 2
Persistent<FunctionTemplate> TrackedObject::constructor;
void
TrackedObject::Init(Handle<Object> target) {
HandleScope scope;
// Constructor
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(TrackedObject::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::NewSymbol("TrackedObject"));
// Prototype
//Local<ObjectTemplate> proto = constructor->PrototypeTemplate();
NODE_SET_PROTOTYPE_METHOD(constructor, "track", Track);
target->Set(String::NewSymbol("TrackedObject"), constructor->GetFunction());
};
Handle<Value>
TrackedObject::New(const Arguments &args) {
HandleScope scope;
if (args.This()->InternalFieldCount() == 0){
JSTHROW_TYPE("Cannot Instantiate without new")
}
Matrix* m = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::Rect r;
int channel = CHANNEL_HUE;
if (args[1]->IsArray()){
Local<Object> v8rec = args[1]->ToObject();
r = cv::Rect(
v8rec->Get(0)->IntegerValue(),
v8rec->Get(1)->IntegerValue(),
v8rec->Get(2)->IntegerValue() - v8rec->Get(0)->IntegerValue(),
v8rec->Get(3)->IntegerValue() - v8rec->Get(1)->IntegerValue());
} else {
JSTHROW_TYPE("Must pass rectangle to track")
}
if (args[2]->IsObject()){
Local<Object> opts = args[2]->ToObject();
if (opts->Get(String::New("channel"))->IsString()){
v8::String::Utf8Value c(opts->Get(String::New("channel"))->ToString());
std::string cc = std::string(*c);
if (cc == "hue" || cc == "h"){
channel = CHANNEL_HUE;
}
if (cc == "saturation" || cc == "s"){
channel = CHANNEL_SATURATION;
}
if (cc == "value" || cc == "v"){
channel = CHANNEL_VALUE;
}
}
}
TrackedObject *to = new TrackedObject(m->mat, r, channel);
to->Wrap(args.This());
return args.This();
}
void update_chann_image(TrackedObject* t, cv::Mat image){
// Store HSV Hue Image
cv::cvtColor(image, t->hsv, CV_BGR2HSV); // convert to HSV space
//mask out-of-range values
int vmin = 65, vmax = 256, smin = 55;
cv::inRange(t->hsv, //source
cv::Scalar(0, smin, MIN(vmin, vmax), 0), //lower bound
cv::Scalar(180, 256, MAX(vmin, vmax) ,0), //upper bound
t->mask); //destination
//extract the hue channel, split: src, dest channels
vector<cv::Mat> hsvplanes;
cv::split(t->hsv, hsvplanes);
t->hue = hsvplanes[t->channel];
}
TrackedObject::TrackedObject(cv::Mat image, cv::Rect rect, int chan){
channel = chan;
update_chann_image(this, image);
prev_rect = rect;
// Calculate Histogram
int hbins = 30, sbins = 32;
int histSizes[] = {hbins, sbins};
//float hranges[] = { 0, 180 };
// saturation varies from 0 (black-gray-white) to
// 255 (pure spectrum color)
float sranges[] = { 0, 256 };
const float* ranges[] = { sranges };
cv::Mat hue_roi = hue(rect);
cv::Mat mask_roi = mask(rect);
cv::calcHist(&hue_roi, 1, 0, mask_roi, hist, 1, histSizes, ranges, true, false);
}
Handle<Value>
TrackedObject::Track(const v8::Arguments& args){
SETUP_FUNCTION(TrackedObject)
if (args.Length() != 1){
v8::ThrowException(v8::Exception::TypeError(v8::String::New("track takes an image param")));
return Undefined();
}
Matrix *im = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::RotatedRect r;
if (self->prev_rect.x <0 ||
self->prev_rect.y <0 ||
self->prev_rect.width <= 1 ||
self->prev_rect.height <= 1){
return v8::ThrowException(v8::Exception::TypeError(v8::String::New("OPENCV ERROR: prev rectangle is illogical")));
}
update_chann_image(self, im->mat);
cv::Rect backup_prev_rect = cv::Rect(
self->prev_rect.x,
self->prev_rect.y,
self->prev_rect.width,
self->prev_rect.height);
float sranges[] = { 0, 256 };
const float* ranges[] = { sranges };
int channel = 0;
cv::calcBackProject(&self->hue, 1, &channel, self->hist, self->prob, ranges);
r = cv::CamShift(self->prob, self->prev_rect,
cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1));
cv::Rect bounds = r.boundingRect();
if (bounds.x >=0 && bounds.y >=0 && bounds.width > 1 && bounds.height > 1){
self->prev_rect = bounds;
} else {
//printf("CRAP> %i %i %i %i ;", self->prev_rect.x, self->prev_rect.y, self->prev_rect.width, self->prev_rect.height);
// We have encountered a bug in opencv. Somehow the prev_rect has got mangled, so we
// must reset it to a good value.
self->prev_rect = backup_prev_rect;
}
v8::Local<v8::Array> arr = v8::Array::New(4);
arr->Set(0, Number::New(bounds.x));
arr->Set(1, Number::New(bounds.y));
arr->Set(2, Number::New(bounds.x + bounds.width));
arr->Set(3, Number::New(bounds.y + bounds.height));
/*
cv::Point2f pts[4];
r.points(pts);
for (int i=0; i<8; i+=2){
arr->Set(i, Number::New(pts[i].x));
arr->Set(i+1, Number::New(pts[i].y));
}
*/
return scope.Close(arr);
}
<commit_msg>std::vector, explicitly<commit_after>#include "CamShift.h"
#include "OpenCV.h"
#include "Matrix.h"
#define CHANNEL_HUE 0
#define CHANNEL_SATURATION 1
#define CHANNEL_VALUE 2
Persistent<FunctionTemplate> TrackedObject::constructor;
void
TrackedObject::Init(Handle<Object> target) {
HandleScope scope;
// Constructor
constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(TrackedObject::New));
constructor->InstanceTemplate()->SetInternalFieldCount(1);
constructor->SetClassName(String::NewSymbol("TrackedObject"));
// Prototype
//Local<ObjectTemplate> proto = constructor->PrototypeTemplate();
NODE_SET_PROTOTYPE_METHOD(constructor, "track", Track);
target->Set(String::NewSymbol("TrackedObject"), constructor->GetFunction());
};
Handle<Value>
TrackedObject::New(const Arguments &args) {
HandleScope scope;
if (args.This()->InternalFieldCount() == 0){
JSTHROW_TYPE("Cannot Instantiate without new")
}
Matrix* m = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::Rect r;
int channel = CHANNEL_HUE;
if (args[1]->IsArray()){
Local<Object> v8rec = args[1]->ToObject();
r = cv::Rect(
v8rec->Get(0)->IntegerValue(),
v8rec->Get(1)->IntegerValue(),
v8rec->Get(2)->IntegerValue() - v8rec->Get(0)->IntegerValue(),
v8rec->Get(3)->IntegerValue() - v8rec->Get(1)->IntegerValue());
} else {
JSTHROW_TYPE("Must pass rectangle to track")
}
if (args[2]->IsObject()){
Local<Object> opts = args[2]->ToObject();
if (opts->Get(String::New("channel"))->IsString()){
v8::String::Utf8Value c(opts->Get(String::New("channel"))->ToString());
std::string cc = std::string(*c);
if (cc == "hue" || cc == "h"){
channel = CHANNEL_HUE;
}
if (cc == "saturation" || cc == "s"){
channel = CHANNEL_SATURATION;
}
if (cc == "value" || cc == "v"){
channel = CHANNEL_VALUE;
}
}
}
TrackedObject *to = new TrackedObject(m->mat, r, channel);
to->Wrap(args.This());
return args.This();
}
void update_chann_image(TrackedObject* t, cv::Mat image){
// Store HSV Hue Image
cv::cvtColor(image, t->hsv, CV_BGR2HSV); // convert to HSV space
//mask out-of-range values
int vmin = 65, vmax = 256, smin = 55;
cv::inRange(t->hsv, //source
cv::Scalar(0, smin, MIN(vmin, vmax), 0), //lower bound
cv::Scalar(180, 256, MAX(vmin, vmax) ,0), //upper bound
t->mask); //destination
//extract the hue channel, split: src, dest channels
std::vector<cv::Mat> hsvplanes;
cv::split(t->hsv, hsvplanes);
t->hue = hsvplanes[t->channel];
}
TrackedObject::TrackedObject(cv::Mat image, cv::Rect rect, int chan){
channel = chan;
update_chann_image(this, image);
prev_rect = rect;
// Calculate Histogram
int hbins = 30, sbins = 32;
int histSizes[] = {hbins, sbins};
//float hranges[] = { 0, 180 };
// saturation varies from 0 (black-gray-white) to
// 255 (pure spectrum color)
float sranges[] = { 0, 256 };
const float* ranges[] = { sranges };
cv::Mat hue_roi = hue(rect);
cv::Mat mask_roi = mask(rect);
cv::calcHist(&hue_roi, 1, 0, mask_roi, hist, 1, histSizes, ranges, true, false);
}
Handle<Value>
TrackedObject::Track(const v8::Arguments& args){
SETUP_FUNCTION(TrackedObject)
if (args.Length() != 1){
v8::ThrowException(v8::Exception::TypeError(v8::String::New("track takes an image param")));
return Undefined();
}
Matrix *im = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject());
cv::RotatedRect r;
if (self->prev_rect.x <0 ||
self->prev_rect.y <0 ||
self->prev_rect.width <= 1 ||
self->prev_rect.height <= 1){
return v8::ThrowException(v8::Exception::TypeError(v8::String::New("OPENCV ERROR: prev rectangle is illogical")));
}
update_chann_image(self, im->mat);
cv::Rect backup_prev_rect = cv::Rect(
self->prev_rect.x,
self->prev_rect.y,
self->prev_rect.width,
self->prev_rect.height);
float sranges[] = { 0, 256 };
const float* ranges[] = { sranges };
int channel = 0;
cv::calcBackProject(&self->hue, 1, &channel, self->hist, self->prob, ranges);
r = cv::CamShift(self->prob, self->prev_rect,
cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1));
cv::Rect bounds = r.boundingRect();
if (bounds.x >=0 && bounds.y >=0 && bounds.width > 1 && bounds.height > 1){
self->prev_rect = bounds;
} else {
//printf("CRAP> %i %i %i %i ;", self->prev_rect.x, self->prev_rect.y, self->prev_rect.width, self->prev_rect.height);
// We have encountered a bug in opencv. Somehow the prev_rect has got mangled, so we
// must reset it to a good value.
self->prev_rect = backup_prev_rect;
}
v8::Local<v8::Array> arr = v8::Array::New(4);
arr->Set(0, Number::New(bounds.x));
arr->Set(1, Number::New(bounds.y));
arr->Set(2, Number::New(bounds.x + bounds.width));
arr->Set(3, Number::New(bounds.y + bounds.height));
/*
cv::Point2f pts[4];
r.points(pts);
for (int i=0; i<8; i+=2){
arr->Set(i, Number::New(pts[i].x));
arr->Set(i+1, Number::New(pts[i].y));
}
*/
return scope.Close(arr);
}
<|endoftext|> |
<commit_before>#include "alloutil/al_World.hpp"
#include "allocore/graphics/al_Isosurface.hpp"
using namespace al;
class MyActor : public Actor{
public:
MyActor(){}
virtual void onDraw(Graphics& g, const Viewpoint& v){
Frustumd fr;
v.camera().frustum(fr, v.worldTransform(), v.viewport().aspect());
// printf("ntl: %g %g %g\n", fr.ntl[0], fr.ntl[1], fr.ntl[2]);
// printf("ftl: %g %g %g\n", fr.ftl[0], fr.ftl[1], fr.ftl[2]);
Mesh& m = g.mesh();
m.reset();
m.primitive(g.LINES);
m.vertex(-1,-1,11);
m.vertex( 1, 1,12);
for(int i=0; i<m.vertices().size(); ++i){
int r = fr.testPoint(m.vertices()[i]);
m.color(HSV(r ? 0.3 : 0));
}
g.lineWidth(10);
g.antialiasing(g.NICEST);
g.draw();
{
// int r = fr.testPoint(Vec3d(0,0,15));
// printf("%d\n", r);
}
// // draw frustum
// m.reset();
// m.vertex(fr.nbl);
// m.vertex(fr.nbr);
// m.vertex(fr.ntr);
// m.vertex(fr.ntl);
// m.vertex(fr.fbl);
// m.vertex(fr.fbr);
// m.vertex(fr.ftr);
// m.vertex(fr.ftl);
// m.color(Color(0.5,0.5,0.5));
// m.color(Color(1,0,0));
// m.color(Color(1,1,0));
// m.color(Color(0,1,0));
// m.color(Color(0,0,1));
// m.color(Color(1,0,1));
// m.color(Color(1,1,1));
// m.color(Color(0,1,1));
//
// {
// int edges[] = {
// 0,1, 3,2, 7,6, 4,5,
// 5,2,
// 2,6, 1,5, 0,4, 3,7,
// };
// for(unsigned e=0; e<sizeof(edges)/sizeof(edges[0]); ++e){
// m.index(edges[e]);
// }
// }
// m.primitive(g.LINE_STRIP);
// g.draw();
//
// m.indices().reset();
// {
// int edges[] = {
// 3, 2, 0, 1, 7, 6, 4, 5
// };
// for(unsigned e=0; e<sizeof(edges)/sizeof(edges[0]); ++e){
// m.index(edges[e]);
// }
// }
//
// g.pointSize(20);
// m.primitive(g.POINTS);
// g.draw();
}
};
int main(){
World w;
w.name("Frustum Testing");
w.camera().near(10).far(25);
w.nav().quat().fromAxisAngle(0, 0,0,1);
ViewpointWindow win(0,0, 600,400, w.name());
Viewpoint vp;
vp.parentTransform(w.nav());
MyActor myActor;
win.add(vp);
w.add(win, true);
w.add(myActor);
w.start();
return 0;
}
<commit_msg>frustumTesting example: added frustum diagonal rect<commit_after>#include "alloutil/al_World.hpp"
#include "allocore/graphics/al_Isosurface.hpp"
using namespace al;
class MyActor : public Actor{
public:
MyActor(){}
virtual void onDraw(Graphics& g, const Viewpoint& v){
Frustumd fr;
v.camera().frustum(fr, v.worldTransform(), v.viewport().aspect());
// printf("ntl: %g %g %g\n", fr.ntl[0], fr.ntl[1], fr.ntl[2]);
// printf("ftl: %g %g %g\n", fr.ftl[0], fr.ftl[1], fr.ftl[2]);
Mesh& m = g.mesh();
m.reset();
m.primitive(g.LINES);
m.vertex(-1,-1,11);
m.vertex( 1, 1,12);
for(int i=0; i<m.vertices().size(); ++i){
int r = fr.testPoint(m.vertices()[i]);
m.color(HSV(r ? 0.3 : 0));
}
g.lineWidth(10);
g.antialiasing(g.NICEST);
g.draw();
{
// int r = fr.testPoint(Vec3d(0,0,15));
// printf("%d\n", r);
}
// draw rectangle across frustum diagonal
m.reset();
m.color(Color(0.5));
m.vertex(fr.nbl);
m.vertex(fr.fbr);
m.vertex(fr.ntr);
m.vertex(fr.ftl);
m.primitive(g.LINE_LOOP);
g.draw();
}
};
int main(){
World w;
w.name("Frustum Testing");
w.camera().near(10).far(25);
w.nav().quat().fromAxisAngle(0, 0,0,1);
ViewpointWindow win(0,0, 600,400, w.name());
Viewpoint vp;
vp.parentTransform(w.nav());
MyActor myActor;
win.add(vp);
w.add(win, true);
w.add(myActor);
w.start();
return 0;
}
<|endoftext|> |
<commit_before>/*
* _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa
* .wWV!!!T |Wm; dQ[ $WF _mWT!"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW
* .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ
* |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: <B:$Qc :WBWQ()W[ dQ
* |W#: .ww ;WW; dQ[ dQ[ ....... ]Qk )QB?YYW#: jf ]Qp.:mE)Qm]Q[ )W
* +WQ; :Wm |Wm; .mQ[ dQ[ :qgggggga ]Qm. ]WE :Q# :=QasuQm;:Wk 3QQW[ )Y
* ]Wmi.:Wm +$Q; .mW( dQ[ !"!!"!!^ dQk, ._ ]WE :Q# :3D"!!$Qc.Wk -$WQ[
* "?????? ` "?!=m?! ??' -??????! -?! -?? -?' "?"-?" "??' "?
*
* Copyright (c) 2004 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of darkbits nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/sdl/sdlimageloader.hpp"
#include "guichan/exception.hpp"
#include <SDL/SDL_image.h>
namespace gcn
{
SDLImageLoader::SDLImageLoader()
{
mCurrentImage = NULL;
} // end SDLImageLoader
void SDLImageLoader::prepare(const std::string& filename)
{
if (mCurrentImage != NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::prepare. Function called before finalizing or discarding last loaded image.");
}
mCurrentImage = IMG_Load(filename.c_str());
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION(std::string("SDLImageLoader::prepare. Unable to load image file: ")+filename);
}
} // end prepare
void* SDLImageLoader::finalize()
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::finalize. No image prepared.");
}
SDL_DisplayFormat(mCurrentImage);
return finalizeNoConvert();
} // end finalize
void* SDLImageLoader::finalizeNoConvert()
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::finalizeNoConvert. No image prepared.");
}
SDL_Surface* temp = mCurrentImage;
mCurrentImage = NULL;
return temp;
} // end finalizeNoConvert
void SDLImageLoader::discard()
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::discard. No image prepared.");
}
SDL_FreeSurface(mCurrentImage);
mCurrentImage = NULL;
} // end discard
void SDLImageLoader::free(Image* image)
{
if (image->_getData() == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::free. Image data points to null.");
}
SDL_FreeSurface((SDL_Surface*)image->_getData());
} // end free
int SDLImageLoader::getWidth() const
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::getWidth. No image prepared.");
}
return mCurrentImage->w;
} // end getWidth
int SDLImageLoader::getHeight() const
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::getHeight. No image prepared.");
}
return mCurrentImage->h;
} // end getHeight
} // end gcn
<commit_msg>Implemented putPixel and getPixel.<commit_after>/*
* _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa
* .wWV!!!T |Wm; dQ[ $WF _mWT!"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW
* .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ
* |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: <B:$Qc :WBWQ()W[ dQ
* |W#: .ww ;WW; dQ[ dQ[ ....... ]Qk )QB?YYW#: jf ]Qp.:mE)Qm]Q[ )W
* +WQ; :Wm |Wm; .mQ[ dQ[ :qgggggga ]Qm. ]WE :Q# :=QasuQm;:Wk 3QQW[ )Y
* ]Wmi.:Wm +$Q; .mW( dQ[ !"!!"!!^ dQk, ._ ]WE :Q# :3D"!!$Qc.Wk -$WQ[
* "?????? ` "?!=m?! ??' -??????! -?! -?? -?' "?"-?" "??' "?
*
* Copyright (c) 2004 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of darkbits nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/sdl/sdlimageloader.hpp"
#include "guichan/exception.hpp"
#include "guichan/sdl/sdlpixel.hpp"
#include <SDL/SDL_image.h>
namespace gcn
{
SDLImageLoader::SDLImageLoader()
{
mCurrentImage = NULL;
} // end SDLImageLoader
void SDLImageLoader::prepare(const std::string& filename)
{
if (mCurrentImage != NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::prepare. Function called before finalizing or discarding last loaded image.");
}
mCurrentImage = IMG_Load(filename.c_str());
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION(std::string("SDLImageLoader::prepare. Unable to load image file: ")+filename);
}
} // end prepare
void* SDLImageLoader::finalize()
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::finalize. No image prepared.");
}
SDL_Surface* temp = SDL_DisplayFormat(mCurrentImage);
SDL_FreeSurface(mCurrentImage);
mCurrentImage = NULL;
return temp;
} // end finalize
void* SDLImageLoader::finalizeNoConvert()
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::finalizeNoConvert. No image prepared.");
}
SDL_Surface* temp = mCurrentImage;
mCurrentImage = NULL;
return temp;
} // end finalizeNoConvert
void SDLImageLoader::discard()
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::discard. No image prepared.");
}
SDL_FreeSurface(mCurrentImage);
mCurrentImage = NULL;
} // end discard
void SDLImageLoader::free(Image* image)
{
if (image->_getData() == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::free. Image data points to null.");
}
SDL_FreeSurface((SDL_Surface*)image->_getData());
} // end free
int SDLImageLoader::getWidth() const
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::getWidth. No image prepared.");
}
return mCurrentImage->w;
} // end getWidth
int SDLImageLoader::getHeight() const
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::getHeight. No image prepared.");
}
return mCurrentImage->h;
} // end getHeight
Color SDLImageLoader::getPixel(int x, int y)
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::getPixel. No image prepared.");
}
if (x < 0 || y < 0 || x >= mCurrentImage->w || y >= mCurrentImage->h)
{
throw GCN_EXCEPTION("SDLImageLoader::getPixel. x and y out of image bound.");
}
return SDLgetPixel(mCurrentImage, x, y);
} // end getPixel
void SDLImageLoader::putPixel(int x, int y, const Color& color)
{
if (mCurrentImage == NULL)
{
throw GCN_EXCEPTION("SDLImageLoader::putPixel. No image prepared.");
}
if (x < 0 || y < 0 || x >= mCurrentImage->w || y >= mCurrentImage->h)
{
throw GCN_EXCEPTION("SDLImageLoader::putPixel. x and y out of image bound.");
}
SDLputPixel(mCurrentImage, x, y, color);
} // end putPixel
} // end gcn
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/benchmark/benchmark_performance_options.h"
#include <algorithm>
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include "tensorflow/core/util/stats_calculator.h"
#include "tensorflow/lite/c/common.h"
#if defined(__ANDROID__)
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/nnapi/nnapi_util.h"
#endif
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/benchmark/benchmark_params.h"
#include "tensorflow/lite/tools/benchmark/benchmark_utils.h"
#include "tensorflow/lite/tools/command_line_flags.h"
#include "tensorflow/lite/tools/logging.h"
#if (defined(ANDROID) || defined(__ANDROID__)) && \
(defined(__arm__) || defined(__aarch64__))
#define TFLITE_ENABLE_HEXAGON
#endif
namespace tflite {
namespace benchmark {
std::string MultiRunStatsRecorder::PerfOptionName(
const BenchmarkParams& params) const {
#if defined(__ANDROID__)
if (params.Get<bool>("use_nnapi")) {
const std::string accelerator =
params.Get<std::string>("nnapi_accelerator_name");
return accelerator.empty() ? "nnapi(w/o accel name)"
: "nnapi(" + accelerator + ")";
}
#endif
if (params.Get<bool>("use_gpu")) {
#if defined(__ANDROID__)
if (params.Get<bool>("gpu_precision_loss_allowed")) {
return "gpu-fp16";
} else {
return "gpu-default";
}
#else
return "gpu-default";
#endif
}
#if defined(TFLITE_ENABLE_HEXAGON)
if (params.Get<bool>("use_hexagon")) {
return "dsp w/ hexagon";
}
#endif
// Handle cases run on CPU
// Note: could use std::to_string to convert an integer to string but it
// requires C++11.
std::stringstream sstm;
sstm << "cpu w/ " << params.Get<int32_t>("num_threads") << " threads";
// Handle cases run on CPU w/ the xnnpack delegate
if (params.Get<bool>("use_xnnpack")) {
sstm << " (xnnpack)";
}
return sstm.str();
}
void MultiRunStatsRecorder::OutputStats() {
// Make a 80-character-long header.
TFLITE_LOG(INFO) << "\n==============Summary of All Runs w/ Different "
"Performance Options==============";
std::sort(results_.begin(), results_.end(), EachRunStatsEntryComparator());
for (const auto& run_stats : results_) {
const auto perf_option_name = PerfOptionName(*run_stats.params);
std::stringstream stream;
stream << std::setw(26) << perf_option_name << ": ";
if (!run_stats.completed) {
stream << " failed!";
} else {
run_stats.metrics.inference_time_us().OutputToStream(&stream);
// NOTE: As of 2019/11/07, the memory usage is collected in an
// OS-process-wide way and this program performs multiple runs in a single
// OS process, therefore, the memory usage information of each run becomes
// incorrect, hence no output here.
}
TFLITE_LOG(INFO) << stream.str();
}
}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkModel* single_option_run,
std::unique_ptr<MultiRunStatsRecorder> all_run_stats)
: BenchmarkPerformanceOptions(DefaultParams(), single_option_run,
std::move(all_run_stats)) {}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkParams params, BenchmarkModel* single_option_run,
std::unique_ptr<MultiRunStatsRecorder> all_run_stats)
: params_(std::move(params)),
single_option_run_(single_option_run),
single_option_run_params_(single_option_run->mutable_params()),
all_run_stats_(std::move(all_run_stats)) {
single_option_run_->AddListener(all_run_stats_.get());
}
BenchmarkParams BenchmarkPerformanceOptions::DefaultParams() {
BenchmarkParams params;
params.AddParam("perf_options_list",
BenchmarkParam::Create<std::string>("all"));
params.AddParam("option_benchmark_run_delay",
BenchmarkParam::Create<float>(-1.0f));
params.AddParam("random_shuffle_benchmark_runs",
BenchmarkParam::Create<bool>(true));
return params;
}
std::vector<Flag> BenchmarkPerformanceOptions::GetFlags() {
return {
CreateFlag<std::string>(
"perf_options_list", ¶ms_,
"A comma-separated list of TFLite performance options to benchmark. "
"By default, all performance options are benchmarked. Note if it's "
"set to 'none', then the tool simply benchmark the model against the "
"specified benchmark parameters."),
CreateFlag<float>("option_benchmark_run_delay", ¶ms_,
"The delay between two consecutive runs of "
"benchmarking performance options in seconds."),
CreateFlag<bool>(
"random_shuffle_benchmark_runs", ¶ms_,
"Whether to perform all benchmark runs, each of which has different "
"performance options, in a random order. It is enabled by default."),
};
}
bool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) {
auto flag_list = GetFlags();
const bool parse_result =
Flags::Parse(argc, const_cast<const char**>(argv), flag_list);
if (!parse_result) {
std::string usage = Flags::Usage(argv[0], flag_list);
TFLITE_LOG(ERROR) << usage;
return false;
}
// Parse the value of --perf_options_list to find performance options to be
// benchmarked.
return ParsePerfOptions();
}
bool BenchmarkPerformanceOptions::ParsePerfOptions() {
const auto& perf_options_list = params_.Get<std::string>("perf_options_list");
if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) {
TFLITE_LOG(ERROR) << "Cannot parse --perf_options_list: '"
<< perf_options_list
<< "'. Please double-check its value.";
perf_options_.clear();
return false;
}
const auto valid_options = GetValidPerfOptions();
bool is_valid = true;
for (const auto& option : perf_options_) {
if (std::find(valid_options.begin(), valid_options.end(), option) ==
valid_options.end()) {
is_valid = false;
break;
}
}
if (!is_valid) {
std::string valid_options_str;
for (int i = 0; i < valid_options.size() - 1; ++i) {
valid_options_str += (valid_options[i] + ", ");
}
valid_options_str += valid_options.back();
TFLITE_LOG(ERROR)
<< "There are invalid perf options in --perf_options_list: '"
<< perf_options_list << "'. Valid perf options are: ["
<< valid_options_str << "]";
perf_options_.clear();
return false;
}
if (HasOption("none") && perf_options_.size() > 1) {
TFLITE_LOG(ERROR) << "The 'none' option can not be used together with "
"other perf options in --perf_options_list!";
perf_options_.clear();
return false;
}
return true;
}
std::vector<std::string> BenchmarkPerformanceOptions::GetValidPerfOptions()
const {
std::vector<std::string> valid_options = {"all", "cpu", "gpu", "nnapi",
"none"};
#if defined(TFLITE_ENABLE_HEXAGON)
valid_options.emplace_back("dsp");
#endif
return valid_options;
}
bool BenchmarkPerformanceOptions::HasOption(const std::string& option) const {
return std::find(perf_options_.begin(), perf_options_.end(), option) !=
perf_options_.end();
}
void BenchmarkPerformanceOptions::ResetPerformanceOptions() {
single_option_run_params_->Set<int32_t>("num_threads", 1);
single_option_run_params_->Set<bool>("use_gpu", false);
#if defined(__ANDROID__)
single_option_run_params_->Set<bool>("gpu_precision_loss_allowed", true);
single_option_run_params_->Set<bool>("use_nnapi", false);
single_option_run_params_->Set<std::string>("nnapi_accelerator_name", "");
single_option_run_params_->Set<bool>("disable_nnapi_cpu", false);
single_option_run_params_->Set<int>("max_delegated_partitions", 0);
single_option_run_params_->Set<bool>("nnapi_allow_fp16", false);
#endif
#if defined(TFLITE_ENABLE_HEXAGON)
single_option_run_params_->Set<bool>("use_hexagon", false);
#endif
single_option_run_params_->Set<bool>("use_xnnpack", false);
}
void BenchmarkPerformanceOptions::CreatePerformanceOptions() {
TFLITE_LOG(INFO) << "The list of TFLite runtime options to be benchmarked: ["
<< params_.Get<std::string>("perf_options_list") << "]";
if (HasOption("none")) {
// Just add an empty BenchmarkParams instance.
BenchmarkParams params;
all_run_params_.emplace_back(std::move(params));
// As 'none' is exclusive to others, simply return here.
return;
}
const bool benchmark_all = HasOption("all");
if (benchmark_all || HasOption("cpu")) {
const std::vector<int> num_threads = {1, 2, 4};
for (const int count : num_threads) {
BenchmarkParams params;
params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(count));
all_run_params_.emplace_back(std::move(params));
BenchmarkParams xnnpack_params;
xnnpack_params.AddParam("use_xnnpack",
BenchmarkParam::Create<bool>(true));
xnnpack_params.AddParam("num_threads",
BenchmarkParam::Create<int32_t>(count));
all_run_params_.emplace_back(std::move(xnnpack_params));
}
}
if (benchmark_all || HasOption("gpu")) {
#if defined(__ANDROID__)
const std::vector<bool> allow_precision_loss = {true, false};
for (const auto precision_loss : allow_precision_loss) {
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
params.AddParam("gpu_precision_loss_allowed",
BenchmarkParam::Create<bool>(precision_loss));
all_run_params_.emplace_back(std::move(params));
}
#else
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
#endif
}
#if defined(__ANDROID__)
if (benchmark_all || HasOption("nnapi")) {
std::string nnapi_accelerators = nnapi::GetStringDeviceNamesList();
if (!nnapi_accelerators.empty()) {
std::vector<std::string> device_names;
util::SplitAndParse(nnapi_accelerators, ',', &device_names);
for (const auto name : device_names) {
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
params.AddParam("nnapi_accelerator_name",
BenchmarkParam::Create<std::string>(name));
params.AddParam("disable_nnapi_cpu",
BenchmarkParam::Create<bool>(false));
params.AddParam("max_delegated_partitions",
BenchmarkParam::Create<int>(0));
all_run_params_.emplace_back(std::move(params));
}
}
// Explicitly test the case when there's no "nnapi_accelerator_name"
// parameter as the nnpai execution is different from the case when
// an accelerator name is explicitly specified.
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
}
#endif
#if defined(TFLITE_ENABLE_HEXAGON)
if (benchmark_all || HasOption("dsp")) {
BenchmarkParams params;
params.AddParam("use_hexagon", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
}
#endif
}
void BenchmarkPerformanceOptions::Run() {
CreatePerformanceOptions();
if (params_.Get<bool>("random_shuffle_benchmark_runs")) {
std::random_shuffle(all_run_params_.begin(), all_run_params_.end());
}
// We need to clean *internally* created benchmark listeners, like the
// profiling listener etc. in each Run() invoke because such listeners may be
// reset and become invalid in the next Run(). As a result, we record the
// number of externally-added listeners here to prevent they're cleared later.
const int num_external_listeners = single_option_run_->NumListeners();
// Now perform all runs, each with different performance-affecting parameters.
for (const auto& run_params : all_run_params_) {
// If the run_params is empty, then it means "none" is set for
// --perf_options_list.
if (!run_params.Empty()) {
// Reset all performance-related options before any runs.
ResetPerformanceOptions();
single_option_run_params_->Set(run_params);
}
util::SleepForSeconds(params_.Get<float>("option_benchmark_run_delay"));
// Clear internally created listeners before each run but keep externally
// created ones.
single_option_run_->RemoveListeners(num_external_listeners);
all_run_stats_->MarkBenchmarkStart(*single_option_run_params_);
single_option_run_->Run();
}
all_run_stats_->OutputStats();
}
void BenchmarkPerformanceOptions::Run(int argc, char** argv) {
// We first parse flags for single-option runs to get information like
// parameters of the input model etc.
if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return;
// Now, we parse flags that are specified for this particular binary.
if (!ParseFlags(&argc, argv)) return;
// Now, the remaining are unrecognized flags and we simply print them out.
for (int i = 1; i < argc; ++i) {
TFLITE_LOG(WARN) << "WARNING: unrecognized commandline flag: " << argv[i];
}
Run();
}
} // namespace benchmark
} // namespace tflite
<commit_msg>Adjust the order of parsing commandline options to avoid the confusing message about the --perf_options_list flag.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/tools/benchmark/benchmark_performance_options.h"
#include <algorithm>
#include <iomanip>
#include <memory>
#include <sstream>
#include <utility>
#include "tensorflow/core/util/stats_calculator.h"
#include "tensorflow/lite/c/common.h"
#if defined(__ANDROID__)
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/nnapi/nnapi_util.h"
#endif
#include "tensorflow/lite/profiling/time.h"
#include "tensorflow/lite/tools/benchmark/benchmark_params.h"
#include "tensorflow/lite/tools/benchmark/benchmark_utils.h"
#include "tensorflow/lite/tools/command_line_flags.h"
#include "tensorflow/lite/tools/logging.h"
#if (defined(ANDROID) || defined(__ANDROID__)) && \
(defined(__arm__) || defined(__aarch64__))
#define TFLITE_ENABLE_HEXAGON
#endif
namespace tflite {
namespace benchmark {
std::string MultiRunStatsRecorder::PerfOptionName(
const BenchmarkParams& params) const {
#if defined(__ANDROID__)
if (params.Get<bool>("use_nnapi")) {
const std::string accelerator =
params.Get<std::string>("nnapi_accelerator_name");
return accelerator.empty() ? "nnapi(w/o accel name)"
: "nnapi(" + accelerator + ")";
}
#endif
if (params.Get<bool>("use_gpu")) {
#if defined(__ANDROID__)
if (params.Get<bool>("gpu_precision_loss_allowed")) {
return "gpu-fp16";
} else {
return "gpu-default";
}
#else
return "gpu-default";
#endif
}
#if defined(TFLITE_ENABLE_HEXAGON)
if (params.Get<bool>("use_hexagon")) {
return "dsp w/ hexagon";
}
#endif
// Handle cases run on CPU
// Note: could use std::to_string to convert an integer to string but it
// requires C++11.
std::stringstream sstm;
sstm << "cpu w/ " << params.Get<int32_t>("num_threads") << " threads";
// Handle cases run on CPU w/ the xnnpack delegate
if (params.Get<bool>("use_xnnpack")) {
sstm << " (xnnpack)";
}
return sstm.str();
}
void MultiRunStatsRecorder::OutputStats() {
// Make a 80-character-long header.
TFLITE_LOG(INFO) << "\n==============Summary of All Runs w/ Different "
"Performance Options==============";
std::sort(results_.begin(), results_.end(), EachRunStatsEntryComparator());
for (const auto& run_stats : results_) {
const auto perf_option_name = PerfOptionName(*run_stats.params);
std::stringstream stream;
stream << std::setw(26) << perf_option_name << ": ";
if (!run_stats.completed) {
stream << " failed!";
} else {
run_stats.metrics.inference_time_us().OutputToStream(&stream);
// NOTE: As of 2019/11/07, the memory usage is collected in an
// OS-process-wide way and this program performs multiple runs in a single
// OS process, therefore, the memory usage information of each run becomes
// incorrect, hence no output here.
}
TFLITE_LOG(INFO) << stream.str();
}
}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkModel* single_option_run,
std::unique_ptr<MultiRunStatsRecorder> all_run_stats)
: BenchmarkPerformanceOptions(DefaultParams(), single_option_run,
std::move(all_run_stats)) {}
BenchmarkPerformanceOptions::BenchmarkPerformanceOptions(
BenchmarkParams params, BenchmarkModel* single_option_run,
std::unique_ptr<MultiRunStatsRecorder> all_run_stats)
: params_(std::move(params)),
single_option_run_(single_option_run),
single_option_run_params_(single_option_run->mutable_params()),
all_run_stats_(std::move(all_run_stats)) {
single_option_run_->AddListener(all_run_stats_.get());
}
BenchmarkParams BenchmarkPerformanceOptions::DefaultParams() {
BenchmarkParams params;
params.AddParam("perf_options_list",
BenchmarkParam::Create<std::string>("all"));
params.AddParam("option_benchmark_run_delay",
BenchmarkParam::Create<float>(-1.0f));
params.AddParam("random_shuffle_benchmark_runs",
BenchmarkParam::Create<bool>(true));
return params;
}
std::vector<Flag> BenchmarkPerformanceOptions::GetFlags() {
return {
CreateFlag<std::string>(
"perf_options_list", ¶ms_,
"A comma-separated list of TFLite performance options to benchmark. "
"By default, all performance options are benchmarked. Note if it's "
"set to 'none', then the tool simply benchmark the model against the "
"specified benchmark parameters."),
CreateFlag<float>("option_benchmark_run_delay", ¶ms_,
"The delay between two consecutive runs of "
"benchmarking performance options in seconds."),
CreateFlag<bool>(
"random_shuffle_benchmark_runs", ¶ms_,
"Whether to perform all benchmark runs, each of which has different "
"performance options, in a random order. It is enabled by default."),
};
}
bool BenchmarkPerformanceOptions::ParseFlags(int* argc, char** argv) {
auto flag_list = GetFlags();
const bool parse_result =
Flags::Parse(argc, const_cast<const char**>(argv), flag_list);
if (!parse_result) {
std::string usage = Flags::Usage(argv[0], flag_list);
TFLITE_LOG(ERROR) << usage;
return false;
}
// Parse the value of --perf_options_list to find performance options to be
// benchmarked.
return ParsePerfOptions();
}
bool BenchmarkPerformanceOptions::ParsePerfOptions() {
const auto& perf_options_list = params_.Get<std::string>("perf_options_list");
if (!util::SplitAndParse(perf_options_list, ',', &perf_options_)) {
TFLITE_LOG(ERROR) << "Cannot parse --perf_options_list: '"
<< perf_options_list
<< "'. Please double-check its value.";
perf_options_.clear();
return false;
}
const auto valid_options = GetValidPerfOptions();
bool is_valid = true;
for (const auto& option : perf_options_) {
if (std::find(valid_options.begin(), valid_options.end(), option) ==
valid_options.end()) {
is_valid = false;
break;
}
}
if (!is_valid) {
std::string valid_options_str;
for (int i = 0; i < valid_options.size() - 1; ++i) {
valid_options_str += (valid_options[i] + ", ");
}
valid_options_str += valid_options.back();
TFLITE_LOG(ERROR)
<< "There are invalid perf options in --perf_options_list: '"
<< perf_options_list << "'. Valid perf options are: ["
<< valid_options_str << "]";
perf_options_.clear();
return false;
}
if (HasOption("none") && perf_options_.size() > 1) {
TFLITE_LOG(ERROR) << "The 'none' option can not be used together with "
"other perf options in --perf_options_list!";
perf_options_.clear();
return false;
}
return true;
}
std::vector<std::string> BenchmarkPerformanceOptions::GetValidPerfOptions()
const {
std::vector<std::string> valid_options = {"all", "cpu", "gpu", "nnapi",
"none"};
#if defined(TFLITE_ENABLE_HEXAGON)
valid_options.emplace_back("dsp");
#endif
return valid_options;
}
bool BenchmarkPerformanceOptions::HasOption(const std::string& option) const {
return std::find(perf_options_.begin(), perf_options_.end(), option) !=
perf_options_.end();
}
void BenchmarkPerformanceOptions::ResetPerformanceOptions() {
single_option_run_params_->Set<int32_t>("num_threads", 1);
single_option_run_params_->Set<bool>("use_gpu", false);
#if defined(__ANDROID__)
single_option_run_params_->Set<bool>("gpu_precision_loss_allowed", true);
single_option_run_params_->Set<bool>("use_nnapi", false);
single_option_run_params_->Set<std::string>("nnapi_accelerator_name", "");
single_option_run_params_->Set<bool>("disable_nnapi_cpu", false);
single_option_run_params_->Set<int>("max_delegated_partitions", 0);
single_option_run_params_->Set<bool>("nnapi_allow_fp16", false);
#endif
#if defined(TFLITE_ENABLE_HEXAGON)
single_option_run_params_->Set<bool>("use_hexagon", false);
#endif
single_option_run_params_->Set<bool>("use_xnnpack", false);
}
void BenchmarkPerformanceOptions::CreatePerformanceOptions() {
TFLITE_LOG(INFO) << "The list of TFLite runtime options to be benchmarked: ["
<< params_.Get<std::string>("perf_options_list") << "]";
if (HasOption("none")) {
// Just add an empty BenchmarkParams instance.
BenchmarkParams params;
all_run_params_.emplace_back(std::move(params));
// As 'none' is exclusive to others, simply return here.
return;
}
const bool benchmark_all = HasOption("all");
if (benchmark_all || HasOption("cpu")) {
const std::vector<int> num_threads = {1, 2, 4};
for (const int count : num_threads) {
BenchmarkParams params;
params.AddParam("num_threads", BenchmarkParam::Create<int32_t>(count));
all_run_params_.emplace_back(std::move(params));
BenchmarkParams xnnpack_params;
xnnpack_params.AddParam("use_xnnpack",
BenchmarkParam::Create<bool>(true));
xnnpack_params.AddParam("num_threads",
BenchmarkParam::Create<int32_t>(count));
all_run_params_.emplace_back(std::move(xnnpack_params));
}
}
if (benchmark_all || HasOption("gpu")) {
#if defined(__ANDROID__)
const std::vector<bool> allow_precision_loss = {true, false};
for (const auto precision_loss : allow_precision_loss) {
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
params.AddParam("gpu_precision_loss_allowed",
BenchmarkParam::Create<bool>(precision_loss));
all_run_params_.emplace_back(std::move(params));
}
#else
BenchmarkParams params;
params.AddParam("use_gpu", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
#endif
}
#if defined(__ANDROID__)
if (benchmark_all || HasOption("nnapi")) {
std::string nnapi_accelerators = nnapi::GetStringDeviceNamesList();
if (!nnapi_accelerators.empty()) {
std::vector<std::string> device_names;
util::SplitAndParse(nnapi_accelerators, ',', &device_names);
for (const auto name : device_names) {
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
params.AddParam("nnapi_accelerator_name",
BenchmarkParam::Create<std::string>(name));
params.AddParam("disable_nnapi_cpu",
BenchmarkParam::Create<bool>(false));
params.AddParam("max_delegated_partitions",
BenchmarkParam::Create<int>(0));
all_run_params_.emplace_back(std::move(params));
}
}
// Explicitly test the case when there's no "nnapi_accelerator_name"
// parameter as the nnpai execution is different from the case when
// an accelerator name is explicitly specified.
BenchmarkParams params;
params.AddParam("use_nnapi", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
}
#endif
#if defined(TFLITE_ENABLE_HEXAGON)
if (benchmark_all || HasOption("dsp")) {
BenchmarkParams params;
params.AddParam("use_hexagon", BenchmarkParam::Create<bool>(true));
all_run_params_.emplace_back(std::move(params));
}
#endif
}
void BenchmarkPerformanceOptions::Run() {
CreatePerformanceOptions();
if (params_.Get<bool>("random_shuffle_benchmark_runs")) {
std::random_shuffle(all_run_params_.begin(), all_run_params_.end());
}
// We need to clean *internally* created benchmark listeners, like the
// profiling listener etc. in each Run() invoke because such listeners may be
// reset and become invalid in the next Run(). As a result, we record the
// number of externally-added listeners here to prevent they're cleared later.
const int num_external_listeners = single_option_run_->NumListeners();
// Now perform all runs, each with different performance-affecting parameters.
for (const auto& run_params : all_run_params_) {
// If the run_params is empty, then it means "none" is set for
// --perf_options_list.
if (!run_params.Empty()) {
// Reset all performance-related options before any runs.
ResetPerformanceOptions();
single_option_run_params_->Set(run_params);
}
util::SleepForSeconds(params_.Get<float>("option_benchmark_run_delay"));
// Clear internally created listeners before each run but keep externally
// created ones.
single_option_run_->RemoveListeners(num_external_listeners);
all_run_stats_->MarkBenchmarkStart(*single_option_run_params_);
single_option_run_->Run();
}
all_run_stats_->OutputStats();
}
void BenchmarkPerformanceOptions::Run(int argc, char** argv) {
// Parse flags that are supported by this particular binary first.
if (!ParseFlags(&argc, argv)) return;
// Then parse flags for single-option runs to get information like parameters
// of the input model etc.
if (single_option_run_->ParseFlags(&argc, argv) != kTfLiteOk) return;
// Now, the remaining are unrecognized flags and we simply print them out.
for (int i = 1; i < argc; ++i) {
TFLITE_LOG(WARN) << "WARNING: unrecognized commandline flag: " << argv[i];
}
Run();
}
} // namespace benchmark
} // namespace tflite
<|endoftext|> |
<commit_before>/* Copyright 2021, The TensorFlow Federated Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
==============================================================================*/
// This file contains the pybind11 defintions for exposing the C++ Executor
// interface in Python.
//
// General principles:
// - Python methods defined here (e.g. `.def_*()`) should not contain
// "business logic". That should be implemented on the underlying C++ class.
// The only logic that may exist here is parameter/result conversions (e.g.
// `OwnedValueId` -> `ValueId`, etc).
#include "net/grpc/public/include/grpcpp/grpcpp.h"
#include "pybind11/include/pybind11/detail/common.h"
#include "pybind11/include/pybind11/pybind11.h"
#include "pybind11/include/pybind11/stl.h"
#include "pybind11_abseil/absl_casters.h"
#include "pybind11_abseil/status_casters.h"
#include "pybind11_protobuf/proto_casters.h"
#include "tensorflow_federated/cc/core/impl/executors/composing_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/executor.h"
#include "tensorflow_federated/cc/core/impl/executors/federating_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/reference_resolving_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/remote_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/tensorflow_executor.h"
#include "tensorflow_federated/proto/v0/computation.proto.h"
#include "tensorflow_federated/proto/v0/executor.proto.h"
namespace tensorflow_federated {
namespace py = ::pybind11;
namespace {
////////////////////////////////////////////////////////////////////////////////
// The Python module defintion `executor_bindings`.
//
// This will be used with `import executor_bindings` on the Python side. This
// module should _not_ be directly imported into the public pip API. The methods
// here will raise `NotOkStatus` errors from absl, which are not user friendly.
////////////////////////////////////////////////////////////////////////////////
PYBIND11_MODULE(executor_bindings, m) {
py::google::ImportStatusModule();
py::google::ImportProtoModule();
m.doc() = "Bindings for the C++ ";
// Provide an `OwnedValueId` class to handle return values from the
// `Executor` interface.
//
// Note: no `init<>()` method defined, this object is only constructor from
// Executor instances.
py::class_<OwnedValueId>(m, "OwnedValueId")
.def_property_readonly("ref", &OwnedValueId::ref)
.def("__str__",
[](const OwnedValueId& self) { return absl::StrCat(self.ref()); })
.def("__repr__", [](const OwnedValueId& self) {
return absl::StrCat("<OwnedValueId: ", self.ref(), ">");
});
// We provide ComposingChild as an opaque object so that they can be returned
// from pybind functions.
py::class_<ComposingChild>(m, "ComposingChild")
.def("__repr__", [](const ComposingChild& self) {
return absl::StrCat(
"<ComposingChild with num clients: ", self.NumClients(), ">");
});
// Provide the `Executor` interface.
//
// A `dispose` method is purposely not exposed. Though `Executor::Dispose`
// exists in C++, Python should call `Dispose` via the `OwnedValueId`
// destructor during garbage collection.
//
// Note: no `init<>()` method defined, must be constructed useing the create_*
// methods defined below.
py::class_<Executor,
// PyExecutor trampoline goes here when ready
std::shared_ptr<Executor>>(m, "Executor")
.def("create_value", &Executor::CreateValue, py::arg("value_pb"),
py::return_value_policy::move)
.def("create_struct", &Executor::CreateStruct,
py::return_value_policy::move)
.def("create_selection", &Executor::CreateSelection,
py::return_value_policy::move)
.def("create_call", &Executor::CreateCall, py::arg("function"),
// Allow `argument` to be `None`.
py::arg("argument").none(true), py::return_value_policy::move)
.def(
"materialize",
[](Executor& e,
const ValueId& value_id) -> absl::StatusOr<v0::Value> {
// Construct a new `v0::Value` to write to and return it to Python.
v0::Value value_pb;
auto result = e.Materialize(value_id, &value_pb);
if (!result.ok()) {
return result;
}
return std::move(value_pb);
},
py::return_value_policy::move);
// Executor construction methods.
m.def("create_tensorflow_executor", &CreateTensorFlowExecutor,
"Creates a TensorFlowExecutor");
m.def("create_reference_resolving_executor",
&CreateReferenceResolvingExecutor,
"Creates a ReferenceResolvingExecutor", py::arg("inner_executor"));
m.def("create_federating_executor", &CreateFederatingExecutor,
py::arg("inner_executor"), py::arg("cardinalities"),
"Creates a FederatingExecutor");
m.def("create_composing_child", &ComposingChild::Make, py::arg("executor"),
py::arg("cardinalities"), "Creates a ComposingExecutor.");
m.def("create_composing_executor", &CreateComposingExecutor,
py::arg("server"), py::arg("children"), "Creates a ComposingExecutor.");
m.def("create_remote_executor",
py::overload_cast<std::shared_ptr<grpc::ChannelInterface>,
const CardinalityMap&>(&CreateRemoteExecutor),
py::arg("channel"), py::arg("cardinalities"),
"Creates a RemoteExecutor.");
py::class_<grpc::ChannelInterface, std::shared_ptr<grpc::ChannelInterface>>(
m, "GRPCChannelInterface");
m.def(
"create_insecure_grpc_channel",
[](const std::string& target) -> std::shared_ptr<grpc::ChannelInterface> {
return grpc::CreateChannel(target, grpc::InsecureChannelCredentials());
},
pybind11::return_value_policy::take_ownership);
}
} // namespace
} // namespace tensorflow_federated
<commit_msg>Sets GRPC Channels to allow int32-max-sized messages.<commit_after>/* Copyright 2021, The TensorFlow Federated Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
==============================================================================*/
// This file contains the pybind11 defintions for exposing the C++ Executor
// interface in Python.
//
// General principles:
// - Python methods defined here (e.g. `.def_*()`) should not contain
// "business logic". That should be implemented on the underlying C++ class.
// The only logic that may exist here is parameter/result conversions (e.g.
// `OwnedValueId` -> `ValueId`, etc).
#include "net/grpc/public/include/grpcpp/grpcpp.h"
#include "pybind11/include/pybind11/detail/common.h"
#include "pybind11/include/pybind11/pybind11.h"
#include "pybind11/include/pybind11/stl.h"
#include "pybind11_abseil/absl_casters.h"
#include "pybind11_abseil/status_casters.h"
#include "pybind11_protobuf/proto_casters.h"
#include "tensorflow_federated/cc/core/impl/executors/composing_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/executor.h"
#include "tensorflow_federated/cc/core/impl/executors/federating_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/reference_resolving_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/remote_executor.h"
#include "tensorflow_federated/cc/core/impl/executors/tensorflow_executor.h"
#include "tensorflow_federated/proto/v0/computation.proto.h"
#include "tensorflow_federated/proto/v0/executor.proto.h"
namespace tensorflow_federated {
namespace py = ::pybind11;
namespace {
////////////////////////////////////////////////////////////////////////////////
// The Python module defintion `executor_bindings`.
//
// This will be used with `import executor_bindings` on the Python side. This
// module should _not_ be directly imported into the public pip API. The methods
// here will raise `NotOkStatus` errors from absl, which are not user friendly.
////////////////////////////////////////////////////////////////////////////////
PYBIND11_MODULE(executor_bindings, m) {
py::google::ImportStatusModule();
py::google::ImportProtoModule();
m.doc() = "Bindings for the C++ ";
// Provide an `OwnedValueId` class to handle return values from the
// `Executor` interface.
//
// Note: no `init<>()` method defined, this object is only constructor from
// Executor instances.
py::class_<OwnedValueId>(m, "OwnedValueId")
.def_property_readonly("ref", &OwnedValueId::ref)
.def("__str__",
[](const OwnedValueId& self) { return absl::StrCat(self.ref()); })
.def("__repr__", [](const OwnedValueId& self) {
return absl::StrCat("<OwnedValueId: ", self.ref(), ">");
});
// We provide ComposingChild as an opaque object so that they can be returned
// from pybind functions.
py::class_<ComposingChild>(m, "ComposingChild")
.def("__repr__", [](const ComposingChild& self) {
return absl::StrCat(
"<ComposingChild with num clients: ", self.NumClients(), ">");
});
// Provide the `Executor` interface.
//
// A `dispose` method is purposely not exposed. Though `Executor::Dispose`
// exists in C++, Python should call `Dispose` via the `OwnedValueId`
// destructor during garbage collection.
//
// Note: no `init<>()` method defined, must be constructed useing the create_*
// methods defined below.
py::class_<Executor,
// PyExecutor trampoline goes here when ready
std::shared_ptr<Executor>>(m, "Executor")
.def("create_value", &Executor::CreateValue, py::arg("value_pb"),
py::return_value_policy::move)
.def("create_struct", &Executor::CreateStruct,
py::return_value_policy::move)
.def("create_selection", &Executor::CreateSelection,
py::return_value_policy::move)
.def("create_call", &Executor::CreateCall, py::arg("function"),
// Allow `argument` to be `None`.
py::arg("argument").none(true), py::return_value_policy::move)
.def(
"materialize",
[](Executor& e,
const ValueId& value_id) -> absl::StatusOr<v0::Value> {
// Construct a new `v0::Value` to write to and return it to Python.
v0::Value value_pb;
auto result = e.Materialize(value_id, &value_pb);
if (!result.ok()) {
return result;
}
return std::move(value_pb);
},
py::return_value_policy::move);
// Executor construction methods.
m.def("create_tensorflow_executor", &CreateTensorFlowExecutor,
"Creates a TensorFlowExecutor");
m.def("create_reference_resolving_executor",
&CreateReferenceResolvingExecutor,
"Creates a ReferenceResolvingExecutor", py::arg("inner_executor"));
m.def("create_federating_executor", &CreateFederatingExecutor,
py::arg("inner_executor"), py::arg("cardinalities"),
"Creates a FederatingExecutor");
m.def("create_composing_child", &ComposingChild::Make, py::arg("executor"),
py::arg("cardinalities"), "Creates a ComposingExecutor.");
m.def("create_composing_executor", &CreateComposingExecutor,
py::arg("server"), py::arg("children"), "Creates a ComposingExecutor.");
m.def("create_remote_executor",
py::overload_cast<std::shared_ptr<grpc::ChannelInterface>,
const CardinalityMap&>(&CreateRemoteExecutor),
py::arg("channel"), py::arg("cardinalities"),
"Creates a RemoteExecutor.");
py::class_<grpc::ChannelInterface, std::shared_ptr<grpc::ChannelInterface>>(
m, "GRPCChannelInterface");
m.def(
"create_insecure_grpc_channel",
[](const std::string& target) -> std::shared_ptr<grpc::ChannelInterface> {
auto channel_options = grpc::ChannelArguments();
channel_options.SetMaxSendMessageSize(
std::numeric_limits<int32>::max());
channel_options.SetMaxReceiveMessageSize(
std::numeric_limits<int32>::max());
return grpc::CreateCustomChannel(
target, grpc::InsecureChannelCredentials(), channel_options);
},
pybind11::return_value_policy::take_ownership);
}
} // namespace
} // namespace tensorflow_federated
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_PIDLoop_inl_
#define _Stroika_Foundation_Execution_PIDLoop_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Characters/StringBuilder.h"
#include "../Characters/ToString.h"
#include "Sleep.h"
// Comment this in to turn on aggressive noisy DbgTrace in this module (note the extra long name since its in a header)
//#define Stroika_Foundation_Execution_PIDLoop_USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace Stroika {
namespace Foundation {
namespace Execution {
/*
********************************************************************************
********************* PIDLoop<CONTROL_VAR_TYPE>::ControlParams *****************
********************************************************************************
*/
template <typename CONTROL_VAR_TYPE>
inline PIDLoop<CONTROL_VAR_TYPE>::ControlParams::ControlParams (ValueType p, ValueType i, ValueType d)
: P (p)
, I (i)
, D (d)
{
}
template <typename CONTROL_VAR_TYPE>
inline bool PIDLoop<CONTROL_VAR_TYPE>::ControlParams::operator== (const ControlParams& rhs) const
{
return P == rhs.P and I == rhs.I and D == rhs.D;
}
template <typename CONTROL_VAR_TYPE>
inline bool PIDLoop<CONTROL_VAR_TYPE>::ControlParams::operator!= (const ControlParams& rhs) const
{
return not operator== (rhs);
}
template <typename CONTROL_VAR_TYPE>
inline Characters::String PIDLoop<CONTROL_VAR_TYPE>::ControlParams::ToString () const
{
Characters::StringBuilder out;
out += L"{";
out += L"P: " + Characters::ToString (P) + L"',";
out += L"I: " + Characters::ToString (I) + L"',";
out += L"D: " + Characters::ToString (D) + L"',";
out += L"}";
return out.str ();
}
/*
********************************************************************************
************************** PIDLoop<CONTROL_VAR_TYPE> ***************************
********************************************************************************
*/
template <typename CONTROL_VAR_TYPE>
PIDLoop<CONTROL_VAR_TYPE>::PIDLoop (const ControlParams& pidParams, Time::DurationSecondsType updatePeriod, const function<ValueType ()>& measureFunction, const function<void(ValueType o)>& outputFunction, ValueType initialSetPoint)
: fPIDParams_ (pidParams)
, fUpdatePeriod_ (updatePeriod)
, fMeasureFunction_ (measureFunction)
, fOutputFunction_ (outputFunction)
{
Require (updatePeriod > 0);
fUpdatableParams_.rwget ()->fSetPoint_ = (initialSetPoint);
}
template <typename CONTROL_VAR_TYPE>
PIDLoop<CONTROL_VAR_TYPE>::PIDLoop (AutoStartFlag, const ControlParams& pidParams, Time::DurationSecondsType updatePeriod, const function<ValueType ()>& measureFunction, const function<void(ValueType o)>& outputFunction, ValueType initialSetPoint)
: PIDLoop (pidParams, updatePeriod, measureFunction, outputFunction, initialSetPoint)
{
(void)RunInThread ();
}
template <typename CONTROL_VAR_TYPE>
PIDLoop<CONTROL_VAR_TYPE>::~PIDLoop ()
{
if (fThread_) {
fThread_->AbortAndWaitForDone ();
}
}
template <typename CONTROL_VAR_TYPE>
inline auto PIDLoop<CONTROL_VAR_TYPE>::GetSetPoint () const -> ValueType
{
return fUpdatableParams_->fSetPoint_;
}
template <typename CONTROL_VAR_TYPE>
inline void PIDLoop<CONTROL_VAR_TYPE>::SetSetPoint (ValueType sp)
{
if (sp != fUpdatableParams_->fSetPoint_) {
// we cannot predict how fPrevError_/fIntegral_ should change with a new setpoint, so clear them
fUpdatableParams_ = {sp, ValueType{}, ValueType{}};
}
}
template <typename CONTROL_VAR_TYPE>
inline auto PIDLoop<CONTROL_VAR_TYPE>::GetControlParams () const -> ControlParams
{
return fPIDParams_;
}
template <typename CONTROL_VAR_TYPE>
inline auto PIDLoop<CONTROL_VAR_TYPE>::GetUpdatePeriod () const -> Time::DurationSecondsType
{
return fUpdatePeriod_;
}
template <typename CONTROL_VAR_TYPE>
void PIDLoop<CONTROL_VAR_TYPE>::RunDirectly ()
{
Time::DurationSecondsType nextRunAt = Time::GetTickCount ();
while (true) {
SleepUntil (nextRunAt);
ValueType measuredValue = fMeasureFunction_ ();
ValueType setPoint = fUpdatableParams_->fSetPoint_;
ValueType error = setPoint - measuredValue;
ValueType derivative = (error - fUpdatableParams_->fPrevError_) / fUpdatePeriod_;
{
auto updateUpdatableParams = fUpdatableParams_.rwget ();
updateUpdatableParams->fIntegral_ += error * fUpdatePeriod_;
updateUpdatableParams->fPrevError_ = error;
}
ValueType outputFunctionArgument = fPIDParams_.P * error + fPIDParams_.I * fUpdatableParams_->fIntegral_ + fPIDParams_.D * derivative;
fOutputFunction_ (outputFunctionArgument);
nextRunAt += fUpdatePeriod_;
#if Stroika_Foundation_Execution_PIDLoop_USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"Completed PIDLoop update: set-point=%s, measuredValue=%s, error=%s, derivative=%s, integral=%s, outputFunctionArgument=%s, nextRunAt=%f", Characters::ToString (setPoint).c_str (), Characters::ToString (measuredValue).c_str (), Characters::ToString (error).c_str (), Characters::ToString (derivative).c_str (), Characters::ToString (updateUpdatableParams->fIntegral_).c_str (), Characters::ToString (outputFunctionArgument).c_str (), nextRunAt);
#endif
}
}
template <typename CONTROL_VAR_TYPE>
Thread::Ptr PIDLoop<CONTROL_VAR_TYPE>::RunInThread ()
{
Require (fThread_.IsMissing ());
fThread_ = Thread::New ([this]() { RunDirectly (); }, Thread::eAutoStart);
return *fThread_;
}
}
}
}
#endif /*_Stroika_Foundation_Execution_PIDLoop_inl_*/
<commit_msg>More tweaks to PIDLoop () - code - exception handling and more trace msg<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved
*/
#ifndef _Stroika_Foundation_Execution_PIDLoop_inl_
#define _Stroika_Foundation_Execution_PIDLoop_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Characters/StringBuilder.h"
#include "../Characters/ToString.h"
#include "Sleep.h"
// Comment this in to turn on aggressive noisy DbgTrace in this module (note the extra long name since its in a header)
//#define Stroika_Foundation_Execution_PIDLoop_USE_NOISY_TRACE_IN_THIS_MODULE_ 1
namespace Stroika {
namespace Foundation {
namespace Execution {
/*
********************************************************************************
********************* PIDLoop<CONTROL_VAR_TYPE>::ControlParams *****************
********************************************************************************
*/
template <typename CONTROL_VAR_TYPE>
inline PIDLoop<CONTROL_VAR_TYPE>::ControlParams::ControlParams (ValueType p, ValueType i, ValueType d)
: P (p)
, I (i)
, D (d)
{
}
template <typename CONTROL_VAR_TYPE>
inline bool PIDLoop<CONTROL_VAR_TYPE>::ControlParams::operator== (const ControlParams& rhs) const
{
return P == rhs.P and I == rhs.I and D == rhs.D;
}
template <typename CONTROL_VAR_TYPE>
inline bool PIDLoop<CONTROL_VAR_TYPE>::ControlParams::operator!= (const ControlParams& rhs) const
{
return not operator== (rhs);
}
template <typename CONTROL_VAR_TYPE>
inline Characters::String PIDLoop<CONTROL_VAR_TYPE>::ControlParams::ToString () const
{
Characters::StringBuilder out;
out += L"{";
out += L"P: " + Characters::ToString (P) + L"',";
out += L"I: " + Characters::ToString (I) + L"',";
out += L"D: " + Characters::ToString (D) + L"',";
out += L"}";
return out.str ();
}
/*
********************************************************************************
************************** PIDLoop<CONTROL_VAR_TYPE> ***************************
********************************************************************************
*/
template <typename CONTROL_VAR_TYPE>
PIDLoop<CONTROL_VAR_TYPE>::PIDLoop (const ControlParams& pidParams, Time::DurationSecondsType updatePeriod, const function<ValueType ()>& measureFunction, const function<void(ValueType o)>& outputFunction, ValueType initialSetPoint)
: fPIDParams_ (pidParams)
, fUpdatePeriod_ (updatePeriod)
, fMeasureFunction_ (measureFunction)
, fOutputFunction_ (outputFunction)
{
Require (updatePeriod > 0);
fUpdatableParams_.rwget ()->fSetPoint_ = (initialSetPoint);
}
template <typename CONTROL_VAR_TYPE>
PIDLoop<CONTROL_VAR_TYPE>::PIDLoop (AutoStartFlag, const ControlParams& pidParams, Time::DurationSecondsType updatePeriod, const function<ValueType ()>& measureFunction, const function<void(ValueType o)>& outputFunction, ValueType initialSetPoint)
: PIDLoop (pidParams, updatePeriod, measureFunction, outputFunction, initialSetPoint)
{
(void)RunInThread ();
}
template <typename CONTROL_VAR_TYPE>
PIDLoop<CONTROL_VAR_TYPE>::~PIDLoop ()
{
if (fThread_) {
fThread_->AbortAndWaitForDone ();
}
}
template <typename CONTROL_VAR_TYPE>
inline auto PIDLoop<CONTROL_VAR_TYPE>::GetSetPoint () const -> ValueType
{
return fUpdatableParams_->fSetPoint_;
}
template <typename CONTROL_VAR_TYPE>
inline void PIDLoop<CONTROL_VAR_TYPE>::SetSetPoint (ValueType sp)
{
if (sp != fUpdatableParams_->fSetPoint_) {
// we cannot predict how fPrevError_/fIntegral_ should change with a new setpoint, so clear them
fUpdatableParams_ = {sp, ValueType{}, ValueType{}};
}
}
template <typename CONTROL_VAR_TYPE>
inline auto PIDLoop<CONTROL_VAR_TYPE>::GetControlParams () const -> ControlParams
{
return fPIDParams_;
}
template <typename CONTROL_VAR_TYPE>
inline auto PIDLoop<CONTROL_VAR_TYPE>::GetUpdatePeriod () const -> Time::DurationSecondsType
{
return fUpdatePeriod_;
}
template <typename CONTROL_VAR_TYPE>
void PIDLoop<CONTROL_VAR_TYPE>::RunDirectly ()
{
Time::DurationSecondsType nextRunAt = Time::GetTickCount ();
while (true) {
SleepUntil (nextRunAt);
try {
ValueType measuredValue = fMeasureFunction_ ();
ValueType setPoint = fUpdatableParams_->fSetPoint_;
ValueType error = setPoint - measuredValue;
ValueType derivative = (error - fUpdatableParams_->fPrevError_) / fUpdatePeriod_;
{
auto updateUpdatableParams = fUpdatableParams_.rwget ();
updateUpdatableParams->fIntegral_ += error * fUpdatePeriod_;
updateUpdatableParams->fPrevError_ = error;
}
ValueType outputFunctionArgument = fPIDParams_.P * error + fPIDParams_.I * fUpdatableParams_->fIntegral_ + fPIDParams_.D * derivative;
fOutputFunction_ (outputFunctionArgument);
nextRunAt += fUpdatePeriod_;
#if Stroika_Foundation_Execution_PIDLoop_USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"Completed PIDLoop update: set-point=%s, measuredValue=%s, error=%s, derivative=%s, integral=%s, outputFunctionArgument=%s, nextRunAt=%f", Characters::ToString (setPoint).c_str (), Characters::ToString (measuredValue).c_str (), Characters::ToString (error).c_str (), Characters::ToString (derivative).c_str (), Characters::ToString (fUpdatableParams_->fIntegral_).c_str (), Characters::ToString (outputFunctionArgument).c_str (), nextRunAt);
#endif
}
catch (const Thread::InterruptException&) {
Execution::ReThrow ();
}
catch (...) {
DbgTrace (L"Suppressing exception in PIDLoop: %s", Characters::ToString (current_exception ()).c_str ());
}
}
}
template <typename CONTROL_VAR_TYPE>
Thread::Ptr PIDLoop<CONTROL_VAR_TYPE>::RunInThread ()
{
Require (fThread_.IsMissing ());
fThread_ = Thread::New ([this]() { RunDirectly (); }, Thread::eAutoStart);
return *fThread_;
}
}
}
}
#endif /*_Stroika_Foundation_Execution_PIDLoop_inl_*/
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbObjectList.h"
#include "otbBandMathXImageFilter.h"
#include "otbMultiChannelExtractROI.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
class BandMathX : public Application
{
public:
/** Standard class typedefs. */
typedef BandMathX Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BandMathX, otb::Application);
typedef otb::MultiChannelExtractROI
<FloatVectorImageType::InternalPixelType,
FloatVectorImageType::InternalPixelType> MultiChannelExtractorType;
typedef otb::BandMathXImageFilter<FloatVectorImageType> BandMathImageFilterType;
private:
void DoInit() ITK_OVERRIDE
{
SetName("BandMathX");
SetDescription("This application performs mathematical operations on multiband images.\n"
"Mathematical formula interpretation is done via muParserX library : http://articles.beltoforion.de/article.php?a=muparserx");
SetDocName("Band Math X");
SetDocLongDescription("The goal of this documentation is to give the user some hints about the syntax used in this application.\n"
"The syntax is mainly constrained by the muparserx library, which can be considered as the core of the application.\n"
"\n\n"
"- Fundamentals:\n\n"
"The default prefix name for variables related to the ith input is 'im(i+1)'(note the indexing from 1 to N, for N inputs). \n"
"The following list summaries the available variables for input #0 (and so on for every input): \n"
"\n"
"im1 --> a pixel from first input, made of n components (n bands)\n"
"im1bj --> jth component of a pixel from first input (first band is indexed by 1)\n"
"im1bjNkxp --> a neighbourhood ('N') of pixels of the jth component from first input, of size kxp\n"
"im1PhyX and im1PhyY --> spacing of first input in X and Y directions (horizontal and vertical)\n"
"im1bjMean im1bjMin im1bjMax im1bjSum im1bjVar --> mean, min, max, sum, variance of jth band from first input (global statistics)\n"
"\nMoreover, we also have the following generic variables:\n"
"idxX and idxY --> indices of the current pixel\n"
"\n"
"Always keep in mind that this application only addresses mathematically well-defined formulas.\n"
"For instance, it is not possible to add vectors of different dimensions (this implies the addition of a row vector with a column vector),\n"
"or add a scalar to a vector or a matrix, or divide two vectors, and so on...\n"
"Thus, it is important to remember that a pixel of n components is always represented as a row vector.\n"
"\n"
"Example :\n\n"
" im1 + im2 (1)\n"
"\nrepresents the addition of pixels from first and second inputs. This expression is consistent only if\n"
"both inputs have the same number of bands.\n"
"Note that it is also possible to use the following expressions to obtain the same result:\n"
"\n"
" im1b1 + im2b1 \n"
" im1b2 + im2b2 (2)\n"
" ..."
"\n\nNevertheless, the first expression is by far much pleaseant. We call this new functionality the 'batch mode'\n"
"(performing the same operation in a band-to-band fashion).\n"
"\n\n"
"- Operations involving neighborhoods of pixels:\n\n"
"Another new fonctionnality is the possibility to perform operations that involve neighborhoods of pixels.\n"
"Variable related to such neighborhoods are always defined following the pattern imIbJNKxP, where: \n"
"- I is an number identifying the image input (remember, input #0 = im1, and so on)\n"
"- J is an number identifying the band (remember, first band is indexed by 1)\n"
"- KxP are two numbers that represent the size of the neighborhood (first one is related to the horizontal direction)\n"
"All neighborhood are centered, thus K and P must be odd numbers.\n"
"Many operators come with this new functionality: dotpr, mean var median min max...\n"
"For instance, if im1 represents the pixel of 3 bands image:\n\n"
" im1 - mean(im1b1N5x5,im1b2N5x5,im1b3N5x5) (3)\n"
"\ncould represent a high pass filter (Note that by implying three neighborhoods, the operator mean returns a row vector of three components.\n"
"It is a typical behaviour for many operators of this application).\n"
"\n\n"
"- Operators:\n\n"
"In addition to the previous operators, other operators are available:\n"
"- existing operators/functions from muParserX, that were not originally defined for vectors and\n"
"matrices (for instance cos, sin, ...). These new operators/ functions keep the original names to which we added the prefix 'v' for vector (vcos, vsin, ...).\n"
"- mult, div and pow operators, that perform element-wise multiplication, division or exponentiation of vector/matrices (for instance im1 div im2)\n"
"- mlt, dv and pw operators, that perform multiplication, division or exponentiation of vector/matrices by a scalar (for instance im1 dv 2.0)\n"
"- bands, which is a very useful operator. It allows selecting specific bands from an image, and/or to rearrange them in a new vector;\n"
"for instance bands(im1,{1,2,1,1}) produces a vector of 4 components made of band 1, band 2, band 1 and band 1 values from the first input.\n"
"Note that curly brackets must be used in order to select the desired band indices.\n"
"... and so on.\n"
"\n\n"
"- Application itself:\n\n"
"The application takes the following parameters :\n"
"- Setting the list of inputs can be done with the 'il' parameter.\n"
"- Setting expressions can be done with the 'exp' parameter (see also limitations section below).\n"
"- Setting constants can be done with the 'incontext' parameter. User must provide a txt file with a specific syntax: #type name value\n"
"An example of such a file is given below:\n\n"
"#F expo 1.1\n"
"#M kernel1 { 0.1 , 0.2 , 0.3; 0.4 , 0.5 , 0.6; 0.7 , 0.8 , 0.9; 1 , 1.1 , 1.2; 1.3 , 1.4 , 1.5 }\n"
"\nAs we can see, #I/#F allows the definition of an integer/float constant, whereas #M allows the definition of a vector/matrix.\n"
"In the latter case, elements of a row must be separated by commas, and rows must be separated by semicolons.\n"
"It is also possible to define expressions within the same txt file, with the pattern #E expr. For instance (two expressions; see also limitations section below):\n\n"
"#E $dotpr(kernel1,im1b1N3x5); im2b1^expo$\n"
"\n- The 'outcontext' parameter allows saving user's constants and expressions (context).\n"
"- Setting the output image can be done with the 'out' parameter (multi-outputs is not implemented yet).\n"
"\n\n"
"Finally, we strongly recommend that the reader takes a look at the cookbook, where additional information can be found (http://www.orfeo-toolbox.org/packages/OTBCookBook.pdf).\n"
);
SetDocLimitations("The application is currently unable to produce one output image per expression, contrary to otbBandMathXImageFilter.\n"
"Separating expressions by semi-colons (; ) will concatenate their results into a unique multiband output image. ");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag("Miscellaneous");
AddParameter(ParameterType_InputImageList, "il", "Input image list");
SetParameterDescription("il", "Image list to perform computation on.");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out","Output image.");
AddRAMParameter();
AddParameter(ParameterType_String, "exp", "Expressions");
SetParameterDescription("exp",
"Mathematical expression to apply.");
AddParameter(ParameterType_InputFilename, "incontext", "Import context");
SetParameterDescription("incontext",
"A txt file containing user's constants and expressions.");
MandatoryOff("incontext");
AddParameter(ParameterType_OutputFilename, "outcontext", "Export context");
SetParameterDescription("outcontext",
"A txt file where to save user's constants and expressions.");
MandatoryOff("outcontext");
// Doc example parameter settings
SetDocExampleParameterValue("il", "verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif");
SetDocExampleParameterValue("out", "apTvUtBandMathOutput.tif");
SetDocExampleParameterValue("exp", "\"cos(im1b1)+im2b1*im3b1-im3b2+ndvi(im3b3, im3b4)\"");
SetOfficialDocLink();
}
void DoUpdateParameters() ITK_OVERRIDE
{
// check if input context should be used
bool useContext = this->ContextCheck();
// Check if the expression is correctly set
if (HasValue("il") && HasValue("exp"))
{
this->LiveCheck(useContext);
}
}
bool ContextCheck(void)
{
bool useContext = false;
if (IsParameterEnabled("incontext") && HasValue("incontext"))
{
std::string contextPath = GetParameterString("incontext");
// check that file exists
if (itksys::SystemTools::FileExists(contextPath.c_str(),true))
{
BandMathImageFilterType::Pointer dummyFilter =
BandMathImageFilterType::New();
dummyFilter->SetManyExpressions(false);
try
{
dummyFilter->ImportContext(contextPath);
useContext = true;
}
catch(itk::ExceptionObject& err)
{
//trick to prevent unreferenced local variable warning on MSVC
(void)err;
// silent catch
useContext = false;
}
if (useContext)
{
// only set the first expression, 'ManyExpression' is disabled.
this->SetParameterString("exp",dummyFilter->GetExpression(0), false);
}
}
}
return useContext;
}
void LiveCheck(bool useContext=false)
{
BandMathImageFilterType::Pointer dummyFilter =
BandMathImageFilterType::New();
dummyFilter->SetManyExpressions(false);
std::vector<MultiChannelExtractorType::Pointer> extractors;
FloatVectorImageListType::Pointer inList = GetParameterImageList("il");
for (unsigned int i = 0; i < inList->Size(); i++)
{
FloatVectorImageType::Pointer inImg = inList->GetNthElement(i);
FloatVectorImageType::RegionType largestRegion = inImg->GetLargestPossibleRegion();
unsigned int nbChannels = inImg->GetNumberOfComponentsPerPixel();
MultiChannelExtractorType::Pointer extract = MultiChannelExtractorType::New();
extractors.push_back(extract);
extract->SetInput(inImg);
extract->SetStartX(largestRegion.GetIndex(0));
extract->SetStartY(largestRegion.GetIndex(1));
// Set extract size to 1 in case of global stats computation
extract->SetSizeX(1);
extract->SetSizeY(1);
for (unsigned int j=0 ; j<nbChannels ; ++j)
{
extract->SetChannel(j+1);
}
dummyFilter->SetNthInput(i,extract->GetOutput());
}
if (useContext)
{
dummyFilter->ImportContext(GetParameterString("incontext"));
}
else
{
dummyFilter->SetExpression(GetParameterString("exp"));
}
try
{
dummyFilter->UpdateOutputInformation();
SetParameterDescription("exp", "Valid expression");
}
catch(itk::ExceptionObject& err)
{
// Change the parameter description to be able to have the
// parser errors in the tooltip
SetParameterDescription("exp", err.GetDescription());
}
}
void DoExecute() ITK_OVERRIDE
{
// Get the input image list
FloatVectorImageListType::Pointer inList = GetParameterImageList("il");
// checking the input images list validity
const unsigned int nbImages = inList->Size();
if (nbImages == 0)
{
itkExceptionMacro("No input Image set...; please set at least one input image");
}
if ( (!IsParameterEnabled("exp")) && (!IsParameterEnabled("incontext")) )
{
itkExceptionMacro("No expression set...; please set and enable at least one one expression");
}
m_Filter = BandMathImageFilterType::New();
m_Filter->SetManyExpressions(false);
for (unsigned int i = 0; i < nbImages; i++)
{
FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i);
currentImage->UpdateOutputInformation();
otbAppLogINFO( << "Image #" << i + 1 << " has "
<< currentImage->GetNumberOfComponentsPerPixel()
<< " components");
m_Filter->SetNthInput(i,currentImage);
}
bool useContext = this->ContextCheck();
std::string expStr = GetParameterString("exp");
if (useContext)
{
otbAppLogINFO("Using input context : " << expStr );
m_Filter->ImportContext(GetParameterString("incontext"));
}
else
{
otbAppLogINFO("Using expression : " << expStr );
m_Filter->SetExpression(expStr);
}
if ( IsParameterEnabled("outcontext") && HasValue("outcontext") )
m_Filter->ExportContext(GetParameterString("outcontext"));
// Set the output image
SetParameterOutputImage("out", m_Filter->GetOutput());
}
BandMathImageFilterType::Pointer m_Filter;
};
} // namespace Wrapper
} // namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::BandMathX)
<commit_msg>DOC: Updated BandMathX documentation.<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbObjectList.h"
#include "otbBandMathXImageFilter.h"
#include "otbMultiChannelExtractROI.h"
#include "itksys/SystemTools.hxx"
namespace otb
{
namespace Wrapper
{
class BandMathX : public Application
{
public:
/** Standard class typedefs. */
typedef BandMathX Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BandMathX, otb::Application);
typedef otb::MultiChannelExtractROI
<FloatVectorImageType::InternalPixelType,
FloatVectorImageType::InternalPixelType> MultiChannelExtractorType;
typedef otb::BandMathXImageFilter<FloatVectorImageType> BandMathImageFilterType;
private:
void DoInit() ITK_OVERRIDE
{
SetName( "BandMathX" );
SetDescription(
"This application performs mathematical operations on several multiband images.\n"
);
SetDocName( "Band Math X" );
SetDocLongDescription(
"This application performs a mathematical operation on several multi-band "
"images and outputs the result into an image (multi- or mono-band, as "
"opposed to the BandMath OTB-application). The mathematical formula is "
"done by the muParserX libraries.\n\n"
"The list of features and the syntax of muParserX is available at: "
"http://articles.beltoforion.de/article.php?a=muparserx\n\n"
"As opposed to muParser (and thus the BandMath OTB-application), "
"muParserX supports vector expressions which allows to output multi-band "
"images.\n\n"
"Hereafter is a brief reference of the muParserX syntax\n\n"
"Fundamentals\n"
"------------\n\n"
"The i-th input image is identified by the 'im<i+1>' (e.g. 'im1') prefix "
"(please, note the indexing from 1 to N, for N inputs).\n\n"
"The following list summarizes the available variables of input #0:\n\n"
"im1\n"
" a pixel from 1st input, made of n components (n bands).\n\n"
"im1b2\n"
" the 2nd component of a pixel from 1st input (band index is 1-based).\n\n"
"im1b2N3x4\n"
" a 3x4 pixels 'N'eighbourhood of a pixel the 2nd component of a pixel "
"from the 1st input.\n\n"
"im1PhyX\n"
" horizontal (X-axis) spacing of the 1st input.\n\n"
"im1PhyY\n"
" vertical spacing of the 1st input input.\n\n"
"im1b2Mean\n"
" mean of the 2nd component of the 1st input (global statistics)\n\n"
"im1b2Min\n"
" minimum of the 2nd component of the 1st input (global statistics)\n\n"
"im1b2Max\n"
" minimum of the 2nd component of the 1st input (global statistics)\n\n"
"im1b2Sum\n"
" minimum of the 2nd component of the 1st input (global statistics)\n\n"
"im1b2Var\n"
" minimum of the 2nd component of the 1st input (global statistics)\n\n"
"Generic variables:\n"
"idxX, idxY\n"
" indices of the current pixel\n\n"
"Always keep in mind that this application only addresses mathematically "
"well-defined formulas. For instance, it is not possible to add vectors of"
" different dimensions (e.g. addition of a row vector with a column vector"
"), or a scalar to a vector or matrix, or divide two vectors, etc.\n\n"
"Thus, it is important to remember that a pixel of n components is always "
"represented as a row vector.\n\n"
"Example:\n"
" im1 + im2 (1)\n"
" represents the addition of pixels from the 1st and 2nd inputs. This "
"expression is consistent only if both inputs have the same number of "
"bands.\n\n"
"Please, note that it is also possible to use the following expressions"
" to obtain the same result:\n"
" im1b1 + im2b1\n"
" im1b2 + im2b2 (2)\n"
" ...\n\n"
"Nevertheless, the first expression is by far much pleaseant. We call "
"this new functionality the 'batch mode' (performing the same operation "
"in a band-to-band fashion).\n\n"
"Operations involving neighborhoods of pixels\n"
"--------------------------------------------\n\n"
"Another new feature is the possibility to perform operations that "
"involve neighborhoods of pixels. Variables related to such neighborhoods "
"are always defined following the imIbJNKxP pattern, where:\n"
"- I is an number identifying the image input (remember, input #0 = im1, "
"and so on)\n"
"- J is an number identifying the band (remember, first band is indexed by"
"1)\n"
"- KxP are two numbers that represent the size of the neighborhood (first "
"one is related to the horizontal direction)\n\n"
"NB: All neighborhood are centered, thus K and P must be odd numbers.\n\n"
"Many operators come with this new functionality:\n"
"- dotpr\n"
"- mean\n"
"- var\n"
"- median\n"
"- min\n"
"- max\n"
"- etc.\n\n"
"For instance, if im1 represents the pixel of 3 bands image:\n"
" im1 - mean( im1b1N5x5, im1b2N5x5, im1b3N5x5 ) (3)\n\n"
"could represent a high pass filter (note that by implying three "
"neighborhoods, the operator mean returns a row vector of three components"
". It is a typical behaviour for many operators of this application).\n\n"
"In addition to the previous operators, other operators are available:\n"
"- existing operators/functions from muParserX, that were not originally "
"defined for vectors and matrices (e.g. cos, sin). These new "
"operators/functions keep the original names to which we added the prefix "
"'v' for vector (vcos, vsin, etc.)\n"
"- mult, div and pow operators, that perform element-wise multiplication, "
"division or exponentiation of vector/matrices (e.g. im1 div im2).\n"
"- mlt, dv and pw operators, that perform multiplication, division or "
"exponentiation of vector/matrices by a scalar (e.g. im1 dv 2.0).\n"
"- bands, which is a very useful operator. It allows selecting specific "
"bands from an image, and/or to rearrange them in a new vector (e.g."
"bands( im1, { 1, 2, 1, 1 } ) produces a vector of 4 components made of "
"band 1, band 2, band 1 and band 1 values from the first input.\n\n"
"Note that curly brackets must be used in order to select the desired band"
"indices.\n\n"
"The application itself\n"
"----------------------\n\n"
"The application takes the following parameters:\n"
"-il Sets the list of inputs\n"
"-ext Sets the mathematical expression (see also limitations "
"section below).\n"
"-incontext Sets the text filename containing constants values (syntax: "
"'#type name value')\n\n"
"An example of such a file is given below:\n"
" #F expo 1.1\n"
" #M kernel1 { 0.1 , 0.2 , 0.3; 0.4 , 0.5 , 0.6; 0.7 , 0.8 , 0.9; 1 , 1.1"
", 1.2; 1.3 , 1.4 , 1.5 }\n\n"
"As we can see, #I/#F allows the definition of an integer/float constant, "
"whereas #M allows the definition of a vector/matrix. In the latter case, "
"elements of a row must be separated by commas, and rows must be separated"
" by semicolons.\n\n"
"It is also possible to define expressions within the same txt file, with "
"#E <expr> (see limitations, below). For instance:\n"
" #E $dotpr( kernel1, im1b1N3x5 ); im2b1^expo$\n\n"
"-outcontext Output usesr's constants and expressions (context).\n"
"-out Sets output image (multi-outputs is not implemented yet).\n"
"\n"
"Finally, we strongly recommend to read the OTB Cookbook which can be "
"found at: http://www.orfeo-toolbox.org/packages/OTBCookBook.pdf\n"
);
SetDocLimitations(
"The application is currently unable to produce one output image per "
"expression, contrary to otbBandMathXImageFilter.\n\n"
"Separating expressions by semi-colons ';' will concatenate their results "
"into a unique multiband output image."
);
SetDocAuthors( "OTB-Team" );
SetDocSeeAlso( "" );
AddDocTag( "Miscellaneous" );
AddParameter( ParameterType_InputImageList, "il", "Input image-list" );
SetParameterDescription( "il", "Image-list to perform computation on." );
AddParameter( ParameterType_OutputImage, "out", "Output Image" );
SetParameterDescription( "out", "Output image." );
AddRAMParameter();
AddParameter( ParameterType_String, "exp", "Expressions" );
SetParameterDescription(
"exp",
"Mathematical expression to apply."
);
AddParameter( ParameterType_InputFilename, "incontext", "Import context" );
SetParameterDescription(
"incontext",
"A txt file containing user's constants and expressions."
);
MandatoryOff( "incontext" );
AddParameter( ParameterType_OutputFilename, "outcontext", "Export context" );
SetParameterDescription(
"outcontext",
"A txt file where to save user's constants and expressions."
);
MandatoryOff( "outcontext" );
// Doc example parameter settings
SetDocExampleParameterValue(
"il",
"verySmallFSATSW_r.tif verySmallFSATSW_nir.tif verySmallFSATSW.tif"
);
SetDocExampleParameterValue( "out", "apTvUtBandMathOutput.tif");
SetDocExampleParameterValue(
"exp",
"'cos( im1b1 ) + im2b1 * im3b1 - im3b2 + ndvi( im3b3, im3b4 )'"
);
SetOfficialDocLink();
}
void DoUpdateParameters() ITK_OVERRIDE
{
// check if input context should be used
bool useContext = this->ContextCheck();
// Check if the expression is correctly set
if (HasValue("il") && HasValue("exp"))
{
this->LiveCheck(useContext);
}
}
bool ContextCheck(void)
{
bool useContext = false;
if (IsParameterEnabled("incontext") && HasValue("incontext"))
{
std::string contextPath = GetParameterString("incontext");
// check that file exists
if (itksys::SystemTools::FileExists(contextPath.c_str(),true))
{
BandMathImageFilterType::Pointer dummyFilter =
BandMathImageFilterType::New();
dummyFilter->SetManyExpressions(false);
try
{
dummyFilter->ImportContext(contextPath);
useContext = true;
}
catch(itk::ExceptionObject& err)
{
//trick to prevent unreferenced local variable warning on MSVC
(void)err;
// silent catch
useContext = false;
}
if (useContext)
{
// only set the first expression, 'ManyExpression' is disabled.
this->SetParameterString("exp",dummyFilter->GetExpression(0), false);
}
}
}
return useContext;
}
void LiveCheck(bool useContext=false)
{
BandMathImageFilterType::Pointer dummyFilter =
BandMathImageFilterType::New();
dummyFilter->SetManyExpressions(false);
std::vector<MultiChannelExtractorType::Pointer> extractors;
FloatVectorImageListType::Pointer inList = GetParameterImageList("il");
for (unsigned int i = 0; i < inList->Size(); i++)
{
FloatVectorImageType::Pointer inImg = inList->GetNthElement(i);
FloatVectorImageType::RegionType largestRegion = inImg->GetLargestPossibleRegion();
unsigned int nbChannels = inImg->GetNumberOfComponentsPerPixel();
MultiChannelExtractorType::Pointer extract = MultiChannelExtractorType::New();
extractors.push_back(extract);
extract->SetInput(inImg);
extract->SetStartX(largestRegion.GetIndex(0));
extract->SetStartY(largestRegion.GetIndex(1));
// Set extract size to 1 in case of global stats computation
extract->SetSizeX(1);
extract->SetSizeY(1);
for (unsigned int j=0 ; j<nbChannels ; ++j)
{
extract->SetChannel(j+1);
}
dummyFilter->SetNthInput(i,extract->GetOutput());
}
if (useContext)
{
dummyFilter->ImportContext(GetParameterString("incontext"));
}
else
{
dummyFilter->SetExpression(GetParameterString("exp"));
}
try
{
dummyFilter->UpdateOutputInformation();
SetParameterDescription("exp", "Valid expression");
}
catch(itk::ExceptionObject& err)
{
// Change the parameter description to be able to have the
// parser errors in the tooltip
SetParameterDescription("exp", err.GetDescription());
}
}
void DoExecute() ITK_OVERRIDE
{
// Get the input image list
FloatVectorImageListType::Pointer inList = GetParameterImageList("il");
// checking the input images list validity
const unsigned int nbImages = inList->Size();
if (nbImages == 0)
{
itkExceptionMacro("No input Image set...; please set at least one input image");
}
if ( (!IsParameterEnabled("exp")) && (!IsParameterEnabled("incontext")) )
{
itkExceptionMacro("No expression set...; please set and enable at least one one expression");
}
m_Filter = BandMathImageFilterType::New();
m_Filter->SetManyExpressions(false);
for (unsigned int i = 0; i < nbImages; i++)
{
FloatVectorImageType::Pointer currentImage = inList->GetNthElement(i);
currentImage->UpdateOutputInformation();
otbAppLogINFO( << "Image #" << i + 1 << " has "
<< currentImage->GetNumberOfComponentsPerPixel()
<< " components");
m_Filter->SetNthInput(i,currentImage);
}
bool useContext = this->ContextCheck();
std::string expStr = GetParameterString("exp");
if (useContext)
{
otbAppLogINFO("Using input context : " << expStr );
m_Filter->ImportContext(GetParameterString("incontext"));
}
else
{
otbAppLogINFO("Using expression : " << expStr );
m_Filter->SetExpression(expStr);
}
if ( IsParameterEnabled("outcontext") && HasValue("outcontext") )
m_Filter->ExportContext(GetParameterString("outcontext"));
// Set the output image
SetParameterOutputImage("out", m_Filter->GetOutput());
}
BandMathImageFilterType::Pointer m_Filter;
};
} // namespace Wrapper
} // namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::BandMathX)
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "shared_macros.h"
#include "xsapi/services.h"
#include "user_context.h"
#include "xbox_system_factory.h"
#include "xbox_live_context_impl.h"
#if !TV_API && !UNIT_TEST_SERVICES && !XSAPI_U
#include "Misc/notification_service.h"
#endif
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN
#if XSAPI_XDK_AUTH
xbox_live_context::xbox_live_context(
_In_ Windows::Xbox::System::User^ user
)
{
m_xboxLiveContextImpl = xsapi_allocate_shared<xbox_live_context_impl>(user);
m_xboxLiveContextImpl->user_context()->set_caller_api_type(xbox::services::caller_api_type::api_cpp);
m_xboxLiveContextImpl->init();
}
Windows::Xbox::System::User^
xbox_live_context::user()
{
return m_xboxLiveContextImpl->user();
}
#endif
#if XSAPI_NONXDK_CPP_AUTH && !UNIT_TEST_SERVICES
xbox_live_context::xbox_live_context(
_In_ std::shared_ptr<system::xbox_live_user> user
)
{
user->_User_impl()->set_user_pointer(user);
m_xboxLiveContextImpl = xsapi_allocate_shared<xbox_live_context_impl>(user);
m_xboxLiveContextImpl->user_context()->set_caller_api_type(xbox::services::caller_api_type::api_cpp);
this->init();
}
std::shared_ptr<system::xbox_live_user>
xbox_live_context::user()
{
return m_xboxLiveContextImpl->user();
}
#endif
#if XSAPI_NONXDK_WINRT_AUTH
xbox_live_context::xbox_live_context(
_In_ Microsoft::Xbox::Services::System::XboxLiveUser^ user
)
{
m_xboxLiveContextImpl = xsapi_allocate_shared<xbox_live_context_impl>(user);
m_xboxLiveContextImpl->user_context()->set_caller_api_type(xbox::services::caller_api_type::api_cpp);
this->init();
}
Microsoft::Xbox::Services::System::XboxLiveUser^
xbox_live_context::user()
{
return m_xboxLiveContextImpl->user();
}
#endif
void xbox_live_context::init()
{
m_xboxLiveContextImpl->init();
m_achievementService = achievements::achievement_service(m_xboxLiveContextImpl->achievement_service_internal());
m_profileService = social::profile_service(m_xboxLiveContextImpl->profile_service_impl());
m_socialService = social::social_service(settings(), m_xboxLiveContextImpl->social_service_impl());
m_reputationService = social::reputation_service(m_xboxLiveContextImpl->reputation_service_impl());
m_presenceService = presence::presence_service(m_xboxLiveContextImpl->presence_service());
}
string_t xbox_live_context::xbox_live_user_id()
{
return utils::string_t_from_internal_string(m_xboxLiveContextImpl->xbox_live_user_id());
}
social::profile_service&
xbox_live_context::profile_service()
{
return m_profileService;
}
social::social_service&
xbox_live_context::social_service()
{
return m_socialService;
}
social::reputation_service&
xbox_live_context::reputation_service()
{
return m_reputationService;
}
leaderboard::leaderboard_service&
xbox_live_context::leaderboard_service()
{
return m_xboxLiveContextImpl->leaderboard_service();
}
achievements::achievement_service&
xbox_live_context::achievement_service()
{
return m_achievementService;
}
multiplayer::multiplayer_service&
xbox_live_context::multiplayer_service()
{
return m_xboxLiveContextImpl->multiplayer_service();
}
matchmaking::matchmaking_service&
xbox_live_context::matchmaking_service()
{
return m_xboxLiveContextImpl->matchmaking_service();
}
tournaments::tournament_service&
xbox_live_context::tournament_service()
{
return m_xboxLiveContextImpl->tournament_service();
}
user_statistics::user_statistics_service&
xbox_live_context::user_statistics_service()
{
return m_xboxLiveContextImpl->user_statistics_service();
}
const std::shared_ptr<real_time_activity::real_time_activity_service>&
xbox_live_context::real_time_activity_service()
{
return m_xboxLiveContextImpl->real_time_activity_service();
}
presence::presence_service&
xbox_live_context::presence_service()
{
return m_presenceService;
}
game_server_platform::game_server_platform_service&
xbox_live_context::game_server_platform_service()
{
return m_xboxLiveContextImpl->game_server_platform_service();
}
title_storage::title_storage_service&
xbox_live_context::title_storage_service()
{
return m_xboxLiveContextImpl->title_storage_service();
}
privacy::privacy_service&
xbox_live_context::privacy_service()
{
return m_xboxLiveContextImpl->privacy_service();
}
system::string_service&
xbox_live_context::string_service()
{
return m_xboxLiveContextImpl->string_service();
}
contextual_search::contextual_search_service&
xbox_live_context::contextual_search_service()
{
return m_xboxLiveContextImpl->contextual_search_service();
}
clubs::clubs_service&
xbox_live_context::clubs_service()
{
return m_xboxLiveContextImpl->clubs_service();
}
#if UWP_API || XSAPI_U
events::events_service&
xbox_live_context::events_service()
{
return m_xboxLiveContextImpl->events_service();
}
#endif
#if TV_API || UNIT_TEST_SERVICES
marketplace::catalog_service&
xbox_live_context::catalog_service()
{
return m_xboxLiveContextImpl->catalog_service();
}
marketplace::inventory_service&
xbox_live_context::inventory_service()
{
return m_xboxLiveContextImpl->inventory_service();
}
entertainment_profile::entertainment_profile_list_service&
xbox_live_context::entertainment_profile_list_service()
{
return m_xboxLiveContextImpl->entertainment_profile_list_service();
}
#endif
std::shared_ptr<xbox_live_context_settings>
xbox_live_context::settings()
{
return m_xboxLiveContextImpl->settings();
}
std::shared_ptr<xbox_live_app_config>
xbox_live_context::application_config()
{
return m_xboxLiveContextImpl->application_config();
}
#if !XSAPI_CPP
std::shared_ptr<user_context>
xbox_live_context::_User_context() const
{
return m_xboxLiveContextImpl->user_context();
}
#endif
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END<commit_msg>Changed xbox_live_context to use its init (#411)<commit_after>// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "shared_macros.h"
#include "xsapi/services.h"
#include "user_context.h"
#include "xbox_system_factory.h"
#include "xbox_live_context_impl.h"
#if !TV_API && !UNIT_TEST_SERVICES && !XSAPI_U
#include "Misc/notification_service.h"
#endif
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN
#if XSAPI_XDK_AUTH
xbox_live_context::xbox_live_context(
_In_ Windows::Xbox::System::User^ user
)
{
m_xboxLiveContextImpl = xsapi_allocate_shared<xbox_live_context_impl>(user);
m_xboxLiveContextImpl->user_context()->set_caller_api_type(xbox::services::caller_api_type::api_cpp);
init();
}
Windows::Xbox::System::User^
xbox_live_context::user()
{
return m_xboxLiveContextImpl->user();
}
#endif
#if XSAPI_NONXDK_CPP_AUTH && !UNIT_TEST_SERVICES
xbox_live_context::xbox_live_context(
_In_ std::shared_ptr<system::xbox_live_user> user
)
{
user->_User_impl()->set_user_pointer(user);
m_xboxLiveContextImpl = xsapi_allocate_shared<xbox_live_context_impl>(user);
m_xboxLiveContextImpl->user_context()->set_caller_api_type(xbox::services::caller_api_type::api_cpp);
this->init();
}
std::shared_ptr<system::xbox_live_user>
xbox_live_context::user()
{
return m_xboxLiveContextImpl->user();
}
#endif
#if XSAPI_NONXDK_WINRT_AUTH
xbox_live_context::xbox_live_context(
_In_ Microsoft::Xbox::Services::System::XboxLiveUser^ user
)
{
m_xboxLiveContextImpl = xsapi_allocate_shared<xbox_live_context_impl>(user);
m_xboxLiveContextImpl->user_context()->set_caller_api_type(xbox::services::caller_api_type::api_cpp);
this->init();
}
Microsoft::Xbox::Services::System::XboxLiveUser^
xbox_live_context::user()
{
return m_xboxLiveContextImpl->user();
}
#endif
void xbox_live_context::init()
{
m_xboxLiveContextImpl->init();
m_achievementService = achievements::achievement_service(m_xboxLiveContextImpl->achievement_service_internal());
m_profileService = social::profile_service(m_xboxLiveContextImpl->profile_service_impl());
m_socialService = social::social_service(settings(), m_xboxLiveContextImpl->social_service_impl());
m_reputationService = social::reputation_service(m_xboxLiveContextImpl->reputation_service_impl());
m_presenceService = presence::presence_service(m_xboxLiveContextImpl->presence_service());
}
string_t xbox_live_context::xbox_live_user_id()
{
return utils::string_t_from_internal_string(m_xboxLiveContextImpl->xbox_live_user_id());
}
social::profile_service&
xbox_live_context::profile_service()
{
return m_profileService;
}
social::social_service&
xbox_live_context::social_service()
{
return m_socialService;
}
social::reputation_service&
xbox_live_context::reputation_service()
{
return m_reputationService;
}
leaderboard::leaderboard_service&
xbox_live_context::leaderboard_service()
{
return m_xboxLiveContextImpl->leaderboard_service();
}
achievements::achievement_service&
xbox_live_context::achievement_service()
{
return m_achievementService;
}
multiplayer::multiplayer_service&
xbox_live_context::multiplayer_service()
{
return m_xboxLiveContextImpl->multiplayer_service();
}
matchmaking::matchmaking_service&
xbox_live_context::matchmaking_service()
{
return m_xboxLiveContextImpl->matchmaking_service();
}
tournaments::tournament_service&
xbox_live_context::tournament_service()
{
return m_xboxLiveContextImpl->tournament_service();
}
user_statistics::user_statistics_service&
xbox_live_context::user_statistics_service()
{
return m_xboxLiveContextImpl->user_statistics_service();
}
const std::shared_ptr<real_time_activity::real_time_activity_service>&
xbox_live_context::real_time_activity_service()
{
return m_xboxLiveContextImpl->real_time_activity_service();
}
presence::presence_service&
xbox_live_context::presence_service()
{
return m_presenceService;
}
game_server_platform::game_server_platform_service&
xbox_live_context::game_server_platform_service()
{
return m_xboxLiveContextImpl->game_server_platform_service();
}
title_storage::title_storage_service&
xbox_live_context::title_storage_service()
{
return m_xboxLiveContextImpl->title_storage_service();
}
privacy::privacy_service&
xbox_live_context::privacy_service()
{
return m_xboxLiveContextImpl->privacy_service();
}
system::string_service&
xbox_live_context::string_service()
{
return m_xboxLiveContextImpl->string_service();
}
contextual_search::contextual_search_service&
xbox_live_context::contextual_search_service()
{
return m_xboxLiveContextImpl->contextual_search_service();
}
clubs::clubs_service&
xbox_live_context::clubs_service()
{
return m_xboxLiveContextImpl->clubs_service();
}
#if UWP_API || XSAPI_U
events::events_service&
xbox_live_context::events_service()
{
return m_xboxLiveContextImpl->events_service();
}
#endif
#if TV_API || UNIT_TEST_SERVICES
marketplace::catalog_service&
xbox_live_context::catalog_service()
{
return m_xboxLiveContextImpl->catalog_service();
}
marketplace::inventory_service&
xbox_live_context::inventory_service()
{
return m_xboxLiveContextImpl->inventory_service();
}
entertainment_profile::entertainment_profile_list_service&
xbox_live_context::entertainment_profile_list_service()
{
return m_xboxLiveContextImpl->entertainment_profile_list_service();
}
#endif
std::shared_ptr<xbox_live_context_settings>
xbox_live_context::settings()
{
return m_xboxLiveContextImpl->settings();
}
std::shared_ptr<xbox_live_app_config>
xbox_live_context::application_config()
{
return m_xboxLiveContextImpl->application_config();
}
#if !XSAPI_CPP
std::shared_ptr<user_context>
xbox_live_context::_User_context() const
{
return m_xboxLiveContextImpl->user_context();
}
#endif
NAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END<|endoftext|> |
<commit_before>#include <osgProducer/Viewer>
#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>
#include <osg/ClusterCullingCallback>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <osgText/FadeText>
#include <osgTerrain/DataSet>
#include <osgSim/OverlayNode>
#include <osgSim/SphereSegment>
#include <osgGA/NodeTrackerManipulator>
class GraphicsContext {
public:
GraphicsContext()
{
rs = new Producer::RenderSurface;
rs->setWindowRectangle(0,0,1,1);
rs->useBorder(false);
rs->useConfigEventThread(false);
rs->realize();
}
virtual ~GraphicsContext()
{
}
private:
Producer::ref_ptr<Producer::RenderSurface> rs;
};
osg::Node* createEarth()
{
osg::ref_ptr<osg::Node> scene;
{
std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
// make osgTerrain::DataSet quieter..
osgTerrain::DataSet::setNotifyOffset(1);
osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;
// register the source imagery
{
osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);
source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));
source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);
dataSet->addSource(source);
}
// set up destination database paramters.
dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
dataSet->setConvertFromGeographicToGeocentric(true);
dataSet->setDestinationName("test.osg");
// load the source data and record sizes.
dataSet->loadSources();
GraphicsContext context;
dataSet->createDestination(30);
if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
else dataSet->writeDestination();
scene = dataSet->getDestinationRootNode();
// now we must get rid of all the old OpenGL objects before we start using the scene graph again
// otherwise it'll end up in an inconsistent state.
scene->releaseGLObjects(dataSet->getState());
osg::Texture::flushAllDeletedTextureObjects(0);
osg::Drawable::flushAllDeletedDisplayLists(0);
}
return scene.release();
}
osgText::Text* createText(osg::EllipsoidModel* ellipsoid, double latitude, double longitude, double height, const std::string& str)
{
double X,Y,Z;
ellipsoid->convertLatLongHeightToXYZ( osg::DegreesToRadians(latitude), osg::DegreesToRadians(longitude), height, X, Y, Z);
osgText::Text* text = new osgText::FadeText;
osg::Vec3 normal = ellipsoid->computeLocalUpVector( X, Y, Z);
text->setCullCallback(new osg::ClusterCullingCallback(osg::Vec3(X,Y,Z), normal, 0.0));
text->setText(str);
text->setFont("fonts/arial.ttf");
text->setPosition(osg::Vec3(X,Y,Z));
text->setCharacterSize(300000.0f);
text->setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
text->setAutoRotateToScreen(true);
return text;
}
osg::Node* createFadeText(osg::EllipsoidModel* ellipsoid)
{
osg::Group* group = new osg::Group;
group->getOrCreateStateSet()->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
osg::Geode* geode = new osg::Geode;
group->addChild(geode);
std::vector<std::string> textList;
textList.push_back("Town");
textList.push_back("City");
textList.push_back("Village");
textList.push_back("River");
textList.push_back("Mountain");
textList.push_back("Road");
textList.push_back("Lake");
unsigned int numLat = 15;
unsigned int numLong = 20;
double latitude = 50.0;
double longitude = 0.0;
double deltaLatitude = 1.0f;
double deltaLongitude = 1.0f;
unsigned int t = 0;
for(unsigned int i = 0; i < numLat; ++i, latitude += deltaLatitude)
{
longitude = 0.0;
for(unsigned int j = 0; j < numLong; ++j, ++t, longitude += deltaLongitude)
{
geode->addDrawable( createText( ellipsoid, latitude, longitude, 0, textList[t % textList.size()]) );
}
}
return group;
}
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
viewer.getCullSettings().setNearFarRatio(0.00001f);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> root = createEarth();
if (!root) return 0;
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root.get());
osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
if (csn)
{
// add fade text around the globe
csn->addChild(createFadeText(csn->getEllipsoidModel()));
}
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete.
viewer.sync();
// run a clean up frame to delete all OpenGL objects.
viewer.cleanup_frame();
// wait for all the clean up frame to complete.
viewer.sync();
return 0;
}
<commit_msg>Updated positions of the text labels to make them move obvious on start up<commit_after>#include <osgProducer/Viewer>
#include <osg/Group>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Texture2D>
#include <osg/PositionAttitudeTransform>
#include <osg/MatrixTransform>
#include <osg/CoordinateSystemNode>
#include <osg/ClusterCullingCallback>
#include <osgDB/FileUtils>
#include <osgDB/ReadFile>
#include <osgText/FadeText>
#include <osgTerrain/DataSet>
#include <osgSim/OverlayNode>
#include <osgSim/SphereSegment>
#include <osgGA/NodeTrackerManipulator>
class GraphicsContext {
public:
GraphicsContext()
{
rs = new Producer::RenderSurface;
rs->setWindowRectangle(0,0,1,1);
rs->useBorder(false);
rs->useConfigEventThread(false);
rs->realize();
}
virtual ~GraphicsContext()
{
}
private:
Producer::ref_ptr<Producer::RenderSurface> rs;
};
osg::Node* createEarth()
{
osg::ref_ptr<osg::Node> scene;
{
std::string filename = osgDB::findDataFile("Images/land_shallow_topo_2048.jpg");
// make osgTerrain::DataSet quieter..
osgTerrain::DataSet::setNotifyOffset(1);
osg::ref_ptr<osgTerrain::DataSet> dataSet = new osgTerrain::DataSet;
// register the source imagery
{
osgTerrain::DataSet::Source* source = new osgTerrain::DataSet::Source(osgTerrain::DataSet::Source::IMAGE, filename);
source->setCoordinateSystemPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS);
source->setCoordinateSystem(osgTerrain::DataSet::coordinateSystemStringToWTK("WGS84"));
source->setGeoTransformPolicy(osgTerrain::DataSet::Source::PREFER_CONFIG_SETTINGS_BUT_SCALE_BY_FILE_RESOLUTION);
source->setGeoTransformFromRange(-180.0, 180.0, -90.0, 90.0);
dataSet->addSource(source);
}
// set up destination database paramters.
dataSet->setDatabaseType(osgTerrain::DataSet::LOD_DATABASE);
dataSet->setConvertFromGeographicToGeocentric(true);
dataSet->setDestinationName("test.osg");
// load the source data and record sizes.
dataSet->loadSources();
GraphicsContext context;
dataSet->createDestination(30);
if (dataSet->getDatabaseType()==osgTerrain::DataSet::LOD_DATABASE) dataSet->buildDestination();
else dataSet->writeDestination();
scene = dataSet->getDestinationRootNode();
// now we must get rid of all the old OpenGL objects before we start using the scene graph again
// otherwise it'll end up in an inconsistent state.
scene->releaseGLObjects(dataSet->getState());
osg::Texture::flushAllDeletedTextureObjects(0);
osg::Drawable::flushAllDeletedDisplayLists(0);
}
return scene.release();
}
osgText::Text* createText(osg::EllipsoidModel* ellipsoid, double latitude, double longitude, double height, const std::string& str)
{
double X,Y,Z;
ellipsoid->convertLatLongHeightToXYZ( osg::DegreesToRadians(latitude), osg::DegreesToRadians(longitude), height, X, Y, Z);
osgText::Text* text = new osgText::FadeText;
osg::Vec3 normal = ellipsoid->computeLocalUpVector( X, Y, Z);
text->setCullCallback(new osg::ClusterCullingCallback(osg::Vec3(X,Y,Z), normal, 0.0));
text->setText(str);
text->setFont("fonts/arial.ttf");
text->setPosition(osg::Vec3(X,Y,Z));
text->setCharacterSize(300000.0f);
text->setCharacterSizeMode(osgText::Text::OBJECT_COORDS_WITH_MAXIMUM_SCREEN_SIZE_CAPPED_BY_FONT_HEIGHT);
text->setAutoRotateToScreen(true);
return text;
}
osg::Node* createFadeText(osg::EllipsoidModel* ellipsoid)
{
osg::Group* group = new osg::Group;
group->getOrCreateStateSet()->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
osg::Geode* geode = new osg::Geode;
group->addChild(geode);
std::vector<std::string> textList;
textList.push_back("Town");
textList.push_back("City");
textList.push_back("Village");
textList.push_back("River");
textList.push_back("Mountain");
textList.push_back("Road");
textList.push_back("Lake");
unsigned int numLat = 15;
unsigned int numLong = 20;
double latitude = 0.0;
double longitude = -100.0;
double deltaLatitude = 1.0f;
double deltaLongitude = 1.0f;
unsigned int t = 0;
for(unsigned int i = 0; i < numLat; ++i, latitude += deltaLatitude)
{
double lgnt = longitude;
for(unsigned int j = 0; j < numLong; ++j, ++t, lgnt += deltaLongitude)
{
geode->addDrawable( createText( ellipsoid, latitude, lgnt, 0, textList[t % textList.size()]) );
}
}
return group;
}
int main(int argc, char **argv)
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the example which demonstrates use of node tracker.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName());
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
viewer.getCullSettings().setComputeNearFarMode(osg::CullSettings::COMPUTE_NEAR_FAR_USING_PRIMITIVES);
viewer.getCullSettings().setNearFarRatio(0.00001f);
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> root = createEarth();
if (!root) return 0;
// add a viewport to the viewer and attach the scene graph.
viewer.setSceneData(root.get());
osg::CoordinateSystemNode* csn = dynamic_cast<osg::CoordinateSystemNode*>(root.get());
if (csn)
{
// add fade text around the globe
csn->addChild(createFadeText(csn->getEllipsoidModel()));
}
// create the windows and run the threads.
viewer.realize();
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete.
viewer.sync();
// run a clean up frame to delete all OpenGL objects.
viewer.cleanup_frame();
// wait for all the clean up frame to complete.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>#include "OBJLIGHT.H"
#include "CAMERA.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#if PSX_VERSION || PSXPC_VERSION
#include "SPHERES.H"
#include "BUBBLES.H"
#endif
struct FOOTPRINT FootPrint[32];
int FootPrintNum;
//void /*$ra*/ TriggerAlertLight(long x /*$s2*/, long y /*$s3*/, long z /*$s1*/, long r /*$s5*/, long g /*stack 16*/, long b /*stack 20*/, long angle /*stack 24*/, int room_no /*stack 28*/, int falloff /*stack 32*/)
void TriggerAlertLight(long x, long y, long z, long r, long g, long b, long angle, int room_no, int falloff)//5D018, 5D494
{
UNIMPLEMENTED();
}
void ControlStrobeLight(short item_number)//5D118(<), 5D594 ///@FIXME im not sure this is correct redo this
{
struct ITEM_INFO* item;
long angle;
long sin;
long cos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
angle = item->pos.y_rot + 2912;
r = (item->trigger_flags) & 0x1F << 3;
b = (item->trigger_flags << 16) >> 17 & 0xF8;
g = (item->trigger_flags << 16) >> 12 & 0xF8;
item->pos.y_rot = angle;
angle += 22528;
angle >>= 4;
angle &= 0xFFF;
TriggerAlertLight(item->box_number, item->pos.y_pos - 512, item->pos.z_pos, r, g, b, angle, 12, item->room_number);
sin = rcossin_tbl[angle];
cos = rcossin_tbl[angle | 1];
TriggerDynamic(item->pos.x_pos + ((sin << 16) >> 14), item->pos.y_pos - 768, (item->pos.z_pos + (cos << 16) >> 14), 12, r, g ,b);
}
void ControlPulseLight(short item_number)//5D254(<), 5D6D0 (F)
{
struct ITEM_INFO* item;
long sin;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
item->item_flags[0] -= 1024;
sin = ABS(SIN((item->pos.y_pos & 0x3FFF) << 2) << 16 >> 14);
if (sin > 255)
{
sin = 255;
}//5D2F0
r = sin * ((item->trigger_flags & 0x1F) << 3) >> 9;
g = sin * ((item->trigger_flags << 10) >> 12) & 0xF8 >> 9;
b = sin * ((item->trigger_flags >> 17) & 0xF8) >> 9;
TriggerDynamic(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 24, r, g, b);
}
void ControlColouredLight(short item_number)//5D368, 5D7E4
{
UNIMPLEMENTED();
}
void ControlElectricalLight(short item_number)//5D3F8, 5D874
{
UNIMPLEMENTED();
}
void ControlBlinker(short item_number)//5D660(<), 5DADC (F)
{
struct ITEM_INFO* item;
struct PHD_VECTOR pos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
if (--item->item_flags[0] < 3)
{
pos.z = 0;
pos.y = 0;
pos.z = 0;
GetJointAbsPosition(item, &pos, 0);
r = (item->trigger_flags & 0x1F) << 3;
g = (item->trigger_flags >> 4) & 0xF8;
b = (item->trigger_flags >> 1) & 0xF8;
TriggerDynamic(pos.x, pos.y, pos.z, 16, r, g, b);
item->mesh_bits = 2;
if (item->item_flags[0] < 0)
{
item->item_flags[0] = 30;
}//5D73C
}
else
{
//5D734
item->mesh_bits = 1;
}
}<commit_msg>Add ControlColouredLight<commit_after>#include "OBJLIGHT.H"
#include "CAMERA.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#if PSX_VERSION || PSXPC_VERSION
#include "SPHERES.H"
#include "BUBBLES.H"
#endif
struct FOOTPRINT FootPrint[32];
int FootPrintNum;
//void /*$ra*/ TriggerAlertLight(long x /*$s2*/, long y /*$s3*/, long z /*$s1*/, long r /*$s5*/, long g /*stack 16*/, long b /*stack 20*/, long angle /*stack 24*/, int room_no /*stack 28*/, int falloff /*stack 32*/)
void TriggerAlertLight(long x, long y, long z, long r, long g, long b, long angle, int room_no, int falloff)//5D018, 5D494
{
UNIMPLEMENTED();
}
void ControlStrobeLight(short item_number)//5D118(<), 5D594 ///@FIXME im not sure this is correct redo this
{
struct ITEM_INFO* item;
long angle;
long sin;
long cos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
angle = item->pos.y_rot + 2912;
r = (item->trigger_flags) & 0x1F << 3;
b = (item->trigger_flags << 16) >> 17 & 0xF8;
g = (item->trigger_flags << 16) >> 12 & 0xF8;
item->pos.y_rot = angle;
angle += 22528;
angle >>= 4;
angle &= 0xFFF;
TriggerAlertLight(item->box_number, item->pos.y_pos - 512, item->pos.z_pos, r, g, b, angle, 12, item->room_number);
sin = rcossin_tbl[angle];
cos = rcossin_tbl[angle | 1];
TriggerDynamic(item->pos.x_pos + ((sin << 16) >> 14), item->pos.y_pos - 768, (item->pos.z_pos + (cos << 16) >> 14), 12, r, g ,b);
}
void ControlPulseLight(short item_number)//5D254(<), 5D6D0 (F)
{
struct ITEM_INFO* item;
long sin;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
item->item_flags[0] -= 1024;
sin = ABS(SIN((item->pos.y_pos & 0x3FFF) << 2) << 16 >> 14);
if (sin > 255)
{
sin = 255;
}//5D2F0
r = sin * ((item->trigger_flags & 0x1F) << 3) >> 9;
g = sin * ((item->trigger_flags << 16) >> 18) & 0xF8 >> 9;
b = sin * ((item->trigger_flags >> 23) & 0xF8) >> 9;
TriggerDynamic(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 24, r, g, b);
}
void ControlColouredLight(short item_number)//5D368(<), 5D7E4 (F)
{
struct ITEM_INFO* item;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
r = (item->trigger_flags & 0x1F) << 3;
g = (item->trigger_flags << 16) >> 18 & 0xF8;
b = (item->trigger_flags << 23) >> 17 & 0xF8;
TriggerDynamic(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 24, r, g, b);
UNIMPLEMENTED();
}
void ControlElectricalLight(short item_number)//5D3F8, 5D874
{
UNIMPLEMENTED();
}
void ControlBlinker(short item_number)//5D660(<), 5DADC (F)
{
struct ITEM_INFO* item;
struct PHD_VECTOR pos;
long r;
long g;
long b;
item = &items[item_number];
if (!TriggerActive(item))
return;
if (--item->item_flags[0] < 3)
{
pos.z = 0;
pos.y = 0;
pos.z = 0;
GetJointAbsPosition(item, &pos, 0);
r = (item->trigger_flags & 0x1F) << 3;
g = (item->trigger_flags >> 4) & 0xF8;
b = (item->trigger_flags >> 1) & 0xF8;
TriggerDynamic(pos.x, pos.y, pos.z, 16, r, g, b);
item->mesh_bits = 2;
if (item->item_flags[0] < 0)
{
item->item_flags[0] = 30;
}//5D73C
}
else
{
//5D734
item->mesh_bits = 1;
}
}<|endoftext|> |
<commit_before>/* OpenSceneGraph example, osganimate.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Notify>
#include <osg/io_utils>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
int main( int argc, char **argv )
{
osg::ArgumentParser arguments(&argc,argv);
// initialize the viewer.
osgViewer::Viewer viewer(arguments);
osg::Vec2d translate(0.0,0.0);
osg::Vec2d scale(1.0,1.0);
osg::Vec2d taper(1.0,1.0);
double angle = 0; // osg::inDegrees(45.0);
if (arguments.read("-a",angle)) { OSG_NOTICE<<"angle = "<<angle<<std::endl; angle = osg::inDegrees(angle); }
if (arguments.read("-t",translate.x(), translate.y())) { OSG_NOTICE<<"translate = "<<translate<<std::endl;}
if (arguments.read("-s",scale.x(), scale.y())) { OSG_NOTICE<<"scale = "<<scale<<std::endl;}
if (arguments.read("-k",taper.x(), taper.y())) { OSG_NOTICE<<"taper = "<<taper<<std::endl;}
osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
if (!model)
{
OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl;
return 1;
}
viewer.setSceneData(model.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.realize();
viewer.getCamera()->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
osg::Matrixd& pm = viewer.getCamera()->getProjectionMatrix();
pm.postMultRotate(osg::Quat(angle, osg::Vec3d(0.0,0.0,1.0)));
pm.postMultScale(osg::Vec3d(scale.x(),scale.y(),1.0));
pm.postMultTranslate(osg::Vec3d(translate.x(),translate.y(),0.0));
if (taper.x()!=1.0)
{
double x0 = (1.0+taper.x())/(1-taper.x());
OSG_NOTICE<<"x0 = "<<x0<<std::endl;
pm.postMult(osg::Matrixd(1.0-x0, 0.0, 0.0, 1.0,
0.0, 1.0-x0, 0.0, 0.0,
0.0, 0.0, (1.0-x0)*0.5, 0.0,
0.0, 0.0, 0.0, -x0));
}
return viewer.run();
}
<commit_msg>Added event handle for interactive setting of keystone variables<commit_after>/* OpenSceneGraph example, osganimate.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Notify>
#include <osg/io_utils>
#include <osgDB/ReadFile>
#include <osgGA/TrackballManipulator>
#include <osgViewer/Viewer>
class ControlPoints : public osg::Referenced
{
public:
ControlPoints():
bottom_left(-1.0,-1.0),
bottom_right(1.0,-1.0),
top_left(-1.0,1.0),
top_right(1.0,1.0) {}
void reset()
{
bottom_left.set(-1.0,-1.0);
bottom_right.set(1.0,-1.0);
top_left.set(-1.0,1.0);
top_right.set(1.0,1.0);
}
ControlPoints& operator = (const ControlPoints& rhs)
{
if (&rhs==this) return *this;
bottom_left = rhs.bottom_left;
bottom_right = rhs.bottom_right;
top_left = rhs.top_left;
top_right = rhs.top_right;
return *this;
}
osg::Vec2d bottom_left;
osg::Vec2d bottom_right;
osg::Vec2d top_left;
osg::Vec2d top_right;
};
class Keystone : public osg::Referenced
{
public:
Keystone():
translate(0.0,0.0),
scale(1.0,1.0),
taper(1.0,1.0),
angle(0.0)
{
}
void updateKeystone(ControlPoints cp)
{
// compute translation
translate = (cp.bottom_left+cp.bottom_right+cp.top_left+cp.top_right)*0.25;
// adjust control points to fit translation
cp.top_left += translate;
cp.top_right += translate;
cp.bottom_right += translate;
cp.bottom_left += translate;
// compute scaling
scale.x() = ( (cp.top_right.x()-cp.top_left.x()) + (cp.bottom_right.x()-cp.bottom_left.x()) )/4.0;
scale.y() = ( (cp.top_right.y()-cp.bottom_right.y()) + (cp.top_left.y()-cp.bottom_left.y()) )/4.0;
// adjust control points to fit scaling
cp.top_left.x() *= scale.x();
cp.top_right.x() *= scale.x();
cp.bottom_right.x() *= scale.x();
cp.bottom_left.x() *= scale.x();
cp.top_left.y() *= scale.y();
cp.top_right.y() *= scale.y();
cp.bottom_right.y() *= scale.y();
cp.bottom_left.y() *= scale.y();
//angle = atan2(-cp.bottom_left.x(),(-cp.bottom_left.y())
//taper.x() = (cp.top_left-cp.bottom_left).length() / (cp.top_right-cp.bottom_right).length();
//taper.y() = (cp.top_right-cp.top_left).length() / (cp.bottom_right-cp.bottom_left).length();
OSG_NOTICE<<"translate="<<translate<<std::endl;
OSG_NOTICE<<"scale="<<scale<<std::endl;
OSG_NOTICE<<"taper="<<taper<<std::endl;
OSG_NOTICE<<"angle="<<osg::RadiansToDegrees(angle)<<std::endl;
}
osg::Matrixd computeKeystoneMatrix() const
{
osg::Matrixd pm;
pm.postMultRotate(osg::Quat(angle, osg::Vec3d(0.0,0.0,1.0)));
pm.postMultScale(osg::Vec3d(scale.x(),scale.y(),1.0));
pm.postMultTranslate(osg::Vec3d(translate.x(),translate.y(),0.0));
if (taper.x()!=1.0)
{
double x0 = (1.0+taper.x())/(1-taper.x());
pm.postMult(osg::Matrixd(1.0-x0, 0.0, 0.0, 1.0,
0.0, 1.0-x0, 0.0, 0.0,
0.0, 0.0, (1.0-x0)*0.5, 0.0,
0.0, 0.0, 0.0, -x0));
}
if (taper.y()!=1.0)
{
double y0 = (1.0+taper.y())/(1-taper.y());
pm.postMult(osg::Matrixd(1.0-y0, 0.0, 0.0, 0.0,
0.0, 1.0-y0, 0.0, 1.0,
0.0, 0.0, (1.0-y0)*0.5, 0.0,
0.0, 0.0, 0.0, -y0));
}
return pm;
}
osg::Vec2d translate;
osg::Vec2d scale;
osg::Vec2d taper;
double angle;
};
class KeystoneHandler : public osgGA::GUIEventHandler
{
public:
KeystoneHandler(Keystone* keystone);
~KeystoneHandler() {}
bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa);
enum Region
{
NONE_SELECTED,
TOP_LEFT,
TOP,
TOP_RIGHT,
RIGHT,
BOTTOM_RIGHT,
BOTTOM,
BOTTOM_LEFT,
LEFT,
CENTER
};
protected:
osg::ref_ptr<Keystone> _keystone;
osg::Vec2d _startPosition;
osg::ref_ptr<ControlPoints> _startControlPoints;
Region _selectedRegion;
osg::ref_ptr<ControlPoints> _currentControlPoints;
};
KeystoneHandler::KeystoneHandler(Keystone* keystone):
_keystone(keystone),
_selectedRegion(NONE_SELECTED)
{
_startControlPoints = new ControlPoints;
_currentControlPoints = new ControlPoints;
}
bool KeystoneHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::PUSH):
{
OSG_NOTICE<<"Push with ea.getModKeyMask()="<<ea.getModKeyMask()<<std::endl;
if (ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_LEFT_CTRL || ea.getModKeyMask()==osgGA::GUIEventAdapter::MODKEY_RIGHT_CTRL )
{
OSG_NOTICE<<"Mouse "<<ea.getXnormalized()<<", "<<ea.getYnormalized()<<std::endl;
float x = ea.getXnormalized();
float y = ea.getYnormalized();
if (x<-0.33)
{
// left side
if (y<-0.33) _selectedRegion = BOTTOM_LEFT;
else if (y<0.33) _selectedRegion = LEFT;
else _selectedRegion = TOP_LEFT;
}
else if (x<0.33)
{
// center side
if (y<-0.33) _selectedRegion = BOTTOM;
else if (y<0.33) _selectedRegion = CENTER;
else _selectedRegion = TOP;
}
else
{
// right side
if (y<-0.33) _selectedRegion = BOTTOM_RIGHT;
else if (y<0.33) _selectedRegion = RIGHT;
else _selectedRegion = TOP_RIGHT;
}
(*_startControlPoints) = (*_currentControlPoints);
_startPosition.set(x,y);
OSG_NOTICE<<"Region "<<_selectedRegion<<std::endl;
}
else
{
_selectedRegion = NONE_SELECTED;
}
return false;
}
case(osgGA::GUIEventAdapter::DRAG):
{
if (_selectedRegion!=NONE_SELECTED)
{
(*_currentControlPoints) = (*_startControlPoints);
osg::Vec2d currentPosition(ea.getXnormalized(), ea.getYnormalized());
osg::Vec2d delta(currentPosition-_startPosition);
OSG_NOTICE<<"Moving region "<<_selectedRegion<<", moving by "<<currentPosition-_startPosition<<std::endl;
switch(_selectedRegion)
{
case(TOP_LEFT):
_currentControlPoints->top_left += delta;
break;
case(TOP):
_currentControlPoints->top_left += delta;
_currentControlPoints->top_right += delta;
break;
case(TOP_RIGHT):
_currentControlPoints->top_right += delta;
break;
case(RIGHT):
_currentControlPoints->top_right += delta;
_currentControlPoints->bottom_right += delta;
break;
case(BOTTOM_RIGHT):
_currentControlPoints->bottom_right += delta;
break;
case(BOTTOM):
_currentControlPoints->bottom_right += delta;
_currentControlPoints->bottom_left += delta;
break;
case(BOTTOM_LEFT):
_currentControlPoints->bottom_left += delta;
break;
case(LEFT):
_currentControlPoints->bottom_left += delta;
_currentControlPoints->top_left += delta;
break;
case(CENTER):
_currentControlPoints->bottom_left += delta;
_currentControlPoints->top_left += delta;
_currentControlPoints->bottom_right += delta;
_currentControlPoints->top_right += delta;
break;
case(NONE_SELECTED):
break;
}
_keystone->updateKeystone(*_currentControlPoints);
return true;
}
return false;
}
case(osgGA::GUIEventAdapter::RELEASE):
{
OSG_NOTICE<<"Mouse released "<<std::endl;
_selectedRegion = NONE_SELECTED;
return false;
}
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='r')
{
_selectedRegion = NONE_SELECTED;
_startControlPoints->reset();
_currentControlPoints->reset();
_keystone->updateKeystone(*_currentControlPoints);
}
return false;
}
default:
return false;
}
}
int main( int argc, char **argv )
{
osg::ArgumentParser arguments(&argc,argv);
// initialize the viewer.
osgViewer::Viewer viewer(arguments);
osg::ref_ptr<Keystone> keystone = new Keystone;
double distance, width, view_angle;
if (arguments.read("-p",distance, width, view_angle))
{
keystone->taper.x() = (2.0 + (width/distance) * sin(osg::inDegrees(view_angle))) / (2.0 - (width/distance) * sin(osg::inDegrees(view_angle)));
//scale.x() = 1.0/cos(osg::inDegrees(view_angle));
OSG_NOTICE<<"scale "<<keystone->scale<<std::endl;
OSG_NOTICE<<"taper "<<keystone->taper<<std::endl;
}
if (arguments.read("-a",keystone->angle)) { OSG_NOTICE<<"angle = "<<keystone->angle<<std::endl; keystone->angle = osg::inDegrees(keystone->angle); }
if (arguments.read("-t",keystone->translate.x(), keystone->translate.y())) { OSG_NOTICE<<"translate = "<<keystone->translate<<std::endl;}
if (arguments.read("-s",keystone->scale.x(), keystone->scale.y())) { OSG_NOTICE<<"scale = "<<keystone->scale<<std::endl;}
if (arguments.read("-k",keystone->taper.x(), keystone->taper.y())) { OSG_NOTICE<<"taper = "<<keystone->taper<<std::endl;}
osg::ref_ptr<osg::Node> model = osgDB::readNodeFiles(arguments);
if (!model)
{
OSG_NOTICE<<"No models loaded, please specify a model file on the command line"<<std::endl;
return 1;
}
viewer.setSceneData(model.get());
viewer.setCameraManipulator(new osgGA::TrackballManipulator());
viewer.realize();
viewer.getCamera()->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
osg::Matrixd original_pm = viewer.getCamera()->getProjectionMatrix();
viewer.addEventHandler(new KeystoneHandler(keystone));
while(!viewer.done())
{
viewer.advance();
viewer.eventTraversal();
viewer.updateTraversal();
if (keystone.valid())
{
viewer.getCamera()->setProjectionMatrix(original_pm * keystone->computeKeystoneMatrix());
}
viewer.renderingTraversals();
}
return 0;
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <fstream>
#include <sstream>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/BlendFunc>
#include <osg/ClearNode>
#include <osg/Depth>
#include <osg/Projection>
#include <osgUtil/Tesselator>
#include <osgUtil/TransformCallback>
#include <osgUtil/CullVisitor>
#include <osgUtil/Optimizer>
#include <osgText/Text>
#include <osgGA/TrackballManipulator>
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
int runApp(std::string xapp);
// class to handle events with a pick
class PickHandler : public osgGA::GUIEventHandler {
public:
PickHandler(osgProducer::Viewer* viewer,osgText::Text* updateText):
_viewer(viewer),
_updateText(updateText) {}
~PickHandler() {}
bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
std::string pick(float x, float y);
void highlight(const std::string& name)
{
if (_updateText.get()) _updateText->setText(name);
}
protected:
osgProducer::Viewer* _viewer;
osg::ref_ptr<osgText::Text> _updateText;
};
bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::FRAME):
case(osgGA::GUIEventAdapter::MOVE):
{
//osg::notify(osg::NOTICE)<<"MOVE "<<ea.getX()<<ea.getY()<<std::endl;
std::string picked_name = pick(ea.getX(),ea.getY());
highlight(picked_name);
return false;
}
case(osgGA::GUIEventAdapter::PUSH):
{
//osg::notify(osg::NOTICE)<<"PUSH "<<ea.getX()<<ea.getY()<<std::endl;
std::string picked_name = pick(ea.getX(),ea.getY());
if (!picked_name.empty())
{
runApp(picked_name);
return true;
}
else
{
return false;
}
}
default:
return false;
}
}
std::string PickHandler::pick(float x, float y)
{
osgUtil::IntersectVisitor::HitList hlist;
if (_viewer->computeIntersections(x, y, hlist))
{
for(osgUtil::IntersectVisitor::HitList::iterator hitr=hlist.begin();
hitr!=hlist.end();
++hitr)
{
if (hitr->_geode.valid() && !hitr->_geode->getName().empty()) return hitr->_geode->getName();
}
}
return "";
}
osg::Node* createHUD(osgText::Text* updateText)
{ // create the hud. derived from osgHud.cpp
// adds a set of quads, each in a separate Geode - which can be picked individually
// eg to be used as a menuing/help system!
// Can pick texts too!
osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
modelview_abs->setMatrix(osg::Matrix::identity());
osg::Projection* projection = new osg::Projection;
projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
projection->addChild(modelview_abs);
std::string timesFont("fonts/times.ttf");
// turn lighting off for the text and disable depth test to ensure its always ontop.
osg::Vec3 position(50.0f,510.0f,0.0f);
osg::Vec3 delta(0.0f,-60.0f,0.0f);
{ // this displays what has been selected
osg::Geode* geode = new osg::Geode();
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
geode->setName("The text label");
geode->addDrawable( updateText );
modelview_abs->addChild(geode);
updateText->setCharacterSize(20.0f);
updateText->setFont(timesFont);
updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
updateText->setText("");
updateText->setPosition(position);
position += delta;
}
return projection;
} // end create HUDf
static osg::Vec3 defaultPos( 0.0f, 0.0f, 0.0f );
static osg::Vec3 centerScope(0.0f, 0.0f, 0.0f);
class Xample
{
std::string texture;
std::string app;
public:
Xample(std::string image, std::string prog)
{
texture = image;
app = prog;
std::cout << "New Xample!" << std::endl;
};
~Xample() { };
std::string getTexture()
{
return texture;
}
std::string getApp()
{
return app;
}
}; // end class Xample
typedef std::list<Xample>::iterator OP;
static std::list<Xample> Xamplelist;
void printList()
{
std::cout << "start printList()" << std::endl;
for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i)
{
Xample& x = *i;
std::cout << "current x.texture = " << x.getTexture() << std::endl;
std::cout << "current x.app = " << x.getApp() << std::endl;
}
std::cout << "end printList()" << std::endl;
} // end printList()
int runApp(std::string xapp)
{
std::cout << "start runApp()" << std::endl;
for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i)
{
Xample& x = *i;
if(!xapp.compare(x.getApp()))
{
std::cout << "app found!" << std::endl;
const char* cxapp = xapp.c_str();
std::cout << "char* = " << cxapp <<std::endl;
system(cxapp);
return 1;
}
}
std::cout << "app not found!" << std::endl;
return 0;
} // end printList()
void readConfFile(char* confFile) // read confFile 1
{
std::cout << "Start reading confFile" << std::endl;
std::string fileName = osgDB::findDataFile(confFile);
if (fileName.empty())
{
std::cout << "Config file not found"<<confFile << std::endl;
return;
}
std::ifstream in(fileName.c_str());
if (!in)
{
std::cout << "File " << fileName << " can not be opened!" << std::endl;
exit(1);
}
std::string imageBuffer;
std::string appBuffer;
while (!in.eof())
{
getline(in, imageBuffer);
getline(in, appBuffer);
if(imageBuffer == "" || appBuffer == "");
else
{
std::cout << "imageBuffer: " << imageBuffer << std::endl;
std::cout << "appBuffer: " << appBuffer << std::endl;
// jeweils checken ob image vorhanden ist.
Xample tmp(imageBuffer, appBuffer); // create Xample objects 2
Xamplelist.push_back(tmp); // store objects in list 2
}
}
in.close();
std::cout << "End reading confFile" << std::endl;
printList();
} // end readConfFile
void SetObjectTextureState(osg::Geode *geodeCurrent, std::string texture)
{
// retrieve or create a StateSet
osg::StateSet* stateTexture = geodeCurrent->getOrCreateStateSet();
// load texture.jpg as an image
osg::Image* imgTexture = osgDB::readImageFile( texture );
// if the image is successfully loaded
if (imgTexture)
{
// create a new two-dimensional texture object
osg::Texture2D* texCube = new osg::Texture2D;
// set the texture to the loaded image
texCube->setImage(imgTexture);
// set the texture to the state
stateTexture->setTextureAttributeAndModes(0,texCube,osg::StateAttribute::ON);
// set the state of the current geode
geodeCurrent->setStateSet(stateTexture);
}
} // end SetObjectTextureState
osg::Geode* createTexturedCube(float fRadius,osg::Vec3 vPosition, std::string texture, std::string geodeName)
{
// create a cube shape
osg::Box *bCube = new osg::Box(vPosition,fRadius);
// osg::Box *bCube = new osg::Box(vPosition,fRadius);
// create a container that makes the cube drawable
osg::ShapeDrawable *sdCube = new osg::ShapeDrawable(bCube);
// create a geode object to as a container for our drawable cube object
osg::Geode* geodeCube = new osg::Geode();
geodeCube->setName( geodeName );
// set the object texture state
SetObjectTextureState(geodeCube, texture);
// add our drawable cube to the geode container
geodeCube->addDrawable(sdCube);
return(geodeCube);
} // end CreateCube
osg::PositionAttitudeTransform* getPATransformation(osg::Node* object, osg::Vec3 position, osg::Vec3 scale, osg::Vec3 pivot)
{
osg::PositionAttitudeTransform* tmpTrans = new osg::PositionAttitudeTransform();
tmpTrans->addChild( object );
tmpTrans->setPosition( position );
tmpTrans->setScale( scale );
tmpTrans->setPivotPoint( pivot );
return tmpTrans;
}
void printBoundings(osg::Node* current, std::string name)
{
const osg::BoundingSphere& currentBound = current->getBound();
std::cout << name << std::endl;
std::cout << "center = " << currentBound.center() << std::endl;
std::cout << "radius = " << currentBound.radius() << std::endl;
// return currentBound.radius();
}
osg::Group* setupGraph() // create Geodes/Nodes from Xamplelist 3
{
osg::Group* xGroup = new osg::Group();
// positioning and sizes
float defaultRadius = 0.8f;
int itemsInLine = 4; // name says everything
float offset = 0.05f;
float bs = (defaultRadius / 4) + offset;
float xstart = (3*bs) * (-1);
float zstart = xstart * (-1);
float xnext = xstart;
float znext = zstart;
float xjump = (2*bs);
float zjump = xjump;
osg::Vec3 vScale( 0.5f, 0.5f, 0.5f );
osg::Vec3 vPivot( 0.0f, 0.0f, 0.0f );
// run through Xampleliste
int z = 1;
for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i, ++z)
{
Xample& x = *i;
osg::Node* tmpCube = createTexturedCube(defaultRadius, defaultPos, x.getTexture(), x.getApp());
printBoundings(tmpCube, x.getApp());
osg::Vec3 vPosition( xnext, 0.0f, znext );
osg::PositionAttitudeTransform* transX = getPATransformation(tmpCube, vPosition, vScale, vPivot);
xGroup->addChild( transX );
// line feed
if(z < itemsInLine)
xnext += xjump;
else
{
xnext = xstart;
znext -= zjump;
z = 0;
}
} // end run through list
return xGroup;
} // end setupGraph
int main( int argc, char **argv )
{
if (argc<=1)
{
readConfFile("osg.conf"); // read ConfigFile 1
}
else
{
readConfFile(argv[1]); // read ConfigFile 1
}
// construct the viewer.
osgProducer::Viewer viewer;
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
// add the handler for doing the picking
viewer.getEventHandlerList().push_front(new PickHandler(&viewer,updateText.get()));
osg::Group* root = new osg::Group();
root->addChild( setupGraph() );
// add the HUD subgraph.
root->addChild(createHUD(updateText.get()));
// add model to viewer.
viewer.setSceneData( root );
// create the windows and run the threads.
viewer.realize();
osg::Matrix lookAt;
lookAt.makeLookAt(osg::Vec3(0.0f, -4.0f, 0.0f), centerScope, osg::Vec3(0.0f, 0.0f, 1.0f));
//viewer.setView(lookAt);
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// to be able to turn scene, place next call before viewer.update()
viewer.setView(lookAt);
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
} // end main
<commit_msg>Changed debugging info to use osg::notify<commit_after>#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <list>
#include <string>
#include <fstream>
#include <sstream>
#include <osg/Geode>
#include <osg/ShapeDrawable>
#include <osg/Material>
#include <osg/Texture2D>
#include <osg/Geometry>
#include <osg/MatrixTransform>
#include <osg/PositionAttitudeTransform>
#include <osg/BlendFunc>
#include <osg/ClearNode>
#include <osg/Depth>
#include <osg/Projection>
#include <osgUtil/Tesselator>
#include <osgUtil/TransformCallback>
#include <osgUtil/CullVisitor>
#include <osgUtil/Optimizer>
#include <osgText/Text>
#include <osgGA/TrackballManipulator>
#include <osgProducer/Viewer>
#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
int runApp(std::string xapp);
// class to handle events with a pick
class PickHandler : public osgGA::GUIEventHandler {
public:
PickHandler(osgProducer::Viewer* viewer,osgText::Text* updateText):
_viewer(viewer),
_updateText(updateText) {}
~PickHandler() {}
bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us);
std::string pick(float x, float y);
void highlight(const std::string& name)
{
if (_updateText.get()) _updateText->setText(name);
}
protected:
osgProducer::Viewer* _viewer;
osg::ref_ptr<osgText::Text> _updateText;
};
bool PickHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::FRAME):
case(osgGA::GUIEventAdapter::MOVE):
{
//osg::notify(osg::NOTICE)<<"MOVE "<<ea.getX()<<ea.getY()<<std::endl;
std::string picked_name = pick(ea.getX(),ea.getY());
highlight(picked_name);
return false;
}
case(osgGA::GUIEventAdapter::PUSH):
{
//osg::notify(osg::NOTICE)<<"PUSH "<<ea.getX()<<ea.getY()<<std::endl;
std::string picked_name = pick(ea.getX(),ea.getY());
if (!picked_name.empty())
{
runApp(picked_name);
return true;
}
else
{
return false;
}
}
default:
return false;
}
}
std::string PickHandler::pick(float x, float y)
{
osgUtil::IntersectVisitor::HitList hlist;
if (_viewer->computeIntersections(x, y, hlist))
{
for(osgUtil::IntersectVisitor::HitList::iterator hitr=hlist.begin();
hitr!=hlist.end();
++hitr)
{
if (hitr->_geode.valid() && !hitr->_geode->getName().empty()) return hitr->_geode->getName();
}
}
return "";
}
osg::Node* createHUD(osgText::Text* updateText)
{ // create the hud. derived from osgHud.cpp
// adds a set of quads, each in a separate Geode - which can be picked individually
// eg to be used as a menuing/help system!
// Can pick texts too!
osg::MatrixTransform* modelview_abs = new osg::MatrixTransform;
modelview_abs->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
modelview_abs->setMatrix(osg::Matrix::identity());
osg::Projection* projection = new osg::Projection;
projection->setMatrix(osg::Matrix::ortho2D(0,1280,0,1024));
projection->addChild(modelview_abs);
std::string timesFont("fonts/times.ttf");
// turn lighting off for the text and disable depth test to ensure its always ontop.
osg::Vec3 position(50.0f,510.0f,0.0f);
osg::Vec3 delta(0.0f,-60.0f,0.0f);
{ // this displays what has been selected
osg::Geode* geode = new osg::Geode();
osg::StateSet* stateset = geode->getOrCreateStateSet();
stateset->setMode(GL_LIGHTING,osg::StateAttribute::OFF);
stateset->setMode(GL_DEPTH_TEST,osg::StateAttribute::OFF);
geode->setName("The text label");
geode->addDrawable( updateText );
modelview_abs->addChild(geode);
updateText->setCharacterSize(20.0f);
updateText->setFont(timesFont);
updateText->setColor(osg::Vec4(1.0f,1.0f,0.0f,1.0f));
updateText->setText("");
updateText->setPosition(position);
position += delta;
}
return projection;
} // end create HUDf
static osg::Vec3 defaultPos( 0.0f, 0.0f, 0.0f );
static osg::Vec3 centerScope(0.0f, 0.0f, 0.0f);
class Xample
{
std::string texture;
std::string app;
public:
Xample(std::string image, std::string prog)
{
texture = image;
app = prog;
osg::notify(osg::INFO) << "New Xample!" << std::endl;
};
~Xample() { };
std::string getTexture()
{
return texture;
}
std::string getApp()
{
return app;
}
}; // end class Xample
typedef std::list<Xample>::iterator OP;
static std::list<Xample> Xamplelist;
void printList()
{
osg::notify(osg::INFO) << "start printList()" << std::endl;
for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i)
{
Xample& x = *i;
osg::notify(osg::INFO) << "current x.texture = " << x.getTexture() << std::endl;
osg::notify(osg::INFO) << "current x.app = " << x.getApp() << std::endl;
}
osg::notify(osg::INFO) << "end printList()" << std::endl;
} // end printList()
int runApp(std::string xapp)
{
osg::notify(osg::INFO) << "start runApp()" << std::endl;
for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i)
{
Xample& x = *i;
if(!xapp.compare(x.getApp()))
{
osg::notify(osg::INFO) << "app found!" << std::endl;
const char* cxapp = xapp.c_str();
osg::notify(osg::INFO) << "char* = " << cxapp <<std::endl;
system(cxapp);
return 1;
}
}
osg::notify(osg::INFO) << "app not found!" << std::endl;
return 0;
} // end printList()
void readConfFile(char* confFile) // read confFile 1
{
osg::notify(osg::INFO) << "Start reading confFile" << std::endl;
std::string fileName = osgDB::findDataFile(confFile);
if (fileName.empty())
{
osg::notify(osg::INFO) << "Config file not found"<<confFile << std::endl;
return;
}
std::ifstream in(fileName.c_str());
if (!in)
{
osg::notify(osg::INFO) << "File " << fileName << " can not be opened!" << std::endl;
exit(1);
}
std::string imageBuffer;
std::string appBuffer;
while (!in.eof())
{
getline(in, imageBuffer);
getline(in, appBuffer);
if(imageBuffer == "" || appBuffer == "");
else
{
osg::notify(osg::INFO) << "imageBuffer: " << imageBuffer << std::endl;
osg::notify(osg::INFO) << "appBuffer: " << appBuffer << std::endl;
// jeweils checken ob image vorhanden ist.
Xample tmp(imageBuffer, appBuffer); // create Xample objects 2
Xamplelist.push_back(tmp); // store objects in list 2
}
}
in.close();
osg::notify(osg::INFO) << "End reading confFile" << std::endl;
printList();
} // end readConfFile
void SetObjectTextureState(osg::Geode *geodeCurrent, std::string texture)
{
// retrieve or create a StateSet
osg::StateSet* stateTexture = geodeCurrent->getOrCreateStateSet();
// load texture.jpg as an image
osg::Image* imgTexture = osgDB::readImageFile( texture );
// if the image is successfully loaded
if (imgTexture)
{
// create a new two-dimensional texture object
osg::Texture2D* texCube = new osg::Texture2D;
// set the texture to the loaded image
texCube->setImage(imgTexture);
// set the texture to the state
stateTexture->setTextureAttributeAndModes(0,texCube,osg::StateAttribute::ON);
// set the state of the current geode
geodeCurrent->setStateSet(stateTexture);
}
} // end SetObjectTextureState
osg::Geode* createTexturedCube(float fRadius,osg::Vec3 vPosition, std::string texture, std::string geodeName)
{
// create a cube shape
osg::Box *bCube = new osg::Box(vPosition,fRadius);
// osg::Box *bCube = new osg::Box(vPosition,fRadius);
// create a container that makes the cube drawable
osg::ShapeDrawable *sdCube = new osg::ShapeDrawable(bCube);
// create a geode object to as a container for our drawable cube object
osg::Geode* geodeCube = new osg::Geode();
geodeCube->setName( geodeName );
// set the object texture state
SetObjectTextureState(geodeCube, texture);
// add our drawable cube to the geode container
geodeCube->addDrawable(sdCube);
return(geodeCube);
} // end CreateCube
osg::PositionAttitudeTransform* getPATransformation(osg::Node* object, osg::Vec3 position, osg::Vec3 scale, osg::Vec3 pivot)
{
osg::PositionAttitudeTransform* tmpTrans = new osg::PositionAttitudeTransform();
tmpTrans->addChild( object );
tmpTrans->setPosition( position );
tmpTrans->setScale( scale );
tmpTrans->setPivotPoint( pivot );
return tmpTrans;
}
void printBoundings(osg::Node* current, std::string name)
{
const osg::BoundingSphere& currentBound = current->getBound();
osg::notify(osg::INFO) << name << std::endl;
osg::notify(osg::INFO) << "center = " << currentBound.center() << std::endl;
osg::notify(osg::INFO) << "radius = " << currentBound.radius() << std::endl;
// return currentBound.radius();
}
osg::Group* setupGraph() // create Geodes/Nodes from Xamplelist 3
{
osg::Group* xGroup = new osg::Group();
// positioning and sizes
float defaultRadius = 0.8f;
int itemsInLine = 4; // name says everything
float offset = 0.05f;
float bs = (defaultRadius / 4) + offset;
float xstart = (3*bs) * (-1);
float zstart = xstart * (-1);
float xnext = xstart;
float znext = zstart;
float xjump = (2*bs);
float zjump = xjump;
osg::Vec3 vScale( 0.5f, 0.5f, 0.5f );
osg::Vec3 vPivot( 0.0f, 0.0f, 0.0f );
// run through Xampleliste
int z = 1;
for (OP i = Xamplelist.begin() ; i != Xamplelist.end() ; ++i, ++z)
{
Xample& x = *i;
osg::Node* tmpCube = createTexturedCube(defaultRadius, defaultPos, x.getTexture(), x.getApp());
printBoundings(tmpCube, x.getApp());
osg::Vec3 vPosition( xnext, 0.0f, znext );
osg::PositionAttitudeTransform* transX = getPATransformation(tmpCube, vPosition, vScale, vPivot);
xGroup->addChild( transX );
// line feed
if(z < itemsInLine)
xnext += xjump;
else
{
xnext = xstart;
znext -= zjump;
z = 0;
}
} // end run through list
return xGroup;
} // end setupGraph
int main( int argc, char **argv )
{
if (argc<=1)
{
readConfFile("osg.conf"); // read ConfigFile 1
}
else
{
readConfFile(argv[1]); // read ConfigFile 1
}
// construct the viewer.
osgProducer::Viewer viewer;
// set up the value with sensible default event handlers.
viewer.setUpViewer(osgProducer::Viewer::STANDARD_SETTINGS);
osg::ref_ptr<osgText::Text> updateText = new osgText::Text;
// add the handler for doing the picking
viewer.getEventHandlerList().push_front(new PickHandler(&viewer,updateText.get()));
osg::Group* root = new osg::Group();
root->addChild( setupGraph() );
// add the HUD subgraph.
root->addChild(createHUD(updateText.get()));
// add model to viewer.
viewer.setSceneData( root );
// create the windows and run the threads.
viewer.realize();
osg::Matrix lookAt;
lookAt.makeLookAt(osg::Vec3(0.0f, -4.0f, 0.0f), centerScope, osg::Vec3(0.0f, 0.0f, 1.0f));
//viewer.setView(lookAt);
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// to be able to turn scene, place next call before viewer.update()
viewer.setView(lookAt);
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
} // end main
<|endoftext|> |
<commit_before>#include <iostream>
#include "consoleui.h"
#include "performer.h"
#include "dataaccess.h"
using namespace std;
ConsoleUI::ConsoleUI()
{
}
// Should not contain logic for individual commands, that should be in separate functions!
void ConsoleUI::run()
{
intro();
commandHelp();
string command;
do
{
cout << endl << "Enter a command or help for list of commands: ";
cin >> command;
cout << endl;
if (command == "list")
{
displayListOfPerformers();
}
else if (command == "add")
{
commandAdd();
}
else if (command == "search")
{
displaySearch();
}
else if(command == "sort")
{
chooseSort();
}
else if (command == "help")
{
commandHelp();
}
else if (command == "exit")
{
cout << "exiting" << endl;
}
else
{
cout << "invalid command." << endl;
cout << "type 'help' to see list of commands" << endl;
}
}while (command != "exit");
}
void ConsoleUI::displayListOfPerformers()
{
displayTopTable();
vector<Performer> pf = _service.getPerformers();
for (size_t i = 0; i < pf.size(); ++i)
{
if(pf[i].getName().length() > 16)
{
cout << i+1 << "\t" << pf[i].getName();
cout << "\t" << pf[i].getGender() << "\t" << "\t";
cout << pf[i].getbYear() << "\t\t\t" << pf[i].getdYear();
cout << "\t\t\t" << pf[i].getNation() << endl;
}
else if(pf[i].getName().length() < 16 && pf[i].getName().length() > 8)
{
cout << i+1 << "\t" << pf[i].getName();
cout << "\t\t" << pf[i].getGender() << "\t" << "\t";
cout << pf[i].getbYear() << "\t\t\t" << pf[i].getdYear();
cout << "\t\t\t" << pf[i].getNation() << endl;
}
else if(pf[i].getName().length() <= 8)
{
cout << i+1 << "\t" << pf[i].getName();
cout << "\t\t\t" << pf[i].getGender() << "\t" << "\t";
cout << pf[i].getbYear() << "\t\t\t" << pf[i].getdYear();
cout << "\t\t\t" << pf[i].getNation() << endl;
}
}
}
void ConsoleUI::displaySearch()
{
string input;
cout << "Enter full name to search for, the search is case-sensitive: ";
cin.ignore();
getline(cin, input);
vector <Performer> newVector = _service.search(input);
if(newVector.size() == 0)
{
cout << "Nothing was found!";
}
if(newVector.size() > 0)
{
displayTopTable();
}
for(size_t i = 0; i < newVector.size(); i++)
{
if(newVector[i].getName().length() > 16)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() < 16 && newVector[i].getName().length() > 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() <= 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
}
}
void ConsoleUI::displaySort(vector<Performer> newVector)
{
for(size_t i = 0; i < newVector.size(); i++)
{
if(newVector[i].getName().length() > 16)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() < 16 && newVector[i].getName().length() > 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() <= 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
}
}
string ConsoleUI::inputName()
{
string name;
cout << "Enter full name: ";
cin.ignore();
getline(cin, name);
int nameLength = name.length();
for(int i = 0;i < nameLength;i++)
{
while(!isalpha(name[i]) && name[i] != ' ')
{
cout << "Invalid name, try again: ";
cin.ignore();
getline(cin, name);
nameLength = name.length();
}
}
return name;
}
string ConsoleUI::inputGender()
{
string gender;
cout << "Enter gender (Male or Female): ";
do
{
getline(cin, gender);
if(gender == "Male")
{
return gender;
}
else if (gender == "male")
{
gender = "Male";
return gender;
}
else if(gender == "Female")
{
return gender;
}
else if (gender == "female")
{
gender = "Female";
return gender;
}
else
{
cout << "That's not a gender!" << endl;
cout << "Enter gender (Male or Female): ";
}
}while(1 == 1);
return gender;
}
string ConsoleUI::inputBirth()
{
string birth;
cout << "Enter year of birth: ";
getline(cin, birth);
int value = atoi(birth.c_str());
int birthLength = birth.length();
for(int i = 0;i < birthLength;i++)
{
while(!isdigit(birth[i]))
{
cout << "Invalid year, try again: ";
getline(cin, birth);
birthLength = birth.length();
}
}
while(value < 0 || value > 2016)
{
cout << "That's not a valid year" << endl;
cout << "Enter year of birth: ";
getline(cin, birth);
value = atoi(birth.c_str());
}
return birth;
}
string ConsoleUI::inputDeath()
{
string death;
cout << "Enter year of death or enter '--' if alive: ";
getline(cin, death);
int value = atoi(death.c_str());
if(death == "--")
{
return death;
}
int deathLength = death.length();
for(int i = 0;i < deathLength;i++)
{
while(!isdigit(death[i]))
{
cout << "Invalid year, try again: ";
getline(cin, death);
deathLength = death.length();
}
}
while(value < 0 || value > 2016)
{
cout << "That's not a valid year" << endl;
cout << "Enter year of death: ";
getline(cin, death);
value = atoi(death.c_str());
}
return death;
}
string ConsoleUI::inputNation()
{
string nation;
cout << "Enter Nation: ";
getline(cin, nation);
int nationLength = nation.length();
for(int i = 0;i < nationLength;i++)
{
while(!isalpha(nation[i]))
{
cout << "Invalid nation, try again: ";
getline(cin, nation);
nationLength = nation.length();
}
}
return nation;
}
void ConsoleUI::chooseSort()
{
int choice;
cout << "Choose 1 to sort in alphabetical order" << endl;
cout << "Choose 2 to sort by birth year" << endl;
cout << "Choose 3 to sort by gender" << endl;
cout << "Choose 4 to sort by nationality" << endl;
cout << "Choice: ";
cin >> choice;
if(choice == 1)
{
vector<Performer> newVector = _service.sortByName();
cout << endl;
cout << " " << "---- List ordered alphabetically by first name ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
displaySort(newVector);
}
else if(choice == 2)
{
cout << endl;
cout << " " << "---- List ordered by birth year ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
vector <Performer> newVector = _service.sortBybYear();
displaySort(newVector);
}
else if(choice == 3)
{
cout << endl;
cout << " " << "---- List ordered by gender ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
vector <Performer> newVector = _service.sortByGender();
displaySort(newVector);
}
else if(choice == 4)
{
vector<Performer> newVector = _service.sortByNationality();
cout << endl;
cout << " " << "---- List ordered alphabetically by nationality ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
displaySort(newVector);
}
else {
cout << "Invalid choice!";
}
}
void ConsoleUI::commandHelp()
{
cout << "list - This will list all computer scientists in the system" << endl;
cout << "add - This will add a new computer scientists" << endl;
cout << "search - Searches for a given computer scientist" << endl;
cout << "sort - Sorts the computer scientists by choice" << endl;
cout << "help - Displays list of commands" << endl;
cout << "exit - This will close the application" << endl;
}
void ConsoleUI::commandAdd()
{
string name = inputName();
string gender = inputGender();
string birth = inputBirth();
string death = inputDeath();
int value = 0;
int value2 = 0;
if(death != "--")
{
value = atoi(birth.c_str());
value2 = atoi(death.c_str());
}
while(value2 < value)
{
cout << "Death year can't be less than birth year!" << endl;
death = inputDeath();
if(death == "--")
{
break;
}
value2 = atoi(death.c_str());
}
string nation = inputNation();
_service.addPerformer(name, gender, birth, death, nation);
cout << endl;
cout << name << " has been added to the database!" << endl;
}
void ConsoleUI::intro()
{
cout << endl;
cout << "This program is designed to keep track of some details on known computer scientists. " << endl;
cout << "User is able to enter known characters from the history of computer science into a database." << endl;
cout << "The program can display a list of the characters that have been entered into the database." << endl;
cout << "It is also possible to perform a search of a specific person from the list." << endl << endl;
for (int i = 0; i < 45*2; ++i)
{
cout << "=";
}
cout << endl;
cout << endl;
cout << "Please enter one of the following commands to continue:" << endl;
cout << endl;
}
void ConsoleUI::displayTopTable()
{
cout << endl;
cout << " " << "---- List of all computer scientists in the system ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
}
<commit_msg>Lagaði útlit ofl UI<commit_after>#include <iostream>
#include "consoleui.h"
#include "performer.h"
#include "dataaccess.h"
using namespace std;
ConsoleUI::ConsoleUI()
{
}
// Should not contain logic for individual commands, that should be in separate functions!
void ConsoleUI::run()
{
intro();
commandHelp();
string command;
do
{
cout << endl << "Enter a command ('help' for list of commands): ";
cin >> command;
cout << endl;
if (command == "list")
{
displayListOfPerformers();
}
else if (command == "add")
{
commandAdd();
}
else if (command == "search")
{
displaySearch();
}
else if(command == "sort")
{
chooseSort();
}
else if (command == "help")
{
commandHelp();
}
else if (command == "exit")
{
cout << "exiting" << endl;
}
else
{
cout << "invalid command." << endl;
cout << "Enter 'help' to see list of commands" << endl;
}
}while (command != "exit");
}
void ConsoleUI::displayListOfPerformers()
{
displayTopTable();
vector<Performer> pf = _service.getPerformers();
for (size_t i = 0; i < pf.size(); ++i)
{
if(pf[i].getName().length() > 16)
{
cout << i+1 << "\t" << pf[i].getName();
cout << "\t" << pf[i].getGender() << "\t" << "\t";
cout << pf[i].getbYear() << "\t\t\t" << pf[i].getdYear();
cout << "\t\t\t" << pf[i].getNation() << endl;
}
else if(pf[i].getName().length() < 16 && pf[i].getName().length() > 8)
{
cout << i+1 << "\t" << pf[i].getName();
cout << "\t\t" << pf[i].getGender() << "\t" << "\t";
cout << pf[i].getbYear() << "\t\t\t" << pf[i].getdYear();
cout << "\t\t\t" << pf[i].getNation() << endl;
}
else if(pf[i].getName().length() <= 8)
{
cout << i+1 << "\t" << pf[i].getName();
cout << "\t\t\t" << pf[i].getGender() << "\t" << "\t";
cout << pf[i].getbYear() << "\t\t\t" << pf[i].getdYear();
cout << "\t\t\t" << pf[i].getNation() << endl;
}
}
}
void ConsoleUI::displaySearch()
{
string input;
cout << "Enter full name of computer scientist (the search is case-sensitive): ";
cin.ignore();
getline(cin, input);
vector <Performer> newVector = _service.search(input);
if(newVector.size() == 0)
{
cout << "Nothing was found! Please enter 'search' to try again" << endl;
}
if(newVector.size() > 0)
{
displayTopTable();
}
for(size_t i = 0; i < newVector.size(); i++)
{
if(newVector[i].getName().length() > 16)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() < 16 && newVector[i].getName().length() > 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() <= 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
}
}
void ConsoleUI::displaySort(vector<Performer> newVector)
{
for(size_t i = 0; i < newVector.size(); i++)
{
if(newVector[i].getName().length() > 16)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() < 16 && newVector[i].getName().length() > 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
else if(newVector[i].getName().length() <= 8)
{
cout << i+1 << "\t" << newVector[i].getName();
cout << "\t\t\t" << newVector[i].getGender() << "\t" << "\t";
cout << newVector[i].getbYear() << "\t\t\t" << newVector[i].getdYear();
cout << "\t\t\t" << newVector[i].getNation() << endl;
}
}
}
string ConsoleUI::inputName()
{
string name;
cout << "Enter full name: ";
cin.ignore();
getline(cin, name);
int nameLength = name.length();
for(int i = 0;i < nameLength;i++)
{
while(!isalpha(name[i]) && name[i] != ' ')
{
cout << "Invalid name, please try again: ";
cin.ignore();
getline(cin, name);
nameLength = name.length();
}
}
return name;
}
string ConsoleUI::inputGender()
{
string gender;
cout << "Enter gender (Male or Female): ";
do
{
getline(cin, gender);
if(gender == "Male")
{
return gender;
}
else if (gender == "male")
{
gender = "Male";
return gender;
}
else if(gender == "Female")
{
return gender;
}
else if (gender == "female")
{
gender = "Female";
return gender;
}
else
{
cout << "That is not a gender!" << endl;
cout << "Enter gender (Male or Female): ";
}
}while(1 == 1);
return gender;
}
string ConsoleUI::inputBirth()
{
string birth;
cout << "Enter year of birth: ";
getline(cin, birth);
int value = atoi(birth.c_str());
int birthLength = birth.length();
for(int i = 0;i < birthLength;i++)
{
while(!isdigit(birth[i]))
{
cout << "Invalid year,please try again: ";
getline(cin, birth);
birthLength = birth.length();
}
}
while(value < 0 || value > 2016)
{
cout << "That is not a valid year" << endl;
cout << "Enter year of birth: ";
getline(cin, birth);
value = atoi(birth.c_str());
}
return birth;
}
string ConsoleUI::inputDeath()
{
string death;
cout << "Enter year of death or enter '--' if alive: ";
getline(cin, death);
int value = atoi(death.c_str());
if(death == "--")
{
return death;
}
int deathLength = death.length();
for(int i = 0;i < deathLength;i++)
{
while(!isdigit(death[i]))
{
cout << "Invalid year, please try again: ";
getline(cin, death);
deathLength = death.length();
}
}
while(value < 0 || value > 2016)
{
cout << "That's not a valid year" << endl;
cout << "Enter year of death: ";
getline(cin, death);
value = atoi(death.c_str());
}
return death;
}
string ConsoleUI::inputNation()
{
string nation;
cout << "Enter Nationality: ";
getline(cin, nation);
int nationLength = nation.length();
for(int i = 0;i < nationLength;i++)
{
while(!isalpha(nation[i]))
{
cout << "Invalid nationality, please try again: ";
getline(cin, nation);
nationLength = nation.length();
}
}
return nation;
}
void ConsoleUI::chooseSort()
{
int choice;
cout << "Choose '1' to display a list sorted in alphabetical order" << endl;
cout << "Choose '2' to display a list sorted by birth year" << endl;
cout << "Choose '3' to display a list sorted by gender" << endl;
cout << "Choose '4' to display a list sorted by nationality" << endl;
cout << "Enter a number to continue: ";
cin >> choice;
if(choice == 1)
{
vector<Performer> newVector = _service.sortByName();
cout << endl;
cout << " " << "---- List ordered alphabetically by first name ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
displaySort(newVector);
}
else if(choice == 2)
{
cout << endl;
cout << " " << "---- List ordered by birth year ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
vector <Performer> newVector = _service.sortBybYear();
displaySort(newVector);
}
else if(choice == 3)
{
cout << endl;
cout << " " << "---- List ordered by gender ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
vector <Performer> newVector = _service.sortByGender();
displaySort(newVector);
}
else if(choice == 4)
{
vector<Performer> newVector = _service.sortByNationality();
cout << endl;
cout << " " << "---- List ordered alphabetically by nationality ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
displaySort(newVector);
}
else {
cout << "Invalid choice!";
}
}
void ConsoleUI::commandHelp()
{
cout << "list - This will list all computer scientists in the system" << endl;
cout << "add - This will add a new computer scientists" << endl;
cout << "search - Searches for a given computer scientist" << endl;
cout << "sort - Sorts the computer scientists by preferences" << endl;
cout << "help - Displays list of commands" << endl;
cout << "exit - This will close the application" << endl;
}
void ConsoleUI::commandAdd()
{
string name = inputName();
string gender = inputGender();
string birth = inputBirth();
string death = inputDeath();
int value = 0;
int value2 = 0;
if(death != "--")
{
value = atoi(birth.c_str());
value2 = atoi(death.c_str());
}
while(value2 < value)
{
cout << "Death year can not be less than birth year! Please try again. " << endl;
death = inputDeath();
if(death == "--")
{
break;
}
value2 = atoi(death.c_str());
}
string nation = inputNation();
_service.addPerformer(name, gender, birth, death, nation);
cout << endl;
cout << name << " has been added to the database!" << endl;
}
void ConsoleUI::intro()
{
cout << endl;
cout << "This program is designed to keep track of some details on known computer scientists. " << endl;
cout << "User is able to enter known characters from the history of computer science into a database." << endl;
cout << "The program can display a list of the characters that have been entered into the database." << endl;
cout << "The program can sort the list by the user's preferences" << endl;
cout << "It is also possible to perform a search of a specific person from the list." << endl << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
cout << endl;
cout << "Please enter one of the following commands to continue:" << endl;
cout << endl;
}
void ConsoleUI::displayTopTable()
{
cout << endl;
cout << " " << "---- List of all computer scientists in the system ----" << endl;
cout << endl;
cout << "Nr" << "\t" << "Name" << "\t\t\t" << "Gender";
cout << "\t\t" << "Birth year" << "\t\t" << "Deceased" << "\t\t" <<"Nationality" << endl;
for (int i = 0; i < 54*2; ++i)
{
cout << "=";
}
cout << endl;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Tasks/BasicTasks/CombatTask.h>
#include <hspp/Tasks/BasicTasks/DamageTask.h>
#include <hspp/Tasks/BasicTasks/DestroyMinionTask.h>
#include <hspp/Tasks/PowerTasks/FreezeTask.h>
#include <hspp/Tasks/PowerTasks/PoisonousTask.h>
namespace Hearthstonepp::BasicTasks
{
CombatTask::CombatTask(TaskAgent& agent)
: m_requirement(TaskID::SELECT_TARGET, agent)
{
// Do Nothing
}
TaskID CombatTask::GetTaskID() const
{
return TaskID::COMBAT;
}
MetaData CombatTask::Impl(Player& player1, Player& player2)
{
TaskMeta serialized;
// Get Targeting Response from GameInterface
m_requirement.Interact(player1.id, serialized);
auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized);
if (req == nullptr)
{
return MetaData::COMBAT_FLATBUFFER_NULLPTR;
}
BYTE src = req->src();
BYTE dst = req->dst();
// Source Minion Index Verification
if (src > player1.field.size())
{
return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE;
}
// Destination Verification
// dst == 0 : hero
// 1 < dst <= field.size : minion
if (dst > player2.field.size())
{
return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE;
}
source = (src > 0) ? dynamic_cast<Character*>(player1.field[src - 1])
: dynamic_cast<Character*>(player1.hero);
target = (dst > 0) ? dynamic_cast<Character*>(player2.field[dst - 1])
: dynamic_cast<Character*>(player2.hero);
if (!source->CanAttack() || !source->IsValidAttackTarget(player2, *target))
{
return MetaData::COMBAT_SOURCE_CANT_ATTACK;
}
source->attackableCount--;
const size_t targetAttack = target->GetAttack();
const size_t sourceAttack = source->GetAttack();
const size_t targetDamage = target->TakeDamage(*source, sourceAttack);
const bool isTargetDamaged = targetDamage > 0;
// Destroy target if attacker is poisonous
if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
{
PowerTask::PoisonousTask(target).Run(player1, player2);
}
// Freeze target if attacker is freezer
if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
{
PowerTask::FreezeTask(target, TargetType::OPPONENT_MINION)
.Run(player1, player2);
}
// Ignore damage from defenders with 0 attack
if (targetAttack > 0)
{
const size_t sourceDamage = source->TakeDamage(*target, targetAttack);
const bool isSourceDamaged = sourceDamage > 0;
// Destroy source if defender is poisonous
if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
{
PowerTask::PoisonousTask(source).Run(player1, player2);
}
// Freeze source if defender is freezer
if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
{
PowerTask::FreezeTask(source, TargetType::OPPONENT_MINION)
.Run(player1, player2);
}
}
if (source->GetGameTag(GameTag::STEALTH) == 1)
{
source->SetGameTag(GameTag::STEALTH, 0);
}
// Source Health Check
if (source->health <= 0)
{
DestroyMinionTask(source).Run(player1, player2);
}
// Target Health Check
if (target->health <= 0)
{
DestroyMinionTask(target).Run(player2, player1);
}
return MetaData::COMBAT_SUCCESS;
}
} // namespace Hearthstonepp::BasicTasks
<commit_msg>refactor: Add comments, add 'const' to variables and change names<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include <hspp/Tasks/BasicTasks/CombatTask.h>
#include <hspp/Tasks/BasicTasks/DestroyMinionTask.h>
#include <hspp/Tasks/PowerTasks/FreezeTask.h>
#include <hspp/Tasks/PowerTasks/PoisonousTask.h>
namespace Hearthstonepp::BasicTasks
{
CombatTask::CombatTask(TaskAgent& agent)
: m_requirement(TaskID::SELECT_TARGET, agent)
{
// Do Nothing
}
TaskID CombatTask::GetTaskID() const
{
return TaskID::COMBAT;
}
MetaData CombatTask::Impl(Player& player1, Player& player2)
{
TaskMeta serialized;
// Get targeting response from game interface
m_requirement.Interact(player1.id, serialized);
// Get the source and the target
const auto req = TaskMeta::ConvertTo<FlatData::ResponseTarget>(serialized);
if (req == nullptr)
{
return MetaData::COMBAT_FLATBUFFER_NULLPTR;
}
const BYTE sourceIndex = req->src();
const BYTE targetIndex = req->dst();
// Verify index of the source
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (sourceIndex > player1.field.size())
{
return MetaData::COMBAT_SRC_IDX_OUT_OF_RANGE;
}
// Verify index of the target
// NOTE: 0 means hero, 1 ~ field.size() means minion
if (targetIndex > player2.field.size())
{
return MetaData::COMBAT_DST_IDX_OUT_OF_RANGE;
}
source = (sourceIndex > 0)
? dynamic_cast<Character*>(player1.field[sourceIndex - 1])
: dynamic_cast<Character*>(player1.hero);
target = (targetIndex > 0)
? dynamic_cast<Character*>(player2.field[targetIndex - 1])
: dynamic_cast<Character*>(player2.hero);
if (!source->CanAttack() || !source->IsValidAttackTarget(player2, *target))
{
return MetaData::COMBAT_SOURCE_CANT_ATTACK;
}
source->attackableCount--;
const size_t targetAttack = target->GetAttack();
const size_t sourceAttack = source->GetAttack();
const size_t targetDamage = target->TakeDamage(*source, sourceAttack);
const bool isTargetDamaged = targetDamage > 0;
// Destroy target if attacker is poisonous
if (isTargetDamaged && source->GetGameTag(GameTag::POISONOUS) == 1)
{
PowerTask::PoisonousTask(target).Run(player1, player2);
}
// Freeze target if attacker is freezer
if (isTargetDamaged && source->GetGameTag(GameTag::FREEZE) == 1)
{
PowerTask::FreezeTask(target, TargetType::OPPONENT_MINION)
.Run(player1, player2);
}
// Ignore damage from defenders with 0 attack
if (targetAttack > 0)
{
const size_t sourceDamage = source->TakeDamage(*target, targetAttack);
const bool isSourceDamaged = sourceDamage > 0;
// Destroy source if defender is poisonous
if (isSourceDamaged && target->GetGameTag(GameTag::POISONOUS) == 1)
{
PowerTask::PoisonousTask(source).Run(player1, player2);
}
// Freeze source if defender is freezer
if (isSourceDamaged && target->GetGameTag(GameTag::FREEZE) == 1)
{
PowerTask::FreezeTask(source, TargetType::OPPONENT_MINION)
.Run(player1, player2);
}
}
// Remove stealth ability if attacker has it
if (source->GetGameTag(GameTag::STEALTH) == 1)
{
source->SetGameTag(GameTag::STEALTH, 0);
}
// Check health of the source
if (source->health <= 0)
{
DestroyMinionTask(source).Run(player1, player2);
}
// Check health of the target
if (target->health <= 0)
{
DestroyMinionTask(target).Run(player2, player1);
}
return MetaData::COMBAT_SUCCESS;
}
} // namespace Hearthstonepp::BasicTasks
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the GNU Public License (GPL) version 1.0 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
* OpenSceneGraph Public License for more details.
*/
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#include <osgGA/TrackballManipulator>
#include "SlideEventHandler.h"
#include "PointsEventHandler.h"
#include "SlideShowConstructor.h"
class FindHomePositionVisitor : public osg::NodeVisitor
{
public:
FindHomePositionVisitor():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
void apply(osg::Node& node)
{
SlideShowConstructor::HomePosition* homePosition = dynamic_cast<SlideShowConstructor::HomePosition*>(node.getUserData());
if (homePosition)
{
_homePosition = homePosition;
}
traverse(node);
}
osg::ref_ptr<SlideShowConstructor::HomePosition> _homePosition;
};
// add in because MipsPro can't handle no osgGA infront of TrackballManipulator
// but VisualStudio6.0 can't handle the osgGA...
using namespace osgGA;
class SlideShowTrackballManipulator : public osgGA::TrackballManipulator
{
public:
SlideShowTrackballManipulator()
{
}
virtual void home(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us)
{
FindHomePositionVisitor fhpv;
if (_node.valid()) _node->accept(fhpv);
if (fhpv._homePosition.valid())
{
computePosition(fhpv._homePosition->eye,
fhpv._homePosition->center,
fhpv._homePosition->up);
us.requestRedraw();
}
else
{
TrackballManipulator::home(ea,us);
}
}
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the application for presenting 3D interactive slide shows.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-a","Turn auto stepping on by default");
arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time duration in seconds between layers/slides");
arguments.getApplicationUsage()->addCommandLineOption("-s <float> <float> <float>","width, height, distance and of the screen away from the viewer");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
SlideShowTrackballManipulator* sstbm = new SlideShowTrackballManipulator;
viewer.addCameraManipulator(sstbm);
// set up the value with sensible default event handler.
viewer.setUpViewer(osgProducer::Viewer::DRIVE_MANIPULATOR |
osgProducer::Viewer::FLIGHT_MANIPULATOR |
osgProducer::Viewer::STATE_MANIPULATOR |
osgProducer::Viewer::HEAD_LIGHT_SOURCE |
osgProducer::Viewer::STATS_MANIPULATOR |
osgProducer::Viewer::VIEWER_MANIPULATOR |
osgProducer::Viewer::ESCAPE_SETS_DONE);
// read any time delay argument.
float timeDelayBetweenSlides = 1.5f;
while (arguments.read("-d",timeDelayBetweenSlides)) {}
bool autoSteppingActive = false;
while (arguments.read("-a")) autoSteppingActive = true;
// register the slide event handler - which moves the presentation from slide to slide, layer to layer.
SlideEventHandler* seh = new SlideEventHandler;
viewer.getEventHandlerList().push_front(seh);
seh->setAutoSteppingActive(autoSteppingActive);
seh->setTimeDelayBetweenSlides(timeDelayBetweenSlides);
// register the handler for modifying the point size
PointsEventHandler* peh = new PointsEventHandler;
viewer.getEventHandlerList().push_front(peh);
osg::DisplaySettings::instance()->setSplitStereoAutoAjustAspectRatio(false);
float width = osg::DisplaySettings::instance()->getScreenWidth();
float height = osg::DisplaySettings::instance()->getScreenHeight();
float distance = osg::DisplaySettings::instance()->getScreenDistance();
bool sizesSpecified = false;
while (arguments.read("-s", width, height, distance))
{
sizesSpecified = true;
osg::DisplaySettings::instance()->setScreenDistance(distance);
osg::DisplaySettings::instance()->setScreenHeight(height);
osg::DisplaySettings::instance()->setScreenWidth(width);
}
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
//arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
osg::Timer timer;
osg::Timer_t start_tick = timer.tick();
// allow sharing of models.
osgDB::Registry::instance()->setUseObjectCacheHint(true);
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
// switch sharing of loaded models back off.
osgDB::Registry::instance()->setUseObjectCacheHint(false);
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
osg::Timer_t end_tick = timer.tick();
std::cout << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
// optimize the scene graph, remove rendundent nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(loadedModel.get());
// pass the model to the slide event handler so it knows which to manipulate.
seh->set(loadedModel.get());
// set the scene to render
viewer.setSceneData(loadedModel.get());
// pass the global stateset to the point event handler so that it can
// alter the point size of all points in the scene.
peh->setStateSet(viewer.getGlobalStateSet());
// create the windows and run the threads.
viewer.realize();
double vfov = osg::RadiansToDegrees(atan2(height/2.0,distance)*2.0);
double hfov = osg::RadiansToDegrees(atan2(width/2.0,distance)*2.0);
viewer.setLensPerspective( hfov, vfov, 0.1, 1000.0);
// set all the sceneview's up so that their left and right add cull masks are set up.
for(osgProducer::OsgCameraGroup::SceneHandlerList::iterator itr=viewer.getSceneHandlerList().begin();
itr!=viewer.getSceneHandlerList().end();
++itr)
{
osgUtil::SceneView* sceneview = (*itr)->getSceneView();
sceneview->setCullMask(0xffffffff);
sceneview->setCullMaskLeft(0x00000001);
sceneview->setCullMaskRight(0x00000002);
// sceneview->setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius);
}
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<commit_msg>Added a f after 2.0 definitions in atan2 to get round stupid MS errors.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the GNU Public License (GPL) version 1.0 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
* OpenSceneGraph Public License for more details.
*/
#include <osgDB/ReadFile>
#include <osgUtil/Optimizer>
#include <osgProducer/Viewer>
#include <osgGA/TrackballManipulator>
#include "SlideEventHandler.h"
#include "PointsEventHandler.h"
#include "SlideShowConstructor.h"
class FindHomePositionVisitor : public osg::NodeVisitor
{
public:
FindHomePositionVisitor():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
void apply(osg::Node& node)
{
SlideShowConstructor::HomePosition* homePosition = dynamic_cast<SlideShowConstructor::HomePosition*>(node.getUserData());
if (homePosition)
{
_homePosition = homePosition;
}
traverse(node);
}
osg::ref_ptr<SlideShowConstructor::HomePosition> _homePosition;
};
// add in because MipsPro can't handle no osgGA infront of TrackballManipulator
// but VisualStudio6.0 can't handle the osgGA...
using namespace osgGA;
class SlideShowTrackballManipulator : public osgGA::TrackballManipulator
{
public:
SlideShowTrackballManipulator()
{
}
virtual void home(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& us)
{
FindHomePositionVisitor fhpv;
if (_node.valid()) _node->accept(fhpv);
if (fhpv._homePosition.valid())
{
computePosition(fhpv._homePosition->eye,
fhpv._homePosition->center,
fhpv._homePosition->up);
us.requestRedraw();
}
else
{
TrackballManipulator::home(ea,us);
}
}
};
int main( int argc, char **argv )
{
// use an ArgumentParser object to manage the program arguments.
osg::ArgumentParser arguments(&argc,argv);
// set up the usage document, in case we need to print out how to use this program.
arguments.getApplicationUsage()->setApplicationName(arguments.getApplicationName());
arguments.getApplicationUsage()->setDescription(arguments.getApplicationName()+" is the application for presenting 3D interactive slide shows.");
arguments.getApplicationUsage()->setCommandLineUsage(arguments.getApplicationName()+" [options] filename ...");
arguments.getApplicationUsage()->addCommandLineOption("-h or --help","Display this information");
arguments.getApplicationUsage()->addCommandLineOption("-a","Turn auto stepping on by default");
arguments.getApplicationUsage()->addCommandLineOption("-d <float>","Time duration in seconds between layers/slides");
arguments.getApplicationUsage()->addCommandLineOption("-s <float> <float> <float>","width, height, distance and of the screen away from the viewer");
// construct the viewer.
osgProducer::Viewer viewer(arguments);
SlideShowTrackballManipulator* sstbm = new SlideShowTrackballManipulator;
viewer.addCameraManipulator(sstbm);
// set up the value with sensible default event handler.
viewer.setUpViewer(osgProducer::Viewer::DRIVE_MANIPULATOR |
osgProducer::Viewer::FLIGHT_MANIPULATOR |
osgProducer::Viewer::STATE_MANIPULATOR |
osgProducer::Viewer::HEAD_LIGHT_SOURCE |
osgProducer::Viewer::STATS_MANIPULATOR |
osgProducer::Viewer::VIEWER_MANIPULATOR |
osgProducer::Viewer::ESCAPE_SETS_DONE);
// read any time delay argument.
float timeDelayBetweenSlides = 1.5f;
while (arguments.read("-d",timeDelayBetweenSlides)) {}
bool autoSteppingActive = false;
while (arguments.read("-a")) autoSteppingActive = true;
// register the slide event handler - which moves the presentation from slide to slide, layer to layer.
SlideEventHandler* seh = new SlideEventHandler;
viewer.getEventHandlerList().push_front(seh);
seh->setAutoSteppingActive(autoSteppingActive);
seh->setTimeDelayBetweenSlides(timeDelayBetweenSlides);
// register the handler for modifying the point size
PointsEventHandler* peh = new PointsEventHandler;
viewer.getEventHandlerList().push_front(peh);
osg::DisplaySettings::instance()->setSplitStereoAutoAjustAspectRatio(false);
float width = osg::DisplaySettings::instance()->getScreenWidth();
float height = osg::DisplaySettings::instance()->getScreenHeight();
float distance = osg::DisplaySettings::instance()->getScreenDistance();
bool sizesSpecified = false;
while (arguments.read("-s", width, height, distance))
{
sizesSpecified = true;
osg::DisplaySettings::instance()->setScreenDistance(distance);
osg::DisplaySettings::instance()->setScreenHeight(height);
osg::DisplaySettings::instance()->setScreenWidth(width);
}
// get details on keyboard and mouse bindings used by the viewer.
viewer.getUsage(*arguments.getApplicationUsage());
// if user request help write it out to cout.
if (arguments.read("-h") || arguments.read("--help"))
{
arguments.getApplicationUsage()->write(std::cout);
return 1;
}
// any option left unread are converted into errors to write out later.
//arguments.reportRemainingOptionsAsUnrecognized();
// report any errors if they have occured when parsing the program aguments.
if (arguments.errors())
{
arguments.writeErrorMessages(std::cout);
return 1;
}
osg::Timer timer;
osg::Timer_t start_tick = timer.tick();
// allow sharing of models.
osgDB::Registry::instance()->setUseObjectCacheHint(true);
// read the scene from the list of file specified commandline args.
osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFiles(arguments);
// switch sharing of loaded models back off.
osgDB::Registry::instance()->setUseObjectCacheHint(false);
// if no model has been successfully loaded report failure.
if (!loadedModel)
{
std::cout << arguments.getApplicationName() <<": No data loaded" << std::endl;
return 1;
}
osg::Timer_t end_tick = timer.tick();
std::cout << "Time to load = "<<timer.delta_s(start_tick,end_tick)<<std::endl;
// optimize the scene graph, remove rendundent nodes and state etc.
osgUtil::Optimizer optimizer;
optimizer.optimize(loadedModel.get());
// pass the model to the slide event handler so it knows which to manipulate.
seh->set(loadedModel.get());
// set the scene to render
viewer.setSceneData(loadedModel.get());
// pass the global stateset to the point event handler so that it can
// alter the point size of all points in the scene.
peh->setStateSet(viewer.getGlobalStateSet());
// create the windows and run the threads.
viewer.realize();
double vfov = osg::RadiansToDegrees(atan2(height/2.0f,distance)*2.0);
double hfov = osg::RadiansToDegrees(atan2(width/2.0f,distance)*2.0);
viewer.setLensPerspective( hfov, vfov, 0.1, 1000.0);
// set all the sceneview's up so that their left and right add cull masks are set up.
for(osgProducer::OsgCameraGroup::SceneHandlerList::iterator itr=viewer.getSceneHandlerList().begin();
itr!=viewer.getSceneHandlerList().end();
++itr)
{
osgUtil::SceneView* sceneview = (*itr)->getSceneView();
sceneview->setCullMask(0xffffffff);
sceneview->setCullMaskLeft(0x00000001);
sceneview->setCullMaskRight(0x00000002);
// sceneview->setFusionDistance(osgUtil::SceneView::USE_FUSION_DISTANCE_VALUE,radius);
}
while( !viewer.done() )
{
// wait for all cull and draw threads to complete.
viewer.sync();
// update the scene by traversing it with the the update visitor which will
// call all node update callbacks and animations.
viewer.update();
// fire off the cull and draw traversals of the scene.
viewer.frame();
}
// wait for all cull and draw threads to complete before exit.
viewer.sync();
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
int main()
{
std::cout << "hello world" << std::endl;
return 0;
}
<commit_msg>context-menu-cleaner: Scan context menu items<commit_after>#include <iostream>
#include "kbase/logging.h"
#include "kbase/registry.h"
#include "kbase/string_encoding_conversions.h"
#include "kbase/string_format.h"
#include "kbase/string_util.h"
namespace cmc {
struct entry {
using string_type = std::wstring;
string_type path;
string_type value;
string_type command;
};
std::wstring StringifyRootKey(HKEY root)
{
// Workaround for switch on pointers.
constexpr auto kClassRoot = reinterpret_cast<ULONG_PTR>(HKEY_CLASSES_ROOT);
constexpr auto kCurrentUser = reinterpret_cast<ULONG_PTR>(HKEY_CURRENT_USER);
constexpr auto kLocalMachine = reinterpret_cast<ULONG_PTR>(HKEY_LOCAL_MACHINE);
constexpr auto kUsers = reinterpret_cast<ULONG_PTR>(HKEY_USERS);
switch (reinterpret_cast<ULONG_PTR>(root)) {
case kClassRoot:
return L"HKEY_CLASSES_ROOT";
case kCurrentUser:
return L"HKEY_CURRENT_USER";
case kLocalMachine:
return L"HKEY_LOCAL_MACHINE";
case kUsers:
return L"HKEY_USERS";
default:
throw std::invalid_argument(kbase::StringPrintf(
"unknown root key; key=%x", reinterpret_cast<ULONG_PTR>(root)));
}
}
std::wstring AppendRegPath(const std::wstring& base, const std::wstring& key)
{
std::wstring result(base);
if (!kbase::EndsWith(result, L"\\")) {
result.append(L"\\");
}
result.append(key);
return result;
}
void ScanEntriesAt(HKEY root, const wchar_t* sub, std::vector<entry>& entries)
{
auto prefix = AppendRegPath(StringifyRootKey(root), sub);
kbase::RegKeyIterator key_it(root, sub);
for (const auto& key : key_it) {
if (!key) {
continue;
}
kbase::RegKey command;
command.Open(key.Get(), L"command", KEY_READ);
if (!command || !command.HasValue(L"")) {
continue;
}
std::wstring value, cmd_value;
if (key.HasValue(L"")) {
key.ReadValue(L"", value);
}
command.ReadValue(L"", cmd_value);
auto ent = entry{AppendRegPath(prefix, key.subkey_name()), value, cmd_value};
entries.push_back(std::move(ent));
}
}
} // namespace cmc
int main()
{
std::vector<cmc::entry> menu_entries;
cmc::ScanEntriesAt(HKEY_CLASSES_ROOT, L"Directory\\Background\\shell", menu_entries);
for (const auto& entry : menu_entries) {
std::cout << "Path=" << kbase::WideToASCII(entry.path) << "\n"
<< "Value=" << kbase::WideToASCII(entry.value) << "\n"
<< "Cmd=" << kbase::WideToASCII(entry.command) << "\n\n";
}
return 0;
}
<|endoftext|> |
<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ
m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
m_pStarControl = new CStarControl();
m_pRayControl = new CRayControl();
return 1;
}
int CGameProcess::ShutDown() //رϷ
{
delete m_pRole;
delete m_pSkillSystem;
delete m_pCameraBase;
delete m_pStarControl;
delete m_pRayControl;
DelAllListen();
return 0;
}
int CGameProcess::Update()
{
float ifps = g_Engine.pGame->GetIFps();
if (g_Engine.pInput->IsKeyDown('1'))
{
CAction* pAction = m_pRole->OrceAction("attack02");
if (pAction)
{
pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('2'))
{
CAction* pAction = m_pRole->OrceAction("skill01");
if (pAction)
{
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('3'))
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CRoleBase* pTarget = NULL;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 15.0f)
{
pTarget = m_vAIList[i];
break;
}
}
if (pTarget)
{
CVector<int> vTarget;
vTarget.Append(pTarget->GetRoleID());
pAction->SetupSkillBulletTarget(vTarget);
m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
}
}
}
else if (g_Engine.pInput->IsKeyDown('4'))//ӵ
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
{
vTarget.Append(m_vAIList[i]->GetRoleID());
}
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
else if (g_Engine.pInput->IsKeyDown('5'))
{
CAction* pAction = m_pRole->OrceAction("skill03");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('6'))
{
CAction* pAction = m_pRole->OrceAction("skill06");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vPos.Append(m_vAIList[i]->GetPosition());
}
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('7'))
{
CAction* pAction = m_pRole->OrceAction("skill05");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vTarget.Append(m_vAIList[i]->GetRoleID());
}
}
}
return 0;
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
#include "World.h"
#include "Action.h"
#include "FPSRoleLocal.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ
m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
m_pStarControl = new CStarControl();
m_pRayControl = new CRayControl();
return 1;
}
int CGameProcess::ShutDown() //رϷ
{
delete m_pRole;
delete m_pSkillSystem;
delete m_pCameraBase;
delete m_pStarControl;
delete m_pRayControl;
DelAllListen();
return 0;
}
int CGameProcess::Update()
{
float ifps = g_Engine.pGame->GetIFps();
if (g_Engine.pInput->IsKeyDown('1'))
{
CAction* pAction = m_pRole->OrceAction("attack02");
if (pAction)
{
pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('2'))
{
CAction* pAction = m_pRole->OrceAction("skill01");
if (pAction)
{
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('3'))
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CRoleBase* pTarget = NULL;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 15.0f)
{
pTarget = m_vAIList[i];
break;
}
}
if (pTarget)
{
CVector<int> vTarget;
vTarget.Append(pTarget->GetRoleID());
pAction->SetupSkillBulletTarget(vTarget);
m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1);
}
}
}
else if (g_Engine.pInput->IsKeyDown('4'))//ӵ
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
{
vTarget.Append(m_vAIList[i]->GetRoleID());
}
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
else if (g_Engine.pInput->IsKeyDown('5'))
{
CAction* pAction = m_pRole->OrceAction("skill03");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('6'))
{
CAction* pAction = m_pRole->OrceAction("skill06");
if (pAction)
{
m_pRole->StopMove();
CVector<vec3> vPos;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vPos.Append(m_vAIList[i]->GetPosition());
}
pAction->SetupSkillTargetPoint(vPos);
}
}
else if (g_Engine.pInput->IsKeyDown('7'))
{
CAction* pAction = m_pRole->OrceAction("skill05");
if (pAction)
{
m_pRole->StopMove();
CVector<int> vTarget;
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 20.0f)
vTarget.Append(m_vAIList[i]->GetRoleID());
}
if (!vTarget.Empty())
{
pAction->SetupSkillBulletTarget(vTarget);
}
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <boost/program_options.hpp>
#include "Main.h"
#include "InputFileStream.h"
#include "OutputFileStream.h"
#include "AlignedSentence.h"
#include "AlignedSentenceSyntax.h"
#include "Parameter.h"
#include "Rules.h"
using namespace std;
bool g_debug = false;
int main(int argc, char** argv)
{
cerr << "Starting" << endl;
Parameter params;
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help", "Print help messages")
("MaxSpan", po::value<int>()->default_value(params.maxSpan), "Max (source) span of a rule. ie. number of words in the source")
("GZOutput", po::value<bool>()->default_value(params.gzOutput), "Compress extract files")
("GlueGrammar", po::value<string>()->default_value(params.gluePath), "Output glue grammar to here")
("SentenceOffset", po::value<long>()->default_value(params.sentenceOffset), "Starting sentence id. Not used")
("SourceSyntax", po::value<bool>()->default_value(params.sourceSyntax), "Source sentence is a parse tree")
("TargetSyntax", po::value<bool>()->default_value(params.targetSyntax), "Target sentence is a parse tree")
("MixedSyntaxType", po::value<int>()->default_value(params.mixedSyntaxType), "Hieu's Mixed syntax type. 0(default)=no mixed syntax, 1=add [X] only if no syntactic label. 2=add [X] everywhere");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // can throw
/** --help option
*/
if ( vm.count("help") || argc < 5 )
{
std::cout << "Basic Command Line Parameter App" << std::endl
<< desc << std::endl;
return EXIT_SUCCESS;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return EXIT_FAILURE;
}
if (vm.count("MaxSpan")) params.maxSpan = vm["MaxSpan"].as<int>();
if (vm.count("GZOutput")) params.gzOutput = true;
if (vm.count("GlueGrammar")) params.gluePath = vm["GlueGrammar"].as<string>();
if (vm.count("SentenceOffset")) params.sentenceOffset = vm["SentenceOffset"].as<long>();
if (vm.count("SourceSyntax")) params.sourceSyntax = true;
if (vm.count("TargetSyntax")) params.targetSyntax = true;
if (vm.count("MixedSyntaxType")) params.mixedSyntaxType = vm["MixedSyntaxType"].as<int>();
// input files;
string pathTarget = argv[1];
string pathSource = argv[2];
string pathAlignment = argv[3];
string pathExtract = argv[4];
string pathExtractInv = pathExtract;
if (params.gzOutput) {
pathExtract += ".gz";
pathExtractInv += ".gz";
}
Moses::InputFileStream strmTarget(pathTarget);
Moses::InputFileStream strmSource(pathSource);
Moses::InputFileStream strmAlignment(pathAlignment);
Moses::OutputFileStream extractFile(pathExtract);
Moses::OutputFileStream extractInvFile(pathExtractInv);
// MAIN LOOP
string lineTarget, lineSource, lineAlignment;
while (getline(strmTarget, lineTarget)) {
bool success;
success = getline(strmSource, lineSource);
if (!success) {
throw "Couldn't read source";
}
success = getline(strmAlignment, lineAlignment);
if (!success) {
throw "Couldn't read alignment";
}
/*
cerr << "lineTarget=" << lineTarget << endl;
cerr << "lineSource=" << lineSource << endl;
cerr << "lineAlignment=" << lineAlignment << endl;
*/
AlignedSentence *alignedSentence;
if (params.sourceSyntax || params.targetSyntax) {
alignedSentence = new AlignedSentenceSyntax(lineSource, lineTarget, lineAlignment);
}
else {
alignedSentence = new AlignedSentence(lineSource, lineTarget, lineAlignment);
}
alignedSentence->Create(params);
//cerr << alignedSentence->Debug();
Rules rules(*alignedSentence);
rules.Extend(params);
rules.Consolidate(params);
//cerr << rules.Debug();
rules.Output(extractFile, true);
rules.Output(extractInvFile, false);
delete alignedSentence;
}
if (!params.gluePath.empty()) {
Moses::OutputFileStream glueFile(params.gluePath);
CreateGlueGrammar(glueFile);
}
cerr << "Finished" << endl;
}
void CreateGlueGrammar(Moses::OutputFileStream &glueFile)
{
glueFile << "<s> [X] ||| <s> [S] ||| 1 ||| ||| 0" << endl
<< "[X][S] </s> [X] ||| [X][S] </s> [S] ||| 1 ||| 0-0 ||| 0" << endl
<< "[X][S] [X][X] [X] ||| [X][S] [X][X] [S] ||| 2.718 ||| 0-0 1-1 ||| 0" << endl;
}
<commit_msg>boolean args<commit_after>#include <iostream>
#include <cstdlib>
#include <boost/program_options.hpp>
#include "Main.h"
#include "InputFileStream.h"
#include "OutputFileStream.h"
#include "AlignedSentence.h"
#include "AlignedSentenceSyntax.h"
#include "Parameter.h"
#include "Rules.h"
using namespace std;
bool g_debug = false;
int main(int argc, char** argv)
{
cerr << "Starting" << endl;
Parameter params;
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help", "Print help messages")
("MaxSpan", po::value<int>()->default_value(params.maxSpan), "Max (source) span of a rule. ie. number of words in the source")
("GlueGrammar", po::value<string>()->default_value(params.gluePath), "Output glue grammar to here")
("SentenceOffset", po::value<long>()->default_value(params.sentenceOffset), "Starting sentence id. Not used")
("GZOutput", "Compress extract files")
("SourceSyntax", "Source sentence is a parse tree")
("TargetSyntax", "Target sentence is a parse tree")
("MixedSyntaxType", po::value<int>()->default_value(params.mixedSyntaxType), "Hieu's Mixed syntax type. 0(default)=no mixed syntax, 1=add [X] only if no syntactic label. 2=add [X] everywhere");
po::variables_map vm;
try
{
po::store(po::parse_command_line(argc, argv, desc),
vm); // can throw
/** --help option
*/
if ( vm.count("help") || argc < 5 )
{
std::cout << "Basic Command Line Parameter App" << std::endl
<< desc << std::endl;
return EXIT_SUCCESS;
}
po::notify(vm); // throws on error, so do after help in case
// there are any problems
}
catch(po::error& e)
{
std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
std::cerr << desc << std::endl;
return EXIT_FAILURE;
}
if (vm.count("MaxSpan")) params.maxSpan = vm["MaxSpan"].as<int>();
if (vm.count("GZOutput")) params.gzOutput = true;
if (vm.count("GlueGrammar")) params.gluePath = vm["GlueGrammar"].as<string>();
if (vm.count("SentenceOffset")) params.sentenceOffset = vm["SentenceOffset"].as<long>();
if (vm.count("SourceSyntax")) params.sourceSyntax = true;
if (vm.count("TargetSyntax")) params.targetSyntax = true;
if (vm.count("MixedSyntaxType")) params.mixedSyntaxType = vm["MixedSyntaxType"].as<int>();
// input files;
string pathTarget = argv[1];
string pathSource = argv[2];
string pathAlignment = argv[3];
string pathExtract = argv[4];
string pathExtractInv = pathExtract;
if (params.gzOutput) {
pathExtract += ".gz";
pathExtractInv += ".gz";
}
Moses::InputFileStream strmTarget(pathTarget);
Moses::InputFileStream strmSource(pathSource);
Moses::InputFileStream strmAlignment(pathAlignment);
Moses::OutputFileStream extractFile(pathExtract);
Moses::OutputFileStream extractInvFile(pathExtractInv);
// MAIN LOOP
string lineTarget, lineSource, lineAlignment;
while (getline(strmTarget, lineTarget)) {
bool success;
success = getline(strmSource, lineSource);
if (!success) {
throw "Couldn't read source";
}
success = getline(strmAlignment, lineAlignment);
if (!success) {
throw "Couldn't read alignment";
}
/*
cerr << "lineTarget=" << lineTarget << endl;
cerr << "lineSource=" << lineSource << endl;
cerr << "lineAlignment=" << lineAlignment << endl;
*/
AlignedSentence *alignedSentence;
if (params.sourceSyntax || params.targetSyntax) {
alignedSentence = new AlignedSentenceSyntax(lineSource, lineTarget, lineAlignment);
}
else {
alignedSentence = new AlignedSentence(lineSource, lineTarget, lineAlignment);
}
alignedSentence->Create(params);
//cerr << alignedSentence->Debug();
Rules rules(*alignedSentence);
rules.Extend(params);
rules.Consolidate(params);
//cerr << rules.Debug();
rules.Output(extractFile, true);
rules.Output(extractInvFile, false);
delete alignedSentence;
}
if (!params.gluePath.empty()) {
Moses::OutputFileStream glueFile(params.gluePath);
CreateGlueGrammar(glueFile);
}
cerr << "Finished" << endl;
}
void CreateGlueGrammar(Moses::OutputFileStream &glueFile)
{
glueFile << "<s> [X] ||| <s> [S] ||| 1 ||| ||| 0" << endl
<< "[X][S] </s> [X] ||| [X][S] </s> [S] ||| 1 ||| 0-0 ||| 0" << endl
<< "[X][S] [X][X] [X] ||| [X][S] [X][X] [S] ||| 2.718 ||| 0-0 1-1 ||| 0" << endl;
}
<|endoftext|> |
<commit_before>#include "thruster_sim.h"
ThrusterSimNode::ThrusterSimNode(int argc, char **argv, int rate){
ros::Rate loop_rate(rate);
subscriber = n.subscribe("/qubo/thrusters_input", 1000, &ThrusterSimNode::thrusterCallBack,this);
publisher = n.advertise<std_msgs::Float64MultiArray>("/g500/thrusters_input", 1000);
};
ThrusterSimNode::~ThrusterSimNode(){};
/*Turns a R3 cartesian vector into a Float64MultiArray.*/
void ThrusterSimNode::cartesianToVelocity(double [] velocity){
double xPower = velocity[0];
double yPower = velocity[1];
double zPower = velocity[2];
publisher.publish({xPower/2,xPower/2,yPower,zPower/2,zPower/2});
}
void ThrusterSimNode::update(){
ros::spinOnce(); //the only thing we care about is depth here which updated whenever we get a depth call back, on a real node we may need to do something else.
}
void ThrusterSimNode::publish(){ //We might be able to get rid of this and always just call publisher.publish
publisher.publish(msg);
}
void ThrusterSimNode::thrusterCallBack(const std_msgs::Float64MultiArray sim_msg)
{
msg.data = sim_msg.data;
}
<commit_msg>Should properly send Float64MultiArrays<commit_after>#include "thruster_sim.h"
#include "std_msgs/Float64MultiArray.h"
ThrusterSimNode::ThrusterSimNode(int argc, char **argv, int rate){
ros::Rate loop_rate(rate);
subscriber = n.subscribe("/qubo/thrusters_input", 1000, &ThrusterSimNode::thrusterCallBack,this);
publisher = n.advertise<std_msgs::Float64MultiArray>("/g500/thrusters_input", 1000);
};
ThrusterSimNode::~ThrusterSimNode(){};
/*Turns a R3 cartesian vector into a Float64MultiArray.*/
void ThrusterSimNode::cartesianToVelocity(double [] velocity){
/*This is the data that will be contained in the velocity vector */
double xPower = velocity[0];
double yPower = velocity[1];
double zPower = velocity[2];
double data [5] = {xPower/2,xPower/2,yPower,zPower/2,zPower/2};
std_msgs::Float64MultiArray msg;
msg.dim[0].label = "thrust";
msg.dim[0].size = 5;
msg.dim[0].stride = 5;
msg.data[0] = xPower/2;
msg.data[1] = xPower/2;
msg.data[2] = yPower;
msg.data[3] = zPower/2;
msg.data[4] = zPower/2;
publisher.publish(msg);
}
void ThrusterSimNode::update(){
ros::spinOnce(); //the only thing we care about is depth here which updated whenever we get a depth call back, on a real node we may need to do something else.
}
void ThrusterSimNode::publish(){ //We might be able to get rid of this and always just call publisher.publish
publisher.publish(msg);
}
void ThrusterSimNode::thrusterCallBack(const std_msgs::Float64MultiArray sim_msg)
{
msg.data = sim_msg.data;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Satyajit Jena. *
* 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. *
**************************************************************************/
//=========================================================================//
// AliEbyE Fluctuaion Analysis for PID //
// Deepika Jena | drathee@cern.ch //
// Satyajit Jena | sjena@cern.ch //
//=========================================================================//
#include "TChain.h"
#include "TList.h"
#include "TFile.h"
#include "TTree.h"
#include "TH1D.h"
#include "TH2F.h"
#include "TH3F.h"
#include "THnSparse.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliAODEvent.h"
#include "AliStack.h"
#include "AliGenEventHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenDPMjetEventHeader.h"
#include "TDatabasePDG.h"
#include "AliEbyEPidTaskFastGen.h"
ClassImp(AliEbyEPidTaskFastGen)
//-----------------------------------------------------------------------
AliEbyEPidTaskFastGen::AliEbyEPidTaskFastGen( const char *name )
: AliAnalysisTaskSE( name ),
fThnList(0),
fVxMax(3.),
fVyMax(3.),
fVzMax(15.),
fPtLowerLimit(0.2),
fPtHigherLimit(5.),
fEtaLowerLimit(-1.),
fEtaHigherLimit(1.),
fHistoCorrelationMC(NULL)
{
DefineOutput(1, TList::Class());
}
AliEbyEPidTaskFastGen::~AliEbyEPidTaskFastGen()
{
if (fThnList) delete fThnList;
}
//---------------------------------------------------------------------------------
void AliEbyEPidTaskFastGen::UserCreateOutputObjects() {
fThnList = new TList();
fThnList->SetOwner(kTRUE);
Int_t fgSparseDataBins[kNSparseData] = {50000, 500, 10000, 10000, 5000, 5000, 1500, 1500, 500, 500, 250, 250};
Double_t fgSparseDataMin[kNSparseData] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
Double_t fgSparseDataMax[kNSparseData] = {50000., 50., 10000., 10000., 5000., 5000., 1500., 1500., 500., 500., 250., 250.};
const Char_t *fgkSparseDataTitle[] = {
"Nnumber of Partiles",
"Impact Parameters",
"N_{p}",
"N_{t}",
"N_{+}",
"N_{-}",
"N_{#pi^{+}}",
"N_{#pi^{-}}",
"N_{K^{+}}",
"N_{K^{-}}",
"N_{p}",
"N_{#bar{p}}"
};
fHistoCorrelationMC = new THnSparseI("hHistoPR", "", 12, fgSparseDataBins, fgSparseDataMin, fgSparseDataMax);
for (Int_t iaxis = 0; iaxis < kNSparseData; iaxis++)
fHistoCorrelationMC->GetAxis(iaxis)->SetTitle(fgkSparseDataTitle[iaxis]);
fThnList->Add(fHistoCorrelationMC);
PostData(1, fThnList);
}
//----------------------------------------------------------------------------------
void AliEbyEPidTaskFastGen::UserExec( Option_t * ){
AliMCEvent* mcEvent = MCEvent();
if (!mcEvent) {
Printf("ERROR: Could not retrieve MC event");
return;
}
AliStack *stack = mcEvent->Stack();
AliGenEventHeader* genHeader = mcEvent->GenEventHeader();
if(!genHeader){
printf(" Event generator header not available!!!\n");
return;
}
Double_t imp = -1;
Double_t np = -1;
Double_t nt = -1;
if(genHeader->InheritsFrom(AliGenHijingEventHeader::Class())){
imp = ((AliGenHijingEventHeader*) genHeader)->ImpactParameter();
nt = ((AliGenHijingEventHeader*) genHeader)->TargetParticipants();
np = ((AliGenHijingEventHeader*) genHeader)->ProjectileParticipants();
}
Int_t count[4][2];
for (Int_t i = 0; i < 4; i++) {
for (Int_t j = 0; j < 2; j++) count[i][j] = 0;
}
Int_t nParticles = stack->GetNtrack();
for (Int_t iParticle = 0; iParticle < nParticles; iParticle++) {
TParticle* part = stack->Particle(iParticle);
if (!part) {
Printf(" No Particle Available ");
continue;
}
// TDatabasePDG* pdgDB = TDatabasePDG::Instance();
// TParticlePDG* pdgPart = pdgDB->GetParticle(part->GetPdgCode());
Float_t pt = part->Pt();
if(pt < fPtLowerLimit || pt > fPtHigherLimit ) continue;
Float_t gEta = part->Eta();
if(gEta < fEtaLowerLimit || gEta > fEtaHigherLimit ) continue;
// Float_t gCharge = (pdgPart ? pdgPart->Charge() : 0);
Int_t pid = part->GetPdgCode();
if(pid == 211) { count[1][0]++; count[0][0]++; }
else if(pid == -211) { count[1][1]++; count[0][1]++; }
else if(pid == 321) { count[2][0]++; count[0][0]++; }
else if(pid == -321) { count[2][1]++; count[0][1]++; }
else if(pid == 2212) { count[3][0]++; count[0][0]++; }
else if(pid == -2212) { count[3][1]++; count[0][1]++; }
}
Double_t vsparseMC[kNSparseData];
vsparseMC[0] = nParticles;
vsparseMC[1] = imp;
vsparseMC[2] = np;
vsparseMC[3] = nt;
vsparseMC[4] = count[0][0];
vsparseMC[5] = count[0][1];
vsparseMC[6] = count[1][0];
vsparseMC[7] = count[1][1];
vsparseMC[8] = count[2][0];
vsparseMC[9] = count[2][1];
vsparseMC[10] = count[3][0];
vsparseMC[11] = count[3][1];
Printf(" %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f",
vsparseMC[0], vsparseMC[1], vsparseMC[2], vsparseMC[3],
vsparseMC[4], vsparseMC[5], vsparseMC[6], vsparseMC[7],
vsparseMC[8], vsparseMC[9], vsparseMC[10], vsparseMC[11]);
fHistoCorrelationMC->Fill(vsparseMC);
PostData(1, fThnList);
}
void AliEbyEPidTaskFastGen::Terminate( Option_t * ){
Info("AliEbyEHigherMomentTask"," Task Successfully finished");
}
<commit_msg>some modification to suppress text outputs (Deepika Rathee <deepika.rathee@cern.ch>)<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: Satyajit Jena. *
* 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. *
**************************************************************************/
//=========================================================================//
// AliEbyE Fluctuaion Analysis for PID //
// Deepika Jena | drathee@cern.ch //
// Satyajit Jena | sjena@cern.ch //
//=========================================================================//
#include "TChain.h"
#include "TList.h"
#include "TFile.h"
#include "TTree.h"
#include "TH1D.h"
#include "TH2F.h"
#include "TH3F.h"
#include "THnSparse.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliVEvent.h"
#include "AliESDEvent.h"
#include "AliMCEvent.h"
#include "AliAODEvent.h"
#include "AliStack.h"
#include "AliGenEventHeader.h"
#include "AliGenPythiaEventHeader.h"
#include "AliGenHijingEventHeader.h"
#include "AliGenDPMjetEventHeader.h"
#include "TDatabasePDG.h"
#include "AliEbyEPidTaskFastGen.h"
ClassImp(AliEbyEPidTaskFastGen)
//-----------------------------------------------------------------------
AliEbyEPidTaskFastGen::AliEbyEPidTaskFastGen( const char *name )
: AliAnalysisTaskSE( name ),
fThnList(0),
fVxMax(3.),
fVyMax(3.),
fVzMax(15.),
fPtLowerLimit(0.2),
fPtHigherLimit(5.),
fEtaLowerLimit(-1.),
fEtaHigherLimit(1.),
fHistoCorrelationMC(NULL)
{
DefineOutput(1, TList::Class());
}
AliEbyEPidTaskFastGen::~AliEbyEPidTaskFastGen()
{
if (fThnList) delete fThnList;
}
//---------------------------------------------------------------------------------
void AliEbyEPidTaskFastGen::UserCreateOutputObjects() {
fThnList = new TList();
fThnList->SetOwner(kTRUE);
Int_t fgSparseDataBins[kNSparseData] = {50000, 500, 10000, 10000, 5000, 5000, 1500, 1500, 500, 500, 250, 250};
Double_t fgSparseDataMin[kNSparseData] = {0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.};
Double_t fgSparseDataMax[kNSparseData] = {50000., 50., 10000., 10000., 5000., 5000., 1500., 1500., 500., 500., 250., 250.};
const Char_t *fgkSparseDataTitle[] = {
"Nnumber of Partiles",
"Impact Parameters",
"N_{p}",
"N_{t}",
"N_{+}",
"N_{-}",
"N_{#pi^{+}}",
"N_{#pi^{-}}",
"N_{K^{+}}",
"N_{K^{-}}",
"N_{p}",
"N_{#bar{p}}"
};
fHistoCorrelationMC = new THnSparseI("hHistoPR", "", 12, fgSparseDataBins, fgSparseDataMin, fgSparseDataMax);
for (Int_t iaxis = 0; iaxis < kNSparseData; iaxis++)
fHistoCorrelationMC->GetAxis(iaxis)->SetTitle(fgkSparseDataTitle[iaxis]);
fThnList->Add(fHistoCorrelationMC);
PostData(1, fThnList);
}
//----------------------------------------------------------------------------------
void AliEbyEPidTaskFastGen::UserExec( Option_t * ){
AliMCEvent* mcEvent = MCEvent();
if (!mcEvent) {
Printf("ERROR: Could not retrieve MC event");
return;
}
AliStack *stack = mcEvent->Stack();
AliGenEventHeader* genHeader = mcEvent->GenEventHeader();
if(!genHeader){
printf(" Event generator header not available!!!\n");
return;
}
Double_t imp = -1;
Double_t np = -1;
Double_t nt = -1;
if(genHeader->InheritsFrom(AliGenHijingEventHeader::Class())){
imp = ((AliGenHijingEventHeader*) genHeader)->ImpactParameter();
nt = ((AliGenHijingEventHeader*) genHeader)->TargetParticipants();
np = ((AliGenHijingEventHeader*) genHeader)->ProjectileParticipants();
}
Int_t count[4][2];
for (Int_t i = 0; i < 4; i++) {
for (Int_t j = 0; j < 2; j++) count[i][j] = 0;
}
Int_t nParticles = stack->GetNtrack();
for (Int_t iParticle = 0; iParticle < nParticles; iParticle++) {
TParticle* part = stack->Particle(iParticle);
if (!part) {
Printf(" No Particle Available ");
continue;
}
// TDatabasePDG* pdgDB = TDatabasePDG::Instance();
// TParticlePDG* pdgPart = pdgDB->GetParticle(part->GetPdgCode());
Float_t pt = part->Pt();
if(pt < fPtLowerLimit || pt > fPtHigherLimit ) continue;
Float_t gEta = part->Eta();
if(gEta < fEtaLowerLimit || gEta > fEtaHigherLimit ) continue;
// Float_t gCharge = (pdgPart ? pdgPart->Charge() : 0);
Int_t pid = part->GetPdgCode();
if(pid == 211) { count[1][0]++; count[0][0]++; }
else if(pid == -211) { count[1][1]++; count[0][1]++; }
else if(pid == 321) { count[2][0]++; count[0][0]++; }
else if(pid == -321) { count[2][1]++; count[0][1]++; }
else if(pid == 2212) { count[3][0]++; count[0][0]++; }
else if(pid == -2212) { count[3][1]++; count[0][1]++; }
}
Double_t vsparseMC[kNSparseData];
vsparseMC[0] = nParticles;
vsparseMC[1] = imp;
vsparseMC[2] = np;
vsparseMC[3] = nt;
vsparseMC[4] = count[0][0];
vsparseMC[5] = count[0][1];
vsparseMC[6] = count[1][0];
vsparseMC[7] = count[1][1];
vsparseMC[8] = count[2][0];
vsparseMC[9] = count[2][1];
vsparseMC[10] = count[3][0];
vsparseMC[11] = count[3][1];
/* Printf(" %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f %10.2f",
vsparseMC[0], vsparseMC[1], vsparseMC[2], vsparseMC[3],
vsparseMC[4], vsparseMC[5], vsparseMC[6], vsparseMC[7],
vsparseMC[8], vsparseMC[9], vsparseMC[10], vsparseMC[11]);*/
fHistoCorrelationMC->Fill(vsparseMC);
PostData(1, fThnList);
}
void AliEbyEPidTaskFastGen::Terminate( Option_t * ){
Info("AliEbyEHigherMomentTask"," Task Successfully finished");
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenVoronoi.
*
* OpenVoronoi 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.
*
* OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "common/point.hpp"
#include "common/numeric.hpp"
using namespace ovd::numeric; // sq() chop() determinant()
namespace ovd {
namespace solvers {
// this solver is called when we want to position a vertex on a SEPARATOR edge
// a SEPARATOR edge exists between a LineSite and one of its PointSite end-points
// the input sites are thus s1=LineSite and s2=PointSite (if arcs are supported in the future then s1=ArcSite is possible)
// s3 can be either a LineSite or a PointSite (of arcs are supported, s3=ArcSite is possible)
//
// s1 (LineSite) offset eq. is a1 x + b1 y + c1 + k1 t = 0 (1)
// s2 (PointSite) offset eq. is (x-x2)^2 + (y-y2)^2 = t^2 (2)
//
// Two possibilities for s3:
// s3 (LineSite) a3 x + b3 y + c3 + k3 t = 0
// s3 (PointSite) (x-x3)^2 + (y-y3)^2 = t^2
//
// This configuration constrains the solution to lie on the separator edge.
// The separator is given by
// SEP = p2 + t* sv
// where p2 is the location of s2, and the separator direction sv is
// sv = (-a1,-b1) if k1=-1
// sv = (a1,b1) if k1=-1
// thus points on the separator are located at:
//
// x_sep = x2 + t*sv.x
// y_sep = y2 + t*sv.y
//
// This can be inserted into (1) or (2) above, which leads to a linear equation in t.
//
// Insert into (1):
// a3 (x2 + t*sv.x) + b3 (y2 + t*sv.y) + c3 + k3 t = 0
// ==>
// t = -( a3*x2 + b3*y2 + c3 ) / (sv.x*a3 + sv.y*b3 + k3)
//
// Insert into (2):
// (x2 + t*sv.x-x3)^2 + (y2 + t*sv.y-y3)^2 = t^2
// ==> (using dx= x2-x3 and dy = x2-x3)
// t^2 (sv.x^2 + sv.y^1 - 1) + t (2*dx*sv.x + 2*dy*sv.y) + dx^2 + dy^2 = 0
// ==> (since sv is a unit-vector sv.x^2 + sv.y^1 - 1 = 0)
// t = - (dx^2+dy^2) / (2*(dx*sv.x + dy*sv.y))
//
// FIXME: what happens if we get a divide by zero situation ??
//
/// \brief ::SEPARATOR Solver
class SEPSolver : public Solver {
public:
int solve( Site* s1, double k1,
Site* s2, double k2,
Site* s3, double k3, std::vector<Solution>& slns ) {
// swap sites if necessary ?
if (debug)
std::cout << "SEPSolver.\n";
assert( s1->isLine() && s2->isPoint() );
// separator direction
Point sv(0,0);
if (k2 == -1) { // was k2?? but k2 is allways +1??
sv.x = s1->a(); //l1.a
sv.y = s1->b(); //l1.b
} else {
sv.x = -s1->a();
sv.y = -s1->b();
}
if (debug) std::cout << " SEPSolver sv= "<< sv << "\n";
double tsln(0);
if ( s3->isPoint() ) {
double dx = s2->x() - s3->x();
double dy = s2->y() - s3->y();
tsln = -(dx*dx+dy*dy) / (2*( dx*sv.x+dy*sv.y )); // check for divide-by-zero?
} else if (s3->isLine()) {
tsln = -(s3->a()*s2->x()+s3->b()*s2->y()+s3->c()) / ( sv.x*s3->a() + sv.y*s3->b() + k3 );
} else {
assert(0);
exit(-1);
}
Point psln = Point(s2->x(), s2->y() ) + tsln * sv;
slns.push_back( Solution( psln, tsln, k3 ) );
return 1;
}
};
} // solvers
} // ovd
<commit_msg>comment out code that coverage-testing showed was never used<commit_after>/*
* Copyright 2012 Anders Wallin (anders.e.e.wallin "at" gmail.com)
*
* This file is part of OpenVoronoi.
*
* OpenVoronoi 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.
*
* OpenVoronoi 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 OpenVoronoi. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "common/point.hpp"
#include "common/numeric.hpp"
using namespace ovd::numeric; // sq() chop() determinant()
namespace ovd {
namespace solvers {
// this solver is called when we want to position a vertex on a SEPARATOR edge
// a SEPARATOR edge exists between a LineSite and one of its PointSite end-points
// the input sites are thus s1=LineSite and s2=PointSite (if arcs are supported in the future then s1=ArcSite is possible)
// s3 can be either a LineSite or a PointSite (of arcs are supported, s3=ArcSite is possible)
//
// s1 (LineSite) offset eq. is a1 x + b1 y + c1 + k1 t = 0 (1)
// s2 (PointSite) offset eq. is (x-x2)^2 + (y-y2)^2 = t^2 (2)
//
// Two possibilities for s3:
// s3 (LineSite) a3 x + b3 y + c3 + k3 t = 0
// s3 (PointSite) (x-x3)^2 + (y-y3)^2 = t^2
//
// This configuration constrains the solution to lie on the separator edge.
// The separator is given by
// SEP = p2 + t* sv
// where p2 is the location of s2, and the separator direction sv is
// sv = (-a1,-b1) if k1=-1
// sv = (a1,b1) if k1=-1
// thus points on the separator are located at:
//
// x_sep = x2 + t*sv.x
// y_sep = y2 + t*sv.y
//
// This can be inserted into (1) or (2) above, which leads to a linear equation in t.
//
// Insert into (1):
// a3 (x2 + t*sv.x) + b3 (y2 + t*sv.y) + c3 + k3 t = 0
// ==>
// t = -( a3*x2 + b3*y2 + c3 ) / (sv.x*a3 + sv.y*b3 + k3)
//
// Insert into (2):
// (x2 + t*sv.x-x3)^2 + (y2 + t*sv.y-y3)^2 = t^2
// ==> (using dx= x2-x3 and dy = x2-x3)
// t^2 (sv.x^2 + sv.y^1 - 1) + t (2*dx*sv.x + 2*dy*sv.y) + dx^2 + dy^2 = 0
// ==> (since sv is a unit-vector sv.x^2 + sv.y^1 - 1 = 0)
// t = - (dx^2+dy^2) / (2*(dx*sv.x + dy*sv.y))
//
// FIXME: what happens if we get a divide by zero situation ??
//
/// \brief ::SEPARATOR Solver
class SEPSolver : public Solver {
public:
int solve( Site* s1, double k1,
Site* s2, double k2,
Site* s3, double k3, std::vector<Solution>& slns ) {
// swap sites if necessary ?
if (debug)
std::cout << "SEPSolver.\n";
assert( s1->isLine() && s2->isPoint() );
// separator direction
Point sv(0,0);
/* code-coverage testing shows this never happens...
if (k2 == -1) { // was k2?? but k2 is allways +1??
sv.x = s1->a(); //l1.a
sv.y = s1->b(); //l1.b
} else */
{
sv.x = -s1->a();
sv.y = -s1->b();
}
if (debug) std::cout << " SEPSolver sv= "<< sv << "\n";
double tsln(0);
/* code-coverage testing shows this never happens...
if ( s3->isPoint() ) {
double dx = s2->x() - s3->x();
double dy = s2->y() - s3->y();
tsln = -(dx*dx+dy*dy) / (2*( dx*sv.x+dy*sv.y )); // check for divide-by-zero?
} else */
if (s3->isLine()) {
tsln = -(s3->a()*s2->x()+s3->b()*s2->y()+s3->c()) / ( sv.x*s3->a() + sv.y*s3->b() + k3 );
} else {
assert(0);
exit(-1);
}
Point psln = Point(s2->x(), s2->y() ) + tsln * sv;
slns.push_back( Solution( psln, tsln, k3 ) );
return 1;
}
};
} // solvers
} // ovd
<|endoftext|> |
<commit_before>/* -*- Mode: C++; c-file-style: "gnu" -*- */
/*
* Copyright 2014 Waseda University, Sato Laboratory
* Author: Jairo Eduardo Lopez <jairo@ruri.waseda.jp>
*
* nnn-nullp.cc is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nnn-nullp.cc 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with nnn-nullp.cc. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <ns3-dev/ns3/log.h>
#include <ns3-dev/ns3/unused.h>
#include <ns3-dev/ns3/packet.h>
#include "nnn-nullp.h"
NS_LOG_COMPONENT_DEFINE ("nnn.NULLp");
namespace ns3 {
namespace nnn {
NULLp::NULLp ()
: m_packetid (0)
, m_ttl (Seconds (0))
, m_length (0)
, m_payload (Create<Packet> ())
, m_wire (0)
{
}
NULLp::NULLp (Ptr<Packet> payload)
: m_packetid (0)
, m_ttl (Seconds (1))
, m_wire (0)
{
if (m_payload == 0)
{
m_payload = Create<Packet> ();
m_length = 0;
} else
{
m_payload = payload;
m_length = m_payload->GetSize();
}
}
NULLp::NULLp (const NULLp &nullp)
: m_packetid (0)
, m_ttl (nullp.m_ttl)
, m_payload (nullp.GetPayload ()->Copy ())
, m_length (nullp.m_length)
, m_wire (0)
{
NS_LOG_FUNCTION("NULLp correct copy constructor");
}
void
NULLp::SetLifetime (Time ttl)
{
m_ttl = ttl;
m_wire = 0;
}
Time
NULLp::GetLifetime () const
{
return m_ttl;
}
void
NULLp::SetLength (uint32_t len)
{
m_length = len;
}
uint32_t
NULLp::GetLength () const
{
return m_length;
}
void
NULLp::SetPayload (Ptr<Packet> payload)
{
m_payload = payload;
m_wire = 0;
}
Ptr<const Packet>
NULLp::GetPayload () const
{
return m_payload;
}
void
NULLp::Print (std::ostream &os) const
{
os << "<NULLp>\n";
os << " <TTL>" << GetLifetime () << "</TTL>\n";
os << " <Length>" << GetLength () << "</Length>\n";
if (m_payload != 0)
{
os << " <Payload>Yes</Payload>\n";
} else
{
os << " <Payload>No</Payload>\n";
}
os << "</NULLp>";
}
} // namespace nnn
} // namespace ns3
<commit_msg>NULL packet implementation changing constructors<commit_after>/* -*- Mode: C++; c-file-style: "gnu" -*- */
/*
* Copyright 2014 Waseda University, Sato Laboratory
* Author: Jairo Eduardo Lopez <jairo@ruri.waseda.jp>
*
* nnn-nullp.cc is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* nnn-nullp.cc 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 Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with nnn-nullp.cc. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <ns3-dev/ns3/log.h>
#include <ns3-dev/ns3/unused.h>
#include <ns3-dev/ns3/packet.h>
#include "nnn-nullp.h"
NS_LOG_COMPONENT_DEFINE ("nnn.NULLp");
namespace ns3 {
namespace nnn {
NULLp::NULLp ()
: m_packetid (0)
, m_ttl (Seconds (0))
, m_length (0)
, m_payload (Create<Packet> ())
, m_wire (0)
{
}
NULLp::NULLp (Ptr<Packet> payload)
: m_packetid (0)
, m_ttl (Seconds (1))
, m_wire (0)
{
if (m_payload == 0)
{
m_payload = Create<Packet> ();
m_length = 0;
} else
{
m_payload = payload;
m_length = m_payload->GetSize();
}
}
NULLp::NULLp (const NULLp &nullp)
: m_packetid (0)
, m_ttl (nullp.m_ttl)
, m_length (nullp.m_length)
, m_payload (nullp.GetPayload ()->Copy ())
, m_wire (0)
{
NS_LOG_FUNCTION("NULLp correct copy constructor");
}
void
NULLp::SetLifetime (Time ttl)
{
m_ttl = ttl;
m_wire = 0;
}
Time
NULLp::GetLifetime () const
{
return m_ttl;
}
void
NULLp::SetLength (uint32_t len)
{
m_length = len;
}
uint32_t
NULLp::GetLength () const
{
return m_length;
}
void
NULLp::SetPayload (Ptr<Packet> payload)
{
m_payload = payload;
m_wire = 0;
}
Ptr<const Packet>
NULLp::GetPayload () const
{
return m_payload;
}
void
NULLp::Print (std::ostream &os) const
{
os << "<NULLp>\n";
os << " <TTL>" << GetLifetime () << "</TTL>\n";
os << " <Length>" << GetLength () << "</Length>\n";
if (m_payload != 0)
{
os << " <Payload>Yes</Payload>\n";
} else
{
os << " <Payload>No</Payload>\n";
}
os << "</NULLp>";
}
} // namespace nnn
} // namespace ns3
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <lua.hpp>
#include <fblualib/LuaUtils.h>
#include "Encoding.h"
#include "Serialization.h"
#include <folly/io/Compression.h>
using namespace fblualib;
using namespace fblualib::thrift;
using folly::io::CodecType;
namespace {
struct CodecInfo {
const char* name;
CodecType type;
};
CodecInfo gCodecs[] = {
{"NONE", CodecType::NO_COMPRESSION},
{"LZ4", CodecType::LZ4},
{"SNAPPY", CodecType::SNAPPY},
{"ZLIB", CodecType::ZLIB},
{"LZMA2", CodecType::LZMA2},
};
constexpr size_t kCodecCount = sizeof(gCodecs) / sizeof(gCodecs[0]);
LuaVersionInfo getVersion(lua_State* L) {
int origTop = lua_gettop(L);
lua_getglobal(L, "jit");
if (lua_isnil(L, -1)) {
luaL_error(L, "Cannot find global \"jit\", cannot determine version");
}
int jitIdx = lua_gettop(L);
// Just to make sure, look at jit.version, see if it starts with LuaJIT
lua_getfield(L, jitIdx, "version");
auto ver = luaGetStringChecked(L, -1);
if (!ver.startsWith("LuaJIT")) {
luaL_error(L, "Invalid jit.version, expecting LuaJIT: %*s",
ver.size(), ver.data());
}
LuaVersionInfo info;
info.interpreterVersion = ver.str();
// LuaJIT bytecode is compatible between the same <major>.<minor>
// version_num is <major> * 10000 + <minor> * 100 + <patchlevel>
lua_getfield(L, jitIdx, "version_num");
long verNum = lua_tointeger(L, -1);
if (verNum < 2 * 100 * 100) {
luaL_error(L, "Invalid LuaJIT version, expected >= 20000: %ld", verNum);
}
info.bytecodeVersion = folly::sformat("LuaJIT:{:04d}", verNum / 100);
lua_settop(L, origTop);
return info;
}
int serializeToString(lua_State* L) {
auto codecType =
(lua_type(L, 2) != LUA_TNIL && lua_type(L, 2) != LUA_TNONE ?
static_cast<CodecType>(luaL_checkinteger(L, 2)) :
CodecType::NO_COMPRESSION);
auto luaChunkSize = luaGetNumber<uint64_t>(L, 3);
uint64_t chunkSize =
luaChunkSize ? *luaChunkSize : std::numeric_limits<uint64_t>::max();
Serializer serializer;
auto obj = serializer.toThrift(L, 1);
StringWriter writer;
encode(obj, codecType, getVersion(L), writer, kAnyVersion, chunkSize);
auto str = folly::StringPiece(writer.finish());
lua_pushlstring(L, str.data(), str.size());
return 1;
}
// LuaJIT allows conversion from Lua files and FILE*, but only through FFI,
// which is incompatible with the standard Lua/C API. So, in Lua code,
// we encode the pointer as a Lua string and pass it down here.
FILE* getFP(lua_State* L, int index) {
// Black magic. Don't look.
auto filePtrData = luaGetStringChecked(L, index, true /*strict*/);
luaL_argcheck(L,
filePtrData.size() == sizeof(void*),
index,
"expected FILE* encoded as string");
FILE* fp = nullptr;
memcpy(&fp, filePtrData.data(), sizeof(void*));
return fp;
}
int serializeToFile(lua_State* L) {
auto codecType =
(lua_type(L, 3) != LUA_TNIL && lua_type(L, 3) != LUA_TNONE ?
static_cast<CodecType>(luaL_checkinteger(L, 3)) :
CodecType::NO_COMPRESSION);
auto luaChunkSize = luaGetNumber<uint64_t>(L, 3);
uint64_t chunkSize =
luaChunkSize ? *luaChunkSize : std::numeric_limits<uint64_t>::max();
auto fp = getFP(L, 2);
Serializer serializer;
auto obj = serializer.toThrift(L, 1);
FILEWriter writer(fp);
encode(obj, codecType, getVersion(L), writer, kAnyVersion, chunkSize);
return 0;
}
int doDeserialize(lua_State* L, DecodedObject&& decodedObject) {
auto version = getVersion(L);
unsigned int options = 0;
// Check for bytecode version compatibility
auto& decodedBytecodeVersion = decodedObject.luaVersionInfo.bytecodeVersion;
if (decodedBytecodeVersion.empty() ||
decodedBytecodeVersion != version.bytecodeVersion) {
options |= Deserializer::NO_BYTECODE;
}
return Deserializer(options).fromThrift(L, decodedObject.output);
}
int deserializeFromString(lua_State* L) {
folly::ByteRange br(luaGetStringChecked(L, 1));
StringReader reader(&br);
return doDeserialize(L, decode(reader));
}
int deserializeFromFile(lua_State* L) {
auto fp = getFP(L, 1);
FILEReader reader(fp);
return doDeserialize(L, decode(reader));
}
int setCallbacks(lua_State* L) {
// Set serialization and deserialization callbacks for special objects
luaL_checktype(L, 1, LUA_TFUNCTION);
luaL_checktype(L, 2, LUA_TFUNCTION);
setSpecialSerializationCallback(L, 1);
setSpecialDeserializationCallback(L, 2);
return 0;
}
const struct luaL_reg gFuncs[] = {
{"to_string", serializeToString},
{"_to_file", serializeToFile},
{"from_string", deserializeFromString},
{"_from_file", deserializeFromFile},
{"_set_callbacks", setCallbacks},
{nullptr, nullptr}, // sentinel
};
} // namespace
extern "C" int LUAOPEN(lua_State* L) {
lua_newtable(L);
luaL_register(L, nullptr, gFuncs);
// Create "codec" table
lua_newtable(L);
for (size_t i = 0; i < kCodecCount; ++i) {
auto codecType = gCodecs[i].type;
try {
auto codec = folly::io::getCodec(codecType);
} catch (const std::invalid_argument& e) {
continue;
}
lua_pushinteger(L, static_cast<int>(codecType));
lua_setfield(L, -2, gCodecs[i].name);
}
lua_setfield(L, -2, "codec");
return 1;
}
<commit_msg>facepalm: fix bug in thrift.to_file<commit_after>/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <lua.hpp>
#include <fblualib/LuaUtils.h>
#include "Encoding.h"
#include "Serialization.h"
#include <folly/io/Compression.h>
using namespace fblualib;
using namespace fblualib::thrift;
using folly::io::CodecType;
namespace {
struct CodecInfo {
const char* name;
CodecType type;
};
CodecInfo gCodecs[] = {
{"NONE", CodecType::NO_COMPRESSION},
{"LZ4", CodecType::LZ4},
{"SNAPPY", CodecType::SNAPPY},
{"ZLIB", CodecType::ZLIB},
{"LZMA2", CodecType::LZMA2},
};
constexpr size_t kCodecCount = sizeof(gCodecs) / sizeof(gCodecs[0]);
LuaVersionInfo getVersion(lua_State* L) {
int origTop = lua_gettop(L);
lua_getglobal(L, "jit");
if (lua_isnil(L, -1)) {
luaL_error(L, "Cannot find global \"jit\", cannot determine version");
}
int jitIdx = lua_gettop(L);
// Just to make sure, look at jit.version, see if it starts with LuaJIT
lua_getfield(L, jitIdx, "version");
auto ver = luaGetStringChecked(L, -1);
if (!ver.startsWith("LuaJIT")) {
luaL_error(L, "Invalid jit.version, expecting LuaJIT: %*s",
ver.size(), ver.data());
}
LuaVersionInfo info;
info.interpreterVersion = ver.str();
// LuaJIT bytecode is compatible between the same <major>.<minor>
// version_num is <major> * 10000 + <minor> * 100 + <patchlevel>
lua_getfield(L, jitIdx, "version_num");
long verNum = lua_tointeger(L, -1);
if (verNum < 2 * 100 * 100) {
luaL_error(L, "Invalid LuaJIT version, expected >= 20000: %ld", verNum);
}
info.bytecodeVersion = folly::sformat("LuaJIT:{:04d}", verNum / 100);
lua_settop(L, origTop);
return info;
}
int serializeToString(lua_State* L) {
auto codecType =
(lua_type(L, 2) != LUA_TNIL && lua_type(L, 2) != LUA_TNONE ?
static_cast<CodecType>(luaL_checkinteger(L, 2)) :
CodecType::NO_COMPRESSION);
auto luaChunkSize = luaGetNumber<uint64_t>(L, 3);
uint64_t chunkSize =
luaChunkSize ? *luaChunkSize : std::numeric_limits<uint64_t>::max();
Serializer serializer;
auto obj = serializer.toThrift(L, 1);
StringWriter writer;
encode(obj, codecType, getVersion(L), writer, kAnyVersion, chunkSize);
auto str = folly::StringPiece(writer.finish());
lua_pushlstring(L, str.data(), str.size());
return 1;
}
// LuaJIT allows conversion from Lua files and FILE*, but only through FFI,
// which is incompatible with the standard Lua/C API. So, in Lua code,
// we encode the pointer as a Lua string and pass it down here.
FILE* getFP(lua_State* L, int index) {
// Black magic. Don't look.
auto filePtrData = luaGetStringChecked(L, index, true /*strict*/);
luaL_argcheck(L,
filePtrData.size() == sizeof(void*),
index,
"expected FILE* encoded as string");
FILE* fp = nullptr;
memcpy(&fp, filePtrData.data(), sizeof(void*));
return fp;
}
int serializeToFile(lua_State* L) {
auto codecType =
(lua_type(L, 3) != LUA_TNIL && lua_type(L, 3) != LUA_TNONE ?
static_cast<CodecType>(luaL_checkinteger(L, 3)) :
CodecType::NO_COMPRESSION);
auto luaChunkSize = luaGetNumber<uint64_t>(L, 4);
uint64_t chunkSize =
luaChunkSize ? *luaChunkSize : std::numeric_limits<uint64_t>::max();
auto fp = getFP(L, 2);
Serializer serializer;
auto obj = serializer.toThrift(L, 1);
FILEWriter writer(fp);
encode(obj, codecType, getVersion(L), writer, kAnyVersion, chunkSize);
return 0;
}
int doDeserialize(lua_State* L, DecodedObject&& decodedObject) {
auto version = getVersion(L);
unsigned int options = 0;
// Check for bytecode version compatibility
auto& decodedBytecodeVersion = decodedObject.luaVersionInfo.bytecodeVersion;
if (decodedBytecodeVersion.empty() ||
decodedBytecodeVersion != version.bytecodeVersion) {
options |= Deserializer::NO_BYTECODE;
}
return Deserializer(options).fromThrift(L, decodedObject.output);
}
int deserializeFromString(lua_State* L) {
folly::ByteRange br(luaGetStringChecked(L, 1));
StringReader reader(&br);
return doDeserialize(L, decode(reader));
}
int deserializeFromFile(lua_State* L) {
auto fp = getFP(L, 1);
FILEReader reader(fp);
return doDeserialize(L, decode(reader));
}
int setCallbacks(lua_State* L) {
// Set serialization and deserialization callbacks for special objects
luaL_checktype(L, 1, LUA_TFUNCTION);
luaL_checktype(L, 2, LUA_TFUNCTION);
setSpecialSerializationCallback(L, 1);
setSpecialDeserializationCallback(L, 2);
return 0;
}
const struct luaL_reg gFuncs[] = {
{"to_string", serializeToString},
{"_to_file", serializeToFile},
{"from_string", deserializeFromString},
{"_from_file", deserializeFromFile},
{"_set_callbacks", setCallbacks},
{nullptr, nullptr}, // sentinel
};
} // namespace
extern "C" int LUAOPEN(lua_State* L) {
lua_newtable(L);
luaL_register(L, nullptr, gFuncs);
// Create "codec" table
lua_newtable(L);
for (size_t i = 0; i < kCodecCount; ++i) {
auto codecType = gCodecs[i].type;
try {
auto codec = folly::io::getCodec(codecType);
} catch (const std::invalid_argument& e) {
continue;
}
lua_pushinteger(L, static_cast<int>(codecType));
lua_setfield(L, -2, gCodecs[i].name);
}
lua_setfield(L, -2, "codec");
return 1;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "gflags/gflags.h"
#include "paddle/contrib/inference/paddle_inference_api_impl.h"
#include "paddle/fluid/inference/tests/test_helper.h"
DEFINE_string(dirname, "", "Directory of the inference model.");
namespace paddle {
PaddleTensor LodTensorToPaddleTensor(framework::LoDTensor* t) {
PaddleTensor pt;
pt.data.data = t->data<void>();
if (t->type() == typeid(int64_t)) {
pt.data.length = t->numel() * sizeof(int64_t);
pt.dtype = PaddleDType::INT64;
} else if (t->type() == typeid(float)) {
pt.data.length = t->numel() * sizeof(float);
pt.dtype = PaddleDType::FLOAT32;
} else {
LOG(FATAL) << "unsupported type.";
}
pt.shape = framework::vectorize2int(t->dims());
return pt;
}
ConfigImpl GetConfig() {
ConfigImpl config;
config.model_dir = FLAGS_dirname + "word2vec.inference.model";
LOG(INFO) << "dirname " << config.model_dir;
config.fraction_of_gpu_memory = 0.15;
config.device = 0;
config.share_variables = true;
return config;
}
TEST(paddle_inference_api_impl, word2vec) {
ConfigImpl config = GetConfig();
std::unique_ptr<PaddlePredictor> predictor = CreatePaddlePredictor(config);
framework::LoDTensor first_word, second_word, third_word, fourth_word;
framework::LoD lod{{0, 1}};
int64_t dict_size = 2073; // The size of dictionary
SetupLoDTensor(&first_word, lod, static_cast<int64_t>(0), dict_size - 1);
SetupLoDTensor(&second_word, lod, static_cast<int64_t>(0), dict_size - 1);
SetupLoDTensor(&third_word, lod, static_cast<int64_t>(0), dict_size - 1);
SetupLoDTensor(&fourth_word, lod, static_cast<int64_t>(0), dict_size - 1);
std::vector<PaddleTensor> paddle_tensor_feeds;
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&first_word));
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&second_word));
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&third_word));
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&fourth_word));
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));
ASSERT_EQ(outputs.size(), 1UL);
size_t len = outputs[0].data.length;
float* data = static_cast<float*>(outputs[0].data.data);
for (int j = 0; j < len / sizeof(float); ++j) {
ASSERT_LT(data[j], 1.0);
ASSERT_GT(data[j], -1.0);
}
std::vector<paddle::framework::LoDTensor*> cpu_feeds;
cpu_feeds.push_back(&first_word);
cpu_feeds.push_back(&second_word);
cpu_feeds.push_back(&third_word);
cpu_feeds.push_back(&fourth_word);
framework::LoDTensor output1;
std::vector<paddle::framework::LoDTensor*> cpu_fetchs1;
cpu_fetchs1.push_back(&output1);
TestInference<platform::CPUPlace>(config.model_dir, cpu_feeds, cpu_fetchs1);
float* lod_data = output1.data<float>();
for (size_t i = 0; i < output1.numel(); ++i) {
EXPECT_LT(lod_data[i] - data[i], 1e-3);
EXPECT_GT(lod_data[i] - data[i], -1e-3);
}
free(outputs[0].data.data);
}
TEST(paddle_inference_api_impl, image_classification) {
int batch_size = 2;
bool use_mkldnn = false;
bool repeat = false;
ConfigImpl config = GetConfig();
config.model_dir =
FLAGS_dirname + "image_classification_resnet.inference.model";
const bool is_combined = false;
std::vector<std::vector<int64_t>> feed_target_shapes =
GetFeedTargetShapes(config.model_dir, is_combined);
framework::LoDTensor input;
// Use normilized image pixels as input data,
// which should be in the range [0.0, 1.0].
feed_target_shapes[0][0] = batch_size;
framework::DDim input_dims = framework::make_ddim(feed_target_shapes[0]);
SetupTensor<float>(
&input, input_dims, static_cast<float>(0), static_cast<float>(1));
std::vector<framework::LoDTensor*> cpu_feeds;
cpu_feeds.push_back(&input);
framework::LoDTensor output1;
std::vector<framework::LoDTensor*> cpu_fetchs1;
cpu_fetchs1.push_back(&output1);
TestInference<platform::CPUPlace, false, true>(config.model_dir,
cpu_feeds,
cpu_fetchs1,
repeat,
is_combined,
use_mkldnn);
std::unique_ptr<PaddlePredictor> predictor = CreatePaddlePredictor(config);
std::vector<PaddleTensor> paddle_tensor_feeds;
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&input));
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));
ASSERT_EQ(outputs.size(), 1UL);
size_t len = outputs[0].data.length;
float* data = static_cast<float*>(outputs[0].data.data);
float* lod_data = output1.data<float>();
for (size_t j = 0; j < len / sizeof(float); ++j) {
EXPECT_NEAR(lod_data[j], data[j], 1e-6);
}
free(data);
}
} // namespace paddle
<commit_msg>clean<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <glog/logging.h>
#include <gtest/gtest.h>
#include "gflags/gflags.h"
#include "paddle/contrib/inference/paddle_inference_api_impl.h"
#include "paddle/fluid/inference/tests/test_helper.h"
DEFINE_string(dirname, "", "Directory of the inference model.");
namespace paddle {
PaddleTensor LodTensorToPaddleTensor(framework::LoDTensor* t) {
PaddleTensor pt;
pt.data.data = t->data<void>();
if (t->type() == typeid(int64_t)) {
pt.data.length = t->numel() * sizeof(int64_t);
pt.dtype = PaddleDType::INT64;
} else if (t->type() == typeid(float)) {
pt.data.length = t->numel() * sizeof(float);
pt.dtype = PaddleDType::FLOAT32;
} else {
LOG(FATAL) << "unsupported type.";
}
pt.shape = framework::vectorize2int(t->dims());
return pt;
}
ConfigImpl GetConfig() {
ConfigImpl config;
config.model_dir = FLAGS_dirname + "word2vec.inference.model";
LOG(INFO) << "dirname " << config.model_dir;
config.fraction_of_gpu_memory = 0.15;
config.device = 0;
config.share_variables = true;
return config;
}
TEST(paddle_inference_api_impl, word2vec) {
ConfigImpl config = GetConfig();
std::unique_ptr<PaddlePredictor> predictor = CreatePaddlePredictor(config);
framework::LoDTensor first_word, second_word, third_word, fourth_word;
framework::LoD lod{{0, 1}};
int64_t dict_size = 2073; // The size of dictionary
SetupLoDTensor(&first_word, lod, static_cast<int64_t>(0), dict_size - 1);
SetupLoDTensor(&second_word, lod, static_cast<int64_t>(0), dict_size - 1);
SetupLoDTensor(&third_word, lod, static_cast<int64_t>(0), dict_size - 1);
SetupLoDTensor(&fourth_word, lod, static_cast<int64_t>(0), dict_size - 1);
std::vector<PaddleTensor> paddle_tensor_feeds;
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&first_word));
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&second_word));
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&third_word));
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&fourth_word));
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));
ASSERT_EQ(outputs.size(), 1UL);
size_t len = outputs[0].data.length;
float* data = static_cast<float*>(outputs[0].data.data);
for (int j = 0; j < len / sizeof(float); ++j) {
ASSERT_LT(data[j], 1.0);
ASSERT_GT(data[j], -1.0);
}
std::vector<paddle::framework::LoDTensor*> cpu_feeds;
cpu_feeds.push_back(&first_word);
cpu_feeds.push_back(&second_word);
cpu_feeds.push_back(&third_word);
cpu_feeds.push_back(&fourth_word);
framework::LoDTensor output1;
std::vector<paddle::framework::LoDTensor*> cpu_fetchs1;
cpu_fetchs1.push_back(&output1);
TestInference<platform::CPUPlace>(config.model_dir, cpu_feeds, cpu_fetchs1);
float* lod_data = output1.data<float>();
for (size_t i = 0; i < output1.numel(); ++i) {
EXPECT_LT(lod_data[i] - data[i], 1e-3);
EXPECT_GT(lod_data[i] - data[i], -1e-3);
}
free(outputs[0].data.data);
}
TEST(paddle_inference_api_impl, image_classification) {
int batch_size = 2;
bool use_mkldnn = false;
bool repeat = false;
ConfigImpl config = GetConfig();
config.model_dir =
FLAGS_dirname + "image_classification_resnet.inference.model";
const bool is_combined = false;
std::vector<std::vector<int64_t>> feed_target_shapes =
GetFeedTargetShapes(config.model_dir, is_combined);
framework::LoDTensor input;
// Use normilized image pixels as input data,
// which should be in the range [0.0, 1.0].
feed_target_shapes[0][0] = batch_size;
framework::DDim input_dims = framework::make_ddim(feed_target_shapes[0]);
SetupTensor<float>(
&input, input_dims, static_cast<float>(0), static_cast<float>(1));
std::vector<framework::LoDTensor*> cpu_feeds;
cpu_feeds.push_back(&input);
framework::LoDTensor output1;
std::vector<framework::LoDTensor*> cpu_fetchs1;
cpu_fetchs1.push_back(&output1);
TestInference<platform::CPUPlace, false, true>(config.model_dir,
cpu_feeds,
cpu_fetchs1,
repeat,
is_combined,
use_mkldnn);
std::unique_ptr<PaddlePredictor> predictor = CreatePaddlePredictor(config);
std::vector<PaddleTensor> paddle_tensor_feeds;
paddle_tensor_feeds.push_back(LodTensorToPaddleTensor(&input));
std::vector<PaddleTensor> outputs;
ASSERT_TRUE(predictor->Run(paddle_tensor_feeds, &outputs));
ASSERT_EQ(outputs.size(), 1UL);
size_t len = outputs[0].data.length;
float* data = static_cast<float*>(outputs[0].data.data);
float* lod_data = output1.data<float>();
for (size_t j = 0; j < len / sizeof(float); ++j) {
EXPECT_NEAR(lod_data[j], data[j], 1e-3);
}
free(data);
}
} // namespace paddle
<|endoftext|> |
<commit_before>#ifndef STAN_VARIATIONAL_ADVI_HPP
#define STAN_VARIATIONAL_ADVI_HPP
#include <stan/math.hpp>
#include <stan/io/dump.hpp>
#include <stan/model/util.hpp>
#include <stan/services/io/write_iteration_csv.hpp>
#include <stan/services/io/write_iteration.hpp>
#include <stan/services/error_codes.hpp>
#include <stan/variational/families/normal_fullrank.hpp>
#include <stan/variational/families/normal_meanfield.hpp>
#include <boost/circular_buffer.hpp>
#include <algorithm>
#include <limits>
#include <numeric>
#include <ostream>
#include <vector>
namespace stan {
namespace variational {
/**
* AUTOMATIC DIFFERENTIATION VARIATIONAL INFERENCE
*
* Runs "black box" variational inference by applying stochastic gradient
* ascent in order to maximize the Evidence Lower Bound for a given model
* and variational family.
*
* @tparam M class of model
* @tparam Q class of variational distribution
* @tparam BaseRNG class of random number generator
* @param m stan model
* @param cont_params initialization of continuous parameters
* @param n_monte_carlo_grad number of samples for gradient computation
* @param n_monte_carlo_elbo number of samples for ELBO computation
* @param eta_adagrad eta parameter for adaGrad
* @param rng random number generator
* @param eval_elbo evaluate ELBO at every "eval_elbo" iters
* @param n_posterior_samples number of samples to draw from posterior
* @param print_stream stream for convergence assessment output
* @param output_stream stream for parameters output
* @param diagnostic_stream stream for ELBO output
*/
template <class M, class Q, class BaseRNG>
class advi {
public:
advi(M& m,
Eigen::VectorXd& cont_params,
int n_monte_carlo_grad,
int n_monte_carlo_elbo,
double eta_adagrad,
BaseRNG& rng,
int eval_elbo,
int n_posterior_samples,
std::ostream* print_stream,
std::ostream* output_stream,
std::ostream* diagnostic_stream) :
model_(m),
cont_params_(cont_params),
rng_(rng),
n_monte_carlo_grad_(n_monte_carlo_grad),
n_monte_carlo_elbo_(n_monte_carlo_elbo),
eta_adagrad_(eta_adagrad),
eval_elbo_(eval_elbo),
n_posterior_samples_(n_posterior_samples),
print_stream_(print_stream),
out_stream_(output_stream),
diag_stream_(diagnostic_stream) {
static const char* function = "stan::variational::advi";
stan::math::check_positive(function,
"Number of Monte Carlo samples for gradients",
n_monte_carlo_grad_);
stan::math::check_positive(function,
"Number of Monte Carlo samples for ELBO",
n_monte_carlo_elbo_);
stan::math::check_positive(function,
"Number of posterior samples for output",
n_posterior_samples_);
stan::math::check_positive(function, "Eta stepsize", eta_adagrad_);
}
/**
* Calculates the Evidence Lower BOund (ELBO) by sampling from
* the variational distribution and then evaluating the log joint,
* adjusted by the entropy term of the variational distribution.
*
* @tparam Q class of variational distribution
* @return evidence lower bound (elbo)
*/
double calc_ELBO(const Q& variational) const {
static const char* function =
"stan::variational::advi::calc_ELBO";
double elbo = 0.0;
int dim = variational.dimension();
Eigen::VectorXd zeta(dim);
int i = 0;
int n_monte_carlo_drop = 0;
while (i < n_monte_carlo_elbo_) {
variational.sample(rng_, zeta);
try {
double energy_i = model_.template log_prob<false, true>(zeta,
print_stream_);
stan::math::check_finite(function, "energy_i", energy_i);
elbo += energy_i;
i += 1;
} catch (std::exception& e) {
this->write_error_msg_(print_stream_, e);
n_monte_carlo_drop += 1;
if (n_monte_carlo_drop >= n_monte_carlo_elbo_) {
const char* name = "The number of dropped evaluations";
const char* msg1 = "has reached its maximum amount (";
int y = n_monte_carlo_elbo_;
const char* msg2 = "). Your model may be either severely "
"ill-conditioned or misspecified.";
stan::math::domain_error(function, name, y, msg1, msg2);
}
}
}
// Divide to get Monte Carlo integral estimate
elbo /= n_monte_carlo_elbo_;
elbo += variational.entropy();
return elbo;
}
/**
* Calculates the "black box" gradient of the ELBO.
*
* @param variational variational distribution
* @param elbo_grad gradient of ELBO with respect to variational parameters
*/
void calc_ELBO_grad(const Q& variational, Q& elbo_grad) const {
static const char* function =
"stan::variational::advi::calc_ELBO_grad";
stan::math::check_size_match(function,
"Dimension of elbo_grad", elbo_grad.dimension(),
"Dimension of variational q", variational.dimension());
stan::math::check_size_match(function,
"Dimension of variational q", variational.dimension(),
"Dimension of variables in model", cont_params_.size());
variational.calc_grad(elbo_grad,
model_, cont_params_, n_monte_carlo_grad_, rng_,
print_stream_);
}
/**
* Runs stochastic gradient ascent with Adagrad.
*
* @param variational variational distribution
* @param tol_rel_obj relative tolerance parameter for convergence
* @param max_iterations max number of iterations to run algorithm
*/
void robbins_monro_adagrad(Q& variational,
double tol_rel_obj,
int max_iterations) const {
static const char* function =
"stan::variational::advi.robbins_monro_adagrad";
stan::math::check_positive(function,
"Relative objective function tolerance",
tol_rel_obj);
stan::math::check_positive(function,
"Maximum iterations",
max_iterations);
// Gradient parameters
Q elbo_grad = Q(model_.num_params_r());
// Adagrad parameters
double tau = 1.0;
Q params_adagrad = Q(model_.num_params_r());
// RMSprop window_size
double window_size = 10.0;
double post_factor = 1.0 / window_size;
double pre_factor = 1.0 - post_factor;
// Initialize ELBO and convergence tracking variables
double elbo(0.0);
double elbo_prev = std::numeric_limits<double>::min();
double delta_elbo = std::numeric_limits<double>::max();
double delta_elbo_ave = std::numeric_limits<double>::max();
double delta_elbo_med = std::numeric_limits<double>::max();
// Heuristic to estimate how far to look back in rolling window
int cb_size = static_cast<int>(
std::max(0.1*max_iterations/static_cast<double>(eval_elbo_),
1.0));
boost::circular_buffer<double> cb(cb_size);
// Print stuff
if (print_stream_) {
*print_stream_ << " iter"
<< " ELBO"
<< " delta_ELBO_mean"
<< " delta_ELBO_med"
<< " notes "
<< std::endl;
}
// Timing variables
clock_t start = clock();
clock_t end;
double delta_t;
// Main loop
std::vector<double> print_vector;
bool do_more_iterations = true;
int iter_counter = 0;
while (do_more_iterations) {
// Compute gradient using Monte Carlo integration
calc_ELBO_grad(variational, elbo_grad);
// RMSprop moving average weighting
if (iter_counter == 0) {
params_adagrad += elbo_grad.square();
} else {
params_adagrad = pre_factor * params_adagrad +
post_factor * elbo_grad.square();
}
// Stochastic gradient update
variational += eta_adagrad_ * elbo_grad /
(tau + params_adagrad.sqrt());
// Check for convergence every "eval_elbo_"th iteration
if (iter_counter % eval_elbo_ == 0) {
elbo_prev = elbo;
elbo = calc_ELBO(variational);
delta_elbo = rel_decrease(elbo, elbo_prev);
cb.push_back(delta_elbo);
delta_elbo_ave = std::accumulate(cb.begin(), cb.end(), 0.0)
/ static_cast<double>(cb.size());
delta_elbo_med = circ_buff_median(cb);
if (print_stream_) {
*print_stream_
<< " "
<< std::setw(4) << iter_counter
<< " "
<< std::right << std::setw(9) << std::setprecision(1)
<< elbo
<< " "
<< std::setw(16) << std::fixed << std::setprecision(3)
<< delta_elbo_ave
<< " "
<< std::setw(15) << std::fixed << std::setprecision(3)
<< delta_elbo_med;
}
if (diag_stream_) {
end = clock();
delta_t = static_cast<double>(end - start) / CLOCKS_PER_SEC;
print_vector.clear();
print_vector.push_back(delta_t);
print_vector.push_back(elbo);
services::io::write_iteration_csv(*diag_stream_,
iter_counter, print_vector);
}
if (delta_elbo_ave < tol_rel_obj) {
if (print_stream_)
*print_stream_ << " MEAN ELBO CONVERGED";
do_more_iterations = false;
}
if (delta_elbo_med < tol_rel_obj) {
if (print_stream_)
*print_stream_ << " MEDIAN ELBO CONVERGED";
do_more_iterations = false;
}
if (iter_counter > 100) {
if (delta_elbo_med > 0.5 || delta_elbo_ave > 0.5) {
if (print_stream_)
*print_stream_ << " MAY BE DIVERGING... INSPECT ELBO";
}
}
if (print_stream_)
*print_stream_ << std::endl;
}
// Check for max iterations
if (iter_counter == max_iterations) {
if (print_stream_)
*print_stream_ << "MAX ITERATIONS REACHED" << std::endl;
do_more_iterations = false;
}
++iter_counter;
}
}
/**
* Runs the algorithm and writes to output.
*
* @param tol_rel_obj relative tolerance parameter for convergence
* @param max_iterations max number of iterations to run algorithm
*/
int run(double tol_rel_obj, int max_iterations) const {
if (diag_stream_) {
*diag_stream_ << "iter,time_in_seconds,ELBO" << std::endl;
}
// initialize variational approximation
Q variational = Q(cont_params_);
// run inference algorithm
robbins_monro_adagrad(variational, tol_rel_obj, max_iterations);
// get mean of posterior approximation and write on first output line
cont_params_ = variational.mean();
// This is temporary as lp is not really helpful for variational
// inference; furthermore it can be costly to compute.
double lp = model_.template log_prob<false, true>(cont_params_,
print_stream_);
std::vector<double> cont_vector(cont_params_.size());
for (int i = 0; i < cont_params_.size(); ++i)
cont_vector.at(i) = cont_params_(i);
std::vector<int> disc_vector;
if (out_stream_) {
services::io::write_iteration(*out_stream_, model_, rng_,
lp, cont_vector, disc_vector,
print_stream_);
}
// draw more samples from posterior and write on subsequent lines
if (out_stream_) {
for (int n = 0; n < n_posterior_samples_; ++n) {
variational.sample(rng_, cont_params_);
double lp = model_.template log_prob<false, true>(cont_params_,
print_stream_);
for (int i = 0; i < cont_params_.size(); ++i) {
cont_vector.at(i) = cont_params_(i);
}
services::io::write_iteration(*out_stream_, model_, rng_,
lp, cont_vector, disc_vector, print_stream_);
}
}
return stan::services::error_codes::OK;
}
// Helper function: compute the median of a circular buffer
double circ_buff_median(const boost::circular_buffer<double>& cb) const {
// FIXME: naive implementation; creates a copy as a vector
std::vector<double> v;
for (boost::circular_buffer<double>::const_iterator i = cb.begin();
i != cb.end(); ++i) {
v.push_back(*i);
}
size_t n = v.size() / 2;
std::nth_element(v.begin(), v.begin()+n, v.end());
return v[n];
}
// Helper function: compute relative decrease between two doubles
double rel_decrease(double prev, double curr) const {
return std::abs(curr - prev) / std::abs(prev);
}
protected:
M& model_;
Eigen::VectorXd& cont_params_;
BaseRNG& rng_;
int n_monte_carlo_grad_;
int n_monte_carlo_elbo_;
double eta_adagrad_;
int eval_elbo_;
int n_posterior_samples_;
std::ostream* print_stream_;
std::ostream* out_stream_;
std::ostream* diag_stream_;
void write_error_msg_(std::ostream* error_msgs,
const std::exception& e) const {
if (!error_msgs) {
return;
}
*error_msgs
<< std::endl
<< "Informational Message: The current sample evaluation "
<< "of the ELBO is ignored because of the following issue:"
<< std::endl
<< e.what() << std::endl
<< "If this warning occurs often then your model may be "
<< "either severely ill-conditioned or misspecified."
<< std::endl;
}
};
} // variational
} // stan
#endif
<commit_msg>force decreasing learning rate; convergence; minimum buffer size<commit_after>#ifndef STAN_VARIATIONAL_ADVI_HPP
#define STAN_VARIATIONAL_ADVI_HPP
#include <stan/math.hpp>
#include <stan/io/dump.hpp>
#include <stan/model/util.hpp>
#include <stan/services/io/write_iteration_csv.hpp>
#include <stan/services/io/write_iteration.hpp>
#include <stan/services/error_codes.hpp>
#include <stan/variational/families/normal_fullrank.hpp>
#include <stan/variational/families/normal_meanfield.hpp>
#include <boost/circular_buffer.hpp>
#include <algorithm>
#include <limits>
#include <numeric>
#include <ostream>
#include <vector>
namespace stan {
namespace variational {
/**
* AUTOMATIC DIFFERENTIATION VARIATIONAL INFERENCE
*
* Runs "black box" variational inference by applying stochastic gradient
* ascent in order to maximize the Evidence Lower Bound for a given model
* and variational family.
*
* @tparam M class of model
* @tparam Q class of variational distribution
* @tparam BaseRNG class of random number generator
* @param m stan model
* @param cont_params initialization of continuous parameters
* @param n_monte_carlo_grad number of samples for gradient computation
* @param n_monte_carlo_elbo number of samples for ELBO computation
* @param eta_adagrad eta parameter for adaGrad
* @param rng random number generator
* @param eval_elbo evaluate ELBO at every "eval_elbo" iters
* @param n_posterior_samples number of samples to draw from posterior
* @param print_stream stream for convergence assessment output
* @param output_stream stream for parameters output
* @param diagnostic_stream stream for ELBO output
*/
template <class M, class Q, class BaseRNG>
class advi {
public:
advi(M& m,
Eigen::VectorXd& cont_params,
int n_monte_carlo_grad,
int n_monte_carlo_elbo,
double eta_adagrad,
BaseRNG& rng,
int eval_elbo,
int n_posterior_samples,
std::ostream* print_stream,
std::ostream* output_stream,
std::ostream* diagnostic_stream) :
model_(m),
cont_params_(cont_params),
rng_(rng),
n_monte_carlo_grad_(n_monte_carlo_grad),
n_monte_carlo_elbo_(n_monte_carlo_elbo),
eta_adagrad_(eta_adagrad),
eval_elbo_(eval_elbo),
n_posterior_samples_(n_posterior_samples),
print_stream_(print_stream),
out_stream_(output_stream),
diag_stream_(diagnostic_stream) {
static const char* function = "stan::variational::advi";
stan::math::check_positive(function,
"Number of Monte Carlo samples for gradients",
n_monte_carlo_grad_);
stan::math::check_positive(function,
"Number of Monte Carlo samples for ELBO",
n_monte_carlo_elbo_);
stan::math::check_positive(function,
"Number of posterior samples for output",
n_posterior_samples_);
stan::math::check_positive(function, "Eta stepsize", eta_adagrad_);
}
/**
* Calculates the Evidence Lower BOund (ELBO) by sampling from
* the variational distribution and then evaluating the log joint,
* adjusted by the entropy term of the variational distribution.
*
* @tparam Q class of variational distribution
* @return evidence lower bound (elbo)
*/
double calc_ELBO(const Q& variational) const {
static const char* function =
"stan::variational::advi::calc_ELBO";
double elbo = 0.0;
int dim = variational.dimension();
Eigen::VectorXd zeta(dim);
int i = 0;
int n_monte_carlo_drop = 0;
while (i < n_monte_carlo_elbo_) {
variational.sample(rng_, zeta);
try {
double energy_i = model_.template log_prob<false, true>(zeta,
print_stream_);
stan::math::check_finite(function, "energy_i", energy_i);
elbo += energy_i;
i += 1;
} catch (std::exception& e) {
this->write_error_msg_(print_stream_, e);
n_monte_carlo_drop += 1;
if (n_monte_carlo_drop >= n_monte_carlo_elbo_) {
const char* name = "The number of dropped evaluations";
const char* msg1 = "has reached its maximum amount (";
int y = n_monte_carlo_elbo_;
const char* msg2 = "). Your model may be either severely "
"ill-conditioned or misspecified.";
stan::math::domain_error(function, name, y, msg1, msg2);
}
}
}
// Divide to get Monte Carlo integral estimate
elbo /= n_monte_carlo_elbo_;
elbo += variational.entropy();
return elbo;
}
/**
* Calculates the "black box" gradient of the ELBO.
*
* @param variational variational distribution
* @param elbo_grad gradient of ELBO with respect to variational parameters
*/
void calc_ELBO_grad(const Q& variational, Q& elbo_grad) const {
static const char* function =
"stan::variational::advi::calc_ELBO_grad";
stan::math::check_size_match(function,
"Dimension of elbo_grad", elbo_grad.dimension(),
"Dimension of variational q", variational.dimension());
stan::math::check_size_match(function,
"Dimension of variational q", variational.dimension(),
"Dimension of variables in model", cont_params_.size());
variational.calc_grad(elbo_grad,
model_, cont_params_, n_monte_carlo_grad_, rng_,
print_stream_);
}
/**
* Runs stochastic gradient ascent with Adagrad.
*
* @param variational variational distribution
* @param tol_rel_obj relative tolerance parameter for convergence
* @param max_iterations max number of iterations to run algorithm
*/
void robbins_monro_adagrad(Q& variational,
double tol_rel_obj,
int max_iterations) const {
static const char* function =
"stan::variational::advi.robbins_monro_adagrad";
stan::math::check_positive(function,
"Relative objective function tolerance",
tol_rel_obj);
stan::math::check_positive(function,
"Maximum iterations",
max_iterations);
// Gradient parameters
Q elbo_grad = Q(model_.num_params_r());
// Adagrad parameters
double tau = 1.0;
Q params_adagrad = Q(model_.num_params_r());
double eta_scaled;
// RMSprop window_size
double window_size = 10.0;
double post_factor = 1.0 / window_size;
double pre_factor = 1.0 - post_factor;
// Initialize ELBO and convergence tracking variables
double elbo(0.0);
double elbo_prev = std::numeric_limits<double>::min();
double delta_elbo = std::numeric_limits<double>::max();
double delta_elbo_ave = std::numeric_limits<double>::max();
double delta_elbo_med = std::numeric_limits<double>::max();
// Heuristic to estimate how far to look back in rolling window
int cb_size = static_cast<int>(
std::max(0.1*max_iterations/static_cast<double>(eval_elbo_),
2.0));
boost::circular_buffer<double> cb(cb_size);
// Print stuff
if (print_stream_) {
*print_stream_ << " iter"
<< " ELBO"
<< " delta_ELBO_mean"
<< " delta_ELBO_med"
<< " notes "
<< std::endl;
}
// Timing variables
clock_t start = clock();
clock_t end;
double delta_t;
// Main loop
std::vector<double> print_vector;
bool do_more_iterations = true;
int iter_counter = 0;
while (do_more_iterations) {
// Compute gradient using Monte Carlo integration
calc_ELBO_grad(variational, elbo_grad);
// RMSprop moving average weighting
if (iter_counter == 0) {
params_adagrad += elbo_grad.square();
} else {
params_adagrad = pre_factor * params_adagrad +
post_factor * elbo_grad.square();
}
eta_scaled = eta_adagrad_ / sqrt(static_cast<double>(iter_counter));
// Stochastic gradient update
variational += eta_scaled * elbo_grad /
(tau + params_adagrad.sqrt());
// Check for convergence every "eval_elbo_"th iteration
if (iter_counter % eval_elbo_ == 0) {
elbo_prev = elbo;
elbo = calc_ELBO(variational);
delta_elbo = rel_decrease(elbo, elbo_prev);
cb.push_back(delta_elbo);
delta_elbo_ave = std::accumulate(cb.begin(), cb.end(), 0.0)
/ static_cast<double>(cb.size());
delta_elbo_med = circ_buff_median(cb);
if (print_stream_) {
*print_stream_
<< " "
<< std::setw(4) << iter_counter
<< " "
<< std::right << std::setw(9) << std::setprecision(1)
<< elbo
<< " "
<< std::setw(16) << std::fixed << std::setprecision(3)
<< delta_elbo_ave
<< " "
<< std::setw(15) << std::fixed << std::setprecision(3)
<< delta_elbo_med;
}
if (diag_stream_) {
end = clock();
delta_t = static_cast<double>(end - start) / CLOCKS_PER_SEC;
print_vector.clear();
print_vector.push_back(delta_t);
print_vector.push_back(elbo);
services::io::write_iteration_csv(*diag_stream_,
iter_counter, print_vector);
}
if (delta_elbo_ave < tol_rel_obj) {
if (print_stream_)
*print_stream_ << " MEAN ELBO CONVERGED";
do_more_iterations = false;
}
if (delta_elbo_med < tol_rel_obj) {
if (print_stream_)
*print_stream_ << " MEDIAN ELBO CONVERGED";
do_more_iterations = false;
}
if (iter_counter > 2*eval_elbo_) {
if (delta_elbo_med > 0.5 || delta_elbo_ave > 0.5) {
if (print_stream_)
*print_stream_ << " MAY BE DIVERGING... INSPECT ELBO";
}
}
if (print_stream_)
*print_stream_ << std::endl;
}
// Check for max iterations
if (iter_counter == max_iterations) {
if (print_stream_)
*print_stream_ << "MAX ITERATIONS REACHED" << std::endl;
do_more_iterations = false;
}
++iter_counter;
}
}
/**
* Runs the algorithm and writes to output.
*
* @param tol_rel_obj relative tolerance parameter for convergence
* @param max_iterations max number of iterations to run algorithm
*/
int run(double tol_rel_obj, int max_iterations) const {
if (diag_stream_) {
*diag_stream_ << "iter,time_in_seconds,ELBO" << std::endl;
}
// initialize variational approximation
Q variational = Q(cont_params_);
// run inference algorithm
robbins_monro_adagrad(variational, tol_rel_obj, max_iterations);
// get mean of posterior approximation and write on first output line
cont_params_ = variational.mean();
// This is temporary as lp is not really helpful for variational
// inference; furthermore it can be costly to compute.
double lp = model_.template log_prob<false, true>(cont_params_,
print_stream_);
std::vector<double> cont_vector(cont_params_.size());
for (int i = 0; i < cont_params_.size(); ++i)
cont_vector.at(i) = cont_params_(i);
std::vector<int> disc_vector;
if (out_stream_) {
services::io::write_iteration(*out_stream_, model_, rng_,
lp, cont_vector, disc_vector,
print_stream_);
}
// draw more samples from posterior and write on subsequent lines
if (out_stream_) {
for (int n = 0; n < n_posterior_samples_; ++n) {
variational.sample(rng_, cont_params_);
double lp = model_.template log_prob<false, true>(cont_params_,
print_stream_);
for (int i = 0; i < cont_params_.size(); ++i) {
cont_vector.at(i) = cont_params_(i);
}
services::io::write_iteration(*out_stream_, model_, rng_,
lp, cont_vector, disc_vector, print_stream_);
}
}
return stan::services::error_codes::OK;
}
// Helper function: compute the median of a circular buffer
double circ_buff_median(const boost::circular_buffer<double>& cb) const {
// FIXME: naive implementation; creates a copy as a vector
std::vector<double> v;
for (boost::circular_buffer<double>::const_iterator i = cb.begin();
i != cb.end(); ++i) {
v.push_back(*i);
}
size_t n = v.size() / 2;
std::nth_element(v.begin(), v.begin()+n, v.end());
return v[n];
}
// Helper function: compute relative decrease between two doubles
double rel_decrease(double prev, double curr) const {
return std::abs(curr - prev) / std::abs(prev);
}
protected:
M& model_;
Eigen::VectorXd& cont_params_;
BaseRNG& rng_;
int n_monte_carlo_grad_;
int n_monte_carlo_elbo_;
double eta_adagrad_;
int eval_elbo_;
int n_posterior_samples_;
std::ostream* print_stream_;
std::ostream* out_stream_;
std::ostream* diag_stream_;
void write_error_msg_(std::ostream* error_msgs,
const std::exception& e) const {
if (!error_msgs) {
return;
}
*error_msgs
<< std::endl
<< "Informational Message: The current sample evaluation "
<< "of the ELBO is ignored because of the following issue:"
<< std::endl
<< e.what() << std::endl
<< "If this warning occurs often then your model may be "
<< "either severely ill-conditioned or misspecified."
<< std::endl;
}
};
} // variational
} // stan
#endif
<|endoftext|> |
<commit_before>// @(#)root/rootx:$Id$
// Author: Fons Rademakers 19/02/98
//////////////////////////////////////////////////////////////////////////
// //
// Rootx //
// //
// Rootx is a small front-end program that starts the main ROOT module. //
// This program is called "root" in the $ROOTSYS/bin directory and the //
// real ROOT executable is now called "root.exe" (formerly "root"). //
// Rootx puts up a splash screen giving some info about the current //
// version of ROOT and, more importantly, it sets up the required //
// LD_LIBRARY_PATH, SHLIB_PATH and LIBPATH environment variables //
// (depending on the platform). //
// //
//////////////////////////////////////////////////////////////////////////
#include "RConfigure.h"
#include "Rtypes.h"
#include "rootCommandLineOptionsHelp.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <string>
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#include <mach-o/dyld.h>
#endif
#ifdef __sun
# ifndef _REENTRANT
# if __SUNPRO_CC > 0x420
# define GLOBAL_ERRNO
# endif
# endif
#endif
#if defined(__CYGWIN__) && defined(__GNUC__)
#define ROOTBINARY "root_exe.exe"
#else
#define ROOTBINARY "root.exe"
#endif
#define ROOTNBBINARY "rootnb.exe"
extern void PopupLogo(bool);
extern void WaitLogo();
extern void PopdownLogo();
extern void CloseDisplay();
static bool gNoLogo = false;
//const int kMAXPATHLEN = 8192; defined in Rtypes.h
//Part for Cocoa - requires external linkage.
namespace ROOT {
namespace ROOTX {
//This had internal linkage before, now must be accessible from rootx-cocoa.mm.
int gChildpid = -1;
}
}
#ifdef R__HAS_COCOA
using ROOT::ROOTX::gChildpid;
#else
static int gChildpid;
static int GetErrno()
{
#ifdef GLOBAL_ERRNO
return ::errno;
#else
return errno;
#endif
}
static void ResetErrno()
{
#ifdef GLOBAL_ERRNO
::errno = 0;
#else
errno = 0;
#endif
}
#endif
static const char *GetExePath()
{
static std::string exepath;
if (exepath == "") {
#ifdef __APPLE__
exepath = _dyld_get_image_name(0);
#endif
#ifdef __linux
char linkname[64]; // /proc/<pid>/exe
char buf[kMAXPATHLEN]; // exe path name
pid_t pid;
// get our pid and build the name of the link in /proc
pid = getpid();
snprintf(linkname,64, "/proc/%i/exe", pid);
int ret = readlink(linkname, buf, kMAXPATHLEN);
if (ret > 0 && ret < kMAXPATHLEN) {
buf[ret] = 0;
exepath = buf;
}
#endif
}
return exepath.c_str();
}
static void SetRootSys()
{
const char *exepath = GetExePath();
if (exepath && *exepath) {
int l1 = strlen(exepath)+1;
char *ep = new char[l1];
strlcpy(ep, exepath, l1);
char *s;
if ((s = strrchr(ep, '/'))) {
*s = 0;
if ((s = strrchr(ep, '/'))) {
*s = 0;
int l2 = strlen(ep) + 10;
char *env = new char[l2];
snprintf(env, l2, "ROOTSYS=%s", ep);
putenv(env);
}
}
delete [] ep;
}
}
static void SetLibraryPath()
{
#ifdef ROOTPREFIX
if (getenv("ROOTIGNOREPREFIX")) {
#endif
// Set library path for the different platforms.
char *msg;
# if defined(__hpux) || defined(_HIUX_SOURCE)
if (getenv("SHLIB_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("SHLIB_PATH"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("SHLIB_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib", getenv("ROOTSYS"));
}
# elif defined(_AIX)
if (getenv("LIBPATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LIBPATH"))+100];
sprintf(msg, "LIBPATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LIBPATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "LIBPATH=%s/lib:/lib:/usr/lib", getenv("ROOTSYS"));
}
# elif defined(__APPLE__)
if (getenv("DYLD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("DYLD_LIBRARY_PATH"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("DYLD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
}
# else
if (getenv("LD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LD_LIBRARY_PATH"))+100];
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
# if defined(__sun)
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:/usr/dt/lib", getenv("ROOTSYS"));
# else
sprintf(msg, "LD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
# endif
}
# endif
putenv(msg);
#ifdef ROOTPREFIX
}
#endif
}
extern "C" {
static void SigUsr1(int);
static void SigTerm(int);
}
static void SigUsr1(int)
{
// When we get SIGUSR1 from child (i.e. ROOT) then pop down logo.
if (!gNoLogo)
PopdownLogo();
}
static void SigTerm(int sig)
{
// When we get terminated, terminate child, too.
kill(gChildpid, sig);
}
//ifdefs for Cocoa/other *xes.
#ifdef R__HAS_COCOA
namespace ROOT {
namespace ROOTX {
//Before it had internal linkage, now must be external,
//add namespaces!
void WaitChild();
}
}
using ROOT::ROOTX::WaitChild;
#else
static void WaitChild()
{
// Wait till child (i.e. ROOT) is finished.
int status;
do {
while (waitpid(gChildpid, &status, WUNTRACED) < 0) {
if (GetErrno() != EINTR)
break;
ResetErrno();
}
if (WIFEXITED(status))
exit(WEXITSTATUS(status));
if (WIFSIGNALED(status))
exit(WTERMSIG(status));
if (WIFSTOPPED(status)) { // child got ctlr-Z
raise(SIGTSTP); // stop also parent
kill(gChildpid, SIGCONT); // if parent wakes up, wake up child
}
} while (WIFSTOPPED(status));
exit(0);
}
#endif
static void PrintUsage()
{
fprintf(stderr, kCommandLineOptionsHelp);
}
int main(int argc, char **argv)
{
char **argvv;
char arg0[kMAXPATHLEN];
#ifdef ROOTPREFIX
if (getenv("ROOTIGNOREPREFIX")) {
#endif
// Try to set ROOTSYS depending on pathname of the executable
SetRootSys();
if (!getenv("ROOTSYS")) {
fprintf(stderr, "%s: ROOTSYS not set. Set it before trying to run %s.\n",
argv[0], argv[0]);
return 1;
}
#ifdef ROOTPREFIX
}
#endif
// In batch mode don't show splash screen, idem for no logo mode,
// in about mode show always splash screen
bool batch = false, about = false;
bool notebook = false;
int i;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
!strncmp(argv[i], "--help", 6)) {
PrintUsage();
return 1;
}
if (!strcmp(argv[i], "-b")) batch = true;
if (!strcmp(argv[i], "-l")) gNoLogo = true;
if (!strcmp(argv[i], "-ll")) gNoLogo = true;
if (!strcmp(argv[i], "-a")) about = true;
if (!strcmp(argv[i], "-config")) gNoLogo = true;
if (!strcmp(argv[i], "--version")) gNoLogo = true;
if (!strcmp(argv[i], "--notebook")) notebook = true;
}
if (notebook) {
// Build command
#ifdef ROOTBINDIR
if (getenv("ROOTIGNOREPREFIX"))
#endif
snprintf(arg0, sizeof(arg0), "%s/bin/%s", getenv("ROOTSYS"), ROOTNBBINARY);
#ifdef ROOTBINDIR
else
snprintf(arg0, sizeof(arg0), "%s/%s", ROOTBINDIR, ROOTNBBINARY);
#endif
// Execute ROOT notebook binary
execl(arg0, arg0, NULL);
// Exec failed
fprintf(stderr, "%s: can't start ROOT notebook -- this option is only available when building with CMake, please check that %s exists\n",
argv[0], arg0);
return 1;
}
#ifndef R__HAS_COCOA
if (!getenv("DISPLAY")) {
gNoLogo = true;
}
#endif
if (batch)
gNoLogo = true;
if (about) {
batch = false;
gNoLogo = false;
}
if (!batch) {
if (about) {
PopupLogo(true);
WaitLogo();
return 0;
} else if (!gNoLogo)
PopupLogo(false);
}
// Ignore SIGINT and SIGQUIT. Install handler for SIGUSR1.
struct sigaction ignore, actUsr1, actTerm,
saveintr, savequit, saveusr1, saveterm;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
ignore.sa_handler = (void (*)())SIG_IGN;
#elif defined(__sun) && defined(__SVR4)
ignore.sa_handler = (void (*)(int))SIG_IGN;
#else
ignore.sa_handler = SIG_IGN;
#endif
sigemptyset(&ignore.sa_mask);
ignore.sa_flags = 0;
actUsr1 = ignore;
actTerm = ignore;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
actUsr1.sa_handler = (void (*)())SigUsr1;
actTerm.sa_handler = (void (*)())SigTerm;
#elif defined(__sun) && defined(__SVR4)
actUsr1.sa_handler = SigUsr1;
actTerm.sa_handler = SigTerm;
#elif (defined(__sgi) && !defined(__KCC)) || defined(__Lynx__)
# if defined(IRIX64) || (__GNUG__>=3)
actUsr1.sa_handler = SigUsr1;
actTerm.sa_handler = SigTerm;
# else
actUsr1.sa_handler = (void (*)(...))SigUsr1;
actTerm.sa_handler = (void (*)(...))SigTerm;
# endif
#else
actUsr1.sa_handler = SigUsr1;
actTerm.sa_handler = SigTerm;
#endif
sigaction(SIGINT, &ignore, &saveintr);
sigaction(SIGQUIT, &ignore, &savequit);
sigaction(SIGUSR1, &actUsr1, &saveusr1);
sigaction(SIGTERM, &actTerm, &saveterm);
// Create child...
if ((gChildpid = fork()) < 0) {
fprintf(stderr, "%s: error forking child\n", argv[0]);
return 1;
} else if (gChildpid > 0) {
if (!gNoLogo)
WaitLogo();
WaitChild();
}
// Continue with child...
// Restore original signal actions
sigaction(SIGINT, &saveintr, 0);
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGUSR1, &saveusr1, 0);
sigaction(SIGTERM, &saveterm, 0);
// Close X display connection
CloseDisplay();
// Child is going to overlay itself with the actual ROOT module...
// Build argv vector
argvv = new char* [argc+2];
#ifdef ROOTBINDIR
if (getenv("ROOTIGNOREPREFIX"))
#endif
snprintf(arg0, sizeof(arg0), "%s/bin/%s", getenv("ROOTSYS"), ROOTBINARY);
#ifdef ROOTBINDIR
else
snprintf(arg0, sizeof(arg0), "%s/%s", ROOTBINDIR, ROOTBINARY);
#endif
argvv[0] = arg0;
argvv[1] = (char *) "-splash";
for (i = 1; i < argc; i++)
argvv[1+i] = argv[i];
argvv[1+i] = 0;
// Make sure library path is set
SetLibraryPath();
// Execute actual ROOT module
execv(arg0, argvv);
// Exec failed
fprintf(stderr, "%s: can't start ROOT -- check that %s exists!\n",
argv[0], arg0);
return 1;
}
<commit_msg>Disable splash screen by default<commit_after>// @(#)root/rootx:$Id$
// Author: Fons Rademakers 19/02/98
//////////////////////////////////////////////////////////////////////////
// //
// Rootx //
// //
// Rootx is a small front-end program that starts the main ROOT module. //
// This program is called "root" in the $ROOTSYS/bin directory and the //
// real ROOT executable is now called "root.exe" (formerly "root"). //
// Rootx puts up a splash screen giving some info about the current //
// version of ROOT and, more importantly, it sets up the required //
// LD_LIBRARY_PATH, SHLIB_PATH and LIBPATH environment variables //
// (depending on the platform). //
// //
//////////////////////////////////////////////////////////////////////////
#include "RConfigure.h"
#include "Rtypes.h"
#include "rootCommandLineOptionsHelp.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <errno.h>
#include <netdb.h>
#include <sys/socket.h>
#include <string>
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#include <mach-o/dyld.h>
#endif
#ifdef __sun
# ifndef _REENTRANT
# if __SUNPRO_CC > 0x420
# define GLOBAL_ERRNO
# endif
# endif
#endif
#if defined(__CYGWIN__) && defined(__GNUC__)
#define ROOTBINARY "root_exe.exe"
#else
#define ROOTBINARY "root.exe"
#endif
#define ROOTNBBINARY "rootnb.exe"
extern void PopupLogo(bool);
extern void WaitLogo();
extern void PopdownLogo();
extern void CloseDisplay();
static bool gNoLogo = true;
//const int kMAXPATHLEN = 8192; defined in Rtypes.h
//Part for Cocoa - requires external linkage.
namespace ROOT {
namespace ROOTX {
//This had internal linkage before, now must be accessible from rootx-cocoa.mm.
int gChildpid = -1;
}
}
#ifdef R__HAS_COCOA
using ROOT::ROOTX::gChildpid;
#else
static int gChildpid;
static int GetErrno()
{
#ifdef GLOBAL_ERRNO
return ::errno;
#else
return errno;
#endif
}
static void ResetErrno()
{
#ifdef GLOBAL_ERRNO
::errno = 0;
#else
errno = 0;
#endif
}
#endif
static const char *GetExePath()
{
static std::string exepath;
if (exepath == "") {
#ifdef __APPLE__
exepath = _dyld_get_image_name(0);
#endif
#ifdef __linux
char linkname[64]; // /proc/<pid>/exe
char buf[kMAXPATHLEN]; // exe path name
pid_t pid;
// get our pid and build the name of the link in /proc
pid = getpid();
snprintf(linkname,64, "/proc/%i/exe", pid);
int ret = readlink(linkname, buf, kMAXPATHLEN);
if (ret > 0 && ret < kMAXPATHLEN) {
buf[ret] = 0;
exepath = buf;
}
#endif
}
return exepath.c_str();
}
static void SetRootSys()
{
const char *exepath = GetExePath();
if (exepath && *exepath) {
int l1 = strlen(exepath)+1;
char *ep = new char[l1];
strlcpy(ep, exepath, l1);
char *s;
if ((s = strrchr(ep, '/'))) {
*s = 0;
if ((s = strrchr(ep, '/'))) {
*s = 0;
int l2 = strlen(ep) + 10;
char *env = new char[l2];
snprintf(env, l2, "ROOTSYS=%s", ep);
putenv(env);
}
}
delete [] ep;
}
}
static void SetLibraryPath()
{
#ifdef ROOTPREFIX
if (getenv("ROOTIGNOREPREFIX")) {
#endif
// Set library path for the different platforms.
char *msg;
# if defined(__hpux) || defined(_HIUX_SOURCE)
if (getenv("SHLIB_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("SHLIB_PATH"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("SHLIB_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "SHLIB_PATH=%s/lib", getenv("ROOTSYS"));
}
# elif defined(_AIX)
if (getenv("LIBPATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LIBPATH"))+100];
sprintf(msg, "LIBPATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LIBPATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "LIBPATH=%s/lib:/lib:/usr/lib", getenv("ROOTSYS"));
}
# elif defined(__APPLE__)
if (getenv("DYLD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("DYLD_LIBRARY_PATH"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("DYLD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
sprintf(msg, "DYLD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
}
# else
if (getenv("LD_LIBRARY_PATH")) {
msg = new char [strlen(getenv("ROOTSYS"))+strlen(getenv("LD_LIBRARY_PATH"))+100];
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:%s", getenv("ROOTSYS"),
getenv("LD_LIBRARY_PATH"));
} else {
msg = new char [strlen(getenv("ROOTSYS"))+100];
# if defined(__sun)
sprintf(msg, "LD_LIBRARY_PATH=%s/lib:/usr/dt/lib", getenv("ROOTSYS"));
# else
sprintf(msg, "LD_LIBRARY_PATH=%s/lib", getenv("ROOTSYS"));
# endif
}
# endif
putenv(msg);
#ifdef ROOTPREFIX
}
#endif
}
extern "C" {
static void SigUsr1(int);
static void SigTerm(int);
}
static void SigUsr1(int)
{
// When we get SIGUSR1 from child (i.e. ROOT) then pop down logo.
if (!gNoLogo)
PopdownLogo();
}
static void SigTerm(int sig)
{
// When we get terminated, terminate child, too.
kill(gChildpid, sig);
}
//ifdefs for Cocoa/other *xes.
#ifdef R__HAS_COCOA
namespace ROOT {
namespace ROOTX {
//Before it had internal linkage, now must be external,
//add namespaces!
void WaitChild();
}
}
using ROOT::ROOTX::WaitChild;
#else
static void WaitChild()
{
// Wait till child (i.e. ROOT) is finished.
int status;
do {
while (waitpid(gChildpid, &status, WUNTRACED) < 0) {
if (GetErrno() != EINTR)
break;
ResetErrno();
}
if (WIFEXITED(status))
exit(WEXITSTATUS(status));
if (WIFSIGNALED(status))
exit(WTERMSIG(status));
if (WIFSTOPPED(status)) { // child got ctlr-Z
raise(SIGTSTP); // stop also parent
kill(gChildpid, SIGCONT); // if parent wakes up, wake up child
}
} while (WIFSTOPPED(status));
exit(0);
}
#endif
static void PrintUsage()
{
fprintf(stderr, kCommandLineOptionsHelp);
}
int main(int argc, char **argv)
{
char **argvv;
char arg0[kMAXPATHLEN];
#ifdef ROOTPREFIX
if (getenv("ROOTIGNOREPREFIX")) {
#endif
// Try to set ROOTSYS depending on pathname of the executable
SetRootSys();
if (!getenv("ROOTSYS")) {
fprintf(stderr, "%s: ROOTSYS not set. Set it before trying to run %s.\n",
argv[0], argv[0]);
return 1;
}
#ifdef ROOTPREFIX
}
#endif
// In batch mode don't show splash screen, idem for no logo mode,
// in about mode show always splash screen
bool batch = false, about = false;
bool notebook = false;
int i;
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-?") || !strncmp(argv[i], "-h", 2) ||
!strncmp(argv[i], "--help", 6)) {
PrintUsage();
return 1;
}
if (!strcmp(argv[i], "-b")) batch = true;
if (!strcmp(argv[i], "-l")) gNoLogo = true;
if (!strcmp(argv[i], "-ll")) gNoLogo = true;
if (!strcmp(argv[i], "-a")) about = true;
if (!strcmp(argv[i], "-config")) gNoLogo = true;
if (!strcmp(argv[i], "--version")) gNoLogo = true;
if (!strcmp(argv[i], "--notebook")) notebook = true;
}
if (notebook) {
// Build command
#ifdef ROOTBINDIR
if (getenv("ROOTIGNOREPREFIX"))
#endif
snprintf(arg0, sizeof(arg0), "%s/bin/%s", getenv("ROOTSYS"), ROOTNBBINARY);
#ifdef ROOTBINDIR
else
snprintf(arg0, sizeof(arg0), "%s/%s", ROOTBINDIR, ROOTNBBINARY);
#endif
// Execute ROOT notebook binary
execl(arg0, arg0, NULL);
// Exec failed
fprintf(stderr, "%s: can't start ROOT notebook -- this option is only available when building with CMake, please check that %s exists\n",
argv[0], arg0);
return 1;
}
#ifndef R__HAS_COCOA
if (!getenv("DISPLAY")) {
gNoLogo = true;
}
#endif
if (batch)
gNoLogo = true;
if (about) {
batch = false;
gNoLogo = false;
}
if (!batch) {
if (about) {
PopupLogo(true);
WaitLogo();
return 0;
} else if (!gNoLogo)
PopupLogo(false);
}
// Ignore SIGINT and SIGQUIT. Install handler for SIGUSR1.
struct sigaction ignore, actUsr1, actTerm,
saveintr, savequit, saveusr1, saveterm;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
ignore.sa_handler = (void (*)())SIG_IGN;
#elif defined(__sun) && defined(__SVR4)
ignore.sa_handler = (void (*)(int))SIG_IGN;
#else
ignore.sa_handler = SIG_IGN;
#endif
sigemptyset(&ignore.sa_mask);
ignore.sa_flags = 0;
actUsr1 = ignore;
actTerm = ignore;
#if defined(__sun) && !defined(__i386) && !defined(__SVR4)
actUsr1.sa_handler = (void (*)())SigUsr1;
actTerm.sa_handler = (void (*)())SigTerm;
#elif defined(__sun) && defined(__SVR4)
actUsr1.sa_handler = SigUsr1;
actTerm.sa_handler = SigTerm;
#elif (defined(__sgi) && !defined(__KCC)) || defined(__Lynx__)
# if defined(IRIX64) || (__GNUG__>=3)
actUsr1.sa_handler = SigUsr1;
actTerm.sa_handler = SigTerm;
# else
actUsr1.sa_handler = (void (*)(...))SigUsr1;
actTerm.sa_handler = (void (*)(...))SigTerm;
# endif
#else
actUsr1.sa_handler = SigUsr1;
actTerm.sa_handler = SigTerm;
#endif
sigaction(SIGINT, &ignore, &saveintr);
sigaction(SIGQUIT, &ignore, &savequit);
sigaction(SIGUSR1, &actUsr1, &saveusr1);
sigaction(SIGTERM, &actTerm, &saveterm);
// Create child...
if ((gChildpid = fork()) < 0) {
fprintf(stderr, "%s: error forking child\n", argv[0]);
return 1;
} else if (gChildpid > 0) {
if (!gNoLogo)
WaitLogo();
WaitChild();
}
// Continue with child...
// Restore original signal actions
sigaction(SIGINT, &saveintr, 0);
sigaction(SIGQUIT, &savequit, 0);
sigaction(SIGUSR1, &saveusr1, 0);
sigaction(SIGTERM, &saveterm, 0);
// Close X display connection
CloseDisplay();
// Child is going to overlay itself with the actual ROOT module...
// Build argv vector
argvv = new char* [argc+2];
#ifdef ROOTBINDIR
if (getenv("ROOTIGNOREPREFIX"))
#endif
snprintf(arg0, sizeof(arg0), "%s/bin/%s", getenv("ROOTSYS"), ROOTBINARY);
#ifdef ROOTBINDIR
else
snprintf(arg0, sizeof(arg0), "%s/%s", ROOTBINDIR, ROOTBINARY);
#endif
argvv[0] = arg0;
argvv[1] = (char *) "-splash";
for (i = 1; i < argc; i++)
argvv[1+i] = argv[i];
argvv[1+i] = 0;
// Make sure library path is set
SetLibraryPath();
// Execute actual ROOT module
execv(arg0, argvv);
// Exec failed
fprintf(stderr, "%s: can't start ROOT -- check that %s exists!\n",
argv[0], arg0);
return 1;
}
<|endoftext|> |
<commit_before>/** deme_expander.cc ---
*
* Copyright (C) 2013 OpenCog Foundation
*
* Author: Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "deme_expander.h"
namespace opencog {
namespace moses {
string_seq deme_expander::fs_to_names(const set<arity_t>& fs,
const string_seq& ilabels) const
{
vector<string> fs_names;
for (arity_t i : fs)
fs_names.push_back(ilabels[i]);
return fs_names;
}
void deme_expander::log_selected_feature_sets(const feature_set_pop& sf_pop,
const feature_set& xmplr_features,
const string_seq& ilabels,
const vector<demeID_t>& demeIDs) const
{
unsigned sfps = sf_pop.size(), sfi = 0;
OC_ASSERT(sfps == demeIDs.size(), "The code is probably not robust enough");
for (const auto& sf : sf_pop) {
logger().info() << "Breadth-first expansion for deme : "
<< demeIDs[sfi];
logger().info() << "Selected " << sf.second.size()
<< " features for representation building";
auto xmplr_sf = set_intersection(sf.second, xmplr_features);
auto new_sf = set_difference(sf.second, xmplr_features);
logger().info() << "Of these, " << xmplr_sf.size()
<< " are already in the exemplar, and " << new_sf.size()
<< " are new.";
ostreamContainer(logger().info() << "Selected features which are in the exemplar: ",
fs_to_names(xmplr_sf, ilabels), ",");
ostreamContainer(logger().info() << "Selected features which are new: ",
fs_to_names(new_sf, ilabels), ",");
sfi++;
}
}
combo_tree deme_expander::prune_xmplr(const combo_tree& xmplr,
const feature_set& selected_features) const
{
combo_tree res = xmplr;
// remove literals of non selected features from the exemplar
for (auto it = res.begin(); it != res.end();) {
if (is_argument(*it)) {
arity_t feature = get_argument(*it).abs_idx_from_zero();
auto fit = selected_features.find(feature);
if (fit == selected_features.end())
it = res.erase(it); // not selected, prune it
else
++it;
}
else
++it;
}
simplify_knob_building(res);
// if the exemplar is empty use a seed
if (res.empty()) {
type_node otn = get_type_node(get_signature_output(_type_sig));
res = type_to_exemplar(otn);
}
return res;
}
bool deme_expander::create_demes(const combo_tree& exemplar, int n_expansions)
{
using namespace reduct;
OC_ASSERT(_ignore_idxs_seq.empty());
OC_ASSERT(_reps.empty());
OC_ASSERT(_demes.empty());
combo_tree xmplr = exemplar;
// Define the demeIDs of the demes to be spawned
vector<demeID_t> demeIDs;
if (_params.fstor && _params.fstor->params.n_demes > 1) {
for (unsigned i = 0; i < _params.fstor->params.n_demes; i++)
demeIDs.emplace_back(n_expansions + 1, i);
} else
demeIDs.emplace_back(n_expansions + 1);
// [HIGHLY EXPERIMENTAL]. Limit the number of features used to
// build the exemplar to a more manageable number. Basically,
// this is 'on-the-fly' feature selection. This differs from an
// ordinary, one-time only, up-front round of feature selection by
// using only those features which score well with the current
// exemplar.
vector<operator_set> ignore_ops_seq, considered_args_seq;
vector<combo_tree> xmplr_seq;
if (_params.fstor) {
// copy, any change in the parameters will not be remembered
feature_selector festor = *_params.fstor;
// return the set of selected features as column index
// (left most column corresponds to 0)
auto sf_pop = festor(exemplar);
// get the set of features of the exemplar
auto xmplr_features = get_argument_abs_idx_from_zero_set(exemplar);
// get labels corresponding to all the features
const auto& ilabels = festor._ctable.get_input_labels();
if (festor.params.n_demes > 1)
logger().info() << "Breadth-first deme expansion (same exemplar, multiple feature sets): " << festor.params.n_demes << " demes";
log_selected_feature_sets(sf_pop, xmplr_features, ilabels, demeIDs);
unsigned sfi = 0;
for (auto& sf : sf_pop) {
// Either prune the exemplar, or add all exemplars
// features to the feature sets
if (festor.params.prune_xmplr) {
auto xmplr_nsf = set_difference(xmplr_features,
sf.second);
if (xmplr_features.empty())
logger().debug() << "No feature to prune in the "
<< "exemplar for deme " << demeIDs[sfi];
else {
ostreamContainer(logger().debug() <<
"Prune the exemplar from non-selected "
"features for deme " << demeIDs[sfi]
<< ": ",
fs_to_names(xmplr_nsf, ilabels));
xmplr_seq.push_back(prune_xmplr(exemplar, sf.second));
}
}
else {
logger().debug() << "Do not prune the exemplar from "
<< "non-selected features "
<< "for deme " << demeIDs[sfi];
// Insert exemplar features as they are not pruned
sf.second.insert(xmplr_features.begin(), xmplr_features.end());
xmplr_seq.push_back(exemplar);
}
// add the complement of the selected features to ignore_ops
unsigned arity = festor._ctable.get_arity();
set<arity_t> ignore_idxs;
vertex_set ignore_ops, considered_args;
for (unsigned i = 0; i < arity; i++) {
argument arg(i + 1);
if (sf.second.find(i) == sf.second.end()) {
ignore_idxs.insert(i);
ignore_ops.insert(arg);
}
else {
considered_args.insert(arg);
}
}
_ignore_idxs_seq.push_back(ignore_idxs);
ignore_ops_seq.push_back(ignore_ops);
considered_args_seq.push_back(considered_args);
sfi++;
}
}
else { // no feature selection within moses
ignore_ops_seq.push_back(_params.ignore_ops);
xmplr_seq.push_back(exemplar);
}
for (unsigned i = 0; i < xmplr_seq.size(); i++) {
if (logger().isDebugEnabled()) {
logger().debug() << "Attempt to build rep from exemplar "
<< "for deme " << demeIDs[i]
<< " : " << xmplr_seq[i];
if (!considered_args_seq.empty())
ostreamContainer(logger().debug() << "Using arguments: ",
considered_args_seq[i]);
}
// Build a representation by adding knobs to the exemplar,
// creating a field set, and a mapping from field set to knobs.
_reps.push_back(new representation(simplify_candidate,
simplify_knob_building,
xmplr_seq[i], _type_sig,
ignore_ops_seq[i],
_params.perceptions,
_params.actions,
_params.linear_contin,
_params.perm_ratio));
// If the representation is empty, try the next
// best-scoring exemplar.
if (_reps.back().fields().empty()) {
_reps.pop_back();
logger().warn("The representation is empty, perhaps the reduct "
"effort for knob building is too high.");
}
}
if (_reps.empty()) return false;
// Create empty demes with their IDs
for (unsigned i = 0; i < _reps.size(); i++)
_demes.push_back(new deme_t(_reps[i].fields(), demeIDs[i]));
return true;
}
vector<unsigned> deme_expander::optimize_demes(int max_evals, time_t max_time)
{
vector<unsigned> actl_evals;
int max_evals_per_deme = max_evals / _demes.size();
for (unsigned i = 0; i < _demes.size(); i++)
{
if (logger().isDebugEnabled()) {
stringstream ss;
ss << "Optimize deme " << _demes[i].getID() << "; "
<< "max evaluations allowed: " << max_evals_per_deme;
logger().debug(ss.str());
}
if (_params.fstor) {
// Attempt to compress the CTable further (to optimize and
// update max score)
_cscorer.ignore_idxs(_ignore_idxs_seq[i]);
// compute the max target for that deme (if features have been
// selected is might be less that the global target)
//
// TODO: DO NOT CHANGE THE MAX SCORE IF USER SET IT: BUT THAT
// OPTION ISN'T GLOBAL WHAT TO DO?
score_t deme_target_score = _cscorer.best_possible_score();
logger().info("Inferred target score for that deme = %g",
deme_target_score);
// negative min_improv is interpreted as percentage of
// improvement, if so then don't substract anything, since in that
// scenario the absolute min improvent can be arbitrarily small
logger().info("It appears there is an algorithmic bug in "
"precision_bscore::best_possible_bscore. "
"Till not fixed we shall not rely on it to "
"terminate deme search");
// TODO: re-enable that once best_possible_bscore is fixed
// score_t actual_min_improv = std::max(_cscorer.min_improv(),
// (score_t)0);
// deme_target_score -= actual_min_improv;
// logger().info("Subtract %g (minimum significant improvement) "
// "from the target score to deal with float "
// "imprecision = %g",
// actual_min_improv, deme_target_score);
// // update max score optimizer
// _optimize.opt_params.terminate_if_gte = deme_target_score;
}
// Optimize
complexity_based_scorer cpx_scorer =
complexity_based_scorer(_cscorer, _reps[i], _params.reduce_all);
actl_evals.push_back(_optimize(_demes[i], cpx_scorer,
max_evals_per_deme, max_time));
}
if (_params.fstor) {
// reset scorer to use all variables (important so that
// behavioral score is consistent across generations
set<arity_t> empty_idxs;
_cscorer.ignore_idxs(empty_idxs);
}
return actl_evals;
}
void deme_expander::free_demes()
{
_ignore_idxs_seq.clear();
_demes.clear();
_reps.clear();
}
} // ~namespace moses
} // ~namespace opencog
<commit_msg>Fix xmplr_seq initialization<commit_after>/** deme_expander.cc ---
*
* Copyright (C) 2013 OpenCog Foundation
*
* Author: Nil Geisweiller
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* 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 Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "deme_expander.h"
namespace opencog {
namespace moses {
string_seq deme_expander::fs_to_names(const set<arity_t>& fs,
const string_seq& ilabels) const
{
vector<string> fs_names;
for (arity_t i : fs)
fs_names.push_back(ilabels[i]);
return fs_names;
}
void deme_expander::log_selected_feature_sets(const feature_set_pop& sf_pop,
const feature_set& xmplr_features,
const string_seq& ilabels,
const vector<demeID_t>& demeIDs) const
{
unsigned sfps = sf_pop.size(), sfi = 0;
OC_ASSERT(sfps == demeIDs.size(), "The code is probably not robust enough");
for (const auto& sf : sf_pop) {
logger().info() << "Breadth-first expansion for deme : "
<< demeIDs[sfi];
logger().info() << "Selected " << sf.second.size()
<< " features for representation building";
auto xmplr_sf = set_intersection(sf.second, xmplr_features);
auto new_sf = set_difference(sf.second, xmplr_features);
logger().info() << "Of these, " << xmplr_sf.size()
<< " are already in the exemplar, and " << new_sf.size()
<< " are new.";
ostreamContainer(logger().info() << "Selected features which are in the exemplar: ",
fs_to_names(xmplr_sf, ilabels), ",");
ostreamContainer(logger().info() << "Selected features which are new: ",
fs_to_names(new_sf, ilabels), ",");
sfi++;
}
}
combo_tree deme_expander::prune_xmplr(const combo_tree& xmplr,
const feature_set& selected_features) const
{
combo_tree res = xmplr;
// remove literals of non selected features from the exemplar
for (auto it = res.begin(); it != res.end();) {
if (is_argument(*it)) {
arity_t feature = get_argument(*it).abs_idx_from_zero();
auto fit = selected_features.find(feature);
if (fit == selected_features.end())
it = res.erase(it); // not selected, prune it
else
++it;
}
else
++it;
}
simplify_knob_building(res);
// if the exemplar is empty use a seed
if (res.empty()) {
type_node otn = get_type_node(get_signature_output(_type_sig));
res = type_to_exemplar(otn);
}
return res;
}
bool deme_expander::create_demes(const combo_tree& exemplar, int n_expansions)
{
using namespace reduct;
OC_ASSERT(_ignore_idxs_seq.empty());
OC_ASSERT(_reps.empty());
OC_ASSERT(_demes.empty());
combo_tree xmplr = exemplar;
// Define the demeIDs of the demes to be spawned
vector<demeID_t> demeIDs;
if (_params.fstor && _params.fstor->params.n_demes > 1) {
for (unsigned i = 0; i < _params.fstor->params.n_demes; i++)
demeIDs.emplace_back(n_expansions + 1, i);
} else
demeIDs.emplace_back(n_expansions + 1);
// [HIGHLY EXPERIMENTAL]. Limit the number of features used to
// build the exemplar to a more manageable number. Basically,
// this is 'on-the-fly' feature selection. This differs from an
// ordinary, one-time only, up-front round of feature selection by
// using only those features which score well with the current
// exemplar.
vector<operator_set> ignore_ops_seq, considered_args_seq;
vector<combo_tree> xmplr_seq;
if (_params.fstor) {
// copy, any change in the parameters will not be remembered
feature_selector festor = *_params.fstor;
// return the set of selected features as column index
// (left most column corresponds to 0)
auto sf_pop = festor(exemplar);
// get the set of features of the exemplar
auto xmplr_features = get_argument_abs_idx_from_zero_set(exemplar);
// get labels corresponding to all the features
const auto& ilabels = festor._ctable.get_input_labels();
if (festor.params.n_demes > 1)
logger().info() << "Breadth-first deme expansion (same exemplar, multiple feature sets): " << festor.params.n_demes << " demes";
log_selected_feature_sets(sf_pop, xmplr_features, ilabels, demeIDs);
unsigned sfi = 0;
for (auto& sf : sf_pop) {
// Either prune the exemplar, or add all exemplars
// features to the feature sets
if (festor.params.prune_xmplr) {
auto xmplr_nsf = set_difference(xmplr_features,
sf.second);
if (xmplr_features.empty())
logger().debug() << "No feature to prune in the "
<< "exemplar for deme " << demeIDs[sfi];
else {
ostreamContainer(logger().debug() <<
"Prune the exemplar from non-selected "
"features for deme " << demeIDs[sfi]
<< ": ",
fs_to_names(xmplr_nsf, ilabels));
}
xmplr_seq.push_back(prune_xmplr(exemplar, sf.second));
}
else {
logger().debug() << "Do not prune the exemplar from "
<< "non-selected features "
<< "for deme " << demeIDs[sfi];
// Insert exemplar features as they are not pruned
sf.second.insert(xmplr_features.begin(), xmplr_features.end());
xmplr_seq.push_back(exemplar);
}
// add the complement of the selected features to ignore_ops
unsigned arity = festor._ctable.get_arity();
set<arity_t> ignore_idxs;
vertex_set ignore_ops, considered_args;
for (unsigned i = 0; i < arity; i++) {
argument arg(i + 1);
if (sf.second.find(i) == sf.second.end()) {
ignore_idxs.insert(i);
ignore_ops.insert(arg);
}
else {
considered_args.insert(arg);
}
}
_ignore_idxs_seq.push_back(ignore_idxs);
ignore_ops_seq.push_back(ignore_ops);
considered_args_seq.push_back(considered_args);
sfi++;
}
}
else { // no feature selection within moses
ignore_ops_seq.push_back(_params.ignore_ops);
xmplr_seq.push_back(exemplar);
}
for (unsigned i = 0; i < xmplr_seq.size(); i++) {
if (logger().isDebugEnabled()) {
logger().debug() << "Attempt to build rep from exemplar "
<< "for deme " << demeIDs[i]
<< " : " << xmplr_seq[i];
if (!considered_args_seq.empty())
ostreamContainer(logger().debug() << "Using arguments: ",
considered_args_seq[i]);
}
// Build a representation by adding knobs to the exemplar,
// creating a field set, and a mapping from field set to knobs.
_reps.push_back(new representation(simplify_candidate,
simplify_knob_building,
xmplr_seq[i], _type_sig,
ignore_ops_seq[i],
_params.perceptions,
_params.actions,
_params.linear_contin,
_params.perm_ratio));
// If the representation is empty, try the next
// best-scoring exemplar.
if (_reps.back().fields().empty()) {
_reps.pop_back();
logger().warn("The representation is empty, perhaps the reduct "
"effort for knob building is too high.");
}
}
if (_reps.empty()) return false;
// Create empty demes with their IDs
for (unsigned i = 0; i < _reps.size(); i++)
_demes.push_back(new deme_t(_reps[i].fields(), demeIDs[i]));
return true;
}
vector<unsigned> deme_expander::optimize_demes(int max_evals, time_t max_time)
{
vector<unsigned> actl_evals;
int max_evals_per_deme = max_evals / _demes.size();
for (unsigned i = 0; i < _demes.size(); i++)
{
if (logger().isDebugEnabled()) {
stringstream ss;
ss << "Optimize deme " << _demes[i].getID() << "; "
<< "max evaluations allowed: " << max_evals_per_deme;
logger().debug(ss.str());
}
if (_params.fstor) {
// Attempt to compress the CTable further (to optimize and
// update max score)
_cscorer.ignore_idxs(_ignore_idxs_seq[i]);
// compute the max target for that deme (if features have been
// selected is might be less that the global target)
//
// TODO: DO NOT CHANGE THE MAX SCORE IF USER SET IT: BUT THAT
// OPTION ISN'T GLOBAL WHAT TO DO?
score_t deme_target_score = _cscorer.best_possible_score();
logger().info("Inferred target score for that deme = %g",
deme_target_score);
// negative min_improv is interpreted as percentage of
// improvement, if so then don't substract anything, since in that
// scenario the absolute min improvent can be arbitrarily small
logger().info("It appears there is an algorithmic bug in "
"precision_bscore::best_possible_bscore. "
"Till not fixed we shall not rely on it to "
"terminate deme search");
// TODO: re-enable that once best_possible_bscore is fixed
// score_t actual_min_improv = std::max(_cscorer.min_improv(),
// (score_t)0);
// deme_target_score -= actual_min_improv;
// logger().info("Subtract %g (minimum significant improvement) "
// "from the target score to deal with float "
// "imprecision = %g",
// actual_min_improv, deme_target_score);
// // update max score optimizer
// _optimize.opt_params.terminate_if_gte = deme_target_score;
}
// Optimize
complexity_based_scorer cpx_scorer =
complexity_based_scorer(_cscorer, _reps[i], _params.reduce_all);
actl_evals.push_back(_optimize(_demes[i], cpx_scorer,
max_evals_per_deme, max_time));
}
if (_params.fstor) {
// reset scorer to use all variables (important so that
// behavioral score is consistent across generations
set<arity_t> empty_idxs;
_cscorer.ignore_idxs(empty_idxs);
}
return actl_evals;
}
void deme_expander::free_demes()
{
_ignore_idxs_seq.clear();
_demes.clear();
_reps.clear();
}
} // ~namespace moses
} // ~namespace opencog
<|endoftext|> |
<commit_before><commit_msg>cui: unused code in SvxAreaTabPage::ClickGradientHdl_Impl<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2011 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 <cxxtools/jsonformatter.h>
#include <cxxtools/convert.h>
#include <cxxtools/log.h>
#include <limits>
log_define("cxxtools.jsonformatter")
namespace cxxtools
{
namespace
{
void checkTs(std::basic_ostream<Char>* _ts)
{
if (_ts == 0)
throw std::logic_error("textstream is not set in JsonFormatter");
}
}
void JsonFormatter::begin(std::basic_ostream<Char>& ts)
{
_ts = &ts;
_level = 0;
_lastLevel = -1;
}
void JsonFormatter::finish()
{
log_trace("finish");
if (_beautify)
*_ts << L'\n';
_level = 0;
_lastLevel = -1;
}
void JsonFormatter::addValueString(const std::string& name, const std::string& type,
const String& value)
{
log_trace("addValueString name=\"" << name << "\", type=\"" << type << "\", value=\"" << value << '"');
if (type == "bool")
{
addValueBool(name, type, convert<bool>(value));
}
else if (type == "int")
{
addValueInt(name, type, convert<int_type>(value));
}
else if (type == "double")
{
addValueFloat(name, type, convert<long double>(value));
}
else
{
beginValue(name);
if (type == "null")
{
*_ts << L"null";
}
else
{
*_ts << L'"';
stringOut(value);
*_ts << L'"';
}
finishValue();
}
}
void JsonFormatter::addValueStdString(const std::string& name, const std::string& type,
const std::string& value)
{
log_trace("addValueStdString name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"');
if (type == "bool")
{
addValueBool(name, type, convert<bool>(value));
}
else if (type == "int")
{
addValueInt(name, type, convert<int_type>(value));
}
else if (type == "double")
{
addValueFloat(name, type, convert<long double>(value));
}
else
{
beginValue(name);
if (type == "null")
{
*_ts << L"null";
}
else
{
*_ts << L'"';
stringOut(value);
*_ts << L'"';
}
finishValue();
}
}
void JsonFormatter::addValueBool(const std::string& name, const std::string& type,
bool value)
{
log_trace("addValueBool name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"');
beginValue(name);
*_ts << (value ? L"true" : L"false");
finishValue();
}
void JsonFormatter::addValueInt(const std::string& name, const std::string& type,
int_type value)
{
log_trace("addValueInt name=\"" << name << "\", type=\"" << type << "\", \" value=" << value);
beginValue(name);
if (type == "bool")
*_ts << (value ? L"true" : L"false");
else
*_ts << value;
finishValue();
}
void JsonFormatter::addValueUnsigned(const std::string& name, const std::string& type,
unsigned_type value)
{
log_trace("addValueUnsigned name=\"" << name << "\", type=\"" << type << "\", \" value=" << value);
beginValue(name);
if (type == "bool")
*_ts << (value ? L"true" : L"false");
else
*_ts << value;
finishValue();
}
void JsonFormatter::addValueFloat(const std::string& name, const std::string& type,
long double value)
{
log_trace("addValueFloat name=\"" << name << "\", type=\"" << type << "\", \" value=" << value);
beginValue(name);
if (value != value // check for nan
|| value == std::numeric_limits<long double>::infinity()
|| value == -std::numeric_limits<long double>::infinity())
{
*_ts << L"null";
}
else
{
*_ts << convert<String>(value);
}
finishValue();
}
void JsonFormatter::addNull(const std::string& name, const std::string& type)
{
beginValue(name);
*_ts << L"null";
finishValue();
}
void JsonFormatter::beginArray(const std::string& name, const std::string& type)
{
checkTs(_ts);
if (_level == _lastLevel)
{
*_ts << L',';
if (_beautify)
*_ts << L'\n';
}
else
_lastLevel = _level;
if (_beautify)
indent();
++_level;
if (!name.empty())
{
*_ts << L'"';
stringOut(name);
*_ts << L'"'
<< L':';
if (_beautify)
*_ts << L' ';
}
*_ts << L'[';
if (_beautify)
*_ts << L'\n';
}
void JsonFormatter::finishArray()
{
checkTs(_ts);
--_level;
_lastLevel = _level;
if (_beautify)
{
*_ts << L'\n';
indent();
}
*_ts << L']';
}
void JsonFormatter::beginObject(const std::string& name, const std::string& type)
{
checkTs(_ts);
log_trace("beginObject name=\"" << name << '"');
if (_level == _lastLevel)
{
*_ts << L',';
if (_beautify)
*_ts << L'\n';
}
else
_lastLevel = _level;
if (_beautify)
indent();
++_level;
if (!name.empty())
{
*_ts << L'"';
stringOut(name);
*_ts << L'"'
<< L':';
if (_beautify)
*_ts << L' ';
}
*_ts << L'{';
if (_beautify)
*_ts << L'\n';
}
void JsonFormatter::beginMember(const std::string& name)
{
}
void JsonFormatter::finishMember()
{
}
void JsonFormatter::finishObject()
{
checkTs(_ts);
log_trace("finishObject");
--_level;
_lastLevel = _level;
if (_beautify)
{
*_ts << L'\n';
indent();
}
*_ts << L'}';
}
void JsonFormatter::indent()
{
for (unsigned n = 0; n < _level; ++n)
*_ts << L'\t';
}
void JsonFormatter::stringOut(const std::string& str)
{
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it == '"')
*_ts << L'\\'
<< L'\"';
else if (*it == '\\')
*_ts << L'\\'
<< L'\\';
else if (*it == '\b')
*_ts << L'\\'
<< L'b';
else if (*it == '\f')
*_ts << L'\\'
<< L'f';
else if (*it == '\n')
*_ts << L'\\'
<< L'n';
else if (*it == '\r')
*_ts << L'\\'
<< L'r';
else if (*it == '\t')
*_ts << L'\\'
<< L't';
else if (static_cast<unsigned char>(*it) >= 0x80 || static_cast<unsigned char>(*it) < 0x20)
{
*_ts << L'\\'
<< L'u';
static const char hex[] = "0123456789abcdef";
uint32_t v = static_cast<unsigned char>(*it);
for (uint32_t s = 16; s > 0; s -= 4)
{
*_ts << Char(hex[(v >> (s - 4)) & 0xf]);
}
}
else
*_ts << Char(*it);
}
}
void JsonFormatter::stringOut(const cxxtools::String& str)
{
for (cxxtools::String::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it == L'"')
*_ts << L'\\'
<< L'\"';
else if (*it == L'\\')
*_ts << L'\\'
<< L'\\';
else if (*it == L'\b')
*_ts << L'\\'
<< L'b';
else if (*it == L'\f')
*_ts << L'\\'
<< L'f';
else if (*it == L'\n')
*_ts << L'\\'
<< L'n';
else if (*it == L'\r')
*_ts << L'\\'
<< L'r';
else if (*it == L'\t')
*_ts << L'\\'
<< L't';
else if (it->value() >= 0x80 || it->value() < 0x20)
{
*_ts << L'\\'
<< L'u';
static const char hex[] = "0123456789abcdef";
uint32_t v = it->value();
for (uint32_t s = 16; s > 0; s -= 4)
{
*_ts << Char(hex[(v >> (s - 4)) & 0xf]);
}
}
else
*_ts << *it;
}
}
void JsonFormatter::beginValue(const std::string& name)
{
checkTs(_ts);
if (_level == _lastLevel)
{
*_ts << L',';
if (_beautify)
{
if (name.empty())
*_ts << L' ';
else
{
*_ts << L'\n';
indent();
}
}
}
else
{
_lastLevel = _level;
if (_beautify)
indent();
}
if (!name.empty())
{
*_ts << L'"';
stringOut(name);
*_ts << L'"'
<< L':';
if (_beautify)
*_ts << L' ';
}
++_level;
}
void JsonFormatter::finishValue()
{
--_level;
}
}
<commit_msg>do not convert string values to double and back in json formatter when doubles are serialized as strings<commit_after>/*
* Copyright (C) 2011 Tommi Maekitalo
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 <cxxtools/jsonformatter.h>
#include <cxxtools/convert.h>
#include <cxxtools/log.h>
#include <limits>
log_define("cxxtools.jsonformatter")
namespace cxxtools
{
namespace
{
void checkTs(std::basic_ostream<Char>* _ts)
{
if (_ts == 0)
throw std::logic_error("textstream is not set in JsonFormatter");
}
}
void JsonFormatter::begin(std::basic_ostream<Char>& ts)
{
_ts = &ts;
_level = 0;
_lastLevel = -1;
}
void JsonFormatter::finish()
{
log_trace("finish");
if (_beautify)
*_ts << L'\n';
_level = 0;
_lastLevel = -1;
}
void JsonFormatter::addValueString(const std::string& name, const std::string& type,
const String& value)
{
log_trace("addValueString name=\"" << name << "\", type=\"" << type << "\", value=\"" << value << '"');
if (type == "bool")
{
addValueBool(name, type, convert<bool>(value));
}
else
{
beginValue(name);
if (type == "int" || type == "double")
{
stringOut(value);
}
else if (type == "null")
{
*_ts << L"null";
}
else
{
*_ts << L'"';
stringOut(value);
*_ts << L'"';
}
finishValue();
}
}
void JsonFormatter::addValueStdString(const std::string& name, const std::string& type,
const std::string& value)
{
log_trace("addValueStdString name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"');
if (type == "bool")
{
addValueBool(name, type, convert<bool>(value));
}
else
{
beginValue(name);
if (type == "int" || type == "double")
{
stringOut(value);
}
else if (type == "null")
{
*_ts << L"null";
}
else
{
*_ts << L'"';
stringOut(value);
*_ts << L'"';
}
finishValue();
}
}
void JsonFormatter::addValueBool(const std::string& name, const std::string& type,
bool value)
{
log_trace("addValueBool name=\"" << name << "\", type=\"" << type << "\", \" value=\"" << value << '"');
beginValue(name);
*_ts << (value ? L"true" : L"false");
finishValue();
}
void JsonFormatter::addValueInt(const std::string& name, const std::string& type,
int_type value)
{
log_trace("addValueInt name=\"" << name << "\", type=\"" << type << "\", \" value=" << value);
beginValue(name);
if (type == "bool")
*_ts << (value ? L"true" : L"false");
else
*_ts << value;
finishValue();
}
void JsonFormatter::addValueUnsigned(const std::string& name, const std::string& type,
unsigned_type value)
{
log_trace("addValueUnsigned name=\"" << name << "\", type=\"" << type << "\", \" value=" << value);
beginValue(name);
if (type == "bool")
*_ts << (value ? L"true" : L"false");
else
*_ts << value;
finishValue();
}
void JsonFormatter::addValueFloat(const std::string& name, const std::string& type,
long double value)
{
log_trace("addValueFloat name=\"" << name << "\", type=\"" << type << "\", \" value=" << value);
beginValue(name);
if (value != value // check for nan
|| value == std::numeric_limits<long double>::infinity()
|| value == -std::numeric_limits<long double>::infinity())
{
*_ts << L"null";
}
else
{
*_ts << convert<String>(value);
}
finishValue();
}
void JsonFormatter::addNull(const std::string& name, const std::string& type)
{
beginValue(name);
*_ts << L"null";
finishValue();
}
void JsonFormatter::beginArray(const std::string& name, const std::string& type)
{
checkTs(_ts);
if (_level == _lastLevel)
{
*_ts << L',';
if (_beautify)
*_ts << L'\n';
}
else
_lastLevel = _level;
if (_beautify)
indent();
++_level;
if (!name.empty())
{
*_ts << L'"';
stringOut(name);
*_ts << L'"'
<< L':';
if (_beautify)
*_ts << L' ';
}
*_ts << L'[';
if (_beautify)
*_ts << L'\n';
}
void JsonFormatter::finishArray()
{
checkTs(_ts);
--_level;
_lastLevel = _level;
if (_beautify)
{
*_ts << L'\n';
indent();
}
*_ts << L']';
}
void JsonFormatter::beginObject(const std::string& name, const std::string& type)
{
checkTs(_ts);
log_trace("beginObject name=\"" << name << '"');
if (_level == _lastLevel)
{
*_ts << L',';
if (_beautify)
*_ts << L'\n';
}
else
_lastLevel = _level;
if (_beautify)
indent();
++_level;
if (!name.empty())
{
*_ts << L'"';
stringOut(name);
*_ts << L'"'
<< L':';
if (_beautify)
*_ts << L' ';
}
*_ts << L'{';
if (_beautify)
*_ts << L'\n';
}
void JsonFormatter::beginMember(const std::string& name)
{
}
void JsonFormatter::finishMember()
{
}
void JsonFormatter::finishObject()
{
checkTs(_ts);
log_trace("finishObject");
--_level;
_lastLevel = _level;
if (_beautify)
{
*_ts << L'\n';
indent();
}
*_ts << L'}';
}
void JsonFormatter::indent()
{
for (unsigned n = 0; n < _level; ++n)
*_ts << L'\t';
}
void JsonFormatter::stringOut(const std::string& str)
{
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it == '"')
*_ts << L'\\'
<< L'\"';
else if (*it == '\\')
*_ts << L'\\'
<< L'\\';
else if (*it == '\b')
*_ts << L'\\'
<< L'b';
else if (*it == '\f')
*_ts << L'\\'
<< L'f';
else if (*it == '\n')
*_ts << L'\\'
<< L'n';
else if (*it == '\r')
*_ts << L'\\'
<< L'r';
else if (*it == '\t')
*_ts << L'\\'
<< L't';
else if (static_cast<unsigned char>(*it) >= 0x80 || static_cast<unsigned char>(*it) < 0x20)
{
*_ts << L'\\'
<< L'u';
static const char hex[] = "0123456789abcdef";
uint32_t v = static_cast<unsigned char>(*it);
for (uint32_t s = 16; s > 0; s -= 4)
{
*_ts << Char(hex[(v >> (s - 4)) & 0xf]);
}
}
else
*_ts << Char(*it);
}
}
void JsonFormatter::stringOut(const cxxtools::String& str)
{
for (cxxtools::String::const_iterator it = str.begin(); it != str.end(); ++it)
{
if (*it == L'"')
*_ts << L'\\'
<< L'\"';
else if (*it == L'\\')
*_ts << L'\\'
<< L'\\';
else if (*it == L'\b')
*_ts << L'\\'
<< L'b';
else if (*it == L'\f')
*_ts << L'\\'
<< L'f';
else if (*it == L'\n')
*_ts << L'\\'
<< L'n';
else if (*it == L'\r')
*_ts << L'\\'
<< L'r';
else if (*it == L'\t')
*_ts << L'\\'
<< L't';
else if (it->value() >= 0x80 || it->value() < 0x20)
{
*_ts << L'\\'
<< L'u';
static const char hex[] = "0123456789abcdef";
uint32_t v = it->value();
for (uint32_t s = 16; s > 0; s -= 4)
{
*_ts << Char(hex[(v >> (s - 4)) & 0xf]);
}
}
else
*_ts << *it;
}
}
void JsonFormatter::beginValue(const std::string& name)
{
checkTs(_ts);
if (_level == _lastLevel)
{
*_ts << L',';
if (_beautify)
{
if (name.empty())
*_ts << L' ';
else
{
*_ts << L'\n';
indent();
}
}
}
else
{
_lastLevel = _level;
if (_beautify)
indent();
}
if (!name.empty())
{
*_ts << L'"';
stringOut(name);
*_ts << L'"'
<< L':';
if (_beautify)
*_ts << L' ';
}
++_level;
}
void JsonFormatter::finishValue()
{
--_level;
}
}
<|endoftext|> |
<commit_before>/* Copyright 2014 Peter Goodman, all rights reserved. */
#ifdef GRANARY_WHERE_user
#include <granary.h>
#include "clients/user/signal.h"
#include "clients/user/syscall.h"
using namespace granary;
GRANARY_DEFINE_bool(debug_gdb_prompt, true,
"Should a GDB process attacher helper be printed out on startup? Default "
"is `yes`.",
"gdb");
extern "C" {
extern int getpid(void);
extern long long write(int __fd, const void *__buf, size_t __n);
extern long long read(int __fd, void *__buf, size_t __nbytes);
} // extern C
namespace {
// Initialize Granary for debugging by GDB. For example, if one is doing:
//
// grr --tools=foo -- ls
//
// Then in another terminal, one can do:
//
// sudo gdb /bin/ls
// (gdb) a <pid that is printed out>
// (gdb) c
//
// Then press the ENTER key in the origin terminal (where `grr ... ls` is) to
// continue execution under GDB's supervision.
extern "C" void AwaitAttach(int signum, void *siginfo, void *context) {
char buff[1024];
auto num_bytes = Format(
buff, sizeof buff,
"Process ID for attaching GDB: %d\nPress enter to continue.\n",
getpid());
write(1, buff, num_bytes);
read(0, buff, 1);
// Useful for debugging purposes.
GRANARY_USED(signum);
GRANARY_USED(siginfo); // `siginfo_t *`.
GRANARY_USED(context); // `ucontext *` on Linux.
}
// Used to attach a signal handler to an arbitrary signal, such that when the
// signal is triggered, a message is printed to the screen that allows
// Granary to be attached to the process.
static void AwaitAttachOnSignal(int signum) {
struct sigaction new_sigaction;
memset(&new_sigaction, 0, sizeof new_sigaction);
memset(&(new_sigaction.sa_mask), 0xFF, sizeof new_sigaction.sa_mask);
new_sigaction.sa_sigaction = &AwaitAttach;
new_sigaction.sa_flags = SA_SIGINFO;
rt_sigaction(signum, &new_sigaction, nullptr, _NSIG / 8);
}
// Prevents user-space code from replacing the `SIGSEGV` and `SIGILL`
// signal handlers. This is to help in the debugging of user space
// programs, where attaching GDB early on in the program's execution
// causes the bug to disappear.
static void SuppressSigAction(void *, SystemCallContext ctx) {
if (__NR_rt_sigaction != ctx.Number()) return;
// If `act == NULL` then code is querying the current state of the signal
// handler.
if (!ctx.Arg1()) return;
// Turn this `sigaction` into a no-op (that will likely return `-EINVAL`)
auto signum = ctx.Arg0();
if (SIGILL == signum || SIGTRAP == signum ||
SIGBUS == signum || SIGSEGV == signum) {
ctx.Arg0() = SIGUNUSED;
ctx.Arg1() = 0;
ctx.Arg2() = 0;
}
}
} // namespace
// Tool that helps user-space instrumentation work.
class GDBDebuggerHelper : public InstrumentationTool {
public:
virtual ~GDBDebuggerHelper(void) = default;
// Initialize Granary for debugging. This is geared toward GDB-based debugging,
// where we can either attach GDB on program startup. Alternatively, if
// attaching GDB somehow makes the bug being debugged disappear, then we
// register a signal handler for `SEGFAULT`s that will prompt for GDB to be
// attached.
virtual void Init(InitReason) {
if (!FLAG_debug_gdb_prompt) AddSystemCallEntryFunction(SuppressSigAction);
}
// GDB inserts hidden breakpoints into programs, especially in programs
// using `pthreads`. When Granary comes across these breakpoints, it most
// likely will detach, which, when combined with the `transparent_returns`
// tool, results in full thread detaches. Here we try to handle these special
// cases in a completely non-portable way. The comments, however, give
// some guidance as to how to port this.
bool FixHiddenBreakpoints(BlockFactory *factory, ControlFlowInstruction *cfi,
BasicBlock *block) {
auto fixed = false;
auto decoded_pc = block->StartAppPC();
auto module = os::ModuleContainingPC(decoded_pc);
auto module_name = module->Name();
auto offset = module->OffsetOfPC(decoded_pc);
auto call_native = false;
if (StringsMatch("ld", module_name)) {
// `__GI__dl_debug_state` (or just `_dl_debug_state`), which is just a
// simple return.
call_native = 0x10970 == offset.offset;
} else if (StringsMatch("libpthread", module_name)) {
// `__GI___nptl_create_event` and `__GI___nptl_death_event`.
call_native = 0x6f50 == offset.offset || 0x6f60 == offset.offset;
}
// GDB somtimes puts `int3`s on specific functions so that I knows when key
// events (e.g. thread creation) happen.
if (call_native) {
cfi->InsertBefore(lir::Call(factory, decoded_pc, REQUEST_NATIVE));
cfi->InsertBefore(lir::Return(factory));
fixed = true;
}
if (fixed) {
Instruction::Unlink(cfi);
return true;
}
os::Log(os::LogOutput, "code = %p\n", decoded_pc);
os::Log(os::LogOutput, "module = %s\n", module_name);
os::Log(os::LogOutput, "offset = %lx\n\n", offset.offset);
granary_curiosity();
return false;
}
virtual void InstrumentControlFlow(BlockFactory *factory,
LocalControlFlowGraph *cfg) {
for (auto block : cfg->NewBlocks()) {
for (auto succ : block->Successors()) {
if (succ.cfi->HasIndirectTarget()) continue;
if (!IsA<NativeBasicBlock *>(succ.block)) continue;
FixHiddenBreakpoints(factory, succ.cfi, succ.block);
break;
}
}
}
};
// Initialize the `gdb` tool.
GRANARY_CLIENT_INIT({
if (FLAG_debug_gdb_prompt) {
AwaitAttach(-1, nullptr, nullptr);
} else {
AwaitAttachOnSignal(SIGSEGV);
AwaitAttachOnSignal(SIGILL);
AwaitAttachOnSignal(SIGBUS);
AwaitAttachOnSignal(SIGTRAP);
}
RegisterInstrumentationTool<GDBDebuggerHelper>("gdb");
})
#endif // GRANARY_WHERE_user
<commit_msg>Minor fixes to the gdb tool.<commit_after>/* Copyright 2014 Peter Goodman, all rights reserved. */
#ifdef GRANARY_WHERE_user
#include <granary.h>
#include "clients/user/signal.h"
#include "clients/user/syscall.h"
using namespace granary;
GRANARY_DEFINE_bool(debug_gdb_prompt, true,
"Should a GDB process attacher helper be printed out on startup? Default "
"is `yes`.",
"gdb");
extern "C" {
extern int getpid(void);
extern long long write(int __fd, const void *__buf, size_t __n);
extern long long read(int __fd, void *__buf, size_t __nbytes);
} // extern C
namespace {
// Initialize Granary for debugging by GDB. For example, if one is doing:
//
// grr --tools=foo -- ls
//
// Then in another terminal, one can do:
//
// sudo gdb /bin/ls
// (gdb) a <pid that is printed out>
// (gdb) c
//
// Then press the ENTER key in the origin terminal (where `grr ... ls` is) to
// continue execution under GDB's supervision.
extern "C" void AwaitAttach(int signum, void *siginfo, void *context) {
char buff[1024];
auto num_bytes = Format(
buff, sizeof buff,
"Process ID for attaching GDB: %d\nPress enter to continue.\n",
getpid());
write(1, buff, num_bytes);
read(0, buff, 1);
// Useful for debugging purposes.
GRANARY_USED(signum);
GRANARY_USED(siginfo); // `siginfo_t *`.
GRANARY_USED(context); // `ucontext *` on Linux.
}
// Used to attach a signal handler to an arbitrary signal, such that when the
// signal is triggered, a message is printed to the screen that allows
// Granary to be attached to the process.
static void AwaitAttachOnSignal(int signum) {
struct sigaction new_sigaction;
memset(&new_sigaction, 0, sizeof new_sigaction);
memset(&(new_sigaction.sa_mask), 0xFF, sizeof new_sigaction.sa_mask);
new_sigaction.sa_sigaction = &AwaitAttach;
new_sigaction.sa_flags = SA_SIGINFO;
rt_sigaction(signum, &new_sigaction, nullptr, _NSIG / 8);
}
// Prevents user-space code from replacing the `SIGSEGV` and `SIGILL`
// signal handlers. This is to help in the debugging of user space
// programs, where attaching GDB early on in the program's execution
// causes the bug to disappear.
static void SuppressSigAction(void *, SystemCallContext ctx) {
if (__NR_rt_sigaction != ctx.Number()) return;
// If `act == NULL` then code is querying the current state of the signal
// handler.
if (!ctx.Arg1()) return;
// Turn this `sigaction` into a no-op (that will likely return `-EINVAL`)
auto signum = ctx.Arg0();
if (SIGILL == signum || SIGTRAP == signum ||
SIGBUS == signum || SIGSEGV == signum) {
ctx.Arg0() = SIGUNUSED;
ctx.Arg1() = 0;
ctx.Arg2() = 0;
}
}
} // namespace
// Tool that helps user-space instrumentation work.
class GDBDebuggerHelper : public InstrumentationTool {
public:
virtual ~GDBDebuggerHelper(void) = default;
// Initialize Granary for debugging. This is geared toward GDB-based debugging,
// where we can either attach GDB on program startup. Alternatively, if
// attaching GDB somehow makes the bug being debugged disappear, then we
// register a signal handler for `SEGFAULT`s that will prompt for GDB to be
// attached.
virtual void Init(InitReason) {
if (!FLAG_debug_gdb_prompt) AddSystemCallEntryFunction(SuppressSigAction);
}
// GDB inserts hidden breakpoints into programs, especially in programs
// using `pthreads`. When Granary comes across these breakpoints, it most
// likely will detach, which, when combined with the `transparent_returns`
// tool, results in full thread detaches. Here we try to handle these special
// cases in a completely non-portable way. The comments, however, give
// some guidance as to how to port this.
bool FixHiddenBreakpoints(BlockFactory *factory, ControlFlowInstruction *cfi,
BasicBlock *block) {
auto decoded_pc = block->StartAppPC();
auto module = os::ModuleContainingPC(decoded_pc);
auto module_name = module->Name();
auto offset = module->OffsetOfPC(decoded_pc);
auto call_native = false;
if (StringsMatch("ld", module_name)) {
// `__GI__dl_debug_state` (or just `_dl_debug_state`), which is just a
// simple return.
call_native = 0x10970 == offset.offset;
} else if (StringsMatch("libpthread", module_name)) {
// `__GI___nptl_create_event` and `__GI___nptl_death_event`.
call_native = 0x6f50 == offset.offset || 0x6f60 == offset.offset;
}
// GDB somtimes puts `int3`s on specific functions so that it knows when
// key events (e.g. thread creation) happen. Most of these functions are
// basically no-ops, so would can just manually call them recursively).
if (call_native) {
cfi->InsertBefore(lir::Call(factory, decoded_pc, REQUEST_NATIVE));
cfi->InsertBefore(lir::Return(factory));
Instruction::Unlink(cfi);
return true;
}
os::Log(os::LogOutput, "code = %p\nmodule = %s\noffset = %lx\n\n",
decoded_pc, module_name, offset.offset);
return false;
}
virtual void InstrumentControlFlow(BlockFactory *factory,
LocalControlFlowGraph *cfg) {
for (auto block : cfg->NewBlocks()) {
for (auto succ : block->Successors()) {
if (succ.cfi->HasIndirectTarget()) continue;
if (!IsA<NativeBasicBlock *>(succ.block)) continue;
FixHiddenBreakpoints(factory, succ.cfi, succ.block);
break;
}
}
}
};
// Initialize the `gdb` tool.
GRANARY_CLIENT_INIT({
if (FLAG_debug_gdb_prompt) {
AwaitAttach(-1, nullptr, nullptr);
} else {
AwaitAttachOnSignal(SIGSEGV);
AwaitAttachOnSignal(SIGILL);
AwaitAttachOnSignal(SIGBUS);
AwaitAttachOnSignal(SIGTRAP);
}
RegisterInstrumentationTool<GDBDebuggerHelper>("gdb");
})
#endif // GRANARY_WHERE_user
<|endoftext|> |
<commit_before>#include "ScrollingMsg.hpp"
#include <pango/pangocairo.h>
ScrollingMsg::ScrollingMsg()
:m_current_w(0)
,m_current_h(0)
,m_friendly_name("None")
,m_msg("None")
,m_loops(0)
,m_current_loop(0)
,m_fontfamily("Sans Bold 12")
,m_ypos(300)
,m_xpos(0)
,m_scroll_time(12.0f)
{
};
ScrollingMsg::ScrollingMsg( const int width,
const int height,
const std::string& font,
const std::string& friendly_name,
const int& loop,
const std::string& msg,
const double& scroll_time,
const int& y_pos)
:m_current_w(width)
,m_current_h(height)
,m_friendly_name(friendly_name)
,m_msg(msg)
,m_loops(loop)
,m_current_loop(0)
,m_fontfamily(font)
,m_ypos(y_pos)
,m_xpos(width)
,m_scroll_time(scroll_time)
{
};
void ScrollingMsg::Resize(const int width, const int height) {
m_current_w = width;
m_current_h = height;
};
void ScrollingMsg::Update(const float dt)
{
//TODO: separate update and drawing of msg to facilitate different ordering.
};
void ScrollingMsg::Draw(cairo_t* context, const float dt)
{
cairo_save(context);
PangoLayout *pango_layout;
PangoFontDescription *pango_fontdesc;
pango_layout = pango_cairo_create_layout(context);
pango_layout_set_text(pango_layout, m_msg.c_str(), -1);
pango_fontdesc = pango_font_description_from_string(m_fontfamily.c_str());
pango_layout_set_font_description(pango_layout, pango_fontdesc);
pango_font_description_free(pango_fontdesc);
cairo_text_extents_t te;
cairo_set_source_rgb (context, 1.0, 1.0, 0.0);
PangoRectangle ink_rect, logical_rect;
pango_layout_get_pixel_extents(pango_layout, &ink_rect, &logical_rect);
//d_pos = d/t * dt
m_xpos -= ((m_current_w + ink_rect.width)/m_scroll_time)*dt;
if(m_xpos<(-1.0f*ink_rect.width)) {//wraparound
m_xpos = m_current_w;
m_current_loop += 1;
if(m_current_loop==m_loops) {
m_current_loop = -1;//indicates controller should remove this msg.
}
}
cairo_translate(context, m_xpos, m_ypos);
pango_cairo_update_layout(context, pango_layout);
pango_cairo_show_layout(context, pango_layout);
g_object_unref(pango_layout);
cairo_restore (context);
}
ScrollingMsgController::ScrollingMsgController()
{
}
void ScrollingMsgController::AddMsg(const int width,
const int height,
const std::string& font,
const std::string& friendly_name,
const int& loop,
const std::string& msg,
const double& scroll_time,
const int& y_pos)
{
if(m_msgs.find(friendly_name)==m_msgs.end()) {
m_msgs[friendly_name]=ScrollingMsg(width, height, font, friendly_name, loop, msg, scroll_time, y_pos);
}
}
void ScrollingMsgController::RemoveMsg(const std::string& friendly_name)
{
std::map< std::string, ScrollingMsg >::iterator msg = m_msgs.find(friendly_name);
if(msg!=m_msgs.end())
{
m_msgs.erase(msg);
}
};
void ScrollingMsgController::Update(float dt) {
for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin();
imsg!=m_msgs.end();)
{
imsg->second.Update(dt);
//remove those msgs that are 'done'
if(imsg->second.CurrentLoop()<0) {
imsg = m_msgs.erase(imsg);
}else{
++imsg;
}
}
};
void ScrollingMsgController::Draw(cairo_t* context, const float dt) {
for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin();
imsg!=m_msgs.end(); ++imsg)
{
imsg->second.Draw(context, dt);
}
}
void ScrollingMsgController::Resize(const int width, const int height) {
for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin();
imsg!=m_msgs.end(); ++imsg)
{
imsg->second.Resize(width, height);
}
}
<commit_msg>Added support for pango markup.<commit_after>#include "ScrollingMsg.hpp"
#include <pango/pangocairo.h>
ScrollingMsg::ScrollingMsg()
:m_current_w(0)
,m_current_h(0)
,m_friendly_name("None")
,m_msg("None")
,m_loops(0)
,m_current_loop(0)
,m_fontfamily("Sans Bold 12")
,m_ypos(300)
,m_xpos(0)
,m_scroll_time(12.0f)
{
};
ScrollingMsg::ScrollingMsg( const int width,
const int height,
const std::string& font,
const std::string& friendly_name,
const int& loop,
const std::string& msg,
const double& scroll_time,
const int& y_pos)
:m_current_w(width)
,m_current_h(height)
,m_friendly_name(friendly_name)
,m_msg(msg)
,m_loops(loop)
,m_current_loop(0)
,m_fontfamily(font)
,m_ypos(y_pos)
,m_xpos(width)
,m_scroll_time(scroll_time)
{
};
void ScrollingMsg::Resize(const int width, const int height) {
m_current_w = width;
m_current_h = height;
};
void ScrollingMsg::Update(const float dt)
{
//TODO: separate update and drawing of msg to facilitate different ordering.
};
void ScrollingMsg::Draw(cairo_t* context, const float dt)
{
cairo_save(context);
PangoLayout *pango_layout;
PangoFontDescription *pango_fontdesc;
pango_layout = pango_cairo_create_layout(context);
PangoAttrList* pTextAttributes = pango_attr_list_new();
gchar *text = 0;//stupidly gchar disallows deallocation, but not in code
if(!pango_parse_markup (m_msg.c_str(),
-1,//null terminated text string above
0,//no accellerated marker
&pTextAttributes,
&text,
NULL,
NULL))
{
}
pango_layout_set_text(pango_layout, text, -1);
pango_layout_set_attributes (pango_layout, pTextAttributes);
pango_attr_list_unref(pTextAttributes);
pango_fontdesc = pango_font_description_from_string(m_fontfamily.c_str());
pango_layout_set_font_description(pango_layout, pango_fontdesc);
pango_font_description_free(pango_fontdesc);
cairo_text_extents_t te;
cairo_set_source_rgb (context, 1.0, 1.0, 0.0);
PangoRectangle ink_rect, logical_rect;
pango_layout_get_pixel_extents(pango_layout, &ink_rect, &logical_rect);
//d_pos = d/t * dt
m_xpos -= ((m_current_w + ink_rect.width)/m_scroll_time)*dt;
if(m_xpos<(-1.0f*ink_rect.width)) {//wraparound
m_xpos = m_current_w;
m_current_loop += 1;
if(m_current_loop==m_loops) {
m_current_loop = -1;//indicates controller should remove this msg.
}
}
cairo_translate(context, m_xpos, m_ypos);
pango_cairo_update_layout(context, pango_layout);
pango_cairo_show_layout(context, pango_layout);
g_object_unref(pango_layout);
cairo_restore (context);
}
ScrollingMsgController::ScrollingMsgController()
{
}
void ScrollingMsgController::AddMsg(const int width,
const int height,
const std::string& font,
const std::string& friendly_name,
const int& loop,
const std::string& msg,
const double& scroll_time,
const int& y_pos)
{
if(m_msgs.find(friendly_name)==m_msgs.end()) {
m_msgs[friendly_name]=ScrollingMsg(width, height, font, friendly_name, loop, msg, scroll_time, y_pos);
}
}
void ScrollingMsgController::RemoveMsg(const std::string& friendly_name)
{
std::map< std::string, ScrollingMsg >::iterator msg = m_msgs.find(friendly_name);
if(msg!=m_msgs.end())
{
m_msgs.erase(msg);
}
};
void ScrollingMsgController::Update(float dt) {
for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin();
imsg!=m_msgs.end();)
{
imsg->second.Update(dt);
//remove those msgs that are 'done'
if(imsg->second.CurrentLoop()<0) {
imsg = m_msgs.erase(imsg);
}else{
++imsg;
}
}
};
void ScrollingMsgController::Draw(cairo_t* context, const float dt) {
for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin();
imsg!=m_msgs.end(); ++imsg)
{
imsg->second.Draw(context, dt);
}
}
void ScrollingMsgController::Resize(const int width, const int height) {
for(std::map< std::string, ScrollingMsg >::iterator imsg=m_msgs.begin();
imsg!=m_msgs.end(); ++imsg)
{
imsg->second.Resize(width, height);
}
}
<|endoftext|> |
<commit_before>#include "otbVectorImage.h"
#include "otbVectorRescaleIntensityImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageAlternateViewer.h"
#include "Fl/Fl.H"
int otbAlternateViewerTest(int argc, char* argv[])
{
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::VectorImage<PixelType,Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageAlternateViewer<PixelType> ViewerType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
reader->GenerateOutputInformation();
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName(argv[2]);
reader2->GenerateOutputInformation();
ImageType::PixelType min,max;
min.SetSize(reader->GetOutput()->GetNumberOfComponentsPerPixel());
max.SetSize(reader->GetOutput()->GetNumberOfComponentsPerPixel());
// min[0]=195;
// min[1]=241;
// min[2]=127;
// min[3]=130;
// max[0]=387;
// max[1]=602;
// max[2]=469;
// max[3]=740;
min.Fill(0);
max.Fill(255);
// RescalerType::Pointer rescaler = RescalerType::New();
// rescaler->SetOutputMinimum(min);
// rescaler->SetOutputMaximum(max);
// rescaler->SetInput(reader->GetOutput());
// rescaler->SetClampThreshold(atof(argv[2]));
// rescaler->GenerateOutputInformation();
Fl_Window window(512,512);
ViewerType::Pointer viewer = ViewerType::New();
viewer->SetImage(reader->GetOutput());
viewer->SetSecondImage(reader2->GetOutput());
viewer->SetMinComponentValues(min);
viewer->SetMaxComponentValues(max);
viewer->SetRedChannelIndex(atoi(argv[3]));
viewer->SetGreenChannelIndex(atoi(argv[4]));
viewer->SetBlueChannelIndex(atoi(argv[5]));
window.end();
window.resizable(viewer.GetPointer());
viewer->Init("test de la nouvelle visu");
window.show();
viewer->Show();
Fl::run();
return EXIT_SUCCESS;
}
<commit_msg>FIX: Fl::check()<commit_after>#include "otbVectorImage.h"
#include "otbVectorRescaleIntensityImageFilter.h"
#include "otbImageFileReader.h"
#include "otbImageAlternateViewer.h"
#include "Fl/Fl.H"
int otbAlternateViewerTest(int argc, char* argv[])
{
const unsigned int Dimension = 2;
typedef double PixelType;
typedef otb::VectorImage<PixelType,Dimension> ImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageAlternateViewer<PixelType> ViewerType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(argv[1]);
reader->GenerateOutputInformation();
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName(argv[2]);
reader2->GenerateOutputInformation();
ImageType::PixelType min,max;
min.SetSize(reader->GetOutput()->GetNumberOfComponentsPerPixel());
max.SetSize(reader->GetOutput()->GetNumberOfComponentsPerPixel());
// min[0]=195;
// min[1]=241;
// min[2]=127;
// min[3]=130;
// max[0]=387;
// max[1]=602;
// max[2]=469;
// max[3]=740;
min.Fill(0);
max.Fill(255);
// RescalerType::Pointer rescaler = RescalerType::New();
// rescaler->SetOutputMinimum(min);
// rescaler->SetOutputMaximum(max);
// rescaler->SetInput(reader->GetOutput());
// rescaler->SetClampThreshold(atof(argv[2]));
// rescaler->GenerateOutputInformation();
Fl_Window window(512,512);
ViewerType::Pointer viewer = ViewerType::New();
viewer->SetImage(reader->GetOutput());
viewer->SetSecondImage(reader2->GetOutput());
viewer->SetMinComponentValues(min);
viewer->SetMaxComponentValues(max);
viewer->SetRedChannelIndex(atoi(argv[3]));
viewer->SetGreenChannelIndex(atoi(argv[4]));
viewer->SetBlueChannelIndex(atoi(argv[5]));
window.end();
window.resizable(viewer.GetPointer());
viewer->Init("test de la nouvelle visu");
window.show();
viewer->Show();
Fl::check();
// Fl::run();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "UnreferencedInterfaces.h"
#include "ClassHierarchy.h"
#include "DexAnnotation.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "IROpcode.h"
#include "Resolver.h"
#include "Trace.h"
#include "Walkers.h"
namespace {
void update_scope(const TypeSet& removable, Scope& scope) {
if (removable.empty()) return;
Scope tscope(scope);
scope.clear();
for (DexClass* cls : tscope) {
if (removable.count(cls->get_type()) > 0) {
TRACE(UNREF_INTF, 3, "Removing interface %s", SHOW(cls));
} else {
scope.push_back(cls);
}
}
}
void get_super_interfaces(TypeSet& interfaces, DexClass* intf) {
const auto super_intfs = intf->get_interfaces()->get_type_list();
for (const auto super : super_intfs) {
interfaces.insert(super);
auto super_intf = type_class(super);
if (super_intf != nullptr) {
get_super_interfaces(interfaces, super_intf);
}
}
}
void get_interfaces(TypeSet& interfaces, DexClass* cls) {
const auto intfs = cls->get_interfaces()->get_type_list();
for (const auto& intf : intfs) {
interfaces.insert(intf);
const auto intf_cls = type_class(intf);
get_super_interfaces(interfaces, intf_cls);
}
const auto super = type_class(cls->get_super_class());
if (super != nullptr) {
get_interfaces(interfaces, super);
}
}
// Collect candidate interfaces that could be safe to remove
TypeSet collect_interfaces(
const Scope& scope, UnreferencedInterfacesPass::Metric& metric) {
TypeSet candidates;
for (const auto& cls : scope) {
if (!is_interface(cls)) continue;
if (!can_delete(cls)) continue;
if (!cls->get_sfields().empty()) continue;
candidates.insert(cls->get_type());
metric.candidates++;
}
// Exclude interfaces implemented by abstract classes.
// Things could get complicated.
for (const auto& cls : scope) {
if (is_interface(cls) || !is_abstract(cls)) continue;
// Only abstract classes
TypeSet implemented;
get_interfaces(implemented, cls);
for (const auto& intf : implemented) {
if (candidates.count(intf) > 0) {
candidates.erase(intf);
metric.on_abstract_cls++;
}
}
}
std::vector<const DexType*> external;
for (const auto& intf : candidates) {
const auto cls = type_class(intf);
if (cls == nullptr || cls->is_external()) {
external.emplace_back(intf);
}
}
for (const auto& intf : external) {
metric.external += candidates.erase(intf);
}
return candidates;
}
void remove_referenced(const Scope& scope,
TypeSet& candidates,
UnreferencedInterfacesPass::Metric& metric) {
const auto check_type = [&](DexType* t, size_t& count) {
const auto type = get_array_type_or_self(t);
if (candidates.count(type) > 0) {
candidates.erase(type);
count++;
}
};
walk::fields(scope,
[&](DexField* field) {
check_type(field->get_type(), metric.field_refs);
});
walk::methods(scope,
[&](DexMethod* meth) {
const auto proto = meth->get_proto();
check_type(proto->get_rtype(), metric.sig_refs);
for (const auto& type : proto->get_args()->get_type_list()) {
check_type(type, metric.sig_refs);
}
});
walk::annotations(scope,
[&](DexAnnotation* anno) {
std::vector<DexType*> types_in_anno;
anno->gather_types(types_in_anno);
for (const auto& type : types_in_anno) {
check_type(type, metric.anno_refs);
}
});
walk::opcodes(scope,
[](DexMethod*) { return true; },
[&](DexMethod*, IRInstruction* insn) {
if (insn->has_type()) {
check_type(insn->get_type(), metric.insn_refs);
return;
}
std::vector<DexType*> types_in_insn;
if (insn->has_field()) {
insn->get_field()->gather_types_shallow(types_in_insn);
} else if (insn->has_method()) {
insn->get_method()->gather_types_shallow(types_in_insn);
}
for (const auto type : types_in_insn) {
check_type(type, metric.insn_refs);
}
if (!insn->has_method()) return;
const auto opcode = insn->opcode();
DexMethod* meth = nullptr;
if (opcode == OPCODE_INVOKE_VIRTUAL) {
meth = resolve_method(insn->get_method(), MethodSearch::Virtual);
} else if (opcode == OPCODE_INVOKE_INTERFACE) {
meth = resolve_method(insn->get_method(), MethodSearch::Interface);
} else {
return;
}
if (meth != nullptr) {
check_type(meth->get_class(), metric.insn_refs);
return;
}
// the method resolved to nothing which is odd but there are
// cases where it happens (OS versions, virtual call on an
// unimplemented interface method, etc.).
// To be safe let's remove every interface involved in this branch
const auto& cls = type_class(insn->get_method()->get_class());
if (cls == nullptr) return;
TypeSet intfs;
if (is_interface(cls)) {
intfs.insert(cls->get_type());
get_super_interfaces(intfs, cls);
} else {
get_interfaces(intfs, cls);
}
for (const auto& intf : intfs) {
metric.unresolved_meths += candidates.erase(intf);
}
});
}
bool implements_removables(const TypeSet& removable, DexClass* cls) {
for (const auto intf : cls->get_interfaces()->get_type_list()) {
if (removable.count(intf) > 0) {
return true;
}
}
return false;
}
void get_impls(DexType* intf,
const TypeSet& removable,
std::set<DexType*, dextypes_comparator>& new_intfs) {
const auto cls_intf = type_class(intf);
if (cls_intf == nullptr) return;
for (const auto& super_intf : cls_intf->get_interfaces()->get_type_list()) {
if (removable.count(super_intf) == 0) {
new_intfs.insert(super_intf);
continue;
}
get_impls(super_intf, removable, new_intfs);
}
};
void set_new_impl_list(const TypeSet& removable, DexClass* cls) {
TRACE(UNREF_INTF, 3, "Changing implements for %s:\n\tfrom %s",
SHOW(cls), SHOW(cls->get_interfaces()));
std::set<DexType*, dextypes_comparator> new_intfs;
for (const auto& intf : cls->get_interfaces()->get_type_list()) {
if (removable.count(intf) == 0) {
new_intfs.insert(intf);
continue;
}
get_impls(intf, removable, new_intfs);
}
std::deque<DexType*> deque;
for (const auto& intf : new_intfs) {
deque.emplace_back(intf);
}
auto implements = DexTypeList::make_type_list(std::move(deque));
TRACE(UNREF_INTF, 3, "\tto %s", SHOW(implements));
cls->set_interfaces(implements);
}
} // namespace
void UnreferencedInterfacesPass::run_pass(
DexStoresVector& stores, ConfigFiles& /*cfg*/, PassManager& mgr) {
auto scope = build_class_scope(stores);
auto removable = collect_interfaces(scope, m_metric);
remove_referenced(scope, removable, m_metric);
for (const auto& cls : scope) {
if (!implements_removables(removable, cls)) {
continue;
}
m_metric.updated_impls++;
set_new_impl_list(removable, cls);
}
m_metric.removed = removable.size();
update_scope(removable, scope);
post_dexen_changes(scope, stores);
TRACE(UNREF_INTF, 1, "candidates %ld", m_metric.candidates);
TRACE(UNREF_INTF, 1, "external %ld", m_metric.external);
TRACE(UNREF_INTF, 1, "on abstract classes %ld", m_metric.on_abstract_cls);
TRACE(UNREF_INTF, 1, "field references %ld", m_metric.field_refs);
TRACE(UNREF_INTF, 1, "signature references %ld", m_metric.sig_refs);
TRACE(UNREF_INTF, 1, "instruction references %ld", m_metric.insn_refs);
TRACE(UNREF_INTF, 1, "annotation references %ld", m_metric.anno_refs);
TRACE(UNREF_INTF, 1, "unresolved methods %ld",
m_metric.unresolved_meths);
TRACE(UNREF_INTF, 1, "updated implementations %ld", m_metric.updated_impls);
TRACE(UNREF_INTF, 1, "removable %ld", m_metric.removed);
mgr.set_metric("updated implementations", m_metric.updated_impls);
mgr.set_metric("removed_interfaces", m_metric.removed);
}
static UnreferencedInterfacesPass s_pass;
<commit_msg>fix UnreferencedInterfaces crash<commit_after>/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "UnreferencedInterfaces.h"
#include "ClassHierarchy.h"
#include "DexAnnotation.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "IROpcode.h"
#include "Resolver.h"
#include "Trace.h"
#include "Walkers.h"
namespace {
void update_scope(const TypeSet& removable, Scope& scope) {
if (removable.empty()) return;
Scope tscope(scope);
scope.clear();
for (DexClass* cls : tscope) {
if (removable.count(cls->get_type()) > 0) {
TRACE(UNREF_INTF, 3, "Removing interface %s", SHOW(cls));
} else {
scope.push_back(cls);
}
}
}
void get_super_interfaces(TypeSet& interfaces, DexClass* intf) {
const auto super_intfs = intf->get_interfaces()->get_type_list();
for (const auto super : super_intfs) {
interfaces.insert(super);
auto super_intf = type_class(super);
if (super_intf != nullptr) {
get_super_interfaces(interfaces, super_intf);
}
}
}
void get_interfaces(TypeSet& interfaces, DexClass* cls) {
const auto intfs = cls->get_interfaces()->get_type_list();
for (const auto& intf : intfs) {
interfaces.insert(intf);
const auto intf_cls = type_class(intf);
if (intf_cls != nullptr) {
get_super_interfaces(interfaces, intf_cls);
}
}
const auto super = type_class(cls->get_super_class());
if (super != nullptr) {
get_interfaces(interfaces, super);
}
}
// Collect candidate interfaces that could be safe to remove
TypeSet collect_interfaces(
const Scope& scope, UnreferencedInterfacesPass::Metric& metric) {
TypeSet candidates;
for (const auto& cls : scope) {
if (!is_interface(cls)) continue;
if (!can_delete(cls)) continue;
if (!cls->get_sfields().empty()) continue;
candidates.insert(cls->get_type());
metric.candidates++;
}
// Exclude interfaces implemented by abstract classes.
// Things could get complicated.
for (const auto& cls : scope) {
if (is_interface(cls) || !is_abstract(cls)) continue;
// Only abstract classes
TypeSet implemented;
get_interfaces(implemented, cls);
for (const auto& intf : implemented) {
if (candidates.count(intf) > 0) {
candidates.erase(intf);
metric.on_abstract_cls++;
}
}
}
std::vector<const DexType*> external;
for (const auto& intf : candidates) {
const auto cls = type_class(intf);
if (cls == nullptr || cls->is_external()) {
external.emplace_back(intf);
}
}
for (const auto& intf : external) {
metric.external += candidates.erase(intf);
}
return candidates;
}
void remove_referenced(const Scope& scope,
TypeSet& candidates,
UnreferencedInterfacesPass::Metric& metric) {
const auto check_type = [&](DexType* t, size_t& count) {
const auto type = get_array_type_or_self(t);
if (candidates.count(type) > 0) {
candidates.erase(type);
count++;
}
};
walk::fields(scope,
[&](DexField* field) {
check_type(field->get_type(), metric.field_refs);
});
walk::methods(scope,
[&](DexMethod* meth) {
const auto proto = meth->get_proto();
check_type(proto->get_rtype(), metric.sig_refs);
for (const auto& type : proto->get_args()->get_type_list()) {
check_type(type, metric.sig_refs);
}
});
walk::annotations(scope,
[&](DexAnnotation* anno) {
std::vector<DexType*> types_in_anno;
anno->gather_types(types_in_anno);
for (const auto& type : types_in_anno) {
check_type(type, metric.anno_refs);
}
});
walk::opcodes(scope,
[](DexMethod*) { return true; },
[&](DexMethod*, IRInstruction* insn) {
if (insn->has_type()) {
check_type(insn->get_type(), metric.insn_refs);
return;
}
std::vector<DexType*> types_in_insn;
if (insn->has_field()) {
insn->get_field()->gather_types_shallow(types_in_insn);
} else if (insn->has_method()) {
insn->get_method()->gather_types_shallow(types_in_insn);
}
for (const auto type : types_in_insn) {
check_type(type, metric.insn_refs);
}
if (!insn->has_method()) return;
const auto opcode = insn->opcode();
DexMethod* meth = nullptr;
if (opcode == OPCODE_INVOKE_VIRTUAL) {
meth = resolve_method(insn->get_method(), MethodSearch::Virtual);
} else if (opcode == OPCODE_INVOKE_INTERFACE) {
meth = resolve_method(insn->get_method(), MethodSearch::Interface);
} else {
return;
}
if (meth != nullptr) {
check_type(meth->get_class(), metric.insn_refs);
return;
}
// the method resolved to nothing which is odd but there are
// cases where it happens (OS versions, virtual call on an
// unimplemented interface method, etc.).
// To be safe let's remove every interface involved in this branch
const auto& cls = type_class(insn->get_method()->get_class());
if (cls == nullptr) return;
TypeSet intfs;
if (is_interface(cls)) {
intfs.insert(cls->get_type());
get_super_interfaces(intfs, cls);
} else {
get_interfaces(intfs, cls);
}
for (const auto& intf : intfs) {
metric.unresolved_meths += candidates.erase(intf);
}
});
}
bool implements_removables(const TypeSet& removable, DexClass* cls) {
for (const auto intf : cls->get_interfaces()->get_type_list()) {
if (removable.count(intf) > 0) {
return true;
}
}
return false;
}
void get_impls(DexType* intf,
const TypeSet& removable,
std::set<DexType*, dextypes_comparator>& new_intfs) {
const auto cls_intf = type_class(intf);
if (cls_intf == nullptr) return;
for (const auto& super_intf : cls_intf->get_interfaces()->get_type_list()) {
if (removable.count(super_intf) == 0) {
new_intfs.insert(super_intf);
continue;
}
get_impls(super_intf, removable, new_intfs);
}
};
void set_new_impl_list(const TypeSet& removable, DexClass* cls) {
TRACE(UNREF_INTF, 3, "Changing implements for %s:\n\tfrom %s",
SHOW(cls), SHOW(cls->get_interfaces()));
std::set<DexType*, dextypes_comparator> new_intfs;
for (const auto& intf : cls->get_interfaces()->get_type_list()) {
if (removable.count(intf) == 0) {
new_intfs.insert(intf);
continue;
}
get_impls(intf, removable, new_intfs);
}
std::deque<DexType*> deque;
for (const auto& intf : new_intfs) {
deque.emplace_back(intf);
}
auto implements = DexTypeList::make_type_list(std::move(deque));
TRACE(UNREF_INTF, 3, "\tto %s", SHOW(implements));
cls->set_interfaces(implements);
}
} // namespace
void UnreferencedInterfacesPass::run_pass(
DexStoresVector& stores, ConfigFiles& /*cfg*/, PassManager& mgr) {
auto scope = build_class_scope(stores);
auto removable = collect_interfaces(scope, m_metric);
remove_referenced(scope, removable, m_metric);
for (const auto& cls : scope) {
if (!implements_removables(removable, cls)) {
continue;
}
m_metric.updated_impls++;
set_new_impl_list(removable, cls);
}
m_metric.removed = removable.size();
update_scope(removable, scope);
post_dexen_changes(scope, stores);
TRACE(UNREF_INTF, 1, "candidates %ld", m_metric.candidates);
TRACE(UNREF_INTF, 1, "external %ld", m_metric.external);
TRACE(UNREF_INTF, 1, "on abstract classes %ld", m_metric.on_abstract_cls);
TRACE(UNREF_INTF, 1, "field references %ld", m_metric.field_refs);
TRACE(UNREF_INTF, 1, "signature references %ld", m_metric.sig_refs);
TRACE(UNREF_INTF, 1, "instruction references %ld", m_metric.insn_refs);
TRACE(UNREF_INTF, 1, "annotation references %ld", m_metric.anno_refs);
TRACE(UNREF_INTF, 1, "unresolved methods %ld",
m_metric.unresolved_meths);
TRACE(UNREF_INTF, 1, "updated implementations %ld", m_metric.updated_impls);
TRACE(UNREF_INTF, 1, "removable %ld", m_metric.removed);
mgr.set_metric("updated implementations", m_metric.updated_impls);
mgr.set_metric("removed_interfaces", m_metric.removed);
}
static UnreferencedInterfacesPass s_pass;
<|endoftext|> |
<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <SmurffCpp/Types.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Configs/NoiseConfig.h>
#include <SmurffCpp/Configs/DataConfig.h>
#include <SmurffCpp/Sessions/PythonSession.h>
// ----------------
// Python interface
// ----------------
namespace py = pybind11;
// wrap as Python module
PYBIND11_MODULE(wrapper, m)
{
m.doc() = "SMURFF Python Interface";
py::class_<smurff::Config>(m, "Config")
.def(py::init<>())
.def("setPriorTypes", py::overload_cast<std::vector<std::string>>(&smurff::Config::setPriorTypes))
.def("setModelInitType", py::overload_cast<std::string>(&smurff::Config::setModelInitType))
.def("setSaveName", &smurff::Config::setSaveName)
.def("setSaveFreq", &smurff::Config::setSaveFreq)
.def("setRandomSeed", &smurff::Config::setRandomSeed)
.def("setVerbose", &smurff::Config::setVerbose)
.def("setBurnin", &smurff::Config::setBurnin)
.def("setNSamples", &smurff::Config::setNSamples)
.def("setNumLatent", &smurff::Config::setNumLatent)
.def("setNumThreads", &smurff::Config::setNumThreads)
.def("setThreshold", &smurff::Config::setThreshold)
;
py::class_<smurff::NoiseConfig>(m, "NoiseConfig")
.def(py::init<const std::string, double, double, double, double>(),
py::arg("noise_type") = "fixed",
py::arg("precision") = 5.0,
py::arg("sn_init") = 1.0,
py::arg("sn_max") = 10.0,
py::arg("threshold") = 0.5
)
;
py::class_<smurff::StatusItem>(m, "StatusItem", "Short set of parameters indicative for the training progress.")
.def(py::init<>())
.def("__str__", &smurff::StatusItem::asString)
.def_readonly("phase", &smurff::StatusItem::phase, "{ \"Burnin\", \"Sampling\" }")
.def_readonly("iter", &smurff::StatusItem::iter, "Current iteration in current phase")
.def_readonly("rmse_avg", &smurff::StatusItem::rmse_avg, "Averag RMSE for test matrix across all samples")
.def_readonly("rmse_1sample", &smurff::StatusItem::rmse_1sample, "RMSE for test matrix of last sample" )
.def_readonly("train_rmse", &smurff::StatusItem::train_rmse, "RMSE for train matrix of last sample" )
.def_readonly("auc_avg", &smurff::StatusItem::auc_avg, "Average ROC AUC of the test matrix across all samples"
"Only available if you provided a threshold")
.def_readonly("auc_1sample", &smurff::StatusItem::auc_1sample, "ROC AUC of the test matrix of the last sample"
"Only available if you provided a threshold")
.def_readonly("elapsed_iter", &smurff::StatusItem::elapsed_iter, "Number of seconds the last sampling iteration took")
.def_readonly("nnz_per_sec", &smurff::StatusItem::nnz_per_sec, "Compute performance indicator; number of non-zero elements in train processed per second")
.def_readonly("samples_per_sec", &smurff::StatusItem::samples_per_sec, "Compute performance indicator; number of rows and columns in U/V processed per second")
;
py::class_<smurff::ResultItem>(m, "ResultItem", "Predictions for a single point in the matrix/tensor")
.def("__str__", &smurff::ResultItem::to_string)
.def("coords", [](const smurff::ResultItem &r) { return r.coords.as_vector(); })
.def_readonly("val", &smurff::ResultItem::val)
.def_readonly("pred_1sample", &smurff::ResultItem::pred_1sample)
.def_readonly("pred_avg", &smurff::ResultItem::pred_avg)
.def_readonly("var", &smurff::ResultItem::var)
.def_readonly("nsamples", &smurff::ResultItem::nsamples)
.def_readonly("pred_all", &smurff::ResultItem::pred_all)
;
py::class_<smurff::SparseTensor>(m, "SparseTensor")
.def(py::init<
const std::vector<std::uint64_t> &,
const std::vector<std::vector<std::uint32_t>> &,
const std::vector<double> &
>())
;
py::class_<smurff::DataConfig>(m, "DataConfig")
.def(py::init<>())
.def("setData", py::overload_cast<const smurff::Matrix &>(&smurff::DataConfig::setData))
.def("setData", py::overload_cast<const smurff::SparseMatrix &, bool>(&smurff::DataConfig::setData))
.def("setData", py::overload_cast<const smurff::DenseTensor &>(&smurff::DataConfig::setData))
.def("setData", py::overload_cast<const smurff::SparseTensor &, bool>(&smurff::DataConfig::setData))
.def("setNoiseConfig", &smurff::DataConfig::setNoiseConfig)
;
py::class_<smurff::PythonSession>(m, "PythonSession")
.def(py::init<const smurff::Config &>())
.def("__str__", &smurff::ISession::infoAsString)
// add data
.def("setTrain", &smurff::PythonSession::setTrainDense<smurff::Matrix>)
.def("setTrain", &smurff::PythonSession::setTrainSparse<smurff::SparseMatrix>)
.def("setTrain", &smurff::PythonSession::setTrainDense<smurff::DenseTensor>)
.def("setTrain", &smurff::PythonSession::setTrainSparse<smurff::SparseTensor>)
.def("setTest", &smurff::PythonSession::setTest<smurff::SparseMatrix>)
.def("setTest", &smurff::PythonSession::setTest<smurff::SparseTensor>)
.def("addSideInfo", &smurff::PythonSession::addSideInfoDense)
.def("addSideInfo", &smurff::PythonSession::addSideInfoSparse)
.def("addData", &smurff::PythonSession::addDataDense<smurff::Matrix>)
.def("addData", &smurff::PythonSession::addDataSparse<smurff::SparseMatrix>)
.def("addData", &smurff::PythonSession::addDataDense<smurff::DenseTensor>)
.def("addData", &smurff::PythonSession::addDataSparse<smurff::SparseTensor>)
.def("addPropagatedPosterior", &smurff::PythonSession::addPropagatedPosterior)
// get result functions
.def("getStatus", &smurff::TrainSession::getStatus)
.def("getRmseAvg", &smurff::TrainSession::getRmseAvg)
.def("getTestPredictions", [](const smurff::PythonSession &s) { return s.getResult().m_predictions; })
// run functions
.def("init", &smurff::TrainSession::init)
.def("step", &smurff::PythonSession::step)
.def("interrupted", &smurff::PythonSession::interrupted)
;
}
<commit_msg>python wrapper: coords is property<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <SmurffCpp/Types.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Configs/NoiseConfig.h>
#include <SmurffCpp/Configs/DataConfig.h>
#include <SmurffCpp/Sessions/PythonSession.h>
// ----------------
// Python interface
// ----------------
namespace py = pybind11;
// wrap as Python module
PYBIND11_MODULE(wrapper, m)
{
m.doc() = "SMURFF Python Interface";
py::class_<smurff::Config>(m, "Config")
.def(py::init<>())
.def("setPriorTypes", py::overload_cast<std::vector<std::string>>(&smurff::Config::setPriorTypes))
.def("setModelInitType", py::overload_cast<std::string>(&smurff::Config::setModelInitType))
.def("setSaveName", &smurff::Config::setSaveName)
.def("setSaveFreq", &smurff::Config::setSaveFreq)
.def("setRandomSeed", &smurff::Config::setRandomSeed)
.def("setVerbose", &smurff::Config::setVerbose)
.def("setBurnin", &smurff::Config::setBurnin)
.def("setNSamples", &smurff::Config::setNSamples)
.def("setNumLatent", &smurff::Config::setNumLatent)
.def("setNumThreads", &smurff::Config::setNumThreads)
.def("setThreshold", &smurff::Config::setThreshold)
;
py::class_<smurff::NoiseConfig>(m, "NoiseConfig")
.def(py::init<const std::string, double, double, double, double>(),
py::arg("noise_type") = "fixed",
py::arg("precision") = 5.0,
py::arg("sn_init") = 1.0,
py::arg("sn_max") = 10.0,
py::arg("threshold") = 0.5
)
;
py::class_<smurff::StatusItem>(m, "StatusItem", "Short set of parameters indicative for the training progress.")
.def(py::init<>())
.def("__str__", &smurff::StatusItem::asString)
.def_readonly("phase", &smurff::StatusItem::phase, "{ \"Burnin\", \"Sampling\" }")
.def_readonly("iter", &smurff::StatusItem::iter, "Current iteration in current phase")
.def_readonly("rmse_avg", &smurff::StatusItem::rmse_avg, "Averag RMSE for test matrix across all samples")
.def_readonly("rmse_1sample", &smurff::StatusItem::rmse_1sample, "RMSE for test matrix of last sample" )
.def_readonly("train_rmse", &smurff::StatusItem::train_rmse, "RMSE for train matrix of last sample" )
.def_readonly("auc_avg", &smurff::StatusItem::auc_avg, "Average ROC AUC of the test matrix across all samples"
"Only available if you provided a threshold")
.def_readonly("auc_1sample", &smurff::StatusItem::auc_1sample, "ROC AUC of the test matrix of the last sample"
"Only available if you provided a threshold")
.def_readonly("elapsed_iter", &smurff::StatusItem::elapsed_iter, "Number of seconds the last sampling iteration took")
.def_readonly("nnz_per_sec", &smurff::StatusItem::nnz_per_sec, "Compute performance indicator; number of non-zero elements in train processed per second")
.def_readonly("samples_per_sec", &smurff::StatusItem::samples_per_sec, "Compute performance indicator; number of rows and columns in U/V processed per second")
;
py::class_<smurff::ResultItem>(m, "ResultItem", "Predictions for a single point in the matrix/tensor")
.def("__str__", &smurff::ResultItem::to_string)
.def_property_readonly("coords", [](const smurff::ResultItem &r) { return py::tuple(r.coords.as_vector()); })
.def_readonly("val", &smurff::ResultItem::val)
.def_readonly("pred_1sample", &smurff::ResultItem::pred_1sample)
.def_readonly("pred_avg", &smurff::ResultItem::pred_avg)
.def_readonly("var", &smurff::ResultItem::var)
.def_readonly("nsamples", &smurff::ResultItem::nsamples)
.def_readonly("pred_all", &smurff::ResultItem::pred_all)
;
py::class_<smurff::SparseTensor>(m, "SparseTensor")
.def(py::init<
const std::vector<std::uint64_t> &,
const std::vector<std::vector<std::uint32_t>> &,
const std::vector<double> &
>())
;
py::class_<smurff::DataConfig>(m, "DataConfig")
.def(py::init<>())
.def("setData", py::overload_cast<const smurff::Matrix &>(&smurff::DataConfig::setData))
.def("setData", py::overload_cast<const smurff::SparseMatrix &, bool>(&smurff::DataConfig::setData))
.def("setData", py::overload_cast<const smurff::DenseTensor &>(&smurff::DataConfig::setData))
.def("setData", py::overload_cast<const smurff::SparseTensor &, bool>(&smurff::DataConfig::setData))
.def("setNoiseConfig", &smurff::DataConfig::setNoiseConfig)
;
py::class_<smurff::PythonSession>(m, "PythonSession")
.def(py::init<const smurff::Config &>())
.def("__str__", &smurff::ISession::infoAsString)
// add data
.def("setTrain", &smurff::PythonSession::setTrainDense<smurff::Matrix>)
.def("setTrain", &smurff::PythonSession::setTrainSparse<smurff::SparseMatrix>)
.def("setTrain", &smurff::PythonSession::setTrainDense<smurff::DenseTensor>)
.def("setTrain", &smurff::PythonSession::setTrainSparse<smurff::SparseTensor>)
.def("setTest", &smurff::PythonSession::setTest<smurff::SparseMatrix>)
.def("setTest", &smurff::PythonSession::setTest<smurff::SparseTensor>)
.def("addSideInfo", &smurff::PythonSession::addSideInfoDense)
.def("addSideInfo", &smurff::PythonSession::addSideInfoSparse)
.def("addData", &smurff::PythonSession::addDataDense<smurff::Matrix>)
.def("addData", &smurff::PythonSession::addDataSparse<smurff::SparseMatrix>)
.def("addData", &smurff::PythonSession::addDataDense<smurff::DenseTensor>)
.def("addData", &smurff::PythonSession::addDataSparse<smurff::SparseTensor>)
.def("addPropagatedPosterior", &smurff::PythonSession::addPropagatedPosterior)
// get result functions
.def("getStatus", &smurff::TrainSession::getStatus)
.def("getRmseAvg", &smurff::TrainSession::getRmseAvg)
.def("getTestPredictions", [](const smurff::PythonSession &s) { return s.getResult().m_predictions; })
// run functions
.def("init", &smurff::TrainSession::init)
.def("step", &smurff::PythonSession::step)
.def("interrupted", &smurff::PythonSession::interrupted)
;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Copyright (c) Kitware Inc. All rights reserved.
See Copyright.txt or http://www.Kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "midasCLI.h"
#include "midasDotProgressReporter.h"
#include "midasStatus.h"
midasCLI::midasCLI()
{
this->Synchronizer = new midasSynchronizer();
this->Synchronizer->SetDatabase(
kwsys::SystemTools::GetCurrentWorkingDirectory() + "/midas.db");
this->Synchronizer->SetProgressReporter(
reinterpret_cast<midasProgressReporter*>(
new midasDotProgressReporter(30)));
}
midasCLI::~midasCLI()
{
delete this->Synchronizer;
}
//-------------------------------------------------------------------
int midasCLI::Perform(std::vector<std::string> args)
{
if(args.size() == 0)
{
this->PrintUsage();
return -1;
}
bool ok = false;
for(unsigned i = 0; i < args.size(); i++)
{
if(args[i] == "add")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseAdd(postOpArgs);
break;
}
else if(args[i] == "clean")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseClean(postOpArgs);
break;
}
else if(args[i] == "clone")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseClone(postOpArgs);
break;
}
else if(args[i] == "create_profile")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
return this->PerformCreateProfile(postOpArgs);
}
else if(args[i] == "push")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParsePush(postOpArgs);
break;
}
else if(args[i] == "pull")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParsePull(postOpArgs);
break;
}
else if(args[i] == "status")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseStatus(postOpArgs);
break;
}
else if(args[i] == "--database" && i + 1 < args.size())
{
i++;
this->Synchronizer->SetDatabase(args[i]);
}
else if(args[i] == "--profile" && i + 1 < args.size())
{
i++;
this->Synchronizer->GetAuthenticator()->SetProfile(args[i]);
}
else if(args[i] == "--help")
{
if(i + 1 < args.size())
{
i++;
this->PrintCommandHelp(args[i]);
}
else
{
this->PrintUsage();
}
return 0;
}
else
{
this->PrintUsage();
return -1;
}
}
return ok ? this->Synchronizer->Perform() : -1;
}
//-------------------------------------------------------------------
int midasCLI::PerformCreateProfile(std::vector<std::string> args)
{
unsigned i;
std::string name, user, apiKey, appName;
for(i = 0; i < args.size(); i++)
{
if(args[i] == "-e" || args[i] == "--email"
&& args.size() > i + 1)
{
i++;
user = args[i];
}
else if(args[i] == "-n" || args[i] == "--name"
&& args.size() > i + 1)
{
i++;
name = args[i];
}
else if(args[i] == "-k" || args[i] == "--api-key"
&& args.size() > i + 1)
{
i++;
apiKey = args[i];
}
else if(args[i] == "-a" || args[i] == "--app-name"
&& args.size() > i + 1)
{
i++;
appName = args[i];
}
else
{
this->Synchronizer->SetServerURL(args[i]);
}
}
if(name == "" || user == "" || apiKey == "" || appName == "")
{
this->PrintCommandHelp("create_profile");
return -1;
}
std::cout << "Adding authentication profile '" << name << "'" << std::endl;
bool ok = this->Synchronizer->GetAuthenticator()->AddAuthProfile(
user, appName, apiKey, name);
if(ok)
{
std::cout << "Profile successfully created." << std::endl;
return 0;
}
else
{
std::cout << "Failed to add authentication profile." << std::endl;
return -1;
}
}
//-------------------------------------------------------------------
bool midasCLI::ParseAdd(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_ADD);
unsigned i;
for(i = 0; i < args.size(); i++)
{
if(args[i] == "-c")
{
this->Synchronizer->SetResourceType(midasResourceType::COLLECTION);
}
else if(args[i] == "-C")
{
this->Synchronizer->SetResourceType(midasResourceType::COMMUNITY);
}
else if(args[i] == "-i")
{
this->Synchronizer->SetResourceType(midasResourceType::ITEM);
}
else if(args[i] == "-b")
{
this->Synchronizer->SetResourceType(midasResourceType::BITSTREAM);
}
else if(args[i] == "--parent")
{
i++;
if(i + 1 < args.size())
{
this->Synchronizer->SetParentId(atoi(args[i].c_str()));
}
else
{
this->PrintCommandHelp("add");
return false;
}
}
else
{
break;
}
}
if(i < args.size() &&
this->Synchronizer->GetResourceType() != midasResourceType::NONE)
{
this->Synchronizer->SetResourceHandle(args[i]);
}
else
{
this->PrintCommandHelp("add");
return false;
}
i++;
if(i < args.size())
{
this->Synchronizer->SetServerURL(args[i]);
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParseClean(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_CLEAN);
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParseClone(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_CLONE);
this->Synchronizer->SetRecursive(true);
if(args.size())
{
this->Synchronizer->SetServerURL(args[0]);
}
else if(this->Synchronizer->GetServerURL() == "")
{
this->PrintCommandHelp("clone");
return false;
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParsePull(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_PULL);
unsigned i;
for(i = 0; i < args.size(); i++)
{
if(args[i] == "-r")
{
this->Synchronizer->SetRecursive(true);
}
else if(args[i] == "-c")
{
this->Synchronizer->SetResourceType(midasResourceType::COLLECTION);
}
else if(args[i] == "-C")
{
this->Synchronizer->SetResourceType(midasResourceType::COMMUNITY);
}
else if(args[i] == "-i")
{
this->Synchronizer->SetResourceType(midasResourceType::ITEM);
}
else if(args[i] == "-b")
{
this->Synchronizer->SetResourceType(midasResourceType::BITSTREAM);
}
else
{
break;
}
}
if(this->Synchronizer->GetResourceType() == midasResourceType::NONE)
{
this->PrintCommandHelp("pull");
return false;
}
if(i < args.size())
{
i++;
this->Synchronizer->SetResourceHandle(args[i]);
}
else
{
this->PrintCommandHelp("pull");
return false;
}
i++;
if(i < args.size())
{
this->Synchronizer->SetServerURL(args[i]);
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParsePush(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_PUSH);
if(!args.size() && this->Synchronizer->GetServerURL() == "")
{
this->PrintCommandHelp("push");
return false;
}
else if(args.size())
{
this->Synchronizer->SetServerURL(args[0]);
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParseStatus(std::vector<std::string> args)
{
std::vector<midasStatus> stats = this->Synchronizer->GetStatusEntries();
for(std::vector<midasStatus>::iterator i = stats.begin(); i != stats.end();
++i)
{
switch(i->GetType())
{
case midasResourceType::BITSTREAM:
std::cout << "b";
break;
case midasResourceType::COLLECTION:
std::cout << "c";
break;
case midasResourceType::COMMUNITY:
std::cout << "C";
break;
case midasResourceType::ITEM:
std::cout << "i";
break;
}
std::cout << " " << i->GetPath() << std::endl;
}
return true;
}
//-------------------------------------------------------------------
void midasCLI::PrintUsage()
{
std::cout << "MIDAS Command Line Interface" << std::endl
<< "Usage: MIDAScli [--database DATABASE_LOCATION] [--profile PROFILE]"
" COMMAND [ARGS]" << std::endl << std::endl
<< "Where COMMAND is one of the following:"
<< std::endl <<
" add Add a file into the local repository."
<< std::endl <<
" clean Clean the local repository."
<< std::endl <<
" clone Copy an entire MIDAS database locally."
<< std::endl <<
" create_profile Create an authentication profile."
<< std::endl <<
" pull Copy part of a MIDAS database locally."
<< std::endl <<
" push Copy local resources to a MIDAS server."
<< std::endl << std::endl << "Use MIDAScli --help COMMAND for "
"help with individual commands." << std::endl;
}
//-------------------------------------------------------------------
void midasCLI::PrintCommandHelp(std::string command)
{
if(command == "pull")
{
std::cout << "Usage: MIDAScli ... pull [COMMAND_OPTIONS] RESOURCE_ID "
"[URL]" << std::endl << "Where COMMAND_OPTIONS can be: "
<< std::endl << " -r Copy recursively."
<< std::endl << " -C For pulling a community."
<< std::endl << " -c For pulling a collection."
<< std::endl << " -i For pulling an item."
<< std::endl << " -b For pulling a bitstream."
<< std::endl << "Exactly one type must be specified (-b, -i, -c, -C)."
<< std::endl;
}
else if(command == "push")
{
std::cout << "Usage: MIDAScli ... push [URL] " << std::endl;
}
else if(command == "clone")
{
std::cout << "Usage: MIDAScli ... clone [URL]" << std::endl;
}
else if(command == "clean")
{
std::cout << "Usage: MIDAScli ... clean" << std::endl;
}
else if(command == "add")
{
std::cout << "Usage: MIDAScli ... add [COMMAND_OPTIONS] PATH [URL]"
<< std::endl << "Where COMMAND_OPTIONS can be: "
<< std::endl << " -C For adding a community."
<< std::endl << " -c For adding a collection."
<< std::endl << " -i For adding an item."
<< std::endl << " -b For adding a bitstream."
<< std::endl << " --local Do not push this resource to the server."
<< std::endl << " --parent PARENT_ID"
<< std::endl << " Specify the id of the server-side parent."
<< std::endl << "Exactly one type must be specified (-b, -i, -c, -C)."
<< std::endl
<< "And PATH is a relative or absolute path to the dir/file to add."
<< std::endl;
}
else if(command == "create_profile")
{
std::cout << "Usage: MIDAScli ... create_profile PROPERTIES [URL]"
<< std::endl << "Where PROPERTIES must contain all of: "
<< std::endl <<
" --name NAME The name of the profile to create"
<< std::endl <<
" --email EMAIL The user's email for logging in"
<< std::endl <<
" --api-key KEY The API key generated by MIDAS"
<< std::endl <<
" --app-name APPNAME The application name for the given key"
<< std::endl;
}
}
<commit_msg>ENH: specify log in the view<commit_after>/*=========================================================================
Copyright (c) Kitware Inc. All rights reserved.
See Copyright.txt or http://www.Kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "midasCLI.h"
#include "midasDotProgressReporter.h"
#include "midasStatus.h"
#include "midasStdOutLog.h"
midasCLI::midasCLI()
{
this->Synchronizer = new midasSynchronizer();
this->Synchronizer->SetDatabase(
kwsys::SystemTools::GetCurrentWorkingDirectory() + "/midas.db");
this->Synchronizer->SetProgressReporter(
reinterpret_cast<midasProgressReporter*>(
new midasDotProgressReporter(30)));
this->Synchronizer->SetLog(new midasStdOutLog());
}
midasCLI::~midasCLI()
{
delete this->Synchronizer;
this->Synchronizer->DeleteLog();
}
//-------------------------------------------------------------------
int midasCLI::Perform(std::vector<std::string> args)
{
if(args.size() == 0)
{
this->PrintUsage();
return -1;
}
bool ok = false;
for(unsigned i = 0; i < args.size(); i++)
{
if(args[i] == "add")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseAdd(postOpArgs);
break;
}
else if(args[i] == "clean")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseClean(postOpArgs);
break;
}
else if(args[i] == "clone")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseClone(postOpArgs);
break;
}
else if(args[i] == "create_profile")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
return this->PerformCreateProfile(postOpArgs);
}
else if(args[i] == "push")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParsePush(postOpArgs);
break;
}
else if(args[i] == "pull")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParsePull(postOpArgs);
break;
}
else if(args[i] == "status")
{
std::vector<std::string> postOpArgs(args.begin() + i + 1, args.end());
ok = this->ParseStatus(postOpArgs);
break;
}
else if(args[i] == "--database" && i + 1 < args.size())
{
i++;
this->Synchronizer->SetDatabase(args[i]);
}
else if(args[i] == "--profile" && i + 1 < args.size())
{
i++;
this->Synchronizer->GetAuthenticator()->SetProfile(args[i]);
}
else if(args[i] == "--help")
{
if(i + 1 < args.size())
{
i++;
this->PrintCommandHelp(args[i]);
}
else
{
this->PrintUsage();
}
return 0;
}
else
{
this->PrintUsage();
return -1;
}
}
return ok ? this->Synchronizer->Perform() : -1;
}
//-------------------------------------------------------------------
int midasCLI::PerformCreateProfile(std::vector<std::string> args)
{
unsigned i;
std::string name, user, apiKey, appName;
for(i = 0; i < args.size(); i++)
{
if(args[i] == "-e" || args[i] == "--email"
&& args.size() > i + 1)
{
i++;
user = args[i];
}
else if(args[i] == "-n" || args[i] == "--name"
&& args.size() > i + 1)
{
i++;
name = args[i];
}
else if(args[i] == "-k" || args[i] == "--api-key"
&& args.size() > i + 1)
{
i++;
apiKey = args[i];
}
else if(args[i] == "-a" || args[i] == "--app-name"
&& args.size() > i + 1)
{
i++;
appName = args[i];
}
else
{
this->Synchronizer->SetServerURL(args[i]);
}
}
if(name == "" || user == "" || apiKey == "" || appName == "")
{
this->PrintCommandHelp("create_profile");
return -1;
}
std::cout << "Adding authentication profile '" << name << "'" << std::endl;
bool ok = this->Synchronizer->GetAuthenticator()->AddAuthProfile(
user, appName, apiKey, name);
if(ok)
{
std::cout << "Profile successfully created." << std::endl;
return 0;
}
else
{
std::cout << "Failed to add authentication profile." << std::endl;
return -1;
}
}
//-------------------------------------------------------------------
bool midasCLI::ParseAdd(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_ADD);
unsigned i;
for(i = 0; i < args.size(); i++)
{
if(args[i] == "-c")
{
this->Synchronizer->SetResourceType(midasResourceType::COLLECTION);
}
else if(args[i] == "-C")
{
this->Synchronizer->SetResourceType(midasResourceType::COMMUNITY);
}
else if(args[i] == "-i")
{
this->Synchronizer->SetResourceType(midasResourceType::ITEM);
}
else if(args[i] == "-b")
{
this->Synchronizer->SetResourceType(midasResourceType::BITSTREAM);
}
else if(args[i] == "--parent")
{
i++;
if(i + 1 < args.size())
{
this->Synchronizer->SetParentId(atoi(args[i].c_str()));
}
else
{
this->PrintCommandHelp("add");
return false;
}
}
else
{
break;
}
}
if(i < args.size() &&
this->Synchronizer->GetResourceType() != midasResourceType::NONE)
{
this->Synchronizer->SetResourceHandle(args[i]);
}
else
{
this->PrintCommandHelp("add");
return false;
}
i++;
if(i < args.size())
{
this->Synchronizer->SetServerURL(args[i]);
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParseClean(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_CLEAN);
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParseClone(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_CLONE);
this->Synchronizer->SetRecursive(true);
if(args.size())
{
this->Synchronizer->SetServerURL(args[0]);
}
else if(this->Synchronizer->GetServerURL() == "")
{
this->PrintCommandHelp("clone");
return false;
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParsePull(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_PULL);
unsigned i;
for(i = 0; i < args.size(); i++)
{
if(args[i] == "-r")
{
this->Synchronizer->SetRecursive(true);
}
else if(args[i] == "-c")
{
this->Synchronizer->SetResourceType(midasResourceType::COLLECTION);
}
else if(args[i] == "-C")
{
this->Synchronizer->SetResourceType(midasResourceType::COMMUNITY);
}
else if(args[i] == "-i")
{
this->Synchronizer->SetResourceType(midasResourceType::ITEM);
}
else if(args[i] == "-b")
{
this->Synchronizer->SetResourceType(midasResourceType::BITSTREAM);
}
else
{
break;
}
}
if(this->Synchronizer->GetResourceType() == midasResourceType::NONE)
{
this->PrintCommandHelp("pull");
return false;
}
if(i < args.size())
{
i++;
this->Synchronizer->SetResourceHandle(args[i]);
}
else
{
this->PrintCommandHelp("pull");
return false;
}
i++;
if(i < args.size())
{
this->Synchronizer->SetServerURL(args[i]);
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParsePush(std::vector<std::string> args)
{
this->Synchronizer->SetOperation(midasSynchronizer::OPERATION_PUSH);
if(!args.size() && this->Synchronizer->GetServerURL() == "")
{
this->PrintCommandHelp("push");
return false;
}
else if(args.size())
{
this->Synchronizer->SetServerURL(args[0]);
}
return true;
}
//-------------------------------------------------------------------
bool midasCLI::ParseStatus(std::vector<std::string> args)
{
std::vector<midasStatus> stats = this->Synchronizer->GetStatusEntries();
for(std::vector<midasStatus>::iterator i = stats.begin(); i != stats.end();
++i)
{
switch(i->GetType())
{
case midasResourceType::BITSTREAM:
std::cout << "b";
break;
case midasResourceType::COLLECTION:
std::cout << "c";
break;
case midasResourceType::COMMUNITY:
std::cout << "C";
break;
case midasResourceType::ITEM:
std::cout << "i";
break;
}
std::cout << " " << i->GetPath() << std::endl;
}
return true;
}
//-------------------------------------------------------------------
void midasCLI::PrintUsage()
{
std::cout << "MIDAS Command Line Interface" << std::endl
<< "Usage: MIDAScli [--database DATABASE_LOCATION] [--profile PROFILE]"
" COMMAND [ARGS]" << std::endl << std::endl
<< "Where COMMAND is one of the following:"
<< std::endl <<
" add Add a file into the local repository."
<< std::endl <<
" clean Clean the local repository."
<< std::endl <<
" clone Copy an entire MIDAS database locally."
<< std::endl <<
" create_profile Create an authentication profile."
<< std::endl <<
" pull Copy part of a MIDAS database locally."
<< std::endl <<
" push Copy local resources to a MIDAS server."
<< std::endl << std::endl << "Use MIDAScli --help COMMAND for "
"help with individual commands." << std::endl;
}
//-------------------------------------------------------------------
void midasCLI::PrintCommandHelp(std::string command)
{
if(command == "pull")
{
std::cout << "Usage: MIDAScli ... pull [COMMAND_OPTIONS] RESOURCE_ID "
"[URL]" << std::endl << "Where COMMAND_OPTIONS can be: "
<< std::endl << " -r Copy recursively."
<< std::endl << " -C For pulling a community."
<< std::endl << " -c For pulling a collection."
<< std::endl << " -i For pulling an item."
<< std::endl << " -b For pulling a bitstream."
<< std::endl << "Exactly one type must be specified (-b, -i, -c, -C)."
<< std::endl;
}
else if(command == "push")
{
std::cout << "Usage: MIDAScli ... push [URL] " << std::endl;
}
else if(command == "clone")
{
std::cout << "Usage: MIDAScli ... clone [URL]" << std::endl;
}
else if(command == "clean")
{
std::cout << "Usage: MIDAScli ... clean" << std::endl;
}
else if(command == "add")
{
std::cout << "Usage: MIDAScli ... add [COMMAND_OPTIONS] PATH [URL]"
<< std::endl << "Where COMMAND_OPTIONS can be: "
<< std::endl << " -C For adding a community."
<< std::endl << " -c For adding a collection."
<< std::endl << " -i For adding an item."
<< std::endl << " -b For adding a bitstream."
<< std::endl << " --local Do not push this resource to the server."
<< std::endl << " --parent PARENT_ID"
<< std::endl << " Specify the id of the server-side parent."
<< std::endl << "Exactly one type must be specified (-b, -i, -c, -C)."
<< std::endl
<< "And PATH is a relative or absolute path to the dir/file to add."
<< std::endl;
}
else if(command == "create_profile")
{
std::cout << "Usage: MIDAScli ... create_profile PROPERTIES [URL]"
<< std::endl << "Where PROPERTIES must contain all of: "
<< std::endl <<
" --name NAME The name of the profile to create"
<< std::endl <<
" --email EMAIL The user's email for logging in"
<< std::endl <<
" --api-key KEY The API key generated by MIDAS"
<< std::endl <<
" --app-name APPNAME The application name for the given key"
<< std::endl;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "drake/Path.h"
#include "drake/util/Polynomial.h"
#include "drake/systems/Simulation.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/cascade_system.h"
#include "drake/util/drakeAppUtil.h"
#include "drake/systems/plants/RigidBodySystem.h"
#include "drake/examples/kuka_iiwa_arm/robot_state_tap.h"
using Drake::RigidBodySystem;
using Drake::BotVisualizer;
using Eigen::VectorXd;
using drake::RobotStateTap;
int main(int argc, char* argv[]) {
// Initializes LCM.
std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();
// Instantiates a rigid body system and adds the robot arm to it.
auto rigid_body_sys = std::allocate_shared<RigidBodySystem>(
Eigen::aligned_allocator<RigidBodySystem>());
rigid_body_sys->addRobotFromFile(
Drake::getDrakePath() + "/examples/kuka_iiwa_arm/urdf/iiwa14.urdf",
DrakeJoint::FIXED);
// Obtains a reference to the rigid body tree within the rigid body system.
auto const& tree = rigid_body_sys->getRigidBodyTree();
// Adds the ground.
{
double box_width = 3;
double box_depth = 0.2;
DrakeShapes::Box geom(Eigen::Vector3d(box_width, box_width, box_depth));
Eigen::Isometry3d T_element_to_link = Eigen::Isometry3d::Identity();
T_element_to_link.translation() << 0, 0,
-box_depth / 2.0; // top of the box is at z = 0
RigidBody& world = tree->world();
Eigen::Vector4d color;
color << 0.9297, 0.7930, 0.6758,
1; // was hex2dec({'ee','cb','ad'})'/256 in matlab
world.addVisualElement(
DrakeShapes::VisualElement(geom, T_element_to_link, color));
tree->addCollisionElement(
RigidBody::CollisionElement(geom, T_element_to_link, &world), world,
"terrain");
tree->updateStaticCollisionElements();
}
// Sets the stiffness of the ground.
{
rigid_body_sys->penetration_stiffness = 3000.0;
rigid_body_sys->penetration_damping = 0;
}
// Instantiates additional systems and cascades them with the rigid body
// system.
auto visualizer =
std::make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree);
auto robot_state_tap = std::make_shared<RobotStateTap<RigidBodySystem::StateVector>>();
auto sys = cascade(cascade(rigid_body_sys, visualizer), robot_state_tap);
// Obtains an initial state of the simulation.
VectorXd x0 = VectorXd::Zero(rigid_body_sys->getNumStates());
x0.head(tree->number_of_positions()) = tree->getZeroConfiguration();
// Specifies the simulation options.
Drake::SimulationOptions options;
options.realtime_factor = 1.0;
options.initial_step_size = 0.002;
// Prevents exception from being thrown when simulation runs slower than real
// time, which it most likely will given the small step size.
options.warn_real_time_violation = true;
// Starts the simulation.
Drake::simulate(*sys.get(), 0, 5, x0, options);
auto final_robot_state = robot_state_tap->get_input_vector();
int num_positions = rigid_body_sys->number_of_positions();
int num_velocities = rigid_body_sys->number_of_velocities();
// Ensures the size of the output is correct.
if (final_robot_state.size() != rigid_body_sys->getNumOutputs()) {
throw std::runtime_error(
"ERROR: Size of final robot state ("
+ std::to_string(final_robot_state.size())
+ ") does not match size of rigid body system's output ("
+ std::to_string(rigid_body_sys->getNumOutputs()) + ").");
}
// Ensures the number of position states equals the number of velocity states.
if (num_positions != num_velocities) {
throw std::runtime_error(
"ERROR: Number of positions ("
+ std::to_string(num_positions)
+ ") does not match the number of velocities ("
+ std::to_string(num_velocities) + ").");
}
// Ensures the number of position and velocity states match the size of the
// final robot state.
if ((num_positions + num_velocities) != final_robot_state.size()) {
throw std::runtime_error(
"ERROR: Total number of positions and velocities ("
+ std::to_string(num_positions + num_velocities)
+ ") does not match size of robot state ("
+ std::to_string(final_robot_state.size()) + ").");
}
// Ensures the robot's joints are within their position limits.
std::vector<std::unique_ptr<RigidBody>>& bodies = tree->bodies;
for (int robot_state_index = 0, body_index = 0; body_index < bodies.size();
++body_index) {
// skip rigid bodies without a parent (this includes the world link)
if (!bodies[body_index]->hasParent()) continue;
const DrakeJoint& joint = bodies[body_index]->getJoint();
const Eigen::VectorXd& min_limit = joint.getJointLimitMin();
const Eigen::VectorXd& max_limit = joint.getJointLimitMax();
for (int ii = 0; ii < joint.getNumPositions(); ++ii) {
double position = final_robot_state[robot_state_index++];
if (position < min_limit[ii]) {
throw std::runtime_error("ERROR: Joint " + joint.getName() + " (DOF "
+ joint.getPositionName(ii) + ") violated minimum position limit ("
+ std::to_string(position) + " < "
+ std::to_string(min_limit[ii]) + ").");
}
if (position > max_limit[ii]) {
throw std::runtime_error("ERROR: Joint " + joint.getName() + " (DOF "
+ joint.getPositionName(ii) + ") violated maximum position limit ("
+ std::to_string(position) + " > "
+ std::to_string(max_limit[ii]) + ").");
}
}
}
// Unfortunately we cannot check the joint velocities since the velocity
// limits are not being parsed.
}
<commit_msg>Fixed comment grammar.<commit_after>#include <iostream>
#include "drake/Path.h"
#include "drake/util/Polynomial.h"
#include "drake/systems/Simulation.h"
#include "drake/systems/plants/BotVisualizer.h"
#include "drake/systems/LCMSystem.h"
#include "drake/systems/cascade_system.h"
#include "drake/util/drakeAppUtil.h"
#include "drake/systems/plants/RigidBodySystem.h"
#include "drake/examples/kuka_iiwa_arm/robot_state_tap.h"
using Drake::RigidBodySystem;
using Drake::BotVisualizer;
using Eigen::VectorXd;
using drake::RobotStateTap;
int main(int argc, char* argv[]) {
// Initializes LCM.
std::shared_ptr<lcm::LCM> lcm = std::make_shared<lcm::LCM>();
// Instantiates a rigid body system and adds the robot arm to it.
auto rigid_body_sys = std::allocate_shared<RigidBodySystem>(
Eigen::aligned_allocator<RigidBodySystem>());
rigid_body_sys->addRobotFromFile(
Drake::getDrakePath() + "/examples/kuka_iiwa_arm/urdf/iiwa14.urdf",
DrakeJoint::FIXED);
// Obtains a reference to the rigid body tree within the rigid body system.
auto const& tree = rigid_body_sys->getRigidBodyTree();
// Adds the ground.
{
double box_width = 3;
double box_depth = 0.2;
DrakeShapes::Box geom(Eigen::Vector3d(box_width, box_width, box_depth));
Eigen::Isometry3d T_element_to_link = Eigen::Isometry3d::Identity();
T_element_to_link.translation() << 0, 0,
-box_depth / 2.0; // top of the box is at z = 0
RigidBody& world = tree->world();
Eigen::Vector4d color;
color << 0.9297, 0.7930, 0.6758,
1; // was hex2dec({'ee','cb','ad'})'/256 in matlab
world.addVisualElement(
DrakeShapes::VisualElement(geom, T_element_to_link, color));
tree->addCollisionElement(
RigidBody::CollisionElement(geom, T_element_to_link, &world), world,
"terrain");
tree->updateStaticCollisionElements();
}
// Sets the stiffness of the ground.
{
rigid_body_sys->penetration_stiffness = 3000.0;
rigid_body_sys->penetration_damping = 0;
}
// Instantiates additional systems and cascades them with the rigid body
// system.
auto visualizer =
std::make_shared<BotVisualizer<RigidBodySystem::StateVector>>(lcm, tree);
auto robot_state_tap = std::make_shared<RobotStateTap<RigidBodySystem::StateVector>>();
auto sys = cascade(cascade(rigid_body_sys, visualizer), robot_state_tap);
// Obtains an initial state of the simulation.
VectorXd x0 = VectorXd::Zero(rigid_body_sys->getNumStates());
x0.head(tree->number_of_positions()) = tree->getZeroConfiguration();
// Specifies the simulation options.
Drake::SimulationOptions options;
options.realtime_factor = 1.0;
options.initial_step_size = 0.002;
// Prevents exception from being thrown when simulation runs slower than real
// time, which it most likely will given the small step size.
options.warn_real_time_violation = true;
// Starts the simulation.
Drake::simulate(*sys.get(), 0, 5, x0, options);
auto final_robot_state = robot_state_tap->get_input_vector();
int num_positions = rigid_body_sys->number_of_positions();
int num_velocities = rigid_body_sys->number_of_velocities();
// Ensures the size of the output is correct.
if (final_robot_state.size() != rigid_body_sys->getNumOutputs()) {
throw std::runtime_error(
"ERROR: Size of final robot state ("
+ std::to_string(final_robot_state.size())
+ ") does not match size of rigid body system's output ("
+ std::to_string(rigid_body_sys->getNumOutputs()) + ").");
}
// Ensures the number of position states equals the number of velocity states.
if (num_positions != num_velocities) {
throw std::runtime_error(
"ERROR: Number of positions ("
+ std::to_string(num_positions)
+ ") does not match the number of velocities ("
+ std::to_string(num_velocities) + ").");
}
// Ensures the number of position and velocity states match the size of the
// final robot state.
if ((num_positions + num_velocities) != final_robot_state.size()) {
throw std::runtime_error(
"ERROR: Total number of positions and velocities ("
+ std::to_string(num_positions + num_velocities)
+ ") does not match size of robot state ("
+ std::to_string(final_robot_state.size()) + ").");
}
// Ensures the robot's joints are within their position limits.
std::vector<std::unique_ptr<RigidBody>>& bodies = tree->bodies;
for (int robot_state_index = 0, body_index = 0; body_index < bodies.size();
++body_index) {
// Skips rigid bodies without a parent (this includes the world link).
if (!bodies[body_index]->hasParent()) continue;
const DrakeJoint& joint = bodies[body_index]->getJoint();
const Eigen::VectorXd& min_limit = joint.getJointLimitMin();
const Eigen::VectorXd& max_limit = joint.getJointLimitMax();
for (int ii = 0; ii < joint.getNumPositions(); ++ii) {
double position = final_robot_state[robot_state_index++];
if (position < min_limit[ii]) {
throw std::runtime_error("ERROR: Joint " + joint.getName() + " (DOF "
+ joint.getPositionName(ii) + ") violated minimum position limit ("
+ std::to_string(position) + " < "
+ std::to_string(min_limit[ii]) + ").");
}
if (position > max_limit[ii]) {
throw std::runtime_error("ERROR: Joint " + joint.getName() + " (DOF "
+ joint.getPositionName(ii) + ") violated maximum position limit ("
+ std::to_string(position) + " > "
+ std::to_string(max_limit[ii]) + ").");
}
}
}
// Unfortunately we cannot check the joint velocities since the velocity
// limits are not being parsed.
}
<|endoftext|> |
<commit_before>// ReportDefinitionVector.cpp: implementation of the CReportDefinitionVector class.
//
//////////////////////////////////////////////////////////////////////
#include "CReportDefinitionVector.h"
#include "CKeyFactory.cpp"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CReportDefinitionVector::CReportDefinitionVector(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "TrajectoryTask", CCopasiObject::Container),
mKey(CKeyFactory::add("CReportDefinitionVector", this))
{}
CReportDefinitionVector::~CReportDefinitionVector()
{
cleanup();
}
const std::vector< CReportDefinition >* CReportDefinitionVector::getReportDefinitionsAddr()
{
return &mReportDefinitions;
}
void CReportDefinitionVector::cleanup()
{
CKeyFactory::remove(mKey);
mReportDefinitions.clear();
}
std::string CReportDefinitionVector::getKey()
{
return mKey;
}
<commit_msg>add function for load/save, fix the linking error,<commit_after>// ReportDefinitionVector.cpp: implementation of the CReportDefinitionVector class.
//
//////////////////////////////////////////////////////////////////////
#include "CReportDefinitionVector.h"
#include "CKeyFactory.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CReportDefinitionVector::CReportDefinitionVector(const std::string & name,
const CCopasiContainer * pParent):
CCopasiContainer(name, pParent, "TrajectoryTask", CCopasiObject::Container),
mKey(CKeyFactory::add("CReportDefinitionVector", this))
{}
CReportDefinitionVector::~CReportDefinitionVector()
{
cleanup();
}
const std::vector< CReportDefinition >* CReportDefinitionVector::getReportDefinitionsAddr()
{
return &mReportDefinitions;
}
void CReportDefinitionVector::cleanup()
{
CKeyFactory::remove(mKey);
mReportDefinitions.clear();
}
std::string CReportDefinitionVector::getKey()
{
return mKey;
}
void CReportDefinitionVector::load(CReadConfig & configBuffer)
{}
void CReportDefinitionVector::save(CWriteConfig & configBuffer)
{}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* adiosMPIFunctions.inl
*
* Created on: Sep 7, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#ifndef ADIOS2_HELPER_ADIOSMPIFUNCTIONS_INL_
#define ADIOS2_HELPER_ADIOSMPIFUNCTIONS_INL_
#ifndef ADIOS2_HELPER_ADIOSMPIFUNCTIONS_H_
#error "Inline file should only be included from it's header, never on it's own"
#endif
#include <numeric> //std::accumulate
#include <stdexcept> //std::runtime_error
namespace adios2
{
// GatherValues specializations
template <class T>
std::vector<T> GatherValues(const T source, MPI_Comm mpiComm,
const int rankDestination)
{
int rank, size;
MPI_Comm_rank(mpiComm, &rank);
MPI_Comm_size(mpiComm, &size);
std::vector<T> output;
if (rank == rankDestination) // pre-allocate in destination rank
{
output.resize(size);
}
T sourceCopy = source; // so we can have an address for rvalues
GatherArrays(&sourceCopy, 1, output.data(), mpiComm, rankDestination);
return output;
}
template <class T>
void GathervVectors(const std::vector<T> &in, std::vector<T> &out,
size_t &position, MPI_Comm mpiComm,
const int rankDestination)
{
const size_t inSize = in.size();
std::vector<size_t> counts = GatherValues(inSize, mpiComm, rankDestination);
size_t gatheredSize = 0;
int rank;
MPI_Comm_rank(mpiComm, &rank);
if (rank == rankDestination) // pre-allocate vector
{
gatheredSize = std::accumulate(counts.begin(), counts.end(), 0);
const size_t newSize = out.size() + gatheredSize;
try
{
out.resize(newSize);
if (newSize == 0)
{
return; // nothing to copy or do
}
}
catch (...)
{
std::throw_with_nested(
std::runtime_error("ERROR: buffer overflow when resizing to " +
std::to_string(newSize) +
" bytes, in call to GathervVectors\n"));
}
}
GathervArrays(in.data(), in.size(), counts.data(), counts.size(),
&out[position], mpiComm);
position += gatheredSize;
}
} // end namespace adios2
#endif /* ADIOS2_HELPER_ADIOSMPIFUNCTIONS_INL_ */
<commit_msg>Issue #396 extra check for empty GathervVectors <commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* adiosMPIFunctions.inl
*
* Created on: Sep 7, 2017
* Author: William F Godoy godoywf@ornl.gov
*/
#ifndef ADIOS2_HELPER_ADIOSMPIFUNCTIONS_INL_
#define ADIOS2_HELPER_ADIOSMPIFUNCTIONS_INL_
#ifndef ADIOS2_HELPER_ADIOSMPIFUNCTIONS_H_
#error "Inline file should only be included from it's header, never on it's own"
#endif
#include <numeric> //std::accumulate
#include <stdexcept> //std::runtime_error
namespace adios2
{
// GatherValues specializations
template <class T>
std::vector<T> GatherValues(const T source, MPI_Comm mpiComm,
const int rankDestination)
{
int rank, size;
MPI_Comm_rank(mpiComm, &rank);
MPI_Comm_size(mpiComm, &size);
std::vector<T> output;
if (rank == rankDestination) // pre-allocate in destination rank
{
output.resize(size);
}
T sourceCopy = source; // so we can have an address for rvalues
GatherArrays(&sourceCopy, 1, output.data(), mpiComm, rankDestination);
return output;
}
template <class T>
void GathervVectors(const std::vector<T> &in, std::vector<T> &out,
size_t &position, MPI_Comm mpiComm,
const int rankDestination)
{
const size_t inSize = in.size();
std::vector<size_t> counts = GatherValues(inSize, mpiComm, rankDestination);
size_t gatheredSize = 0;
int rank;
MPI_Comm_rank(mpiComm, &rank);
if (rank == rankDestination) // pre-allocate vector
{
gatheredSize = std::accumulate(counts.begin(), counts.end(), 0);
MPI_Bcast(&gatheredSize, 1, ADIOS2_MPI_SIZE_T, rankDestination,
mpiComm);
if (gatheredSize > 0)
{
const size_t newSize = out.size() + gatheredSize;
try
{
out.resize(newSize);
}
catch (...)
{
std::throw_with_nested(std::runtime_error(
"ERROR: buffer overflow when resizing to " +
std::to_string(newSize) +
" bytes, in call to GathervVectors\n"));
}
}
}
else
{
MPI_Bcast(&gatheredSize, 1, ADIOS2_MPI_SIZE_T, rankDestination,
mpiComm);
}
if (gatheredSize > 0)
{
GathervArrays(in.data(), in.size(), counts.data(), counts.size(),
&out[position], mpiComm);
position += gatheredSize;
}
}
} // end namespace adios2
#endif /* ADIOS2_HELPER_ADIOSMPIFUNCTIONS_INL_ */
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "OSMock.hpp"
#include "experiment/payload/payload_exp.hpp"
#include "mock/FsMock.hpp"
#include "mock/PayloadDeviceMock.hpp"
#include "mock/SunSDriverMock.hpp"
#include "mock/power.hpp"
#include "mock/time.hpp"
using testing::NiceMock;
using testing::Return;
using testing::InSequence;
using testing::Eq;
using testing::_;
using namespace experiment::payload;
using experiments::IterationResult;
using experiments::StartResult;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using namespace std::chrono_literals;
namespace
{
class PayloadExperimentTest : public testing::Test
{
public:
PayloadExperimentTest();
protected:
NiceMock<FsMock> _fs;
NiceMock<CurrentTimeMock> _time;
NiceMock<PayloadDeviceMock> _payload;
NiceMock<SunSDriverMock> _suns;
NiceMock<OSMock> _os;
OSReset _osReset{InstallProxy(&_os)};
PayloadCommissioningExperiment _exp;
NiceMock<PowerControlMock> _power;
static constexpr const char* TestFileName = "/test_payload";
void StartupStepTest();
void RadFETStepTest();
void CamsStepTest();
void CamsFullStepTest();
void SunSStepTest();
void TelemetrySnapshotStepTest();
};
PayloadExperimentTest::PayloadExperimentTest() : _exp(_payload, _fs, _power, _time, _suns)
{
ON_CALL(_power, SensPower(_)).WillByDefault(Return(true));
ON_CALL(_power, SunSPower(_)).WillByDefault(Return(true));
ON_CALL(_power, CameraNadir(_)).WillByDefault(Return(true));
ON_CALL(_power, CameraWing(_)).WillByDefault(Return(true));
ON_CALL(this->_time, GetCurrentTime()).WillByDefault(Return(Some(10ms)));
}
TEST_F(PayloadExperimentTest, TestExperimentStartStop)
{
auto r = _exp.Start();
ASSERT_THAT(r, Eq(StartResult::Success));
_exp.Stop(IterationResult::Finished);
}
void PayloadExperimentTest::TelemetrySnapshotStepTest()
{
// TODO Save Telemetry snapshot
}
void PayloadExperimentTest::StartupStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
EXPECT_CALL(_payload, GetWhoami(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureHousekeeping(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureSunSRef(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasurePhotodiodes(_)).WillOnce(Return(OSResult::Success));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::RadFETStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(2s)));
EXPECT_CALL(_payload, GetWhoami(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureHousekeeping(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, RadFETOn(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
EXPECT_CALL(_payload, MeasureRadFET(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, GetWhoami(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureHousekeeping(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, RadFETOff(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(2s)));
EXPECT_CALL(_payload, MeasureRadFET(_)).WillOnce(Return(OSResult::Success));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::CamsStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, CameraNadir(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
TelemetrySnapshotStepTest();
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_power, CameraNadir(false)).WillOnce(Return(true));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, CameraWing(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
TelemetrySnapshotStepTest();
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_power, CameraWing(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::CamsFullStepTest()
{
// TODO: WRITE THAT
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::SunSStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SunSPower(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(2s)));
EXPECT_CALL(_suns, StartMeasurement(0, 10));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SunSPower(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::Finished));
}
TEST_F(PayloadExperimentTest, IterationFlow)
{
std::array<std::uint8_t, 2320> buffer;
_fs.AddFile(TestFileName, buffer);
_exp.SetOutputFile(TestFileName);
_exp.Start();
{
InSequence s;
StartupStepTest();
RadFETStepTest();
CamsStepTest();
CamsFullStepTest();
SunSStepTest();
}
}
}
<commit_msg>[Experiment - Payload] Unit test fix.<commit_after>#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "OSMock.hpp"
#include "experiment/payload/payload_exp.hpp"
#include "mock/FsMock.hpp"
#include "mock/PayloadDeviceMock.hpp"
#include "mock/SunSDriverMock.hpp"
#include "mock/power.hpp"
#include "mock/time.hpp"
using testing::NiceMock;
using testing::Return;
using testing::InSequence;
using testing::Eq;
using testing::_;
using namespace experiment::payload;
using experiments::IterationResult;
using experiments::StartResult;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using namespace std::chrono_literals;
namespace
{
class PayloadExperimentTest : public testing::Test
{
public:
PayloadExperimentTest();
protected:
NiceMock<FsMock> _fs;
NiceMock<CurrentTimeMock> _time;
NiceMock<PayloadDeviceMock> _payload;
NiceMock<SunSDriverMock> _suns;
NiceMock<OSMock> _os;
OSReset _osReset{InstallProxy(&_os)};
PayloadCommissioningExperiment _exp;
NiceMock<PowerControlMock> _power;
static constexpr const char* TestFileName = "/test_payload";
void StartupStepTest();
void RadFETStepTest();
void CamsStepTest();
void CamsFullStepTest();
void SunSStepTest();
void TelemetrySnapshotStepTest();
std::array<std::uint8_t, 696> buffer;
};
PayloadExperimentTest::PayloadExperimentTest() : _exp(_payload, _fs, _power, _time, _suns)
{
ON_CALL(_power, SensPower(_)).WillByDefault(Return(true));
ON_CALL(_power, SunSPower(_)).WillByDefault(Return(true));
ON_CALL(_power, CameraNadir(_)).WillByDefault(Return(true));
ON_CALL(_power, CameraWing(_)).WillByDefault(Return(true));
ON_CALL(this->_time, GetCurrentTime()).WillByDefault(Return(Some(10ms)));
_fs.AddFile(TestFileName, buffer);
}
TEST_F(PayloadExperimentTest, TestExperimentStartStop)
{
_exp.SetOutputFile(TestFileName);
auto r = _exp.Start();
ASSERT_THAT(r, Eq(StartResult::Success));
_exp.Stop(IterationResult::Finished);
}
void PayloadExperimentTest::TelemetrySnapshotStepTest()
{
// TODO Save Telemetry snapshot
}
void PayloadExperimentTest::StartupStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
EXPECT_CALL(_payload, GetWhoami(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureHousekeeping(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureSunSRef(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasurePhotodiodes(_)).WillOnce(Return(OSResult::Success));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::RadFETStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(2s)));
EXPECT_CALL(_payload, GetWhoami(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureHousekeeping(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, RadFETOn(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
EXPECT_CALL(_payload, MeasureRadFET(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, GetWhoami(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, MeasureHousekeeping(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_payload, RadFETOff(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(2s)));
EXPECT_CALL(_payload, MeasureRadFET(_)).WillOnce(Return(OSResult::Success));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SensPower(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::CamsStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, CameraNadir(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
TelemetrySnapshotStepTest();
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_power, CameraNadir(false)).WillOnce(Return(true));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, CameraWing(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(10s)));
TelemetrySnapshotStepTest();
EXPECT_CALL(_payload, MeasureTemperatures(_)).WillOnce(Return(OSResult::Success));
EXPECT_CALL(_power, CameraWing(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::CamsFullStepTest()
{
// TODO: WRITE THAT
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::WaitForNextCycle));
}
void PayloadExperimentTest::SunSStepTest()
{
{
InSequence s;
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SunSPower(true)).WillOnce(Return(true));
EXPECT_CALL(_os, Sleep(duration_cast<milliseconds>(2s)));
EXPECT_CALL(_suns, MeasureSunS(_, 0, 10));
TelemetrySnapshotStepTest();
EXPECT_CALL(_power, SunSPower(false)).WillOnce(Return(true));
}
auto r = _exp.Iteration();
ASSERT_THAT(r, Eq(IterationResult::Finished));
}
TEST_F(PayloadExperimentTest, IterationFlow)
{
_exp.SetOutputFile(TestFileName);
_exp.Start();
{
InSequence s;
StartupStepTest();
RadFETStepTest();
CamsStepTest();
CamsFullStepTest();
SunSStepTest();
}
}
}
<|endoftext|> |
<commit_before>//=====================================================================//
/*! @file
@brief MP3 ID3 TAG クラス@n
libid3tag を利用
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif
#include "mp3_tag.hpp"
#include "utils/file_io.hpp"
// #define MSG_
namespace mp3 {
// ローカルな変換
static void ucs4_to_sjis_(const id3_ucs4_t* ucs4, std::string& dst)
{
id3_ucs4_t c;
while((c = *ucs4++) != 0) {
if(c <= 0xff) {
dst += c;
} else {
#ifdef MSG_
std::cout << boost::format("%x ") % c;
#endif
}
}
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void mp3_tag::initialize()
{
destroy();
open_ = false;
id3_file_ = 0;
id3_tag_ = 0;
}
//-----------------------------------------------------------------//
/*!
@brief オープン
@param[in] fin ファイル入力
@return 成功なら「true」が返る
*/
//-----------------------------------------------------------------//
bool mp3_tag::open(utils::file_io& fin)
{
int fd = fin.file_handle();
id3_file_ = id3_file_fdopen(fd, ID3_FILE_MODE_READONLY);
if(id3_file_ == 0) return false;
id3_tag_ = id3_file_tag(id3_file_);
if(id3_tag_ == 0) {
id3_file_close(id3_file_);
id3_file_ = 0;
return false;
}
open_ = true;
value_ = 0;
for(int i = 0; i < id3_t::limit_; ++i) {
text_[i].clear();
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief TAG 内の全てのフレームをパース
@return 成功なら「true」が返る
*/
//-----------------------------------------------------------------//
bool mp3_tag::decode()
{
if(open_ == false) return false;
if(id3_tag_ == 0) return false;
// std::cout << boost::format("Tag frame num: %d\n") % id3_tag_->nframes;
// std::cout << boost::format("Tag version: %d\n") % id3_tag_->version;
// std::cout << boost::format("Tag size: %d (%X)\n") % static_cast<int>(id3_tag_->paddedsize)
// % static_cast<int>(id3_tag_->paddedsize);
int skip = id3_tag_->paddedsize;
/// if(skip & 3) { skip |= 3; ++skip; }
skip_head_ = skip;
for(int i = 0; i < id3_tag_->nframes; ++i) {
id3_frame* fm = id3_tag_->frames[i];
frame_t_ = id3_t::none;
bool picture = false;
if(strcmp(fm->id, "APIC") == 0) picture = true;
else if(strcmp(fm->id, "TALB") == 0) frame_t_ = id3_t::album;
else if(strcmp(fm->id, "TIT2") == 0) frame_t_ = id3_t::title;
else if(strcmp(fm->id, "TPE1") == 0) frame_t_ = id3_t::artist;
else if(strcmp(fm->id, "TPE2") == 0) frame_t_ = id3_t::artist2;
else if(strcmp(fm->id, "TCON") == 0) frame_t_ = id3_t::content;
else if(strcmp(fm->id, "TRCK") == 0) frame_t_ = id3_t::track;
else if(strcmp(fm->id, "TPOS") == 0) frame_t_ = id3_t::disc;
else if(strcmp(fm->id, "TDRC") == 0) frame_t_ = id3_t::release_year;
else {
}
#ifdef MSG_
std::cout << fm->id << " ";
#endif
for(int j = 0; j < fm->nfields; ++j) {
id3_field* fd = &fm->fields[j];
switch(fd->type) {
case ID3_FIELD_TYPE_TEXTENCODING:
text_code_ = id3_field_gettextencoding(fd);
#ifdef MSG_
if(text_code_ == ID3_FIELD_TEXTENCODING_ISO_8859_1) {
std::cout << "ISO_8859" << std::endl;
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16) {
std::cout << "UTF_16 " << std::endl;
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16BE) {
std::cout << "UTF_16BE" << std::endl;
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_8) {
std::cout << "UTF_8 " << std::endl;
}
#endif
break;
case ID3_FIELD_TYPE_LATIN1:
{
const id3_latin1_t* t = id3_field_getlatin1(fd);
}
break;
case ID3_FIELD_TYPE_LATIN1FULL:
break;
// ID3_FIELD_TYPE_LATIN1LIST,
case ID3_FIELD_TYPE_STRING:
{
const id3_ucs4_t* ucs4 = id3_field_getstring(fd);
if(picture) {
if(ucs4[0] == 0xff && ucs4[1] == 0xd8 && ucs4[2] == 0xff && ucs4[3] == 0xe0) {
apic_string_[0] = ucs4[0];
apic_string_[1] = ucs4[1];
apic_string_[2] = ucs4[2];
apic_string_[3] = ucs4[3];
/// apic_string_len_ = fd->string.length;
} else {
apic_string_len_ = 0;
}
} else {
std::string dst;
bool cnv = true;
if(text_code_ == ID3_FIELD_TEXTENCODING_ISO_8859_1) {
std::string tmp;
ucs4_to_sjis_(ucs4, tmp);
/// utils::sjis_to_utf8(tmp, dst);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16) {
id3_utf16_t* utf16 = id3_ucs4_utf16duplicate(ucs4);
utils::utf16_to_utf8((const uint16_t*)utf16, dst);
free(utf16);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_8) {
id3_utf8_t* utf8 = id3_ucs4_utf8duplicate(ucs4);
dst = (char*)(utf8);
free(utf8);
} else {
cnv = false;
}
if(cnv) {
text_[frame_t_] = dst;
#ifdef MSG_
std::cout << "STRING: '" << dst << "'";
#endif
}
}
}
break;
case ID3_FIELD_TYPE_STRINGFULL:
break;
case ID3_FIELD_TYPE_STRINGLIST:
{
for(int n = 0; n < id3_field_getnstrings(fd); ++n) {
const id3_ucs4_t* ucs4 = id3_field_getstrings(fd, n);
std::string dst;
bool cnv = true;
if(text_code_ == ID3_FIELD_TEXTENCODING_ISO_8859_1) {
id3_latin1_t* sjis = id3_ucs4_latin1duplicate(ucs4);
/// utils::sjis_to_utf8((const char*)sjis, dst);
free(sjis);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16) {
id3_utf16_t* utf16 = id3_ucs4_utf16duplicate(ucs4);
utils::utf16_to_utf8((uint16_t*)utf16, dst);
free(utf16);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_8) {
id3_utf8_t* utf8 = id3_ucs4_utf8duplicate(ucs4);
dst = (char*)utf8;
free(utf8);
} else {
cnv = false;
}
if(cnv) {
text_[frame_t_] = dst;
#ifdef MSG_
std::cout << boost::format("STRINGS(%d): '%s'\n") % n % dst;
#endif
}
}
}
break;
// ID3_FIELD_TYPE_LANGUAGE,
case ID3_FIELD_TYPE_FRAMEID:
{
const char* id = id3_field_getframeid(fd);
if(id) {
}
}
break;
case ID3_FIELD_TYPE_DATE:
break;
case ID3_FIELD_TYPE_INT8:
{
value_ = id3_field_getint(fd);
}
break;
// ID3_FIELD_TYPE_INT16,
// ID3_FIELD_TYPE_INT24,
// ID3_FIELD_TYPE_INT32,
// ID3_FIELD_TYPE_INT32PLUS,
case ID3_FIELD_TYPE_BINARYDATA:
{
id3_length_t len;
const id3_byte_t* p = id3_field_getbinarydata(fd, &len);
if(picture == true && len > 0) {
id3_byte_t* tmp = 0;
if(apic_string_len_ == (len + 5)) {
tmp = new id3_byte_t[len + 5];
tmp[0] = apic_string_[0];
tmp[1] = apic_string_[1];
tmp[2] = apic_string_[2];
tmp[3] = apic_string_[3];
tmp[4] = 0;
memcpy(tmp + 5, p, len);
}
jpegio_.destroy();
pngio_.destroy();
utils::file_io mem;
if(tmp) {
mem.open((const char*)tmp, len + 5);
} else {
mem.open((const char*)p, len);
}
if(jpegio_.probe(mem)) {
jpegio_.load(mem);
} else if(pngio_.probe(mem)) {
pngio_.load(mem);
} else {
// std::cout << "APIC can't decode picture format: ";
// for(int i = 0; i < 4; ++i) {
// std::cout << boost::format("%02X,") % p[i];
// }
// std::cout << std::endl;
}
mem.close();
delete[] tmp;
}
}
break;
default:
break;
}
}
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief クローズ
*/
//-----------------------------------------------------------------//
void mp3_tag::close()
{
if(open_) {
id3_file_close(id3_file_);
id3_file_ = 0;
id3_tag_ = 0;
jpegio_.destroy();
pngio_.destroy();
}
open_ = false;
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void mp3_tag::destroy()
{
for(int i = 0; i < id3_t::limit_; ++i) {
text_[i] = "";
}
close();
}
}
<commit_msg>support sjis convert for os-x<commit_after>//=====================================================================//
/*! @file
@brief MP3 ID3 TAG クラス@n
libid3tag を利用
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#ifdef WIN32
#include <io.h>
#include <fcntl.h>
#endif
#include "mp3_tag.hpp"
#include "utils/file_io.hpp"
// #define MSG_
namespace mp3 {
// ローカルな変換
static void ucs4_to_sjis_(const id3_ucs4_t* ucs4, std::string& dst)
{
id3_ucs4_t c;
while((c = *ucs4++) != 0) {
if(c <= 0xff) {
dst += c;
} else {
#ifdef MSG_
std::cout << boost::format("%x ") % c;
#endif
}
}
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
*/
//-----------------------------------------------------------------//
void mp3_tag::initialize()
{
destroy();
open_ = false;
id3_file_ = 0;
id3_tag_ = 0;
}
//-----------------------------------------------------------------//
/*!
@brief オープン
@param[in] fin ファイル入力
@return 成功なら「true」が返る
*/
//-----------------------------------------------------------------//
bool mp3_tag::open(utils::file_io& fin)
{
int fd = fin.file_handle();
id3_file_ = id3_file_fdopen(fd, ID3_FILE_MODE_READONLY);
if(id3_file_ == 0) return false;
id3_tag_ = id3_file_tag(id3_file_);
if(id3_tag_ == 0) {
id3_file_close(id3_file_);
id3_file_ = 0;
return false;
}
open_ = true;
value_ = 0;
for(int i = 0; i < id3_t::limit_; ++i) {
text_[i].clear();
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief TAG 内の全てのフレームをパース
@return 成功なら「true」が返る
*/
//-----------------------------------------------------------------//
bool mp3_tag::decode()
{
if(open_ == false) return false;
if(id3_tag_ == 0) return false;
// std::cout << boost::format("Tag frame num: %d\n") % id3_tag_->nframes;
// std::cout << boost::format("Tag version: %d\n") % id3_tag_->version;
// std::cout << boost::format("Tag size: %d (%X)\n") % static_cast<int>(id3_tag_->paddedsize)
// % static_cast<int>(id3_tag_->paddedsize);
int skip = id3_tag_->paddedsize;
/// if(skip & 3) { skip |= 3; ++skip; }
skip_head_ = skip;
for(int i = 0; i < id3_tag_->nframes; ++i) {
id3_frame* fm = id3_tag_->frames[i];
frame_t_ = id3_t::none;
bool picture = false;
if(strcmp(fm->id, "APIC") == 0) picture = true;
else if(strcmp(fm->id, "TALB") == 0) frame_t_ = id3_t::album;
else if(strcmp(fm->id, "TIT2") == 0) frame_t_ = id3_t::title;
else if(strcmp(fm->id, "TPE1") == 0) frame_t_ = id3_t::artist;
else if(strcmp(fm->id, "TPE2") == 0) frame_t_ = id3_t::artist2;
else if(strcmp(fm->id, "TCON") == 0) frame_t_ = id3_t::content;
else if(strcmp(fm->id, "TRCK") == 0) frame_t_ = id3_t::track;
else if(strcmp(fm->id, "TPOS") == 0) frame_t_ = id3_t::disc;
else if(strcmp(fm->id, "TDRC") == 0) frame_t_ = id3_t::release_year;
else {
}
#ifdef MSG_
std::cout << fm->id << " ";
#endif
for(int j = 0; j < fm->nfields; ++j) {
id3_field* fd = &fm->fields[j];
switch(fd->type) {
case ID3_FIELD_TYPE_TEXTENCODING:
text_code_ = id3_field_gettextencoding(fd);
#ifdef MSG_
if(text_code_ == ID3_FIELD_TEXTENCODING_ISO_8859_1) {
std::cout << "ISO_8859" << std::endl;
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16) {
std::cout << "UTF_16 " << std::endl;
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16BE) {
std::cout << "UTF_16BE" << std::endl;
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_8) {
std::cout << "UTF_8 " << std::endl;
}
#endif
break;
case ID3_FIELD_TYPE_LATIN1:
{
const id3_latin1_t* t = id3_field_getlatin1(fd);
}
break;
case ID3_FIELD_TYPE_LATIN1FULL:
break;
// ID3_FIELD_TYPE_LATIN1LIST,
case ID3_FIELD_TYPE_STRING:
{
const id3_ucs4_t* ucs4 = id3_field_getstring(fd);
if(picture) {
if(ucs4[0] == 0xff && ucs4[1] == 0xd8 && ucs4[2] == 0xff && ucs4[3] == 0xe0) {
apic_string_[0] = ucs4[0];
apic_string_[1] = ucs4[1];
apic_string_[2] = ucs4[2];
apic_string_[3] = ucs4[3];
/// apic_string_len_ = fd->string.length;
} else {
apic_string_len_ = 0;
}
} else {
std::string dst;
bool cnv = true;
if(text_code_ == ID3_FIELD_TEXTENCODING_ISO_8859_1) {
std::string tmp;
ucs4_to_sjis_(ucs4, tmp);
utils::sjis_to_utf8(tmp, dst);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16) {
id3_utf16_t* utf16 = id3_ucs4_utf16duplicate(ucs4);
utils::utf16_to_utf8((const uint16_t*)utf16, dst);
free(utf16);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_8) {
id3_utf8_t* utf8 = id3_ucs4_utf8duplicate(ucs4);
dst = (char*)(utf8);
free(utf8);
} else {
cnv = false;
}
if(cnv) {
text_[frame_t_] = dst;
#ifdef MSG_
std::cout << "STRING: '" << dst << "'";
#endif
}
}
}
break;
case ID3_FIELD_TYPE_STRINGFULL:
break;
case ID3_FIELD_TYPE_STRINGLIST:
{
for(int n = 0; n < id3_field_getnstrings(fd); ++n) {
const id3_ucs4_t* ucs4 = id3_field_getstrings(fd, n);
std::string dst;
bool cnv = true;
if(text_code_ == ID3_FIELD_TEXTENCODING_ISO_8859_1) {
id3_latin1_t* sjis = id3_ucs4_latin1duplicate(ucs4);
utils::sjis_to_utf8((const char*)sjis, dst);
free(sjis);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_16) {
id3_utf16_t* utf16 = id3_ucs4_utf16duplicate(ucs4);
utils::utf16_to_utf8((uint16_t*)utf16, dst);
free(utf16);
} else if(text_code_ == ID3_FIELD_TEXTENCODING_UTF_8) {
id3_utf8_t* utf8 = id3_ucs4_utf8duplicate(ucs4);
dst = (char*)utf8;
free(utf8);
} else {
cnv = false;
}
if(cnv) {
text_[frame_t_] = dst;
#ifdef MSG_
std::cout << boost::format("STRINGS(%d): '%s'\n") % n % dst;
#endif
}
}
}
break;
// ID3_FIELD_TYPE_LANGUAGE,
case ID3_FIELD_TYPE_FRAMEID:
{
const char* id = id3_field_getframeid(fd);
if(id) {
}
}
break;
case ID3_FIELD_TYPE_DATE:
break;
case ID3_FIELD_TYPE_INT8:
{
value_ = id3_field_getint(fd);
}
break;
// ID3_FIELD_TYPE_INT16,
// ID3_FIELD_TYPE_INT24,
// ID3_FIELD_TYPE_INT32,
// ID3_FIELD_TYPE_INT32PLUS,
case ID3_FIELD_TYPE_BINARYDATA:
{
id3_length_t len;
const id3_byte_t* p = id3_field_getbinarydata(fd, &len);
if(picture == true && len > 0) {
id3_byte_t* tmp = 0;
if(apic_string_len_ == (len + 5)) {
tmp = new id3_byte_t[len + 5];
tmp[0] = apic_string_[0];
tmp[1] = apic_string_[1];
tmp[2] = apic_string_[2];
tmp[3] = apic_string_[3];
tmp[4] = 0;
memcpy(tmp + 5, p, len);
}
jpegio_.destroy();
pngio_.destroy();
utils::file_io mem;
if(tmp) {
mem.open((const char*)tmp, len + 5);
} else {
mem.open((const char*)p, len);
}
if(jpegio_.probe(mem)) {
jpegio_.load(mem);
} else if(pngio_.probe(mem)) {
pngio_.load(mem);
} else {
// std::cout << "APIC can't decode picture format: ";
// for(int i = 0; i < 4; ++i) {
// std::cout << boost::format("%02X,") % p[i];
// }
// std::cout << std::endl;
}
mem.close();
delete[] tmp;
}
}
break;
default:
break;
}
}
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief クローズ
*/
//-----------------------------------------------------------------//
void mp3_tag::close()
{
if(open_) {
id3_file_close(id3_file_);
id3_file_ = 0;
id3_tag_ = 0;
jpegio_.destroy();
pngio_.destroy();
}
open_ = false;
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void mp3_tag::destroy()
{
for(int i = 0; i < id3_t::limit_; ++i) {
text_[i] = "";
}
close();
}
}
<|endoftext|> |
<commit_before>/*
* File: Sf1Watcher.cpp
* Author: Paolo D'Apice
*
* Created on February 21, 2012, 9:42 AM
*/
#include "Sf1Watcher.hpp"
#include "ZooKeeperNamespace.hpp"
#include "net/sf1r/distributed/ZooKeeperRouter.hpp"
#include <boost/regex.hpp>
#include <glog/logging.h>
NS_IZENELIB_SF1R_BEGIN
using iz::ZooKeeperEvent;
using std::string;
Sf1Watcher::Sf1Watcher(ZooKeeperRouter& r, bool rw)
: router(r), rewatch(rw) {
DLOG(INFO) << "watcher created";
}
Sf1Watcher::~Sf1Watcher() {
DLOG(INFO) << "watcher destroyed";
}
void
Sf1Watcher::process(ZooKeeperEvent& zkEvent) {
LOG(INFO) << zkEvent.toString();
if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_EXPIRED_SESSION_STATE)
{
LOG(INFO) << "session expired, reconnect.";
router.reconnect();
}
}
void
Sf1Watcher::onNodeCreated(const string& path) {
LOG(INFO) << "created: " << path;
if (boost::regex_match(path, TOPOLOGY_REGEX)) {
LOG(INFO) << "adding " << path << " ...";
router.addSearchTopology(path);
}
}
void
Sf1Watcher::onNodeDeleted(const string& path) {
LOG(INFO) << "deleted: " << path;
if (boost::regex_match(path, SF1R_NODE_REGEX)) {
LOG(INFO) << "removing " << path << " ...";
router.removeSf1Node(path);
} else if (boost::regex_match(path, TOPOLOGY_REGEX)) {
LOG(INFO) << "watching " << path << " ...";
router.watchChildren(path);
}
}
void
Sf1Watcher::onDataChanged(const string& path) {
DLOG(INFO) << "changed: " << path;
if (boost::regex_match(path, SF1R_NODE_REGEX)) {
LOG(INFO) << "reloading " << path << " ...";
router.updateNodeData(path);
}
}
void
Sf1Watcher::onChildrenChanged(const string& path) {
LOG(INFO) << "children changed: " << path;
if (boost::regex_search(path, SF1R_ROOT_REGEX) || path == ROOT_NODE) {
router.watchChildren(path);
}
}
NS_IZENELIB_SF1R_END
<commit_msg>try reconnect if fail to connect<commit_after>/*
* File: Sf1Watcher.cpp
* Author: Paolo D'Apice
*
* Created on February 21, 2012, 9:42 AM
*/
#include "Sf1Watcher.hpp"
#include "ZooKeeperNamespace.hpp"
#include "net/sf1r/distributed/ZooKeeperRouter.hpp"
#include <boost/regex.hpp>
#include <glog/logging.h>
NS_IZENELIB_SF1R_BEGIN
using iz::ZooKeeperEvent;
using std::string;
Sf1Watcher::Sf1Watcher(ZooKeeperRouter& r, bool rw)
: router(r), rewatch(rw) {
DLOG(INFO) << "watcher created";
}
Sf1Watcher::~Sf1Watcher() {
DLOG(INFO) << "watcher destroyed";
}
void
Sf1Watcher::process(ZooKeeperEvent& zkEvent) {
LOG(INFO) << zkEvent.toString();
if (zkEvent.type_ == ZOO_SESSION_EVENT && zkEvent.state_ == ZOO_EXPIRED_SESSION_STATE)
{
while(true)
{
try
{
LOG(INFO) << "session expired, reconnect.";
router.reconnect();
break;
}
catch(...)
{
sleep(10);
}
}
}
}
void
Sf1Watcher::onNodeCreated(const string& path) {
LOG(INFO) << "created: " << path;
if (boost::regex_match(path, TOPOLOGY_REGEX)) {
LOG(INFO) << "adding " << path << " ...";
router.addSearchTopology(path);
}
}
void
Sf1Watcher::onNodeDeleted(const string& path) {
LOG(INFO) << "deleted: " << path;
if (boost::regex_match(path, SF1R_NODE_REGEX)) {
LOG(INFO) << "removing " << path << " ...";
router.removeSf1Node(path);
} else if (boost::regex_match(path, TOPOLOGY_REGEX)) {
LOG(INFO) << "watching " << path << " ...";
router.watchChildren(path);
}
}
void
Sf1Watcher::onDataChanged(const string& path) {
DLOG(INFO) << "changed: " << path;
if (boost::regex_match(path, SF1R_NODE_REGEX)) {
LOG(INFO) << "reloading " << path << " ...";
router.updateNodeData(path);
}
}
void
Sf1Watcher::onChildrenChanged(const string& path) {
LOG(INFO) << "children changed: " << path;
if (boost::regex_search(path, SF1R_ROOT_REGEX) || path == ROOT_NODE) {
router.watchChildren(path);
}
}
NS_IZENELIB_SF1R_END
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ScrollbarThemeComposite.h"
#include "ChromeClient.h"
#include "Frame.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "Page.h"
#include "PlatformMouseEvent.h"
#include "Scrollbar.h"
#include "ScrollbarClient.h"
#include "Settings.h"
namespace WebCore {
static Page* pageForScrollView(ScrollView* view)
{
if (!view)
return 0;
if (!view->isFrameView())
return 0;
FrameView* frameView = static_cast<FrameView*>(view);
if (!frameView->frame())
return 0;
return frameView->frame()->page();
}
bool ScrollbarThemeComposite::paint(Scrollbar* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
{
// Create the ScrollbarControlPartMask based on the damageRect
ScrollbarControlPartMask scrollMask = NoPart;
IntRect backButtonPaintRect;
IntRect forwardButtonPaintRect;
if (hasButtons(scrollbar)) {
backButtonPaintRect = backButtonRect(scrollbar, true);
if (damageRect.intersects(backButtonPaintRect))
scrollMask |= BackButtonPart;
forwardButtonPaintRect = forwardButtonRect(scrollbar, true);
if (damageRect.intersects(forwardButtonPaintRect))
scrollMask |= ForwardButtonPart;
}
IntRect startTrackRect;
IntRect thumbRect;
IntRect endTrackRect;
IntRect trackPaintRect = trackRect(scrollbar, true);
bool thumbPresent = hasThumb(scrollbar);
if (thumbPresent) {
IntRect track = trackRect(scrollbar);
splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
if (damageRect.intersects(thumbRect)) {
scrollMask |= ThumbPart;
if (trackIsSinglePiece()) {
// The track is a single strip that paints under the thumb.
// Add both components of the track to the mask.
scrollMask |= BackTrackPart;
scrollMask |= ForwardTrackPart;
}
}
if (damageRect.intersects(startTrackRect))
scrollMask |= BackTrackPart;
if (damageRect.intersects(endTrackRect))
scrollMask |= ForwardTrackPart;
} else if (damageRect.intersects(trackPaintRect)) {
scrollMask |= BackTrackPart;
scrollMask |= ForwardTrackPart;
}
// FIXME: This API makes the assumption that the custom scrollbar's metrics will match
// the theme's metrics. This is not a valid assumption. The ability for a client to paint
// custom scrollbars should be removed once scrollbars can be styled via CSS.
if (Page* page = pageForScrollView(scrollbar->parent())) {
if (page->settings()->shouldPaintCustomScrollbars()) {
float proportion = static_cast<float>(scrollbar->visibleSize()) / scrollbar->totalSize();
float value = scrollbar->currentPos() / static_cast<float>(scrollbar->maximum());
ScrollbarControlState s = 0;
if (scrollbar->client()->isActive())
s |= ActiveScrollbarState;
if (scrollbar->isEnabled())
s |= EnabledScrollbarState;
if (scrollbar->pressedPart() != NoPart)
s |= PressedScrollbarState;
if (page->chrome()->client()->paintCustomScrollbar(graphicsContext,
scrollbar->frameGeometry(),
scrollbar->controlSize(),
s,
scrollbar->pressedPart(),
scrollbar->orientation() == VerticalScrollbar,
value,
proportion,
scrollMask))
return true;
}
}
// Paint the track.
if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) {
if (!thumbPresent || trackIsSinglePiece())
paintTrack(graphicsContext, scrollbar, trackPaintRect, ForwardTrackPart | BackTrackPart);
else {
if (scrollMask & BackTrackPart)
paintTrack(graphicsContext, scrollbar, startTrackRect, BackTrackPart);
if (scrollMask & ForwardTrackPart)
paintTrack(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart);
}
}
// Paint the back and forward buttons.
if (scrollMask & BackButtonPart)
paintButton(graphicsContext, scrollbar, backButtonPaintRect, BackButtonPart);
if (scrollMask & ForwardButtonPart)
paintButton(graphicsContext, scrollbar, forwardButtonPaintRect, ForwardButtonPart);
// Paint the thumb.
if (scrollMask & ThumbPart)
paintThumb(graphicsContext, scrollbar, thumbRect);
return true;
}
ScrollbarPart ScrollbarThemeComposite::hitTest(Scrollbar* scrollbar, const PlatformMouseEvent& evt)
{
ScrollbarPart result = NoPart;
if (!scrollbar->isEnabled())
return result;
IntPoint mousePosition = scrollbar->convertFromContainingWindow(evt.pos());
mousePosition.move(scrollbar->x(), scrollbar->y());
if (backButtonRect(scrollbar).contains(mousePosition))
result = BackButtonPart;
else if (forwardButtonRect(scrollbar).contains(mousePosition))
result = ForwardButtonPart;
else {
IntRect track = trackRect(scrollbar);
if (track.contains(mousePosition)) {
IntRect beforeThumbRect;
IntRect thumbRect;
IntRect afterThumbRect;
splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect);
if (beforeThumbRect.contains(mousePosition))
result = BackTrackPart;
else if (thumbRect.contains(mousePosition))
result = ThumbPart;
else
result = ForwardTrackPart;
}
}
return result;
}
void ScrollbarThemeComposite::invalidatePart(Scrollbar* scrollbar, ScrollbarPart part)
{
if (part == NoPart)
return;
IntRect result;
switch (part) {
case BackButtonPart:
result = backButtonRect(scrollbar, true);
break;
case ForwardButtonPart:
result = forwardButtonRect(scrollbar, true);
break;
default: {
IntRect beforeThumbRect, thumbRect, afterThumbRect;
splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect);
if (part == BackTrackPart)
result = beforeThumbRect;
else if (part == ForwardTrackPart)
result = afterThumbRect;
else
result = thumbRect;
}
}
result.move(-scrollbar->x(), -scrollbar->y());
scrollbar->invalidateRect(result);
}
void ScrollbarThemeComposite::splitTrack(Scrollbar* scrollbar, const IntRect& trackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect)
{
// This function won't even get called unless we're big enough to have some combination of these three rects where at least
// one of them is non-empty.
int thickness = scrollbarThickness();
int thumbPos = thumbPosition(scrollbar);
if (scrollbar->orientation() == HorizontalScrollbar) {
thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y() + (trackRect.height() - thickness) / 2, thumbLength(scrollbar), thickness);
beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos, trackRect.height());
afterThumbRect = IntRect(thumbRect.x() + thumbRect.width(), trackRect.y(), trackRect.right() - thumbRect.right(), trackRect.height());
} else {
thumbRect = IntRect(trackRect.x() + (trackRect.width() - thickness) / 2, trackRect.y() + thumbPos, thickness, thumbLength(scrollbar));
beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos);
afterThumbRect = IntRect(trackRect.x(), thumbRect.y() + thumbRect.height(), trackRect.width(), trackRect.bottom() - thumbRect.bottom());
}
}
int ScrollbarThemeComposite::thumbPosition(Scrollbar* scrollbar)
{
if (scrollbar->isEnabled())
return scrollbar->currentPos() * (trackLength(scrollbar) - thumbLength(scrollbar)) / scrollbar->maximum();
return 0;
}
int ScrollbarThemeComposite::thumbLength(Scrollbar* scrollbar)
{
if (!scrollbar->isEnabled())
return 0;
float proportion = (float)scrollbar->visibleSize() / scrollbar->totalSize();
int trackLen = trackLength(scrollbar);
int length = proportion * trackLen;
length = max(length, minimumThumbLength(scrollbar));
if (length > trackLen)
length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track).
return length;
}
int ScrollbarThemeComposite::minimumThumbLength(Scrollbar* scrollbar)
{
return scrollbarThickness(scrollbar->controlSize());
}
int ScrollbarThemeComposite::trackPosition(Scrollbar* scrollbar)
{
return (scrollbar->orientation() == HorizontalScrollbar) ? trackRect(scrollbar).x() : trackRect(scrollbar).y();
}
int ScrollbarThemeComposite::trackLength(Scrollbar* scrollbar)
{
return (scrollbar->orientation() == HorizontalScrollbar) ? trackRect(scrollbar).width() : trackRect(scrollbar).height();
}
}
<commit_msg>Fix Win build bustage.<commit_after>/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ScrollbarThemeComposite.h"
#include "ChromeClient.h"
#include "Frame.h"
#include "FrameView.h"
#include "GraphicsContext.h"
#include "Page.h"
#include "PlatformMouseEvent.h"
#include "Scrollbar.h"
#include "ScrollbarClient.h"
#include "Settings.h"
namespace WebCore {
static Page* pageForScrollView(ScrollView* view)
{
if (!view)
return 0;
if (!view->isFrameView())
return 0;
FrameView* frameView = static_cast<FrameView*>(view);
if (!frameView->frame())
return 0;
return frameView->frame()->page();
}
bool ScrollbarThemeComposite::paint(Scrollbar* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
{
// Create the ScrollbarControlPartMask based on the damageRect
ScrollbarControlPartMask scrollMask = NoPart;
IntRect backButtonPaintRect;
IntRect forwardButtonPaintRect;
if (hasButtons(scrollbar)) {
backButtonPaintRect = backButtonRect(scrollbar, true);
if (damageRect.intersects(backButtonPaintRect))
scrollMask |= BackButtonPart;
forwardButtonPaintRect = forwardButtonRect(scrollbar, true);
if (damageRect.intersects(forwardButtonPaintRect))
scrollMask |= ForwardButtonPart;
}
IntRect startTrackRect;
IntRect thumbRect;
IntRect endTrackRect;
IntRect trackPaintRect = trackRect(scrollbar, true);
bool thumbPresent = hasThumb(scrollbar);
if (thumbPresent) {
IntRect track = trackRect(scrollbar);
splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
if (damageRect.intersects(thumbRect)) {
scrollMask |= ThumbPart;
if (trackIsSinglePiece()) {
// The track is a single strip that paints under the thumb.
// Add both components of the track to the mask.
scrollMask |= BackTrackPart;
scrollMask |= ForwardTrackPart;
}
}
if (damageRect.intersects(startTrackRect))
scrollMask |= BackTrackPart;
if (damageRect.intersects(endTrackRect))
scrollMask |= ForwardTrackPart;
} else if (damageRect.intersects(trackPaintRect)) {
scrollMask |= BackTrackPart;
scrollMask |= ForwardTrackPart;
}
// FIXME: This API makes the assumption that the custom scrollbar's metrics will match
// the theme's metrics. This is not a valid assumption. The ability for a client to paint
// custom scrollbars should be removed once scrollbars can be styled via CSS.
if (Page* page = pageForScrollView(scrollbar->parent())) {
if (page->settings()->shouldPaintCustomScrollbars()) {
float proportion = static_cast<float>(scrollbar->visibleSize()) / scrollbar->totalSize();
float value = scrollbar->currentPos() / static_cast<float>(scrollbar->maximum());
ScrollbarControlState s = 0;
if (scrollbar->client()->isActive())
s |= ActiveScrollbarState;
if (scrollbar->enabled())
s |= EnabledScrollbarState;
if (scrollbar->pressedPart() != NoPart)
s |= PressedScrollbarState;
if (page->chrome()->client()->paintCustomScrollbar(graphicsContext,
scrollbar->frameGeometry(),
scrollbar->controlSize(),
s,
scrollbar->pressedPart(),
scrollbar->orientation() == VerticalScrollbar,
value,
proportion,
scrollMask))
return true;
}
}
// Paint the track.
if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) {
if (!thumbPresent || trackIsSinglePiece())
paintTrack(graphicsContext, scrollbar, trackPaintRect, ForwardTrackPart | BackTrackPart);
else {
if (scrollMask & BackTrackPart)
paintTrack(graphicsContext, scrollbar, startTrackRect, BackTrackPart);
if (scrollMask & ForwardTrackPart)
paintTrack(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart);
}
}
// Paint the back and forward buttons.
if (scrollMask & BackButtonPart)
paintButton(graphicsContext, scrollbar, backButtonPaintRect, BackButtonPart);
if (scrollMask & ForwardButtonPart)
paintButton(graphicsContext, scrollbar, forwardButtonPaintRect, ForwardButtonPart);
// Paint the thumb.
if (scrollMask & ThumbPart)
paintThumb(graphicsContext, scrollbar, thumbRect);
return true;
}
ScrollbarPart ScrollbarThemeComposite::hitTest(Scrollbar* scrollbar, const PlatformMouseEvent& evt)
{
ScrollbarPart result = NoPart;
if (!scrollbar->enabled())
return result;
IntPoint mousePosition = scrollbar->convertFromContainingWindow(evt.pos());
mousePosition.move(scrollbar->x(), scrollbar->y());
if (backButtonRect(scrollbar).contains(mousePosition))
result = BackButtonPart;
else if (forwardButtonRect(scrollbar).contains(mousePosition))
result = ForwardButtonPart;
else {
IntRect track = trackRect(scrollbar);
if (track.contains(mousePosition)) {
IntRect beforeThumbRect;
IntRect thumbRect;
IntRect afterThumbRect;
splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect);
if (beforeThumbRect.contains(mousePosition))
result = BackTrackPart;
else if (thumbRect.contains(mousePosition))
result = ThumbPart;
else
result = ForwardTrackPart;
}
}
return result;
}
void ScrollbarThemeComposite::invalidatePart(Scrollbar* scrollbar, ScrollbarPart part)
{
if (part == NoPart)
return;
IntRect result;
switch (part) {
case BackButtonPart:
result = backButtonRect(scrollbar, true);
break;
case ForwardButtonPart:
result = forwardButtonRect(scrollbar, true);
break;
default: {
IntRect beforeThumbRect, thumbRect, afterThumbRect;
splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect);
if (part == BackTrackPart)
result = beforeThumbRect;
else if (part == ForwardTrackPart)
result = afterThumbRect;
else
result = thumbRect;
}
}
result.move(-scrollbar->x(), -scrollbar->y());
scrollbar->invalidateRect(result);
}
void ScrollbarThemeComposite::splitTrack(Scrollbar* scrollbar, const IntRect& trackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect)
{
// This function won't even get called unless we're big enough to have some combination of these three rects where at least
// one of them is non-empty.
int thickness = scrollbarThickness();
int thumbPos = thumbPosition(scrollbar);
if (scrollbar->orientation() == HorizontalScrollbar) {
thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y() + (trackRect.height() - thickness) / 2, thumbLength(scrollbar), thickness);
beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos, trackRect.height());
afterThumbRect = IntRect(thumbRect.x() + thumbRect.width(), trackRect.y(), trackRect.right() - thumbRect.right(), trackRect.height());
} else {
thumbRect = IntRect(trackRect.x() + (trackRect.width() - thickness) / 2, trackRect.y() + thumbPos, thickness, thumbLength(scrollbar));
beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos);
afterThumbRect = IntRect(trackRect.x(), thumbRect.y() + thumbRect.height(), trackRect.width(), trackRect.bottom() - thumbRect.bottom());
}
}
int ScrollbarThemeComposite::thumbPosition(Scrollbar* scrollbar)
{
if (scrollbar->enabled())
return scrollbar->currentPos() * (trackLength(scrollbar) - thumbLength(scrollbar)) / scrollbar->maximum();
return 0;
}
int ScrollbarThemeComposite::thumbLength(Scrollbar* scrollbar)
{
if (!scrollbar->enabled())
return 0;
float proportion = (float)scrollbar->visibleSize() / scrollbar->totalSize();
int trackLen = trackLength(scrollbar);
int length = proportion * trackLen;
length = max(length, minimumThumbLength(scrollbar));
if (length > trackLen)
length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track).
return length;
}
int ScrollbarThemeComposite::minimumThumbLength(Scrollbar* scrollbar)
{
return scrollbarThickness(scrollbar->controlSize());
}
int ScrollbarThemeComposite::trackPosition(Scrollbar* scrollbar)
{
return (scrollbar->orientation() == HorizontalScrollbar) ? trackRect(scrollbar).x() : trackRect(scrollbar).y();
}
int ScrollbarThemeComposite::trackLength(Scrollbar* scrollbar)
{
return (scrollbar->orientation() == HorizontalScrollbar) ? trackRect(scrollbar).width() : trackRect(scrollbar).height();
}
}
<|endoftext|> |
<commit_before>// Memory-backed files used for disk images
#include "SAMdisk.h"
#include "MemFile.h"
#ifdef HAVE_ZLIB
#include <zlib.h>
#include "unzip.h"
#endif
#ifdef HAVE_BZIP2
#define BZ_NO_STDIO
#include <bzlib.h>
#endif
std::string to_string (const Compress &compression)
{
switch (compression)
{
default:
case Compress::None: return "none";
case Compress::Zip: return "zip";
case Compress::Gzip: return "gzip";
case Compress::Bzip2: return "bzip2";
}
}
bool MemFile::open (const std::string &path_, bool uncompress)
{
MEMORY mem(MAX_IMAGE_SIZE + 1);
size_t uRead = 0;
// Check if zlib is available
#ifdef HAVE_ZLIBSTAT
bool have_zlib = true;
#elif defined(HAVE_ZLIB)
bool have_zlib = CheckLibrary("zlib", "zlibVersion") && zlibVersion()[0] == ZLIB_VERSION[0];
#else
bool have_zlib = false;
#endif
#ifdef HAVE_ZLIB
// Try opening as a zip file
if (uncompress && have_zlib)
{
unzFile hfZip = unzOpen(path_.c_str());
if (hfZip)
{
int nRet;
unz_file_info sInfo;
uLong ulMaxSize = 0;
// Iterate through the contents of the zip looking for a file with a suitable size
for (nRet = unzGoToFirstFile(hfZip); nRet == UNZ_OK; nRet = unzGoToNextFile(hfZip))
{
char szFile[MAX_PATH];
// Get details of the current file
unzGetCurrentFileInfo(hfZip, &sInfo, szFile, MAX_PATH, nullptr, 0, nullptr, 0);
// Ignore directories and empty files
if (!sInfo.uncompressed_size)
continue;
// If the file extension is recognised, read the file contents
// ToDo: GetFileType doesn't really belong here?
if (GetFileType(szFile) != ftUnknown && unzOpenCurrentFile(hfZip) == UNZ_OK)
{
nRet = unzReadCurrentFile(hfZip, mem, static_cast<unsigned int>(mem.size));
unzCloseCurrentFile(hfZip);
break;
}
// Rememeber the largest uncompressed file size
if (sInfo.uncompressed_size > ulMaxSize)
ulMaxSize = sInfo.uncompressed_size;
}
// Did we fail to find a matching extension?
if (nRet == UNZ_END_OF_LIST_OF_FILE)
{
// Loop back over the archive
for (nRet = unzGoToFirstFile(hfZip); nRet == UNZ_OK; nRet = unzGoToNextFile(hfZip))
{
// Get details of the current file
unzGetCurrentFileInfo(hfZip, &sInfo, nullptr, 0, nullptr, 0, nullptr, 0);
// Open the largest file found about
if (sInfo.uncompressed_size == ulMaxSize && unzOpenCurrentFile(hfZip) == UNZ_OK)
{
nRet = unzReadCurrentFile(hfZip, mem, static_cast<unsigned int>(mem.size));
unzCloseCurrentFile(hfZip);
break;
}
}
}
// Close the zip archive
unzClose(hfZip);
// Stop if something went wrong
if (nRet < 0)
throw util::exception("zip extraction failed (", nRet, ")");
uRead = nRet;
m_compress = Compress::Zip;
}
else
{
// Open as gzipped or uncompressed
gzFile gf = gzopen(path_.c_str(), "rb");
if (gf == Z_NULL)
throw posix_error(errno, path_.c_str());
uRead = gzread(gf, mem, static_cast<unsigned>(mem.size));
m_compress = (gztell(gf) != FileSize(path_)) ? Compress::Gzip : Compress::None;
gzclose(gf);
}
}
else
#endif // HAVE_ZLIB
{
// Open as normal file if we couldn't use zlib above
FILE *f = fopen(path_.c_str(), "rb");
if (!f)
throw posix_error(errno, path_.c_str());
uRead = fread(mem, 1, mem.size, f);
fclose(f);
m_compress = Compress::None;
}
// zip compressed? (and not handled above)
if (uncompress && mem[0U] == 'P' && mem[1U] == 'K')
throw util::exception("zlib (zlib1.dll) is required for zip support");
// gzip compressed?
if (uncompress && mem[0U] == 0x1f && mem[1U] == 0x8b && mem[2U] == 0x08)
{
if (!have_zlib)
throw util::exception("zlib (zlib1.dll) is required for gzip support");
#ifdef HAVE_ZLIB
MEMORY mem2(MAX_IMAGE_SIZE + 1);
uint8_t flags = mem[3];
auto pb = mem.pb + 10, pbEnd = mem.pb + mem.size;
if (flags & 0x04) // EXTRA_FIELD
{
if (pb < pbEnd - 1)
pb += 2 + pb[0] + (pb[1] << 8);
}
if (flags & 0x08 || flags & 0x10) // ORIG_NAME or COMMENT
{
while (pb < pbEnd && *pb++);
}
if (flags & 0x02) // HEAD_CRC
pb += 2;
z_stream stream = {};
stream.next_in = pb;
stream.avail_in = (pb < pbEnd) ? static_cast<uInt>(pbEnd - pb) : 0;
stream.next_out = mem2.pb;
stream.avail_out = mem2.size;
auto zerr = inflateInit2(&stream, -MAX_WBITS);
if (zerr == Z_OK)
{
zerr = inflate(&stream, Z_FINISH);
inflateEnd(&stream);
}
if (zerr != Z_STREAM_END)
throw util::exception("gzip decompression failed (", zerr, ")");
memcpy(mem.pb, mem2.pb, uRead = stream.total_out);
m_compress = Compress::Zip;
#endif
}
// bzip2 compressed?
if (uncompress && mem[0U] == 'B' && mem[1U] == 'Z')
{
#ifdef HAVE_BZIP2
if (!CheckLibrary("bzip2", "BZ2_bzBuffToBuffDecompress"))
#endif
throw util::exception("libbz2 (bzip2.dll) is required for bzip2 support");
#ifdef HAVE_BZIP2
MEMORY mem2(MAX_IMAGE_SIZE + 1);
auto uBzRead = static_cast<unsigned>(mem2.size);
auto bzerr = BZ2_bzBuffToBuffDecompress(reinterpret_cast<char *>(mem2.pb), &uBzRead, reinterpret_cast<char *>(mem.pb), uRead, 0, 0);
if (bzerr != BZ_OK)
throw util::exception("bzip2 decompression failed (", bzerr, ")");
memcpy(mem.pb, mem2.pb, uRead = uBzRead);
m_compress = Compress::Bzip2;
#endif // HAVE_BZIP2
}
if (uRead <= MAX_IMAGE_SIZE)
return open(mem.pb, static_cast<int>(uRead), path_);
throw util::exception("file size too big");
}
bool MemFile::open (const void *buf, int len, const std::string &path_)
{
auto pb = reinterpret_cast<const uint8_t *>(buf);
m_data.clear();
m_it = m_data.insert(m_data.begin(), pb, pb + len);
m_path = path_;
return true;
}
const Data &MemFile::data () const
{
return m_data;
}
int MemFile::size () const
{
return static_cast<int>(m_data.size());
}
int MemFile::remaining () const
{
return static_cast<int>(m_data.end() - m_it);
}
const std::string &MemFile::path () const
{
return m_path;
}
const char *MemFile::name () const
{
std::string::size_type pos = m_path.rfind(PATH_SEPARATOR_CHR);
return m_path.c_str() + ((pos == m_path.npos) ? 0 : pos + 1);
}
Compress MemFile::compression () const
{
return m_compress;
}
std::vector<uint8_t> MemFile::read (int len)
{
auto avail_bytes = std::min(len, remaining());
return std::vector<uint8_t>(m_it, m_it + avail_bytes);
}
bool MemFile::read (void *buf, int len)
{
auto avail = std::min(len, remaining());
if (avail != len)
return false;
if (avail)
{
memcpy(buf, &(*m_it), avail); // make this safer when callers can cope
m_it += avail;
}
return true;
}
int MemFile::read (void *buf, int len, int count)
{
if (!len) return count; // can read as many zero-length units as requested!
auto avail_items = std::min(count, remaining() / len);
read(buf, avail_items * len);
return avail_items;
}
bool MemFile::rewind ()
{
return seek(0);
}
bool MemFile::seek (int offset)
{
m_it = m_data.begin() + std::min(offset, static_cast<int>(m_data.size()));
return tell() == offset;
}
int MemFile::tell () const
{
return static_cast<int>(m_it - m_data.begin());
}
bool MemFile::eof () const
{
return m_it == m_data.end();
}
<commit_msg>Work around gzopen false positive of uncompressed content<commit_after>// Memory-backed files used for disk images
#include "SAMdisk.h"
#include "MemFile.h"
#ifdef HAVE_ZLIB
#include <zlib.h>
#include "unzip.h"
#endif
#ifdef HAVE_BZIP2
#define BZ_NO_STDIO
#include <bzlib.h>
#endif
std::string to_string (const Compress &compression)
{
switch (compression)
{
default:
case Compress::None: return "none";
case Compress::Zip: return "zip";
case Compress::Gzip: return "gzip";
case Compress::Bzip2: return "bzip2";
}
}
bool MemFile::open (const std::string &path_, bool uncompress)
{
MEMORY mem(MAX_IMAGE_SIZE + 1);
size_t uRead = 0;
// Check if zlib is available
#ifdef HAVE_ZLIBSTAT
bool have_zlib = true;
#elif defined(HAVE_ZLIB)
bool have_zlib = CheckLibrary("zlib", "zlibVersion") && zlibVersion()[0] == ZLIB_VERSION[0];
#else
bool have_zlib = false;
#endif
#ifdef HAVE_ZLIB
// Try opening as a zip file
if (uncompress && have_zlib)
{
unzFile hfZip = unzOpen(path_.c_str());
if (hfZip)
{
int nRet;
unz_file_info sInfo;
uLong ulMaxSize = 0;
// Iterate through the contents of the zip looking for a file with a suitable size
for (nRet = unzGoToFirstFile(hfZip); nRet == UNZ_OK; nRet = unzGoToNextFile(hfZip))
{
char szFile[MAX_PATH];
// Get details of the current file
unzGetCurrentFileInfo(hfZip, &sInfo, szFile, MAX_PATH, nullptr, 0, nullptr, 0);
// Ignore directories and empty files
if (!sInfo.uncompressed_size)
continue;
// If the file extension is recognised, read the file contents
// ToDo: GetFileType doesn't really belong here?
if (GetFileType(szFile) != ftUnknown && unzOpenCurrentFile(hfZip) == UNZ_OK)
{
nRet = unzReadCurrentFile(hfZip, mem, static_cast<unsigned int>(mem.size));
unzCloseCurrentFile(hfZip);
break;
}
// Rememeber the largest uncompressed file size
if (sInfo.uncompressed_size > ulMaxSize)
ulMaxSize = sInfo.uncompressed_size;
}
// Did we fail to find a matching extension?
if (nRet == UNZ_END_OF_LIST_OF_FILE)
{
// Loop back over the archive
for (nRet = unzGoToFirstFile(hfZip); nRet == UNZ_OK; nRet = unzGoToNextFile(hfZip))
{
// Get details of the current file
unzGetCurrentFileInfo(hfZip, &sInfo, nullptr, 0, nullptr, 0, nullptr, 0);
// Open the largest file found about
if (sInfo.uncompressed_size == ulMaxSize && unzOpenCurrentFile(hfZip) == UNZ_OK)
{
nRet = unzReadCurrentFile(hfZip, mem, static_cast<unsigned int>(mem.size));
unzCloseCurrentFile(hfZip);
break;
}
}
}
// Close the zip archive
unzClose(hfZip);
// Stop if something went wrong
if (nRet < 0)
{
// Retry bad files without zlib if they lack an explicit .zip extension
if (nRet == UNZ_BADZIPFILE && !IsFileExt(path_, ".zip"))
return open(path_, false);
throw util::exception("zip extraction failed (", nRet, ")");
}
uRead = nRet;
m_compress = Compress::Zip;
}
else
{
// Open as gzipped or uncompressed
gzFile gf = gzopen(path_.c_str(), "rb");
if (gf == Z_NULL)
throw posix_error(errno, path_.c_str());
uRead = gzread(gf, mem, static_cast<unsigned>(mem.size));
m_compress = (gztell(gf) != FileSize(path_)) ? Compress::Gzip : Compress::None;
gzclose(gf);
}
}
else
#endif // HAVE_ZLIB
{
// Open as normal file if we couldn't use zlib above
FILE *f = fopen(path_.c_str(), "rb");
if (!f)
throw posix_error(errno, path_.c_str());
uRead = fread(mem, 1, mem.size, f);
fclose(f);
m_compress = Compress::None;
}
// zip compressed? (and not handled above)
if (uncompress && mem[0U] == 'P' && mem[1U] == 'K')
throw util::exception("zlib (zlib1.dll) is required for zip support");
// gzip compressed?
if (uncompress && mem[0U] == 0x1f && mem[1U] == 0x8b && mem[2U] == 0x08)
{
if (!have_zlib)
throw util::exception("zlib (zlib1.dll) is required for gzip support");
#ifdef HAVE_ZLIB
MEMORY mem2(MAX_IMAGE_SIZE + 1);
uint8_t flags = mem[3];
auto pb = mem.pb + 10, pbEnd = mem.pb + mem.size;
if (flags & 0x04) // EXTRA_FIELD
{
if (pb < pbEnd - 1)
pb += 2 + pb[0] + (pb[1] << 8);
}
if (flags & 0x08 || flags & 0x10) // ORIG_NAME or COMMENT
{
while (pb < pbEnd && *pb++);
}
if (flags & 0x02) // HEAD_CRC
pb += 2;
z_stream stream = {};
stream.next_in = pb;
stream.avail_in = (pb < pbEnd) ? static_cast<uInt>(pbEnd - pb) : 0;
stream.next_out = mem2.pb;
stream.avail_out = mem2.size;
auto zerr = inflateInit2(&stream, -MAX_WBITS);
if (zerr == Z_OK)
{
zerr = inflate(&stream, Z_FINISH);
inflateEnd(&stream);
}
if (zerr != Z_STREAM_END)
throw util::exception("gzip decompression failed (", zerr, ")");
memcpy(mem.pb, mem2.pb, uRead = stream.total_out);
m_compress = Compress::Zip;
#endif
}
// bzip2 compressed?
if (uncompress && mem[0U] == 'B' && mem[1U] == 'Z')
{
#ifdef HAVE_BZIP2
if (!CheckLibrary("bzip2", "BZ2_bzBuffToBuffDecompress"))
#endif
throw util::exception("libbz2 (bzip2.dll) is required for bzip2 support");
#ifdef HAVE_BZIP2
MEMORY mem2(MAX_IMAGE_SIZE + 1);
auto uBzRead = static_cast<unsigned>(mem2.size);
auto bzerr = BZ2_bzBuffToBuffDecompress(reinterpret_cast<char *>(mem2.pb), &uBzRead, reinterpret_cast<char *>(mem.pb), uRead, 0, 0);
if (bzerr != BZ_OK)
throw util::exception("bzip2 decompression failed (", bzerr, ")");
memcpy(mem.pb, mem2.pb, uRead = uBzRead);
m_compress = Compress::Bzip2;
#endif // HAVE_BZIP2
}
if (uRead <= MAX_IMAGE_SIZE)
return open(mem.pb, static_cast<int>(uRead), path_);
throw util::exception("file size too big");
}
bool MemFile::open (const void *buf, int len, const std::string &path_)
{
auto pb = reinterpret_cast<const uint8_t *>(buf);
m_data.clear();
m_it = m_data.insert(m_data.begin(), pb, pb + len);
m_path = path_;
return true;
}
const Data &MemFile::data () const
{
return m_data;
}
int MemFile::size () const
{
return static_cast<int>(m_data.size());
}
int MemFile::remaining () const
{
return static_cast<int>(m_data.end() - m_it);
}
const std::string &MemFile::path () const
{
return m_path;
}
const char *MemFile::name () const
{
std::string::size_type pos = m_path.rfind(PATH_SEPARATOR_CHR);
return m_path.c_str() + ((pos == m_path.npos) ? 0 : pos + 1);
}
Compress MemFile::compression () const
{
return m_compress;
}
std::vector<uint8_t> MemFile::read (int len)
{
auto avail_bytes = std::min(len, remaining());
return std::vector<uint8_t>(m_it, m_it + avail_bytes);
}
bool MemFile::read (void *buf, int len)
{
auto avail = std::min(len, remaining());
if (avail != len)
return false;
if (avail)
{
memcpy(buf, &(*m_it), avail); // make this safer when callers can cope
m_it += avail;
}
return true;
}
int MemFile::read (void *buf, int len, int count)
{
if (!len) return count; // can read as many zero-length units as requested!
auto avail_items = std::min(count, remaining() / len);
read(buf, avail_items * len);
return avail_items;
}
bool MemFile::rewind ()
{
return seek(0);
}
bool MemFile::seek (int offset)
{
m_it = m_data.begin() + std::min(offset, static_cast<int>(m_data.size()));
return tell() == offset;
}
int MemFile::tell () const
{
return static_cast<int>(m_it - m_data.begin());
}
bool MemFile::eof () const
{
return m_it == m_data.end();
}
<|endoftext|> |
<commit_before>#include "IHMD.hpp"
#include <bx/fpumath.h>
#include "Registry.hpp"
namespace xveearr
{
namespace
{
const unsigned int gViewportWidth = 1280 / 2;
const unsigned int gViewportHeight = 720;
}
class NullHMD: public IHMD
{
public:
NullHMD()
{
mRenderData[Eye::Left].mFrameBuffer = BGFX_INVALID_HANDLE;
mRenderData[Eye::Right].mFrameBuffer = BGFX_INVALID_HANDLE;
}
bool init(const ApplicationContext&)
{
return true;
}
void shutdown()
{
}
void initRenderer()
{
}
void shutdownRenderer()
{
}
void beginRender()
{
}
void endRender()
{
}
void prepareResources()
{
mRenderData[Eye::Left].mFrameBuffer = bgfx::createFrameBuffer(
gViewportWidth, gViewportHeight,
bgfx::TextureFormat::RGBA8
);
mRenderData[Eye::Right].mFrameBuffer = bgfx::createFrameBuffer(
gViewportWidth, gViewportHeight,
bgfx::TextureFormat::RGBA8
);
float leftEye[] = { -50.0f, 0.0f, 600.f };
float leftLookAt[] = { -50.0f, 0.0f, 0.f };
bx::mtxLookAtRh(
mRenderData[Eye::Left].mViewTransform, leftEye, leftLookAt
);
bx::mtxProjRh(mRenderData[Eye::Left].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
float rightEye[] = { 50.0f, 0.0f, 600.f };
float rightLookAt[] = { 50.0f, 0.0f, 0.f };
bx::mtxLookAtRh(
mRenderData[Eye::Right].mViewTransform, rightEye, rightLookAt
);
bx::mtxProjRh(mRenderData[Eye::Right].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
}
void releaseResources()
{
if(bgfx::isValid(mRenderData[Eye::Left].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Left].mFrameBuffer);
}
if(bgfx::isValid(mRenderData[Eye::Right].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Right].mFrameBuffer);
}
}
void getViewportSize(unsigned int& width, unsigned int& height)
{
width = gViewportWidth;
height = gViewportHeight;
}
const char* getName() const
{
return "null";
}
void update()
{
}
const RenderData& getRenderData(Eye::Enum eye)
{
return mRenderData[eye];
}
private:
RenderData mRenderData[Eye::Count];
};
NullHMD gNullHMDInstance;
Registry<IHMD>::Entry gFakeHMDEntry(&gNullHMDInstance);
}
<commit_msg>Add keyboard control to NullHMD<commit_after>#include "IHMD.hpp"
#include <bx/fpumath.h>
#include <SDL.h>
#include "Registry.hpp"
namespace xveearr
{
namespace
{
const unsigned int gViewportWidth = 1280 / 2;
const unsigned int gViewportHeight = 720;
const float gLeftEye[] = { -50.0f, 0.0f, 0.f };
const float gRightEye[] = { 50.0f, 0.0f, 0.f };
float gLookAt[] = { 0.f, 0.0f, -10.f };
}
class NullHMD: public IHMD
{
public:
NullHMD()
{
mRenderData[Eye::Left].mFrameBuffer = BGFX_INVALID_HANDLE;
mRenderData[Eye::Right].mFrameBuffer = BGFX_INVALID_HANDLE;
}
bool init(const ApplicationContext&)
{
bx::mtxSRT(mHeadTransform,
1.f, 1.f, 1.f,
0.f, 0.f, 0.f,
0.f, 0.f, 600.f);
return true;
}
void shutdown()
{
}
void initRenderer()
{
}
void shutdownRenderer()
{
}
void beginRender()
{
}
void endRender()
{
}
void prepareResources()
{
mRenderData[Eye::Left].mFrameBuffer = bgfx::createFrameBuffer(
gViewportWidth, gViewportHeight,
bgfx::TextureFormat::RGBA8
);
mRenderData[Eye::Right].mFrameBuffer = bgfx::createFrameBuffer(
gViewportWidth, gViewportHeight,
bgfx::TextureFormat::RGBA8
);
}
void releaseResources()
{
if(bgfx::isValid(mRenderData[Eye::Left].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Left].mFrameBuffer);
}
if(bgfx::isValid(mRenderData[Eye::Right].mFrameBuffer))
{
bgfx::destroyFrameBuffer(mRenderData[Eye::Right].mFrameBuffer);
}
}
void getViewportSize(unsigned int& width, unsigned int& height)
{
width = gViewportWidth;
height = gViewportHeight;
}
const char* getName() const
{
return "null";
}
void update()
{
const Uint8* keyStates = SDL_GetKeyboardState(NULL);
float translation[3] = {};
float rotation[3] = {};
if(keyStates[SDL_SCANCODE_A]) { translation[0] = -4.f; }
if(keyStates[SDL_SCANCODE_D]) { translation[0] = 4.f; }
if(keyStates[SDL_SCANCODE_W]) { translation[2] = -4.f; }
if(keyStates[SDL_SCANCODE_S]) { translation[2] = 4.f; }
if(keyStates[SDL_SCANCODE_Q]) { rotation[1] = -0.01f; }
if(keyStates[SDL_SCANCODE_E]) { rotation[1] = 0.01f; }
if(keyStates[SDL_SCANCODE_R]) { rotation[0] = -0.01f; }
if(keyStates[SDL_SCANCODE_F]) { rotation[0] = 0.01f; }
float move[16];
bx::mtxSRT(move,
1.f, 1.f, 1.f,
rotation[0], rotation[1], rotation[2],
translation[0], translation[1], translation[2]
);
float tmp[16];
memcpy(tmp, mHeadTransform, sizeof(tmp));
bx::mtxMul(mHeadTransform, move, tmp);
float leftEye[3];
float leftLookAt[3];
float leftRelLookat[3];
bx::vec3MulMtx(leftEye, gLeftEye, mHeadTransform);
bx::vec3Add(leftRelLookat, gLeftEye, gLookAt);
bx::vec3MulMtx(leftLookAt, leftRelLookat, mHeadTransform);
bx::mtxLookAtRh(
mRenderData[Eye::Left].mViewTransform, leftEye, leftLookAt
);
bx::mtxProjRh(mRenderData[Eye::Left].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
float rightEye[3];
float rightLookAt[3];
float rightRelLookat[3];
bx::vec3MulMtx(rightEye, gRightEye, mHeadTransform);
bx::vec3Add(rightRelLookat, gRightEye, gLookAt);
bx::vec3MulMtx(rightLookAt, rightRelLookat, mHeadTransform);
bx::mtxLookAtRh(
mRenderData[Eye::Right].mViewTransform, rightEye, rightLookAt
);
bx::mtxProjRh(mRenderData[Eye::Right].mViewProjection,
50.0f,
(float)gViewportWidth / (float)gViewportHeight,
1.f, 100000.f
);
}
const RenderData& getRenderData(Eye::Enum eye)
{
return mRenderData[eye];
}
private:
float mHeadTransform[16];
RenderData mRenderData[Eye::Count];
};
NullHMD gNullHMDInstance;
Registry<IHMD>::Entry gFakeHMDEntry(&gNullHMDInstance);
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: asynceventnotifier.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2008-03-12 07:33:58 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _ASYNCEVENTNOTIFIER_HXX_
#define _ASYNCEVENTNOTIFIER_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <list>
#include <utility>
#ifndef _EVENTNOTIFICATION_HXX_
#include "eventnotification.hxx"
#endif
//---------------------------------------------
//
//---------------------------------------------
class CAsyncEventNotifier
{
public:
CAsyncEventNotifier(cppu::OBroadcastHelper& rBroadcastHelper);
~CAsyncEventNotifier();
bool SAL_CALL startup(bool bCreateSuspended = true);
void SAL_CALL shutdown();
// notifications may be added the
// the event queue but will only
// be notified to the clients after
// resume was called
void suspend();
// resume notifying events
void resume();
// this class is responsible for the memory management of
// the CEventNotification instance
void SAL_CALL notifyEvent(CEventNotification* EventNotification);
void SAL_CALL addListener (const ::com::sun::star::uno::Type& aType ,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xListener);
void SAL_CALL removeListener(const ::com::sun::star::uno::Type& aType ,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xListener);
private:
size_t SAL_CALL getEventListSize();
void SAL_CALL resetNotifyEvent();
CEventNotification* SAL_CALL getNextEventRecord();
void SAL_CALL removeNextEventRecord();
void SAL_CALL run( );
static unsigned int WINAPI ThreadProc(LPVOID pParam);
private:
std::list<CEventNotification*> m_EventList;
HANDLE m_hThread;
bool m_bRun;
unsigned m_ThreadId;
::cppu::OBroadcastHelper& m_rBroadcastHelper;
HANDLE m_hEvents[2];
HANDLE& m_NotifyEvent;
HANDLE& m_ResumeNotifying;
osl::Mutex m_Mutex;
// prevent copy and assignment
private:
CAsyncEventNotifier( const CAsyncEventNotifier& );
CAsyncEventNotifier& operator=( const CAsyncEventNotifier& );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.10.12); FILE MERGED 2008/04/01 15:17:04 thb 1.10.12.3: #i85898# Stripping all external header guards 2008/04/01 12:30:50 thb 1.10.12.2: #i85898# Stripping all external header guards 2008/03/31 13:13:17 rt 1.10.12.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: asynceventnotifier.hxx,v $
* $Revision: 1.11 $
*
* 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 _ASYNCEVENTNOTIFIER_HXX_
#define _ASYNCEVENTNOTIFIER_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#include <osl/mutex.hxx>
#include <osl/conditn.hxx>
#include <cppuhelper/interfacecontainer.h>
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#include <list>
#include <utility>
#include "eventnotification.hxx"
//---------------------------------------------
//
//---------------------------------------------
class CAsyncEventNotifier
{
public:
CAsyncEventNotifier(cppu::OBroadcastHelper& rBroadcastHelper);
~CAsyncEventNotifier();
bool SAL_CALL startup(bool bCreateSuspended = true);
void SAL_CALL shutdown();
// notifications may be added the
// the event queue but will only
// be notified to the clients after
// resume was called
void suspend();
// resume notifying events
void resume();
// this class is responsible for the memory management of
// the CEventNotification instance
void SAL_CALL notifyEvent(CEventNotification* EventNotification);
void SAL_CALL addListener (const ::com::sun::star::uno::Type& aType ,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xListener);
void SAL_CALL removeListener(const ::com::sun::star::uno::Type& aType ,
const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xListener);
private:
size_t SAL_CALL getEventListSize();
void SAL_CALL resetNotifyEvent();
CEventNotification* SAL_CALL getNextEventRecord();
void SAL_CALL removeNextEventRecord();
void SAL_CALL run( );
static unsigned int WINAPI ThreadProc(LPVOID pParam);
private:
std::list<CEventNotification*> m_EventList;
HANDLE m_hThread;
bool m_bRun;
unsigned m_ThreadId;
::cppu::OBroadcastHelper& m_rBroadcastHelper;
HANDLE m_hEvents[2];
HANDLE& m_NotifyEvent;
HANDLE& m_ResumeNotifying;
osl::Mutex m_Mutex;
// prevent copy and assignment
private:
CAsyncEventNotifier( const CAsyncEventNotifier& );
CAsyncEventNotifier& operator=( const CAsyncEventNotifier& );
};
#endif
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2014, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/DataStructures/PlyReader.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Physics/Fem3DRepresentation.h"
#include "SurgSim/Physics/Fem3DRepresentationPlyReaderDelegate.h"
#include "SurgSim/Physics/Fem3DElementTetrahedron.h"
using SurgSim::DataStructures::PlyReader;
namespace SurgSim
{
namespace Physics
{
Fem3DRepresentationPlyReaderDelegate::Fem3DRepresentationPlyReaderDelegate(std::shared_ptr<Fem3DRepresentation> fem)
: vertexIterator(nullptr), m_fem(fem), m_hasBoundaryConditions(false)
{
}
Fem3DRepresentationPlyReaderDelegate::PolyhedronData::PolyhedronData() : indicies(nullptr), vertexCount(0)
{
}
bool Fem3DRepresentationPlyReaderDelegate::fileIsAcceptable(const PlyReader& reader)
{
bool result = true;
// Shortcut test if one fails ...
result = result && reader.hasProperty("vertex", "x");
result = result && reader.hasProperty("vertex", "y");
result = result && reader.hasProperty("vertex", "z");
result = result && reader.hasProperty("polyhedron", "vertex_indices");
result = result && !reader.isScalar("polyhedron", "vertex_indices");
result = result && reader.hasProperty("material", "mass_density");
result = result && reader.hasProperty("material", "poisson_ratio");
result = result && reader.hasProperty("material", "young_modulus");
m_hasBoundaryConditions = reader.hasProperty("boundary_condition", "vertex_index");
return result;
}
bool Fem3DRepresentationPlyReaderDelegate::registerDelegate(PlyReader* reader)
{
// Vertex processing
reader->requestElement(
"vertex",
std::bind(
&Fem3DRepresentationPlyReaderDelegate::beginVertices, this, std::placeholders::_1, std::placeholders::_2),
std::bind(&Fem3DRepresentationPlyReaderDelegate::processVertex, this, std::placeholders::_1),
std::bind(&Fem3DRepresentationPlyReaderDelegate::endVertices, this, std::placeholders::_1));
reader->requestScalarProperty("vertex", "x", PlyReader::TYPE_DOUBLE, 0 * sizeof(m_vertexData[0]));
reader->requestScalarProperty("vertex", "y", PlyReader::TYPE_DOUBLE, 1 * sizeof(m_vertexData[0]));
reader->requestScalarProperty("vertex", "z", PlyReader::TYPE_DOUBLE, 2 * sizeof(m_vertexData[0]));
// Polyhedron Processing
reader->requestElement(
"polyhedron",
std::bind(&Fem3DRepresentationPlyReaderDelegate::beginPolyhedrons,
this,
std::placeholders::_1,
std::placeholders::_2),
std::bind(&Fem3DRepresentationPlyReaderDelegate::processPolyhedron, this, std::placeholders::_1),
std::bind(&Fem3DRepresentationPlyReaderDelegate::endPolyhedrons, this, std::placeholders::_1));
reader->requestListProperty("polyhedron",
"vertex_indices",
PlyReader::TYPE_UNSIGNED_INT,
offsetof(PolyhedronData, indicies),
PlyReader::TYPE_UNSIGNED_INT,
offsetof(PolyhedronData, vertexCount));
reader->requestElement(
"material",
std::bind(
&Fem3DRepresentationPlyReaderDelegate::beginMaterials, this, std::placeholders::_1, std::placeholders::_2),
nullptr,
nullptr);
reader->requestScalarProperty(
"material", "mass_density", PlyReader::TYPE_DOUBLE, offsetof(MaterialData, massDensity));
reader->requestScalarProperty(
"material", "poisson_ratio", PlyReader::TYPE_DOUBLE, offsetof(MaterialData, poissonRatio));
reader->requestScalarProperty(
"material", "young_modulus", PlyReader::TYPE_DOUBLE, offsetof(MaterialData, youngModulus));
// Boundary Condition Processing
if (m_hasBoundaryConditions)
{
reader->requestElement(
"boundary_condition",
std::bind(&Fem3DRepresentationPlyReaderDelegate::beginBoundaryConditions,
this,
std::placeholders::_1,
std::placeholders::_2),
std::bind(&Fem3DRepresentationPlyReaderDelegate::processBoundaryCondition, this, std::placeholders::_1),
nullptr);
reader->requestScalarProperty("boundary_condition", "vertex_index", PlyReader::TYPE_UNSIGNED_INT, 0);
}
reader->setStartParseFileCallback(std::bind(&Fem3DRepresentationPlyReaderDelegate::startParseFile, this));
reader->setEndParseFileCallback(std::bind(&Fem3DRepresentationPlyReaderDelegate::endParseFile, this));
return true;
}
void Fem3DRepresentationPlyReaderDelegate::startParseFile()
{
SURGSIM_ASSERT(m_fem != nullptr) << "The Representation cannot be nullptr.";
SURGSIM_ASSERT(m_fem->getNumFemElements() == 0)
<< "The Representation already contains fem elements, so it cannot be initialized.";
SURGSIM_ASSERT(m_fem->getInitialState() == nullptr)
<< "The Representation's initial state must be uninitialized.";
m_state = std::make_shared<SurgSim::Math::OdeState>();
}
void Fem3DRepresentationPlyReaderDelegate::endParseFile()
{
for (size_t i = 0; i < m_fem->getNumFemElements(); i++)
{
m_fem->getFemElement(i)->setMassDensity(m_materialData.massDensity);
m_fem->getFemElement(i)->setPoissonRatio(m_materialData.poissonRatio);
m_fem->getFemElement(i)->setYoungModulus(m_materialData.youngModulus);
}
m_fem->setInitialState(m_state);
}
void* Fem3DRepresentationPlyReaderDelegate::beginVertices(const std::string& elementName, size_t vertexCount)
{
m_state->setNumDof(3, vertexCount);
vertexIterator = m_state->getPositions().data();
return m_vertexData.data();
}
void Fem3DRepresentationPlyReaderDelegate::processVertex(const std::string& elementName)
{
std::copy(std::begin(m_vertexData), std::end(m_vertexData), vertexIterator);
vertexIterator += 3;
}
void Fem3DRepresentationPlyReaderDelegate::endVertices(const std::string& elementName)
{
vertexIterator = nullptr;
}
void* Fem3DRepresentationPlyReaderDelegate::beginPolyhedrons(const std::string& elementName, size_t polyhedronCount)
{
return &m_polyhedronData;
}
void Fem3DRepresentationPlyReaderDelegate::processPolyhedron(const std::string& elementName)
{
SURGSIM_ASSERT(m_polyhedronData.vertexCount == 4) << "Cannot process polyhedron with "
<< m_polyhedronData.vertexCount << " vertices.";
std::array<unsigned int, 4> polyhedronVertices;
std::copy(m_polyhedronData.indicies, m_polyhedronData.indicies + 4, polyhedronVertices.begin());
m_fem->addFemElement(std::make_shared<Fem3DElementTetrahedron>(polyhedronVertices));
}
void Fem3DRepresentationPlyReaderDelegate::endPolyhedrons(const std::string& elementName)
{
m_polyhedronData.indicies = nullptr;
}
void* Fem3DRepresentationPlyReaderDelegate::beginMaterials(const std::string& elementName, size_t materialCount)
{
return &m_materialData;
}
void* Fem3DRepresentationPlyReaderDelegate::beginBoundaryConditions(const std::string& elementName,
size_t boundaryConditionCount)
{
return &m_boundaryConditionData;
}
void Fem3DRepresentationPlyReaderDelegate::processBoundaryCondition(const std::string& elementName)
{
m_state->addBoundaryCondition(m_boundaryConditionData);
}
} // namespace SurgSim
} // namespace DataStructures
<commit_msg>Reorganize alphabetically header files<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2014, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "SurgSim/DataStructures/PlyReader.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Physics/Fem3DElementTetrahedron.h"
#include "SurgSim/Physics/Fem3DRepresentation.h"
#include "SurgSim/Physics/Fem3DRepresentationPlyReaderDelegate.h"
using SurgSim::DataStructures::PlyReader;
namespace SurgSim
{
namespace Physics
{
Fem3DRepresentationPlyReaderDelegate::Fem3DRepresentationPlyReaderDelegate(std::shared_ptr<Fem3DRepresentation> fem)
: vertexIterator(nullptr), m_fem(fem), m_hasBoundaryConditions(false)
{
}
Fem3DRepresentationPlyReaderDelegate::PolyhedronData::PolyhedronData() : indicies(nullptr), vertexCount(0)
{
}
bool Fem3DRepresentationPlyReaderDelegate::fileIsAcceptable(const PlyReader& reader)
{
bool result = true;
// Shortcut test if one fails ...
result = result && reader.hasProperty("vertex", "x");
result = result && reader.hasProperty("vertex", "y");
result = result && reader.hasProperty("vertex", "z");
result = result && reader.hasProperty("polyhedron", "vertex_indices");
result = result && !reader.isScalar("polyhedron", "vertex_indices");
result = result && reader.hasProperty("material", "mass_density");
result = result && reader.hasProperty("material", "poisson_ratio");
result = result && reader.hasProperty("material", "young_modulus");
m_hasBoundaryConditions = reader.hasProperty("boundary_condition", "vertex_index");
return result;
}
bool Fem3DRepresentationPlyReaderDelegate::registerDelegate(PlyReader* reader)
{
// Vertex processing
reader->requestElement(
"vertex",
std::bind(
&Fem3DRepresentationPlyReaderDelegate::beginVertices, this, std::placeholders::_1, std::placeholders::_2),
std::bind(&Fem3DRepresentationPlyReaderDelegate::processVertex, this, std::placeholders::_1),
std::bind(&Fem3DRepresentationPlyReaderDelegate::endVertices, this, std::placeholders::_1));
reader->requestScalarProperty("vertex", "x", PlyReader::TYPE_DOUBLE, 0 * sizeof(m_vertexData[0]));
reader->requestScalarProperty("vertex", "y", PlyReader::TYPE_DOUBLE, 1 * sizeof(m_vertexData[0]));
reader->requestScalarProperty("vertex", "z", PlyReader::TYPE_DOUBLE, 2 * sizeof(m_vertexData[0]));
// Polyhedron Processing
reader->requestElement(
"polyhedron",
std::bind(&Fem3DRepresentationPlyReaderDelegate::beginPolyhedrons,
this,
std::placeholders::_1,
std::placeholders::_2),
std::bind(&Fem3DRepresentationPlyReaderDelegate::processPolyhedron, this, std::placeholders::_1),
std::bind(&Fem3DRepresentationPlyReaderDelegate::endPolyhedrons, this, std::placeholders::_1));
reader->requestListProperty("polyhedron",
"vertex_indices",
PlyReader::TYPE_UNSIGNED_INT,
offsetof(PolyhedronData, indicies),
PlyReader::TYPE_UNSIGNED_INT,
offsetof(PolyhedronData, vertexCount));
reader->requestElement(
"material",
std::bind(
&Fem3DRepresentationPlyReaderDelegate::beginMaterials, this, std::placeholders::_1, std::placeholders::_2),
nullptr,
nullptr);
reader->requestScalarProperty(
"material", "mass_density", PlyReader::TYPE_DOUBLE, offsetof(MaterialData, massDensity));
reader->requestScalarProperty(
"material", "poisson_ratio", PlyReader::TYPE_DOUBLE, offsetof(MaterialData, poissonRatio));
reader->requestScalarProperty(
"material", "young_modulus", PlyReader::TYPE_DOUBLE, offsetof(MaterialData, youngModulus));
// Boundary Condition Processing
if (m_hasBoundaryConditions)
{
reader->requestElement(
"boundary_condition",
std::bind(&Fem3DRepresentationPlyReaderDelegate::beginBoundaryConditions,
this,
std::placeholders::_1,
std::placeholders::_2),
std::bind(&Fem3DRepresentationPlyReaderDelegate::processBoundaryCondition, this, std::placeholders::_1),
nullptr);
reader->requestScalarProperty("boundary_condition", "vertex_index", PlyReader::TYPE_UNSIGNED_INT, 0);
}
reader->setStartParseFileCallback(std::bind(&Fem3DRepresentationPlyReaderDelegate::startParseFile, this));
reader->setEndParseFileCallback(std::bind(&Fem3DRepresentationPlyReaderDelegate::endParseFile, this));
return true;
}
void Fem3DRepresentationPlyReaderDelegate::startParseFile()
{
SURGSIM_ASSERT(m_fem != nullptr) << "The Representation cannot be nullptr.";
SURGSIM_ASSERT(m_fem->getNumFemElements() == 0)
<< "The Representation already contains fem elements, so it cannot be initialized.";
SURGSIM_ASSERT(m_fem->getInitialState() == nullptr)
<< "The Representation's initial state must be uninitialized.";
m_state = std::make_shared<SurgSim::Math::OdeState>();
}
void Fem3DRepresentationPlyReaderDelegate::endParseFile()
{
for (size_t i = 0; i < m_fem->getNumFemElements(); i++)
{
m_fem->getFemElement(i)->setMassDensity(m_materialData.massDensity);
m_fem->getFemElement(i)->setPoissonRatio(m_materialData.poissonRatio);
m_fem->getFemElement(i)->setYoungModulus(m_materialData.youngModulus);
}
m_fem->setInitialState(m_state);
}
void* Fem3DRepresentationPlyReaderDelegate::beginVertices(const std::string& elementName, size_t vertexCount)
{
m_state->setNumDof(3, vertexCount);
vertexIterator = m_state->getPositions().data();
return m_vertexData.data();
}
void Fem3DRepresentationPlyReaderDelegate::processVertex(const std::string& elementName)
{
std::copy(std::begin(m_vertexData), std::end(m_vertexData), vertexIterator);
vertexIterator += 3;
}
void Fem3DRepresentationPlyReaderDelegate::endVertices(const std::string& elementName)
{
vertexIterator = nullptr;
}
void* Fem3DRepresentationPlyReaderDelegate::beginPolyhedrons(const std::string& elementName, size_t polyhedronCount)
{
return &m_polyhedronData;
}
void Fem3DRepresentationPlyReaderDelegate::processPolyhedron(const std::string& elementName)
{
SURGSIM_ASSERT(m_polyhedronData.vertexCount == 4) << "Cannot process polyhedron with "
<< m_polyhedronData.vertexCount << " vertices.";
std::array<unsigned int, 4> polyhedronVertices;
std::copy(m_polyhedronData.indicies, m_polyhedronData.indicies + 4, polyhedronVertices.begin());
m_fem->addFemElement(std::make_shared<Fem3DElementTetrahedron>(polyhedronVertices));
}
void Fem3DRepresentationPlyReaderDelegate::endPolyhedrons(const std::string& elementName)
{
m_polyhedronData.indicies = nullptr;
}
void* Fem3DRepresentationPlyReaderDelegate::beginMaterials(const std::string& elementName, size_t materialCount)
{
return &m_materialData;
}
void* Fem3DRepresentationPlyReaderDelegate::beginBoundaryConditions(const std::string& elementName,
size_t boundaryConditionCount)
{
return &m_boundaryConditionData;
}
void Fem3DRepresentationPlyReaderDelegate::processBoundaryCondition(const std::string& elementName)
{
m_state->addBoundaryCondition(m_boundaryConditionData);
}
} // namespace SurgSim
} // namespace DataStructures
<|endoftext|> |
<commit_before>#include "Planned.h"
#include "BlackCrow.h"
#include <BWEM/bwem.h>
#include "Geyser.h"
#include "Macro.h"
namespace BlackCrow {
using namespace BWAPI;
using namespace Filter;
Planned::Planned(BlackCrow &parent) : bc(parent), status(Status::ACTIVE) {}
// Planned Unit
PlannedUnit::PlannedUnit(BlackCrow &parent, BWAPI::UnitType type, BWAPI::Position nearTo) : Planned(parent), type(type), nearTo(nearTo) {}
int PlannedUnit::getMineralPrice() {
if (!unit || unit->getType() == UnitTypes::Zerg_Larva)
return type.mineralPrice();
else
return 0;
}
int PlannedUnit::getGasPrice() {
if (!unit || unit->getType() == UnitTypes::Zerg_Larva)
return type.gasPrice();
else
return 0;
}
void PlannedUnit::onFrame() {
if (status == Status::FAILED)
return;
// Was unit/larva/egg killed?
if (status == Status::ACTIVE && unit && !unit->exists() && alreadyGrabbedLarva) {
status = Status::FAILED;
return;
}
// When we have no larva, grab one
if (!unit) {
unit = bc.macro.getUnreservedLarva(nearTo);
if (unit) {
alreadyGrabbedLarva = true;
} else {
return;
}
}
// Can we morph it?
if (unit && unit->getType() == UnitTypes::Zerg_Larva)
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice())
unit->morph(type);
// Is it finished?
if (unit && unit->getType() == type && unit->isCompleted()) {
status = Status::COMPLETED;
if (type == UnitTypes::Zerg_Drone) {
bc.macro.addDrone(unit);
} else {
if (type != UnitTypes::Zerg_Overlord) {
bc.army.assignAutomaticAttackSquad(bc.army.addToArmy(unit));
}
}
}
}
BWAPI::Unit PlannedUnit::reservedLarva() {
/*if (unit && unit->getType() == UnitTypes::Zerg_Larva)
return unit;
else
return nullptr;*/
return unit;
}
float PlannedUnit::progressPercent() {
if (unit) {
if (unit->getType() == UnitTypes::Zerg_Egg) {
return ((float)unit->getRemainingBuildTime() / (float)type.buildTime());
}
}
return 0;
}
std::string PlannedUnit::getName() {
return type.getName();
}
// Planned Building
PlannedBuilding::PlannedBuilding(BlackCrow &parent, BWAPI::UnitType type, BWAPI::TilePosition buildPosition) : Planned(parent), type(type), buildPosition(buildPosition) {
if (type == UnitTypes::Zerg_Extractor)
assert(!"Wrong Building Type. Use PlannedExtractor instead of PlannedBuilding for building an extractor");
}
int PlannedBuilding::getMineralPrice() {
if (droneOrBuilding && droneOrBuilding->getType().isBuilding())
return 0;
else
return type.mineralPrice();
}
int PlannedBuilding::getGasPrice() {
if (droneOrBuilding && droneOrBuilding->getType().isBuilding())
return 0;
else
return type.gasPrice();
}
void PlannedBuilding::onFrame() {
if (status == Status::FAILED || status == Status::COMPLETED)
return;
if (!droneOrBuilding) {
droneOrBuilding = bc.macro.getDroneForBuilding(Position(buildPosition));
if (!droneOrBuilding)
return;
}
if (status == Status::ACTIVE && droneOrBuilding && !droneOrBuilding->exists()) {
status = Status::FAILED;
return;
}
if (!droneOrBuilding->getType().isBuilding()) {
Position buildingCenter = Position(buildPosition) + Util::middleOfBuilding(type);
if (Util::distance(droneOrBuilding->getPosition(), buildingCenter) <= BWAPI::UnitTypes::Zerg_Drone.sightRange() * 0.8) {
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice()) {
if (!droneOrBuilding->build(type, buildPosition)) { // Check instead if drone is busy or something?
// TODO Error Spam
if (Broodwar->getLastError() != BWAPI::Errors::Unit_Busy) {
//Broodwar << Broodwar->getLastError() << std::endl;
// TODO Spam of NONE NONE NONE when building could not be placed
// Mark tiles where to build as "markedForBuilding" and squad units should avoid that space
}
}
}
} else {
droneOrBuilding->move(buildingCenter);
}
} else {
if (droneOrBuilding->isCompleted())
status = Status::COMPLETED;
}
}
float PlannedBuilding::progressPercent() {
if (droneOrBuilding && droneOrBuilding->getType().isBuilding()) {
return ((float)droneOrBuilding->getRemainingBuildTime() / (float)droneOrBuilding->getType().buildTime());
}
return 0;
}
std::string PlannedBuilding::getName() {
return type.getName();
}
// Planned Extractor
PlannedExtractor::PlannedExtractor(BlackCrow &parent, Geyser& geyser) : Planned(parent), geyser(geyser) {
geyser.registerPlannedExtractor(*this);
}
int PlannedExtractor::getMineralPrice() {
if (!alreadyBuiltExtractor)
return UnitTypes::Zerg_Extractor.mineralPrice();
else
return 0;
}
int PlannedExtractor::getGasPrice() {
if (!alreadyBuiltExtractor)
return UnitTypes::Zerg_Extractor.gasPrice();
else
return 0;
}
void PlannedExtractor::onFrame() {
if (status == Status::FAILED || status == Status::COMPLETED) {
geyser.unregisterPlannedExtractor(*this);
return;
}
if (!drone)
drone = bc.macro.getDroneForBuilding(geyser.bwemGeyser->Pos());
if (drone && drone->exists()) {
if(drone->build(UnitTypes::Zerg_Extractor, geyser.bwemGeyser->TopLeft()))
alreadyBuiltExtractor = true;
} else if(alreadyBuiltExtractor) {
if (!geyser.geyserUnit || !geyser.geyserUnit->exists()) {
auto unitsOnGeyser = Broodwar->getUnitsOnTile(geyser.bwemGeyser->TopLeft(), IsRefinery && IsBuilding);
if (unitsOnGeyser.size() > 0) {
geyser.geyserUnit = *unitsOnGeyser.begin();
geyserUnitFound = true;
}
if (unitsOnGeyser.size() > 1)
Broodwar->sendText("Found more than 1 building for extractor");
} else if (geyser.geyserUnit->isCompleted()) {
status = Status::COMPLETED;
}
}
if ((status == Status::ACTIVE && drone && !drone->exists() && !alreadyBuiltExtractor) // Drone died during building
|| (status == Status::ACTIVE && alreadyBuiltExtractor && geyserUnitFound && !geyser.geyserUnit->exists()) // Extractor was killed while constructing
) {
status = Status::FAILED;
return;
}
}
float PlannedExtractor::progressPercent() {
if (geyser.geyserUnit) {
return ((float)geyser.geyserUnit->getRemainingBuildTime() / (float)geyser.geyserUnit->getType().buildTime());
}
return 0;
}
std::string PlannedExtractor::getName() {
return UnitTypes::Zerg_Extractor.getName();
}
// Planned Tech
PlannedTech::PlannedTech(BlackCrow& parent, BWAPI::TechType type) : Planned(parent), type(type) {}
int PlannedTech::getMineralPrice() {
return type.mineralPrice();
}
int PlannedTech::getGasPrice() {
return type.gasPrice();
}
void PlannedTech::onFrame() {
Broodwar->sendText("PlannedTech onFrame() not implemented");
}
float PlannedTech::progressPercent() {
return 0;
}
std::string PlannedTech::getName() {
return type.getName();
}
// Planned Upgrade
PlannedUpgrade::PlannedUpgrade(BlackCrow& parent, BWAPI::UpgradeType type, int level) : Planned(parent), type(type), level(level) {}
int PlannedUpgrade::getMineralPrice() {
if (researchingBuilding && researchingBuilding->isUpgrading())
return 0;
else
return type.mineralPrice();
}
int PlannedUpgrade::getGasPrice() {
if (researchingBuilding && researchingBuilding->isUpgrading())
return 0;
else
return type.gasPrice();
}
void PlannedUpgrade::onFrame() {
if (researchingBuilding && !researchingBuilding->exists()) {
status = Status::FAILED;
return;
}
if (status == Status::ACTIVE && !researchingBuilding) {
auto ownUnits = Broodwar->self()->getUnits();
auto freeSpawningPoolIt = std::find_if(ownUnits.begin(), ownUnits.end(), [&](BWAPI::Unit unit) { return unit->getType() == type.whatUpgrades() && !unit->isUpgrading(); });
if (freeSpawningPoolIt != ownUnits.end()) {
researchingBuilding = *freeSpawningPoolIt;
}
}
if (status == Status::ACTIVE && researchingBuilding)
if (!researchingBuilding->isUpgrading() && researchingBuilding->canUpgrade())
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice())
researchingBuilding->upgrade(type);
if (status == Status::ACTIVE && Broodwar->self()->getUpgradeLevel(type) >= level)
status = Status::COMPLETED;
}
float PlannedUpgrade::progressPercent() {
if (researchingBuilding && researchingBuilding->isUpgrading())
return (float)researchingBuilding->getRemainingUpgradeTime() / (float)type.upgradeTime(level);
else
return 0;
}
std::string PlannedUpgrade::getName() {
return "\x1F" + type.getName();
}
}<commit_msg>Planned buildings only grab a drone when resources are available<commit_after>#include "Planned.h"
#include "BlackCrow.h"
#include <BWEM/bwem.h>
#include "Geyser.h"
#include "Macro.h"
namespace BlackCrow {
using namespace BWAPI;
using namespace Filter;
Planned::Planned(BlackCrow &parent) : bc(parent), status(Status::ACTIVE) {}
// Planned Unit
PlannedUnit::PlannedUnit(BlackCrow &parent, BWAPI::UnitType type, BWAPI::Position nearTo) : Planned(parent), type(type), nearTo(nearTo) {}
int PlannedUnit::getMineralPrice() {
if (!unit || unit->getType() == UnitTypes::Zerg_Larva)
return type.mineralPrice();
else
return 0;
}
int PlannedUnit::getGasPrice() {
if (!unit || unit->getType() == UnitTypes::Zerg_Larva)
return type.gasPrice();
else
return 0;
}
void PlannedUnit::onFrame() {
if (status == Status::FAILED)
return;
// Was unit/larva/egg killed?
if (status == Status::ACTIVE && unit && !unit->exists() && alreadyGrabbedLarva) {
status = Status::FAILED;
return;
}
// When we have no larva, grab one
if (!unit) {
unit = bc.macro.getUnreservedLarva(nearTo);
if (unit) {
alreadyGrabbedLarva = true;
} else {
return;
}
}
// Can we morph it?
if (unit && unit->getType() == UnitTypes::Zerg_Larva)
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice())
unit->morph(type);
// Is it finished?
if (unit && unit->getType() == type && unit->isCompleted()) {
status = Status::COMPLETED;
if (type == UnitTypes::Zerg_Drone) {
bc.macro.addDrone(unit);
} else {
if (type != UnitTypes::Zerg_Overlord) {
bc.army.assignAutomaticAttackSquad(bc.army.addToArmy(unit));
}
}
}
}
BWAPI::Unit PlannedUnit::reservedLarva() {
/*if (unit && unit->getType() == UnitTypes::Zerg_Larva)
return unit;
else
return nullptr;*/
return unit;
}
float PlannedUnit::progressPercent() {
if (unit) {
if (unit->getType() == UnitTypes::Zerg_Egg) {
return ((float)unit->getRemainingBuildTime() / (float)type.buildTime());
}
}
return 0;
}
std::string PlannedUnit::getName() {
return type.getName();
}
// Planned Building
PlannedBuilding::PlannedBuilding(BlackCrow &parent, BWAPI::UnitType type, BWAPI::TilePosition buildPosition) : Planned(parent), type(type), buildPosition(buildPosition) {
if (type == UnitTypes::Zerg_Extractor)
assert(!"Wrong Building Type. Use PlannedExtractor instead of PlannedBuilding for building an extractor");
}
int PlannedBuilding::getMineralPrice() {
if (droneOrBuilding && droneOrBuilding->getType().isBuilding())
return 0;
else
return type.mineralPrice();
}
int PlannedBuilding::getGasPrice() {
if (droneOrBuilding && droneOrBuilding->getType().isBuilding())
return 0;
else
return type.gasPrice();
}
void PlannedBuilding::onFrame() {
if (status == Status::FAILED || status == Status::COMPLETED)
return;
if (!droneOrBuilding) {
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice()) {
droneOrBuilding = bc.macro.getDroneForBuilding(Position(buildPosition));
if (!droneOrBuilding)
return;
} else
return;
}
if (status == Status::ACTIVE && droneOrBuilding && !droneOrBuilding->exists()) {
status = Status::FAILED;
return;
}
if (!droneOrBuilding->getType().isBuilding()) {
Position buildingCenter = Position(buildPosition) + Util::middleOfBuilding(type);
if (Util::distance(droneOrBuilding->getPosition(), buildingCenter) <= BWAPI::UnitTypes::Zerg_Drone.sightRange() * 0.8) {
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice()) {
if (!droneOrBuilding->build(type, buildPosition)) { // Check instead if drone is busy or something?
// TODO Error Spam
if (Broodwar->getLastError() != BWAPI::Errors::Unit_Busy) {
//Broodwar << Broodwar->getLastError() << std::endl;
// TODO Spam of NONE NONE NONE when building could not be placed
// Mark tiles where to build as "markedForBuilding" and squad units should avoid that space
}
}
}
} else {
droneOrBuilding->move(buildingCenter);
}
} else {
if (droneOrBuilding->isCompleted())
status = Status::COMPLETED;
}
}
float PlannedBuilding::progressPercent() {
if (droneOrBuilding && droneOrBuilding->getType().isBuilding()) {
return ((float)droneOrBuilding->getRemainingBuildTime() / (float)droneOrBuilding->getType().buildTime());
}
return 0;
}
std::string PlannedBuilding::getName() {
return type.getName();
}
// Planned Extractor
PlannedExtractor::PlannedExtractor(BlackCrow &parent, Geyser& geyser) : Planned(parent), geyser(geyser) {
geyser.registerPlannedExtractor(*this);
}
int PlannedExtractor::getMineralPrice() {
if (!alreadyBuiltExtractor)
return UnitTypes::Zerg_Extractor.mineralPrice();
else
return 0;
}
int PlannedExtractor::getGasPrice() {
if (!alreadyBuiltExtractor)
return UnitTypes::Zerg_Extractor.gasPrice();
else
return 0;
}
void PlannedExtractor::onFrame() {
if (status == Status::FAILED || status == Status::COMPLETED) {
geyser.unregisterPlannedExtractor(*this);
return;
}
if (!drone)
drone = bc.macro.getDroneForBuilding(geyser.bwemGeyser->Pos());
if (drone && drone->exists()) {
if(drone->build(UnitTypes::Zerg_Extractor, geyser.bwemGeyser->TopLeft()))
alreadyBuiltExtractor = true;
} else if(alreadyBuiltExtractor) {
if (!geyser.geyserUnit || !geyser.geyserUnit->exists()) {
auto unitsOnGeyser = Broodwar->getUnitsOnTile(geyser.bwemGeyser->TopLeft(), IsRefinery && IsBuilding);
if (unitsOnGeyser.size() > 0) {
geyser.geyserUnit = *unitsOnGeyser.begin();
geyserUnitFound = true;
}
if (unitsOnGeyser.size() > 1)
Broodwar->sendText("Found more than 1 building for extractor");
} else if (geyser.geyserUnit->isCompleted()) {
status = Status::COMPLETED;
}
}
if ((status == Status::ACTIVE && drone && !drone->exists() && !alreadyBuiltExtractor) // Drone died during building
|| (status == Status::ACTIVE && alreadyBuiltExtractor && geyserUnitFound && !geyser.geyserUnit->exists()) // Extractor was killed while constructing
) {
status = Status::FAILED;
return;
}
}
float PlannedExtractor::progressPercent() {
if (geyser.geyserUnit) {
return ((float)geyser.geyserUnit->getRemainingBuildTime() / (float)geyser.geyserUnit->getType().buildTime());
}
return 0;
}
std::string PlannedExtractor::getName() {
return UnitTypes::Zerg_Extractor.getName();
}
// Planned Tech
PlannedTech::PlannedTech(BlackCrow& parent, BWAPI::TechType type) : Planned(parent), type(type) {}
int PlannedTech::getMineralPrice() {
return type.mineralPrice();
}
int PlannedTech::getGasPrice() {
return type.gasPrice();
}
void PlannedTech::onFrame() {
Broodwar->sendText("PlannedTech onFrame() not implemented");
}
float PlannedTech::progressPercent() {
return 0;
}
std::string PlannedTech::getName() {
return type.getName();
}
// Planned Upgrade
PlannedUpgrade::PlannedUpgrade(BlackCrow& parent, BWAPI::UpgradeType type, int level) : Planned(parent), type(type), level(level) {}
int PlannedUpgrade::getMineralPrice() {
if (researchingBuilding && researchingBuilding->isUpgrading())
return 0;
else
return type.mineralPrice();
}
int PlannedUpgrade::getGasPrice() {
if (researchingBuilding && researchingBuilding->isUpgrading())
return 0;
else
return type.gasPrice();
}
void PlannedUpgrade::onFrame() {
if (researchingBuilding && !researchingBuilding->exists()) {
status = Status::FAILED;
return;
}
if (status == Status::ACTIVE && !researchingBuilding) {
auto ownUnits = Broodwar->self()->getUnits();
auto freeSpawningPoolIt = std::find_if(ownUnits.begin(), ownUnits.end(), [&](BWAPI::Unit unit) { return unit->getType() == type.whatUpgrades() && !unit->isUpgrading(); });
if (freeSpawningPoolIt != ownUnits.end()) {
researchingBuilding = *freeSpawningPoolIt;
}
}
if (status == Status::ACTIVE && researchingBuilding)
if (!researchingBuilding->isUpgrading() && researchingBuilding->canUpgrade())
if (Broodwar->self()->minerals() >= type.mineralPrice() && Broodwar->self()->gas() >= type.gasPrice())
researchingBuilding->upgrade(type);
if (status == Status::ACTIVE && Broodwar->self()->getUpgradeLevel(type) >= level)
status = Status::COMPLETED;
}
float PlannedUpgrade::progressPercent() {
if (researchingBuilding && researchingBuilding->isUpgrading())
return (float)researchingBuilding->getRemainingUpgradeTime() / (float)type.upgradeTime(level);
else
return 0;
}
std::string PlannedUpgrade::getName() {
return "\x1F" + type.getName();
}
}<|endoftext|> |
<commit_before>#include "AM2320.h"
#include <Wire.h>
//
// AM2321 Temperature & Humidity Sensor library for Arduino
// Сделана Тимофеевым Е.Н. из AM2320-master
unsigned int CRC16(byte *ptr, byte length)
{
unsigned int crc = 0xFFFF;
uint8_t s = 0x00;
while(length--) {
crc ^= *ptr++;
for(s = 0; s < 8; s++) {
if((crc & 0x01) != 0) {
crc >>= 1;
crc ^= 0xA001;
} else crc >>= 1;
}
}
return crc;
}
AM2320::AM2320()
{
}
int AM2320::Read()
{
byte buf[8];
for(int s = 0; s < 8; s++) buf[s] = 0x00;
Wire.beginTransmission(AM2320_address);
Wire.endTransmission();
// запрос 4 байт (температуры и влажности)
Wire.beginTransmission(AM2320_address);
Wire.write(0x03);// запрос
Wire.write(0x00); // с 0-го адреса
Wire.write(0x04); // 4 байта
if (Wire.endTransmission(1) != 0) return 1;
delayMicroseconds(1600); //>1.5ms
// считываем результаты запроса
Wire.requestFrom(AM2320_address, 0x08);
for (int i = 0; i < 0x08; i++) buf[i] = Wire.read();
// CRC check
unsigned int Rcrc = buf[7] << 8;
Rcrc += buf[6];
if (Rcrc == CRC16(buf, 6)) {
unsigned int temperature = ((buf[4] & 0x7F) << 8) + buf[5];
t = temperature / 10.0;
t = ((buf[4] & 0x80) >> 7) == 1 ? t * (-1) : t;
unsigned int humidity = (buf[2] << 8) + buf[3];
h = humidity / 10.0;
return 0;
}
return 2;
}
<commit_msg>Update AM2320.cpp<commit_after>#include "AM2320.h"
#include < Wire.h >
// AM2320 Temperature & Humidity Sensor library for Arduino
// Modified by Timofeev E.N. from https://github.com/thakshak/AM2320/
unsigned int CRC16(byte * ptr, byte length) {
unsigned int crc = 0xFFFF;
uint8_t s = 0x00;
while (length--) {
crc ^ = * ptr++;
for (s = 0; s < 8; s++) {
if ((crc & 0x01) ! = 0) {
crc >> = 1;
crc ^ = 0xA001;
} else crc >> = 1;
}
}
return crc;
}
AM2320::AM2320() {}
int AM2320::Read() {
byte buf[8];
for (int s = 0; s < 8; s++) buf[s] = 0x00;
Wire.beginTransmission(AM2320_address);
Wire.endTransmission();
// request 4 bytes (temperature and humidity)
Wire.beginTransmission(AM2320_address);
Wire.write(0x03); // request
Wire.write(0x00); // from the 0th address
Wire.write(0x04); // 4 bytes
if (Wire.endTransmission(1) ! = 0) return 1;
delayMicroseconds(1600); //>1.5ms
// read the query results
Wire.requestFrom(AM2320_address, 0x08);
for (int i = 0; i < 0x08; i++) buf[i] = Wire.read();
// CRC check
unsigned int Rcrc = buf[7] << 8;
Rcrc + = buf[6];
if (Rcrc == CRC16(buf, 6)) {
unsigned int temperature = ((buf[4] & 0x7F) << 8) + buf[5];
t = temperature / 10.0;
t = ((buf[4] & 0x80) >> 7) == 1 ? t * (-1) : t;
unsigned int humidity = (buf[2] << 8) + buf[3];
h = humidity / 10.0;
return 0;
}
return 2;
}
<|endoftext|> |
<commit_before><commit_msg>created pipeline cache, renderpass and framebuffer then started working on moving the vertex data to gpu memory<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <set>
#include "otbImage.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionReverseIterator.h"
#include "itkImageRandomIteratorWithIndex.h"
#include "itkImageScanlineIterator.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "otbSubsampledImageRegionIterator.h"
#include "otbMaskedIteratorDecorator.h"
// Generate a test image of specified size and value
template <typename ImageType>
typename ImageType::Pointer GetTestImage(itk::SizeValueType fillSize, const typename ImageType::PixelType& value)
{
typename ImageType::Pointer image = ImageType::New();
typename ImageType::SizeType size;
size.Fill(fillSize);
typename ImageType::RegionType region;
region.SetSize(size);
image->SetRegions(region);
image->Allocate();
image->FillBuffer(value);
return image;
}
// Fill half of the pixels with a value
// Used for generating a test mask
template <typename ImageType>
void FillHalf(typename ImageType::Pointer image, const typename ImageType::RegionType& region, const typename ImageType::PixelType& value)
{
itk::ImageRegionIterator<ImageType> it(image, region);
unsigned int count = 0;
for(it.GoToBegin(); !it.IsAtEnd(); ++it, ++count)
{
if (count % 2 == 0)
{
it.Set(value);
}
}
}
// Test template instanciation
int otbMaskedIteratorDecoratorNew(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
ImageType::RegionType region(image->GetLargestPossibleRegion());
otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region);
return EXIT_SUCCESS;
}
// Test forward iteration interface
int otbMaskedIteratorDecoratorForward(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
ImageType::RegionType region(image->GetLargestPossibleRegion());
FillHalf<ImageType>(mask, region, 1);
otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region);
it.GoToBegin();
if (!it.IsAtBegin()) {return EXIT_FAILURE;}
unsigned int loopCount = 0;
for(; !it.IsAtEnd(); ++it)
{
if (loopCount != 0 && it.IsAtBegin()) {return EXIT_FAILURE;}
if (it.IsAtEnd()) {return EXIT_FAILURE;}
it.Set(it.Value() * 0.42);
loopCount += 1;
}
if(!it.IsAtEnd()) {return EXIT_FAILURE;}
return EXIT_SUCCESS;
}
// Test reverse iteration interface
int otbMaskedIteratorDecoratorReverse(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
ImageType::RegionType region(image->GetLargestPossibleRegion());
FillHalf<ImageType>(mask, region, 1);
otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region);
it.GoToEnd();
if (!it.IsAtEnd()) {return EXIT_FAILURE;}
bool beginReached = false;
do
{
--it;
if (it.IsAtEnd()) {return EXIT_FAILURE;}
if (it.IsAtBegin())
{
if (beginReached)
{
return EXIT_FAILURE;
}
else {
beginReached = true;
}
}
it.Set(it.Value() * 0.42);
} while (!it.IsAtBegin());
if(!it.IsAtBegin()) {return EXIT_FAILURE;}
return EXIT_SUCCESS;
}
// Check bijection between iterated and non masked
// i.e all locations where mask value != 0 are in the iteration (injection)
// and mask value != 0 at all iteration locations (surjection)
// Templated to test decoration of different iterator types
template <typename ImageType, template <class> class IteratorType>
int BijectiveTest()
{
typename ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
typename ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
typename ImageType::RegionType region(image->GetLargestPossibleRegion());
FillHalf<ImageType>(mask, region, 1);
otb::MaskedIteratorDecorator<IteratorType<ImageType> > itDecorated(mask, image, region);
IteratorType<ImageType> it(image, region);
it.GoToBegin();
itDecorated.GoToBegin();
while (!it.IsAtEnd() && itDecorated.IsAtEnd())
{
// Iteration locations are the same
if (it.GetIndex() != itDecorated.GetIndex()) {return EXIT_FAILURE;}
++itDecorated;
do
{
++it;
} while (mask->GetPixel(it.GetIndex()) == 0 && !it.IsAtEnd());
}
return EXIT_SUCCESS;
}
int otbMaskedIteratorDecoratorBijective(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
return BijectiveTest<ImageType, itk::ImageRegionIterator>()
&& BijectiveTest<ImageType, itk::ImageRegionConstIterator>()
&& BijectiveTest<ImageType, itk::ImageRandomConstIteratorWithIndex>()
&& BijectiveTest<ImageType, otb::SubsampledImageRegionIterator>()
&& BijectiveTest<ImageType, itk::ImageRandomIteratorWithIndex>()
&& BijectiveTest<ImageType, itk::ImageScanlineIterator>()
&& BijectiveTest<ImageType, itk::ImageScanlineConstIterator>()
&& BijectiveTest<ImageType, itk::ImageRandomNonRepeatingConstIteratorWithIndex>()
&& BijectiveTest<ImageType, itk::ImageRandomNonRepeatingIteratorWithIndex>()
;
// Other iterators potentially compatible:
// Different template interface, testable but not with BijectiveTest:
// itk::PathIterator
// itk::NeighborhoodIterator
// itk::DataObjectIterator
// Different constructor, testable but not with BijectiveTest
// itk::LineIterator
// itk::SliceIterator
// GoToEnd is not implemented
// itk::ImageLinearIteratorWithIndex
// itk::ReflectiveImageRegionIterator
// itk::ImageRegionExclusionConstIteratorWithIndex
// itk::ImageRegionIteratorWithIndex
// Other problem:
// itk::ImageRegionReverseIterator>() // IsAtEnd not a const method
// otb::PolyLineImageIterator>() // header not found
// itk::ImageRandomConstIteratorWithOnlyIndex>() // no Value method
}
<commit_msg>ENH: Simplify MaskedIteratorDecorator test code<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include <set>
#include "otbImage.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionReverseIterator.h"
#include "itkImageRandomIteratorWithIndex.h"
#include "itkImageScanlineIterator.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "otbSubsampledImageRegionIterator.h"
#include "otbMaskedIteratorDecorator.h"
// Generate a test image of specified size and value
template <typename ImageType>
typename ImageType::Pointer GetTestImage(itk::SizeValueType fillSize, const typename ImageType::PixelType& value)
{
typename ImageType::Pointer image = ImageType::New();
typename ImageType::SizeType size;
size.Fill(fillSize);
typename ImageType::RegionType region;
region.SetSize(size);
image->SetRegions(region);
image->Allocate();
image->FillBuffer(value);
return image;
}
// Fill half of the pixels with a value
// Used for generating a test mask
template <typename ImageType>
void FillHalf(typename ImageType::Pointer image, const typename ImageType::RegionType& region, const typename ImageType::PixelType& value)
{
itk::ImageRegionIterator<ImageType> it(image, region);
unsigned int count = 0;
for(it.GoToBegin(); !it.IsAtEnd(); ++it, ++count)
{
if (count % 2 == 0)
{
it.Set(value);
}
}
}
// Test template instanciation
int otbMaskedIteratorDecoratorNew(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
ImageType::RegionType region(image->GetLargestPossibleRegion());
otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region);
return EXIT_SUCCESS;
}
// Test forward iteration interface
int otbMaskedIteratorDecoratorForward(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
ImageType::RegionType region(image->GetLargestPossibleRegion());
FillHalf<ImageType>(mask, region, 1);
otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region);
it.GoToBegin();
if (!it.IsAtBegin()) {return EXIT_FAILURE;}
unsigned int loopCount = 0;
for(; !it.IsAtEnd(); ++it)
{
if (loopCount != 0 && it.IsAtBegin()) {return EXIT_FAILURE;}
if (it.IsAtEnd()) {return EXIT_FAILURE;}
it.Set(it.Value() * 0.42);
loopCount += 1;
}
if(!it.IsAtEnd()) {return EXIT_FAILURE;}
return EXIT_SUCCESS;
}
// Test reverse iteration interface
int otbMaskedIteratorDecoratorReverse(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
ImageType::Pointer image = GetTestImage<ImageType>(10, 10);
ImageType::Pointer mask = GetTestImage<ImageType>(10, 0);
ImageType::RegionType region(image->GetLargestPossibleRegion());
FillHalf<ImageType>(mask, region, 1);
otb::MaskedIteratorDecorator<itk::ImageRegionIterator<ImageType> > it(mask, image, region);
it.GoToEnd();
if (!it.IsAtEnd()) {return EXIT_FAILURE;}
bool beginReached = false;
do
{
--it;
if (it.IsAtEnd()) {return EXIT_FAILURE;}
if (it.IsAtBegin())
{
if (beginReached)
{
return EXIT_FAILURE;
}
else {
beginReached = true;
}
}
it.Set(it.Value() * 0.42);
} while (!it.IsAtBegin());
if(!it.IsAtBegin()) {return EXIT_FAILURE;}
return EXIT_SUCCESS;
}
// Check bijection between iterated and non masked
// i.e all locations where mask value != 0 are in the iteration (injection)
// and mask value != 0 at all iteration locations (surjection)
// Templated to test decoration of different iterator types
template <typename IteratorType>
int BijectiveTest()
{
typename IteratorType::ImageType::Pointer image = GetTestImage<typename IteratorType::ImageType>(10, 10);
typename IteratorType::ImageType::Pointer mask = GetTestImage<typename IteratorType::ImageType>(10, 0);
typename IteratorType::ImageType::RegionType region(image->GetLargestPossibleRegion());
FillHalf<typename IteratorType::ImageType>(mask, region, 1);
otb::MaskedIteratorDecorator<IteratorType> itDecorated(mask, image, region);
IteratorType it(image, region);
it.GoToBegin();
itDecorated.GoToBegin();
while (!it.IsAtEnd() && itDecorated.IsAtEnd())
{
// Iteration locations are the same
if (it.GetIndex() != itDecorated.GetIndex()) {return EXIT_FAILURE;}
++itDecorated;
do
{
++it;
} while (mask->GetPixel(it.GetIndex()) == 0 && !it.IsAtEnd());
}
return EXIT_SUCCESS;
}
int otbMaskedIteratorDecoratorBijective(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef otb::Image<double, 2> ImageType;
return BijectiveTest< itk::ImageRegionIterator<ImageType> >()
&& BijectiveTest< itk::ImageRegionConstIterator<ImageType> >()
&& BijectiveTest< itk::ImageRandomConstIteratorWithIndex<ImageType> >()
&& BijectiveTest< otb::SubsampledImageRegionIterator<ImageType> >()
&& BijectiveTest< itk::ImageRandomIteratorWithIndex<ImageType> >()
&& BijectiveTest< itk::ImageScanlineIterator<ImageType> >()
&& BijectiveTest< itk::ImageScanlineConstIterator<ImageType> >()
&& BijectiveTest< itk::ImageRandomNonRepeatingConstIteratorWithIndex<ImageType> >()
&& BijectiveTest< itk::ImageRandomNonRepeatingIteratorWithIndex<ImageType> >()
;
// Other iterators potentially compatible:
// Different constructor, testable but not with BijectiveTest
// itk::PathIterator
// itk::LineIterator
// itk::SliceIterator
// itk::NeighborhoodIterator
// GoToEnd is not implemented
// itk::ImageLinearIteratorWithIndex
// itk::ReflectiveImageRegionIterator
// itk::ImageRegionExclusionConstIteratorWithIndex
// itk::ImageRegionIteratorWithIndex
// Other problem:
// itk::ImageRegionReverseIterator>() // IsAtEnd not a const method
// otb::PolyLineImageIterator>() // header not found
// itk::ImageRandomConstIteratorWithOnlyIndex>() // no Value method
}
<|endoftext|> |
<commit_before>/** \file normalise_and_deduplicate_language.cc
* \brief Normalises language codes and removes duplicates from specific MARC record fields
* \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <cinttypes>
#include <cstring>
#include <unistd.h>
#include "IniFile.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbosity=min_verbosity] marc_input marc_output \n"
<< "\n";
std::exit(EXIT_FAILURE);
}
const std::string CONFIG_FILE_PATH("/usr/local/var/lib/tuelib/normalize_and_deduplicate_lang.conf");
const std::string LANGUAGE_CODE_OVERRIDE_SECTION("Overrides");
struct LanguageCodeParams {
static constexpr size_t MAX_LANGUAGE_CODE_LENGTH = 3;
std::unordered_map<std::string, std::string> variant_to_canonical_form_map_;
std::unordered_set<std::string> valid_language_codes_;
public:
inline bool isCanonical(const std::string &language_code) { return valid_language_codes_.find(language_code) != valid_language_codes_.end(); }
bool getCanonicalCode(const std::string &language_code, std::string * const canonical_code, bool fallback_to_original = true);
};
bool IsValidLanguageCodeLength(const std::string &language_code) {
return language_code.length() == LanguageCodeParams::MAX_LANGUAGE_CODE_LENGTH;
}
bool LanguageCodeParams::getCanonicalCode(const std::string &language_code, std::string * const canonical_code, bool fallback_to_original) {
if (isCanonical(language_code)) {
*canonical_code = language_code;
return true;
}
const auto match(variant_to_canonical_form_map_.find(language_code));
if (match != variant_to_canonical_form_map_.cend()) {
*canonical_code = match->second;
return true;
} else {
if (fallback_to_original)
*canonical_code = language_code;
return false;
}
}
void LoadLanguageCodesFromConfig(const IniFile &config, LanguageCodeParams * const params) {
std::vector<std::string> raw_language_codes;
StringUtil::Split(config.getString("", "canonical_language_codes"), ",", &raw_language_codes);
if (raw_language_codes.empty())
LOG_ERROR("Couldn't read canonical language codes from config file!");
for (const auto& language_code : raw_language_codes) {
if (not IsValidLanguageCodeLength(language_code))
LOG_ERROR("Invalid length for language code '" + language_code + "'!");
else if (params->isCanonical(language_code))
LOG_WARNING("Duplicate canonical language code '" + language_code + "' found!");
else
params->valid_language_codes_.insert(language_code);
}
for (const auto& variant : config.getSectionEntryNames(LANGUAGE_CODE_OVERRIDE_SECTION)) {
const auto canonical_name(config.getString(LANGUAGE_CODE_OVERRIDE_SECTION, variant));
if (not IsValidLanguageCodeLength(variant))
LOG_ERROR("Invalid length for language code '" + variant + "'!");
else if (not IsValidLanguageCodeLength(canonical_name))
LOG_ERROR("Invalid length for language code '" + canonical_name + "'!");
else if (not params->isCanonical(canonical_name))
LOG_ERROR("Unknown canonical language code '" + canonical_name + "' for variant '" + variant + "'!");
params->variant_to_canonical_form_map_.insert(std::make_pair(variant, canonical_name));
}
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
::progname = argv[0];
if (argc < 2)
Usage();
IniFile config_file(CONFIG_FILE_PATH);
LanguageCodeParams params;
std::unique_ptr<MARC::Reader> reader(MARC::Reader::Factory(argv[1]));
std::unique_ptr<MARC::Writer> writer(MARC::Writer::Factory(argv[2]));
LoadLanguageCodesFromConfig(config_file, ¶ms);
int num_records(0);
while (MARC::Record record = reader->read()) {
num_records++;
const auto ppn(record.findTag("001")->getContents());
const auto LogOutput = [&ppn, &num_records](const std::string &message, bool warning = false) {
const auto msg("Record '" + ppn + "' [" + std::to_string(num_records) + "]: " + message);
if (not warning)
LOG_INFO(msg);
else
LOG_WARNING(msg);
};
const auto tag_008(record.findTag("008"));
const auto tag_041(record.findTag("041"));
auto language_code_008(tag_008->getContents().substr(35, 3));
StringUtil::Trim(&language_code_008);
if (language_code_008.empty() or language_code_008 == "|||")
language_code_008.clear(); // to indicate absence in the case of '|||'
else {
std::string language_code_008_normalized;
if (not params.getCanonicalCode(language_code_008, &language_code_008_normalized))
LogOutput("Unknown language code variant '" + language_code_008 + "' in control field 008", true);
if (language_code_008 != language_code_008_normalized) {
LogOutput("Normalized control field 008 language code: '" + language_code_008
+ "' => " + language_code_008_normalized + "'");
auto old_content(tag_008->getContents());
old_content.replace(35, 3, language_code_008_normalized);
tag_008->setContents(old_content);
language_code_008 = language_code_008_normalized;
}
}
if (tag_041 == record.end()) {
if (not language_code_008.empty()) {
LogOutput("Copying language code '" + language_code_008 + "' from 008 => 041");
record.insertField("041", { { 'a', language_code_008 } });
}
} else {
// normalize and remove the existing records
MARC::Record::Field modified_tag_041(*tag_041);
MARC::Subfields modified_subfields;
bool propagate_changes(false);
std::unordered_set<std::string> unique_language_codes;
const auto indicator1(modified_tag_041.getIndicator1()), indicator2(modified_tag_041.getIndicator2());
for (auto& subfield : tag_041->getSubfields()) {
if (unique_language_codes.find(subfield.value_) != unique_language_codes.end()) {
LogOutput("Removing duplicate subfield entry 041$" + std::string(1, subfield.code_) +
" '" + subfield.value_ + "'");
propagate_changes = true;
continue;
}
std::string normalized_language_code;
if (not params.getCanonicalCode(subfield.value_, &normalized_language_code)) {
LogOutput("Unknown language code variant '" + subfield.value_ + "' in subfield 041$" +
std::string(1, subfield.code_), true);
}
if (normalized_language_code != subfield.value_) {
LogOutput("Normalized subfield 041$" + std::string(1, subfield.code_) +
" language code: '" + subfield.value_ + "' => '" + normalized_language_code + "'");
subfield.value_ = normalized_language_code;
propagate_changes = true;
}
unique_language_codes.insert(subfield.value_);
modified_subfields.addSubfield(subfield.code_, subfield.value_);
}
if (propagate_changes)
tag_041->setContents(modified_subfields, indicator1, indicator2);
}
writer->write(record);
}
return EXIT_SUCCESS;
}
<commit_msg>Update usage note, cosmetic<commit_after>/** \file normalise_and_deduplicate_language.cc
* \brief Normalises language codes and removes duplicates from specific MARC record fields
* \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <cinttypes>
#include <cstring>
#include <unistd.h>
#include "IniFile.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname << " [--verbosity=min_verbosity] marc_input marc_output \n"
<< " Normalises language codes and removes their duplicates from specific MARC "
"record fields (008 and 041)."
<< "\n";
std::exit(EXIT_FAILURE);
}
const std::string CONFIG_FILE_PATH("/usr/local/var/lib/tuelib/normalize_and_deduplicate_lang.conf");
const std::string LANGUAGE_CODE_OVERRIDE_SECTION("Overrides");
struct LanguageCodeParams {
static constexpr size_t LANGUAGE_CODE_LENGTH = 3;
std::unordered_map<std::string, std::string> variant_to_canonical_form_map_;
std::unordered_set<std::string> valid_language_codes_;
public:
inline bool isCanonical(const std::string &language_code) { return valid_language_codes_.find(language_code) != valid_language_codes_.end(); }
bool getCanonicalCode(const std::string &language_code, std::string * const canonical_code, const bool fallback_to_original = true);
};
bool HasValidLanguageCodeLength(const std::string &language_code) {
return language_code.length() == LanguageCodeParams::LANGUAGE_CODE_LENGTH;
}
bool LanguageCodeParams::getCanonicalCode(const std::string &language_code, std::string * const canonical_code, const bool fallback_to_original) {
if (isCanonical(language_code)) {
*canonical_code = language_code;
return true;
}
const auto match(variant_to_canonical_form_map_.find(language_code));
if (match != variant_to_canonical_form_map_.cend()) {
*canonical_code = match->second;
return true;
} else {
if (fallback_to_original)
*canonical_code = language_code;
return false;
}
}
void LoadLanguageCodesFromConfig(const IniFile &config, LanguageCodeParams * const params) {
std::vector<std::string> raw_language_codes;
StringUtil::Split(config.getString("", "canonical_language_codes"), ",", &raw_language_codes);
if (raw_language_codes.empty())
LOG_ERROR("Couldn't read canonical language codes from config file '" + CONFIG_FILE_PATH + "'!");
for (const auto &language_code : raw_language_codes) {
if (not HasValidLanguageCodeLength(language_code))
LOG_ERROR("Invalid length for language code '" + language_code + "'!");
else if (params->isCanonical(language_code))
LOG_WARNING("Duplicate canonical language code '" + language_code + "' found!");
else
params->valid_language_codes_.insert(language_code);
}
for (const auto &variant : config.getSectionEntryNames(LANGUAGE_CODE_OVERRIDE_SECTION)) {
const auto canonical_name(config.getString(LANGUAGE_CODE_OVERRIDE_SECTION, variant));
if (not HasValidLanguageCodeLength(variant))
LOG_ERROR("Invalid length for language code '" + variant + "'!");
else if (not HasValidLanguageCodeLength(canonical_name))
LOG_ERROR("Invalid length for language code '" + canonical_name + "'!");
else if (not params->isCanonical(canonical_name))
LOG_ERROR("Unknown canonical language code '" + canonical_name + "' for variant '" + variant + "'!");
params->variant_to_canonical_form_map_.insert(std::make_pair(variant, canonical_name));
}
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
::progname = argv[0];
if (argc < 2)
Usage();
IniFile config_file(CONFIG_FILE_PATH);
LanguageCodeParams params;
std::unique_ptr<MARC::Reader> reader(MARC::Reader::Factory(argv[1]));
std::unique_ptr<MARC::Writer> writer(MARC::Writer::Factory(argv[2]));
LoadLanguageCodesFromConfig(config_file, ¶ms);
int num_records(0);
while (MARC::Record record = reader->read()) {
++num_records;
const auto ppn(record.findTag("001")->getContents());
const auto LogOutput = [&ppn, &num_records](const std::string &message, bool warning = false) {
const auto msg("Record '" + ppn + "' [" + std::to_string(num_records) + "]: " + message);
if (not warning)
LOG_INFO(msg);
else
LOG_WARNING(msg);
};
const auto tag_008(record.findTag("008"));
const auto tag_041(record.findTag("041"));
auto language_code_008(tag_008->getContents().substr(35, 3));
StringUtil::Trim(&language_code_008);
if (language_code_008.empty() or language_code_008 == "|||")
language_code_008.clear(); // to indicate absence in the case of '|||'
else {
std::string language_code_008_normalized;
if (not params.getCanonicalCode(language_code_008, &language_code_008_normalized))
LogOutput("Unknown language code variant '" + language_code_008 + "' in control field 008", true);
if (language_code_008 != language_code_008_normalized) {
LogOutput("Normalized control field 008 language code: '" + language_code_008
+ "' => " + language_code_008_normalized + "'");
auto old_content(tag_008->getContents());
old_content.replace(35, 3, language_code_008_normalized);
tag_008->setContents(old_content);
language_code_008 = language_code_008_normalized;
}
}
if (tag_041 == record.end()) {
if (not language_code_008.empty()) {
LogOutput("Copying language code '" + language_code_008 + "' from 008 => 041");
record.insertField("041", { { 'a', language_code_008 } });
}
} else {
// normalize and remove the existing records
MARC::Record::Field modified_tag_041(*tag_041);
MARC::Subfields modified_subfields;
bool propagate_changes(false);
std::unordered_set<std::string> unique_language_codes;
const auto indicator1(modified_tag_041.getIndicator1()), indicator2(modified_tag_041.getIndicator2());
for (auto& subfield : tag_041->getSubfields()) {
if (unique_language_codes.find(subfield.value_) != unique_language_codes.end()) {
LogOutput("Removing duplicate subfield entry 041$" + std::string(1, subfield.code_) +
" '" + subfield.value_ + "'");
propagate_changes = true;
continue;
}
std::string normalized_language_code;
if (not params.getCanonicalCode(subfield.value_, &normalized_language_code)) {
LogOutput("Unknown language code variant '" + subfield.value_ + "' in subfield 041$" +
std::string(1, subfield.code_), true);
}
if (normalized_language_code != subfield.value_) {
LogOutput("Normalized subfield 041$" + std::string(1, subfield.code_) +
" language code: '" + subfield.value_ + "' => '" + normalized_language_code + "'");
subfield.value_ = normalized_language_code;
propagate_changes = true;
}
unique_language_codes.insert(subfield.value_);
modified_subfields.addSubfield(subfield.code_, subfield.value_);
}
if (propagate_changes)
tag_041->setContents(modified_subfields, indicator1, indicator2);
}
writer->write(record);
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <time.h>
timeonaxis()
{
// This macro illustrates the use of the time mode on the axis
// with different time intervals and time formats. It's result can
// be seen begin_html <a href="gif/timeonaxis.gif">here</a> end_html
// Through all this script, the time is expressed in UTC. some
// information about this format (and others like GPS) may be found at
// begin_html <a href="http://tycho.usno.navy.mil/systime.html">http://tycho.usno.navy.mil/systime.html</a> end_html
// or
// begin_html <a href="http://www.topology.org/sci/time.html">http://www.topology.org/sci/time.html</a> end_html
gROOT->Reset();
// The start time is : almost NOW (the time at which the script is executed)
// actualy, the nearest preceeding hour beginning.
// The time is in general expressed in UTC time with the C time() function
// This will obviously most of the time not be the time displayed on your watch
// since it is universal time. See the C time functions for converting this time
// into more useful structures.
time_t script_time;
script_time = time(0);
script_time = 3600*(int)(script_time/3600);
// The time offset is the one that will be used by all graphs.
// If one changes it, it will be changed even on the graphs already defined
gStyle->SetTimeOffset(script_time);
ct = new TCanvas("ct","Time on axis",10,10,700,900);
ct->Divide(1,3);
ct->SetFillColor(28);
int i;
//======= Build a signal : noisy damped sine ======
// Time interval : 30 minutes
gStyle->SetTitleH(0.08);
float noise;
ht = new TH1F("ht","Love at first sight",3000,0.,2000.);
for (i=1;i<3000;i++) {
noise = gRandom->Gaus(0,120);
if (i>700) {
noise += 1000*sin((i-700)*6.28/30)*exp((double)(700-i)/300);
}
ht->SetBinContent(i,noise);
}
ct->cd(1);
ct_1->SetFillColor(41);
ct_1->SetFrameFillColor(33);
ht->SetLineColor(2);
ht->GetXaxis()->SetLabelSize(0.05);
ht->Draw();
// Sets time on the X axis
// The time used is the one set as time offset added to the value
// of the axis. This is converted into day/month/year hour:min:sec and
// a reasonnable tick interval value is chosen.
ht->GetXaxis()->SetTimeDisplay(1);
//======= Build a simple graph beginning at a different time ======
// Time interval : 5 seconds
float x[100], t[100];
for (i=0;i<100;i++) {
x[i] = sin(i*4*3.1415926/50)*exp(-(double)i/20);
t[i] = 6000+(double)i/20;
}
gt = new TGraph(100,t,x);
gt->SetTitle("Politics");
ct->cd(2);
ct_2->SetFillColor(41);
ct_2->SetFrameFillColor(33);
gt->SetFillColor(19);
gt->SetLineColor(5);
gt->SetLineWidth(2);
gt->Draw("AL");
gt->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt->GetXaxis()->SetTimeDisplay(1);
gPad->Modified();
//======= Build a second simple graph for a very long time interval ======
// Time interval : a few years
float x2[10], t2[10];
for (i=0;i<10;i++) {
x2[i] = gRandom->Gaus(500,100)*i;
t2[i] = i*365*86400;
}
gt2 = new TGraph(10,t2,x2);
gt2->SetTitle("Number of monkeys on the moon");
ct->cd(3);
ct_3->SetFillColor(41);
ct_3->SetFrameFillColor(33);
gt2->SetFillColor(19);
gt2->SetMarkerColor(4);
gt2->SetMarkerStyle(29);
gt2->SetMarkerSize(1.3);
gt2->Draw("AP");
gt2->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt2->GetXaxis()->SetTimeDisplay(1);
//
// One can choose a different time format than the one chosen by default
// The time format is the same as the one of the C strftime() function
// It's a string containing the following formats :
// for date :
// %a abbreviated weekday name
// %b abbreviated month name
// %d day of the month (01-31)
// %m month (01-12)
// %y year without century
// %Y year with century
//
// for time :
// %H hour (24-hour clock)
// %I hour (12-hour clock)
// %p local equivalent of AM or PM
// %M minute (00-59)
// %S seconds (00-61)
// %% %
// The other characters are output as is.
gt2->GetXaxis()->SetTimeFormat("y. %Y");
gPad->Modified();
}
<commit_msg>Remove call to gROOT->Reset in timeonaxis.C<commit_after>#include <time.h>
void timeonaxis()
{
// This macro illustrates the use of the time mode on the axis
// with different time intervals and time formats. It's result can
// be seen begin_html <a href="gif/timeonaxis.gif">here</a> end_html
// Through all this script, the time is expressed in UTC. some
// information about this format (and others like GPS) may be found at
// begin_html <a href="http://tycho.usno.navy.mil/systime.html">http://tycho.usno.navy.mil/systime.html</a> end_html
// or
// begin_html <a href="http://www.topology.org/sci/time.html">http://www.topology.org/sci/time.html</a> end_html
//
// The start time is : almost NOW (the time at which the script is executed)
// actualy, the nearest preceeding hour beginning.
// The time is in general expressed in UTC time with the C time() function
// This will obviously most of the time not be the time displayed on your watch
// since it is universal time. See the C time functions for converting this time
// into more useful structures.
time_t script_time;
script_time = time(0);
script_time = 3600*(int)(script_time/3600);
// The time offset is the one that will be used by all graphs.
// If one changes it, it will be changed even on the graphs already defined
gStyle->SetTimeOffset(script_time);
ct = new TCanvas("ct","Time on axis",10,10,700,900);
ct->Divide(1,3);
ct->SetFillColor(28);
int i;
//======= Build a signal : noisy damped sine ======
// Time interval : 30 minutes
gStyle->SetTitleH(0.08);
float noise;
ht = new TH1F("ht","Love at first sight",3000,0.,2000.);
for (i=1;i<3000;i++) {
noise = gRandom->Gaus(0,120);
if (i>700) {
noise += 1000*sin((i-700)*6.28/30)*exp((double)(700-i)/300);
}
ht->SetBinContent(i,noise);
}
ct->cd(1);
ct_1->SetFillColor(41);
ct_1->SetFrameFillColor(33);
ht->SetLineColor(2);
ht->GetXaxis()->SetLabelSize(0.05);
ht->Draw();
// Sets time on the X axis
// The time used is the one set as time offset added to the value
// of the axis. This is converted into day/month/year hour:min:sec and
// a reasonnable tick interval value is chosen.
ht->GetXaxis()->SetTimeDisplay(1);
//======= Build a simple graph beginning at a different time ======
// Time interval : 5 seconds
float x[100], t[100];
for (i=0;i<100;i++) {
x[i] = sin(i*4*3.1415926/50)*exp(-(double)i/20);
t[i] = 6000+(double)i/20;
}
gt = new TGraph(100,t,x);
gt->SetTitle("Politics");
ct->cd(2);
ct_2->SetFillColor(41);
ct_2->SetFrameFillColor(33);
gt->SetFillColor(19);
gt->SetLineColor(5);
gt->SetLineWidth(2);
gt->Draw("AL");
gt->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt->GetXaxis()->SetTimeDisplay(1);
gPad->Modified();
//======= Build a second simple graph for a very long time interval ======
// Time interval : a few years
float x2[10], t2[10];
for (i=0;i<10;i++) {
x2[i] = gRandom->Gaus(500,100)*i;
t2[i] = i*365*86400;
}
gt2 = new TGraph(10,t2,x2);
gt2->SetTitle("Number of monkeys on the moon");
ct->cd(3);
ct_3->SetFillColor(41);
ct_3->SetFrameFillColor(33);
gt2->SetFillColor(19);
gt2->SetMarkerColor(4);
gt2->SetMarkerStyle(29);
gt2->SetMarkerSize(1.3);
gt2->Draw("AP");
gt2->GetXaxis()->SetLabelSize(0.05);
// Sets time on the X axis
gt2->GetXaxis()->SetTimeDisplay(1);
//
// One can choose a different time format than the one chosen by default
// The time format is the same as the one of the C strftime() function
// It's a string containing the following formats :
// for date :
// %a abbreviated weekday name
// %b abbreviated month name
// %d day of the month (01-31)
// %m month (01-12)
// %y year without century
// %Y year with century
//
// for time :
// %H hour (24-hour clock)
// %I hour (12-hour clock)
// %p local equivalent of AM or PM
// %M minute (00-59)
// %S seconds (00-61)
// %% %
// The other characters are output as is.
gt2->GetXaxis()->SetTimeFormat("y. %Y");
gPad->Modified();
}
<|endoftext|> |
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角
m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
//velocity
if (m_pStates[STATE_RUN])
impulse *= m_fMaxVelocity;
else
impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角
m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
//velocity
if (m_pStates[STATE_RUN])
impulse *= m_fMaxVelocity;
else
impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
}<|endoftext|> |
<commit_before>// c++ -std=c++11 converter.cpp -o converter -I/usr/local/include -L/usr/local/lib -lassimp -g -Wall
#define SAVE_RIG 1
#include <iostream>
#include <fstream>
#include <algorithm> // pair
#include <unordered_map>
#include <cassert>
#include <assimp/Exporter.hpp>
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
namespace
{
/// From my: stl.h
// Behaves like the python os.path.split() function.
inline std::pair< std::string, std::string > os_path_split( const std::string& path )
{
const std::string::size_type split = path.find_last_of( "/" );
if( split == std::string::npos )
return std::make_pair( std::string(), path );
else
{
std::string::size_type split_start = split;
// Remove multiple trailing slashes.
while( split_start > 0 && path[ split_start-1 ] == '/' ) split_start -= 1;
// Don't remove the leading slash.
if( split_start == 0 ) split_start = 1;
return std::make_pair( path.substr( 0, split_start ), path.substr( split+1 ) );
}
}
// Behaves like the python os.path.splitext() function.
inline std::pair< std::string, std::string > os_path_splitext( const std::string& path )
{
const std::string::size_type split_dot = path.find_last_of( "." );
const std::string::size_type split_slash = path.find_last_of( "/" );
if( split_dot != std::string::npos && (split_slash == std::string::npos || split_slash < split_dot) )
return std::make_pair( path.substr( 0, split_dot ), path.substr( split_dot ) );
else
return std::make_pair( path, std::string() );
}
/// From: http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
bool os_path_exists( const std::string& name ) {
std::ifstream f(name.c_str());
if (f.good()) {
f.close();
return true;
} else {
f.close();
return false;
}
}
}
void print_importers( std::ostream& out )
{
out << "## Importers:\n";
aiString s;
aiGetExtensionList( &s );
out << s.C_Str() << std::endl;
}
void print_exporters( std::ostream& out )
{
out << "## Exporters:\n";
Assimp::Exporter exporter;
const size_t count = exporter.GetExportFormatCount();
for( size_t i = 0; i < count; ++i )
{
const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i );
assert( desc );
out << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl;
}
}
const char* IdFromExtension( const std::string& extension )
{
Assimp::Exporter exporter;
const size_t count = exporter.GetExportFormatCount();
for( size_t i = 0; i < count; ++i )
{
const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i );
assert( desc );
if( extension == desc->fileExtension )
{
std::cout << "Found a match for extension: " << extension << std::endl;
std::cout << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl;
return desc->id;
}
}
return nullptr;
}
#if SAVE_RIG
void save_rig( const aiMesh* mesh )
{
assert( mesh );
// Iterate over the bones of the mesh.
for( int bone_index = 0; bone_index < mesh->mNumBones; ++bone_index ) {
const aiBone* bone = mesh->mBones[ bone_index ];
// Save the vertex weights for the bone.
// Lookup the index for the bone by its name.
}
}
aiMatrix4x4 FilterNodeTransformation( const aiMatrix4x4& transformation ) {
return transformation;
// Decompose the transformation matrix into translation, rotation, and scaling.
aiVector3D scaling, translation_vector;
aiQuaternion rotation;
transformation.Decompose( scaling, rotation, translation_vector );
rotation.Normalize();
// Convert the translation into a matrix.
aiMatrix4x4 translation_matrix;
aiMatrix4x4::Translation( translation_vector, translation_matrix );
// Keep the rotation times the translation.
aiMatrix4x4 keep( aiMatrix4x4( rotation.GetMatrix() ) * translation_matrix );
return keep;
}
typedef std::unordered_map< std::string, aiMatrix4x4 > StringToMatrix4x4;
// typedef std::unordered_map< std::string, std::string > StringToString;
void recurse( const aiNode* node, const aiMatrix4x4& parent_transformation, StringToMatrix4x4& name2transformation ) {
assert( node );
assert( name2transformation.find( node->mName.C_Str() ) == name2transformation.end() );
const aiMatrix4x4 node_transformation = FilterNodeTransformation( node->mTransformation );
const aiMatrix4x4 transformation_so_far = parent_transformation * node_transformation;
name2transformation[ node->mName.C_Str() ] = transformation_so_far;
for( int child_index = 0; child_index < node->mNumChildren; ++child_index ) {
recurse( node->mChildren[ child_index ], transformation_so_far, name2transformation );
}
}
void print( const StringToMatrix4x4& name2transformation ) {
for( const auto& iter : name2transformation ) {
std::cout << iter.first << ":\n";
std::cout << ' ' << iter.second.a1 << ' ' << iter.second.a2 << ' ' << iter.second.a3 << ' ' << iter.second.a4 << '\n';
std::cout << ' ' << iter.second.b1 << ' ' << iter.second.b2 << ' ' << iter.second.b3 << ' ' << iter.second.b4 << '\n';
std::cout << ' ' << iter.second.c1 << ' ' << iter.second.c2 << ' ' << iter.second.c3 << ' ' << iter.second.c4 << '\n';
std::cout << ' ' << iter.second.d1 << ' ' << iter.second.d2 << ' ' << iter.second.d3 << ' ' << iter.second.d4 << '\n';
}
}
void save_rig( const aiScene* scene )
{
printf( "# Saving the rig.\n" );
assert( scene );
assert( scene->mRootNode );
StringToMatrix4x4 node2transformation;
const aiMatrix4x4 I;
recurse( scene->mRootNode, I, node2transformation );
print( node2transformation );
/// 1 Find the immediate parent of each bone
// TODO: Save the bones. There should be some kind of nodes with their
// names and positions. (We might also need the offsetmatrix from the bone itself).
// Store a map of name to index.
// See (maybe): http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html
/*
import pyassimp
filename = '/Users/yotam/Work/ext/three.js/examples/models/collada/monster/monster.dae'
scene = pyassimp.load( filename )
spaces = 0
def recurse( node ):
global spaces
print (' '*spaces), node.name #, node.transformation
spaces += 1
for child in node.children: recurse( child )
spaces -= 1
recurse( scene.rootnode )
*/
// Meshes have bones. Iterate over meshes.
for( int mesh_index = 0; mesh_index < scene->mNumMeshes; ++mesh_index ) {
printf( "Mesh %d\n", mesh_index );
save_rig( scene->mMeshes[ mesh_index ] );
}
}
#endif
void usage( const char* argv0, std::ostream& out )
{
out << "Usage: " << argv0 << " path/to/input path/to/output" << std::endl;
out << std::endl;
print_importers( out );
out << std::endl;
print_exporters( out );
}
int main( int argc, char* argv[] )
{
/// We need three arguments: the program, the input path, and the output path.
if( 3 != argc ) {
usage( argv[0], std::cerr );
return -1;
}
/// Store the input and output paths.
const char* inpath = argv[1];
const char* outpath = argv[2];
// Exit if the output path already exists.
if( os_path_exists( outpath ) ) {
std::cerr << "ERROR: Output path exists. Not clobbering: " << outpath << std::endl;
usage( argv[0], std::cerr );
return -1;
}
/// Get the extension of the output path and its corresponding ASSIMP id.
std::string extension = os_path_splitext( outpath ).second;
// os_path_splitext.second returns an extension of the form ".obj".
// We want the substring from position 1 to the end.
if( extension.size() <= 1 ) {
std::cerr << "ERROR: No extension detected on the output path: " << extension << std::endl;
usage( argv[0], std::cerr );
return -1;
}
extension = extension.substr(1);
const char* exportId = IdFromExtension( extension );
// Exit if we couldn't find a corresponding ASSIMP id.
if( nullptr == exportId ) {
std::cerr << "ERROR: Output extension unsupported: " << extension << std::endl;
usage( argv[0], std::cerr );
return -1;
}
/// Load the scene.
const aiScene* scene = aiImportFile( inpath, 0 );
if( nullptr == scene ) {
std::cerr << "ERROR: " << aiGetErrorString() << std::endl;
}
std::cout << "Loaded: " << inpath << std::endl;
/// Save the scene.
const aiReturn result = aiExportScene( scene, exportId, outpath, 0 );
if( aiReturn_SUCCESS != result ) {
std::cerr << "ERROR: Could not save the scene: " << ( (aiReturn_OUTOFMEMORY == result) ? "Out of memory" : "Unknown reason" ) << std::endl;
}
std::cout << "Saved: " << outpath << std::endl;
#if SAVE_RIG
/// Save the rig.
save_rig( scene );
#endif
// Cleanup.
aiReleaseImport( scene );
return 0;
}
<commit_msg>commented out a transpose test.<commit_after>// c++ -std=c++11 converter.cpp -o converter -I/usr/local/include -L/usr/local/lib -lassimp -g -Wall
#define SAVE_RIG 1
#include <iostream>
#include <fstream>
#include <algorithm> // pair
#include <unordered_map>
#include <cassert>
#include <assimp/Exporter.hpp>
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
namespace
{
/// From my: stl.h
// Behaves like the python os.path.split() function.
inline std::pair< std::string, std::string > os_path_split( const std::string& path )
{
const std::string::size_type split = path.find_last_of( "/" );
if( split == std::string::npos )
return std::make_pair( std::string(), path );
else
{
std::string::size_type split_start = split;
// Remove multiple trailing slashes.
while( split_start > 0 && path[ split_start-1 ] == '/' ) split_start -= 1;
// Don't remove the leading slash.
if( split_start == 0 ) split_start = 1;
return std::make_pair( path.substr( 0, split_start ), path.substr( split+1 ) );
}
}
// Behaves like the python os.path.splitext() function.
inline std::pair< std::string, std::string > os_path_splitext( const std::string& path )
{
const std::string::size_type split_dot = path.find_last_of( "." );
const std::string::size_type split_slash = path.find_last_of( "/" );
if( split_dot != std::string::npos && (split_slash == std::string::npos || split_slash < split_dot) )
return std::make_pair( path.substr( 0, split_dot ), path.substr( split_dot ) );
else
return std::make_pair( path, std::string() );
}
/// From: http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c
bool os_path_exists( const std::string& name ) {
std::ifstream f(name.c_str());
if (f.good()) {
f.close();
return true;
} else {
f.close();
return false;
}
}
}
void print_importers( std::ostream& out )
{
out << "## Importers:\n";
aiString s;
aiGetExtensionList( &s );
out << s.C_Str() << std::endl;
}
void print_exporters( std::ostream& out )
{
out << "## Exporters:\n";
Assimp::Exporter exporter;
const size_t count = exporter.GetExportFormatCount();
for( size_t i = 0; i < count; ++i )
{
const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i );
assert( desc );
out << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl;
}
}
const char* IdFromExtension( const std::string& extension )
{
Assimp::Exporter exporter;
const size_t count = exporter.GetExportFormatCount();
for( size_t i = 0; i < count; ++i )
{
const aiExportFormatDesc* desc = exporter.GetExportFormatDescription( i );
assert( desc );
if( extension == desc->fileExtension )
{
std::cout << "Found a match for extension: " << extension << std::endl;
std::cout << desc->fileExtension << ": " << desc->description << " (id: " << desc->id << ")" << std::endl;
return desc->id;
}
}
return nullptr;
}
#if SAVE_RIG
void save_rig( const aiMesh* mesh )
{
assert( mesh );
// Iterate over the bones of the mesh.
for( int bone_index = 0; bone_index < mesh->mNumBones; ++bone_index ) {
const aiBone* bone = mesh->mBones[ bone_index ];
// Save the vertex weights for the bone.
// Lookup the index for the bone by its name.
}
}
aiMatrix4x4 FilterNodeTransformation( const aiMatrix4x4& transformation ) {
// return transformation;
// Decompose the transformation matrix into translation, rotation, and scaling.
aiVector3D scaling, translation_vector;
aiQuaternion rotation;
transformation.Decompose( scaling, rotation, translation_vector );
rotation.Normalize();
// Convert the translation into a matrix.
aiMatrix4x4 translation_matrix;
aiMatrix4x4::Translation( translation_vector, translation_matrix );
// Keep the rotation times the translation.
aiMatrix4x4 keep( aiMatrix4x4( rotation.GetMatrix() ) * translation_matrix );
return keep;
}
typedef std::unordered_map< std::string, aiMatrix4x4 > StringToMatrix4x4;
// typedef std::unordered_map< std::string, std::string > StringToString;
void recurse( const aiNode* node, const aiMatrix4x4& parent_transformation, StringToMatrix4x4& name2transformation ) {
assert( node );
assert( name2transformation.find( node->mName.C_Str() ) == name2transformation.end() );
aiMatrix4x4 node_transformation = FilterNodeTransformation( node->mTransformation );
// node_transformation.Transpose();
const aiMatrix4x4 transformation_so_far = parent_transformation * node_transformation;
name2transformation[ node->mName.C_Str() ] = transformation_so_far;
for( int child_index = 0; child_index < node->mNumChildren; ++child_index ) {
recurse( node->mChildren[ child_index ], transformation_so_far, name2transformation );
}
}
void print( const StringToMatrix4x4& name2transformation ) {
for( const auto& iter : name2transformation ) {
std::cout << iter.first << ":\n";
std::cout << ' ' << iter.second.a1 << ' ' << iter.second.a2 << ' ' << iter.second.a3 << ' ' << iter.second.a4 << '\n';
std::cout << ' ' << iter.second.b1 << ' ' << iter.second.b2 << ' ' << iter.second.b3 << ' ' << iter.second.b4 << '\n';
std::cout << ' ' << iter.second.c1 << ' ' << iter.second.c2 << ' ' << iter.second.c3 << ' ' << iter.second.c4 << '\n';
std::cout << ' ' << iter.second.d1 << ' ' << iter.second.d2 << ' ' << iter.second.d3 << ' ' << iter.second.d4 << '\n';
}
}
void save_rig( const aiScene* scene )
{
printf( "# Saving the rig.\n" );
assert( scene );
assert( scene->mRootNode );
StringToMatrix4x4 node2transformation;
const aiMatrix4x4 I;
recurse( scene->mRootNode, I, node2transformation );
print( node2transformation );
/// 1 Find the immediate parent of each bone
// TODO: Save the bones. There should be some kind of nodes with their
// names and positions. (We might also need the offsetmatrix from the bone itself).
// Store a map of name to index.
// See (maybe): http://ogldev.atspace.co.uk/www/tutorial38/tutorial38.html
/*
import pyassimp
filename = '/Users/yotam/Work/ext/three.js/examples/models/collada/monster/monster.dae'
scene = pyassimp.load( filename )
spaces = 0
def recurse( node ):
global spaces
print (' '*spaces), node.name #, node.transformation
spaces += 1
for child in node.children: recurse( child )
spaces -= 1
recurse( scene.rootnode )
*/
// Meshes have bones. Iterate over meshes.
for( int mesh_index = 0; mesh_index < scene->mNumMeshes; ++mesh_index ) {
printf( "Mesh %d\n", mesh_index );
save_rig( scene->mMeshes[ mesh_index ] );
}
}
#endif
void usage( const char* argv0, std::ostream& out )
{
out << "Usage: " << argv0 << " path/to/input path/to/output" << std::endl;
out << std::endl;
print_importers( out );
out << std::endl;
print_exporters( out );
}
int main( int argc, char* argv[] )
{
/// We need three arguments: the program, the input path, and the output path.
if( 3 != argc ) {
usage( argv[0], std::cerr );
return -1;
}
/// Store the input and output paths.
const char* inpath = argv[1];
const char* outpath = argv[2];
// Exit if the output path already exists.
if( os_path_exists( outpath ) ) {
std::cerr << "ERROR: Output path exists. Not clobbering: " << outpath << std::endl;
usage( argv[0], std::cerr );
return -1;
}
/// Get the extension of the output path and its corresponding ASSIMP id.
std::string extension = os_path_splitext( outpath ).second;
// os_path_splitext.second returns an extension of the form ".obj".
// We want the substring from position 1 to the end.
if( extension.size() <= 1 ) {
std::cerr << "ERROR: No extension detected on the output path: " << extension << std::endl;
usage( argv[0], std::cerr );
return -1;
}
extension = extension.substr(1);
const char* exportId = IdFromExtension( extension );
// Exit if we couldn't find a corresponding ASSIMP id.
if( nullptr == exportId ) {
std::cerr << "ERROR: Output extension unsupported: " << extension << std::endl;
usage( argv[0], std::cerr );
return -1;
}
/// Load the scene.
const aiScene* scene = aiImportFile( inpath, 0 );
if( nullptr == scene ) {
std::cerr << "ERROR: " << aiGetErrorString() << std::endl;
}
std::cout << "Loaded: " << inpath << std::endl;
/// Save the scene.
const aiReturn result = aiExportScene( scene, exportId, outpath, 0 );
if( aiReturn_SUCCESS != result ) {
std::cerr << "ERROR: Could not save the scene: " << ( (aiReturn_OUTOFMEMORY == result) ? "Out of memory" : "Unknown reason" ) << std::endl;
}
std::cout << "Saved: " << outpath << std::endl;
#if SAVE_RIG
/// Save the rig.
save_rig( scene );
#endif
// Cleanup.
aiReleaseImport( scene );
return 0;
}
<|endoftext|> |
<commit_before>/**
* @file Simulation.cpp
* @author <a href="mailto:schlottb@informatik.hu-berlin.de">Benjamin Schlotter</a>
* Implementation of class Simulation
*/
#include "Simulation.h"
using namespace naoth;
using namespace std;
Simulation::Simulation()
{
DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", false);
DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", false);
DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", false);
DEBUG_REQUEST_REGISTER("Simulation:draw_best_action","best action",false);
//DEBUG_REQUEST_REGISTER("Simulation:draw_pessimistic_best_action","best pessimistic action",false);
DEBUG_REQUEST_REGISTER("Simulation:GoalLinePreview","GoalLinePreview",false);
DEBUG_REQUEST_REGISTER("Simulation:draw_potential_field","Draw Potential Field",false);
DEBUG_REQUEST_REGISTER("Simulation:use_Parameters","use_Parameters",false);
getDebugParameterList().add(&theParameters);
//actionRingBuffer.resize(ActionModel::numOfActions);
//calculate the actions
action_local.reserve(KickActionModel::numOfActions);
action_local.push_back(Action(KickActionModel::none, Vector2d()));
action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long
action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short
action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right
action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left
}
Simulation::~Simulation(){}
void Simulation::execute()
{
DEBUG_REQUEST("Simulation:use_Parameters",
action_local.clear();
action_local.reserve(KickActionModel::numOfActions);
action_local.push_back(Action(KickActionModel::none, Vector2d()));
action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long
action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short
action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right
action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left
);
if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1)
{
return;
}
else
{
int best_action = 0;
for(size_t i=0; i<action_local.size(); i++)
{
// physics simulator
std::vector<Vector2d> ballPositionResults;
for(size_t j=0; j<30; j++)
{
Vector2d ballPositionResult = calculateOneAction(action_local[j]);
ballPositionResults.push_back(ballPositionResult);
}
// categorize positions
std::vector<CategorizedBallPosition> categorizedBallPositionResults;
}
getKickActionModel().myAction = action_local[best_action].id();
DEBUG_REQUEST("Simulation:draw_best_action",
{
FIELD_DRAWING_CONTEXT;
PEN("FF69B4", 7);
Vector2d actionGlobal = action_local[best_action].target;
FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50);
});
// DEBUG_REQUEST("Simulation:draw_potential_field",
// draw_potential_field();
// );
}
}//end execute
Vector2d Simulation::calculateOneAction(const Action& action) const
{
// STEP 1: predict the action outcome
const Vector2d& ballRelativePreview = getBallModel().positionPreview;
DEBUG_REQUEST("Simulation:draw_ball",
FIELD_DRAWING_CONTEXT;
PEN("FF0000", 1);
Vector2d ball = getRobotPose() * getBallModel().positionPreview;
CIRCLE( ball.x, ball.y, 50);
);
Vector2d result = action.predict(ballRelativePreview, theParameters.distance_variance, theParameters.angle_variance);
DEBUG_REQUEST("Simulation:ActionTarget",
FIELD_DRAWING_CONTEXT;
PEN("0000FF", 1);
Vector2d ball = getRobotPose() * result;
CIRCLE( ball.x, ball.y, 50);
);
// STEP 2: calculate the goal line
GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo());
Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost;
Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost;
//the endpoints of our line are a shortened version of the goal line
Vector2d goalDir = (oppGoalPostRightPreview - oppGoalPostLeftPreview).normalize();
Vector2d leftEndpoint = oppGoalPostLeftPreview + goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);
Vector2d rightEndpoint = oppGoalPostRightPreview - goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);
// this is the goalline we are shooting for
Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint);
// note: the drawing is global
DEBUG_REQUEST("Simulation:GoalLinePreview",
FIELD_DRAWING_CONTEXT;
PEN("000000", 1);
Vector2d globalLeft = getRobotPose() * leftEndpoint;
Vector2d globalRight = getRobotPose() * rightEndpoint;
LINE(globalLeft.x,globalLeft.y,globalRight.x,globalRight.y);
);
// STEP 3: estimate external factors (shooting a goal, ball moved by referee)
//Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));//hmm
Math::LineSegment shootLine(ballRelativePreview, result);
Vector2d resultingBallPosition;
if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine)) {
resultingBallPosition = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0);
} else {
resultingBallPosition = outsideField(getRobotPose() * result);
}
return resultingBallPosition;
}
//correction of distance in percentage, angle in degrees
Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const
{
double random_length = 2.0*Math::random()-1.0;
double random_angle = 2.0*Math::random()-1.0;
Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length);
noisyAction.rotate(angle_variance*random_angle);
return ball + noisyAction;
}
//calcualte according to the rules, without the roboter position, the ball position
//if it goes outside the field
Vector2d Simulation::outsideField(const Vector2d& globalPoint) const
{
Vector2d point = globalPoint;
//Schusslinie
Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint);
if(getFieldInfo().fieldRect.inside(point)){
return point;
}
else
//Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat
{ //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht
if(point.x > getFieldInfo().xPosOpponentGroundline)
{
Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine));
if(OppOutPoint.y < 0)
{
return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check
} else
{
return Vector2d(0, getFieldInfo().yThrowInLineLeft);
}
}
//Own Groundline out - an der seite wo raus geht
else if(point.x < getFieldInfo().xPosOwnGroundline)
{
Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine));
if(OwnOutPoint.y < 0)
{
return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check
} else
{
return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft);
}
}
//an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
else if(point.y > getFieldInfo().yPosLeftSideline )
{
Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine));
point.x = min(leftOutPoint.x,getRobotPose().translation.x);
if(point.x-1000 < getFieldInfo().xThrowInLineOwn)
{
point.x = getFieldInfo().xThrowInLineOwn;
} else
{
point.x -= 1000;
}
return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); //range check
}
//an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
else //(point.y < getFieldInfo().yPosRightSideline)
{
Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine));
point.x = min(rightOutPoint.x,getRobotPose().translation.x);
if(point.x-1000 < getFieldInfo().xThrowInLineOwn)
{
point.x = getFieldInfo().xThrowInLineOwn;
} else
{
point.x -= 1000;
}
return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check
}
}
}
double Simulation::evaluateAction(const Vector2d& a) const{
Vector2d oppGoal(getFieldInfo().xPosOpponentGoal+200, 0.0);
Vector2d oppDiff = oppGoal - a;
double oppValueX = 0.1;
double oppValueY = 1;
MODIFY("Simulation:oppValueX", oppValueX);
MODIFY("Simulation:oppValueY", oppValueY);
double value_opp = oppValueX*oppDiff.x*oppDiff.x + oppValueY*oppDiff.y*oppDiff.y;
//Vector2d ownGoal(getFieldInfo().xPosOwnGoal, 0.0);
//Vector2d ownDiff = ownGoal - a;
//double ownValueX = 0.01;
//double ownValueY = 0.1;
//MODIFY("Simulation:ownValueX", ownValueX);
//MODIFY("Simulation:ownValueY", ownValueY);
//double value_own = ownValueX*ownDiff.x*ownDiff.x + ownValueY*ownDiff.y*ownDiff.y;
//return value_opp - value_own;
return value_opp;
}
void Simulation::draw_potential_field() const
{
static const int ySize = 20;
static const int xSize = 30;
double yWidth = 0.5*getFieldInfo().yFieldLength/(double)ySize;
double xWidth = 0.5*getFieldInfo().xFieldLength/(double)xSize;
FIELD_DRAWING_CONTEXT;
Color white(0.0,0.0,1.0,0.5); // transparent
Color black(1.0,0.0,0.0,0.5);
// create new sample set
std::vector<double> potential(xSize*ySize);
int idx = 0;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++)
{
Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));
potential[idx] = evaluateAction(point);
idx++;
}
}
double maxValue = 0;
idx = 0;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++)
{
maxValue = max(maxValue, potential[idx++]);
}
}
if(maxValue == 0) return;
idx = 0;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++)
{
Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));
double t = potential[idx++] / maxValue;
Color color = black*t + white*(1-t);
PEN(color, 20);
FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth);
}
}
}//end draw_closest_points
<commit_msg>added categorization loop<commit_after>/**
* @file Simulation.cpp
* @author <a href="mailto:schlottb@informatik.hu-berlin.de">Benjamin Schlotter</a>
* Implementation of class Simulation
*/
#include "Simulation.h"
using namespace naoth;
using namespace std;
Simulation::Simulation()
{
DEBUG_REQUEST_REGISTER("Simulation:draw_one_action_point:global","draw_one_action_point:global", false);
DEBUG_REQUEST_REGISTER("Simulation:draw_ball","draw_ball", false);
DEBUG_REQUEST_REGISTER("Simulation:ActionTarget","ActionTarget", false);
DEBUG_REQUEST_REGISTER("Simulation:draw_best_action","best action",false);
//DEBUG_REQUEST_REGISTER("Simulation:draw_pessimistic_best_action","best pessimistic action",false);
DEBUG_REQUEST_REGISTER("Simulation:GoalLinePreview","GoalLinePreview",false);
DEBUG_REQUEST_REGISTER("Simulation:draw_potential_field","Draw Potential Field",false);
DEBUG_REQUEST_REGISTER("Simulation:use_Parameters","use_Parameters",false);
getDebugParameterList().add(&theParameters);
//actionRingBuffer.resize(ActionModel::numOfActions);
//calculate the actions
action_local.reserve(KickActionModel::numOfActions);
action_local.push_back(Action(KickActionModel::none, Vector2d()));
action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long
action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short
action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right
action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left
}
Simulation::~Simulation(){}
void Simulation::execute()
{
DEBUG_REQUEST("Simulation:use_Parameters",
action_local.clear();
action_local.reserve(KickActionModel::numOfActions);
action_local.push_back(Action(KickActionModel::none, Vector2d()));
action_local.push_back(Action(KickActionModel::kick_long, Vector2d(theParameters.action_long_kick_distance, 0))); // long
action_local.push_back(Action(KickActionModel::kick_short, Vector2d(theParameters.action_short_kick_distance, 0))); // short
action_local.push_back(Action(KickActionModel::sidekick_right, Vector2d(0, -theParameters.action_sidekick_distance))); // right
action_local.push_back(Action(KickActionModel::sidekick_left, Vector2d(0, theParameters.action_sidekick_distance))); // left
);
if(!getBallModel().valid || getFrameInfo().getTimeInSeconds() >= getBallModel().frameInfoWhenBallWasSeen.getTimeInSeconds()+1)
{
return;
}
else
{
int best_action = 0;
for(size_t i=0; i<action_local.size(); i++)
{
// physics simulator
std::vector<Vector2d> ballPositionResults;
for(size_t j=0; j<30; j++)
{
Vector2d ballPositionResult = calculateOneAction(action_local[j]);
ballPositionResults.push_back(ballPositionResult);
}
// categorize positions
std::vector<CategorizedBallPosition> categorizedBallPositionResults;
for(std::vector<Vector2d>::iterator ballPosition = ballPositionResults.begin(); ballPosition != ballPositionResults.end(); ballPosition++)
{
CategorizedBallPosition categorizedBallPosition = CategorizedBallPosition(*ballPosition, CategorizedBallPosition::INFIELD);
// do something
categorizedBallPositionResults.push_back(categorizedBallPosition);
}
}
getKickActionModel().myAction = action_local[best_action].id();
DEBUG_REQUEST("Simulation:draw_best_action",
{
FIELD_DRAWING_CONTEXT;
PEN("FF69B4", 7);
Vector2d actionGlobal = action_local[best_action].target;
FILLOVAL(actionGlobal.x, actionGlobal.y, 50,50);
});
// DEBUG_REQUEST("Simulation:draw_potential_field",
// draw_potential_field();
// );
}
}//end execute
Vector2d Simulation::calculateOneAction(const Action& action) const
{
// STEP 1: predict the action outcome
const Vector2d& ballRelativePreview = getBallModel().positionPreview;
DEBUG_REQUEST("Simulation:draw_ball",
FIELD_DRAWING_CONTEXT;
PEN("FF0000", 1);
Vector2d ball = getRobotPose() * getBallModel().positionPreview;
CIRCLE( ball.x, ball.y, 50);
);
Vector2d result = action.predict(ballRelativePreview, theParameters.distance_variance, theParameters.angle_variance);
DEBUG_REQUEST("Simulation:ActionTarget",
FIELD_DRAWING_CONTEXT;
PEN("0000FF", 1);
Vector2d ball = getRobotPose() * result;
CIRCLE( ball.x, ball.y, 50);
);
// STEP 2: calculate the goal line
GoalModel::Goal oppGoalModel = getSelfLocGoalModel().getOppGoal(getCompassDirection(), getFieldInfo());
Vector2d oppGoalPostLeftPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.leftPost;
Vector2d oppGoalPostRightPreview = getMotionStatus().plannedMotion.hip / oppGoalModel.rightPost;
//the endpoints of our line are a shortened version of the goal line
Vector2d goalDir = (oppGoalPostRightPreview - oppGoalPostLeftPreview).normalize();
Vector2d leftEndpoint = oppGoalPostLeftPreview + goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);
Vector2d rightEndpoint = oppGoalPostRightPreview - goalDir*(getFieldInfo().goalpostRadius + getFieldInfo().ballRadius);
// this is the goalline we are shooting for
Math::LineSegment goalLinePreview(leftEndpoint, rightEndpoint);
// note: the drawing is global
DEBUG_REQUEST("Simulation:GoalLinePreview",
FIELD_DRAWING_CONTEXT;
PEN("000000", 1);
Vector2d globalLeft = getRobotPose() * leftEndpoint;
Vector2d globalRight = getRobotPose() * rightEndpoint;
LINE(globalLeft.x,globalLeft.y,globalRight.x,globalRight.y);
);
// STEP 3: estimate external factors (shooting a goal, ball moved by referee)
//Math::LineSegment shootLine(ballRelativePreview, outsideField(lonely_action.target));//hmm
Math::LineSegment shootLine(ballRelativePreview, result);
Vector2d resultingBallPosition;
if(shootLine.intersect(goalLinePreview) && goalLinePreview.intersect(shootLine)) {
resultingBallPosition = Vector2d(getFieldInfo().xPosOpponentGoal+200, 0.0);
} else {
resultingBallPosition = outsideField(getRobotPose() * result);
}
return resultingBallPosition;
}
//correction of distance in percentage, angle in degrees
Vector2d Simulation::Action::predict(const Vector2d& ball, double distance_variance, double angle_variance) const
{
double random_length = 2.0*Math::random()-1.0;
double random_angle = 2.0*Math::random()-1.0;
Vector2d noisyAction = actionVector + actionVector*(distance_variance*random_length);
noisyAction.rotate(angle_variance*random_angle);
return ball + noisyAction;
}
//calcualte according to the rules, without the roboter position, the ball position
//if it goes outside the field
Vector2d Simulation::outsideField(const Vector2d& globalPoint) const
{
Vector2d point = globalPoint;
//Schusslinie
Math::LineSegment shootLine(getBallModel().positionPreview, globalPoint);
if(getFieldInfo().fieldRect.inside(point)){
return point;
}
else
//Nach Prioritten geordnet - zuerst die Regeln mit dem mglichst schlimmsten Resultat
{ //Opponent Groundline Out - Ball einen Meter hinter Roboter mind ansto hhe. jeweils seite wo ins ausgeht
if(point.x > getFieldInfo().xPosOpponentGroundline)
{
Vector2d OppOutPoint = getFieldInfo().oppLineSegment.point(getFieldInfo().oppLineSegment.intersection(shootLine));
if(OppOutPoint.y < 0)
{
return Vector2d(0, getFieldInfo().yThrowInLineRight);//range check
} else
{
return Vector2d(0, getFieldInfo().yThrowInLineLeft);
}
}
//Own Groundline out - an der seite wo raus geht
else if(point.x < getFieldInfo().xPosOwnGroundline)
{
Vector2d OwnOutPoint = getFieldInfo().ownLineSegment.point(getFieldInfo().ownLineSegment.intersection(shootLine));
if(OwnOutPoint.y < 0)
{
return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineRight);//range check
} else
{
return Vector2d(getFieldInfo().xThrowInLineOwn, getFieldInfo().yThrowInLineLeft);
}
}
//an der linken Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
else if(point.y > getFieldInfo().yPosLeftSideline )
{
Vector2d leftOutPoint = getFieldInfo().leftLineSegment.point(getFieldInfo().leftLineSegment.intersection(shootLine));
point.x = min(leftOutPoint.x,getRobotPose().translation.x);
if(point.x-1000 < getFieldInfo().xThrowInLineOwn)
{
point.x = getFieldInfo().xThrowInLineOwn;
} else
{
point.x -= 1000;
}
return Vector2d(point.x, getFieldInfo().yThrowInLineLeft); //range check
}
//an der rechten Seite raus -> ein meter hinter roboter oder wo ins ausgeht ein meter hinter
else //(point.y < getFieldInfo().yPosRightSideline)
{
Vector2d rightOutPoint = getFieldInfo().rightLineSegment.point(getFieldInfo().rightLineSegment.intersection(shootLine));
point.x = min(rightOutPoint.x,getRobotPose().translation.x);
if(point.x-1000 < getFieldInfo().xThrowInLineOwn)
{
point.x = getFieldInfo().xThrowInLineOwn;
} else
{
point.x -= 1000;
}
return Vector2d(point.x, getFieldInfo().yThrowInLineRight);//range check
}
}
}
double Simulation::evaluateAction(const Vector2d& a) const{
Vector2d oppGoal(getFieldInfo().xPosOpponentGoal+200, 0.0);
Vector2d oppDiff = oppGoal - a;
double oppValueX = 0.1;
double oppValueY = 1;
MODIFY("Simulation:oppValueX", oppValueX);
MODIFY("Simulation:oppValueY", oppValueY);
double value_opp = oppValueX*oppDiff.x*oppDiff.x + oppValueY*oppDiff.y*oppDiff.y;
//Vector2d ownGoal(getFieldInfo().xPosOwnGoal, 0.0);
//Vector2d ownDiff = ownGoal - a;
//double ownValueX = 0.01;
//double ownValueY = 0.1;
//MODIFY("Simulation:ownValueX", ownValueX);
//MODIFY("Simulation:ownValueY", ownValueY);
//double value_own = ownValueX*ownDiff.x*ownDiff.x + ownValueY*ownDiff.y*ownDiff.y;
//return value_opp - value_own;
return value_opp;
}
void Simulation::draw_potential_field() const
{
static const int ySize = 20;
static const int xSize = 30;
double yWidth = 0.5*getFieldInfo().yFieldLength/(double)ySize;
double xWidth = 0.5*getFieldInfo().xFieldLength/(double)xSize;
FIELD_DRAWING_CONTEXT;
Color white(0.0,0.0,1.0,0.5); // transparent
Color black(1.0,0.0,0.0,0.5);
// create new sample set
std::vector<double> potential(xSize*ySize);
int idx = 0;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++)
{
Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));
potential[idx] = evaluateAction(point);
idx++;
}
}
double maxValue = 0;
idx = 0;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++)
{
maxValue = max(maxValue, potential[idx++]);
}
}
if(maxValue == 0) return;
idx = 0;
for (int x = 0; x < xSize; x++) {
for (int y = 0; y < ySize; y++)
{
Vector2d point(xWidth*(2*x-xSize+1), yWidth*(2*y-ySize+1));
double t = potential[idx++] / maxValue;
Color color = black*t + white*(1-t);
PEN(color, 20);
FILLBOX(point.x - xWidth, point.y - yWidth, point.x+xWidth, point.y+yWidth);
}
}
}//end draw_closest_points
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FixedText.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 23:49:35 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#ifndef _FORMS_FIXEDTEXT_HXX_
#include "FixedText.hxx"
#endif
#ifndef _FRM_SERVICES_HXX_
#include "services.hxx"
#endif
#ifndef _FRM_PROPERTY_HRC_
#include "property.hrc"
#endif
#ifndef _FRM_PROPERTY_HXX_
#include "property.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//.........................................................................
namespace frm
{
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
//------------------------------------------------------------------------------
InterfaceRef SAL_CALL OFixedTextModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) throw (RuntimeException)
{
return *(new OFixedTextModel(_rxFactory));
}
//------------------------------------------------------------------
DBG_NAME( OFixedTextModel )
//------------------------------------------------------------------
OFixedTextModel::OFixedTextModel( const Reference<XMultiServiceFactory>& _rxFactory )
:OControlModel(_rxFactory, VCL_CONTROLMODEL_FIXEDTEXT)
{
DBG_CTOR( OFixedTextModel, NULL );
m_nClassId = FormComponentType::FIXEDTEXT;
}
//------------------------------------------------------------------
OFixedTextModel::OFixedTextModel( const OFixedTextModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
:OControlModel( _pOriginal, _rxFactory )
{
DBG_CTOR( OFixedTextModel, NULL );
}
//------------------------------------------------------------------
OFixedTextModel::~OFixedTextModel( )
{
DBG_DTOR( OFixedTextModel, NULL );
}
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( OFixedTextModel )
//------------------------------------------------------------------------------
StringSequence SAL_CALL OFixedTextModel::getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)
{
StringSequence aSupported = OControlModel::getSupportedServiceNames();
aSupported.realloc(aSupported.getLength() + 1);
::rtl::OUString* pArray = aSupported.getArray();
pArray[aSupported.getLength()-1] = FRM_SUN_COMPONENT_FIXEDTEXT;
return aSupported;
}
//------------------------------------------------------------------------------
Reference<starbeans::XPropertySetInfo> SAL_CALL OFixedTextModel::getPropertySetInfo() throw(RuntimeException)
{
Reference<starbeans::XPropertySetInfo> xInfo(createPropertySetInfo(getInfoHelper()));
return xInfo;
}
//------------------------------------------------------------------------------
cppu::IPropertyArrayHelper& OFixedTextModel::getInfoHelper()
{
return *const_cast<OFixedTextModel*>(this)->getArrayHelper();
}
//------------------------------------------------------------------------------
void OFixedTextModel::fillProperties(
Sequence< starbeans::Property >& _rProps,
Sequence< starbeans::Property >& _rAggregateProps ) const
{
OControlModel::fillProperties( _rProps, _rAggregateProps );
RemoveProperty( _rAggregateProps, PROPERTY_TABSTOP );
}
//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OFixedTextModel::getServiceName() throw(RuntimeException)
{
return FRM_COMPONENT_FIXEDTEXT; // old (non-sun) name for compatibility !
}
//------------------------------------------------------------------------------
void SAL_CALL OFixedTextModel::write(const Reference<XObjectOutputStream>& _rxOutStream)
throw(IOException, RuntimeException)
{
OControlModel::write(_rxOutStream);
// Version
_rxOutStream->writeShort(0x0002);
writeHelpTextCompatibly(_rxOutStream);
}
//------------------------------------------------------------------------------
void SAL_CALL OFixedTextModel::read(const Reference<XObjectInputStream>& _rxInStream) throw(IOException, RuntimeException)
{
OControlModel::read(_rxInStream);
// Version
sal_Int16 nVersion = _rxInStream->readShort();
if (nVersion > 1)
readHelpTextCompatibly(_rxInStream);
}
//.........................................................................
}
//.........................................................................
<commit_msg>INTEGRATION: CWS hb02 (1.8.52); FILE MERGED 2007/02/01 12:09:37 fs 1.8.52.2: #i74051# split describeFixedProperties in describeFixedProperties and describeAggregateProperties 2007/01/31 10:55:26 fs 1.8.52.1: changed handling of properties in the course of #i74051#<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: FixedText.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2007-03-09 13:25: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_forms.hxx"
#ifndef _FORMS_FIXEDTEXT_HXX_
#include "FixedText.hxx"
#endif
#ifndef _FRM_SERVICES_HXX_
#include "services.hxx"
#endif
#ifndef _FRM_PROPERTY_HRC_
#include "property.hrc"
#endif
#ifndef _FRM_PROPERTY_HXX_
#include "property.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
//.........................................................................
namespace frm
{
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::form;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::util;
//------------------------------------------------------------------------------
InterfaceRef SAL_CALL OFixedTextModel_CreateInstance(const Reference<XMultiServiceFactory>& _rxFactory) throw (RuntimeException)
{
return *(new OFixedTextModel(_rxFactory));
}
//------------------------------------------------------------------
DBG_NAME( OFixedTextModel )
//------------------------------------------------------------------
OFixedTextModel::OFixedTextModel( const Reference<XMultiServiceFactory>& _rxFactory )
:OControlModel(_rxFactory, VCL_CONTROLMODEL_FIXEDTEXT)
{
DBG_CTOR( OFixedTextModel, NULL );
m_nClassId = FormComponentType::FIXEDTEXT;
}
//------------------------------------------------------------------
OFixedTextModel::OFixedTextModel( const OFixedTextModel* _pOriginal, const Reference<XMultiServiceFactory>& _rxFactory )
:OControlModel( _pOriginal, _rxFactory )
{
DBG_CTOR( OFixedTextModel, NULL );
}
//------------------------------------------------------------------
OFixedTextModel::~OFixedTextModel( )
{
DBG_DTOR( OFixedTextModel, NULL );
}
//------------------------------------------------------------------------------
IMPLEMENT_DEFAULT_CLONING( OFixedTextModel )
//------------------------------------------------------------------------------
StringSequence SAL_CALL OFixedTextModel::getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException)
{
StringSequence aSupported = OControlModel::getSupportedServiceNames();
aSupported.realloc(aSupported.getLength() + 1);
::rtl::OUString* pArray = aSupported.getArray();
pArray[aSupported.getLength()-1] = FRM_SUN_COMPONENT_FIXEDTEXT;
return aSupported;
}
//------------------------------------------------------------------------------
void OFixedTextModel::describeAggregateProperties( Sequence< Property >& _rAggregateProps ) const
{
OControlModel::describeAggregateProperties( _rAggregateProps );
RemoveProperty( _rAggregateProps, PROPERTY_TABSTOP );
}
//------------------------------------------------------------------------------
::rtl::OUString SAL_CALL OFixedTextModel::getServiceName() throw(RuntimeException)
{
return FRM_COMPONENT_FIXEDTEXT; // old (non-sun) name for compatibility !
}
//------------------------------------------------------------------------------
void SAL_CALL OFixedTextModel::write(const Reference<XObjectOutputStream>& _rxOutStream)
throw(IOException, RuntimeException)
{
OControlModel::write(_rxOutStream);
// Version
_rxOutStream->writeShort(0x0002);
writeHelpTextCompatibly(_rxOutStream);
}
//------------------------------------------------------------------------------
void SAL_CALL OFixedTextModel::read(const Reference<XObjectInputStream>& _rxInStream) throw(IOException, RuntimeException)
{
OControlModel::read(_rxInStream);
// Version
sal_Int16 nVersion = _rxInStream->readShort();
if (nVersion > 1)
readHelpTextCompatibly(_rxInStream);
}
//.........................................................................
}
//.........................................................................
<|endoftext|> |
<commit_before>#include "Adafruit_MQTT.h"
Adafruit_MQTT::Adafruit_MQTT(char *server, uint16_t port, char *user, char *key) {
strncpy(servername, server, SERVERNAME_SIZE);
servername[SERVERNAME_SIZE-1] = 0;
portnum = port;
serverip = 0;
strncpy(username, user, USERNAME_SIZE);
username[USERNAME_SIZE-1] = 0;
strncpy(userkey, key, KEY_SIZE);
userkey[KEY_SIZE-1] = 0;
errno = 0;
}
// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028
uint8_t Adafruit_MQTT::connectPacket(uint8_t *packet) {
uint8_t *p = packet;
// fixed header, connection messsage no flags
p[0] = (MQTT_CTRL_CONNECT << 4) | 0x0;
p+=2;
// fill in packet[1] last
p[0] = 0;
p[1] = 6; // (strlen(MQIdsp)
p+=2;
memcpy(p,"MQIdsp", 6);
p+=6;
p[0] = MQTT_PROTOCOL_LEVEL;
p++;
p[0] = MQTT_CONN_CLEANSESSION;
if (username[0] != 0)
p[0] |= MQTT_CONN_USERNAMEFLAG;
if (userkey[0] != 0)
p[0] |= MQTT_CONN_PASSWORDFLAG;
p++;
// TODO: add WILL support?
p[0] = MQTT_CONN_KEEPALIVE >> 8;
p++;
p[0] = MQTT_CONN_KEEPALIVE & 0xFF;
p++;
if (username[0] != 0) {
uint16_t len = strlen(username);
p[0] = len >> 8; p++;
p[0] = len & 0xFF; p++;
memcpy(p, username, len);
p+=len;
}
if (userkey[0] != 0) {
uint16_t len = strlen(userkey);
p[0] = len >> 8; p++;
p[0] = len & 0xFF; p++;
memcpy(p, userkey, len);
p+=len;
}
uint8_t totallen = p - packet;
// add two empty bytes at the end (?)
p[0] = 0;
p[1] = 0;
p+=2;
packet[1] = totallen;
return totallen+2;
}
Adafruit_MQTT_Publish::Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, char *feed) {
mqtt = mqttserver;
strncpy(feedname, feed, FEEDNAME_SIZE);
feedname[FEEDNAME_SIZE-1] = 0;
errno = 0;
}
<commit_msg>MQIdsp -> MQIsdp<commit_after>#include "Adafruit_MQTT.h"
Adafruit_MQTT::Adafruit_MQTT(char *server, uint16_t port, char *user, char *key) {
strncpy(servername, server, SERVERNAME_SIZE);
servername[SERVERNAME_SIZE-1] = 0;
portnum = port;
serverip = 0;
strncpy(username, user, USERNAME_SIZE);
username[USERNAME_SIZE-1] = 0;
strncpy(userkey, key, KEY_SIZE);
userkey[KEY_SIZE-1] = 0;
errno = 0;
}
// http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718028
uint8_t Adafruit_MQTT::connectPacket(uint8_t *packet) {
uint8_t *p = packet;
// fixed header, connection messsage no flags
p[0] = (MQTT_CTRL_CONNECT << 4) | 0x0;
p+=2;
// fill in packet[1] last
p[0] = 0;
p[1] = 6; // (strlen(MQIsdp)
p+=2;
memcpy(p,"MQIsdp", 6);
p+=6;
p[0] = MQTT_PROTOCOL_LEVEL;
p++;
p[0] = MQTT_CONN_CLEANSESSION;
if (username[0] != 0)
p[0] |= MQTT_CONN_USERNAMEFLAG;
if (userkey[0] != 0)
p[0] |= MQTT_CONN_PASSWORDFLAG;
p++;
// TODO: add WILL support?
p[0] = MQTT_CONN_KEEPALIVE >> 8;
p++;
p[0] = MQTT_CONN_KEEPALIVE & 0xFF;
p++;
if (username[0] != 0) {
uint16_t len = strlen(username);
p[0] = len >> 8; p++;
p[0] = len & 0xFF; p++;
memcpy(p, username, len);
p+=len;
}
if (userkey[0] != 0) {
uint16_t len = strlen(userkey);
p[0] = len >> 8; p++;
p[0] = len & 0xFF; p++;
memcpy(p, userkey, len);
p+=len;
}
uint8_t totallen = p - packet;
// add two empty bytes at the end (?)
p[0] = 0;
p[1] = 0;
p+=2;
packet[1] = totallen;
return totallen+2;
}
Adafruit_MQTT_Publish::Adafruit_MQTT_Publish(Adafruit_MQTT *mqttserver, char *feed) {
mqtt = mqttserver;
strncpy(feedname, feed, FEEDNAME_SIZE);
feedname[FEEDNAME_SIZE-1] = 0;
errno = 0;
}
<|endoftext|> |
<commit_before>/**
* @file llupdatedownloader.cpp
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include <stdexcept>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>
#include "lldir.h"
#include "llfile.h"
#include "llmd5.h"
#include "llsd.h"
#include "llsdserialize.h"
#include "llthread.h"
#include "llupdatedownloader.h"
#include "llupdaterservice.h"
class LLUpdateDownloader::Implementation:
public LLThread
{
public:
Implementation(LLUpdateDownloader::Client & client);
~Implementation();
void cancel(void);
void download(LLURI const & uri, std::string const & hash);
bool isDownloading(void);
size_t onHeader(void * header, size_t size);
size_t onBody(void * header, size_t size);
void resume(void);
private:
bool mCancelled;
LLUpdateDownloader::Client & mClient;
CURL * mCurl;
LLSD mDownloadData;
llofstream mDownloadStream;
std::string mDownloadRecordPath;
curl_slist * mHeaderList;
void initializeCurlGet(std::string const & url, bool processHeader);
void resumeDownloading(size_t startByte);
void run(void);
void startDownloading(LLURI const & uri, std::string const & hash);
void throwOnCurlError(CURLcode code);
bool validateDownload(void);
LOG_CLASS(LLUpdateDownloader::Implementation);
};
namespace {
class DownloadError:
public std::runtime_error
{
public:
DownloadError(const char * message):
std::runtime_error(message)
{
; // No op.
}
};
const char * gSecondLifeUpdateRecord = "SecondLifeUpdateDownload.xml";
};
// LLUpdateDownloader
//-----------------------------------------------------------------------------
std::string LLUpdateDownloader::downloadMarkerPath(void)
{
return gDirUtilp->getExpandedFilename(LL_PATH_LOGS, gSecondLifeUpdateRecord);
}
LLUpdateDownloader::LLUpdateDownloader(Client & client):
mImplementation(new LLUpdateDownloader::Implementation(client))
{
; // No op.
}
void LLUpdateDownloader::cancel(void)
{
mImplementation->cancel();
}
void LLUpdateDownloader::download(LLURI const & uri, std::string const & hash)
{
mImplementation->download(uri, hash);
}
bool LLUpdateDownloader::isDownloading(void)
{
return mImplementation->isDownloading();
}
void LLUpdateDownloader::resume(void)
{
mImplementation->resume();
}
// LLUpdateDownloader::Implementation
//-----------------------------------------------------------------------------
namespace {
size_t write_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onBody(data, bytes);
}
size_t header_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onHeader(data, bytes);
}
}
LLUpdateDownloader::Implementation::Implementation(LLUpdateDownloader::Client & client):
LLThread("LLUpdateDownloader"),
mCancelled(false),
mClient(client),
mCurl(0),
mHeaderList(0)
{
CURLcode code = curl_global_init(CURL_GLOBAL_ALL); // Just in case.
llverify(code == CURLE_OK); // TODO: real error handling here.
}
LLUpdateDownloader::Implementation::~Implementation()
{
if(isDownloading()) {
cancel();
shutdown();
} else {
; // No op.
}
if(mCurl) curl_easy_cleanup(mCurl);
}
void LLUpdateDownloader::Implementation::cancel(void)
{
mCancelled = true;
}
void LLUpdateDownloader::Implementation::download(LLURI const & uri, std::string const & hash)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
mDownloadData = LLSD();
try {
startDownloading(uri, hash);
} catch(DownloadError const & e) {
mClient.downloadError(e.what());
}
}
bool LLUpdateDownloader::Implementation::isDownloading(void)
{
return !isStopped();
}
void LLUpdateDownloader::Implementation::resume(void)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
llifstream dataStream(mDownloadRecordPath);
if(!dataStream) {
mClient.downloadError("no download marker");
return;
}
LLSDSerialize::fromXMLDocument(mDownloadData, dataStream);
if(!mDownloadData.asBoolean()) {
mClient.downloadError("no download information in marker");
return;
}
std::string filePath = mDownloadData["path"].asString();
try {
if(LLFile::isfile(filePath)) {
llstat fileStatus;
LLFile::stat(filePath, &fileStatus);
if(fileStatus.st_size != mDownloadData["size"].asInteger()) {
resumeDownloading(fileStatus.st_size);
} else if(!validateDownload()) {
LLFile::remove(filePath);
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
} else {
mClient.downloadComplete(mDownloadData);
}
} else {
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
}
} catch(DownloadError & e) {
mClient.downloadError(e.what());
}
}
size_t LLUpdateDownloader::Implementation::onHeader(void * buffer, size_t size)
{
char const * headerPtr = reinterpret_cast<const char *> (buffer);
std::string header(headerPtr, headerPtr + size);
size_t colonPosition = header.find(':');
if(colonPosition == std::string::npos) return size; // HTML response; ignore.
if(header.substr(0, colonPosition) == "Content-Length") {
try {
size_t firstDigitPos = header.find_first_of("0123456789", colonPosition);
size_t lastDigitPos = header.find_last_of("0123456789");
std::string contentLength = header.substr(firstDigitPos, lastDigitPos - firstDigitPos + 1);
size_t size = boost::lexical_cast<size_t>(contentLength);
LL_INFOS("UpdateDownload") << "download size is " << size << LL_ENDL;
mDownloadData["size"] = LLSD(LLSD::Integer(size));
llofstream odataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, odataStream);
} catch (std::exception const & e) {
LL_WARNS("UpdateDownload") << "unable to read content length ("
<< e.what() << ")" << LL_ENDL;
}
} else {
; // No op.
}
return size;
}
size_t LLUpdateDownloader::Implementation::onBody(void * buffer, size_t size)
{
if(mCancelled) return 0; // Forces a write error which will halt curl thread.
mDownloadStream.write(reinterpret_cast<const char *>(buffer), size);
return size;
}
void LLUpdateDownloader::Implementation::run(void)
{
CURLcode code = curl_easy_perform(mCurl);
mDownloadStream.close();
if(code == CURLE_OK) {
LLFile::remove(mDownloadRecordPath);
if(validateDownload()) {
LL_INFOS("UpdateDownload") << "download successful" << LL_ENDL;
mClient.downloadComplete(mDownloadData);
} else {
LL_INFOS("UpdateDownload") << "download failed hash check" << LL_ENDL;
std::string filePath = mDownloadData["path"].asString();
if(filePath.size() != 0) LLFile::remove(filePath);
mClient.downloadError("failed hash check");
}
} else if(mCancelled && (code == CURLE_WRITE_ERROR)) {
LL_INFOS("UpdateDownload") << "download canceled by user" << LL_ENDL;
// Do not call back client.
} else {
LL_WARNS("UpdateDownload") << "download failed with error '" <<
curl_easy_strerror(code) << "'" << LL_ENDL;
LLFile::remove(mDownloadRecordPath);
mClient.downloadError("curl error");
}
if(mHeaderList) {
curl_slist_free_all(mHeaderList);
mHeaderList = 0;
}
}
void LLUpdateDownloader::Implementation::initializeCurlGet(std::string const & url, bool processHeader)
{
if(mCurl == 0) {
mCurl = curl_easy_init();
} else {
curl_easy_reset(mCurl);
}
if(mCurl == 0) throw DownloadError("failed to initialize curl");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_NOSIGNAL, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_FOLLOWLOCATION, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEFUNCTION, &write_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEDATA, this));
if(processHeader) {
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERFUNCTION, &header_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERDATA, this));
}
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPGET, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_URL, url.c_str()));
}
void LLUpdateDownloader::Implementation::resumeDownloading(size_t startByte)
{
LL_INFOS("UpdateDownload") << "resuming download from " << mDownloadData["url"].asString()
<< " at byte " << startByte << LL_ENDL;
initializeCurlGet(mDownloadData["url"].asString(), false);
// The header 'Range: bytes n-' will request the bytes remaining in the
// source begining with byte n and ending with the last byte.
boost::format rangeHeaderFormat("Range: bytes=%u-");
rangeHeaderFormat % startByte;
mHeaderList = curl_slist_append(mHeaderList, rangeHeaderFormat.str().c_str());
if(mHeaderList == 0) throw DownloadError("cannot add Range header");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mHeaderList));
mDownloadStream.open(mDownloadData["path"].asString(),
std::ios_base::out | std::ios_base::binary | std::ios_base::app);
start();
}
void LLUpdateDownloader::Implementation::startDownloading(LLURI const & uri, std::string const & hash)
{
mDownloadData["url"] = uri.asString();
mDownloadData["hash"] = hash;
mDownloadData["current_version"] = ll_get_version();
LLSD path = uri.pathArray();
if(path.size() == 0) throw DownloadError("no file path");
std::string fileName = path[path.size() - 1].asString();
std::string filePath = gDirUtilp->getExpandedFilename(LL_PATH_TEMP, fileName);
mDownloadData["path"] = filePath;
LL_INFOS("UpdateDownload") << "downloading " << filePath
<< " from " << uri.asString() << LL_ENDL;
LL_INFOS("UpdateDownload") << "hash of file is " << hash << LL_ENDL;
llofstream dataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, dataStream);
mDownloadStream.open(filePath, std::ios_base::out | std::ios_base::binary);
initializeCurlGet(uri.asString(), true);
start();
}
void LLUpdateDownloader::Implementation::throwOnCurlError(CURLcode code)
{
if(code != CURLE_OK) {
const char * errorString = curl_easy_strerror(code);
if(errorString != 0) {
throw DownloadError(curl_easy_strerror(code));
} else {
throw DownloadError("unknown curl error");
}
} else {
; // No op.
}
}
bool LLUpdateDownloader::Implementation::validateDownload(void)
{
std::string filePath = mDownloadData["path"].asString();
llifstream fileStream(filePath, std::ios_base::in | std::ios_base::binary);
if(!fileStream) return false;
std::string hash = mDownloadData["hash"].asString();
if(hash.size() != 0) {
LL_INFOS("UpdateDownload") << "checking hash..." << LL_ENDL;
char digest[33];
LLMD5(fileStream).hex_digest(digest);
if(hash != digest) {
LL_WARNS("UpdateDownload") << "download hash mismatch; expeted " << hash <<
" but download is " << digest << LL_ENDL;
}
return hash == digest;
} else {
return true; // No hash check provided.
}
}
<commit_msg>better error checking when writing downloaded file.<commit_after>/**
* @file llupdatedownloader.cpp
*
* $LicenseInfo:firstyear=2010&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* 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
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include <stdexcept>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <curl/curl.h>
#include "lldir.h"
#include "llfile.h"
#include "llmd5.h"
#include "llsd.h"
#include "llsdserialize.h"
#include "llthread.h"
#include "llupdatedownloader.h"
#include "llupdaterservice.h"
class LLUpdateDownloader::Implementation:
public LLThread
{
public:
Implementation(LLUpdateDownloader::Client & client);
~Implementation();
void cancel(void);
void download(LLURI const & uri, std::string const & hash);
bool isDownloading(void);
size_t onHeader(void * header, size_t size);
size_t onBody(void * header, size_t size);
void resume(void);
private:
bool mCancelled;
LLUpdateDownloader::Client & mClient;
CURL * mCurl;
LLSD mDownloadData;
llofstream mDownloadStream;
std::string mDownloadRecordPath;
curl_slist * mHeaderList;
void initializeCurlGet(std::string const & url, bool processHeader);
void resumeDownloading(size_t startByte);
void run(void);
void startDownloading(LLURI const & uri, std::string const & hash);
void throwOnCurlError(CURLcode code);
bool validateDownload(void);
LOG_CLASS(LLUpdateDownloader::Implementation);
};
namespace {
class DownloadError:
public std::runtime_error
{
public:
DownloadError(const char * message):
std::runtime_error(message)
{
; // No op.
}
};
const char * gSecondLifeUpdateRecord = "SecondLifeUpdateDownload.xml";
};
// LLUpdateDownloader
//-----------------------------------------------------------------------------
std::string LLUpdateDownloader::downloadMarkerPath(void)
{
return gDirUtilp->getExpandedFilename(LL_PATH_LOGS, gSecondLifeUpdateRecord);
}
LLUpdateDownloader::LLUpdateDownloader(Client & client):
mImplementation(new LLUpdateDownloader::Implementation(client))
{
; // No op.
}
void LLUpdateDownloader::cancel(void)
{
mImplementation->cancel();
}
void LLUpdateDownloader::download(LLURI const & uri, std::string const & hash)
{
mImplementation->download(uri, hash);
}
bool LLUpdateDownloader::isDownloading(void)
{
return mImplementation->isDownloading();
}
void LLUpdateDownloader::resume(void)
{
mImplementation->resume();
}
// LLUpdateDownloader::Implementation
//-----------------------------------------------------------------------------
namespace {
size_t write_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onBody(data, bytes);
}
size_t header_function(void * data, size_t blockSize, size_t blocks, void * downloader)
{
size_t bytes = blockSize * blocks;
return reinterpret_cast<LLUpdateDownloader::Implementation *>(downloader)->onHeader(data, bytes);
}
}
LLUpdateDownloader::Implementation::Implementation(LLUpdateDownloader::Client & client):
LLThread("LLUpdateDownloader"),
mCancelled(false),
mClient(client),
mCurl(0),
mHeaderList(0)
{
CURLcode code = curl_global_init(CURL_GLOBAL_ALL); // Just in case.
llverify(code == CURLE_OK); // TODO: real error handling here.
}
LLUpdateDownloader::Implementation::~Implementation()
{
if(isDownloading()) {
cancel();
shutdown();
} else {
; // No op.
}
if(mCurl) curl_easy_cleanup(mCurl);
}
void LLUpdateDownloader::Implementation::cancel(void)
{
mCancelled = true;
}
void LLUpdateDownloader::Implementation::download(LLURI const & uri, std::string const & hash)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
mDownloadData = LLSD();
try {
startDownloading(uri, hash);
} catch(DownloadError const & e) {
mClient.downloadError(e.what());
}
}
bool LLUpdateDownloader::Implementation::isDownloading(void)
{
return !isStopped();
}
void LLUpdateDownloader::Implementation::resume(void)
{
if(isDownloading()) mClient.downloadError("download in progress");
mDownloadRecordPath = downloadMarkerPath();
llifstream dataStream(mDownloadRecordPath);
if(!dataStream) {
mClient.downloadError("no download marker");
return;
}
LLSDSerialize::fromXMLDocument(mDownloadData, dataStream);
if(!mDownloadData.asBoolean()) {
mClient.downloadError("no download information in marker");
return;
}
std::string filePath = mDownloadData["path"].asString();
try {
if(LLFile::isfile(filePath)) {
llstat fileStatus;
LLFile::stat(filePath, &fileStatus);
if(fileStatus.st_size != mDownloadData["size"].asInteger()) {
resumeDownloading(fileStatus.st_size);
} else if(!validateDownload()) {
LLFile::remove(filePath);
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
} else {
mClient.downloadComplete(mDownloadData);
}
} else {
download(LLURI(mDownloadData["url"].asString()), mDownloadData["hash"].asString());
}
} catch(DownloadError & e) {
mClient.downloadError(e.what());
}
}
size_t LLUpdateDownloader::Implementation::onHeader(void * buffer, size_t size)
{
char const * headerPtr = reinterpret_cast<const char *> (buffer);
std::string header(headerPtr, headerPtr + size);
size_t colonPosition = header.find(':');
if(colonPosition == std::string::npos) return size; // HTML response; ignore.
if(header.substr(0, colonPosition) == "Content-Length") {
try {
size_t firstDigitPos = header.find_first_of("0123456789", colonPosition);
size_t lastDigitPos = header.find_last_of("0123456789");
std::string contentLength = header.substr(firstDigitPos, lastDigitPos - firstDigitPos + 1);
size_t size = boost::lexical_cast<size_t>(contentLength);
LL_INFOS("UpdateDownload") << "download size is " << size << LL_ENDL;
mDownloadData["size"] = LLSD(LLSD::Integer(size));
llofstream odataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, odataStream);
} catch (std::exception const & e) {
LL_WARNS("UpdateDownload") << "unable to read content length ("
<< e.what() << ")" << LL_ENDL;
}
} else {
; // No op.
}
return size;
}
size_t LLUpdateDownloader::Implementation::onBody(void * buffer, size_t size)
{
if(mCancelled) return 0; // Forces a write error which will halt curl thread.
if((size == 0) || (buffer == 0)) return 0;
mDownloadStream.write(reinterpret_cast<const char *>(buffer), size);
if(mDownloadStream.bad()) {
return 0;
} else {
return size;
}
}
void LLUpdateDownloader::Implementation::run(void)
{
CURLcode code = curl_easy_perform(mCurl);
mDownloadStream.close();
if(code == CURLE_OK) {
LLFile::remove(mDownloadRecordPath);
if(validateDownload()) {
LL_INFOS("UpdateDownload") << "download successful" << LL_ENDL;
mClient.downloadComplete(mDownloadData);
} else {
LL_INFOS("UpdateDownload") << "download failed hash check" << LL_ENDL;
std::string filePath = mDownloadData["path"].asString();
if(filePath.size() != 0) LLFile::remove(filePath);
mClient.downloadError("failed hash check");
}
} else if(mCancelled && (code == CURLE_WRITE_ERROR)) {
LL_INFOS("UpdateDownload") << "download canceled by user" << LL_ENDL;
// Do not call back client.
} else {
LL_WARNS("UpdateDownload") << "download failed with error '" <<
curl_easy_strerror(code) << "'" << LL_ENDL;
LLFile::remove(mDownloadRecordPath);
mClient.downloadError("curl error");
}
if(mHeaderList) {
curl_slist_free_all(mHeaderList);
mHeaderList = 0;
}
}
void LLUpdateDownloader::Implementation::initializeCurlGet(std::string const & url, bool processHeader)
{
if(mCurl == 0) {
mCurl = curl_easy_init();
} else {
curl_easy_reset(mCurl);
}
if(mCurl == 0) throw DownloadError("failed to initialize curl");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_NOSIGNAL, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_FOLLOWLOCATION, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEFUNCTION, &write_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_WRITEDATA, this));
if(processHeader) {
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERFUNCTION, &header_function));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HEADERDATA, this));
}
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPGET, true));
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_URL, url.c_str()));
}
void LLUpdateDownloader::Implementation::resumeDownloading(size_t startByte)
{
LL_INFOS("UpdateDownload") << "resuming download from " << mDownloadData["url"].asString()
<< " at byte " << startByte << LL_ENDL;
initializeCurlGet(mDownloadData["url"].asString(), false);
// The header 'Range: bytes n-' will request the bytes remaining in the
// source begining with byte n and ending with the last byte.
boost::format rangeHeaderFormat("Range: bytes=%u-");
rangeHeaderFormat % startByte;
mHeaderList = curl_slist_append(mHeaderList, rangeHeaderFormat.str().c_str());
if(mHeaderList == 0) throw DownloadError("cannot add Range header");
throwOnCurlError(curl_easy_setopt(mCurl, CURLOPT_HTTPHEADER, mHeaderList));
mDownloadStream.open(mDownloadData["path"].asString(),
std::ios_base::out | std::ios_base::binary | std::ios_base::app);
start();
}
void LLUpdateDownloader::Implementation::startDownloading(LLURI const & uri, std::string const & hash)
{
mDownloadData["url"] = uri.asString();
mDownloadData["hash"] = hash;
mDownloadData["current_version"] = ll_get_version();
LLSD path = uri.pathArray();
if(path.size() == 0) throw DownloadError("no file path");
std::string fileName = path[path.size() - 1].asString();
std::string filePath = gDirUtilp->getExpandedFilename(LL_PATH_TEMP, fileName);
mDownloadData["path"] = filePath;
LL_INFOS("UpdateDownload") << "downloading " << filePath
<< " from " << uri.asString() << LL_ENDL;
LL_INFOS("UpdateDownload") << "hash of file is " << hash << LL_ENDL;
llofstream dataStream(mDownloadRecordPath);
LLSDSerialize::toPrettyXML(mDownloadData, dataStream);
mDownloadStream.open(filePath, std::ios_base::out | std::ios_base::binary);
initializeCurlGet(uri.asString(), true);
start();
}
void LLUpdateDownloader::Implementation::throwOnCurlError(CURLcode code)
{
if(code != CURLE_OK) {
const char * errorString = curl_easy_strerror(code);
if(errorString != 0) {
throw DownloadError(curl_easy_strerror(code));
} else {
throw DownloadError("unknown curl error");
}
} else {
; // No op.
}
}
bool LLUpdateDownloader::Implementation::validateDownload(void)
{
std::string filePath = mDownloadData["path"].asString();
llifstream fileStream(filePath, std::ios_base::in | std::ios_base::binary);
if(!fileStream) return false;
std::string hash = mDownloadData["hash"].asString();
if(hash.size() != 0) {
LL_INFOS("UpdateDownload") << "checking hash..." << LL_ENDL;
char digest[33];
LLMD5(fileStream).hex_digest(digest);
if(hash != digest) {
LL_WARNS("UpdateDownload") << "download hash mismatch; expeted " << hash <<
" but download is " << digest << LL_ENDL;
}
return hash == digest;
} else {
return true; // No hash check provided.
}
}
<|endoftext|> |
<commit_before>/*
This file is part of KXForms.
Copyright (c) 2007 Andre Duffeck <aduffeck@suse.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "editorwidget.h"
#include "editor.h"
#include <kdebug.h>
#include <kpixmapeffect.h>
#include <kactionmenu.h>
#include <kmenu.h>
#include <klocale.h>
#include <kiconloader.h>
#include <QTimer>
#include <QPoint>
#include <QPainter>
#include <QMouseEvent>
#include <QPushButton>
#include <QEventLoop>
#include <QWhatsThis>
using namespace KXForms;
EditorWidget::EditorWidget( Editor *e, QWidget *parent )
: QWidget( parent ), mEditor( e ), mHoveredElement( 0 ), mActiveElement( 0 ),
mEventLoop( new QEventLoop( this ) ), mSelectionMode( false ), mInEdit( false )
{
setMouseTracking( true );
setGeometry( parent->geometry() );
mShowHintsButton = new QPushButton( this );
mShowHintsButton->setIcon( KIconLoader::global()->loadIcon( "list", K3Icon::NoGroup, 32 ) );
mShowHintsButton->move( QPoint( width() - mShowHintsButton->width(), 0 ) );
connect( mShowHintsButton, SIGNAL(clicked()), SLOT(showHints()) );
mEditButton = new QPushButton( this );
mEditButton->setIcon( KIconLoader::global()->loadIcon( "edit", K3Icon::NoGroup, 32 ) );
mEditButton->hide();
connect( mEditButton, SIGNAL(clicked()), SLOT(showActionMenu()) );
}
void EditorWidget::setGuiElements( const GuiElement::List &list )
{
foreach( GuiElement *e, list ) {
QRect r = e->widget()->geometry();
if( e->labelWidget() )
r |= e->labelWidget()->geometry();
QPoint widgetPos = e->widget()->mapToGlobal(QPoint(0,0)) - mapToGlobal(QPoint(0,0));
QPoint labelWidgetPos = e->labelWidget() ? e->labelWidget()->mapToGlobal(QPoint(0,0)) - mapToGlobal(QPoint(0,0)) : widgetPos;
r.moveTop( qMin( widgetPos.y(), labelWidgetPos.y() ) );
r.moveLeft( qMin( widgetPos.x(), labelWidgetPos.x() ) );
mElementMap[e] = r;
}
}
void EditorWidget::setInEdit( bool b )
{
mInEdit = b;
if( !b )
mActiveElement = 0;
}
void EditorWidget::mouseMoveEvent( QMouseEvent *event )
{
// kDebug() << k_funcinfo << endl;
GuiElement *newElement = 0;
QPoint pos = event->pos();
foreach( QRect r, mElementMap.values() ) {
if( r.contains( pos ) ) {
if( !newElement ||
mElementMap[ newElement ].width() > r.width() ||
mElementMap[ newElement ].height() > r.height() ) {
newElement = mElementMap.key( r );
}
}
}
if( mHoveredElement != newElement )
update();
mHoveredElement = newElement;
}
void EditorWidget::mouseReleaseEvent( QMouseEvent *event )
{
// kDebug() << k_funcinfo << endl;
if( !mSelectionMode )
return;
if( mEventLoop->isRunning() ) {
mEventLoop->exit();
}
mSelectionMode = false;
}
void EditorWidget::paintEvent( QPaintEvent *event )
{
// kDebug() << k_funcinfo << endl;
QPainter p( this );
if( mSelectionMode ) {
if( mHoveredElement != mActiveElement )
targetElement( &p, mElementMap[mHoveredElement], mHoveredElement );
}
if( !mInEdit ) {
if( mHoveredElement ) {
highlightElement( &p, mElementMap[mHoveredElement], mHoveredElement );
drawInterface( &p, mElementMap[mHoveredElement], mHoveredElement );
} else {
mEditButton->hide();
}
} else {
if( mActiveElement ) {
highlightElement( &p, mElementMap[mActiveElement], mActiveElement );
}
}
drawGlobalInterface( &p );
}
void EditorWidget::drawGlobalInterface( QPainter *p )
{
p->save();
QBrush b( QColor(0,0,0,25) );
p->fillRect( rect(), b );
int boxWidth = 20 + mShowHintsButton->width();
int boxHeight = 20 + mShowHintsButton->height();
QRect r( width() - boxWidth - 10, 10, boxWidth, boxHeight );
QPen pen;
pen.setColor( QColor(255,255,255,255) );
pen.setWidth( 2 );
b.setColor( QColor(0,0,0,100) );
p->setPen( pen );
p->setBrush( b );
p->drawRoundRect( r );
mShowHintsButton->move( width() - 20 - mShowHintsButton->width(), 20 );
p->restore();
}
void EditorWidget::targetElement( QPainter *p, const QRect &r, GuiElement *w )
{
p->save();
QPen pen;
pen.setColor( QColor(255,0,0,255) );
pen.setWidth( 3 );
p->setPen( pen );
p->drawRect( r );
p->restore();
}
void EditorWidget::highlightElement( QPainter *p, const QRect &r, GuiElement *w )
{
p->save();
QPoint point( r.x()+20, r.y() );
QPen pen;
pen.setColor( QColor(255,255,255,255) );
pen.setWidth( 3 );
p->setPen( pen );
p->drawRect( r );
QBrush b( QColor(0,0,0,100) );
p->fillRect( r, b );
QFont fnt;
fnt.setPointSize( 14 );
fnt.setBold( true );
p->setFont( fnt );
p->drawText( point + QPoint(0,QFontMetrics( fnt ).height() ), w->ref().toString() );
p->restore();
}
void EditorWidget::drawInterface( QPainter *p, const QRect &r, GuiElement *w )
{
Q_UNUSED( p );
QPoint point( r.x()+20, r.y() );
QFont fnt;
fnt.setPointSize( 14 );
fnt.setBold( true );
point.setX( point.x() + 10 + QFontMetrics( fnt ).width( w->ref().toString() ));
mEditButton->move( point );
mEditButton->show();
}
void EditorWidget::showActionMenu()
{
KActionMenu *menu = mEditor->actionMenu( mHoveredElement );
menu->menu()->popup( mapToGlobal( mEditButton->pos() ) );
mActiveElement = mHoveredElement;
}
void EditorWidget::showHints()
{
QString text = mEditor->hints().toRichText();
QWhatsThis::showText( mapToGlobal( mShowHintsButton->pos() ), text );
}
GuiElement *EditorWidget::selectElement()
{
mSelectionMode = true;
mEventLoop->exec();
return mHoveredElement;
}
#include "editorwidget.moc"
<commit_msg>Show tooltips on the edit buttons<commit_after>/*
This file is part of KXForms.
Copyright (c) 2007 Andre Duffeck <aduffeck@suse.de>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "editorwidget.h"
#include "editor.h"
#include <kdebug.h>
#include <kpixmapeffect.h>
#include <kactionmenu.h>
#include <kmenu.h>
#include <klocale.h>
#include <kiconloader.h>
#include <QTimer>
#include <QPoint>
#include <QPainter>
#include <QMouseEvent>
#include <QPushButton>
#include <QEventLoop>
#include <QWhatsThis>
using namespace KXForms;
EditorWidget::EditorWidget( Editor *e, QWidget *parent )
: QWidget( parent ), mEditor( e ), mHoveredElement( 0 ), mActiveElement( 0 ),
mEventLoop( new QEventLoop( this ) ), mSelectionMode( false ), mInEdit( false )
{
setMouseTracking( true );
setGeometry( parent->geometry() );
mShowHintsButton = new QPushButton( this );
mShowHintsButton->setIcon( KIconLoader::global()->loadIcon( "list", K3Icon::NoGroup, 32 ) );
mShowHintsButton->move( QPoint( width() - mShowHintsButton->width(), 0 ) );
mShowHintsButton->setToolTip( i18n("Show hints") );
connect( mShowHintsButton, SIGNAL(clicked()), SLOT(showHints()) );
mEditButton = new QPushButton( this );
mEditButton->setIcon( KIconLoader::global()->loadIcon( "edit", K3Icon::NoGroup, 32 ) );
mEditButton->hide();
mEditButton->setToolTip( i18n("Edit element") );
connect( mEditButton, SIGNAL(clicked()), SLOT(showActionMenu()) );
}
void EditorWidget::setGuiElements( const GuiElement::List &list )
{
foreach( GuiElement *e, list ) {
QRect r = e->widget()->geometry();
if( e->labelWidget() )
r |= e->labelWidget()->geometry();
QPoint widgetPos = e->widget()->mapToGlobal(QPoint(0,0)) - mapToGlobal(QPoint(0,0));
QPoint labelWidgetPos = e->labelWidget() ? e->labelWidget()->mapToGlobal(QPoint(0,0)) - mapToGlobal(QPoint(0,0)) : widgetPos;
r.moveTop( qMin( widgetPos.y(), labelWidgetPos.y() ) );
r.moveLeft( qMin( widgetPos.x(), labelWidgetPos.x() ) );
mElementMap[e] = r;
}
}
void EditorWidget::setInEdit( bool b )
{
mInEdit = b;
if( !b )
mActiveElement = 0;
}
void EditorWidget::mouseMoveEvent( QMouseEvent *event )
{
// kDebug() << k_funcinfo << endl;
GuiElement *newElement = 0;
QPoint pos = event->pos();
foreach( QRect r, mElementMap.values() ) {
if( r.contains( pos ) ) {
if( !newElement ||
mElementMap[ newElement ].width() > r.width() ||
mElementMap[ newElement ].height() > r.height() ) {
newElement = mElementMap.key( r );
}
}
}
if( mHoveredElement != newElement )
update();
mHoveredElement = newElement;
}
void EditorWidget::mouseReleaseEvent( QMouseEvent *event )
{
// kDebug() << k_funcinfo << endl;
if( !mSelectionMode )
return;
if( mEventLoop->isRunning() ) {
mEventLoop->exit();
}
mSelectionMode = false;
}
void EditorWidget::paintEvent( QPaintEvent *event )
{
// kDebug() << k_funcinfo << endl;
QPainter p( this );
if( mSelectionMode ) {
if( mHoveredElement != mActiveElement )
targetElement( &p, mElementMap[mHoveredElement], mHoveredElement );
}
if( !mInEdit ) {
if( mHoveredElement ) {
highlightElement( &p, mElementMap[mHoveredElement], mHoveredElement );
drawInterface( &p, mElementMap[mHoveredElement], mHoveredElement );
} else {
mEditButton->hide();
}
} else {
if( mActiveElement ) {
highlightElement( &p, mElementMap[mActiveElement], mActiveElement );
}
}
drawGlobalInterface( &p );
}
void EditorWidget::drawGlobalInterface( QPainter *p )
{
p->save();
QBrush b( QColor(0,0,0,25) );
p->fillRect( rect(), b );
int boxWidth = 20 + mShowHintsButton->width();
int boxHeight = 20 + mShowHintsButton->height();
QRect r( width() - boxWidth - 10, 10, boxWidth, boxHeight );
QPen pen;
pen.setColor( QColor(255,255,255,255) );
pen.setWidth( 2 );
b.setColor( QColor(0,0,0,100) );
p->setPen( pen );
p->setBrush( b );
p->drawRoundRect( r );
mShowHintsButton->move( width() - 20 - mShowHintsButton->width(), 20 );
p->restore();
}
void EditorWidget::targetElement( QPainter *p, const QRect &r, GuiElement *w )
{
p->save();
QPen pen;
pen.setColor( QColor(255,0,0,255) );
pen.setWidth( 3 );
p->setPen( pen );
p->drawRect( r );
p->restore();
}
void EditorWidget::highlightElement( QPainter *p, const QRect &r, GuiElement *w )
{
p->save();
QPoint point( r.x()+20, r.y() );
QPen pen;
pen.setColor( QColor(255,255,255,255) );
pen.setWidth( 3 );
p->setPen( pen );
p->drawRect( r );
QBrush b( QColor(0,0,0,100) );
p->fillRect( r, b );
QFont fnt;
fnt.setPointSize( 14 );
fnt.setBold( true );
p->setFont( fnt );
p->drawText( point + QPoint(0,QFontMetrics( fnt ).height() ), w->ref().toString() );
p->restore();
}
void EditorWidget::drawInterface( QPainter *p, const QRect &r, GuiElement *w )
{
Q_UNUSED( p );
QPoint point( r.x()+20, r.y() );
QFont fnt;
fnt.setPointSize( 14 );
fnt.setBold( true );
point.setX( point.x() + 10 + QFontMetrics( fnt ).width( w->ref().toString() ));
mEditButton->move( point );
mEditButton->show();
}
void EditorWidget::showActionMenu()
{
KActionMenu *menu = mEditor->actionMenu( mHoveredElement );
menu->menu()->popup( mapToGlobal( mEditButton->pos() ) );
mActiveElement = mHoveredElement;
}
void EditorWidget::showHints()
{
QString text = mEditor->hints().toRichText();
QWhatsThis::showText( mapToGlobal( mShowHintsButton->pos() ), text );
}
GuiElement *EditorWidget::selectElement()
{
mSelectionMode = true;
mEventLoop->exec();
return mHoveredElement;
}
#include "editorwidget.moc"
<|endoftext|> |
<commit_before>/****************************************************************************
This file is part of the QtMediaHub project on http://www.qtmediahub.com
Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Girish Ramakrishnan girish@forwardbias.in
Contact: Nokia Corporation donald.carr@nokia.com
Contact: Nokia Corporation johannes.zellner@nokia.com
You may use this file under the terms of the BSD license as follows:
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 Nokia Corporation and its Subsidiary(-ies) 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 "actionmapper.h"
#include "libraryinfo.h"
#ifdef SCENEGRAPH
#include <QGraphicsView>
#include <QApplication>
#endif
#include <QKeyEvent>
#include "globalsettings.h"
ActionMapper::ActionMapper(GlobalSettings *settings, QObject *parent) :
QObject(parent),
m_settings(settings)
{
setupQtKeyMap();
m_mapName = m_settings->value(GlobalSettings::Keymap).toString();
qDebug() << "Available maps " << availableMaps();
qDebug() << "used keymap" << m_mapName;
populateMap();
}
QHash<ActionMapper::Action, Qt::Key> ActionMapper::s_actionToQtKeyMap;
void ActionMapper::setupQtKeyMap()
{
static bool initialized = false;
if (initialized)
return;
s_actionToQtKeyMap.insert(ActionMapper::Left, Qt::Key_Left);
s_actionToQtKeyMap.insert(ActionMapper::Right, Qt::Key_Right);
s_actionToQtKeyMap.insert(ActionMapper::Up, Qt::Key_Up);
s_actionToQtKeyMap.insert(ActionMapper::Down, Qt::Key_Down);
s_actionToQtKeyMap.insert(ActionMapper::Enter, Qt::Key_Enter);
s_actionToQtKeyMap.insert(ActionMapper::Menu, Qt::Key_Menu);
s_actionToQtKeyMap.insert(ActionMapper::Context, Qt::Key_Context1);
s_actionToQtKeyMap.insert(ActionMapper::ContextualUp, Qt::Key_PageUp);
s_actionToQtKeyMap.insert(ActionMapper::ContextualDown, Qt::Key_PageDown);
s_actionToQtKeyMap.insert(ActionMapper::MediaPlayPause, Qt::Key_MediaTogglePlayPause);
s_actionToQtKeyMap.insert(ActionMapper::MediaStop, Qt::Key_MediaStop);
s_actionToQtKeyMap.insert(ActionMapper::MediaPrevious, Qt::Key_MediaPrevious);
s_actionToQtKeyMap.insert(ActionMapper::MediaNext, Qt::Key_MediaNext);
s_actionToQtKeyMap.insert(ActionMapper::Back, Qt::Key_Back);
s_actionToQtKeyMap.insert(ActionMapper::VolumeUp, Qt::Key_VolumeUp);
s_actionToQtKeyMap.insert(ActionMapper::VolumeDown, Qt::Key_VolumeDown);
initialized = true;
}
void ActionMapper::takeAction(Action action)
{
if (m_recipient.isNull()) {
qWarning("Trying to send an action when no recipient is set");
return;
}
Qt::Key key = s_actionToQtKeyMap.value(action);
QKeyEvent keyPress(QEvent::KeyPress, key, Qt::NoModifier);
qApp->sendEvent(m_recipient.data(), &keyPress);
QKeyEvent keyRelease(QEvent::KeyRelease, key, Qt::NoModifier);
qApp->sendEvent(m_recipient.data(), &keyRelease);
}
void ActionMapper::processKey(qlonglong key)
{
if (m_recipient.isNull()) {
qWarning("Trying to send a key when no recipient is set");
return;
}
int code = (int)key;
bool upper = false;
// lower-/upper-case characters
if (key >= 97 && key <=122) {
code -= 32;
} else if (key >= Qt::Key_A && key <= Qt::Key_Z) {
upper = true;
}
QKeyEvent keyPress(QEvent::KeyPress, code, upper ? Qt::ShiftModifier : Qt::NoModifier, QString(int(key)));
qApp->sendEvent(m_recipient.data(), &keyPress);
QKeyEvent keyRelease(QEvent::KeyRelease, code, upper ? Qt::ShiftModifier : Qt::NoModifier, QString(int(key)));
qApp->sendEvent(m_recipient.data(), &keyRelease);
}
void ActionMapper::populateMap()
{
m_actionMap.clear();
foreach (const QString &keyboardMapPath, LibraryInfo::keyboardMapPaths(m_settings)) {
if (QFile::exists(keyboardMapPath + "/" + m_mapName)
&& loadMapFromDisk(keyboardMapPath + m_mapName)) {
qDebug() << "Using key map:" << keyboardMapPath + m_mapName;
break;
}
}
}
bool ActionMapper::loadMapFromDisk(const QString &mapFilePath)
{
const QMetaObject &ActionMO = ActionMapper::staticMetaObject;
int enumIndex = ActionMO.indexOfEnumerator("Action");
QMetaEnum actionEnum = ActionMO.enumerator(enumIndex);
enumIndex = staticQtMetaObject.indexOfEnumerator("Key");
QMetaEnum keyEnum = staticQtMetaObject.enumerator(enumIndex);
QFile mapFile(mapFilePath);
if (!mapFile.exists() || !mapFile.open(QIODevice::ReadOnly)) {
qWarning() << "Could not load keymap: " << mapFilePath;
return false;
}
QTextStream mapStream(&mapFile);
while (!mapStream.atEnd()) {
QStringList mapping = mapStream.readLine().split("=");
QStringList keyStrings = mapping.at(1).split(",");
QList<int> keys;
int index = actionEnum.keyToValue(mapping[0].toAscii().constData());
if (index == -1) {
qWarning() << "\tMapped action is not defined in ActionMapper, skipping: " << mapping[0];
continue;
}
foreach(const QString &key, keyStrings) {
int keyIndex = keyEnum.keyToValue(QString("Key_").append(key).toAscii().constData());
if (keyIndex == -1) {
qWarning() << "\tQt Key does not exist: Key_" << key;
continue;
}
m_actionMap[keyIndex] = static_cast<Action>(index);
}
}
return true;
}
QStringList ActionMapper::availableMaps() const
{
QStringList maps;
foreach (const QString &keyboardMapPath, LibraryInfo::keyboardMapPaths(m_settings)) {
foreach (const QString &keymap, QDir(keyboardMapPath).entryList(QDir::Files)) {
if (maps.contains(keymap)) {
continue;
}
maps << keymap;
}
}
return maps;
}
void ActionMapper::setMap(const QString &map)
{
m_mapName = map;
populateMap();
}
void ActionMapper::setRecipient(QObject *recipient)
{
recipient->installEventFilter(this);
QGraphicsView *potentialView = qobject_cast<QGraphicsView*>(recipient);
if (potentialView) {
// directly send to the scene, to avoid loops
m_recipient = QWeakPointer<QObject>(potentialView->scene());
} else {
m_recipient = QWeakPointer<QObject>(recipient);
}
}
bool ActionMapper::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
int key = keyEvent->key();
if (m_actionMap.contains(key)) {
QKeyEvent *e = new QKeyEvent(keyEvent->type()
, s_actionToQtKeyMap.value(m_actionMap.value(keyEvent->key()))
, keyEvent->modifiers()
, keyEvent->text()
, keyEvent->isAutoRepeat()
, keyEvent->count());
if (!m_recipient.isNull()) {
QApplication::postEvent(m_recipient.data(), e);
return true;
} else {
qDebug() << "The intended recipient has been forcibly shuffled off this mortal coil";
}
}
}
// standard event processing
return QObject::eventFilter(obj, event);
}
<commit_msg>Fix Qt 5 event voodoo<commit_after>/****************************************************************************
This file is part of the QtMediaHub project on http://www.qtmediahub.com
Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.
Contact: Girish Ramakrishnan girish@forwardbias.in
Contact: Nokia Corporation donald.carr@nokia.com
Contact: Nokia Corporation johannes.zellner@nokia.com
You may use this file under the terms of the BSD license as follows:
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 Nokia Corporation and its Subsidiary(-ies) 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 "actionmapper.h"
#include "libraryinfo.h"
#ifdef SCENEGRAPH
#include <QGraphicsView>
#include <QApplication>
#endif
#include <QKeyEvent>
#include "globalsettings.h"
ActionMapper::ActionMapper(GlobalSettings *settings, QObject *parent) :
QObject(parent),
m_settings(settings)
{
setupQtKeyMap();
m_mapName = m_settings->value(GlobalSettings::Keymap).toString();
qDebug() << "Available maps " << availableMaps();
qDebug() << "used keymap" << m_mapName;
populateMap();
}
QHash<ActionMapper::Action, Qt::Key> ActionMapper::s_actionToQtKeyMap;
void ActionMapper::setupQtKeyMap()
{
static bool initialized = false;
if (initialized)
return;
s_actionToQtKeyMap.insert(ActionMapper::Left, Qt::Key_Left);
s_actionToQtKeyMap.insert(ActionMapper::Right, Qt::Key_Right);
s_actionToQtKeyMap.insert(ActionMapper::Up, Qt::Key_Up);
s_actionToQtKeyMap.insert(ActionMapper::Down, Qt::Key_Down);
s_actionToQtKeyMap.insert(ActionMapper::Enter, Qt::Key_Enter);
s_actionToQtKeyMap.insert(ActionMapper::Menu, Qt::Key_Menu);
s_actionToQtKeyMap.insert(ActionMapper::Context, Qt::Key_Context1);
s_actionToQtKeyMap.insert(ActionMapper::ContextualUp, Qt::Key_PageUp);
s_actionToQtKeyMap.insert(ActionMapper::ContextualDown, Qt::Key_PageDown);
s_actionToQtKeyMap.insert(ActionMapper::MediaPlayPause, Qt::Key_MediaTogglePlayPause);
s_actionToQtKeyMap.insert(ActionMapper::MediaStop, Qt::Key_MediaStop);
s_actionToQtKeyMap.insert(ActionMapper::MediaPrevious, Qt::Key_MediaPrevious);
s_actionToQtKeyMap.insert(ActionMapper::MediaNext, Qt::Key_MediaNext);
s_actionToQtKeyMap.insert(ActionMapper::Back, Qt::Key_Back);
s_actionToQtKeyMap.insert(ActionMapper::VolumeUp, Qt::Key_VolumeUp);
s_actionToQtKeyMap.insert(ActionMapper::VolumeDown, Qt::Key_VolumeDown);
initialized = true;
}
void ActionMapper::takeAction(Action action)
{
if (m_recipient.isNull()) {
qWarning("Trying to send an action when no recipient is set");
return;
}
Qt::Key key = s_actionToQtKeyMap.value(action);
QKeyEvent keyPress(QEvent::KeyPress, key, Qt::NoModifier);
qApp->sendEvent(m_recipient.data(), &keyPress);
QKeyEvent keyRelease(QEvent::KeyRelease, key, Qt::NoModifier);
qApp->sendEvent(m_recipient.data(), &keyRelease);
}
void ActionMapper::processKey(qlonglong key)
{
if (m_recipient.isNull()) {
qWarning("Trying to send a key when no recipient is set");
return;
}
int code = (int)key;
bool upper = false;
// lower-/upper-case characters
if (key >= 97 && key <=122) {
code -= 32;
} else if (key >= Qt::Key_A && key <= Qt::Key_Z) {
upper = true;
}
QKeyEvent keyPress(QEvent::KeyPress, code, upper ? Qt::ShiftModifier : Qt::NoModifier, QString(int(key)));
qApp->sendEvent(m_recipient.data(), &keyPress);
QKeyEvent keyRelease(QEvent::KeyRelease, code, upper ? Qt::ShiftModifier : Qt::NoModifier, QString(int(key)));
qApp->sendEvent(m_recipient.data(), &keyRelease);
}
void ActionMapper::populateMap()
{
m_actionMap.clear();
foreach (const QString &keyboardMapPath, LibraryInfo::keyboardMapPaths(m_settings)) {
if (QFile::exists(keyboardMapPath + "/" + m_mapName)
&& loadMapFromDisk(keyboardMapPath + m_mapName)) {
qDebug() << "Using key map:" << keyboardMapPath + m_mapName;
break;
}
}
}
bool ActionMapper::loadMapFromDisk(const QString &mapFilePath)
{
const QMetaObject &ActionMO = ActionMapper::staticMetaObject;
int enumIndex = ActionMO.indexOfEnumerator("Action");
QMetaEnum actionEnum = ActionMO.enumerator(enumIndex);
enumIndex = staticQtMetaObject.indexOfEnumerator("Key");
QMetaEnum keyEnum = staticQtMetaObject.enumerator(enumIndex);
QFile mapFile(mapFilePath);
if (!mapFile.exists() || !mapFile.open(QIODevice::ReadOnly)) {
qWarning() << "Could not load keymap: " << mapFilePath;
return false;
}
QTextStream mapStream(&mapFile);
while (!mapStream.atEnd()) {
QStringList mapping = mapStream.readLine().split("=");
QStringList keyStrings = mapping.at(1).split(",");
QList<int> keys;
int index = actionEnum.keyToValue(mapping[0].toAscii().constData());
if (index == -1) {
qWarning() << "\tMapped action is not defined in ActionMapper, skipping: " << mapping[0];
continue;
}
foreach(const QString &key, keyStrings) {
int keyIndex = keyEnum.keyToValue(QString("Key_").append(key).toAscii().constData());
if (keyIndex == -1) {
qWarning() << "\tQt Key does not exist: Key_" << key;
continue;
}
m_actionMap[keyIndex] = static_cast<Action>(index);
}
}
return true;
}
QStringList ActionMapper::availableMaps() const
{
QStringList maps;
foreach (const QString &keyboardMapPath, LibraryInfo::keyboardMapPaths(m_settings)) {
foreach (const QString &keymap, QDir(keyboardMapPath).entryList(QDir::Files)) {
if (maps.contains(keymap)) {
continue;
}
maps << keymap;
}
}
return maps;
}
void ActionMapper::setMap(const QString &map)
{
m_mapName = map;
populateMap();
}
void ActionMapper::setRecipient(QObject *recipient)
{
QGraphicsView *potentialView = qobject_cast<QGraphicsView*>(recipient);
if (potentialView) {
recipient->installEventFilter(this);
// directly send to the scene, to avoid loops
m_recipient = QWeakPointer<QObject>(potentialView->scene());
} else {
qDebug() << "Deviation from original filtering";
}
//else {
// m_recipient = QWeakPointer<QObject>(recipient);
//}
}
bool ActionMapper::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
int key = keyEvent->key();
if (m_actionMap.contains(key)) {
QKeyEvent *e = new QKeyEvent(keyEvent->type()
, s_actionToQtKeyMap.value(m_actionMap.value(keyEvent->key()))
, keyEvent->modifiers()
, keyEvent->text()
, keyEvent->isAutoRepeat()
, keyEvent->count());
if (!m_recipient.isNull()) {
QApplication::postEvent(m_recipient.data(), e);
return true;
} else {
qDebug() << "The intended recipient has been forcibly shuffled off this mortal coil";
}
}
}
// standard event processing
return QObject::eventFilter(obj, event);
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
bool TBeing::canDisarm(TBeing *victim, silentTypeT silent)
{
switch (race->getBodyType()) {
case BODY_PIERCER:
case BODY_MOSS:
case BODY_KUOTOA:
case BODY_MANTICORE:
case BODY_GRIFFON:
case BODY_SHEDU:
case BODY_SPHINX:
case BODY_LAMMASU:
case BODY_WYVERN:
case BODY_DRAGONNE:
case BODY_HIPPOGRIFF:
case BODY_CHIMERA:
case BODY_SNAKE:
case BODY_NAGA:
case BODY_ORB:
case BODY_VEGGIE:
case BODY_LION:
case BODY_FELINE:
case BODY_REPTILE:
case BODY_DINOSAUR:
case BODY_FOUR_LEG:
case BODY_PIG:
case BODY_FOUR_HOOF:
case BODY_ELEPHANT:
case BODY_BAANTA:
case BODY_AMPHIBEAN:
case BODY_FROG:
case BODY_MIMIC:
case BODY_WYVELIN:
case BODY_FISH:
case BODY_TREE:
case BODY_SLIME:
if (!silent)
sendTo("You have the wrong bodyform for grappling.\n\r");
return FALSE;
default:
break;
}
if (checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (getCombatMode() == ATTACK_BERSERK) {
if (!silent)
sendTo("You are berserking! You can't focus enough to disarm anyone!\n\r ");
return FALSE;
}
if (victim == this) {
if (!silent)
sendTo("Aren't we funny today...\n\r");
return FALSE;
}
if (riding) {
if (!silent)
sendTo("Yeah... right... while mounted.\n\r");
return FALSE;
}
if (victim->isFlying() && (victim->fight() != this)) {
if (!silent)
sendTo("You can only disarm fliers that are fighting you.\n\r");
return FALSE;
}
if (!victim->heldInPrimHand() && !victim->heldInSecHand()) {
if (!silent)
act("$N is not wielding anything.",FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (isHumanoid()) {
if (bothArmsHurt()) {
if (!silent)
act("You need working arms to disarm!", FALSE, this, 0, 0, TO_CHAR);
return FALSE;
}
}
if (victim->attackers > 3) {
if (!silent)
act("There is no room around $N to disarm $M.", FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (attackers > 3) {
if (!silent)
sendTo("There is no room to disarm!\n\r");
return FALSE;
}
#if 0
if (!equipment[getPrimaryHold()]) {
sendTo("Your primary hand must be FREE in order to attempt a disarm!\n\r");
return FALSE;
}
#endif
return TRUE;
}
// uses the psionic skill telekinesis to automatically retrieve a disarmed wep
// victim is the disarmee, ie the one with the telekinesis skill
bool trytelekinesis(TBeing *caster, TBeing *victim, TObj *obj){
if(!victim->doesKnowSkill(SKILL_TELEKINESIS)){
return FALSE;
}
if(!bSuccess(victim, victim->getSkillValue(SKILL_TELEKINESIS),
SKILL_TELEKINESIS)){
act("You try to retrieve your $p using telekinesis, but it is too difficult.",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_NORMAL);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_CHAR, ANSI_NORMAL);
} else {
act("You catch your $p in mid-air with the powers of your mind and return it to your grasp!",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_CHAR, ANSI_CYAN);
return TRUE;
}
// shouldn't get here
return FALSE;
}
static int disarm(TBeing * caster, TBeing * victim, spellNumT skill)
{
int percent;
int level, i = 0;
if (!caster->canDisarm(victim, SILENT_NO))
return FALSE;
const int disarm_move = 20;
if (caster->getMove() < disarm_move) {
caster->sendTo("You are too tired to attempt a disarm maneuver!\n\r");
return FALSE;
}
caster->addToMove(-disarm_move);
level = caster->getSkillLevel(skill);
int bKnown = caster->getSkillValue(skill);
int level2 = victim->getSkillLevel(skill);
if (caster->isNotPowerful(victim, level, skill, SILENT_YES) ||
!victim->isNotPowerful(caster, level2, skill, SILENT_YES)) {
act("You try to disarm $N, but fail miserably.",
TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n does a nifty fighting move, but then falls on $s butt.",
TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at you, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_VICT);
act("$n lunges at $N, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_NOTVICT);
}
caster->setPosition(POSITION_SITTING);
if (dynamic_cast<TMonster *>(victim) && victim->awake() && !victim->fight())
caster->reconcileDamage(victim, 0, skill);;
return TRUE;
}
percent = 0;
percent += caster->getDexReaction() * 5;
percent -= victim->getDexReaction() * 5;
// if my hands are empty, make it easy
if (!caster->heldInPrimHand() &&
// !caster->hasClass(CLASS_MONK) &&
caster->isHumanoid())
percent += 10;
// if i am an equipped monk, make it tough
if (caster->heldInPrimHand() && caster->hasClass(CLASS_MONK))
percent -= 10;
i = caster->specialAttack(victim,skill);
if (i && bKnown >= 0 && i != GUARANTEED_FAILURE &&
bSuccess(caster, bKnown + percent, skill)) {
TObj * obj = NULL;
bool isobjprim=TRUE; // is the disarmed object the primary hand object?
if (!(obj=dynamic_cast<TObj *>(victim->heldInPrimHand()))){
obj = dynamic_cast<TObj *>(victim->heldInSecHand());
isobjprim=FALSE;
}
if (obj) {
act("You attempt to disarm $N.", TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n makes an impressive fighting move.", TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at $N!",
TRUE, caster, 0, victim, TO_NOTVICT);
act("$n lunges at you!",
TRUE, caster, 0, victim, TO_VICT);
}
act("You send $p flying from $N's grasp.", FALSE, caster, obj, victim, TO_CHAR);
act("$p flies from your grasp.", FALSE, caster, obj, victim, TO_VICT, ANSI_RED);
act("$p flies from $N's grasp.", FALSE, caster, obj, victim, TO_NOTVICT);
if(!trytelekinesis(caster, victim, obj)){
if(isobjprim){
victim->unequip(victim->getPrimaryHold());
} else {
victim->unequip(victim->getSecondaryHold());
}
*victim->roomp += *obj;
victim->logItem(obj, CMD_DISARM);
}
} else {
act("You try to disarm $N, but $E doesn't have a weapon.", TRUE, caster, 0, victim, TO_CHAR);
act("$n makes an impressive fighting move, but does little more.", TRUE, caster, 0, 0, TO_ROOM);
}
caster->reconcileDamage(victim, 0, skill);;
victim->addToWait(combatRound(1));
caster->reconcileHurt(victim, 0.01);
} else {
act("You try to disarm $N, but fail miserably, falling down in the process.", TRUE, caster, 0, victim, TO_CHAR, ANSI_YELLOW);
act("$n does a nifty fighting move, but then falls on $s butt.", TRUE, caster, 0, 0, TO_ROOM);
caster->setPosition(POSITION_SITTING);
caster->reconcileDamage(victim, 0, skill);;
}
return TRUE;
}
int TBeing::doDisarm(const char *argument, TThing *v)
{
char v_name[MAX_INPUT_LENGTH];
TBeing * victim = NULL;
int rc;
spellNumT skill = getSkillNum(SKILL_DISARM);
if (checkBusy(NULL)) {
return FALSE;
}
only_argument(argument, v_name);
if (!v) {
if (!(victim = get_char_room_vis(this, v_name))) {
if (!(victim = fight())) {
if (!*argument) {
sendTo("Syntax: disarm <person | item>\n\r");
return FALSE;
} else {
rc = disarmTrap(argument, NULL);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
} else {
// v is either a being or an obj, unknown at this point
victim = dynamic_cast<TBeing *>(v);
if (!victim) {
TObj *to = dynamic_cast<TObj *>(v);
if (to) {
rc = disarmTrap(argument, to);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
if (!doesKnowSkill(skill)) {
sendTo("You know nothing about how to disarm someone.\n\r");
return FALSE;
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
rc = disarm(this, victim, skill);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
if (rc)
addSkillLag(skill, rc);
return TRUE;
}
<commit_msg>fix typo<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
bool TBeing::canDisarm(TBeing *victim, silentTypeT silent)
{
switch (race->getBodyType()) {
case BODY_PIERCER:
case BODY_MOSS:
case BODY_KUOTOA:
case BODY_MANTICORE:
case BODY_GRIFFON:
case BODY_SHEDU:
case BODY_SPHINX:
case BODY_LAMMASU:
case BODY_WYVERN:
case BODY_DRAGONNE:
case BODY_HIPPOGRIFF:
case BODY_CHIMERA:
case BODY_SNAKE:
case BODY_NAGA:
case BODY_ORB:
case BODY_VEGGIE:
case BODY_LION:
case BODY_FELINE:
case BODY_REPTILE:
case BODY_DINOSAUR:
case BODY_FOUR_LEG:
case BODY_PIG:
case BODY_FOUR_HOOF:
case BODY_ELEPHANT:
case BODY_BAANTA:
case BODY_AMPHIBEAN:
case BODY_FROG:
case BODY_MIMIC:
case BODY_WYVELIN:
case BODY_FISH:
case BODY_TREE:
case BODY_SLIME:
if (!silent)
sendTo("You have the wrong bodyform for grappling.\n\r");
return FALSE;
default:
break;
}
if (checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (getCombatMode() == ATTACK_BERSERK) {
if (!silent)
sendTo("You are berserking! You can't focus enough to disarm anyone!\n\r ");
return FALSE;
}
if (victim == this) {
if (!silent)
sendTo("Aren't we funny today...\n\r");
return FALSE;
}
if (riding) {
if (!silent)
sendTo("Yeah... right... while mounted.\n\r");
return FALSE;
}
if (victim->isFlying() && (victim->fight() != this)) {
if (!silent)
sendTo("You can only disarm fliers that are fighting you.\n\r");
return FALSE;
}
if (!victim->heldInPrimHand() && !victim->heldInSecHand()) {
if (!silent)
act("$N is not wielding anything.",FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (isHumanoid()) {
if (bothArmsHurt()) {
if (!silent)
act("You need working arms to disarm!", FALSE, this, 0, 0, TO_CHAR);
return FALSE;
}
}
if (victim->attackers > 3) {
if (!silent)
act("There is no room around $N to disarm $M.", FALSE, this, 0, victim, TO_CHAR);
return FALSE;
}
if (attackers > 3) {
if (!silent)
sendTo("There is no room to disarm!\n\r");
return FALSE;
}
#if 0
if (!equipment[getPrimaryHold()]) {
sendTo("Your primary hand must be FREE in order to attempt a disarm!\n\r");
return FALSE;
}
#endif
return TRUE;
}
// uses the psionic skill telekinesis to automatically retrieve a disarmed wep
// victim is the disarmee, ie the one with the telekinesis skill
bool trytelekinesis(TBeing *caster, TBeing *victim, TObj *obj){
if(!victim->doesKnowSkill(SKILL_TELEKINESIS)){
return FALSE;
}
if(!bSuccess(victim, victim->getSkillValue(SKILL_TELEKINESIS),
SKILL_TELEKINESIS)){
act("You try to retrieve $p using telekinesis, but it is too difficult.",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_NORMAL);
act("$N furrows $s brow for a moment, but nothing happens.",
FALSE, caster, obj, victim, TO_CHAR, ANSI_NORMAL);
} else {
act("You catch $p in mid-air with the powers of your mind and return it to your grasp!",
FALSE, caster, obj, victim, TO_VICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_NOTVICT, ANSI_CYAN);
act("$N's $p stops in mid-air, then flies back to his hand!",
FALSE, caster, obj, victim, TO_CHAR, ANSI_CYAN);
return TRUE;
}
// shouldn't get here
return FALSE;
}
static int disarm(TBeing * caster, TBeing * victim, spellNumT skill)
{
int percent;
int level, i = 0;
if (!caster->canDisarm(victim, SILENT_NO))
return FALSE;
const int disarm_move = 20;
if (caster->getMove() < disarm_move) {
caster->sendTo("You are too tired to attempt a disarm maneuver!\n\r");
return FALSE;
}
caster->addToMove(-disarm_move);
level = caster->getSkillLevel(skill);
int bKnown = caster->getSkillValue(skill);
int level2 = victim->getSkillLevel(skill);
if (caster->isNotPowerful(victim, level, skill, SILENT_YES) ||
!victim->isNotPowerful(caster, level2, skill, SILENT_YES)) {
act("You try to disarm $N, but fail miserably.",
TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n does a nifty fighting move, but then falls on $s butt.",
TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at you, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_VICT);
act("$n lunges at $N, but fails to accomplish anything.",
TRUE, caster, 0, victim, TO_NOTVICT);
}
caster->setPosition(POSITION_SITTING);
if (dynamic_cast<TMonster *>(victim) && victim->awake() && !victim->fight())
caster->reconcileDamage(victim, 0, skill);;
return TRUE;
}
percent = 0;
percent += caster->getDexReaction() * 5;
percent -= victim->getDexReaction() * 5;
// if my hands are empty, make it easy
if (!caster->heldInPrimHand() &&
// !caster->hasClass(CLASS_MONK) &&
caster->isHumanoid())
percent += 10;
// if i am an equipped monk, make it tough
if (caster->heldInPrimHand() && caster->hasClass(CLASS_MONK))
percent -= 10;
i = caster->specialAttack(victim,skill);
if (i && bKnown >= 0 && i != GUARANTEED_FAILURE &&
bSuccess(caster, bKnown + percent, skill)) {
TObj * obj = NULL;
bool isobjprim=TRUE; // is the disarmed object the primary hand object?
if (!(obj=dynamic_cast<TObj *>(victim->heldInPrimHand()))){
obj = dynamic_cast<TObj *>(victim->heldInSecHand());
isobjprim=FALSE;
}
if (obj) {
act("You attempt to disarm $N.", TRUE, caster, 0, victim, TO_CHAR);
if (caster->isHumanoid())
act("$n makes an impressive fighting move.", TRUE, caster, 0, 0, TO_ROOM);
else {
act("$n lunges at $N!",
TRUE, caster, 0, victim, TO_NOTVICT);
act("$n lunges at you!",
TRUE, caster, 0, victim, TO_VICT);
}
act("You send $p flying from $N's grasp.", FALSE, caster, obj, victim, TO_CHAR);
act("$p flies from your grasp.", FALSE, caster, obj, victim, TO_VICT, ANSI_RED);
act("$p flies from $N's grasp.", FALSE, caster, obj, victim, TO_NOTVICT);
if(!trytelekinesis(caster, victim, obj)){
if(isobjprim){
victim->unequip(victim->getPrimaryHold());
} else {
victim->unequip(victim->getSecondaryHold());
}
*victim->roomp += *obj;
victim->logItem(obj, CMD_DISARM);
}
} else {
act("You try to disarm $N, but $E doesn't have a weapon.", TRUE, caster, 0, victim, TO_CHAR);
act("$n makes an impressive fighting move, but does little more.", TRUE, caster, 0, 0, TO_ROOM);
}
caster->reconcileDamage(victim, 0, skill);;
victim->addToWait(combatRound(1));
caster->reconcileHurt(victim, 0.01);
} else {
act("You try to disarm $N, but fail miserably, falling down in the process.", TRUE, caster, 0, victim, TO_CHAR, ANSI_YELLOW);
act("$n does a nifty fighting move, but then falls on $s butt.", TRUE, caster, 0, 0, TO_ROOM);
caster->setPosition(POSITION_SITTING);
caster->reconcileDamage(victim, 0, skill);;
}
return TRUE;
}
int TBeing::doDisarm(const char *argument, TThing *v)
{
char v_name[MAX_INPUT_LENGTH];
TBeing * victim = NULL;
int rc;
spellNumT skill = getSkillNum(SKILL_DISARM);
if (checkBusy(NULL)) {
return FALSE;
}
only_argument(argument, v_name);
if (!v) {
if (!(victim = get_char_room_vis(this, v_name))) {
if (!(victim = fight())) {
if (!*argument) {
sendTo("Syntax: disarm <person | item>\n\r");
return FALSE;
} else {
rc = disarmTrap(argument, NULL);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
} else {
// v is either a being or an obj, unknown at this point
victim = dynamic_cast<TBeing *>(v);
if (!victim) {
TObj *to = dynamic_cast<TObj *>(v);
if (to) {
rc = disarmTrap(argument, to);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
return FALSE;
}
}
}
if (!doesKnowSkill(skill)) {
sendTo("You know nothing about how to disarm someone.\n\r");
return FALSE;
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
rc = disarm(this, victim, skill);
if (IS_SET_DELETE(rc, DELETE_THIS))
return DELETE_THIS;
if (rc)
addSkillLag(skill, rc);
return TRUE;
}
<|endoftext|> |
<commit_before>/* See LICENSE file for copyright and license details. */
#include <cstdlib>
#include <cassert>
#include "core/v2i.h"
#include "core/misc.h"
#include "core/dir.h"
#include "core/core.h"
#include "core/unit_type.h"
typedef struct {
V2i *v;
int tail;
int head;
int size;
} PathQueue;
static PathQueue q;
void init_path_queue (PathQueue *q, int size) {
assert(size > 0);
assert(q);
q->v = new V2i[size];
q->tail = 0;
q->head = 0;
q->size = size;
}
void init_pathfinding_module() {
init_path_queue(&q, 10000);
}
static void push(
const V2i& m, Dir parent, int newcost, Dir dir)
{
Tile& t = tile(m);
t.cost = newcost;
t.parent = parent;
t.dir = dir;
q.v[q.tail] = m;
q.tail++;
if (q.tail == q.size) {
q.tail = 0;
}
}
static bool is_queue_empty(const PathQueue& q) {
return q.head == q.tail;
}
static V2i pop() {
V2i m;
assert(q.head != q.tail);
m = q.v[q.head];
q.head++;
if (q.head == q.size)
q.head = 0;
return m;
}
/* If this is first(start) tile - no parent tile. */
static Dir get_parent_dir (const Unit& u, const V2i& m) {
Tile& t = tile(m);
if (t.cost == 0) {
return u.dir;
} else {
return opposite_dir(t.parent);
}
}
static int get_tile_cost(
const Unit& u, const V2i& t, const V2i& nb)
{
int cost = 1;
int dx = abs(t.x - nb.x);
int dy = abs(t.y - nb.y);
assert(dx <= 1);
assert(dy <= 1);
if (dx != 0)
cost++;
if (dy != 0)
cost++;
Dir d = m2dir(t, nb);
Dir d2 = get_parent_dir(u, t);
int d_diff = dir_diff(d, d2);
switch (d_diff) {
case 0: break;
case 1: cost += 3; break;
case 2: cost += 20; break;
case 3: cost += 90; break;
case 4: cost += 90; break;
default: exit(1); break;
}
return cost;
}
static bool can_move_there(const V2i& p1, const V2i& p2) {
assert(inboard(p1));
assert(inboard(p2));
if (!dir_is_diagonal(m2dir(p1, p2))) {
return true;
}
V2i neib_left = get_dir_neib(p1, p2, -1);
V2i neib_right = get_dir_neib(p1, p2, +1);
bool is_left_blocked = inboard(neib_left) && tile(neib_left).obstacle;
bool is_right_blocked = inboard(neib_right) && tile(neib_right).obstacle;
#if 0
return !is_left_blocked && !is_right_blocked;
#else
return !is_left_blocked || !is_right_blocked;
#endif
}
/* TODO rename */
/* p1 - orig_pos, p2 - neib pos */
static void process_neibor(
const Unit& u, const V2i& p1, const V2i& p2)
{
Tile& t1 = tile(p1);
Tile& t2 = tile(p2);
if (unit_at(p2) || t2.obstacle || !can_move_there(p1, p2)) {
return;
}
int newcost = t1.cost + get_tile_cost(u, p1, p2);
int ap = get_unit_type(u.type_id).action_points;
if (t2.cost > newcost && newcost <= ap) {
push(p2, m2dir(p2, p1), newcost, m2dir(p1, p2));
}
}
void clean_map() {
V2i p;
FOR_EACH_TILE(&p) {
Tile& t = tile(p);
t.cost = 30000;
t.parent = Dir::D_NONE;
}
}
static void try_to_push_neibors(const Unit& u, const V2i& m) {
assert(inboard(m));
for (int i = static_cast<int>(Dir::D_N);
i <= static_cast<int>(Dir::D_NW);
i++)
{
V2i neib_m = neib(m, static_cast<Dir>(i));
if (inboard(neib_m)) {
process_neibor(u, m, neib_m);
}
}
}
void fill_map(const Unit& u) {
assert(is_queue_empty(q));
clean_map();
// Push start position
push(u.pos, Dir::D_NONE, 0, u.dir);
while (!is_queue_empty(q)) {
V2i p = pop();
try_to_push_neibors(u, p);
}
}
void get_path(V2i *path, int length, V2i pos) {
Dir dir;
int i = length - 1;
assert(path);
assert(inboard(pos));
while (tile(pos).cost != 0) {
path[i] = pos;
dir = tile(pos).parent;
pos = neib(pos, dir);
i--;
}
/* Add start position. */
path[i] = pos;
}
int get_path_length(const V2i& pos) {
V2i p = pos;
int length = 1;
assert(inboard(p));
while (tile(p).cost != 0) {
length++;
Dir dir = tile(p).parent;
p = neib(p, dir);
}
return length;
}
<commit_msg>Made PathQueue more C++'ish<commit_after>/* See LICENSE file for copyright and license details. */
#include <cstdlib>
#include <cassert>
#include <vector>
#include "core/v2i.h"
#include "core/misc.h"
#include "core/dir.h"
#include "core/core.h"
#include "core/unit_type.h"
class PathQueue {
private:
unsigned int mTailNodeIndex;
unsigned int mHeadNodeIndex;
std::vector<V2i> mNodes;
public:
PathQueue(int size)
: mTailNodeIndex(0),
mHeadNodeIndex(0),
mNodes(size)
{
assert(size > 0);
}
~PathQueue() {
}
bool is_empty() const {
return (mHeadNodeIndex == mTailNodeIndex);
}
void push(const V2i& m, Dir parent, int newcost, Dir dir) {
Tile& t = tile(m);
t.cost = newcost;
t.parent = parent;
t.dir = dir;
mNodes[mTailNodeIndex] = m;
mTailNodeIndex++;
if (mTailNodeIndex == mNodes.size()) {
mTailNodeIndex = 0;
}
}
V2i pop() {
assert(mHeadNodeIndex != mTailNodeIndex);
V2i m = mNodes[mHeadNodeIndex];
mHeadNodeIndex++;
if (mHeadNodeIndex == mNodes.size()) {
mHeadNodeIndex = 0;
}
return m;
}
};
static PathQueue q(1000);
void init_pathfinding_module() {
}
/* If this is first(start) tile - no parent tile. */
static Dir get_parent_dir (const Unit& u, const V2i& m) {
Tile& t = tile(m);
if (t.cost == 0) {
return u.dir;
} else {
return opposite_dir(t.parent);
}
}
static int get_tile_cost(const Unit& u, const V2i& t, const V2i& nb) {
int cost = 1;
int dx = abs(t.x - nb.x);
int dy = abs(t.y - nb.y);
assert(dx <= 1);
assert(dy <= 1);
if (dx != 0) {
cost++;
}
if (dy != 0) {
cost++;
}
Dir d = m2dir(t, nb);
Dir d2 = get_parent_dir(u, t);
int d_diff = dir_diff(d, d2);
switch (d_diff) {
case 0: break;
case 1: cost += 3; break;
case 2: cost += 20; break;
case 3: cost += 90; break;
case 4: cost += 90; break;
default: exit(1); break;
}
return cost;
}
static bool can_move_there(const V2i& p1, const V2i& p2) {
assert(inboard(p1));
assert(inboard(p2));
if (!dir_is_diagonal(m2dir(p1, p2))) {
return true;
}
V2i neib_left = get_dir_neib(p1, p2, -1);
V2i neib_right = get_dir_neib(p1, p2, +1);
bool is_left_blocked = inboard(neib_left) && tile(neib_left).obstacle;
bool is_right_blocked = inboard(neib_right) && tile(neib_right).obstacle;
#if 0
return !is_left_blocked && !is_right_blocked;
#else
return !is_left_blocked || !is_right_blocked;
#endif
}
/* TODO rename */
/* p1 - orig_pos, p2 - neib pos */
static void process_neibor(const Unit& u, const V2i& p1, const V2i& p2) {
Tile& t1 = tile(p1);
Tile& t2 = tile(p2);
if (unit_at(p2) || t2.obstacle || !can_move_there(p1, p2)) {
return;
}
int newcost = t1.cost + get_tile_cost(u, p1, p2);
int ap = get_unit_type(u.type_id).action_points;
if (t2.cost > newcost && newcost <= ap) {
q.push(p2, m2dir(p2, p1), newcost, m2dir(p1, p2));
}
}
void clean_map() {
V2i p;
FOR_EACH_TILE(&p) {
Tile& t = tile(p);
t.cost = 30000;
t.parent = Dir::D_NONE;
}
}
static void try_to_push_neibors(const Unit& u, const V2i& m) {
assert(inboard(m));
for (int i = static_cast<int>(Dir::D_N);
i <= static_cast<int>(Dir::D_NW);
i++)
{
V2i neib_m = neib(m, static_cast<Dir>(i));
if (inboard(neib_m)) {
process_neibor(u, m, neib_m);
}
}
}
void fill_map(const Unit& u) {
assert(q.is_empty());
clean_map();
// Push start position
q.push(u.pos, Dir::D_NONE, 0, u.dir);
while (!q.is_empty()) {
V2i p = q.pop();
try_to_push_neibors(u, p);
}
}
void get_path(V2i *path, int length, V2i pos) {
Dir dir;
int i = length - 1;
assert(path);
assert(inboard(pos));
while (tile(pos).cost != 0) {
path[i] = pos;
dir = tile(pos).parent;
pos = neib(pos, dir);
i--;
}
/* Add start position. */
path[i] = pos;
}
int get_path_length(const V2i& pos) {
V2i p = pos;
int length = 1;
assert(inboard(p));
while (tile(p).cost != 0) {
length++;
Dir dir = tile(p).parent;
p = neib(p, dir);
}
return length;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Time_DateUtils_inl_
#define _Stroika_Foundation_Time_DateUtils_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Execution/Exceptions.h"
namespace Stroika {
namespace Foundation {
namespace Time {
// class Date
inline Date::JulianRepType Date::GetJulianRep () const
{
return (fJulianDateRep);
}
inline bool Date::empty () const
{
return fJulianDateRep == kEmptyJulianRep;
}
inline int DayDifference (const Date& lhs, const Date& rhs)
{
Require (not lhs.empty ());
Require (not rhs.empty ()); // since unclear what diff would mean
return lhs.GetJulianRep () - rhs.GetJulianRep ();
}
inline bool operator<= (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () <= rhs.GetJulianRep ();
}
inline bool operator< (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () < rhs.GetJulianRep ();
}
inline bool operator> (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () >rhs.GetJulianRep ();
}
inline bool operator== (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () == rhs.GetJulianRep ();
}
inline bool operator!= (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () != rhs.GetJulianRep ();
}
// class TimeOfDay
inline bool TimeOfDay::empty () const
{
return fTime == static_cast<unsigned int> (-1);
}
inline unsigned int TimeOfDay::GetAsSecondsCount () const
{
if (empty ()) {
return 0;
}
return fTime;
}
inline bool operator< (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () < rhs.GetAsSecondsCount ();
}
inline bool operator> (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () > rhs.GetAsSecondsCount ();
}
inline bool operator== (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () == rhs.GetAsSecondsCount ();
}
inline bool operator!= (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () != rhs.GetAsSecondsCount ();
}
// class TimeOfDay
inline DateTime::DateTime (const Date& date, const TimeOfDay& timeOfDay):
fDate (date),
fTimeOfDay (timeOfDay)
{
}
inline Date DateTime::GetDate () const
{
return fDate;
}
inline TimeOfDay DateTime::GetTimeOfDay () const
{
return fTimeOfDay;
}
inline DateTime::operator Date () const
{
return fDate;
}
}
template <>
inline void _NoReturn_ Execution::DoThrow (const Time::Date::FormatException& e2Throw)
{
DbgTrace (L"Throwing Date::FormatException");
throw e2Throw;
}
template <>
inline void _NoReturn_ Execution::DoThrow (const Time::TimeOfDay::FormatException& e2Throw)
{
DbgTrace (L"Throwing TimeOfDay::FormatException");
throw e2Throw;
}
}
}
#endif /*_Stroika_Foundation_Time_DateUtils_inl_*/
<commit_msg>restructure Execution::DoThrow () overrides in Time/DateUtils.inl<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Time_DateUtils_inl_
#define _Stroika_Foundation_Time_DateUtils_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include "../Execution/Exceptions.h"
namespace Stroika {
namespace Foundation {
namespace Time {
// class Date
inline Date::JulianRepType Date::GetJulianRep () const
{
return (fJulianDateRep);
}
inline bool Date::empty () const
{
return fJulianDateRep == kEmptyJulianRep;
}
inline int DayDifference (const Date& lhs, const Date& rhs)
{
Require (not lhs.empty ());
Require (not rhs.empty ()); // since unclear what diff would mean
return lhs.GetJulianRep () - rhs.GetJulianRep ();
}
inline bool operator<= (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () <= rhs.GetJulianRep ();
}
inline bool operator< (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () < rhs.GetJulianRep ();
}
inline bool operator> (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () >rhs.GetJulianRep ();
}
inline bool operator== (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () == rhs.GetJulianRep ();
}
inline bool operator!= (const Date& lhs, const Date& rhs)
{
return lhs.GetJulianRep () != rhs.GetJulianRep ();
}
// class TimeOfDay
inline bool TimeOfDay::empty () const
{
return fTime == static_cast<unsigned int> (-1);
}
inline unsigned int TimeOfDay::GetAsSecondsCount () const
{
if (empty ()) {
return 0;
}
return fTime;
}
inline bool operator< (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () < rhs.GetAsSecondsCount ();
}
inline bool operator> (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () > rhs.GetAsSecondsCount ();
}
inline bool operator== (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () == rhs.GetAsSecondsCount ();
}
inline bool operator!= (const TimeOfDay& lhs, const TimeOfDay& rhs)
{
return lhs.GetAsSecondsCount () != rhs.GetAsSecondsCount ();
}
// class TimeOfDay
inline DateTime::DateTime (const Date& date, const TimeOfDay& timeOfDay):
fDate (date),
fTimeOfDay (timeOfDay)
{
}
inline Date DateTime::GetDate () const
{
return fDate;
}
inline TimeOfDay DateTime::GetTimeOfDay () const
{
return fTimeOfDay;
}
inline DateTime::operator Date () const
{
return fDate;
}
}
namespace Execution {
template <>
inline void _NoReturn_ DoThrow (const Time::Date::FormatException& e2Throw)
{
DbgTrace (L"Throwing Date::FormatException");
throw e2Throw;
}
template <>
inline void _NoReturn_ DoThrow (const Time::TimeOfDay::FormatException& e2Throw)
{
DbgTrace (L"Throwing TimeOfDay::FormatException");
throw e2Throw;
}
}
}
}
#endif /*_Stroika_Foundation_Time_DateUtils_inl_*/
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.