text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "Controller.hh"
#include <time.h>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include "Exception.hh"
namespace aegir {
/*
* Controller
*/
Controller *Controller::c_instance(0);
Controller::Controller(): PINTracker(), c_mq_io(ZMQ::SocketType::SUB), c_ps(ProcessState::getInstance()),
c_mq_iocmd(ZMQ::SocketType::PUB), c_stoprecirc(false) {
// subscribe to our publisher for IO events
try {
c_mq_io.connect("inproc://iopub").subscribe("");
c_mq_iocmd.connect("inproc://iocmd");
}
catch (std::exception &e) {
printf("Sub failed: %s\n", e.what());
}
catch (...) {
printf("Sub failed: unknown exception\n");
}
c_cfg = Config::getInstance();
// reconfigure state variables
reconfigure();
c_stagehandlers[ProcessState::States::Empty] = std::bind(&Controller::stageEmpty,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Loaded] = std::bind(&Controller::stageLoaded
, std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::PreWait] = std::bind(&Controller::stagePreWait,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::PreHeat] = std::bind(&Controller::stagePreHeat,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::NeedMalt] = std::bind(&Controller::stageNeedMalt,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Mashing] = std::bind(&Controller::stageMashing,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Sparging] = std::bind(&Controller::stageSparging,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::PreBoil] = std::bind(&Controller::stagePreBoil,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Hopping] = std::bind(&Controller::stageHopping,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Cooling] = std::bind(&Controller::stageCooling,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Finished] = std::bind(&Controller::stageFinished, std::placeholders::_1,
std::placeholders::_2);
// finally register to the threadmanager
auto thrmgr = ThreadManager::getInstance();
thrmgr->addThread("Controller", *this);
}
Controller::~Controller() {
}
Controller *Controller::getInstance() {
if ( !c_instance) c_instance = new Controller();
return c_instance;
}
void Controller::run() {
printf("Controller started\n");
// The main event loop
std::shared_ptr<Message> msg;
std::chrono::microseconds ival(20000);
while ( c_run ) {
// PINTracker's cycle
startCycle();
// read the GPIO pin channel first
try {
while ( (msg = c_mq_io.recv()) != nullptr ) {
if ( msg->type() == MessageType::PINSTATE ) {
auto psmsg = std::static_pointer_cast<PinStateMessage>(msg);
#ifdef AEGIR_DEBUG
printf("Controller: received %s:%hhu\n", psmsg->getName().c_str(), psmsg->getState());
#endif
try {
setPIN(psmsg->getName(), psmsg->getState());
}
catch (Exception &e) {
printf("No such pin: '%s' %lu\n", psmsg->getName().c_str(), psmsg->getName().length());
continue;
}
} else if ( msg->type() == MessageType::THERMOREADING ) {
auto trmsg = std::static_pointer_cast<ThermoReadingMessage>(msg);
#ifdef AEGIR_DEBUG
printf("Controller: got temp reading: %s/%f/%u\n",
trmsg->getName().c_str(),
trmsg->getTemp(),
trmsg->getTimestamp());
#endif
// add it to the process state
c_ps.addThermoReading(trmsg->getName(), trmsg->getTimestamp(), trmsg->getTemp());
} else {
printf("Got unhandled message type: %i\n", (int)msg->type());
continue;
}
}
} // End of pin and sensor readings
catch (Exception &e) {
printf("Exception: %s\n", e.what());
}
// handle the changes
controlProcess(*this);
// Send back the commands to IOHandler
// PINTracker::endCycle() does this
endCycle();
// sleep a bit
std::this_thread::sleep_for(ival);
}
printf("Controller stopped\n");
}
void Controller::reconfigure() {
PINTracker::reconfigure();
c_hecycletime = c_cfg->getHECycleTime();
}
void Controller::controlProcess(PINTracker &_pt) {
ProcessState::Guard guard_ps(c_ps);
ProcessState::States state = c_ps.getState();
// The pump&heat control button
if ( _pt.hasChanges() ) {
std::shared_ptr<PINTracker::PIN> swon(_pt.getPIN("swon"));
std::shared_ptr<PINTracker::PIN> swoff(_pt.getPIN("swoff"));
// whether we have at least one of the controls
if ( swon->isChanged() || swoff->isChanged() ) {
if ( swon->getNewValue() != PINState::Off
&& swoff->getNewValue() == PINState::Off ) {
setPIN("swled", PINState::On);
c_stoprecirc = true;
} else if ( swon->getNewValue() == PINState::Off &&
swoff->getNewValue() != PINState::Off ) {
setPIN("swled", PINState::Off);
c_stoprecirc = false;
}
}
} // pump&heat switch
// state function
auto it = c_stagehandlers.find(state);
if ( it != c_stagehandlers.end() ) {
it->second(this, _pt);
} else {
printf("No function found for state %hhu\n", state);
}
if ( c_stoprecirc ) {
setPIN("rimspump", PINState::Off);
setPIN("rimsheat", PINState::Off);
} // stop recirc
} // controlProcess
void Controller::stageEmpty(PINTracker &_pt) {
c_lastcontrol = 0;
}
void Controller::stageLoaded(PINTracker &_pt) {
c_prog = c_ps.getProgram();
// Loaded, so we should verify the timestamps
uint32_t startat = c_ps.getStartat();
c_preheat_phase = 0;
c_hecycletime = c_cfg->getHECycleTime();
// if we start immediately then jump to PreHeat
if ( startat == 0 ) {
c_ps.setState(ProcessState::States::PreHeat);
c_lastcontrol = 0;
} else {
c_ps.setState(ProcessState::States::PreWait);
c_lastcontrol = 0;
}
return;
}
void Controller::stagePreWait(PINTracker &_pt) {
float mttemp = c_ps.getSensorTemp("MashTun");
if ( mttemp == 0 ) return;
// let's see how much time do we have till we have to start pre-heating
uint32_t now = time(0);
// calculate how much time
float tempdiff = c_prog->getStartTemp() - mttemp;
// Pre-Heat time
// the time we have till pre-heating has to actually start
uint32_t phtime = 0;
if ( tempdiff > 0 )
phtime = calcHeatTime(c_ps.getVolume(), tempdiff, 0.001*c_cfg->getHEPower());
printf("Controller::controllProcess() td:%.2f PreHeatTime:%u\n", tempdiff, phtime);
uint32_t startat = c_ps.getStartat();
if ( (now + phtime*1.15) > startat ) {
c_ps.setState(ProcessState::States::PreHeat);
c_lastcontrol = 0;
}
}
void Controller::stagePreHeat(PINTracker &_pt) {
float mttemp = c_ps.getSensorTemp("MashTun");
float rimstemp = c_ps.getSensorTemp("RIMS");
float targettemp = c_prog->getStartTemp();
float tempdiff = targettemp - mttemp;
#if 0
int newphase = 0;
if ( mttemp == 0 || rimstemp == 0 ) {
newphase = 0;
} else if ( tempdiff < 0) {
newphase = 1;
} else if ( tempdiff < 0.2) {
newphase = 2;
} else if ( tempdiff < 1 ) {
newphase = 3;
} else {
newphase = 4;
}
printf("Controller/PreHeat: MT:%.2f RIMS:%.2f T:%.2f D:%.2f NP:%i\n",
mttemp, rimstemp, targettemp, tempdiff, newphase);
if ( c_preheat_phase != newphase ) {
c_preheat_phase = newphase;
if ( newphase == 0 ) {
setPIN("rimspump", PINState::Off);
setPIN("rimsheat", PINState::Off);
} else if ( newphase == 4 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::On);
} else if ( newphase == 3 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.7);
} else if ( newphase == 2 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.15);
} else if ( newphase == 1 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::Off);
c_ps.setState(ProcessState::States::NeedMalt);
c_lastcontrol = 0;
}
}
#endif
tempControl(targettemp, 6);
if ( tempdiff < c_cfg->getTempAccuracy() ) {
c_ps.setState(ProcessState::States::NeedMalt);
c_lastcontrol = 0;
}
}
void Controller::stageNeedMalt(PINTracker &_pt) {
setPIN("rimsheat", PINState::Off);
std::shared_ptr<PINTracker::PIN> buzzer(_pt.getPIN("buzzer"));
// we keep on beeping
if ( buzzer->getValue() != PINState::Pulsate ) {
setPIN("buzzer", PINState::Pulsate, 2.1f, 0.4f);
}
// When the malts are added, temperature decreases
// We have to heat it back up to the designated temperature
float targettemp = c_prog->getStartTemp();
tempControl(targettemp, c_cfg->getHeatOverhad());
}
void Controller::stageMashing(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageSparging(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stagePreBoil(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageHopping(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageCooling(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageFinished(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::handleOutPIN(PINTracker::PIN &_pin) {
c_mq_iocmd.send(PinStateMessage(_pin.getName(),
_pin.getNewValue(),
_pin.getNewCycletime(),
_pin.getNewOnratio()));
}
void Controller::tempControl(float _target, float _maxoverheat) {
float mttemp = c_ps.getSensorTemp("MashTun");
float rimstemp = c_ps.getSensorTemp("RIMS");
float tgtdiff = _target - mttemp;
float rimsdiff = rimstemp - _target;
time_t now = time(0);
if ( getPIN("rimspump")->getOldValue() != PINState::On )
setPIN("rimspump", PINState::On);
// only control every 3 seconds
if ( now - c_lastcontrol < std::ceil(c_hecycletime) ) return;
if ( tgtdiff < c_cfg->getTempAccuracy() ) {
return;
}
c_lastcontrol = now;
// coefficient based on the target temperature different
float coeff_tgt=0;
// coefficient based on the rims-mashtun tempdiff
float coeff_rt=1;
float halfpi = std::atan(INFINITY);
if ( tgtdiff > 0 ) coeff_tgt = std::atan(tgtdiff)/halfpi;
if ( rimsdiff > 0 ) coeff_rt = std::atan(_maxoverheat-rimsdiff)/halfpi;
if ( coeff_rt < 0 ) coeff_rt = 0;
coeff_rt = std::pow(coeff_rt, 1.0/4);
coeff_tgt = std::pow(coeff_tgt, 1.3);
float heratio = coeff_tgt * coeff_rt;
#ifdef AEGIR_DEBUG
printf("Controller::tempControl(): MT:%.2f RIMS:%.2f TGT:%.2f d_tgt:%.2f d_rims:%.2f c_tgt:%.2f c_rt:%.2f HEr:%.2f\n",
mttemp, rimstemp, _target, tgtdiff, rimsdiff, coeff_tgt, coeff_rt, heratio);
#endif
auto pin_he = getPIN("rimsheat");
#ifdef AEGIR_DEBUG
printf("Controller::tempControl(): rimsheat: ST:%hhu CT:%.2f OR:%.2f\n",
pin_he->getValue(), pin_he->getOldCycletime(), pin_he->getOldOnratio());
#endif
if ( std::abs(pin_he->getOldOnratio()-heratio) > 0.03 )
setPIN("rimsheat", PINState::Pulsate, c_hecycletime, heratio);
}
uint32_t Controller::calcHeatTime(uint32_t _vol, uint32_t _tempdiff, float _pkw) const {
return (4.2 * _vol * _tempdiff)/_pkw;
}
}
<commit_msg>[brewd] Controller::tempControl fixes<commit_after>#include "Controller.hh"
#include <time.h>
#include <cmath>
#include <map>
#include <set>
#include <string>
#include "Exception.hh"
namespace aegir {
/*
* Controller
*/
Controller *Controller::c_instance(0);
Controller::Controller(): PINTracker(), c_mq_io(ZMQ::SocketType::SUB), c_ps(ProcessState::getInstance()),
c_mq_iocmd(ZMQ::SocketType::PUB), c_stoprecirc(false) {
// subscribe to our publisher for IO events
try {
c_mq_io.connect("inproc://iopub").subscribe("");
c_mq_iocmd.connect("inproc://iocmd");
}
catch (std::exception &e) {
printf("Sub failed: %s\n", e.what());
}
catch (...) {
printf("Sub failed: unknown exception\n");
}
c_cfg = Config::getInstance();
// reconfigure state variables
reconfigure();
c_stagehandlers[ProcessState::States::Empty] = std::bind(&Controller::stageEmpty,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Loaded] = std::bind(&Controller::stageLoaded
, std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::PreWait] = std::bind(&Controller::stagePreWait,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::PreHeat] = std::bind(&Controller::stagePreHeat,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::NeedMalt] = std::bind(&Controller::stageNeedMalt,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Mashing] = std::bind(&Controller::stageMashing,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Sparging] = std::bind(&Controller::stageSparging,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::PreBoil] = std::bind(&Controller::stagePreBoil,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Hopping] = std::bind(&Controller::stageHopping,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Cooling] = std::bind(&Controller::stageCooling,
std::placeholders::_1, std::placeholders::_2);
c_stagehandlers[ProcessState::States::Finished] = std::bind(&Controller::stageFinished, std::placeholders::_1,
std::placeholders::_2);
// finally register to the threadmanager
auto thrmgr = ThreadManager::getInstance();
thrmgr->addThread("Controller", *this);
}
Controller::~Controller() {
}
Controller *Controller::getInstance() {
if ( !c_instance) c_instance = new Controller();
return c_instance;
}
void Controller::run() {
printf("Controller started\n");
// The main event loop
std::shared_ptr<Message> msg;
std::chrono::microseconds ival(20000);
while ( c_run ) {
// PINTracker's cycle
startCycle();
// read the GPIO pin channel first
try {
while ( (msg = c_mq_io.recv()) != nullptr ) {
if ( msg->type() == MessageType::PINSTATE ) {
auto psmsg = std::static_pointer_cast<PinStateMessage>(msg);
#ifdef AEGIR_DEBUG
printf("Controller: received %s:%hhu\n", psmsg->getName().c_str(), psmsg->getState());
#endif
try {
setPIN(psmsg->getName(), psmsg->getState());
}
catch (Exception &e) {
printf("No such pin: '%s' %lu\n", psmsg->getName().c_str(), psmsg->getName().length());
continue;
}
} else if ( msg->type() == MessageType::THERMOREADING ) {
auto trmsg = std::static_pointer_cast<ThermoReadingMessage>(msg);
#ifdef AEGIR_DEBUG
printf("Controller: got temp reading: %s/%f/%u\n",
trmsg->getName().c_str(),
trmsg->getTemp(),
trmsg->getTimestamp());
#endif
// add it to the process state
c_ps.addThermoReading(trmsg->getName(), trmsg->getTimestamp(), trmsg->getTemp());
} else {
printf("Got unhandled message type: %i\n", (int)msg->type());
continue;
}
}
} // End of pin and sensor readings
catch (Exception &e) {
printf("Exception: %s\n", e.what());
}
// handle the changes
controlProcess(*this);
// Send back the commands to IOHandler
// PINTracker::endCycle() does this
endCycle();
// sleep a bit
std::this_thread::sleep_for(ival);
}
printf("Controller stopped\n");
}
void Controller::reconfigure() {
PINTracker::reconfigure();
c_hecycletime = c_cfg->getHECycleTime();
}
void Controller::controlProcess(PINTracker &_pt) {
ProcessState::Guard guard_ps(c_ps);
ProcessState::States state = c_ps.getState();
// The pump&heat control button
if ( _pt.hasChanges() ) {
std::shared_ptr<PINTracker::PIN> swon(_pt.getPIN("swon"));
std::shared_ptr<PINTracker::PIN> swoff(_pt.getPIN("swoff"));
// whether we have at least one of the controls
if ( swon->isChanged() || swoff->isChanged() ) {
if ( swon->getNewValue() != PINState::Off
&& swoff->getNewValue() == PINState::Off ) {
setPIN("swled", PINState::On);
c_stoprecirc = true;
} else if ( swon->getNewValue() == PINState::Off &&
swoff->getNewValue() != PINState::Off ) {
setPIN("swled", PINState::Off);
c_stoprecirc = false;
}
}
} // pump&heat switch
// state function
auto it = c_stagehandlers.find(state);
if ( it != c_stagehandlers.end() ) {
it->second(this, _pt);
} else {
printf("No function found for state %hhu\n", state);
}
if ( c_stoprecirc ) {
setPIN("rimspump", PINState::Off);
setPIN("rimsheat", PINState::Off);
} // stop recirc
} // controlProcess
void Controller::stageEmpty(PINTracker &_pt) {
c_lastcontrol = 0;
}
void Controller::stageLoaded(PINTracker &_pt) {
c_prog = c_ps.getProgram();
// Loaded, so we should verify the timestamps
uint32_t startat = c_ps.getStartat();
c_preheat_phase = 0;
c_hecycletime = c_cfg->getHECycleTime();
// if we start immediately then jump to PreHeat
if ( startat == 0 ) {
c_ps.setState(ProcessState::States::PreHeat);
c_lastcontrol = 0;
} else {
c_ps.setState(ProcessState::States::PreWait);
c_lastcontrol = 0;
}
return;
}
void Controller::stagePreWait(PINTracker &_pt) {
float mttemp = c_ps.getSensorTemp("MashTun");
if ( mttemp == 0 ) return;
// let's see how much time do we have till we have to start pre-heating
uint32_t now = time(0);
// calculate how much time
float tempdiff = c_prog->getStartTemp() - mttemp;
// Pre-Heat time
// the time we have till pre-heating has to actually start
uint32_t phtime = 0;
if ( tempdiff > 0 )
phtime = calcHeatTime(c_ps.getVolume(), tempdiff, 0.001*c_cfg->getHEPower());
printf("Controller::controllProcess() td:%.2f PreHeatTime:%u\n", tempdiff, phtime);
uint32_t startat = c_ps.getStartat();
if ( (now + phtime*1.15) > startat ) {
c_ps.setState(ProcessState::States::PreHeat);
c_lastcontrol = 0;
}
}
void Controller::stagePreHeat(PINTracker &_pt) {
float mttemp = c_ps.getSensorTemp("MashTun");
float rimstemp = c_ps.getSensorTemp("RIMS");
float targettemp = c_prog->getStartTemp();
float tempdiff = targettemp - mttemp;
#if 0
int newphase = 0;
if ( mttemp == 0 || rimstemp == 0 ) {
newphase = 0;
} else if ( tempdiff < 0) {
newphase = 1;
} else if ( tempdiff < 0.2) {
newphase = 2;
} else if ( tempdiff < 1 ) {
newphase = 3;
} else {
newphase = 4;
}
printf("Controller/PreHeat: MT:%.2f RIMS:%.2f T:%.2f D:%.2f NP:%i\n",
mttemp, rimstemp, targettemp, tempdiff, newphase);
if ( c_preheat_phase != newphase ) {
c_preheat_phase = newphase;
if ( newphase == 0 ) {
setPIN("rimspump", PINState::Off);
setPIN("rimsheat", PINState::Off);
} else if ( newphase == 4 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::On);
} else if ( newphase == 3 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.7);
} else if ( newphase == 2 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::Pulsate, c_hecycletime, 0.15);
} else if ( newphase == 1 ) {
setPIN("rimspump", PINState::On);
setPIN("rimsheat", PINState::Off);
c_ps.setState(ProcessState::States::NeedMalt);
c_lastcontrol = 0;
}
}
#endif
tempControl(targettemp, 6);
if ( tempdiff < 0.2 ) {
c_ps.setState(ProcessState::States::NeedMalt);
c_lastcontrol = 0;
}
}
void Controller::stageNeedMalt(PINTracker &_pt) {
std::shared_ptr<PINTracker::PIN> buzzer(_pt.getPIN("buzzer"));
// we keep on beeping
if ( buzzer->getValue() != PINState::Pulsate ) {
setPIN("buzzer", PINState::Pulsate, 2.1f, 0.4f);
}
// When the malts are added, temperature decreases
// We have to heat it back up to the designated temperature
float targettemp = c_prog->getStartTemp();
tempControl(targettemp, c_cfg->getHeatOverhad());
}
void Controller::stageMashing(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageSparging(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stagePreBoil(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageHopping(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageCooling(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::stageFinished(PINTracker &_pt) {
printf("%s:%i:%s\n", __FILE__, __LINE__, __FUNCTION__);
}
void Controller::handleOutPIN(PINTracker::PIN &_pin) {
c_mq_iocmd.send(PinStateMessage(_pin.getName(),
_pin.getNewValue(),
_pin.getNewCycletime(),
_pin.getNewOnratio()));
}
void Controller::tempControl(float _target, float _maxoverheat) {
float mttemp = c_ps.getSensorTemp("MashTun");
float rimstemp = c_ps.getSensorTemp("RIMS");
if ( mttemp == 0.0f || rimstemp == 0.0f ) return;
float tgtdiff = _target - mttemp;
float rimsdiff = rimstemp - _target;
time_t now = time(0);
if ( getPIN("rimspump")->getOldValue() != PINState::On )
setPIN("rimspump", PINState::On);
// only control every 3 seconds
if ( now - c_lastcontrol < std::ceil(c_hecycletime) ) return;
if ( tgtdiff < c_cfg->getTempAccuracy() ) {
return;
}
c_lastcontrol = now;
// coefficient based on the target temperature different
float coeff_tgt=0;
// coefficient based on the rims-mashtun tempdiff
float coeff_rt=1;
float halfpi = std::atan(INFINITY);
if ( tgtdiff > 0 ) coeff_tgt = std::atan(tgtdiff)/halfpi;
if ( rimsdiff > 0 ) coeff_rt = std::atan(_maxoverheat-rimsdiff)/halfpi;
if ( coeff_rt < 0 ) coeff_rt = 0;
coeff_rt = std::pow(coeff_rt, 1.0/4);
coeff_tgt = std::pow(coeff_tgt, 1.3);
float heratio = coeff_tgt * coeff_rt;
#ifdef AEGIR_DEBUG_TEMPCTRL
printf("Controller::tempControl(): MT:%.2f RIMS:%.2f TGT:%.2f d_tgt:%.2f d_rims:%.2f c_tgt:%.2f c_rt:%.2f HEr:%.2f\n",
mttemp, rimstemp, _target, tgtdiff, rimsdiff, coeff_tgt, coeff_rt, heratio);
#endif
auto pin_he = getPIN("rimsheat");
float absherdiff = std::abs(pin_he->getOldOnratio()-heratio);
#ifdef AEGIR_DEBUG_TEMPCTRL
printf("Controller::tempControl(): rimsheat: ST:%hhu CT:%.2f OR:%.2f AHD:%.2f\n",
pin_he->getValue(), pin_he->getOldCycletime(), pin_he->getOldOnratio(), absherdiff);
#endif
if ( absherdiff > 0.03 ) {
setPIN("rimsheat", PINState::Pulsate, c_hecycletime, heratio);
}
}
uint32_t Controller::calcHeatTime(uint32_t _vol, uint32_t _tempdiff, float _pkw) const {
return (4.2 * _vol * _tempdiff)/_pkw;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright Copyright 2012, System Insights, 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 "rolling_file_logger.hpp"
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ostream>
using namespace dlib;
using namespace std;
RollingFileLogger::RollingFileLogger(std::string aName,
int aMaxBackupIndex,
size_t aMaxSize,
RollingSchedule aSchedule)
: mName(aName), mMaxBackupIndex(aMaxBackupIndex), mMaxSize(aMaxSize),
mSchedule(aSchedule), mFd(0)
{
mFileLock = new mutex();
mFd = ::open(aName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
if (mFd < 0)
{
cerr << "Cannot log open file " << aName << endl;
cerr << "Exiting...";
exit(1);
}
file f(aName);
mFile = f;
mDirectory = get_parent_directory(mFile);
}
RollingFileLogger::~RollingFileLogger()
{
delete mFileLock;
::close(mFd);
}
int RollingFileLogger::getFileAge()
{
struct stat buffer;
int res = ::stat(mFile.full_name().c_str(), &buffer);
if (res < 0)
return 0;
else
return time(NULL) - buffer.st_ctimespec.tv_sec;
}
const int DAY = 24 * 60 * 60;
void RollingFileLogger::write(const char *aMessage)
{
size_t len = strlen(aMessage);
if (mSchedule != NEVER) {
int age = getFileAge();
if ((mSchedule == DAILY && age > DAY) ||
(mSchedule == WEEKLY && age > 7 * DAY))
rollover(0);
} else {
file f(mFile.full_name());
size_t size = f.size();
if (size + len >= mMaxSize)
rollover(size);
}
::write(mFd, aMessage, len);
}
void RollingFileLogger::rollover(size_t aSize)
{
dlib::auto_mutex M(*mFileLock);
// File was probable rolled over... threading race.
if (mSchedule != NEVER) {
int age = getFileAge();
if ((mSchedule == DAILY && age < DAY) ||
(mSchedule == WEEKLY && age < 7 * DAY))
return;
} else {
file f(mFile.full_name());
if (f.size() < aSize)
return;
}
// Close the current file
::close(mFd);
// Remove the last file
std::string name = mFile.full_name() + "." + intToString(mMaxBackupIndex);
if (file_exists(name))
::remove(name.c_str());
// Roll over old log files.
for (int i = mMaxBackupIndex - 1; i >= 1; i--)
{
std::string from = mFile.full_name() + "." + intToString(i);
if (file_exists(from))
{
name = mFile.full_name() + "." + intToString(i + 1);
::rename(from.c_str(), name.c_str());
}
}
name = mFile.full_name() + ".1";
::rename(mFile.full_name().c_str(), name.c_str());
// Open new log file
mFd = ::open(mFile.full_name().c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
if (mFd < 0)
{
cerr << "Cannot log open file " << mName << endl;
cerr << "Exiting...";
exit(1);
}
}<commit_msg>Windows porting.<commit_after>/*
* Copyright Copyright 2012, System Insights, 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 "rolling_file_logger.hpp"
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <ostream>
using namespace dlib;
using namespace std;
RollingFileLogger::RollingFileLogger(std::string aName,
int aMaxBackupIndex,
size_t aMaxSize,
RollingSchedule aSchedule)
: mName(aName), mMaxBackupIndex(aMaxBackupIndex), mMaxSize(aMaxSize),
mSchedule(aSchedule), mFd(0)
{
mFileLock = new mutex();
mFd = ::open(aName.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
if (mFd < 0)
{
cerr << "Cannot log open file " << aName << endl;
cerr << "Exiting...";
exit(1);
}
file f(aName);
mFile = f;
mDirectory = get_parent_directory(mFile);
}
RollingFileLogger::~RollingFileLogger()
{
delete mFileLock;
::close(mFd);
}
int RollingFileLogger::getFileAge()
{
struct stat buffer;
int res = ::stat(mFile.full_name().c_str(), &buffer);
if (res < 0)
return 0;
else
#ifndef WIN32
return time(NULL) - buffer.st_ctimespec.tv_sec;
#else
return time(NULL) - buffer.st_ctime;
#endif
}
const int DAY = 24 * 60 * 60;
void RollingFileLogger::write(const char *aMessage)
{
size_t len = strlen(aMessage);
if (mSchedule != NEVER) {
int age = getFileAge();
if ((mSchedule == DAILY && age > DAY) ||
(mSchedule == WEEKLY && age > 7 * DAY))
rollover(0);
} else {
file f(mFile.full_name());
size_t size = f.size();
if (size + len >= mMaxSize)
rollover(size);
}
::write(mFd, aMessage, len);
}
void RollingFileLogger::rollover(size_t aSize)
{
dlib::auto_mutex M(*mFileLock);
// File was probable rolled over... threading race.
if (mSchedule != NEVER) {
int age = getFileAge();
if ((mSchedule == DAILY && age < DAY) ||
(mSchedule == WEEKLY && age < 7 * DAY))
return;
} else {
file f(mFile.full_name());
if (f.size() < aSize)
return;
}
// Close the current file
::close(mFd);
// Remove the last file
std::string name = mFile.full_name() + "." + intToString(mMaxBackupIndex);
if (file_exists(name))
::remove(name.c_str());
// Roll over old log files.
for (int i = mMaxBackupIndex - 1; i >= 1; i--)
{
std::string from = mFile.full_name() + "." + intToString(i);
if (file_exists(from))
{
name = mFile.full_name() + "." + intToString(i + 1);
::rename(from.c_str(), name.c_str());
}
}
name = mFile.full_name() + ".1";
::rename(mFile.full_name().c_str(), name.c_str());
// Open new log file
mFd = ::open(mFile.full_name().c_str(), O_CREAT | O_APPEND | O_WRONLY, 0644);
if (mFd < 0)
{
cerr << "Cannot log open file " << mName << endl;
cerr << "Exiting...";
exit(1);
}
}<|endoftext|>
|
<commit_before>#ifndef VFRAME_NO_3D
#ifndef NO_GLEW
#include <GL/glew.h>
#endif
#endif
#include "VGame.h"
#include "VCamera.h"
#include "VGlobal.h"
#include "VTimer.h"
#include "VPostEffect.h"
#include "VState.h"
#include <SFML/System/Clock.hpp>
VGame::~VGame()
{
if (!cleaned)
{
Cleanup();
}
}
int VGame::Init()
{
VBase::VLog("Calling Init()");
try
{
#ifndef VFRAME_NO_3D
#ifndef NO_GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
return 2;
#endif
#endif
if (!VGlobal::p()->App->isOpen())
return 3;
renderTarget = std::make_unique<sf::RenderTexture>();
if (!renderTarget->create(VGlobal::p()->Width, VGlobal::p()->Height))
return 4;
VGlobal::p()->WorldBounds = sf::FloatRect(0, 0, static_cast<float>(VGlobal::p()->Width), static_cast<float>(VGlobal::p()->Height));
VGlobal::p()->App->requestFocus();
VCameraList::Default = renderTarget->getDefaultView();
vertexArray.resize(4);
vertexArray.setPrimitiveType(sf::Quads);
vertexArray[0] = sf::Vertex(sf::Vector2f(), sf::Color::White, sf::Vector2f());
vertexArray[1] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f),
sf::Color::White,
sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f));
vertexArray[2] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height),
sf::Color::White,
sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height));
vertexArray[3] = sf::Vertex(sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height),
sf::Color::White,
sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height));
ResizeCheck();
}
catch (int e)
{
return e;
}
return EXIT_SUCCESS;
}
int VGame::Cleanup()
{
VBase::VLog("Calling Cleanup()");
try
{
VGlobal::Cleanup();
cleaned = true;
}
catch (int e)
{
VBase::VLog("Cleanup error: %d", e);
return e;
}
return EXIT_SUCCESS;
}
int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, float fps, int flags, const sf::ContextSettings& settings)
{
return Run(title, initialState, windowwidth, windowheight, windowwidth, windowheight, fps, flags, settings);
}
int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, int screenwidth, int screenheight, float fps, int flags, const sf::ContextSettings& settings)
{
VGlobal::p()->Width = screenwidth;
VGlobal::p()->Height = screenheight;
VGlobal::p()->FPS = fps;
VGlobal::p()->WindowStyle = flags;
VGlobal::p()->ContextSettings = settings;
VGlobal::p()->RenderState = sf::RenderStates::Default;
VGlobal::p()->App->create(sf::VideoMode(windowwidth, windowheight), title, flags, settings);
VBase::VLog("Welcome to the ViglanteFramework - Version: %s ", VFRAME_VERSION);
int error = 0;
if ((error = Init()))
{
VBase::VLogError("Error in Init(): %d", error);
return error;
}
#ifndef VFRAME_NO_3D
#ifndef NO_GLEW
VBase::VLog("OpenGL Version: %s", glGetString(GL_VERSION));
#endif
#endif
VBase::VLog("\nStarting Game: %s", title.toUtf8().c_str());
initialState->DefaultCamera->Reset();
VGlobal::p()->ChangeState(initialState);
VGlobal::p()->ChangeState(nullptr);
sf::Clock clock;
VBase::VLog("Initialisation finished");
try
{
double end = 0.0;
while (VGlobal::p()->IsRunning())
{
VGlobal::p()->Async->ProcessSyncRequests();
float dt = 1.0f / VGlobal::p()->FPS;
double start = clock.getElapsedTime().asSeconds();
double passed = start - end;
float frameRate = (float)(1.0 / passed);
frameRate = frameRate < 12 ? 12 : frameRate;
float deltaScale = (VGlobal::p()->FPS / frameRate);
end = start;
if (VGlobal::p()->IfChangedState)
{
VGlobal::p()->ChangeState(nullptr);
}
if (VGlobal::p()->IfPushedState)
{
VGlobal::p()->PushState(nullptr);
}
HandleEvents();
if (focused)
{
Update(dt * deltaScale * VGlobal::p()->TimeScale);
}
if (focused && !VGlobal::p()->IfChangedState && !VGlobal::p()->IfPushedState)
{
PreRender();
for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
{
Render(VGlobal::p()->CurrentState()->Cameras[c]);
}
PostRender();
}
}
}
catch (int e)
{
return e;
}
if ((error = Cleanup()))
{
VBase::VLogError("Error in Cleanup(): %d", error);
return error;
}
VBase::VLog("Cleanup Successful");
return EXIT_SUCCESS;
}
void VGame::HandleEvents()
{
sf::Event event;
while (VGlobal::p()->App->pollEvent(event))
{
if (VGlobal::p()->CurrentState()->SubState)
{
VGlobal::p()->CurrentState()->SubState->HandleEvents(event);
}
VGlobal::p()->CurrentState()->HandleEvents(event);
if (event.type == sf::Event::Closed)
{
VGlobal::p()->Exit();
}
if (VGlobal::p()->FocusPause)
{
if (event.type == sf::Event::LostFocus)
{
focused = false;
}
if (event.type == sf::Event::GainedFocus)
{
focused = true;
}
}
}
ResizeCheck();
}
void VGame::ResizeCheck()
{
sf::Vector2u windowSize = VGlobal::p()->App->getSize();
if (windowSize.x != VGlobal::p()->WindowWidth || windowSize.y != VGlobal::p()->WindowHeight)
{
VGlobal::p()->WindowWidth = windowSize.x;
VGlobal::p()->WindowHeight = windowSize.y;
VGlobal::p()->App->setView(sf::View(sf::FloatRect(0, 0, (float)windowSize.x, (float)windowSize.y)));
float sx = VGlobal::p()->App->getSize().x / (float)VGlobal::p()->Width;
float sy = VGlobal::p()->App->getSize().y / (float)VGlobal::p()->Height;
float scale = std::fminf(sx, sy);
float scaleW = VGlobal::p()->Width * scale;
float scaleH = VGlobal::p()->Height * scale;
float scaleX = (VGlobal::p()->App->getSize().x - scaleW) / 2;
float scaleY = (VGlobal::p()->App->getSize().y - scaleH) / 2;
vertexArray[0].position = sf::Vector2f(scaleX, scaleY);
vertexArray[1].position = sf::Vector2f(scaleX + scaleW, scaleY);
vertexArray[2].position = sf::Vector2f(scaleX + scaleW, scaleY + scaleH);
vertexArray[3].position = sf::Vector2f(scaleX, scaleY + scaleH);
VGlobal::p()->ViewportOffset = vertexArray[0].position;
}
}
void VGame::Update(float dt)
{
if (VTimeManager::AnyActiveTimers())
{
VTimeManager::p()->Update(dt);
}
VGlobal::p()->Input->Update(dt);
if (VGlobal::p()->CurrentState()->active)
{
VGlobal::p()->CurrentState()->Update(dt);
}
VGlobal::p()->CurrentState()->ResetSubState();
if (VGlobal::p()->CurrentState()->SubState)
{
VGlobal::p()->CurrentState()->SubState->Update(dt);
}
for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
{
VGlobal::p()->CurrentState()->Cameras[c]->Update(dt);
}
VGlobal::p()->Music->Update(dt);
if (VGlobal::p()->PostProcess != nullptr && VPostEffectBase::isSupported())
{
VGlobal::p()->PostProcess->Update(dt);
}
}
void VGame::PreRender()
{
renderTarget->clear(VGlobal::p()->BackgroundColor);
VGlobal::p()->App->clear();
}
void VGame::Render(VCamera* camera)
{
if (!camera->Active)
return;
renderTarget->setView(camera->GetView());
VState* currentState = VGlobal::p()->CurrentState();
if (currentState && currentState->visible)
currentState->Draw(*renderTarget);
if (currentState->SubState && currentState->SubState->visible)
currentState->SubState->Draw(*renderTarget);
camera->Render(*renderTarget);
}
void VGame::PostRender()
{
renderTarget->display();
if (renderTarget->isSmooth() != VGlobal::p()->Antialiasing)
{
renderTarget->setSmooth(VGlobal::p()->Antialiasing);
}
sf::RenderWindow* app = VGlobal::p()->App.get();
app->setActive(true);
app->setVerticalSyncEnabled(VGlobal::p()->VSync);
sf::View view = app->getView();
VGlobal::p()->RenderState.texture = &renderTarget->getTexture();
if (VGlobal::p()->PostProcess == nullptr || !VPostEffectBase::isSupported())
{
view.setViewport(sf::FloatRect(0, 0, 1, 1));
app->draw(vertexArray, VGlobal::p()->RenderState);
}
else
{
sf::Vector2f position = VGlobal::p()->ViewportOffset;
sf::Vector2f size = view.getSize();
float left = position.x / size.x;
float top = position.y / size.y;
view.setViewport(sf::FloatRect(left, top, 1 - (left * 2), 1 - (top * 2)));
VGlobal::p()->PostProcess->Apply(renderTarget->getTexture(), *app);
}
app->setView(view);
VState* currentState = VGlobal::p()->CurrentState();
if (currentState && currentState->visible)
currentState->PostDraw(*VGlobal::p()->App);
if (currentState->SubState && currentState->SubState->visible)
currentState->SubState->PostDraw(*VGlobal::p()->App);
app->display();
}
<commit_msg>Doubles to floats<commit_after>#ifndef VFRAME_NO_3D
#ifndef NO_GLEW
#include <GL/glew.h>
#endif
#endif
#include "VGame.h"
#include "VCamera.h"
#include "VGlobal.h"
#include "VTimer.h"
#include "VPostEffect.h"
#include "VState.h"
#include <SFML/System/Clock.hpp>
VGame::~VGame()
{
if (!cleaned)
{
Cleanup();
}
}
int VGame::Init()
{
VBase::VLog("Calling Init()");
try
{
#ifndef VFRAME_NO_3D
#ifndef NO_GLEW
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
return 2;
#endif
#endif
if (!VGlobal::p()->App->isOpen())
return 3;
renderTarget = std::make_unique<sf::RenderTexture>();
if (!renderTarget->create(VGlobal::p()->Width, VGlobal::p()->Height))
return 4;
VGlobal::p()->WorldBounds = sf::FloatRect(0, 0, static_cast<float>(VGlobal::p()->Width), static_cast<float>(VGlobal::p()->Height));
VGlobal::p()->App->requestFocus();
VCameraList::Default = renderTarget->getDefaultView();
vertexArray.resize(4);
vertexArray.setPrimitiveType(sf::Quads);
vertexArray[0] = sf::Vertex(sf::Vector2f(), sf::Color::White, sf::Vector2f());
vertexArray[1] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f),
sf::Color::White,
sf::Vector2f(VGlobal::p()->WorldBounds.width, 0.0f));
vertexArray[2] = sf::Vertex(sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height),
sf::Color::White,
sf::Vector2f(VGlobal::p()->WorldBounds.width, VGlobal::p()->WorldBounds.height));
vertexArray[3] = sf::Vertex(sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height),
sf::Color::White,
sf::Vector2f(0.0f, VGlobal::p()->WorldBounds.height));
ResizeCheck();
}
catch (int e)
{
return e;
}
return EXIT_SUCCESS;
}
int VGame::Cleanup()
{
VBase::VLog("Calling Cleanup()");
try
{
VGlobal::Cleanup();
cleaned = true;
}
catch (int e)
{
VBase::VLog("Cleanup error: %d", e);
return e;
}
return EXIT_SUCCESS;
}
int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, float fps, int flags, const sf::ContextSettings& settings)
{
return Run(title, initialState, windowwidth, windowheight, windowwidth, windowheight, fps, flags, settings);
}
int VGame::Run(const sf::String& title, VState* initialState, int windowwidth, int windowheight, int screenwidth, int screenheight, float fps, int flags, const sf::ContextSettings& settings)
{
VGlobal::p()->Width = screenwidth;
VGlobal::p()->Height = screenheight;
VGlobal::p()->FPS = fps;
VGlobal::p()->WindowStyle = flags;
VGlobal::p()->ContextSettings = settings;
VGlobal::p()->RenderState = sf::RenderStates::Default;
VGlobal::p()->App->create(sf::VideoMode(windowwidth, windowheight), title, flags, settings);
VBase::VLog("Welcome to the ViglanteFramework - Version: %s ", VFRAME_VERSION);
int error = 0;
if ((error = Init()))
{
VBase::VLogError("Error in Init(): %d", error);
return error;
}
#ifndef VFRAME_NO_3D
#ifndef NO_GLEW
VBase::VLog("OpenGL Version: %s", glGetString(GL_VERSION));
#endif
#endif
VBase::VLog("\nStarting Game: %s", title.toUtf8().c_str());
initialState->DefaultCamera->Reset();
VGlobal::p()->ChangeState(initialState);
VGlobal::p()->ChangeState(nullptr);
sf::Clock clock;
VBase::VLog("Initialisation finished");
try
{
float dt = 1.0f / VGlobal::p()->FPS;
float end = 0.0f;
float frameDelay = dt;
while (VGlobal::p()->IsRunning())
{
VGlobal::p()->Async->ProcessSyncRequests();
float start = clock.getElapsedTime().asSeconds();
float passed = start - end;
float frameRate = 1.0f / passed;
frameRate = frameRate < 12 ? 12 : frameRate;
float deltaScale = (VGlobal::p()->FPS / frameRate);
end = start;
frameDelay += passed;
if (VGlobal::p()->IfChangedState)
{
VGlobal::p()->ChangeState(nullptr);
}
if (VGlobal::p()->IfPushedState)
{
VGlobal::p()->PushState(nullptr);
}
HandleEvents();
if (focused)
{
Update(dt * deltaScale * VGlobal::p()->TimeScale);
if (!VGlobal::p()->IfChangedState && !VGlobal::p()->IfPushedState && frameDelay >= dt)
{
PreRender();
for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
{
Render(VGlobal::p()->CurrentState()->Cameras[c]);
}
PostRender();
frameDelay = 0.0f;
}
}
}
}
catch (int e)
{
return e;
}
if ((error = Cleanup()))
{
VBase::VLogError("Error in Cleanup(): %d", error);
return error;
}
VBase::VLog("Cleanup Successful");
return EXIT_SUCCESS;
}
void VGame::HandleEvents()
{
sf::Event event;
while (VGlobal::p()->App->pollEvent(event))
{
if (VGlobal::p()->CurrentState()->SubState)
{
VGlobal::p()->CurrentState()->SubState->HandleEvents(event);
}
VGlobal::p()->CurrentState()->HandleEvents(event);
if (event.type == sf::Event::Closed)
{
VGlobal::p()->Exit();
}
if (VGlobal::p()->FocusPause)
{
if (event.type == sf::Event::LostFocus)
{
focused = false;
}
if (event.type == sf::Event::GainedFocus)
{
focused = true;
}
}
}
ResizeCheck();
}
void VGame::ResizeCheck()
{
sf::Vector2u windowSize = VGlobal::p()->App->getSize();
if (windowSize.x != VGlobal::p()->WindowWidth || windowSize.y != VGlobal::p()->WindowHeight)
{
VGlobal::p()->WindowWidth = windowSize.x;
VGlobal::p()->WindowHeight = windowSize.y;
VGlobal::p()->App->setView(sf::View(sf::FloatRect(0, 0, (float)windowSize.x, (float)windowSize.y)));
float sx = VGlobal::p()->App->getSize().x / (float)VGlobal::p()->Width;
float sy = VGlobal::p()->App->getSize().y / (float)VGlobal::p()->Height;
float scale = std::fminf(sx, sy);
float scaleW = VGlobal::p()->Width * scale;
float scaleH = VGlobal::p()->Height * scale;
float scaleX = (VGlobal::p()->App->getSize().x - scaleW) / 2;
float scaleY = (VGlobal::p()->App->getSize().y - scaleH) / 2;
vertexArray[0].position = sf::Vector2f(scaleX, scaleY);
vertexArray[1].position = sf::Vector2f(scaleX + scaleW, scaleY);
vertexArray[2].position = sf::Vector2f(scaleX + scaleW, scaleY + scaleH);
vertexArray[3].position = sf::Vector2f(scaleX, scaleY + scaleH);
VGlobal::p()->ViewportOffset = vertexArray[0].position;
}
}
void VGame::Update(float dt)
{
if (VTimeManager::AnyActiveTimers())
{
VTimeManager::p()->Update(dt);
}
VGlobal::p()->Input->Update(dt);
if (VGlobal::p()->CurrentState()->active)
{
VGlobal::p()->CurrentState()->Update(dt);
}
VGlobal::p()->CurrentState()->ResetSubState();
if (VGlobal::p()->CurrentState()->SubState)
{
VGlobal::p()->CurrentState()->SubState->Update(dt);
}
for (unsigned int c = 0; c < VGlobal::p()->CurrentState()->Cameras.size(); c++)
{
VGlobal::p()->CurrentState()->Cameras[c]->Update(dt);
}
VGlobal::p()->Music->Update(dt);
if (VGlobal::p()->PostProcess != nullptr && VPostEffectBase::isSupported())
{
VGlobal::p()->PostProcess->Update(dt);
}
}
void VGame::PreRender()
{
renderTarget->clear(VGlobal::p()->BackgroundColor);
VGlobal::p()->App->clear();
}
void VGame::Render(VCamera* camera)
{
if (!camera->Active)
return;
renderTarget->setView(camera->GetView());
VState* currentState = VGlobal::p()->CurrentState();
if (currentState && currentState->visible)
currentState->Draw(*renderTarget);
if (currentState->SubState && currentState->SubState->visible)
currentState->SubState->Draw(*renderTarget);
camera->Render(*renderTarget);
}
void VGame::PostRender()
{
renderTarget->display();
if (renderTarget->isSmooth() != VGlobal::p()->Antialiasing)
{
renderTarget->setSmooth(VGlobal::p()->Antialiasing);
}
sf::RenderWindow* app = VGlobal::p()->App.get();
app->setActive(true);
app->setVerticalSyncEnabled(VGlobal::p()->VSync);
sf::View view = app->getView();
VGlobal::p()->RenderState.texture = &renderTarget->getTexture();
if (VGlobal::p()->PostProcess == nullptr || !VPostEffectBase::isSupported())
{
view.setViewport(sf::FloatRect(0, 0, 1, 1));
app->draw(vertexArray, VGlobal::p()->RenderState);
}
else
{
sf::Vector2f position = VGlobal::p()->ViewportOffset;
sf::Vector2f size = view.getSize();
float left = position.x / size.x;
float top = position.y / size.y;
view.setViewport(sf::FloatRect(left, top, 1 - (left * 2), 1 - (top * 2)));
VGlobal::p()->PostProcess->Apply(renderTarget->getTexture(), *app);
}
app->setView(view);
VState* currentState = VGlobal::p()->CurrentState();
if (currentState && currentState->visible)
currentState->PostDraw(*VGlobal::p()->App);
if (currentState->SubState && currentState->SubState->visible)
currentState->SubState->PostDraw(*VGlobal::p()->App);
app->display();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include "configuration.h"
using namespace std;
namespace Gps2EventDb {
using namespace boost::program_options;
boost::program_options::variables_map &getConfig()
{
static boost::program_options::variables_map theOneAndOnlyVariableMapInstance;
return theOneAndOnlyVariableMapInstance;
}
void dumpConfiguration(ostream &out)
{
// Print out the configuration information.
variables_map &config=getConfig();
out << endl << "Using this runtime configuration: " << endl;
for (variables_map::const_iterator i=config.begin(); i!=config.end(); ++i) {
// Annoying that we have to iterate over types.
if (i->second.value().type()==typeid(string))
out << i->first << " = " << i->second.as<string>() << endl;
else if (i->second.value().type()==typeid(int))
out << i->first << " = " << i->second.as<int>() << endl;
else if (i->second.value().type()==typeid(unsigned int))
out << i->first << " = " << i->second.as<unsigned int>() << endl;
else if (i->second.value().type()==typeid(double))
out << i->first << " = " << i->second.as<double>() << endl;
else if (i->second.value().type()==typeid(float))
out << i->first << " = " << i->second.as<float>() << endl;
else if (i->second.value().type()==typeid(time_t))
out << i->first << " = " << i->second.as<time_t>() << endl;
else if (i->second.value().type()==typeid(bool))
out << i->first << " = " << (i->second.as<bool>()==true ? "true" : "false") << endl;
else
out << i->first << " = " << "[I don't know how to display this type. Ask Geoff to add it.]" << endl;
}
out << endl;
}
bool loadConfiguration(int argc, char **argv)
{
string binName=basename(argv[0]);
const unsigned int lineLen=120;
// Declare a group of options that will be
// allowed only on command line
options_description generic("Command line only options", lineLen);
generic.add_options()
("help,h", "Show help message.")
("configFile,c", value<string>()->default_value(binName + ".cfg"), "The location of the configuration file.")
;
options_description config("Functional Options. (Allowed on command line or in configuration file.)", lineLen);
config.add_options()
("radius,r", value<double>()->default_value(180.0), "The radius, in meters, in which nodes can hear each other")
("scenario,s", value<string>(), "The MANE scenario file to use. Required arguement.")
("database,d", value<string>()->default_value("event.db"), "The name of the created watcher event datbase.")
;
variables_map &vm=getConfig();
options_description cmdline_options(lineLen);
options_description config_file_options(lineLen);
// Try to sort out all options and complain/exit on error
try {
cmdline_options.add(generic).add(config);
config_file_options.add(config);
store(parse_command_line(argc, argv, cmdline_options), vm);
ifstream confFile(vm["configFile"].as<string>().c_str());
if (confFile.is_open()) {
store(parse_config_file(confFile, config_file_options), vm);
confFile.close();
}
}
catch (const invalid_option_value &e) {
cerr << "Option Error - " << e.what() << endl;
exit(EXIT_FAILURE);
}
catch (const invalid_command_line_syntax &e) {
cerr << "Syntax Error - " << e.what() << endl;
exit(EXIT_FAILURE);
}
notify(vm);
if (vm.count("help")) {
cerr << cmdline_options << endl;
return false;
}
if (!vm.count("scenario")) {
cerr << cmdline_options << endl;
cerr << endl << "scenario is a required argument." << endl << endl;
exit(EXIT_FAILURE);
}
return true;
}
}
<commit_msg>fixed mispleling.<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <boost/program_options.hpp>
#include "configuration.h"
using namespace std;
namespace Gps2EventDb {
using namespace boost::program_options;
boost::program_options::variables_map &getConfig()
{
static boost::program_options::variables_map theOneAndOnlyVariableMapInstance;
return theOneAndOnlyVariableMapInstance;
}
void dumpConfiguration(ostream &out)
{
// Print out the configuration information.
variables_map &config=getConfig();
out << endl << "Using this runtime configuration: " << endl;
for (variables_map::const_iterator i=config.begin(); i!=config.end(); ++i) {
// Annoying that we have to iterate over types.
if (i->second.value().type()==typeid(string))
out << i->first << " = " << i->second.as<string>() << endl;
else if (i->second.value().type()==typeid(int))
out << i->first << " = " << i->second.as<int>() << endl;
else if (i->second.value().type()==typeid(unsigned int))
out << i->first << " = " << i->second.as<unsigned int>() << endl;
else if (i->second.value().type()==typeid(double))
out << i->first << " = " << i->second.as<double>() << endl;
else if (i->second.value().type()==typeid(float))
out << i->first << " = " << i->second.as<float>() << endl;
else if (i->second.value().type()==typeid(time_t))
out << i->first << " = " << i->second.as<time_t>() << endl;
else if (i->second.value().type()==typeid(bool))
out << i->first << " = " << (i->second.as<bool>()==true ? "true" : "false") << endl;
else
out << i->first << " = " << "[I don't know how to display this type. Ask Geoff to add it.]" << endl;
}
out << endl;
}
bool loadConfiguration(int argc, char **argv)
{
string binName=basename(argv[0]);
const unsigned int lineLen=120;
// Declare a group of options that will be
// allowed only on command line
options_description generic("Command line only options", lineLen);
generic.add_options()
("help,h", "Show help message.")
("configFile,c", value<string>()->default_value(binName + ".cfg"), "The location of the configuration file.")
;
options_description config("Functional Options. (Allowed on command line or in configuration file.)", lineLen);
config.add_options()
("radius,r", value<double>()->default_value(180.0), "The radius, in meters, in which nodes can hear each other")
("scenario,s", value<string>(), "The MANE scenario file to use. Required argument.")
("database,d", value<string>()->default_value("event.db"), "The name of the created watcher event datbase.")
;
variables_map &vm=getConfig();
options_description cmdline_options(lineLen);
options_description config_file_options(lineLen);
// Try to sort out all options and complain/exit on error
try {
cmdline_options.add(generic).add(config);
config_file_options.add(config);
store(parse_command_line(argc, argv, cmdline_options), vm);
ifstream confFile(vm["configFile"].as<string>().c_str());
if (confFile.is_open()) {
store(parse_config_file(confFile, config_file_options), vm);
confFile.close();
}
}
catch (const invalid_option_value &e) {
cerr << "Option Error - " << e.what() << endl;
exit(EXIT_FAILURE);
}
catch (const invalid_command_line_syntax &e) {
cerr << "Syntax Error - " << e.what() << endl;
exit(EXIT_FAILURE);
}
notify(vm);
if (vm.count("help")) {
cerr << cmdline_options << endl;
return false;
}
if (!vm.count("scenario")) {
cerr << cmdline_options << endl;
cerr << endl << "scenario is a required argument." << endl << endl;
exit(EXIT_FAILURE);
}
return true;
}
}
<|endoftext|>
|
<commit_before>#include "omnicore/notifications.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/rules.h"
#include "omnicore/utilsbitcoin.h"
#include "omnicore/version.h"
#include "main.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stdint.h>
#include <string>
#include <vector>
namespace mastercore
{
//! Vector of currently active Omni alerts
std::vector<AlertData> currentOmniAlerts;
/**
* Adds a new alert to the alerts vector
*
*/
void AddAlert(uint16_t alertType, uint32_t alertExpiry, const std::string& alertMessage)
{
AlertData newAlert;
newAlert.alert_type = alertType;
newAlert.alert_expiry = alertExpiry;
newAlert.alert_message = alertMessage;
// very basic sanity checks to catch malformed packets
if (alertType > 3) {
PrintToLog("New alert REJECTED (alert type not recognized): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
return;
}
if (alertType == 1 && alertExpiry > 999999) {
PrintToLog("New alert REJECTED (block value too large): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
return;
}
if (alertType == 2 && (alertExpiry < 1439256200 || alertExpiry > 1639256200)) {
PrintToLog("New alert REJECTED (block time values invalid): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
return;
}
if (alertType == 3 && (alertExpiry < 100 || alertExpiry > 900000)) {
PrintToLog("New alert REJECTED (client version invalid): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
return;
}
currentOmniAlerts.push_back(newAlert);
PrintToLog("New alert added: %d, %d, %s\n", alertType, alertExpiry, alertMessage);
}
/**
* Determines whether the sender is an authorized source for Omni Core alerts.
*
* The option "-omnialertallowsender=source" can be used to whitelist additional sources,
* and the option "-omnialertignoresender=source" can be used to ignore a source.
*
* To consider any alert as authorized, "-omnialertallowsender=any" can be used. This
* should only be done for testing purposes!
*/
bool CheckAlertAuthorization(const std::string& sender)
{
std::set<std::string> whitelisted;
// TODO: check email addresses
// Mainnet
whitelisted.insert("16Zwbujf1h3v1DotKcn9XXt1m7FZn2o4mj"); // Craig <craig@omni.foundation>
whitelisted.insert("1MicH2Vu4YVSvREvxW1zAx2XKo2GQomeXY"); // Michael <michael@omni.foundation>
whitelisted.insert("1zAtHRASgdHvZDfHs6xJquMghga4eG7gy"); // Zathras <zathras@omni.foundation>
whitelisted.insert("1dexX7zmPen1yBz2H9ZF62AK5TGGqGTZH"); // dexX7 <dexx@bitwatch.co>
whitelisted.insert("1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); // Exodus (who has access?)
// Testnet
whitelisted.insert("mpDex4kSX4iscrmiEQ8fBiPoyeTH55z23j"); // Michael <michael@omni.foundation>
whitelisted.insert("mpZATHupfCLqet5N1YL48ByCM1ZBfddbGJ"); // Zathras <zathras@omni.foundation>
whitelisted.insert("mk5SSx4kdexENHzLxk9FLhQdbbBexHUFTW"); // dexX7 <dexx@bitwatch.co>
// Add manually whitelisted sources
if (mapArgs.count("-omnialertallowsender")) {
const std::vector<std::string>& sources = mapMultiArgs["-omnialertallowsender"];
for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
whitelisted.insert(*it);
}
}
// Remove manually ignored sources
if (mapArgs.count("-omnialertignoresender")) {
const std::vector<std::string>& sources = mapMultiArgs["-omnialertignoresender"];
for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
whitelisted.erase(*it);
}
}
bool fAuthorized = (whitelisted.count(sender) ||
whitelisted.count("any"));
return fAuthorized;
}
/**
* Alerts including meta data.
*/
std::vector<AlertData> GetOmniCoreAlerts()
{
return currentOmniAlerts;
}
/**
* Human readable alert messages.
*/
std::vector<std::string> GetOmniCoreAlertMessages()
{
std::vector<std::string> vstr;
for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); it++) {
vstr.push_back((*it).alert_message);
}
return vstr;
}
/**
* Expires any alerts that need expiring.
*/
bool CheckExpiredAlerts(unsigned int curBlock, uint64_t curTime)
{
for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); ) {
AlertData alert = *it;
switch (alert.alert_type) {
case 1: // alert expiring by block number
if (curBlock >= alert.alert_expiry) {
PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
} else {
it++;
}
break;
case 2: // alert expiring by block time
if (curTime > alert.alert_expiry) {
PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
} else {
it++;
}
break;
case 3: // alert expiring by client version
if (OMNICORE_VERSION > alert.alert_expiry) {
PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
} else {
it++;
}
break;
default: // unrecognized alert type
PrintToLog("Removing invalid alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
break;
}
}
return true;
}
} // namespace mastercore
<commit_msg>Remove magic number sanity checks on AddAlert<commit_after>#include "omnicore/notifications.h"
#include "omnicore/log.h"
#include "omnicore/omnicore.h"
#include "omnicore/rules.h"
#include "omnicore/utilsbitcoin.h"
#include "omnicore/version.h"
#include "main.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <stdint.h>
#include <string>
#include <vector>
namespace mastercore
{
//! Vector of currently active Omni alerts
std::vector<AlertData> currentOmniAlerts;
/**
* Adds a new alert to the alerts vector
*
*/
void AddAlert(uint16_t alertType, uint32_t alertExpiry, const std::string& alertMessage)
{
AlertData newAlert;
newAlert.alert_type = alertType;
newAlert.alert_expiry = alertExpiry;
newAlert.alert_message = alertMessage;
// very basic sanity checks to catch malformed packets
if (alertType < 1 || alertType > 3) {
PrintToLog("New alert REJECTED (alert type not recognized): %d, %d, %s\n", alertType, alertExpiry, alertMessage);
return;
}
currentOmniAlerts.push_back(newAlert);
PrintToLog("New alert added: %d, %d, %s\n", alertType, alertExpiry, alertMessage);
}
/**
* Determines whether the sender is an authorized source for Omni Core alerts.
*
* The option "-omnialertallowsender=source" can be used to whitelist additional sources,
* and the option "-omnialertignoresender=source" can be used to ignore a source.
*
* To consider any alert as authorized, "-omnialertallowsender=any" can be used. This
* should only be done for testing purposes!
*/
bool CheckAlertAuthorization(const std::string& sender)
{
std::set<std::string> whitelisted;
// TODO: check email addresses
// Mainnet
whitelisted.insert("16Zwbujf1h3v1DotKcn9XXt1m7FZn2o4mj"); // Craig <craig@omni.foundation>
whitelisted.insert("1MicH2Vu4YVSvREvxW1zAx2XKo2GQomeXY"); // Michael <michael@omni.foundation>
whitelisted.insert("1zAtHRASgdHvZDfHs6xJquMghga4eG7gy"); // Zathras <zathras@omni.foundation>
whitelisted.insert("1dexX7zmPen1yBz2H9ZF62AK5TGGqGTZH"); // dexX7 <dexx@bitwatch.co>
whitelisted.insert("1EXoDusjGwvnjZUyKkxZ4UHEf77z6A5S4P"); // Exodus (who has access?)
// Testnet
whitelisted.insert("mpDex4kSX4iscrmiEQ8fBiPoyeTH55z23j"); // Michael <michael@omni.foundation>
whitelisted.insert("mpZATHupfCLqet5N1YL48ByCM1ZBfddbGJ"); // Zathras <zathras@omni.foundation>
whitelisted.insert("mk5SSx4kdexENHzLxk9FLhQdbbBexHUFTW"); // dexX7 <dexx@bitwatch.co>
// Add manually whitelisted sources
if (mapArgs.count("-omnialertallowsender")) {
const std::vector<std::string>& sources = mapMultiArgs["-omnialertallowsender"];
for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
whitelisted.insert(*it);
}
}
// Remove manually ignored sources
if (mapArgs.count("-omnialertignoresender")) {
const std::vector<std::string>& sources = mapMultiArgs["-omnialertignoresender"];
for (std::vector<std::string>::const_iterator it = sources.begin(); it != sources.end(); ++it) {
whitelisted.erase(*it);
}
}
bool fAuthorized = (whitelisted.count(sender) ||
whitelisted.count("any"));
return fAuthorized;
}
/**
* Alerts including meta data.
*/
std::vector<AlertData> GetOmniCoreAlerts()
{
return currentOmniAlerts;
}
/**
* Human readable alert messages.
*/
std::vector<std::string> GetOmniCoreAlertMessages()
{
std::vector<std::string> vstr;
for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); it++) {
vstr.push_back((*it).alert_message);
}
return vstr;
}
/**
* Expires any alerts that need expiring.
*/
bool CheckExpiredAlerts(unsigned int curBlock, uint64_t curTime)
{
for (std::vector<AlertData>::iterator it = currentOmniAlerts.begin(); it != currentOmniAlerts.end(); ) {
AlertData alert = *it;
switch (alert.alert_type) {
case 1: // alert expiring by block number
if (curBlock >= alert.alert_expiry) {
PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
} else {
it++;
}
break;
case 2: // alert expiring by block time
if (curTime > alert.alert_expiry) {
PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
} else {
it++;
}
break;
case 3: // alert expiring by client version
if (OMNICORE_VERSION > alert.alert_expiry) {
PrintToLog("Expiring alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
} else {
it++;
}
break;
default: // unrecognized alert type
PrintToLog("Removing invalid alert (type:%d expiry:%d message:%s)\n", alert.alert_type, alert.alert_expiry, alert.alert_message);
it = currentOmniAlerts.erase(it);
uiInterface.OmniStateChanged();
break;
}
}
return true;
}
} // namespace mastercore
<|endoftext|>
|
<commit_before>#ifndef __NOD_UTIL_HPP__
#define __NOD_UTIL_HPP__
#if _WIN32 && UNICODE
#include <wctype.h>
#include <direct.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#endif
#else
#include <ctype.h>
#endif
#include <sys/stat.h>
#include <string>
#include <algorithm>
#include <LogVisor/LogVisor.hpp>
namespace NOD
{
/* Log Module */
extern LogVisor::LogModule LogModule;
/* filesystem char type */
#if _WIN32 && UNICODE
#define NOD_UCS2 1
typedef struct _stat Sstat;
static inline int Mkdir(const wchar_t* path, int) {return _wmkdir(path);}
static inline int Stat(const wchar_t* path, Sstat* statout) {return _wstat(path, statout);}
#else
typedef struct stat Sstat;
static inline int Mkdir(const char* path, mode_t mode) {return mkdir(path, mode);}
static inline int Stat(const char* path, Sstat* statout) {return stat(path, statout);}
#endif
/* String-converting views */
#if NOD_UCS2
typedef wchar_t SystemChar;
typedef std::wstring SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towlower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towupper);}
class SystemUTF8View
{
std::string m_utf8;
public:
SystemUTF8View(const SystemString& str)
{
int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0, nullptr, nullptr);
m_utf8.assign('\0', len);
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), &m_utf8[0], len, nullptr, nullptr);
}
inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
std::wstring m_sys;
public:
SystemStringView(const std::string& str)
{
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0);
m_sys.assign(L'\0', len);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), &m_sys[0], len);
}
inline const std::wstring& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) L ## val
#endif
#else
typedef char SystemChar;
typedef std::string SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), tolower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), toupper);}
class SystemUTF8View
{
const std::string& m_utf8;
public:
SystemUTF8View(const SystemString& str)
: m_utf8(str) {}
inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
const std::string& m_sys;
public:
SystemStringView(const std::string& str)
: m_sys(str) {}
inline const std::string& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) val
#endif
#endif
/* Type-sensitive byte swappers */
template <typename T>
static inline T bswap16(T val)
{
#if __GNUC__
return __builtin_bswap16(val);
#elif _WIN32
return _byteswap_ushort(val);
#else
return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif
}
template <typename T>
static inline T bswap32(T val)
{
#if __GNUC__
return __builtin_bswap32(val);
#elif _WIN32
return _byteswap_ulong(val);
#else
val = (val & 0x0000FFFF) << 16 | (val & 0xFFFF0000) >> 16;
val = (val & 0x00FF00FF) << 8 | (val & 0xFF00FF00) >> 8;
return val;
#endif
}
template <typename T>
static inline T bswap64(T val)
{
#if __GNUC__
return __builtin_bswap64(val);
#elif _WIN32
return _byteswap_uint64(val);
#else
return ((val & 0xFF00000000000000ULL) >> 56) |
((val & 0x00FF000000000000ULL) >> 40) |
((val & 0x0000FF0000000000ULL) >> 24) |
((val & 0x000000FF00000000ULL) >> 8) |
((val & 0x00000000FF000000ULL) << 8) |
((val & 0x0000000000FF0000ULL) << 24) |
((val & 0x000000000000FF00ULL) << 40) |
((val & 0x00000000000000FFULL) << 56);
#endif
}
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static inline int16_t SBig(int16_t val) {return bswap16(val);}
static inline uint16_t SBig(uint16_t val) {return bswap16(val);}
static inline int32_t SBig(int32_t val) {return bswap32(val);}
static inline uint32_t SBig(uint32_t val) {return bswap32(val);}
static inline int64_t SBig(int64_t val) {return bswap64(val);}
static inline uint64_t SBig(uint64_t val) {return bswap64(val);}
static inline int16_t SLittle(int16_t val) {return val;}
static inline uint16_t SLittle(uint16_t val) {return val;}
static inline int32_t SLittle(int32_t val) {return val;}
static inline uint32_t SLittle(uint32_t val) {return val;}
static inline int64_t SLittle(int64_t val) {return val;}
static inline uint64_t SLittle(uint64_t val) {return val;}
#else
static inline int16_t SLittle(int16_t val) {return bswap16(val);}
static inline uint16_t SLittle(uint16_t val) {return bswap16(val);}
static inline int32_t SLittle(int32_t val) {return bswap32(val);}
static inline uint32_t SLittle(uint32_t val) {return bswap32(val);}
static inline int64_t SLittle(int64_t val) {return bswap64(val);}
static inline uint64_t SLittle(uint64_t val) {return bswap64(val);}
static inline int16_t SBig(int16_t val) {return val;}
static inline uint16_t SBig(uint16_t val) {return val;}
static inline int32_t SBig(int32_t val) {return val;}
static inline uint32_t SBig(uint32_t val) {return val;}
static inline int64_t SBig(int64_t val) {return val;}
static inline uint64_t SBig(uint64_t val) {return val;}
#endif
}
#endif // __NOD_UTIL_HPP__
<commit_msg>string conversion fix for windows<commit_after>#ifndef __NOD_UTIL_HPP__
#define __NOD_UTIL_HPP__
#if _WIN32 && UNICODE
#include <wctype.h>
#include <direct.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#endif
#else
#include <ctype.h>
#endif
#include <sys/stat.h>
#include <string>
#include <algorithm>
#include <LogVisor/LogVisor.hpp>
namespace NOD
{
/* Log Module */
extern LogVisor::LogModule LogModule;
/* filesystem char type */
#if _WIN32 && UNICODE
#define NOD_UCS2 1
typedef struct _stat Sstat;
static inline int Mkdir(const wchar_t* path, int) {return _wmkdir(path);}
static inline int Stat(const wchar_t* path, Sstat* statout) {return _wstat(path, statout);}
#else
typedef struct stat Sstat;
static inline int Mkdir(const char* path, mode_t mode) {return mkdir(path, mode);}
static inline int Stat(const char* path, Sstat* statout) {return stat(path, statout);}
#endif
/* String-converting views */
#if NOD_UCS2
typedef wchar_t SystemChar;
typedef std::wstring SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towlower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towupper);}
class SystemUTF8View
{
std::string m_utf8;
public:
SystemUTF8View(const SystemString& str)
{
int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0, nullptr, nullptr);
m_utf8.assign(len, '\0');
WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), &m_utf8[0], len, nullptr, nullptr);
}
inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
std::wstring m_sys;
public:
SystemStringView(const std::string& str)
{
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0);
m_sys.assign(len, L'\0');
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), &m_sys[0], len);
}
inline const std::wstring& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) L ## val
#endif
#else
typedef char SystemChar;
typedef std::string SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), tolower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), toupper);}
class SystemUTF8View
{
const std::string& m_utf8;
public:
SystemUTF8View(const SystemString& str)
: m_utf8(str) {}
inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
const std::string& m_sys;
public:
SystemStringView(const std::string& str)
: m_sys(str) {}
inline const std::string& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) val
#endif
#endif
/* Type-sensitive byte swappers */
template <typename T>
static inline T bswap16(T val)
{
#if __GNUC__
return __builtin_bswap16(val);
#elif _WIN32
return _byteswap_ushort(val);
#else
return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif
}
template <typename T>
static inline T bswap32(T val)
{
#if __GNUC__
return __builtin_bswap32(val);
#elif _WIN32
return _byteswap_ulong(val);
#else
val = (val & 0x0000FFFF) << 16 | (val & 0xFFFF0000) >> 16;
val = (val & 0x00FF00FF) << 8 | (val & 0xFF00FF00) >> 8;
return val;
#endif
}
template <typename T>
static inline T bswap64(T val)
{
#if __GNUC__
return __builtin_bswap64(val);
#elif _WIN32
return _byteswap_uint64(val);
#else
return ((val & 0xFF00000000000000ULL) >> 56) |
((val & 0x00FF000000000000ULL) >> 40) |
((val & 0x0000FF0000000000ULL) >> 24) |
((val & 0x000000FF00000000ULL) >> 8) |
((val & 0x00000000FF000000ULL) << 8) |
((val & 0x0000000000FF0000ULL) << 24) |
((val & 0x000000000000FF00ULL) << 40) |
((val & 0x00000000000000FFULL) << 56);
#endif
}
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static inline int16_t SBig(int16_t val) {return bswap16(val);}
static inline uint16_t SBig(uint16_t val) {return bswap16(val);}
static inline int32_t SBig(int32_t val) {return bswap32(val);}
static inline uint32_t SBig(uint32_t val) {return bswap32(val);}
static inline int64_t SBig(int64_t val) {return bswap64(val);}
static inline uint64_t SBig(uint64_t val) {return bswap64(val);}
static inline int16_t SLittle(int16_t val) {return val;}
static inline uint16_t SLittle(uint16_t val) {return val;}
static inline int32_t SLittle(int32_t val) {return val;}
static inline uint32_t SLittle(uint32_t val) {return val;}
static inline int64_t SLittle(int64_t val) {return val;}
static inline uint64_t SLittle(uint64_t val) {return val;}
#else
static inline int16_t SLittle(int16_t val) {return bswap16(val);}
static inline uint16_t SLittle(uint16_t val) {return bswap16(val);}
static inline int32_t SLittle(int32_t val) {return bswap32(val);}
static inline uint32_t SLittle(uint32_t val) {return bswap32(val);}
static inline int64_t SLittle(int64_t val) {return bswap64(val);}
static inline uint64_t SLittle(uint64_t val) {return bswap64(val);}
static inline int16_t SBig(int16_t val) {return val;}
static inline uint16_t SBig(uint16_t val) {return val;}
static inline int32_t SBig(int32_t val) {return val;}
static inline uint32_t SBig(uint32_t val) {return val;}
static inline int64_t SBig(int64_t val) {return val;}
static inline uint64_t SBig(uint64_t val) {return val;}
#endif
}
#endif // __NOD_UTIL_HPP__
<|endoftext|>
|
<commit_before>
// Copyright (c) 2014 niXman (i dotty nixman doggy gmail dotty com)
// All rights reserved.
//
// This file is part of aescrypt(https://github.com/niXman/aescrypt) project.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// Neither the name of the {organization} nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _aescrypt__aescrypt_hpp
#define _aescrypt__aescrypt_hpp
#include <cstdint>
#include <memory>
namespace aescrypt {
/***************************************************************************/
enum key_length {
AES128=128
,AES192=192
,AES256=256
};
/***************************************************************************/
struct cryptor {
using buffer_type = std::unique_ptr<char[]>;
cryptor(const char *key, const key_length klen);
~cryptor();
key_length get_key_length() const;
void encrypt(char *dst, const char *src, const std::size_t len) const;
void decrypt(char *dst, const char *src, const std::size_t len) const;
buffer_type encrypt(const char *src, const std::size_t len) const;
buffer_type decrypt(const char *src, const std::size_t len) const;
std::string encrypt(const std::string &src) const;
std::string decrypt(const std::string &src) const;
private:
struct impl;
impl *pimpl;
}; // struct cryptor
/***************************************************************************/
} // ns aesni
#endif // _aescrypt__aescrypt_hpp
<commit_msg>Update aescrypt.hpp<commit_after>
// Copyright (c) 2014-2015 niXman (i dotty nixman doggy gmail dotty com)
// All rights reserved.
//
// This file is part of aescrypt(https://github.com/niXman/aescrypt) project.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this
// list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// Neither the name of the {organization} nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef _aescrypt__aescrypt_hpp
#define _aescrypt__aescrypt_hpp
#include <cstdint>
#include <memory>
namespace aescrypt {
/***************************************************************************/
enum key_length {
AES128=128
,AES192=192
,AES256=256
};
/***************************************************************************/
struct cryptor {
using buffer_type = std::unique_ptr<char[]>;
cryptor(const char *key, const key_length klen);
~cryptor();
key_length get_key_length() const;
void encrypt(char *dst, const char *src, const std::size_t len) const;
void decrypt(char *dst, const char *src, const std::size_t len) const;
buffer_type encrypt(const char *src, const std::size_t len) const;
buffer_type decrypt(const char *src, const std::size_t len) const;
std::string encrypt(const std::string &src) const;
std::string decrypt(const std::string &src) const;
private:
struct impl;
impl *pimpl;
}; // struct cryptor
/***************************************************************************/
} // ns aesni
#endif // _aescrypt__aescrypt_hpp
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2015-2016 Nagisa Sekiguchi
*
* 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 AQUARIUS_CXX_AQUARIUS_HPP
#define AQUARIUS_CXX_AQUARIUS_HPP
#include "internal/expression.hpp"
#include "internal/mapper.hpp"
#include "internal/parser.hpp"
#include "internal/combinator.hpp"
// helper macro
#define aquarius_pattern_t constexpr auto
#define AQUARIUS_DEFINE_RULE(R, name, p) \
template <typename T> \
struct name ## __impl { \
using name = name ## __impl<R>;\
static_assert(std::is_same<T, std::remove_reference<decltype(p)>::type::retType>::value, "must be same type");\
static constexpr auto pattern() { return p; }\
}; using name = name ## __impl<R>
#define AQUARIUS_DECL_RULE(R, name) \
template <typename T> struct name ## __impl; using name = name ## __impl<R>
#endif //AQUARIUS_CXX_AQUARIUS_HPP
<commit_msg>fix build error in older gcc<commit_after>/*
* Copyright (C) 2015-2016 Nagisa Sekiguchi
*
* 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 AQUARIUS_CXX_AQUARIUS_HPP
#define AQUARIUS_CXX_AQUARIUS_HPP
#include "internal/expression.hpp"
#include "internal/mapper.hpp"
#include "internal/parser.hpp"
#include "internal/combinator.hpp"
// helper macro
#define aquarius_pattern_t constexpr auto
#define AQUARIUS_DEFINE_RULE(R, name, p) \
template <typename T> \
struct name ## __impl { \
using name = name ## __impl<R>;\
static_assert(std::is_same<T, std::remove_reference<decltype(p)>::type::retType>::value, "must be same type");\
static constexpr auto pattern() std::remove_reference<decltype(p)>::type { return p; }\
}; using name = name ## __impl<R>
#define AQUARIUS_DECL_RULE(R, name) \
template <typename T> struct name ## __impl; using name = name ## __impl<R>
#endif //AQUARIUS_CXX_AQUARIUS_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
#include "Variant.h"
/// Method to enable unit testing of C++ variant calls from pytest
Scalar testVariantCall(std::shared_ptr<Variant> t, uint64_t step)
{
return (*t)(step);
}
/// Method to enable unit testing of C++ variant min class from pytest
Scalar testVariantMin(std::shared_ptr<Variant> t)
{
return t->min();
}
/// Method to enable unit testing of C++ variant max class from pytest
Scalar testVariantMax(std::shared_ptr<Variant> t)
{
return t->max();
}
//* Trampoline for classes inherited in python
class VariantPy : public Variant
{
public:
// Inherit the constructors
using Variant::Variant;
// trampoline method
Scalar operator()(uint64_t timestep) override
{
PYBIND11_OVERLOAD_NAME(Scalar, // Return type
Variant, // Parent class
"__call__", // name of function in python
operator(), // Name of function in C++
timestep // Argument(s)
);
}
Scalar min() override
{
PYBIND11_OVERLOAD_PURE_NAME(Scalar, // Return type
Variant, // Parent class
"_min", // name of function in python
min // name of function
);
}
Scalar max() override
{
PYBIND11_OVERLOAD_PURE_NAME(Scalar, // Return type
Variant, // Parent class
"_max", // name of function in python
max // name of function
);
}
};
void export_Variant(pybind11::module& m)
{
pybind11::class_<Variant, VariantPy, std::shared_ptr<Variant> >(m,"Variant")
.def(pybind11::init<>())
.def("__call__", &Variant::operator())
.def("_min", &Variant::min)
.def("_max", &Variant::max)
.def_property_readonly("range", &Variant::range)
;
pybind11::class_<VariantConstant, Variant, std::shared_ptr<VariantConstant> >(m, "VariantConstant")
.def(pybind11::init< Scalar >(), pybind11::arg("value"))
.def_property("value", &VariantConstant::getValue, &VariantConstant::setValue)
;
pybind11::class_<VariantRamp, Variant, std::shared_ptr<VariantRamp> >(m, "VariantRamp")
.def(pybind11::init< Scalar, Scalar, uint64_t, uint64_t >(), pybind11::arg("A"),
pybind11::arg("B"),
pybind11::arg("t_start"),
pybind11::arg("t_ramp"))
.def_property("A", &VariantRamp::getA, &VariantRamp::setA)
.def_property("B", &VariantRamp::getB, &VariantRamp::setB)
.def_property("t_start", &VariantRamp::getTStart, &VariantRamp::setTStart)
.def_property("t_ramp", &VariantRamp::getTRamp, &VariantRamp::setTRamp)
;
pybind11::class_<VariantCycle, Variant, std::shared_ptr<VariantCycle> >(m, "VariantCycle")
.def(pybind11::init< Scalar,
Scalar,
uint64_t,
uint64_t,
uint64_t,
uint64_t,
uint64_t >(),
pybind11::arg("A"),
pybind11::arg("B"),
pybind11::arg("t_start"),
pybind11::arg("t_A"),
pybind11::arg("t_AB"),
pybind11::arg("t_B"),
pybind11::arg("t_BA"))
.def_property("A", &VariantCycle::getA, &VariantCycle::setA)
.def_property("B", &VariantCycle::getB, &VariantCycle::setB)
.def_property("t_start", &VariantCycle::getTStart, &VariantCycle::setTStart)
.def_property("t_A", &VariantCycle::getTA, &VariantCycle::setTA)
.def_property("t_AB", &VariantCycle::getTAB, &VariantCycle::setTAB)
.def_property("t_B", &VariantCycle::getTB, &VariantCycle::setTB)
.def_property("t_BA", &VariantCycle::getTBA, &VariantCycle::setTBA)
;
pybind11::class_<VariantPower, Variant,
std::shared_ptr<VariantPower> >(m, "VariantPower")
.def(pybind11::init<Scalar, Scalar, double,
uint64_t, uint64_t>(),
pybind11::arg("A"),
pybind11::arg("B"),
pybind11::arg("power"),
pybind11::arg("t_start"),
pybind11::arg("t_ramp")
)
.def_property("A", &VariantPower::getA, &VariantPower::setA)
.def_property("B", &VariantPower::getB, &VariantPower::setB)
.def_property("power", &VariantPower::getPower,
&VariantPower::setPower)
.def_property("t_start", &VariantPower::getTStart,
&VariantPower::setTStart)
.def_property("t_size", &VariantPower::getTSize,
&VariantPower::setTSize)
;
m.def("_test_variant_call", &testVariantCall);
m.def("_test_variant_min", &testVariantMin);
m.def("_test_variant_max", &testVariantMax);
}
<commit_msg>Add developer comments.<commit_after>// Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
#include "Variant.h"
// These testVariant{Method} functions allow us to test that Python custom
// variants work properly in C++. This ensures we can test that the function
// itself can be called in C++ when defined in Python.
/// Method to enable unit testing of C++ variant calls from pytest
Scalar testVariantCall(std::shared_ptr<Variant> t, uint64_t step)
{
return (*t)(step);
}
/// Method to enable unit testing of C++ variant min class from pytest
Scalar testVariantMin(std::shared_ptr<Variant> t)
{
return t->min();
}
/// Method to enable unit testing of C++ variant max class from pytest
Scalar testVariantMax(std::shared_ptr<Variant> t)
{
return t->max();
}
//* Trampoline for classes inherited in python
class VariantPy : public Variant
{
public:
// Inherit the constructors
using Variant::Variant;
// trampoline method
Scalar operator()(uint64_t timestep) override
{
PYBIND11_OVERLOAD_NAME(Scalar, // Return type
Variant, // Parent class
"__call__", // name of function in python
operator(), // Name of function in C++
timestep // Argument(s)
);
}
Scalar min() override
{
PYBIND11_OVERLOAD_PURE_NAME(Scalar, // Return type
Variant, // Parent class
"_min", // name of function in python
min // name of function
);
}
Scalar max() override
{
PYBIND11_OVERLOAD_PURE_NAME(Scalar, // Return type
Variant, // Parent class
"_max", // name of function in python
max // name of function
);
}
};
void export_Variant(pybind11::module& m)
{
pybind11::class_<Variant, VariantPy, std::shared_ptr<Variant> >(m,"Variant")
.def(pybind11::init<>())
.def("__call__", &Variant::operator())
.def("_min", &Variant::min)
.def("_max", &Variant::max)
.def_property_readonly("range", &Variant::range)
;
pybind11::class_<VariantConstant, Variant, std::shared_ptr<VariantConstant> >(m, "VariantConstant")
.def(pybind11::init< Scalar >(), pybind11::arg("value"))
.def_property("value", &VariantConstant::getValue, &VariantConstant::setValue)
;
pybind11::class_<VariantRamp, Variant, std::shared_ptr<VariantRamp> >(m, "VariantRamp")
.def(pybind11::init< Scalar, Scalar, uint64_t, uint64_t >(), pybind11::arg("A"),
pybind11::arg("B"),
pybind11::arg("t_start"),
pybind11::arg("t_ramp"))
.def_property("A", &VariantRamp::getA, &VariantRamp::setA)
.def_property("B", &VariantRamp::getB, &VariantRamp::setB)
.def_property("t_start", &VariantRamp::getTStart, &VariantRamp::setTStart)
.def_property("t_ramp", &VariantRamp::getTRamp, &VariantRamp::setTRamp)
;
pybind11::class_<VariantCycle, Variant, std::shared_ptr<VariantCycle> >(m, "VariantCycle")
.def(pybind11::init< Scalar,
Scalar,
uint64_t,
uint64_t,
uint64_t,
uint64_t,
uint64_t >(),
pybind11::arg("A"),
pybind11::arg("B"),
pybind11::arg("t_start"),
pybind11::arg("t_A"),
pybind11::arg("t_AB"),
pybind11::arg("t_B"),
pybind11::arg("t_BA"))
.def_property("A", &VariantCycle::getA, &VariantCycle::setA)
.def_property("B", &VariantCycle::getB, &VariantCycle::setB)
.def_property("t_start", &VariantCycle::getTStart, &VariantCycle::setTStart)
.def_property("t_A", &VariantCycle::getTA, &VariantCycle::setTA)
.def_property("t_AB", &VariantCycle::getTAB, &VariantCycle::setTAB)
.def_property("t_B", &VariantCycle::getTB, &VariantCycle::setTB)
.def_property("t_BA", &VariantCycle::getTBA, &VariantCycle::setTBA)
;
pybind11::class_<VariantPower, Variant,
std::shared_ptr<VariantPower> >(m, "VariantPower")
.def(pybind11::init<Scalar, Scalar, double,
uint64_t, uint64_t>(),
pybind11::arg("A"),
pybind11::arg("B"),
pybind11::arg("power"),
pybind11::arg("t_start"),
pybind11::arg("t_ramp")
)
.def_property("A", &VariantPower::getA, &VariantPower::setA)
.def_property("B", &VariantPower::getB, &VariantPower::setB)
.def_property("power", &VariantPower::getPower,
&VariantPower::setPower)
.def_property("t_start", &VariantPower::getTStart,
&VariantPower::setTStart)
.def_property("t_size", &VariantPower::getTSize,
&VariantPower::setTSize)
;
m.def("_test_variant_call", &testVariantCall);
m.def("_test_variant_min", &testVariantMin);
m.def("_test_variant_max", &testVariantMax);
}
<|endoftext|>
|
<commit_before>#include "OGLESGPGPUTest.h"
#include "ogles_gpgpu/common/gl/memtransfer_optimized.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#define INITIAL_PROC_TYPE 1
_GATHERER_GRAPHICS_BEGIN
class MemTransferScopeLock
{
public:
MemTransferScopeLock(ogles_gpgpu::MemTransferOptimized *transfer) : transfer(transfer)
{
ptr = transfer->lockBufferAndGetPtr(ogles_gpgpu::BUF_TYPE_OUTPUT);
}
~MemTransferScopeLock()
{
transfer->unlockBuffer(ogles_gpgpu::BUF_TYPE_OUTPUT);
}
const void *data() const { return ptr; }
operator const void *() const { return ptr; }
protected:
const void *ptr = 0;
ogles_gpgpu::MemTransferOptimized *transfer = 0;
};
OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const float resolution)
: glContext(glContext)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationStd)
{
initCam();
initOGLESGPGPU(glContext);
}
OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const cv::Size &screenSize, const float resolution)
: glContext(glContext)
, screenSize(screenSize)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored)
{
initCam();
initOGLESGPGPU(glContext);
}
OEGLGPGPUTest::~OEGLGPGPUTest()
{
ogles_gpgpu::Core::destroy();
gpgpuMngr = 0;
}
void OEGLGPGPUTest::initCam()
{
/*
* Some temporary code to test the optimized gpu to cpu frame handler.
* This should be instantiated form a higher level (i.e., main.cpp)
* but this class hasn't been allocated at that point yet. This at
* least supports testing of the concept.
*/
#define TEST_FRAME_HANDLER 0
#if TEST_FRAME_HANDLER
frameHandler = [](const cv::Mat &frame)
{
std::stringstream ss;
ss << getenv("HOME") << "/Documents/frame.png";
cv::imwrite(ss.str(), frame);
};
#endif
}
void OEGLGPGPUTest::initOGLESGPGPU(void* glContext)
{
// get ogles_gpgpu::Core singleton instance
gpgpuMngr = ogles_gpgpu::Core::getInstance();
// enable iOS optimizations (fast texture access)
ogles_gpgpu::Core::tryEnablePlatformOptimizations();
// do not use mipmaps (will not work with NPOT images)
gpgpuMngr->setUseMipmaps(false);
// create the pipeline
initGPUPipeline(5);
outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);
// initialize the pipeline (TODO)
gpgpuMngr->init(glContext);
}
void OEGLGPGPUTest::setDisplaySize(int width, int height)
{
outputDispRenderer->setOutputSize(width, height);
}
void OEGLGPGPUTest::initGPUPipeline(int type)
{
if (selectedProcType == type) return; // no change
// reset the pipeline
gpgpuMngr->reset();
// create the pipeline
if (type == 1)
{
gpgpuMngr->addProcToPipeline(&grayscaleProc);
gpgpuMngr->addProcToPipeline(&adaptThreshProc);
}
else if (type == 2)
{
gpgpuMngr->addProcToPipeline(&grayscaleProc);
gpgpuMngr->addProcToPipeline(&simpleThreshProc);
}
else if (type == 3)
{
gpgpuMngr->addProcToPipeline(&gaussProc);
}
else if (type == 4)
{
#define USE_TRANSFORM1 1
#define USE_TRANSFORM2 0
#if USE_TRANSFORM1
ogles_gpgpu::Mat44f transformMatrix =
{{
{1.f,0.f,0.f,0.f},
{0.f,1.f,0.f,0.f},
{0.f,0.f,0.f,0.f},
{0.f,0.f,0.f,1.f}
}};
// Use this to place the texture upright for processing (object, detection, etc)
transformProc1.setTransformMatrix(transformMatrix);
transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
transformProc1.setOutputSize(0.25);
gpgpuMngr->addProcToPipeline(&transformProc1);
#endif
gpgpuMngr->addProcToPipeline(&grayscaleProc);
#if USE_TRANSFORM2
// Use this to place the texture back in the native orientation (and aspect ratio)
// provided by the QML Camera since the QML VideoOutput object that displays the
// frames is expecting that and I don't see a trivial way to work around that.
// It seems we need to override either the VideoObject class or encapsulate this
// native processing pipeline in some kind of ExtendedCamera qml object that
// reports the size and orientation of the final processed texture. Since this
// is all on the GPU it may not matter much from a performance standpoint.
//
// TODO: investigate QT mechanism for avoiding this.
transformProc2.setTransformMatrix(transformMatrix);
transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
transformProc2.setOutputSize(0.25);
gpgpuMngr->addProcToPipeline(&transformProc2);
#endif
}
else if (type == 5) // upright transformation
{
auto interpolation = ogles_gpgpu::TransformProc::BICUBIC;
transformProc1.setInterpolation(interpolation);
float theta = 15.0 * M_PI / 180.0;
float ct = std::cos(theta);
float st = std::sin(theta);
ogles_gpgpu::Mat44f transformMatrix1, transformMatrix2;
transformMatrix1 = transformMatrix2 =
{{
{1.f,0.f,0.f,0.f},
{0.f,1.f,0.f,0.f},
{0.f,0.f,0.f,0.f},
{0.f,0.f,0.f,1.f}
}};
transformMatrix2.data[0][0] = +ct;
transformMatrix2.data[1][1] = +ct;
transformMatrix2.data[1][0] = +st;
transformMatrix2.data[0][1] = -st;
// Use this to place the texture upright for processing (object, detection, etc)
transformProc1.setTransformMatrix(transformMatrix1); // don't rotate
transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
transformProc1.setOutputSize(0.25);
gpgpuMngr->addProcToPipeline(&transformProc1);
transformProc2.setInterpolation(interpolation);
transformProc2.setTransformMatrix(transformMatrix2); // rotate output
transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
transformProc2.setOutputSize(1.0);
gpgpuMngr->addProcToPipeline(&transformProc2);
}
else
{
std::cout << "GPU pipeline definition #%d not supported" << type << std::endl;
}
// create the display renderer with which we can directly render the output
// to the screen via OpenGL
outputDispRenderer = gpgpuMngr->createRenderDisplay(screenSize.width, screenSize.height, dispRenderOrientation);
outputDispRenderer->setDisplayResolution(resolution, resolution);
// reset this to call prepareForFramesOfSize again
firstFrame = true;
if (prepared)
{
prepared = false;
}
}
GLuint OEGLGPGPUTest::getDisplayTexture() const
{
return outputDispRenderer->getOutputTexId();
}
GLuint OEGLGPGPUTest::getInputTexture() const
{
return gpgpuInputHandler->getInputTexId();
}
GLuint OEGLGPGPUTest::getOutputTexture() const
{
return gpgpuInputHandler->getOutputTexId();
}
GLuint OEGLGPGPUTest::getLastShaderOutputTexture() const
{
return gpgpuMngr->getOutputTexId();
}
cv::Size OEGLGPGPUTest::getOutputSize() const
{
return cv::Size(gpgpuMngr->getOutputFrameW(), gpgpuMngr->getOutputFrameH());
}
void OEGLGPGPUTest::captureOutput(cv::Size size, void* pixelBuffer, bool useRawPixels, GLuint inputTexture, GLenum inputPixFormat)
{
// when we get the first frame, prepare the system for the size of the incoming frames
if (firstFrame)
{
frameSize = size;
if(!screenSize.area())
{
screenSize = frameSize;
}
prepareForFrameOfSize(frameSize);
outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);
// YUV:
yuv2RgbProc.init(frameSize.width, frameSize.height, 0, true); // TODO: NEW
yuv2RgbProc.createFBOTex(false);
firstFrame = false;
}
gpgpuInputHandler->setUseRawPixels(useRawPixels);
// on each new frame, this will release the input buffers and textures, and prepare new ones
// texture format must be GL_BGRA because this is one of the native camera formats (see initCam)
if(inputPixFormat == 0)
{
// YUV: Special case NV12=>BGR
auto manager = yuv2RgbProc.getMemTransferObj();
manager->setUseRawPixels(true);
manager->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);
yuv2RgbProc.setTextures(manager->getLuminanceTexId(), manager->getChrominanceTexId());
yuv2RgbProc.render();
glFinish();
inputTexture = yuv2RgbProc.getOutputTexId(); // will be used below
gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, GL_NONE, nullptr);
}
else
{
gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);
}
// set the input texture id - we do not copy any data, we use the camera frame directly as texture!
if (inputTexture)
{
gpgpuMngr->setInputTexId(inputTexture);
}
else
{
gpgpuMngr->setInputTexId(gpgpuInputHandler->getInputTexId());
}
// run processing pipeline
gpgpuMngr->process();
#if 1
if(frameHandler)
{
auto transfer = dynamic_cast<ogles_gpgpu::MemTransferOptimized *>(gpgpuMngr->getOutputMemTransfer());
if(transfer)
{
MemTransferScopeLock data(transfer);
cv::Size outSize(transformProc1.getOutFrameW(), transformProc1.getOutFrameH());
cv::Mat frame(outSize.height, outSize.width, CV_8UC4, (void *)data.data());
frameHandler(frame);
}
}
#endif
std::cerr << "Skipping render..." << std::endl;
return;
// update the GL view to display the output directly
outputDispRenderer->render();
}
void OEGLGPGPUTest::prepareForFrameOfSize(const cv::Size &size)
{
float frameAspectRatio = size.width / size.height;
fprintf(stderr, "camera frames are of size %dx%d (aspect %f)\n", (int)size.width, (int)size.height, frameAspectRatio);
// prepare ogles_gpgpu for the incoming frame size
// GL_NONE means that the input memory transfer object is NOT prepared
// this will be done in captureOutput: on each new frame
#if __ANDROID__
gpgpuMngr->prepare(size.width, size.height, true ? GL_RGBA : GL_NONE);
#else
gpgpuMngr->prepare(size.width, size.height, true ? GL_BGRA : GL_NONE);
#endif
gpgpuInputHandler = gpgpuMngr->getInputMemTransfer();
// everything prepared
prepared = true;
}
_GATHERER_GRAPHICS_END
<commit_msg>useRawPixels may be false<commit_after>#include "OGLESGPGPUTest.h"
#include "ogles_gpgpu/common/gl/memtransfer_optimized.h"
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#define INITIAL_PROC_TYPE 1
_GATHERER_GRAPHICS_BEGIN
class MemTransferScopeLock
{
public:
MemTransferScopeLock(ogles_gpgpu::MemTransferOptimized *transfer) : transfer(transfer)
{
ptr = transfer->lockBufferAndGetPtr(ogles_gpgpu::BUF_TYPE_OUTPUT);
}
~MemTransferScopeLock()
{
transfer->unlockBuffer(ogles_gpgpu::BUF_TYPE_OUTPUT);
}
const void *data() const { return ptr; }
operator const void *() const { return ptr; }
protected:
const void *ptr = 0;
ogles_gpgpu::MemTransferOptimized *transfer = 0;
};
OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const float resolution)
: glContext(glContext)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationStd)
{
initCam();
initOGLESGPGPU(glContext);
}
OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const cv::Size &screenSize, const float resolution)
: glContext(glContext)
, screenSize(screenSize)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored)
{
initCam();
initOGLESGPGPU(glContext);
}
OEGLGPGPUTest::~OEGLGPGPUTest()
{
ogles_gpgpu::Core::destroy();
gpgpuMngr = 0;
}
void OEGLGPGPUTest::initCam()
{
/*
* Some temporary code to test the optimized gpu to cpu frame handler.
* This should be instantiated form a higher level (i.e., main.cpp)
* but this class hasn't been allocated at that point yet. This at
* least supports testing of the concept.
*/
#define TEST_FRAME_HANDLER 0
#if TEST_FRAME_HANDLER
frameHandler = [](const cv::Mat &frame)
{
std::stringstream ss;
ss << getenv("HOME") << "/Documents/frame.png";
cv::imwrite(ss.str(), frame);
};
#endif
}
void OEGLGPGPUTest::initOGLESGPGPU(void* glContext)
{
// get ogles_gpgpu::Core singleton instance
gpgpuMngr = ogles_gpgpu::Core::getInstance();
// enable iOS optimizations (fast texture access)
ogles_gpgpu::Core::tryEnablePlatformOptimizations();
// do not use mipmaps (will not work with NPOT images)
gpgpuMngr->setUseMipmaps(false);
// create the pipeline
initGPUPipeline(5);
outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);
// initialize the pipeline (TODO)
gpgpuMngr->init(glContext);
}
void OEGLGPGPUTest::setDisplaySize(int width, int height)
{
outputDispRenderer->setOutputSize(width, height);
}
void OEGLGPGPUTest::initGPUPipeline(int type)
{
if (selectedProcType == type) return; // no change
// reset the pipeline
gpgpuMngr->reset();
// create the pipeline
if (type == 1)
{
gpgpuMngr->addProcToPipeline(&grayscaleProc);
gpgpuMngr->addProcToPipeline(&adaptThreshProc);
}
else if (type == 2)
{
gpgpuMngr->addProcToPipeline(&grayscaleProc);
gpgpuMngr->addProcToPipeline(&simpleThreshProc);
}
else if (type == 3)
{
gpgpuMngr->addProcToPipeline(&gaussProc);
}
else if (type == 4)
{
#define USE_TRANSFORM1 1
#define USE_TRANSFORM2 0
#if USE_TRANSFORM1
ogles_gpgpu::Mat44f transformMatrix =
{{
{1.f,0.f,0.f,0.f},
{0.f,1.f,0.f,0.f},
{0.f,0.f,0.f,0.f},
{0.f,0.f,0.f,1.f}
}};
// Use this to place the texture upright for processing (object, detection, etc)
transformProc1.setTransformMatrix(transformMatrix);
transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
transformProc1.setOutputSize(0.25);
gpgpuMngr->addProcToPipeline(&transformProc1);
#endif
gpgpuMngr->addProcToPipeline(&grayscaleProc);
#if USE_TRANSFORM2
// Use this to place the texture back in the native orientation (and aspect ratio)
// provided by the QML Camera since the QML VideoOutput object that displays the
// frames is expecting that and I don't see a trivial way to work around that.
// It seems we need to override either the VideoObject class or encapsulate this
// native processing pipeline in some kind of ExtendedCamera qml object that
// reports the size and orientation of the final processed texture. Since this
// is all on the GPU it may not matter much from a performance standpoint.
//
// TODO: investigate QT mechanism for avoiding this.
transformProc2.setTransformMatrix(transformMatrix);
transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
transformProc2.setOutputSize(0.25);
gpgpuMngr->addProcToPipeline(&transformProc2);
#endif
}
else if (type == 5) // upright transformation
{
auto interpolation = ogles_gpgpu::TransformProc::BICUBIC;
transformProc1.setInterpolation(interpolation);
float theta = 15.0 * M_PI / 180.0;
float ct = std::cos(theta);
float st = std::sin(theta);
ogles_gpgpu::Mat44f transformMatrix1, transformMatrix2;
transformMatrix1 = transformMatrix2 =
{{
{1.f,0.f,0.f,0.f},
{0.f,1.f,0.f,0.f},
{0.f,0.f,0.f,0.f},
{0.f,0.f,0.f,1.f}
}};
transformMatrix2.data[0][0] = +ct;
transformMatrix2.data[1][1] = +ct;
transformMatrix2.data[1][0] = +st;
transformMatrix2.data[0][1] = -st;
// Use this to place the texture upright for processing (object, detection, etc)
transformProc1.setTransformMatrix(transformMatrix1); // don't rotate
transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
transformProc1.setOutputSize(0.25);
gpgpuMngr->addProcToPipeline(&transformProc1);
transformProc2.setInterpolation(interpolation);
transformProc2.setTransformMatrix(transformMatrix2); // rotate output
transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
transformProc2.setOutputSize(1.0);
gpgpuMngr->addProcToPipeline(&transformProc2);
}
else
{
std::cout << "GPU pipeline definition #%d not supported" << type << std::endl;
}
// create the display renderer with which we can directly render the output
// to the screen via OpenGL
outputDispRenderer = gpgpuMngr->createRenderDisplay(screenSize.width, screenSize.height, dispRenderOrientation);
outputDispRenderer->setDisplayResolution(resolution, resolution);
// reset this to call prepareForFramesOfSize again
firstFrame = true;
if (prepared)
{
prepared = false;
}
}
GLuint OEGLGPGPUTest::getDisplayTexture() const
{
return outputDispRenderer->getOutputTexId();
}
GLuint OEGLGPGPUTest::getInputTexture() const
{
return gpgpuInputHandler->getInputTexId();
}
GLuint OEGLGPGPUTest::getOutputTexture() const
{
return gpgpuInputHandler->getOutputTexId();
}
GLuint OEGLGPGPUTest::getLastShaderOutputTexture() const
{
return gpgpuMngr->getOutputTexId();
}
cv::Size OEGLGPGPUTest::getOutputSize() const
{
return cv::Size(gpgpuMngr->getOutputFrameW(), gpgpuMngr->getOutputFrameH());
}
void OEGLGPGPUTest::captureOutput(cv::Size size, void* pixelBuffer, bool useRawPixels, GLuint inputTexture, GLenum inputPixFormat)
{
// when we get the first frame, prepare the system for the size of the incoming frames
if (firstFrame)
{
frameSize = size;
if(!screenSize.area())
{
screenSize = frameSize;
}
prepareForFrameOfSize(frameSize);
outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);
// YUV:
yuv2RgbProc.init(frameSize.width, frameSize.height, 0, true); // TODO: NEW
yuv2RgbProc.createFBOTex(false);
firstFrame = false;
}
gpgpuInputHandler->setUseRawPixels(useRawPixels);
// on each new frame, this will release the input buffers and textures, and prepare new ones
// texture format must be GL_BGRA because this is one of the native camera formats (see initCam)
if(inputPixFormat == 0)
{
// YUV: Special case NV12=>BGR
auto manager = yuv2RgbProc.getMemTransferObj();
if (useRawPixels)
{
manager->setUseRawPixels(true);
}
manager->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);
yuv2RgbProc.setTextures(manager->getLuminanceTexId(), manager->getChrominanceTexId());
yuv2RgbProc.render();
glFinish();
inputTexture = yuv2RgbProc.getOutputTexId(); // will be used below
gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, GL_NONE, nullptr);
}
else
{
gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);
}
// set the input texture id - we do not copy any data, we use the camera frame directly as texture!
if (inputTexture)
{
gpgpuMngr->setInputTexId(inputTexture);
}
else
{
gpgpuMngr->setInputTexId(gpgpuInputHandler->getInputTexId());
}
// run processing pipeline
gpgpuMngr->process();
#if 1
if(frameHandler)
{
auto transfer = dynamic_cast<ogles_gpgpu::MemTransferOptimized *>(gpgpuMngr->getOutputMemTransfer());
if(transfer)
{
MemTransferScopeLock data(transfer);
cv::Size outSize(transformProc1.getOutFrameW(), transformProc1.getOutFrameH());
cv::Mat frame(outSize.height, outSize.width, CV_8UC4, (void *)data.data());
frameHandler(frame);
}
}
#endif
std::cerr << "Skipping render..." << std::endl;
return;
// update the GL view to display the output directly
outputDispRenderer->render();
}
void OEGLGPGPUTest::prepareForFrameOfSize(const cv::Size &size)
{
float frameAspectRatio = size.width / size.height;
fprintf(stderr, "camera frames are of size %dx%d (aspect %f)\n", (int)size.width, (int)size.height, frameAspectRatio);
// prepare ogles_gpgpu for the incoming frame size
// GL_NONE means that the input memory transfer object is NOT prepared
// this will be done in captureOutput: on each new frame
#if __ANDROID__
gpgpuMngr->prepare(size.width, size.height, true ? GL_RGBA : GL_NONE);
#else
gpgpuMngr->prepare(size.width, size.height, true ? GL_BGRA : GL_NONE);
#endif
gpgpuInputHandler = gpgpuMngr->getInputMemTransfer();
// everything prepared
prepared = true;
}
_GATHERER_GRAPHICS_END
<|endoftext|>
|
<commit_before>#pragma once
#include <tuple>
#include <type_traits>
#include <limits>
#include <algorithm>
#include <initializer_list>
namespace kl {
using std::index_sequence;
using std::make_index_sequence;
template <typename T>
using make_tuple_indices =
make_index_sequence<std::tuple_size_v<std::remove_reference_t<T>>>;
namespace tuple {
// Applies a function to given tuple
struct apply_fn
{
private:
template <typename Tup, typename Fun, std::size_t... Is>
static auto impl(Tup&& tup, Fun&& fun, index_sequence<Is...>) -> decltype(
std::forward<Fun>(fun)((std::get<Is>(std::forward<Tup>(tup)))...))
{
return std::forward<Fun>(fun)(
(std::get<Is>(std::forward<Tup>(tup)))...);
}
public:
template <typename Tup, typename Fun>
static auto call(Tup&& tup, Fun&& fun)
-> decltype(apply_fn::impl(std::forward<Tup>(tup),
std::forward<Fun>(fun),
make_tuple_indices<Tup>{}))
{
return apply_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
make_tuple_indices<Tup>{});
}
};
struct for_each_fn
{
private:
template <typename Tup, typename Fun, std::size_t... Is>
static void impl(Tup&& tup, Fun&& fun, kl::index_sequence<Is...>)
{
using swallow = std::initializer_list<int>;
(void)swallow{(fun(std::get<Is>(std::forward<Tup>(tup))), 0)...};
}
public:
template <typename Tup, typename Fun>
static void call(Tup&& tup, Fun&& fun)
{
for_each_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
kl::make_tuple_indices<Tup>{});
}
};
// Transforms tuple of dereferencable to tuple of references:
// tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
// tuple<int&, double&, const short&>
struct transform_ref_fn
{
private:
template <typename Tup, std::size_t... Is>
static auto impl(Tup&& tup, index_sequence<Is...>) -> decltype(
std::tuple<decltype(*(std::get<Is>(std::forward<Tup>(tup))))...>{
(*std::get<Is>(std::forward<Tup>(tup)))...})
{
return std::tuple<decltype(*(std::get<Is>(std::forward<Tup>(tup))))...>{
(*std::get<Is>(std::forward<Tup>(tup)))...};
}
public:
template <typename Tup>
static auto call(Tup&& tup)
-> decltype(transform_ref_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{}))
{
return transform_ref_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{});
}
};
// Transforms tuple of dereferencable to tuple of dereferenced values:
// tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
// tuple<int, double, short>
struct transform_deref_fn
{
private:
template <typename Tup, std::size_t... Is>
static auto impl(Tup&& tup, index_sequence<Is...>)
-> decltype(std::make_tuple(*std::get<Is>(std::forward<Tup>(tup))...))
{
return std::make_tuple(*std::get<Is>(std::forward<Tup>(tup))...);
}
public:
template <typename Tup>
static auto call(Tup&& tup)
-> decltype(transform_deref_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{}))
{
return transform_deref_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{});
}
};
// Checks for inequality with two given tuples. We AND instead of OR to
// support zipping Sequences with different size.
struct not_equal_fn
{
private:
template <typename Tup>
static bool impl(Tup&&, Tup&&)
{
return true;
}
template <std::size_t I, std::size_t... Is, typename Tup>
static bool impl(Tup&& tup0, Tup&& tup1)
{
return std::get<I>(std::forward<Tup>(tup0)) !=
std::get<I>(std::forward<Tup>(tup1)) &&
not_equal_fn::template impl<Is...>(std::forward<Tup>(tup0),
std::forward<Tup>(tup1));
}
template <typename Tup, std::size_t... Is>
static bool impl2(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
{
return not_equal_fn::impl<Is...>(std::forward<Tup>(tup0),
std::forward<Tup>(tup1));
}
public:
template <typename Tup>
static bool call(Tup&& tup0, Tup&& tup1)
{
return not_equal_fn::impl2(std::forward<Tup>(tup0),
std::forward<Tup>(tup1),
make_tuple_indices<Tup>{});
}
};
// Calculates minimum value of std::distance's on each pair of the tuples
struct distance_fn
{
private:
#if defined(_MSC_VER)
template <typename T>
static const T& (min)(const T& arg)
{
return arg;
}
template <typename T0, typename T1, typename... Ts>
static const std::common_type_t<T0, T1, Ts...>&
(min)(const T0& arg1, const T1& arg2, const Ts&... args)
{
return (arg1 < arg2) ? (min)(arg1, args...) : (min)(arg2, args...);
}
// This is faster on MSVC2015 than foldl-like with an accumulator
template <typename Tup, std::size_t... Is>
static std::ptrdiff_t impl2(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
{
return (distance_fn::min)(
std::distance(std::get<Is>(std::forward<Tup>(tup0)),
std::get<Is>(std::forward<Tup>(tup1)))...);
}
#else
template <typename Tup>
static std::ptrdiff_t impl(Tup&&, Tup&&, std::ptrdiff_t acc)
{
return acc;
}
template <std::size_t I, std::size_t... Is, typename Tup>
static std::ptrdiff_t impl(Tup&& tup0, Tup&& tup1, std::ptrdiff_t acc)
{
return distance_fn::template impl<Is...>(
std::forward<Tup>(tup0), std::forward<Tup>(tup1),
(std::min)(acc,
std::distance(std::get<I>(std::forward<Tup>(tup0)),
std::get<I>(std::forward<Tup>(tup1)))));
}
template <typename Tup, std::size_t... Is>
static std::ptrdiff_t impl2(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
{
return distance_fn::impl<Is...>(
std::forward<Tup>(tup0), std::forward<Tup>(tup1),
std::numeric_limits<std::ptrdiff_t>::max());
}
#endif
public:
template <typename Tup>
static std::ptrdiff_t call(Tup&& tup0, Tup&& tup1)
{
return distance_fn::impl2(std::forward<Tup>(tup0),
std::forward<Tup>(tup1),
make_tuple_indices<Tup>{});
}
};
// Checks if all tuple elements are convertible to true
struct all_true_fn
{
private:
template <typename Tup>
static bool impl(Tup&&)
{
return true;
}
template <std::size_t I, std::size_t... Is, typename Tup>
static bool impl(Tup&& tup)
{
return !!(std::get<I>(std::forward<Tup>(tup))) &&
all_true_fn::template impl<Is...>(std::forward<Tup>(tup));
}
template <typename Tup, std::size_t... Is>
static bool impl2(Tup&& tup, index_sequence<Is...>)
{
return all_true_fn::impl<Is...>(std::forward<Tup>(tup));
}
public:
template <typename Tup>
static bool call(Tup&& tup)
{
return all_true_fn::impl2(std::forward<Tup>(tup),
make_tuple_indices<Tup>{});
}
};
} // namespace tuple
} // namespace kl
<commit_msg>Simplify tuple-related utilities using fold expressions<commit_after>#pragma once
#include <iterator>
#include <limits>
#include <tuple>
#include <type_traits>
namespace kl {
using std::index_sequence;
using std::make_index_sequence;
template <typename T>
using make_tuple_indices =
make_index_sequence<std::tuple_size_v<std::remove_reference_t<T>>>;
namespace tuple {
// Applies a function to given tuple
struct apply_fn
{
private:
template <typename Tup, typename Fun, std::size_t... Is>
static decltype(auto) impl(Tup&& tup, Fun&& fun, index_sequence<Is...>)
{
return std::forward<Fun>(fun)(
(std::get<Is>(std::forward<Tup>(tup)))...);
}
public:
template <typename Tup, typename Fun>
static decltype(auto) call(Tup&& tup, Fun&& fun)
{
return apply_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
make_tuple_indices<Tup>{});
}
};
struct for_each_fn
{
private:
template <typename Tup, typename Fun, std::size_t... Is>
static void impl(Tup&& tup, Fun&& fun, index_sequence<Is...>)
{
(..., fun(std::get<Is>(std::forward<Tup>(tup))));
}
public:
template <typename Tup, typename Fun>
static void call(Tup&& tup, Fun&& fun)
{
for_each_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
make_tuple_indices<Tup>{});
}
};
// Transforms tuple of dereferencable to tuple of references:
// tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
// tuple<int&, double&, const short&>
struct transform_ref_fn
{
private:
template <typename Tup, std::size_t... Is>
static auto impl(Tup&& tup, index_sequence<Is...>)
{
return std::tuple<decltype(*(std::get<Is>(std::forward<Tup>(tup))))...>{
(*std::get<Is>(std::forward<Tup>(tup)))...};
}
public:
template <typename Tup>
static auto call(Tup&& tup)
{
return transform_ref_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{});
}
};
// Transforms tuple of dereferencable to tuple of dereferenced values:
// tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
// tuple<int, double, short>
struct transform_deref_fn
{
private:
template <typename Tup, std::size_t... Is>
static auto impl(Tup&& tup, index_sequence<Is...>)
{
return std::make_tuple(*std::get<Is>(std::forward<Tup>(tup))...);
}
public:
template <typename Tup>
static auto call(Tup&& tup)
{
return transform_deref_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{});
}
};
// Checks for inequality with two given tuples. We AND instead of OR to
// support zipping Sequences with different size.
struct not_equal_fn
{
private:
template <typename Tup, std::size_t... Is>
static bool impl(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
{
return (... && (std::get<Is>(std::forward<Tup>(tup0)) !=
std::get<Is>(std::forward<Tup>(tup1))));
}
public:
template <typename Tup>
static bool call(Tup&& tup0, Tup&& tup1)
{
return not_equal_fn::impl(std::forward<Tup>(tup0),
std::forward<Tup>(tup1),
make_tuple_indices<Tup>{});
}
};
// Calculates minimum value of std::distance's on each pair of the tuples
struct distance_fn
{
private:
template <typename Tup, std::size_t... Is>
static std::ptrdiff_t impl(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
{
static_assert(sizeof...(Is) > 0);
std::ptrdiff_t min{std::numeric_limits<std::ptrdiff_t>::max()}, dist{};
return (
(min = (dist = std::distance(std::get<Is>(std::forward<Tup>(tup0)),
std::get<Is>(std::forward<Tup>(tup1))),
dist < min ? dist : min)),
...);
}
public:
template <typename Tup>
static std::ptrdiff_t call(Tup&& tup0, Tup&& tup1)
{
return distance_fn::impl(std::forward<Tup>(tup0),
std::forward<Tup>(tup1),
make_tuple_indices<Tup>{});
}
};
// Checks if all tuple elements are convertible to true
struct all_true_fn
{
private:
template <typename Tup, std::size_t... Is>
static bool impl(Tup&& tup, index_sequence<Is...>)
{
return (... && std::get<Is>(std::forward<Tup>(tup)));
}
public:
template <typename Tup>
static bool call(Tup&& tup)
{
return all_true_fn::impl(std::forward<Tup>(tup),
make_tuple_indices<Tup>{});
}
};
} // namespace tuple
} // namespace kl
<|endoftext|>
|
<commit_before>// Copyright 2011 Google Inc. 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.
//
// Author: nadavs@google.com <Nadav Samet>
#ifndef RPCZ_RPC_H
#define RPCZ_RPC_H
#include <stdexcept>
#include <string>
#include "rpcz/macros.hpp"
#include "rpcz/rpcz.pb.h"
#ifdef WIN32
// winerror.h contains #define NO_ERROR 0
#undef NO_ERROR
#endif
namespace rpcz {
typedef rpc_response_header::status_code status_code;
typedef rpc_response_header::application_error_code application_error_code;
namespace status {
static const status_code INACTIVE = rpc_response_header::INACTIVE;
static const status_code ACTIVE = rpc_response_header::ACTIVE;
static const status_code OK = rpc_response_header::OK;
static const status_code CANCELLED = rpc_response_header::CANCELLED;
static const status_code APPLICATION_ERROR = rpc_response_header::APPLICATION_ERROR;
static const status_code DEADLINE_EXCEEDED = rpc_response_header::DEADLINE_EXCEEDED;
static const status_code TERMINATED = rpc_response_header::TERMINATED;
} // namespace status
namespace application_error {
static const application_error_code NO_ERROR = rpc_response_header::NO_ERROR;
static const application_error_code INVALID_HEADER = rpc_response_header::INVALID_HEADER;
static const application_error_code NO_SUCH_SERVICE = rpc_response_header::NO_SUCH_SERVICE;
static const application_error_code NO_SUCH_METHOD = rpc_response_header::NO_SUCH_METHOD;
static const application_error_code INVALID_MESSAGE = rpc_response_header::INVALID_MESSAGE;
static const application_error_code METHOD_NOT_IMPLEMENTED = rpc_response_header::METHOD_NOT_IMPLEMENTED;
} // namespace application_error
class sync_event;
class rpc {
public:
rpc();
~rpc();
inline bool ok() const {
return get_status() == status::OK;
}
status_code get_status() const {
return status_;
}
inline std::string get_error_message() const {
return error_message_;
}
inline int get_application_error_code() const {
return application_error_code_;
}
inline int64 get_deadline_ms() const {
return deadline_ms_;
}
inline void set_deadline_ms(int deadline_ms) {
deadline_ms_ = deadline_ms;
}
void set_failed(int application_error_code, const std::string& message);
int wait();
std::string to_string() const;
private:
void set_status(status_code status);
status_code status_;
std::string error_message_;
int application_error_code_;
int64 deadline_ms_;
scoped_ptr<sync_event> sync_event_;
friend class rpc_channel_impl;
friend class server_channel_impl;
DISALLOW_COPY_AND_ASSIGN(rpc);
};
class rpc_error : public std::runtime_error {
public:
explicit rpc_error(const rpc& rpc_)
: std::runtime_error(rpc_.to_string()),
status_(rpc_.get_status()),
error_message_(rpc_.get_error_message()),
application_error_code_(rpc_.get_application_error_code()) {}
virtual ~rpc_error() throw() {}
status_code get_status() const {
return status_;
}
inline std::string get_error_message() const {
return error_message_;
}
inline int get_application_error_code() const {
return application_error_code_;
}
private:
status_code status_;
std::string error_message_;
int application_error_code_;
};
class invalid_message_error : public std::runtime_error {
public:
explicit invalid_message_error(const std::string& message)
: std::runtime_error(message) {}
};
} // namespace
#endif
<commit_msg>resolve WIN32 compile errors cause by NO_ERROR conflict in pb.h file<commit_after>// Copyright 2011 Google Inc. 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.
//
// Author: nadavs@google.com <Nadav Samet>
#ifndef RPCZ_RPC_H
#define RPCZ_RPC_H
#include <stdexcept>
#include <string>
#ifdef WIN32
// winerror.h contains #define NO_ERROR 0
#undef NO_ERROR
#endif
#include "rpcz/macros.hpp"
#include "rpcz/rpcz.pb.h"
namespace rpcz {
typedef rpc_response_header::status_code status_code;
typedef rpc_response_header::application_error_code application_error_code;
namespace status {
static const status_code INACTIVE = rpc_response_header::INACTIVE;
static const status_code ACTIVE = rpc_response_header::ACTIVE;
static const status_code OK = rpc_response_header::OK;
static const status_code CANCELLED = rpc_response_header::CANCELLED;
static const status_code APPLICATION_ERROR = rpc_response_header::APPLICATION_ERROR;
static const status_code DEADLINE_EXCEEDED = rpc_response_header::DEADLINE_EXCEEDED;
static const status_code TERMINATED = rpc_response_header::TERMINATED;
} // namespace status
namespace application_error {
static const application_error_code NO_ERROR = rpc_response_header::NO_ERROR;
static const application_error_code INVALID_HEADER = rpc_response_header::INVALID_HEADER;
static const application_error_code NO_SUCH_SERVICE = rpc_response_header::NO_SUCH_SERVICE;
static const application_error_code NO_SUCH_METHOD = rpc_response_header::NO_SUCH_METHOD;
static const application_error_code INVALID_MESSAGE = rpc_response_header::INVALID_MESSAGE;
static const application_error_code METHOD_NOT_IMPLEMENTED = rpc_response_header::METHOD_NOT_IMPLEMENTED;
} // namespace application_error
class sync_event;
class rpc {
public:
rpc();
~rpc();
inline bool ok() const {
return get_status() == status::OK;
}
status_code get_status() const {
return status_;
}
inline std::string get_error_message() const {
return error_message_;
}
inline int get_application_error_code() const {
return application_error_code_;
}
inline int64 get_deadline_ms() const {
return deadline_ms_;
}
inline void set_deadline_ms(int deadline_ms) {
deadline_ms_ = deadline_ms;
}
void set_failed(int application_error_code, const std::string& message);
int wait();
std::string to_string() const;
private:
void set_status(status_code status);
status_code status_;
std::string error_message_;
int application_error_code_;
int64 deadline_ms_;
scoped_ptr<sync_event> sync_event_;
friend class rpc_channel_impl;
friend class server_channel_impl;
DISALLOW_COPY_AND_ASSIGN(rpc);
};
class rpc_error : public std::runtime_error {
public:
explicit rpc_error(const rpc& rpc_)
: std::runtime_error(rpc_.to_string()),
status_(rpc_.get_status()),
error_message_(rpc_.get_error_message()),
application_error_code_(rpc_.get_application_error_code()) {}
virtual ~rpc_error() throw() {}
status_code get_status() const {
return status_;
}
inline std::string get_error_message() const {
return error_message_;
}
inline int get_application_error_code() const {
return application_error_code_;
}
private:
status_code status_;
std::string error_message_;
int application_error_code_;
};
class invalid_message_error : public std::runtime_error {
public:
explicit invalid_message_error(const std::string& message)
: std::runtime_error(message) {}
};
} // namespace
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP
#include <realm/column.hpp>
namespace realm {
struct Timestamp {
Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
{
REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
}
explicit Timestamp(const null&) : m_is_null(true) { }
Timestamp() : Timestamp(null()) { }
bool is_null() const { return m_is_null; }
// Note that nullability is handled by query system. These operators are only invoked for non-null dates.
bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
Timestamp& operator=(const Timestamp& rhs) = default;
template<class Ch, class Tr>
friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);
int64_t m_seconds;
uint32_t m_nanoseconds;
bool m_is_null;
static constexpr uint32_t nanoseconds_per_second = 1000000000;
};
template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
return out;
}
// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple, public ColumnTemplate<Timestamp> {
public:
TimestampColumn(Allocator& alloc, ref_type ref);
~TimestampColumn() noexcept override;
static ref_type create(Allocator& alloc, size_t size = 0);
/// Get the number of entries in this column. This operation is relatively
/// slow.
size_t size() const noexcept override;
/// Whether or not this column is nullable.
bool is_nullable() const noexcept override;
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
bool is_null(size_t row_ndx) const noexcept override;
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
void set_null(size_t row_ndx) override;
void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
void destroy() noexcept override;
bool has_search_index() const noexcept final { return bool(m_search_index); }
StringIndex* get_search_index() noexcept final { return m_search_index.get(); }
void destroy_search_index() noexcept override;
void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
bool allow_duplicate_values) final;
void populate_search_index();
StringIndex* create_search_index() override;
StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
void update_from_parent(size_t old_baseline) noexcept override;
void set_ndx_in_parent(size_t ndx) noexcept override;
void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
void verify() const override;
void to_dot(std::ostream&, StringData title = StringData()) const override;
void do_dump_node_structure(std::ostream&, int level) const override;
void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
void add(const Timestamp& ts = Timestamp{});
Timestamp get(size_t row_ndx) const noexcept;
Timestamp get_val(size_t row_ndx) const noexcept override { return get(row_ndx); }
void set(size_t row_ndx, const Timestamp& ts);
bool compare(const TimestampColumn& c) const noexcept;
Timestamp maximum(size_t& result_index) const;
Timestamp minimum(size_t& result_index) const;
size_t count(Timestamp) const;
void erase(size_t row_ndx, bool is_last);
template <class Condition> size_t find(Timestamp value, size_t begin, size_t end) const noexcept
{
// FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match check
// nanoseconds, etc, etc, etc. Lots of possibilities. Below code is naive and slow but works.
Condition cond;
for (size_t t = begin; t < end; t++) {
Timestamp ts = get(t);
if (cond(ts, value, ts.is_null(), value.is_null()))
return t;
}
return npos;
}
typedef Timestamp value_type;
private:
std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
std::unique_ptr<BpTree<int64_t>> m_nanoseconds;
std::unique_ptr<StringIndex> m_search_index;
template<class BT>
class CreateHandler;
template <class Condition> Timestamp minmax(size_t& result_index) const noexcept
{
// Condition is realm::Greater for maximum and realm::Less for minimum.
Timestamp best;
result_index = npos;
if (size() > 0) {
best = get(0);
result_index = 0;
}
for (size_t i = 0; i < size(); ++i) {
if (Condition()(get(i), best, get(i).is_null(), best.is_null())) {
best = get(i);
result_index = i;
}
}
return best;
}
};
} // namespace realm
#endif // REALM_COLUMN_TIMESTAMP_HPP
<commit_msg>Whitespace fixes<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2015] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP
#include <realm/column.hpp>
namespace realm {
struct Timestamp {
Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
{
REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
}
explicit Timestamp(const null&) : m_is_null(true) { }
Timestamp() : Timestamp(null()) { }
bool is_null() const { return m_is_null; }
// Note that nullability is handled by query system. These operators are only invoked for non-null dates.
bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
Timestamp& operator=(const Timestamp& rhs) = default;
template<class Ch, class Tr>
friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);
int64_t m_seconds;
uint32_t m_nanoseconds;
bool m_is_null;
static constexpr uint32_t nanoseconds_per_second = 1000000000;
};
template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
return out;
}
// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple, public ColumnTemplate<Timestamp> {
public:
TimestampColumn(Allocator& alloc, ref_type ref);
~TimestampColumn() noexcept override;
static ref_type create(Allocator& alloc, size_t size = 0);
/// Get the number of entries in this column. This operation is relatively
/// slow.
size_t size() const noexcept override;
/// Whether or not this column is nullable.
bool is_nullable() const noexcept override;
/// Whether or not the value at \a row_ndx is NULL. If the column is not
/// nullable, always returns false.
bool is_null(size_t row_ndx) const noexcept override;
/// Sets the value at \a row_ndx to be NULL.
/// \throw LogicError Thrown if this column is not nullable.
void set_null(size_t row_ndx) override;
void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
bool broken_reciprocal_backlinks) override;
void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
void destroy() noexcept override;
bool has_search_index() const noexcept final { return bool(m_search_index); }
StringIndex* get_search_index() noexcept final { return m_search_index.get(); }
void destroy_search_index() noexcept override;
void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
bool allow_duplicate_values) final;
void populate_search_index();
StringIndex* create_search_index() override;
StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
void update_from_parent(size_t old_baseline) noexcept override;
void set_ndx_in_parent(size_t ndx) noexcept override;
void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
void verify() const override;
void to_dot(std::ostream&, StringData title = StringData()) const override;
void do_dump_node_structure(std::ostream&, int level) const override;
void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
void add(const Timestamp& ts = Timestamp{});
Timestamp get(size_t row_ndx) const noexcept;
Timestamp get_val(size_t row_ndx) const noexcept override { return get(row_ndx); }
void set(size_t row_ndx, const Timestamp& ts);
bool compare(const TimestampColumn& c) const noexcept;
Timestamp maximum(size_t& result_index) const;
Timestamp minimum(size_t& result_index) const;
size_t count(Timestamp) const;
void erase(size_t row_ndx, bool is_last);
template <class Condition>
size_t find(Timestamp value, size_t begin, size_t end) const noexcept
{
// FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match check
// nanoseconds, etc, etc, etc. Lots of possibilities. Below code is naive and slow but works.
Condition cond;
for (size_t t = begin; t < end; t++) {
Timestamp ts = get(t);
if (cond(ts, value, ts.is_null(), value.is_null()))
return t;
}
return npos;
}
typedef Timestamp value_type;
private:
std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
std::unique_ptr<BpTree<int64_t>> m_nanoseconds;
std::unique_ptr<StringIndex> m_search_index;
template<class BT>
class CreateHandler;
template <class Condition>
Timestamp minmax(size_t& result_index) const noexcept
{
// Condition is realm::Greater for maximum and realm::Less for minimum.
Timestamp best;
result_index = npos;
if (size() > 0) {
best = get(0);
result_index = 0;
}
for (size_t i = 0; i < size(); ++i) {
if (Condition()(get(i), best, get(i).is_null(), best.is_null())) {
best = get(i);
result_index = i;
}
}
return best;
}
};
} // namespace realm
#endif // REALM_COLUMN_TIMESTAMP_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_FILE_MAPPER_HPP
#define REALM_UTIL_FILE_MAPPER_HPP
#include <realm/util/file.hpp>
namespace realm {
namespace util {
void *mmap(int fd, size_t size, File::AccessMode access, std::size_t offset, const char *encryption_key);
void munmap(void *addr, size_t size) REALM_NOEXCEPT;
void* mremap(int fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size);
void msync(void *addr, size_t size);
File::SizeType encrypted_size_to_data_size(File::SizeType size) REALM_NOEXCEPT;
File::SizeType data_size_to_encrypted_size(File::SizeType size) REALM_NOEXCEPT;
size_t round_up_to_page_size(size_t size) REALM_NOEXCEPT;
}
}
#endif
<commit_msg>removed std::<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_FILE_MAPPER_HPP
#define REALM_UTIL_FILE_MAPPER_HPP
#include <realm/util/file.hpp>
namespace realm {
namespace util {
void *mmap(int fd, size_t size, File::AccessMode access, size_t offset, const char *encryption_key);
void munmap(void *addr, size_t size) REALM_NOEXCEPT;
void* mremap(int fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size);
void msync(void *addr, size_t size);
File::SizeType encrypted_size_to_data_size(File::SizeType size) REALM_NOEXCEPT;
File::SizeType data_size_to_encrypted_size(File::SizeType size) REALM_NOEXCEPT;
size_t round_up_to_page_size(size_t size) REALM_NOEXCEPT;
}
}
#endif
<|endoftext|>
|
<commit_before>
#define DRAW_TRIANGLE_TEXELP(TARGET, X, Y) (&((DRAW_TRIANGLE_TEXEL_TYPE *) TARGET->pixels)[(Y) * TARGET->width + (X)])
#ifndef DRAW_TRIANGLE_COLOR_TO_TEXEL
#define DRAW_TRIANGLE_COLOR_TO_TEXEL(V) (V)
#endif
#ifndef DRAW_TRIANGLE_TEXEL_TO_COLOR
#define DRAW_TRIANGLE_TEXEL_TO_COLOR(V) (V)
#endif
#if DRAW_TRIANGLE_BLEND
#define DRAW_TRIANGLE_DO_BLEND(CTX, SRC, DST) DRAW_TRIANGLE_TEXEL_TO_COLOR(ctx->blend_func(SRC, DRAW_TRIANGLE_COLOR_TO_TEXEL(DST)))
#else
#define DRAW_TRIANGLE_DO_BLEND(CTX, SRC, DST) DRAW_TRIANGLE_TEXEL_TO_COLOR(SRC)
#endif
#if DRAW_TRIANGLE_ZTEST
#define ZTEST(NEW, OLD) ((NEW > OLD))
#define ALPHA_TEST(A) (A > 0.5f)
#else
#define ZTEST(...) (true)
#define ALPHA_TEST(...) (true)
#endif
static DRAW_TRIANGLE_FUNC(DRAW_TRIANGLE_FUNC_NAME)
{
#define BLOCK_SIZE 8
#define IROUND(v) (to_q8((float) (v)))
DRAW_TRIANGLE_TARGET_TYPE *target = (DRAW_TRIANGLE_TARGET_TYPE *) ctx->target;
p0 = p0 * ctx->viewport_mat;
p1 = p1 * ctx->viewport_mat;
p2 = p2 * ctx->viewport_mat;
q8 px[3] = {IROUND(p0.x), IROUND(p1.x), IROUND(p2.x)};
q8 py[3] = {IROUND(p0.y), IROUND(p1.y), IROUND(p2.y)};
q8 area = edge_funcq(px[1] - px[0], py[1] - py[0], px[2] - px[1], py[2] - py[1]);
#if DRAW_TRIANGLE_CULL
if (area <= 0) {
return;
}
#endif
int32_t minx = qint(MIN3(px[0], px[1], px[2]));
int32_t miny = qint(MIN3(py[0], py[1], py[2]));
int32_t maxx = qint(MAX3(px[0], px[1], px[2]));
int32_t maxy = qint(MAX3(py[0], py[1], py[2]));
int32_t target_width = target->width;
int32_t target_height = target->height;
if (maxx < 0 || maxy < 0 ||
minx >= (target_width) || miny >= (target_height)) {
return;
}
// Clip bounding rect to target rect
minx = MAX(0, minx);
miny = MAX(0, miny);
maxx = MIN(maxx, (target_width - 1));
maxy = MIN(maxy, (target_height - 1));
float rarea = 1.0f / to_float(area);
float z0 = p0.z;
float dz1 = p1.z - z0;
float dz2 = p2.z - z0;
Vec3q w_xinc = {(py[1] - py[2]),
(py[2] - py[0]),
(py[0] - py[1])}; // * rarea;
Vec3q w_yinc = {(px[2] - px[1]),
(px[0] - px[2]),
(px[1] - px[0])}; // * rarea;
int blkminx = minx & ~(BLOCK_SIZE - 1);
int blkminy = miny & ~(BLOCK_SIZE - 1);
// TODO: Handle edge cases or maybe use 2^n sized targets always
int blkmaxx = (maxx + BLOCK_SIZE) & ~(BLOCK_SIZE - 1);
if (blkmaxx > target_width) blkmaxx -= BLOCK_SIZE;
int blkmaxy = (maxy + BLOCK_SIZE) & ~(BLOCK_SIZE - 1);
if (blkmaxy > target_height) blkmaxy -= BLOCK_SIZE;
int blkcountx = (blkmaxx - blkminx) / BLOCK_SIZE;
int blkcounty = (blkmaxy - blkminy) / BLOCK_SIZE;
Vec3q blk_xinc = w_xinc * to_q8((int32_t) BLOCK_SIZE);
Vec3q blk_yinc = w_yinc * to_q8((int32_t) BLOCK_SIZE);
Vec3q c = {(qmul(px[1], py[2]) - qmul(py[1], px[2])),
(qmul(px[2], py[0]) - qmul(py[2], px[0])),
(qmul(px[0], py[1]) - qmul(py[0], px[1]))}; // + (Vec3q){1, 1, 1};
Vec3q basew = c + w_xinc * to_q8(blkminx) + w_yinc * to_q8(blkminy);
float t1dx = to_float(w_xinc.y) * rarea;
float t1dy = to_float(w_yinc.y) * rarea;
float t2dx = to_float(w_xinc.z) * rarea;
float t2dy = to_float(w_yinc.z) * rarea;
q8 blockX = 0;
q8 blockY = 0;
q8 q_blockcntx = to_q8(blkcountx);
q8 q_blockcnty = to_q8(blkcounty);
for (; blockY < q_blockcnty; blockY += Q_ONE) {
blockX = 0;
Vec3q blockW[4];
blockW[1] = basew + blk_yinc * blockY;
blockW[3] = blockW[1] + blk_yinc;
#define INOUT(w) (((w.x >= 0) << 0) | ((w.y >= 0) << 1) | ((w.z >= 0) << 2))
int inout[4] = {0, 0, 0, 0};
inout[1] = INOUT(blockW[1]);
inout[3] = INOUT(blockW[3]);
for (; blockX < q_blockcntx; blockX += Q_ONE) {
blockW[0] = blockW[1];
blockW[2] = blockW[3];
blockW[1] = blockW[0] + blk_xinc;
blockW[3] = blockW[2] + blk_xinc;
inout[0] = inout[1];
inout[2] = inout[3];
inout[1] = INOUT(blockW[1]);
inout[3] = INOUT(blockW[3]);
bool allSame = (inout[0] == inout[1]) && (inout[0] == inout[2]) && (inout[0] == inout[3]);
#if DRAW_TRIANGLE_CULL
bool allInside = allSame && (inout[0] == 7);
#else
bool allInside = allSame && (inout[0] == 7 || inout[0] == 0);
#endif
bool allOutside = allSame && !allInside;
if (allOutside) {
continue; /* Block is outside of the triangle */
}
int bx = qint(blockX) * BLOCK_SIZE;
int by = qint(blockY) * BLOCK_SIZE;
int starty = blkminy + by;
//int endy = starty + BLOCK_SIZE;
int startx = blkminx + bx;
//int endx = blkminx + bx + BLOCK_SIZE;
float t1row = to_float(blockW[0].y) * rarea;
float t2row = to_float(blockW[0].z) * rarea;
float zrow = 1 - (z0 + t1row * dz1 + to_float(blockW[0].z) * rarea * dz2);
float zmaxx = 1 - (z0 + to_float(blockW[1].y) * rarea * dz1 + to_float(blockW[1].z) * rarea * dz2);
float zmaxy = 1 - (z0 + to_float(blockW[2].y) * rarea * dz1 + to_float(blockW[2].z) * rarea * dz2);
float zdx = (zmaxx - zrow) / BLOCK_SIZE;
float zdy = (zmaxy - zrow) / BLOCK_SIZE;
zval_t *zp_row = &ctx->zbuffer[starty * target_width + startx];
DRAW_TRIANGLE_TEXEL_TYPE *bufferp_row = DRAW_TRIANGLE_TEXELP(target, startx, starty);
if (allInside) {
// Block is fully inside the triangle
for (int j = 0; j < BLOCK_SIZE; j++) {
float t1 = t1row;
float t2 = t2row;
float z = zrow;
zval_t *zp = zp_row;
DRAW_TRIANGLE_TEXEL_TYPE *bufferp = bufferp_row;
for (int i = 0; i < BLOCK_SIZE; i++) {
zval_t zvalue = (zval_t) (z * ZBUFFER_MAX);
if (ZTEST(zvalue, *zp)) {
#if DRAW_TRIANGLE_FRAG
Texel color = {};
if (fragment(ctx, shader_data, startx + i, starty + j, 1 - t1 - t2, t1, t2, &color)) {
*bufferp = DRAW_TRIANGLE_DO_BLEND(ctx, color, *bufferp);
}
if (ALPHA_TEST(color.a)) {
*zp = zvalue;
}
#else
*zp = zvalue;
#endif
}
t1 += t1dx;
t2 += t2dx;
z += zdx;
zp++;
bufferp++;
}
t1row += t1dy;
t2row += t2dy;
zrow += zdy;
zp_row += target_width;
bufferp_row += target_width;
}
} else {
// Block is partially inside the triangle
Vec3q wrow = blockW[0];
for (int j = 0; j < BLOCK_SIZE; j++) {
Vec3q w = wrow;
float t1 = t1row;
float t2 = t2row;
float z = zrow;
zval_t *zp = zp_row;
DRAW_TRIANGLE_TEXEL_TYPE *bufferp = bufferp_row;
#if DRAW_TRIANGLE_CULL
#define INSIDE_TRIANGLE(w) ((w.x | w.y | w.z) >= 0)
#else
#define INSIDE_TRIANGLE(w) (((w.x | w.y | w.z) >= 0) || ((w.x < 0.0f) && (w.y < 0.0f) && (w.z < 0.0f)))
#endif
for (int i = 0; i < BLOCK_SIZE; i++) {
if (INSIDE_TRIANGLE(w)) {
zval_t zvalue = (zval_t) (z * ZBUFFER_MAX);
if (ZTEST(zvalue, *zp)) {
#if DRAW_TRIANGLE_FRAG
Texel color = {};
if (fragment(ctx, shader_data, startx + i, starty + j, 1 - t1 - t2, t1, t2, &color)) {
*bufferp = DRAW_TRIANGLE_DO_BLEND(ctx, color, *bufferp);
}
if (ALPHA_TEST(color.a)) {
*zp = zvalue;
}
#else
*zp = zvalue;
#endif
}
}
t1 += t1dx;
t2 += t2dx;
z += zdx;
w = w + w_xinc;
zp++;
bufferp++;
}
t1row += t1dy;
t2row += t2dy;
zrow += zdy;
wrow = wrow + w_yinc;
zp_row += target_width;
bufferp_row += target_width;
}
}
}
}
#undef INSIDE_TRIANGLE
#undef INOUT
#undef IROUND
#undef BLOCK_SIZE
}
#undef ALPHA_TEST
#undef ZTEST
#undef DRAW_TRIANGLE_DO_BLEND
#undef DRAW_TRIANGLE_TEXELP
#undef DRAW_TRIANGLE_FUNC_NAME
#undef DRAW_TRIANGLE_TARGET_TYPE
#undef DRAW_TRIANGLE_TEXEL_TYPE
#undef DRAW_TRIANGLE_COLOR_TO_TEXEL
#undef DRAW_TRIANGLE_TEXEL_TO_COLOR
#undef DRAW_TRIANGLE_BLEND
#undef DRAW_TRIANGLE_CULL
#undef DRAW_TRIANGLE_FRAG
#undef DRAW_TRIANGLE_ZTEST
<commit_msg>Implement top-left fill rule (fixes "holes" in rectangles)<commit_after>
#define DRAW_TRIANGLE_TEXELP(TARGET, X, Y) (&((DRAW_TRIANGLE_TEXEL_TYPE *) TARGET->pixels)[(Y) * TARGET->width + (X)])
#ifndef DRAW_TRIANGLE_COLOR_TO_TEXEL
#define DRAW_TRIANGLE_COLOR_TO_TEXEL(V) (V)
#endif
#ifndef DRAW_TRIANGLE_TEXEL_TO_COLOR
#define DRAW_TRIANGLE_TEXEL_TO_COLOR(V) (V)
#endif
#if DRAW_TRIANGLE_BLEND
#define DRAW_TRIANGLE_DO_BLEND(CTX, SRC, DST) DRAW_TRIANGLE_TEXEL_TO_COLOR(ctx->blend_func(SRC, DRAW_TRIANGLE_COLOR_TO_TEXEL(DST)))
#else
#define DRAW_TRIANGLE_DO_BLEND(CTX, SRC, DST) DRAW_TRIANGLE_TEXEL_TO_COLOR(SRC)
#endif
#if DRAW_TRIANGLE_ZTEST
#define ZTEST(NEW, OLD) ((NEW > OLD))
#define ALPHA_TEST(A) (A > 0.5f)
#else
#define ZTEST(...) (true)
#define ALPHA_TEST(...) (true)
#endif
static DRAW_TRIANGLE_FUNC(DRAW_TRIANGLE_FUNC_NAME)
{
#define BLOCK_SIZE 8
#define IROUND(v) (to_q8((float) (v)))
DRAW_TRIANGLE_TARGET_TYPE *target = (DRAW_TRIANGLE_TARGET_TYPE *) ctx->target;
p0 = p0 * ctx->viewport_mat;
p1 = p1 * ctx->viewport_mat;
p2 = p2 * ctx->viewport_mat;
q8 px[3] = {IROUND(p0.x), IROUND(p1.x), IROUND(p2.x)};
q8 py[3] = {IROUND(p0.y), IROUND(p1.y), IROUND(p2.y)};
q8 area = edge_funcq(px[1] - px[0], py[1] - py[0], px[2] - px[1], py[2] - py[1]);
#if DRAW_TRIANGLE_CULL
if (area <= 0) {
return;
}
#endif
int32_t minx = qint(MIN3(px[0], px[1], px[2]));
int32_t miny = qint(MIN3(py[0], py[1], py[2]));
int32_t maxx = qint(MAX3(px[0], px[1], px[2]));
int32_t maxy = qint(MAX3(py[0], py[1], py[2]));
int32_t target_width = target->width;
int32_t target_height = target->height;
if (maxx < 0 || maxy < 0 ||
minx >= (target_width) || miny >= (target_height)) {
return;
}
// Clip bounding rect to target rect
minx = MAX(0, minx);
miny = MAX(0, miny);
maxx = MIN(maxx, (target_width - 1));
maxy = MIN(maxy, (target_height - 1));
float rarea = 1.0f / to_float(area);
float z0 = p0.z;
float dz1 = p1.z - z0;
float dz2 = p2.z - z0;
Vec3q w_xinc = {(py[1] - py[2]),
(py[2] - py[0]),
(py[0] - py[1])}; // * rarea;
Vec3q w_yinc = {(px[2] - px[1]),
(px[0] - px[2]),
(px[1] - px[0])}; // * rarea;
int blkminx = minx & ~(BLOCK_SIZE - 1);
int blkminy = miny & ~(BLOCK_SIZE - 1);
// TODO: Handle edge cases or maybe use 2^n sized targets always
int blkmaxx = (maxx + BLOCK_SIZE) & ~(BLOCK_SIZE - 1);
if (blkmaxx > target_width) blkmaxx -= BLOCK_SIZE;
int blkmaxy = (maxy + BLOCK_SIZE) & ~(BLOCK_SIZE - 1);
if (blkmaxy > target_height) blkmaxy -= BLOCK_SIZE;
int blkcountx = (blkmaxx - blkminx) / BLOCK_SIZE;
int blkcounty = (blkmaxy - blkminy) / BLOCK_SIZE;
Vec3q blk_xinc = w_xinc * to_q8((int32_t) BLOCK_SIZE);
Vec3q blk_yinc = w_yinc * to_q8((int32_t) BLOCK_SIZE);
Vec3q c = {(qmul(px[1], py[2]) - qmul(py[1], px[2])),
(qmul(px[2], py[0]) - qmul(py[2], px[0])),
(qmul(px[0], py[1]) - qmul(py[0], px[1]))}; // + (Vec3q){1, 1, 1};
#define TOPLEFT(a, b) (((b.y == a.y) && (b.x < a.x)) || (b.y < a.y))
if (!TOPLEFT(p1, p2)) { c.x -= 1; };
if (!TOPLEFT(p2, p0)) { c.y -= 1; };
if (!TOPLEFT(p0, p1)) { c.z -= 1; };
Vec3q basew = c + w_xinc * to_q8(blkminx) + w_yinc * to_q8(blkminy);
float t1dx = to_float(w_xinc.y) * rarea;
float t1dy = to_float(w_yinc.y) * rarea;
float t2dx = to_float(w_xinc.z) * rarea;
float t2dy = to_float(w_yinc.z) * rarea;
q8 blockX = 0;
q8 blockY = 0;
q8 q_blockcntx = to_q8(blkcountx);
q8 q_blockcnty = to_q8(blkcounty);
for (; blockY < q_blockcnty; blockY += Q_ONE) {
blockX = 0;
Vec3q blockW[4];
blockW[1] = basew + blk_yinc * blockY;
blockW[3] = blockW[1] + blk_yinc;
#define INOUT(w) (((w.x >= 0) << 0) | ((w.y >= 0) << 1) | ((w.z >= 0) << 2))
int inout[4] = {0, 0, 0, 0};
inout[1] = INOUT(blockW[1]);
inout[3] = INOUT(blockW[3]);
for (; blockX < q_blockcntx; blockX += Q_ONE) {
blockW[0] = blockW[1];
blockW[2] = blockW[3];
blockW[1] = blockW[0] + blk_xinc;
blockW[3] = blockW[2] + blk_xinc;
inout[0] = inout[1];
inout[2] = inout[3];
inout[1] = INOUT(blockW[1]);
inout[3] = INOUT(blockW[3]);
bool allSame = (inout[0] == inout[1]) && (inout[0] == inout[2]) && (inout[0] == inout[3]);
#if DRAW_TRIANGLE_CULL
bool allInside = allSame && (inout[0] == 7);
#else
bool allInside = allSame && (inout[0] == 7 || inout[0] == 0);
#endif
bool allOutside = allSame && !allInside;
if (allOutside) {
continue; /* Block is outside of the triangle */
}
int bx = qint(blockX) * BLOCK_SIZE;
int by = qint(blockY) * BLOCK_SIZE;
int starty = blkminy + by;
//int endy = starty + BLOCK_SIZE;
int startx = blkminx + bx;
//int endx = blkminx + bx + BLOCK_SIZE;
float t1row = to_float(blockW[0].y) * rarea;
float t2row = to_float(blockW[0].z) * rarea;
float zrow = 1 - (z0 + t1row * dz1 + to_float(blockW[0].z) * rarea * dz2);
float zmaxx = 1 - (z0 + to_float(blockW[1].y) * rarea * dz1 + to_float(blockW[1].z) * rarea * dz2);
float zmaxy = 1 - (z0 + to_float(blockW[2].y) * rarea * dz1 + to_float(blockW[2].z) * rarea * dz2);
float zdx = (zmaxx - zrow) / BLOCK_SIZE;
float zdy = (zmaxy - zrow) / BLOCK_SIZE;
zval_t *zp_row = &ctx->zbuffer[starty * target_width + startx];
DRAW_TRIANGLE_TEXEL_TYPE *bufferp_row = DRAW_TRIANGLE_TEXELP(target, startx, starty);
if (allInside) {
// Block is fully inside the triangle
for (int j = 0; j < BLOCK_SIZE; j++) {
float t1 = t1row;
float t2 = t2row;
float z = zrow;
zval_t *zp = zp_row;
DRAW_TRIANGLE_TEXEL_TYPE *bufferp = bufferp_row;
for (int i = 0; i < BLOCK_SIZE; i++) {
zval_t zvalue = (zval_t) (z * ZBUFFER_MAX);
if (ZTEST(zvalue, *zp)) {
#if DRAW_TRIANGLE_FRAG
Texel color = {};
if (fragment(ctx, shader_data, startx + i, starty + j, 1 - t1 - t2, t1, t2, &color)) {
*bufferp = DRAW_TRIANGLE_DO_BLEND(ctx, color, *bufferp);
}
if (ALPHA_TEST(color.a)) {
*zp = zvalue;
}
#else
*zp = zvalue;
#endif
}
t1 += t1dx;
t2 += t2dx;
z += zdx;
zp++;
bufferp++;
}
t1row += t1dy;
t2row += t2dy;
zrow += zdy;
zp_row += target_width;
bufferp_row += target_width;
}
} else {
// Block is partially inside the triangle
Vec3q wrow = blockW[0];
for (int j = 0; j < BLOCK_SIZE; j++) {
Vec3q w = wrow;
float t1 = t1row;
float t2 = t2row;
float z = zrow;
zval_t *zp = zp_row;
DRAW_TRIANGLE_TEXEL_TYPE *bufferp = bufferp_row;
#if DRAW_TRIANGLE_CULL
#define INSIDE_TRIANGLE(w) ((w.x | w.y | w.z) >= 0)
#else
#define INSIDE_TRIANGLE(w) (((w.x | w.y | w.z) >= 0) || ((w.x < 0.0f) && (w.y < 0.0f) && (w.z < 0.0f)))
#endif
for (int i = 0; i < BLOCK_SIZE; i++) {
if (INSIDE_TRIANGLE(w)) {
zval_t zvalue = (zval_t) (z * ZBUFFER_MAX);
if (ZTEST(zvalue, *zp)) {
#if DRAW_TRIANGLE_FRAG
Texel color = {};
if (fragment(ctx, shader_data, startx + i, starty + j, 1 - t1 - t2, t1, t2, &color)) {
*bufferp = DRAW_TRIANGLE_DO_BLEND(ctx, color, *bufferp);
}
if (ALPHA_TEST(color.a)) {
*zp = zvalue;
}
#else
*zp = zvalue;
#endif
}
}
t1 += t1dx;
t2 += t2dx;
z += zdx;
w = w + w_xinc;
zp++;
bufferp++;
}
t1row += t1dy;
t2row += t2dy;
zrow += zdy;
wrow = wrow + w_yinc;
zp_row += target_width;
bufferp_row += target_width;
}
}
}
}
#undef INSIDE_TRIANGLE
#undef INOUT
#undef IROUND
#undef BLOCK_SIZE
}
#undef ALPHA_TEST
#undef ZTEST
#undef DRAW_TRIANGLE_DO_BLEND
#undef DRAW_TRIANGLE_TEXELP
#undef DRAW_TRIANGLE_FUNC_NAME
#undef DRAW_TRIANGLE_TARGET_TYPE
#undef DRAW_TRIANGLE_TEXEL_TYPE
#undef DRAW_TRIANGLE_COLOR_TO_TEXEL
#undef DRAW_TRIANGLE_TEXEL_TO_COLOR
#undef DRAW_TRIANGLE_BLEND
#undef DRAW_TRIANGLE_CULL
#undef DRAW_TRIANGLE_FRAG
#undef DRAW_TRIANGLE_ZTEST
<|endoftext|>
|
<commit_before>#include "thriftlink_client.h"
boost::shared_ptr<TTransport> _socket;
boost::shared_ptr<TTransport> _transport;
boost::shared_ptr<TProtocol> _protocol;
boost::shared_ptr<ApiForwardClient> _api;
static bool connect_internal();
bool thrift_connect(const char* ipaddr, int port) {
boost::shared_ptr<TTransport> socket(new TSocket(ipaddr, port));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
boost::shared_ptr<ApiForwardClient> api(new ApiForwardClient(protocol));
_socket = socket;
_transport = transport;
_protocol = protocol;
_api = api;
return connect_internal();
}
void thrift_close() {
try {
if (_transport.get() != NULL) {
_transport->close();
}
} catch (TException& tx) {
cout << "ERROR: " << tx.what() << endl;
return;
}
return;
}
static bool connect_internal() {
try {
if (_transport.get()!=NULL) {
if (!_transport->isOpen()) {
_transport->open();
}
}
} catch (TTransportException& tx) {
cout << "ERROR: " << tx.what() << endl;
return false;
} catch (TException& tx) {
cout << "ERROR: " << tx.what() << endl;
return false;
}
return true;
}
bool ensure_connection() {
if (_transport.get() == NULL) return false;
try{
if (!_transport->isOpen()) {
return connect_internal();
}
} catch (TException& tx) {
cout << "ERROR: " << tx.what() << endl;
return false;
}
return true;
}<commit_msg>Update connect_internal() function<commit_after>#include "thriftlink_client.h"
boost::shared_ptr<TTransport> _socket;
boost::shared_ptr<TTransport> _transport;
boost::shared_ptr<TProtocol> _protocol;
boost::shared_ptr<ApiForwardClient> _api;
static bool connect_internal();
bool thrift_connect(const char* ipaddr, int port) {
boost::shared_ptr<TTransport> socket(new TSocket(ipaddr, port));
boost::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
boost::shared_ptr<ApiForwardClient> api(new ApiForwardClient(protocol));
_socket = socket;
_transport = transport;
_protocol = protocol;
_api = api;
return connect_internal();
}
void thrift_close() {
try {
if (_transport.get() != NULL) {
_transport->close();
}
} catch (TException& tx) {
cout << "ERROR: " << tx.what() << endl;
return;
}
return;
}
static bool connect_internal() {
try {
if (_transport.get()!=NULL) {
if (!_transport->isOpen() || !_socket->isOpen()) {
_transport->open();
}
}
else {
return false;
}
} catch (TTransportException& tx) {
cout << "ERROR: " << tx.what() << endl;
return false;
} catch (TException& tx) {
cout << "ERROR: " << tx.what() << endl;
return false;
}
return _transport->isOpen();
}
bool ensure_connection() {
if (_transport.get() == NULL) return false;
try{
if (!_transport->isOpen() || !_socket->isOpen()) {
return connect_internal();
}
} catch (TException& tx) {
cout << "ERROR: " << tx.what() << endl;
return false;
}
return true;
}<|endoftext|>
|
<commit_before>// Copyright (C) 2010 Tim Moore (timoore33@gmail.com)
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU 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 "ConditionNode.hxx"
namespace simgear
{
using namespace osg;
ConditionNode::ConditionNode()
{
}
ConditionNode::ConditionNode(const ConditionNode& rhs, const CopyOp& op)
: Group(rhs, op), _condition(rhs._condition)
{
}
ConditionNode::~ConditionNode()
{
}
void ConditionNode::traverse(NodeVisitor& nv)
{
if (nv.getTraversalMode() == NodeVisitor::TRAVERSE_ACTIVE_CHILDREN) {
unsigned numChildren = getNumChildren();
if (numChildren == 0)
return;
if (!_condition || _condition->test())
getChild(0)->accept(nv);
else if (numChildren > 1)
getChild(1)->accept(nv);
else
return;
} else {
Group::traverse(nv);
}
}
}
<commit_msg>add SGMath.hxx header file to ConditionNode.cxx<commit_after>// Copyright (C) 2010 Tim Moore (timoore33@gmail.com)
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU 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 "ConditionNode.hxx"
#include <simgear/math/SGMath.hxx>
namespace simgear
{
using namespace osg;
ConditionNode::ConditionNode()
{
}
ConditionNode::ConditionNode(const ConditionNode& rhs, const CopyOp& op)
: Group(rhs, op), _condition(rhs._condition)
{
}
ConditionNode::~ConditionNode()
{
}
void ConditionNode::traverse(NodeVisitor& nv)
{
if (nv.getTraversalMode() == NodeVisitor::TRAVERSE_ACTIVE_CHILDREN) {
unsigned numChildren = getNumChildren();
if (numChildren == 0)
return;
if (!_condition || _condition->test())
getChild(0)->accept(nv);
else if (numChildren > 1)
getChild(1)->accept(nv);
else
return;
} else {
Group::traverse(nv);
}
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2010, The Mineserver Project
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 The Mineserver Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <cstdlib>
#include <cstdio>
#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#ifdef WIN32
#include <winsock2.h>
#endif
#include "logger.h"
#include "constants.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "config.h"
#include "physics.h"
namespace
{
void reportError(User *user, std::string message)
{
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Error!" + COLOR_RED + message, Chat::USER);
}
void playerList(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().sendUserlist(user);
}
void about(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + Conf::get().sValue("servername") +
"Running Mineserver v." + VERSION, Chat::USER);
}
void rules(User *user, std::string command, std::deque<std::string> args)
{
User *tUser = user;
if (!args.empty() && user->admin)
tUser = getUserByNick(args[0]);
if (tUser != NULL)
{
// Send rules
std::ifstream motdfs( RULESFILE.c_str() );
std::string temp;
while (getline(motdfs, temp))
{
// If not a comment
if (temp.empty() || temp[0] == COMMENTPREFIX)
Chat::get().sendMsg(tUser, temp, Chat::USER);
}
motdfs.close();
}
else
{
reportError(user, "User " + args[0] + " not found (see /players)");
}
}
void home(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Teleporting you home!", Chat::USER);
user->teleport(Map::get().spawnPos.x, Map::get().spawnPos.y + 2, Map::get().spawnPos.z);
}
void kit(User *user, std::string command, std::deque<std::string> args)
{
if (!args.empty())
{
if (args[0] == "starter")
{
std::vector<int> kitItems = Conf::get().vValue("kit_starter");
for (std::vector<int>::iterator iter = kitItems.begin(), end = kitItems.end();
iter != end;
++iter)
{
spawnedItem item;
item.EID = generateEID();
item.item = *iter;
item.count = 1;
item.x = static_cast<int>(user->pos.x*32 + (rand() % 30));
item.y = static_cast<int>(user->pos.y*32);
item.z = static_cast<int>(user->pos.z*32 + (rand() % 30));
Map::get().sendPickupSpawn(item);
kitItems.pop_back();
}
}
}
}
void saveMap(User *user, std::string command, std::deque<std::string> args)
{
Map::get().saveWholeMap();
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED + " Saved map to disc",
Chat::USER);
}
void kick(User *user, std::string command, std::deque<std::string> args)
{
if (!args.empty())
{
std::string victim = args[0];
LOG("Kicking: " + victim);
User *tUser = getUserByNick(victim);
if (tUser != NULL)
{
args.pop_front();
std::string kickMsg;
if (args.empty())
{
kickMsg = Conf::get().sValue("default_kick_message");
}
else
{
while (!args.empty())
{
kickMsg += args[0] + " ";
args.pop_front();
}
}
tUser->kick(kickMsg);
LOG("Kicked!");
}
else
{
reportError(user, "User " + victim + " not found (see /players)");
}
}
else
{
reportError(user, "Usage: /kick user [reason]");
}
}
void coordinateTeleport(User *user, std::string command, std::deque<std::string> args)
{
if (args.size() > 2)
{
LOG(user->nick + " teleport to: " + args[0] + " " + args[1] + " " + args[2]);
double x = atof(args[0].c_str());
double y = atof(args[1].c_str());
double z = atof(args[2].c_str());
user->teleport(x, y, z);
}
}
void userTeleport(User *user, std::string command, std::deque<std::string> args)
{
if (args.size() == 1)
{
LOG(user->nick + " teleport to: " + args[0]);
User *tUser = getUserByNick(args[0]);
if (tUser != NULL)
user->teleport(tUser->pos.x, tUser->pos.y + 2, tUser->pos.z);
else
reportError(user, "User " + args[0] + " not found (see /players)");
}
else if (args.size() == 2)
{
LOG(user->nick + ": teleport " + args[0] + " to " + args[1]);
User *whatUser = getUserByNick(args[0]);
User *toUser = getUserByNick(args[1]);
if (whatUser != NULL && toUser != NULL)
{
whatUser->teleport(toUser->pos.x, toUser->pos.y + 2, toUser->pos.z);
Chat::get().sendMsg(user, COLOR_MAGENTA + "Teleported!", Chat::USER);
}
else
{
reportError(user, "User " + (whatUser == NULL ? args[0] : args[1]) +
" not found (see /players");
}
}
}
void reloadConfiguration(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().loadAdmins(ADMINFILE);
Conf::get().load(CONFIGFILE);
// Set physics enable state based on config
Physics::get().enabled = ((Conf::get().iValue("liquid_physics")==0)?false:true);
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED +
" Reloaded admins and config", Chat::USER);
// Note that the MOTD is loaded on-demand each time it is requested
}
bool isValidItem(int id)
{
if (id < 1) // zero or negative items are all invalid
return false;
if (id > 91 && id < 256) // these are undefined blocks and items
return false;
if (id == 2256 || id == 2257) // records are special cased
return true;
if (id > 350) // high items are invalid
return false;
if (id >= BLOCK_RED_CLOTH && id <= BLOCK_GRAY_CLOTH) // coloured cloth causes client crashes
return false;
return true;
}
int roundUpTo(int x, int nearest)
{
x += (nearest - 1);
x /= nearest;
x *= nearest;
return x;
}
void giveItems(User *user, std::string command, std::deque<std::string> args)
{
User *tUser = NULL;
int itemId = 0, itemCount, itemStacks;
if (args.size() > 1)
{
tUser = getUserByNick(args[0]);
itemId = Conf::get().iValue(args[1]);
if (itemId == 0)
itemId = atoi(args[1].c_str());
// Check item validity
if (!isValidItem(itemId))
return;
if (args.size() > 2)
itemCount = atoi(args[2].c_str());
else
itemCount = 0;
itemStacks = roundUpTo(itemCount, 64) / 64;
itemCount = itemCount % 64;
}
else
{
reportError(user, "Too few parameters.");
}
if (tUser)
{
int amount = 64;
for (int i = 0; i < itemStacks; i++)
{
// if last stack
if (i == itemStacks - 1)
amount = itemCount;
spawnedItem item;
item.EID = generateEID();
item.item = itemId;
item.health = 0;
item.count = amount;
item.x = static_cast<int>(tUser->pos.x * 32);
item.y = static_cast<int>(tUser->pos.y * 32);
item.z = static_cast<int>(tUser->pos.z * 32);
Map::get().sendPickupSpawn(item);
}
Chat::get().sendMsg(user, COLOR_RED + user->nick + " spawned items", Chat::ADMINS);
}
else
{
reportError(user, "User " + args[0] + " not found (see /players)");
}
}
}
void Chat::registerStandardCommands()
{
registerCommand("players", playerList, false);
registerCommand("about", about, false);
registerCommand("rules", rules, false);
registerCommand("home", home, false);
registerCommand("kit", kit, false);
registerCommand("save", saveMap, true);
registerCommand("kick", kick, true);
registerCommand("ctp", coordinateTeleport, true);
registerCommand("tp", userTeleport, true);
registerCommand("reload", reloadConfiguration, true);
registerCommand("give", giveItems, true);
}
<commit_msg>Minor change for /give command, first check if the item is a number and then search config.<commit_after>/*
Copyright (c) 2010, The Mineserver Project
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 The Mineserver Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 <cstdlib>
#include <cstdio>
#include <iostream>
#include <deque>
#include <fstream>
#include <vector>
#include <ctime>
#include <math.h>
#ifdef WIN32
#include <winsock2.h>
#endif
#include "logger.h"
#include "constants.h"
#include "tools.h"
#include "map.h"
#include "user.h"
#include "chat.h"
#include "config.h"
#include "physics.h"
namespace
{
void reportError(User *user, std::string message)
{
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Error!" + COLOR_RED + message, Chat::USER);
}
void playerList(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().sendUserlist(user);
}
void about(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + Conf::get().sValue("servername") +
"Running Mineserver v." + VERSION, Chat::USER);
}
void rules(User *user, std::string command, std::deque<std::string> args)
{
User *tUser = user;
if (!args.empty() && user->admin)
tUser = getUserByNick(args[0]);
if (tUser != NULL)
{
// Send rules
std::ifstream motdfs( RULESFILE.c_str() );
std::string temp;
while (getline(motdfs, temp))
{
// If not a comment
if (temp.empty() || temp[0] == COMMENTPREFIX)
Chat::get().sendMsg(tUser, temp, Chat::USER);
}
motdfs.close();
}
else
{
reportError(user, "User " + args[0] + " not found (see /players)");
}
}
void home(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "Teleporting you home!", Chat::USER);
user->teleport(Map::get().spawnPos.x, Map::get().spawnPos.y + 2, Map::get().spawnPos.z);
}
void kit(User *user, std::string command, std::deque<std::string> args)
{
if (!args.empty())
{
if (args[0] == "starter")
{
std::vector<int> kitItems = Conf::get().vValue("kit_starter");
for (std::vector<int>::iterator iter = kitItems.begin(), end = kitItems.end();
iter != end;
++iter)
{
spawnedItem item;
item.EID = generateEID();
item.item = *iter;
item.count = 1;
item.x = static_cast<int>(user->pos.x*32 + (rand() % 30));
item.y = static_cast<int>(user->pos.y*32);
item.z = static_cast<int>(user->pos.z*32 + (rand() % 30));
Map::get().sendPickupSpawn(item);
kitItems.pop_back();
}
}
}
}
void saveMap(User *user, std::string command, std::deque<std::string> args)
{
Map::get().saveWholeMap();
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED + " Saved map to disc",
Chat::USER);
}
void kick(User *user, std::string command, std::deque<std::string> args)
{
if (!args.empty())
{
std::string victim = args[0];
LOG("Kicking: " + victim);
User *tUser = getUserByNick(victim);
if (tUser != NULL)
{
args.pop_front();
std::string kickMsg;
if (args.empty())
{
kickMsg = Conf::get().sValue("default_kick_message");
}
else
{
while (!args.empty())
{
kickMsg += args[0] + " ";
args.pop_front();
}
}
tUser->kick(kickMsg);
LOG("Kicked!");
}
else
{
reportError(user, "User " + victim + " not found (see /players)");
}
}
else
{
reportError(user, "Usage: /kick user [reason]");
}
}
void coordinateTeleport(User *user, std::string command, std::deque<std::string> args)
{
if (args.size() > 2)
{
LOG(user->nick + " teleport to: " + args[0] + " " + args[1] + " " + args[2]);
double x = atof(args[0].c_str());
double y = atof(args[1].c_str());
double z = atof(args[2].c_str());
user->teleport(x, y, z);
}
}
void userTeleport(User *user, std::string command, std::deque<std::string> args)
{
if (args.size() == 1)
{
LOG(user->nick + " teleport to: " + args[0]);
User *tUser = getUserByNick(args[0]);
if (tUser != NULL)
user->teleport(tUser->pos.x, tUser->pos.y + 2, tUser->pos.z);
else
reportError(user, "User " + args[0] + " not found (see /players)");
}
else if (args.size() == 2)
{
LOG(user->nick + ": teleport " + args[0] + " to " + args[1]);
User *whatUser = getUserByNick(args[0]);
User *toUser = getUserByNick(args[1]);
if (whatUser != NULL && toUser != NULL)
{
whatUser->teleport(toUser->pos.x, toUser->pos.y + 2, toUser->pos.z);
Chat::get().sendMsg(user, COLOR_MAGENTA + "Teleported!", Chat::USER);
}
else
{
reportError(user, "User " + (whatUser == NULL ? args[0] : args[1]) +
" not found (see /players");
}
}
}
void reloadConfiguration(User *user, std::string command, std::deque<std::string> args)
{
Chat::get().loadAdmins(ADMINFILE);
Conf::get().load(CONFIGFILE);
// Set physics enable state based on config
Physics::get().enabled = ((Conf::get().iValue("liquid_physics")==0)?false:true);
Chat::get().sendMsg(user, COLOR_DARK_MAGENTA + "SERVER:" + COLOR_RED +
" Reloaded admins and config", Chat::USER);
// Note that the MOTD is loaded on-demand each time it is requested
}
bool isValidItem(int id)
{
if (id < 1) // zero or negative items are all invalid
return false;
if (id > 91 && id < 256) // these are undefined blocks and items
return false;
if (id == 2256 || id == 2257) // records are special cased
return true;
if (id > 350) // high items are invalid
return false;
if (id >= BLOCK_RED_CLOTH && id <= BLOCK_GRAY_CLOTH) // coloured cloth causes client crashes
return false;
return true;
}
int roundUpTo(int x, int nearest)
{
x += (nearest - 1);
x /= nearest;
x *= nearest;
return x;
}
void giveItems(User *user, std::string command, std::deque<std::string> args)
{
User *tUser = NULL;
int itemId = 0, itemCount, itemStacks;
if (args.size() > 1)
{
tUser = getUserByNick(args[0]);
//First check if item is a number
itemId = atoi(args[1].c_str());
//If item was not a number, search the name from config
if (itemId == 0)
itemId = Conf::get().iValue(args[1]);
// Check item validity
if (!isValidItem(itemId))
return;
if (args.size() > 2)
itemCount = atoi(args[2].c_str());
else
itemCount = 0;
itemStacks = roundUpTo(itemCount, 64) / 64;
itemCount = itemCount % 64;
}
else
{
reportError(user, "Too few parameters.");
}
if (tUser)
{
int amount = 64;
for (int i = 0; i < itemStacks; i++)
{
// if last stack
if (i == itemStacks - 1)
amount = itemCount;
spawnedItem item;
item.EID = generateEID();
item.item = itemId;
item.health = 0;
item.count = amount;
item.x = static_cast<int>(tUser->pos.x * 32);
item.y = static_cast<int>(tUser->pos.y * 32);
item.z = static_cast<int>(tUser->pos.z * 32);
Map::get().sendPickupSpawn(item);
}
Chat::get().sendMsg(user, COLOR_RED + user->nick + " spawned items", Chat::ADMINS);
}
else
{
reportError(user, "User " + args[0] + " not found (see /players)");
}
}
}
void Chat::registerStandardCommands()
{
registerCommand("players", playerList, false);
registerCommand("about", about, false);
registerCommand("rules", rules, false);
registerCommand("home", home, false);
registerCommand("kit", kit, false);
registerCommand("save", saveMap, true);
registerCommand("kick", kick, true);
registerCommand("ctp", coordinateTeleport, true);
registerCommand("tp", userTeleport, true);
registerCommand("reload", reloadConfiguration, true);
registerCommand("give", giveItems, true);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010-2011 OTClient <https://github.com/edubart/otclient>
*
* 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 "creature.h"
#include "datmanager.h"
#include "localplayer.h"
#include "map.h"
#include <framework/platform/platform.h>
#include <framework/graphics/graphics.h>
Creature::Creature() : Thing(Otc::Creature)
{
m_healthPercent = 0;
m_direction = Otc::South;
m_walking = false;
m_walkOffsetX = 0;
m_walkOffsetY = 0;
m_informationFont = g_fonts.getFont("tibia-12px-rounded");
}
void Creature::draw(int x, int y)
{
//dump << (int)m_speed;
// gspeed = 100
// pspeed = 234
// (recorded) 400 - 866 = 466
// (calc by ot eq) 1000 * 100 / 234 = 427
// gspeed = 150
// pspeed = 234
// (recorded) 934 - 1597 = 663
// (calc by ot eq) 1000 * 150 / 234 = 641
// gspeed = 100
// pspeed = 110
// (recorded) 900 - 1833 = 933
// (calc by ot eq) 1000 * 100 / 110 = 909
// 1000 * groundSpeed / playerSpeed
// TODO 1: FIX RENDER STEP 2
// TODO 2: FIX DIAGONAL WALKING, BUGS MAP
// TODO 3: ADD ANIMATION
x += m_walkOffsetX;
y += m_walkOffsetY;
const ThingAttributes& attributes = getAttributes();
// Render creature
for(m_yDiv = 0; m_yDiv < attributes.ydiv; m_yDiv++) {
// continue if we dont have this addon.
if(m_yDiv > 0 && !(m_outfit.addons & (1 << (m_yDiv-1))))
continue;
// draw white item
internalDraw(x, y, 0);
// draw mask if exists
if(attributes.blendframes > 1) {
// switch to blend color mode
g_graphics.bindBlendFunc(Fw::BlendColorzing);
// head
g_graphics.bindColor(Otc::OutfitColors[m_outfit.head]);
internalDraw(x, y, 1, Otc::SpriteYellowMask);
// body
g_graphics.bindColor(Otc::OutfitColors[m_outfit.body]);
internalDraw(x, y, 1, Otc::SpriteRedMask);
// legs
g_graphics.bindColor(Otc::OutfitColors[m_outfit.legs]);
internalDraw(x, y, 1, Otc::SpriteGreenMask);
// feet
g_graphics.bindColor(Otc::OutfitColors[m_outfit.feet]);
internalDraw(x, y, 1, Otc::SpriteBlueMask);
// restore default blend func
g_graphics.bindBlendFunc(Fw::BlendDefault);
g_graphics.bindColor(Fw::white);
}
}
// Update animation and position
if(m_walking && attributes.animcount > 1) {
if(g_platform.getTicks() - m_lastTicks >= m_walkTimePerPixel) {
int pixelsWalked = std::floor((g_platform.getTicks() - m_lastTicks) / m_walkTimePerPixel);
int remainingTime = (g_platform.getTicks() - m_lastTicks) % (int)m_walkTimePerPixel;
if(m_direction == Otc::North || m_direction == Otc::NorthEast || m_direction == Otc::NorthWest)
m_walkOffsetY = std::max(m_walkOffsetY - pixelsWalked, 0);
else if(m_direction == Otc::South || m_direction == Otc::SouthEast || m_direction == Otc::SouthWest)
m_walkOffsetY = std::min(m_walkOffsetY + pixelsWalked, 0);
if(m_direction == Otc::East || m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
m_walkOffsetX = std::min(m_walkOffsetX + pixelsWalked, 0);
else if(m_direction == Otc::West || m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
m_walkOffsetX = std::max(m_walkOffsetX - pixelsWalked, 0);
//double walkOffset = std::max(m_walkOffsetX, m_walkOffsetY);
/*if((32 - fabs(walkOffset)) / 8 % 2 == 0) {
if(m_animation+1 == attributes.animcount)
m_animation = 1;
else
m_animation++;
//m_lastTicks = g_platform.getTicks();
}*/
if(((m_walkOffsetX == 0 && m_walkOffsetY == 0) && m_walkOffsetX != m_walkOffsetY) ||
((m_walkOffsetX == 0 || m_walkOffsetY == 0) && m_walkOffsetX == m_walkOffsetY)) {
m_walking = false;
m_walkOffsetX = 0;
m_walkOffsetY = 0;
m_animation = 0;
}
m_lastTicks = g_platform.getTicks() - remainingTime;
}
}
}
void Creature::drawInformation(int x, int y, bool useGray)
{
Color fillColor = Color(96, 96, 96);
if(!useGray)
fillColor = m_informationColor;
Rect backgroundRect = Rect(x-(14.5), y, 27, 4);
Rect healthRect = backgroundRect.expanded(-1);
healthRect.setWidth((m_healthPercent/100.0)*25);
g_graphics.bindColor(Fw::black);
g_graphics.drawFilledRect(backgroundRect);
g_graphics.bindColor(fillColor);
g_graphics.drawFilledRect(healthRect);
// name
m_informationFont->renderText(m_name, Rect(x-100, y-15, 200, 15), Fw::AlignTopCenter, fillColor);
}
void Creature::walk(const Position& position)
{
// set walking state
m_walking = true;
m_walkOffsetX = 0;
m_walkOffsetY = 0;
m_walkingFromPosition = m_position;
int walkTimeFactor = 1;
// update map tiles
g_map.removeThingByPtr(asThing());
m_position = position;
g_map.addThing(asThing());
// set new direction
if(m_walkingFromPosition + Position(0, -1, 0) == m_position) {
m_direction = Otc::North;
m_walkOffsetY = 32;
}
else if(m_walkingFromPosition + Position(1, 0, 0) == m_position) {
m_direction = Otc::East;
m_walkOffsetX = -32;
}
else if(m_walkingFromPosition + Position(0, 1, 0) == m_position) {
m_direction = Otc::South;
m_walkOffsetY = -32;
}
else if(m_walkingFromPosition + Position(-1, 0, 0) == m_position) {
m_direction = Otc::West;
m_walkOffsetX = 32;
}
else if(m_walkingFromPosition + Position(1, -1, 0) == m_position) {
m_direction = Otc::NorthEast;
m_walkOffsetX = -32;
m_walkOffsetY = 32;
walkTimeFactor = 2;
}
else if(m_walkingFromPosition + Position(1, 1, 0) == m_position) {
m_direction = Otc::SouthEast;
m_walkOffsetX = -32;
m_walkOffsetY = -32;
walkTimeFactor = 2;
}
else if(m_walkingFromPosition + Position(-1, 1, 0) == m_position) {
m_direction = Otc::SouthWest;
m_walkOffsetX = 32;
m_walkOffsetY = -32;
walkTimeFactor = 2;
}
else if(m_walkingFromPosition + Position(-1, -1, 0) == m_position) {
m_direction = Otc::NorthWest;
m_walkOffsetX = 32;
m_walkOffsetY = 32;
walkTimeFactor = 2;
}
else { // Teleport
// we teleported, dont walk or change direction
m_walking = false;
}
// Calculate xDiv
if(m_direction >= 4) {
if(m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
m_xDiv = Otc::East;
else if(m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
m_xDiv = Otc::West;
}
else {
m_xDiv = m_direction;
}
// get walk speed
int groundSpeed = 0;
ThingPtr ground = g_map.getThing(m_position, 0);
if(ground)
groundSpeed = ground->getAttributes().speed;
float walkTime = walkTimeFactor * 1000.0 * (float)groundSpeed / m_speed;
walkTime = walkTime == 0 ? 1000 : walkTime;
m_walkTimePerPixel = walkTime / 32.0;
m_lastTicks = g_platform.getTicks();
}
void Creature::setHealthPercent(uint8 healthPercent)
{
int oldHealthPercent = m_healthPercent;
m_healthPercent = healthPercent;
onHealthPercentChange(oldHealthPercent);
}
const ThingAttributes& Creature::getAttributes()
{
return g_dat.getCreatureAttributes(m_outfit.type);
}
void Creature::onHealthPercentChange(int)
{
m_informationColor = Fw::black;
if(m_healthPercent > 92) {
m_informationColor.setGreen(188);
}
else if(m_healthPercent > 60) {
m_informationColor.setRed(80);
m_informationColor.setGreen(161);
m_informationColor.setBlue(80);
}
else if(m_healthPercent > 30) {
m_informationColor.setRed(161);
m_informationColor.setGreen(161);
}
else if(m_healthPercent > 8) {
m_informationColor.setRed(160);
m_informationColor.setGreen(39);
m_informationColor.setBlue(39);
}
else if(m_healthPercent > 3) {
m_informationColor.setRed(160);
}
else {
m_informationColor.setRed(79);
}
}
<commit_msg>walk animation<commit_after>/*
* Copyright (c) 2010-2011 OTClient <https://github.com/edubart/otclient>
*
* 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 "creature.h"
#include "datmanager.h"
#include "localplayer.h"
#include "map.h"
#include <framework/platform/platform.h>
#include <framework/graphics/graphics.h>
Creature::Creature() : Thing(Otc::Creature)
{
m_healthPercent = 0;
m_direction = Otc::South;
m_walking = false;
m_walkOffsetX = 0;
m_walkOffsetY = 0;
m_informationFont = g_fonts.getFont("tibia-12px-rounded");
}
void Creature::draw(int x, int y)
{
//dump << (int)m_speed;
// gspeed = 100
// pspeed = 234
// (recorded) 400 - 866 = 466
// (calc by ot eq) 1000 * 100 / 234 = 427
// gspeed = 150
// pspeed = 234
// (recorded) 934 - 1597 = 663
// (calc by ot eq) 1000 * 150 / 234 = 641
// gspeed = 100
// pspeed = 110
// (recorded) 900 - 1833 = 933
// (calc by ot eq) 1000 * 100 / 110 = 909
// 1000 * groundSpeed / playerSpeed
// TODO 1: FIX RENDER STEP 2
// TODO 2: FIX DIAGONAL WALKING, BUGS MAP
// TODO 3: ADD ANIMATION
x += m_walkOffsetX;
y += m_walkOffsetY;
const ThingAttributes& attributes = getAttributes();
// Render creature
for(m_yDiv = 0; m_yDiv < attributes.ydiv; m_yDiv++) {
// continue if we dont have this addon.
if(m_yDiv > 0 && !(m_outfit.addons & (1 << (m_yDiv-1))))
continue;
// draw white item
internalDraw(x, y, 0);
// draw mask if exists
if(attributes.blendframes > 1) {
// switch to blend color mode
g_graphics.bindBlendFunc(Fw::BlendColorzing);
// head
g_graphics.bindColor(Otc::OutfitColors[m_outfit.head]);
internalDraw(x, y, 1, Otc::SpriteYellowMask);
// body
g_graphics.bindColor(Otc::OutfitColors[m_outfit.body]);
internalDraw(x, y, 1, Otc::SpriteRedMask);
// legs
g_graphics.bindColor(Otc::OutfitColors[m_outfit.legs]);
internalDraw(x, y, 1, Otc::SpriteGreenMask);
// feet
g_graphics.bindColor(Otc::OutfitColors[m_outfit.feet]);
internalDraw(x, y, 1, Otc::SpriteBlueMask);
// restore default blend func
g_graphics.bindBlendFunc(Fw::BlendDefault);
g_graphics.bindColor(Fw::white);
}
}
// Update animation and position
if(m_walking && attributes.animcount > 1) {
if(g_platform.getTicks() - m_lastTicks >= m_walkTimePerPixel) {
int pixelsWalked = std::floor((g_platform.getTicks() - m_lastTicks) / m_walkTimePerPixel);
int remainingTime = (g_platform.getTicks() - m_lastTicks) % (int)m_walkTimePerPixel;
if(m_direction == Otc::North || m_direction == Otc::NorthEast || m_direction == Otc::NorthWest)
m_walkOffsetY = std::max(m_walkOffsetY - pixelsWalked, 0);
else if(m_direction == Otc::South || m_direction == Otc::SouthEast || m_direction == Otc::SouthWest)
m_walkOffsetY = std::min(m_walkOffsetY + pixelsWalked, 0);
if(m_direction == Otc::East || m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
m_walkOffsetX = std::min(m_walkOffsetX + pixelsWalked, 0);
else if(m_direction == Otc::West || m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
m_walkOffsetX = std::max(m_walkOffsetX - pixelsWalked, 0);
int walkOffset = std::max(fabs(m_walkOffsetX), fabs(m_walkOffsetY));
if(walkOffset % 8 == 0) {
if(m_animation+1 == attributes.animcount)
m_animation = 1;
else
m_animation++;
}
if(((m_walkOffsetX == 0 && m_walkOffsetY == 0) && m_walkOffsetX != m_walkOffsetY) ||
((m_walkOffsetX == 0 || m_walkOffsetY == 0) && m_walkOffsetX == m_walkOffsetY)) {
m_walking = false;
m_walkOffsetX = 0;
m_walkOffsetY = 0;
m_animation = 0;
}
m_lastTicks = g_platform.getTicks() - remainingTime;
}
}
}
void Creature::drawInformation(int x, int y, bool useGray)
{
Color fillColor = Color(96, 96, 96);
if(!useGray)
fillColor = m_informationColor;
Rect backgroundRect = Rect(x-(14.5), y, 27, 4);
Rect healthRect = backgroundRect.expanded(-1);
healthRect.setWidth((m_healthPercent/100.0)*25);
g_graphics.bindColor(Fw::black);
g_graphics.drawFilledRect(backgroundRect);
g_graphics.bindColor(fillColor);
g_graphics.drawFilledRect(healthRect);
// name
m_informationFont->renderText(m_name, Rect(x-100, y-15, 200, 15), Fw::AlignTopCenter, fillColor);
}
void Creature::walk(const Position& position)
{
// set walking state
m_walking = true;
m_walkOffsetX = 0;
m_walkOffsetY = 0;
m_walkingFromPosition = m_position;
int walkTimeFactor = 1;
// update map tiles
g_map.removeThingByPtr(asThing());
m_position = position;
g_map.addThing(asThing());
// set new direction
if(m_walkingFromPosition + Position(0, -1, 0) == m_position) {
m_direction = Otc::North;
m_walkOffsetY = 32;
}
else if(m_walkingFromPosition + Position(1, 0, 0) == m_position) {
m_direction = Otc::East;
m_walkOffsetX = -32;
}
else if(m_walkingFromPosition + Position(0, 1, 0) == m_position) {
m_direction = Otc::South;
m_walkOffsetY = -32;
}
else if(m_walkingFromPosition + Position(-1, 0, 0) == m_position) {
m_direction = Otc::West;
m_walkOffsetX = 32;
}
else if(m_walkingFromPosition + Position(1, -1, 0) == m_position) {
m_direction = Otc::NorthEast;
m_walkOffsetX = -32;
m_walkOffsetY = 32;
walkTimeFactor = 2;
}
else if(m_walkingFromPosition + Position(1, 1, 0) == m_position) {
m_direction = Otc::SouthEast;
m_walkOffsetX = -32;
m_walkOffsetY = -32;
walkTimeFactor = 2;
}
else if(m_walkingFromPosition + Position(-1, 1, 0) == m_position) {
m_direction = Otc::SouthWest;
m_walkOffsetX = 32;
m_walkOffsetY = -32;
walkTimeFactor = 2;
}
else if(m_walkingFromPosition + Position(-1, -1, 0) == m_position) {
m_direction = Otc::NorthWest;
m_walkOffsetX = 32;
m_walkOffsetY = 32;
walkTimeFactor = 2;
}
else { // Teleport
// we teleported, dont walk or change direction
m_walking = false;
}
// Calculate xDiv
if(m_direction >= 4) {
if(m_direction == Otc::NorthEast || m_direction == Otc::SouthEast)
m_xDiv = Otc::East;
else if(m_direction == Otc::NorthWest || m_direction == Otc::SouthWest)
m_xDiv = Otc::West;
}
else {
m_xDiv = m_direction;
}
// get walk speed
int groundSpeed = 0;
ThingPtr ground = g_map.getThing(m_position, 0);
if(ground)
groundSpeed = ground->getAttributes().speed;
float walkTime = walkTimeFactor * 1000.0 * (float)groundSpeed / m_speed;
walkTime = walkTime == 0 ? 1000 : walkTime;
m_walkTimePerPixel = walkTime / 32.0;
m_lastTicks = g_platform.getTicks();
}
void Creature::setHealthPercent(uint8 healthPercent)
{
int oldHealthPercent = m_healthPercent;
m_healthPercent = healthPercent;
onHealthPercentChange(oldHealthPercent);
}
const ThingAttributes& Creature::getAttributes()
{
return g_dat.getCreatureAttributes(m_outfit.type);
}
void Creature::onHealthPercentChange(int)
{
m_informationColor = Fw::black;
if(m_healthPercent > 92) {
m_informationColor.setGreen(188);
}
else if(m_healthPercent > 60) {
m_informationColor.setRed(80);
m_informationColor.setGreen(161);
m_informationColor.setBlue(80);
}
else if(m_healthPercent > 30) {
m_informationColor.setRed(161);
m_informationColor.setGreen(161);
}
else if(m_healthPercent > 8) {
m_informationColor.setRed(160);
m_informationColor.setGreen(39);
m_informationColor.setBlue(39);
}
else if(m_healthPercent > 3) {
m_informationColor.setRed(160);
}
else {
m_informationColor.setRed(79);
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <map>
#include <vector>
#include <string>
#include <memory>
#include "I18N.h"
// English localization file
// This is an example translation file without strings in it.
namespace i2p
{
namespace i18n
{
namespace chinese // language namespace
{
// language name in lowercase
static std::string language = "chinese";
// See for language plural forms here:
// https://localization-guide.readthedocs.io/en/latest/l10n/pluralforms.html
static int plural (int n) {
return 0;
}
static std::map<std::string, std::string> strings
{
{"KiB", "KiB"},
{"MiB", "MiB"},
{"GiB", "GiB"},
{"building", "正在构建"},
{"failed", "连接失败"},
{"expiring", "即将过期"},
{"established", "连接建立"},
{"unknown", "未知"},
{"exploratory", "探索隧道"},
{"Purple I2P Webconsole", "Purple I2P 网页控制台"},
{"<b>i2pd</b> webconsole", "<b>i2pd</b> 网页控制台"},
{"Main page", "主页"},
{"Router commands", "路由命令"},
{"Local Destinations", "本地目标"},
{"LeaseSets", "租约集"},
{"Tunnels", "隧道"},
{"Transit Tunnels", "中转隧道"},
{"Transports", "传输"},
{"I2P tunnels", "I2P 隧道"},
{"SAM sessions", "SAM 会话"},
{"ERROR", "错误"},
{"OK", "良好"},
{"Testing", "测试中"},
{"Firewalled", "被防火墙阻挡"},
{"Unknown", "未知"},
{"Proxy", "代理"},
{"Mesh", "网格组网"},
{"Error", "错误"},
{"Clock skew", "时钟偏移"},
{"Offline", "离线"},
{"Symmetric NAT", "对称 NAT"},
{"Uptime", "在线时间"},
{"Network status", "IPv4 网络状态"},
{"Network status v6", "IPv6 网络状态"},
{"Stopping in", "距停止还有:"},
{"Family", "家族"},
{"Tunnel creation success rate", "隧道创建成功率"},
{"Received", "已接收"},
{"KiB/s", "KiB/s"},
{"Sent", "已发送"},
{"Transit", "中转"},
{"Data path", "数据文件路径"},
{"Hidden content. Press on text to see.", "隐藏内容 请点击文本查看。"},
{"Router Ident", "路由器标识"},
{"Router Family", "路由器家族"},
{"Router Caps", "路由器分类"},
{"Version", "版本"},
{"Our external address", "外部地址"},
{"supported", "支持"},
{"Routers", "路由节点"},
{"Floodfills", "洪泛节点"},
{"Client Tunnels", "客户端隧道"},
{"Services", "服务"},
{"Enabled", "启用"},
{"Disabled", "禁用"},
{"Encrypted B33 address", "加密的 B33 地址"},
{"Address registration line", "地址域名注册"},
{"Domain", "域名"},
{"Generate", "生成"},
{"<b>Note:</b> result string can be used only for registering 2LD domains (example.i2p). For registering subdomains please use i2pd-tools.", "<b>注意:</b> 结果字符串可以用于注册次级域名(例如:example.i2p)。若想注册次级域名,请使用 i2pd-tools。"},
{"Address", "地址"},
{"Type", "类型"},
{"EncType", "加密类型"},
{"Inbound tunnels", "入站隧道"},
{"ms", "毫秒"},
{"Outbound tunnels", "出站隧道"},
{"Tags", "标签"},
{"Incoming", "传入"},
{"Outgoing", "传出"},
{"Destination", "目标"},
{"Amount", "数量"},
{"Incoming Tags", "传入标签"},
{"Tags sessions", "标签会话"},
{"Status", "状态"},
{"Local Destination", "本地目标"},
{"Streams", "流"},
{"Close stream", "断开流"},
{"I2CP session not found", "未找到 I2CP 会话"},
{"I2CP is not enabled", "I2CP 未启用"},
{"Invalid", "无效"},
{"Store type", "存储类型"},
{"Expires", "过期时间"},
{"Non Expired Leases", "未到期的租约"},
{"Gateway", "网关"},
{"TunnelID", "隧道 ID"},
{"EndDate", "结束日期"},
{"not floodfill", "非洪泛"},
{"Queue size", "队列大小"},
{"Run peer test", "运行群体测试"},
{"Decline transit tunnels", "拒绝中转隧道"},
{"Accept transit tunnels", "允许中转隧道"},
{"Cancel graceful shutdown", "取消计划的停止"},
{"Start graceful shutdown", "待他人断线后停止"},
{"Force shutdown", "强制停止"},
{"Reload external CSS styles", "重载外部 CSS 样式"},
{"<b>Note:</b> any action done here are not persistent and not changes your config files.", "<b>注意:</b> 此处完成的任何操作都不是永久的,不会更改您的配置文件。"},
{"Logging level", "日志级别"},
{"Transit tunnels limit", "中转隧道限制"},
{"Change", "更换"},
{"Change language", "更换语言"},
{"no transit tunnels currently built", "目前未构建中转隧道"},
{"SAM disabled", "SAM 已禁用"},
{"no sessions currently running", "没有正在运行的会话"},
{"SAM session not found", "未找到 SAM 会话"},
{"SAM Session", "SAM 会话"},
{"Server Tunnels", "服务器隧道"},
{"Client Forwards", "客户端转发"},
{"Server Forwards", "服务器转发"},
{"Unknown page", "未知页面"},
{"Invalid token", "无效凭证"},
{"SUCCESS", "成功"},
{"Stream closed", "流已关闭"},
{"Stream not found or already was closed", "流未找到或已关闭"},
{"Destination not found", "找不到目标"},
{"StreamID can't be null", "StreamID 不能为空"},
{"Return to destination page", "返回目标页面"},
{"You will be redirected in 5 seconds", "您将在5秒内被重定向"},
{"Transit tunnels count must not exceed 65535", "中转隧道数量不能超过 65535"},
{"Back to commands list", "返回命令列表"},
{"Register at reg.i2p", "在 reg.i2p 注册域名"},
{"Description", "描述"},
{"A bit information about service on domain", "在此域名上运行的服务的一些信息"},
{"Submit", "提交"},
{"Domain can't end with .b32.i2p", "域名不能以 .b32.i2p 结尾"},
{"Domain must end with .i2p", "域名必须以 .i2p 结尾"},
{"Such destination is not found", "找不到此目标"},
{"Unknown command", "未知指令"},
{"Command accepted", "已接受指令"},
{"Proxy error", "代理错误"},
{"Proxy info", "代理信息"},
{"Proxy error: Host not found", "代理错误:找不到主机"},
{"Remote host not found in router's addressbook", "在路由的地址簿中找不到远程主机"},
{"You may try to find this host on jump services below", "您可以尝试在下方的跳转服务上找到这个主机"},
{"Invalid request", "无效请求"},
{"Proxy unable to parse your request", "代理无法解析您的请求"},
{"addresshelper is not supported", "不支持地址助手"},
{"Host", "主机"},
{"added to router's addressbook from helper", "将此地址从地址助手添加到地址簿"},
{"Click here to proceed:", "点击此处继续:"},
{"Continue", "继续"},
{"Addresshelper found", "找到地址助手"},
{"already in router's addressbook", "已在路由器的地址簿中"},
{"Click here to update record:", "点击此处更新地址簿记录"},
{"invalid request uri", "无效的 URL 请求"},
{"Can't detect destination host from request", "无法从请求中检测到目标主机"},
{"Outproxy failure", "出口代理失效"},
{"bad outproxy settings", "错误的出口代理设置"},
{"not inside I2P network, but outproxy is not enabled", "该地址不在 I2P 网络内,但未启用出口代理"},
{"unknown outproxy url", "未知的出口代理地址"},
{"cannot resolve upstream proxy", "无法解析上游代理"},
{"hostname too long", "主机名过长"},
{"cannot connect to upstream socks proxy", "无法连接到上游 socks 代理"},
{"Cannot negotiate with socks proxy", "无法与 socks 代理协商"},
{"CONNECT error", "连接错误"},
{"Failed to Connect", "连接失败"},
{"socks proxy error", "socks 代理错误"},
{"failed to send request to upstream", "向上游发送请求失败"},
{"No Reply From socks proxy", "没有来自 socks 代理的回复"},
{"cannot connect", "无法连接"},
{"http out proxy not implemented", "http 出口代理未实现"},
{"cannot connect to upstream http proxy", "无法连接到上游 http 代理"},
{"Host is down", "主机已关闭"},
{"Can't create connection to requested host, it may be down. Please try again later.", "无法创建到目标主机的连接。主机可能已下线,请稍后再试。"},
{"", ""},
};
static std::map<std::string, std::vector<std::string>> plurals
{
{"days", {"日"}},
{"hours", {"时"}},
{"minutes", {"分"}},
{"seconds", {"秒"}},
{"", {""}},
};
std::shared_ptr<const i2p::i18n::Locale> GetLocale()
{
return std::make_shared<i2p::i18n::Locale>(language, strings, plurals, [] (int n)->int { return plural(n); });
}
} // language
} // i18n
} // i2p
<commit_msg>change language file comment<commit_after>/*
* Copyright (c) 2022, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
#include <map>
#include <vector>
#include <string>
#include <memory>
#include "I18N.h"
// Simplified Chinese localization file
// This is an example translation file without strings in it.
namespace i2p
{
namespace i18n
{
namespace chinese // language namespace
{
// language name in lowercase
static std::string language = "chinese";
// See for language plural forms here:
// https://localization-guide.readthedocs.io/en/latest/l10n/pluralforms.html
static int plural (int n) {
return 0;
}
static std::map<std::string, std::string> strings
{
{"KiB", "KiB"},
{"MiB", "MiB"},
{"GiB", "GiB"},
{"building", "正在构建"},
{"failed", "连接失败"},
{"expiring", "即将过期"},
{"established", "连接建立"},
{"unknown", "未知"},
{"exploratory", "探索隧道"},
{"Purple I2P Webconsole", "Purple I2P 网页控制台"},
{"<b>i2pd</b> webconsole", "<b>i2pd</b> 网页控制台"},
{"Main page", "主页"},
{"Router commands", "路由命令"},
{"Local Destinations", "本地目标"},
{"LeaseSets", "租约集"},
{"Tunnels", "隧道"},
{"Transit Tunnels", "中转隧道"},
{"Transports", "传输"},
{"I2P tunnels", "I2P 隧道"},
{"SAM sessions", "SAM 会话"},
{"ERROR", "错误"},
{"OK", "良好"},
{"Testing", "测试中"},
{"Firewalled", "被防火墙阻挡"},
{"Unknown", "未知"},
{"Proxy", "代理"},
{"Mesh", "网格组网"},
{"Error", "错误"},
{"Clock skew", "时钟偏移"},
{"Offline", "离线"},
{"Symmetric NAT", "对称 NAT"},
{"Uptime", "在线时间"},
{"Network status", "IPv4 网络状态"},
{"Network status v6", "IPv6 网络状态"},
{"Stopping in", "距停止还有:"},
{"Family", "家族"},
{"Tunnel creation success rate", "隧道创建成功率"},
{"Received", "已接收"},
{"KiB/s", "KiB/s"},
{"Sent", "已发送"},
{"Transit", "中转"},
{"Data path", "数据文件路径"},
{"Hidden content. Press on text to see.", "隐藏内容 请点击文本查看。"},
{"Router Ident", "路由器标识"},
{"Router Family", "路由器家族"},
{"Router Caps", "路由器分类"},
{"Version", "版本"},
{"Our external address", "外部地址"},
{"supported", "支持"},
{"Routers", "路由节点"},
{"Floodfills", "洪泛节点"},
{"Client Tunnels", "客户端隧道"},
{"Services", "服务"},
{"Enabled", "启用"},
{"Disabled", "禁用"},
{"Encrypted B33 address", "加密的 B33 地址"},
{"Address registration line", "地址域名注册"},
{"Domain", "域名"},
{"Generate", "生成"},
{"<b>Note:</b> result string can be used only for registering 2LD domains (example.i2p). For registering subdomains please use i2pd-tools.", "<b>注意:</b> 结果字符串可以用于注册次级域名(例如:example.i2p)。若想注册次级域名,请使用 i2pd-tools。"},
{"Address", "地址"},
{"Type", "类型"},
{"EncType", "加密类型"},
{"Inbound tunnels", "入站隧道"},
{"ms", "毫秒"},
{"Outbound tunnels", "出站隧道"},
{"Tags", "标签"},
{"Incoming", "传入"},
{"Outgoing", "传出"},
{"Destination", "目标"},
{"Amount", "数量"},
{"Incoming Tags", "传入标签"},
{"Tags sessions", "标签会话"},
{"Status", "状态"},
{"Local Destination", "本地目标"},
{"Streams", "流"},
{"Close stream", "断开流"},
{"I2CP session not found", "未找到 I2CP 会话"},
{"I2CP is not enabled", "I2CP 未启用"},
{"Invalid", "无效"},
{"Store type", "存储类型"},
{"Expires", "过期时间"},
{"Non Expired Leases", "未到期的租约"},
{"Gateway", "网关"},
{"TunnelID", "隧道 ID"},
{"EndDate", "结束日期"},
{"not floodfill", "非洪泛"},
{"Queue size", "队列大小"},
{"Run peer test", "运行群体测试"},
{"Decline transit tunnels", "拒绝中转隧道"},
{"Accept transit tunnels", "允许中转隧道"},
{"Cancel graceful shutdown", "取消计划的停止"},
{"Start graceful shutdown", "待他人断线后停止"},
{"Force shutdown", "强制停止"},
{"Reload external CSS styles", "重载外部 CSS 样式"},
{"<b>Note:</b> any action done here are not persistent and not changes your config files.", "<b>注意:</b> 此处完成的任何操作都不是永久的,不会更改您的配置文件。"},
{"Logging level", "日志级别"},
{"Transit tunnels limit", "中转隧道限制"},
{"Change", "更换"},
{"Change language", "更换语言"},
{"no transit tunnels currently built", "目前未构建中转隧道"},
{"SAM disabled", "SAM 已禁用"},
{"no sessions currently running", "没有正在运行的会话"},
{"SAM session not found", "未找到 SAM 会话"},
{"SAM Session", "SAM 会话"},
{"Server Tunnels", "服务器隧道"},
{"Client Forwards", "客户端转发"},
{"Server Forwards", "服务器转发"},
{"Unknown page", "未知页面"},
{"Invalid token", "无效凭证"},
{"SUCCESS", "成功"},
{"Stream closed", "流已关闭"},
{"Stream not found or already was closed", "流未找到或已关闭"},
{"Destination not found", "找不到目标"},
{"StreamID can't be null", "StreamID 不能为空"},
{"Return to destination page", "返回目标页面"},
{"You will be redirected in 5 seconds", "您将在5秒内被重定向"},
{"Transit tunnels count must not exceed 65535", "中转隧道数量不能超过 65535"},
{"Back to commands list", "返回命令列表"},
{"Register at reg.i2p", "在 reg.i2p 注册域名"},
{"Description", "描述"},
{"A bit information about service on domain", "在此域名上运行的服务的一些信息"},
{"Submit", "提交"},
{"Domain can't end with .b32.i2p", "域名不能以 .b32.i2p 结尾"},
{"Domain must end with .i2p", "域名必须以 .i2p 结尾"},
{"Such destination is not found", "找不到此目标"},
{"Unknown command", "未知指令"},
{"Command accepted", "已接受指令"},
{"Proxy error", "代理错误"},
{"Proxy info", "代理信息"},
{"Proxy error: Host not found", "代理错误:找不到主机"},
{"Remote host not found in router's addressbook", "在路由的地址簿中找不到远程主机"},
{"You may try to find this host on jump services below", "您可以尝试在下方的跳转服务上找到这个主机"},
{"Invalid request", "无效请求"},
{"Proxy unable to parse your request", "代理无法解析您的请求"},
{"addresshelper is not supported", "不支持地址助手"},
{"Host", "主机"},
{"added to router's addressbook from helper", "将此地址从地址助手添加到地址簿"},
{"Click here to proceed:", "点击此处继续:"},
{"Continue", "继续"},
{"Addresshelper found", "找到地址助手"},
{"already in router's addressbook", "已在路由器的地址簿中"},
{"Click here to update record:", "点击此处更新地址簿记录"},
{"invalid request uri", "无效的 URL 请求"},
{"Can't detect destination host from request", "无法从请求中检测到目标主机"},
{"Outproxy failure", "出口代理失效"},
{"bad outproxy settings", "错误的出口代理设置"},
{"not inside I2P network, but outproxy is not enabled", "该地址不在 I2P 网络内,但未启用出口代理"},
{"unknown outproxy url", "未知的出口代理地址"},
{"cannot resolve upstream proxy", "无法解析上游代理"},
{"hostname too long", "主机名过长"},
{"cannot connect to upstream socks proxy", "无法连接到上游 socks 代理"},
{"Cannot negotiate with socks proxy", "无法与 socks 代理协商"},
{"CONNECT error", "连接错误"},
{"Failed to Connect", "连接失败"},
{"socks proxy error", "socks 代理错误"},
{"failed to send request to upstream", "向上游发送请求失败"},
{"No Reply From socks proxy", "没有来自 socks 代理的回复"},
{"cannot connect", "无法连接"},
{"http out proxy not implemented", "http 出口代理未实现"},
{"cannot connect to upstream http proxy", "无法连接到上游 http 代理"},
{"Host is down", "主机已关闭"},
{"Can't create connection to requested host, it may be down. Please try again later.", "无法创建到目标主机的连接。主机可能已下线,请稍后再试。"},
{"", ""},
};
static std::map<std::string, std::vector<std::string>> plurals
{
{"days", {"日"}},
{"hours", {"时"}},
{"minutes", {"分"}},
{"seconds", {"秒"}},
{"", {""}},
};
std::shared_ptr<const i2p::i18n::Locale> GetLocale()
{
return std::make_shared<i2p::i18n::Locale>(language, strings, plurals, [] (int n)->int { return plural(n); });
}
} // language
} // i18n
} // i2p
<|endoftext|>
|
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 HTTP_RESPONSE_HPP
#define HTTP_RESPONSE_HPP
#include "message.hpp"
#include "status_line.hpp"
namespace http {
//--------------------------------
// This class is used to represent
// an http response message
//--------------------------------
class Response : public Message {
private:
//------------------------------
// Internal class type aliases
//------------------------------
using Code = status_t;
//------------------------------
public:
//------------------------------
// Constructor to set up a response
// by providing information for the
// status line of the response message
//
// @param code - The status code
// @param version - The version of the message
//------------------------------
explicit Response(const Code code = OK, const Version version = Version{}) noexcept;
//----------------------------------------
// Constructor to construct a response
// message from the incoming character
// stream of data which is a <std::string>
// object
//
// @tparam (std::string) response - The character stream
// of data
//
// @param limit - Capacity of how many fields can
// be added
//----------------------------------------
template <typename Egress>
explicit Response(Egress&& response, const Limit limit = 100);
//----------------------------------------
// Default copy constructor
//----------------------------------------
Response(const Response&) = default;
//----------------------------------------
// Default move constructor
//----------------------------------------
Response(Response&&) noexcept = default;
//------------------------------
// Default destructor
//------------------------------
~Response() noexcept = default;
//----------------------------------------
// Default copy assignment operator
//----------------------------------------
Response& operator = (const Response&) = default;
//----------------------------------------
// Default move assignment operator
//----------------------------------------
Response& operator = (Response&&) = default;
//------------------------------
// Get the status code of this
// message
//
// @return - The status code of this
// message
//------------------------------
Code status_code() const noexcept;
//------------------------------
// Change the status code of this
// message
//
// @param code - The new status code to set
// on this message
//
// @return - The object that invoked this method
//------------------------------
Response& set_status_code(const Code code) noexcept;
//----------------------------------------
// Reset the response message as if it was now
// default constructed
//
// @return - The object that invoked this method
//----------------------------------------
virtual Response& reset() noexcept override;
//-----------------------------------
// Get a string representation of this
// class
//
// @return - A string representation
//-----------------------------------
virtual std::string to_string() const override;
//-----------------------------------
// Operator to transform this class
// into string form
//-----------------------------------
operator std::string () const;
//-----------------------------------
private:
//------------------------------
// Class data members
Status_line status_line_;
//------------------------------
}; //< class Response
/**--v----------- Implementation Details -----------v--**/
inline Response::Response(const Code code, const Version version) noexcept:
status_line_{version, code}
{}
template <typename Egress>
inline Response::Response(Egress&& response, const Limit limit) :
Message{limit},
status_line_{response}
{
add_headers(std::forward<Egress>(response));
auto start_of_body = response.find("\r\n\r\n");
if (start_of_body not_eq std::string::npos) {
add_body(response.substr(start_of_body + 4));
}
}
inline Response::Code Response::status_code() const noexcept {
return static_cast<status_t>(status_line_.get_code());
}
inline Response& Response::set_status_code(const Code code) noexcept {
status_line_.set_code(code);
return *this;
}
inline Response& Response::reset() noexcept {
Message::reset();
return set_status_code(OK);
}
inline std::string Response::to_string() const {
return *this;
}
inline Response::operator std::string () const {
std::ostringstream res;
//-----------------------------------
res << status_line_
<< Message::to_string();
//-----------------------------------
return res.str();
}
inline Response& operator << (Response& res, const Header_set& headers) {
for (const auto& field : headers) {
res.add_header(field.first, field.second);
}
return res;
}
inline Response_ptr make_response(buffer_t buf, const size_t len) {
return std::make_unique<Response>(std::string{reinterpret_cast<char*>(buf.get()), len});
}
inline std::ostream& operator << (std::ostream& output_device, const Response& res) {
return output_device << res.to_string();
}
/**--^----------- Implementation Details -----------^--**/
} //< namespace http
#endif //< HTTP_RESPONSE_HPP
<commit_msg>Refactored http::Response<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 HTTP_RESPONSE_HPP
#define HTTP_RESPONSE_HPP
#include "message.hpp"
#include "status_line.hpp"
namespace http {
/**
* @brief This class is used to represent
* an HTTP response message
*/
class Response : public Message {
private:
//------------------------------
// Internal class type aliases
using Code = status_t;
//------------------------------
public:
/**
* @brief Constructor to set up a response
* by providing information for the
* status line of the response message
*
* @param code:
* The status code
*
* @param version:
* The version of the message
*/
explicit Response(const Code code = OK, const Version version = Version{}) noexcept;
/**
* @brief Construct a response message from the
* incoming character stream of data which is a
* {std::string} object
*
* @tparam T response:
* The character stream of data
*
* @param limit:
* Capacity of how many fields can be added to the header section
*/
template
<
typename T,
typename = std::enable_if_t
<std::is_same
<std::string, std::remove_const_t
<std::remove_reference_t<T>>>::value>
>
explicit Response(T&& response, const Limit limit = 100);
/**
* @brief Default copy constructor
*/
Response(const Response&) = default;
/**
* @brief Default move constructor
*/
Response(Response&&) noexcept = default;
/**
* @brief Default destructor
*/
~Response() noexcept = default;
/**
* @brief Default copy assignment operator
*/
Response& operator = (const Response&) = default;
/**
* @brief Default move assignment operator
*/
Response& operator = (Response&&) = default;
/**
* @brief Get the status code of this message
*
* @return The status code of this message
*/
Code status_code() const noexcept;
/**
* @brief Change the status code of this message
*
* @param code:
* The new status code to set on this message
*
* @return The object that invoked this method
*/
Response& set_status_code(const Code code) noexcept;
/**
* @brief Reset the response message as if it was now
* default constructed
*
* @return The object that invoked this method
*/
virtual Response& reset() noexcept override;
/**
* @brief Get a string representation of this
* class
*
* @return A string representation
*/
virtual std::string to_string() const override;
/**
* @brief Operator to transform this class
* into string form
*/
operator std::string () const;
//-----------------------------------
private:
//------------------------------
// Class data members
Status_line status_line_;
//------------------------------
}; //< class Response
/**--v----------- Implementation Details -----------v--**/
inline Response::Response(const Code code, const Version version) noexcept
: status_line_{version, code}
{}
template <typename Egress, typename>
inline Response::Response(Egress&& response, const Limit limit)
: Message{limit}
, status_line_{response}
{
add_headers(response);
std::size_t start_of_body;
if ((start_of_body = response.find("\r\n\r\n")) not_eq std::string::npos) {
add_body(response.substr(start_of_body + 4));
} else if ((start_of_body = response.find("\n\n")) not_eq std::string::npos) {
add_body(response.substr(start_of_body + 2));
}
}
inline Response::Code Response::status_code() const noexcept {
return static_cast<status_t>(status_line_.get_code());
}
inline Response& Response::set_status_code(const Code code) noexcept {
status_line_.set_code(code);
return *this;
}
inline Response& Response::reset() noexcept {
Message::reset();
return set_status_code(OK);
}
inline std::string Response::to_string() const {
std::ostringstream res;
//-----------------------------------
res << status_line_
<< Message::to_string();
//-----------------------------------
return res.str();
}
inline Response::operator std::string () const {
return to_string();
}
inline Response& operator << (Response& res, const Header_set& headers) {
for (const auto& field : headers) {
res.add_header(field.first, field.second);
}
return res;
}
inline Response_ptr make_response(buffer_t buf, const size_t len) {
return std::make_unique<Response>(std::string{reinterpret_cast<char*>(buf.get()), len});
}
inline std::ostream& operator << (std::ostream& output_device, const Response& res) {
return output_device << res.to_string();
}
/**--^----------- Implementation Details -----------^--**/
} //< namespace http
#endif //< HTTP_RESPONSE_HPP
<|endoftext|>
|
<commit_before>/******************************************************************************/
/* Copyright 2015 Lucas Dário and Renato Cordeiro Ferreira */
/* */
/* 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 HPP_FORK_DEFINED
#define HPP_FORK_DEFINED
// Standard headers
#include <queue>
#include <mutex>
#include <memory>
#include <thread>
#include <iostream>
#include <condition_variable>
// Internal headers
#include "Philosopher.hpp"
// Forward declaration
class Fork;
// Pointer
using ForkPtr = std::shared_ptr<Fork>;
// Class
class Fork {
public:
// Static methods
template<typename... Args>
static ForkPtr make(Args... args) {
return ForkPtr(new Fork(std::forward<Args>(args)...));
}
// Synchronized methods
void take() {
std::unique_lock<std::mutex> lock(_mutex);
wait(lock, not_using);
}
void drop() {
std::unique_lock<std::mutex> lock(_mutex);
signal(not_using);
}
// Concrete methods
unsigned int position() const {
return _position;
}
void position(unsigned int position) {
_position = position;
}
private:
// Instance variables
unsigned int _position;
// Monitor variables
std::mutex _mutex;
std::queue<std::thread::id> _waiting;
std::condition_variable not_using;
// Monitor methods
void wait(std::unique_lock<std::mutex> &lock,
std::condition_variable &cv) {
_waiting.push(std::this_thread::get_id());
cv.wait(lock, [this]() { return _waiting.front() == std::this_thread::get_id(); });
_waiting.pop();
}
void signal(std::condition_variable &cv) {
cv.notify_all();
}
};
#endif
<commit_msg>Fix wait() and signal() from monitor. The fork now know when it's available or not<commit_after>/******************************************************************************/
/* Copyright 2015 Lucas Dário and Renato Cordeiro Ferreira */
/* */
/* 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 HPP_FORK_DEFINED
#define HPP_FORK_DEFINED
// Standard headers
#include <queue>
#include <mutex>
#include <memory>
#include <thread>
#include <iostream>
#include <condition_variable>
// Internal headers
#include "Philosopher.hpp"
// Forward declaration
class Fork;
// Pointer
using ForkPtr = std::shared_ptr<Fork>;
// Class
class Fork {
public:
// Static methods
template<typename... Args>
static ForkPtr make(Args... args) {
return ForkPtr(new Fork(std::forward<Args>(args)...));
}
// Synchronized methods
void take() {
std::unique_lock<std::mutex> lock(_mutex);
wait(lock, not_using);
}
void drop() {
std::unique_lock<std::mutex> lock(_mutex);
signal(not_using);
}
// Concrete methods
unsigned int position() const {
return _position;
}
void position(unsigned int position) {
_position = position;
}
private:
// Instance variables
unsigned int _position;
// Monitor variables
std::mutex _mutex;
std::queue<std::thread::id> _waiting;
std::condition_variable not_using;
bool available = true;
// Monitor methods
void wait(std::unique_lock<std::mutex> &lock,
std::condition_variable &cv) {
_waiting.push(std::this_thread::get_id());
cv.wait(lock, [this]() { return std::this_thread::get_id() == _waiting.front() && available; });
available = false;
_waiting.pop();
}
void signal(std::condition_variable &cv) {
available = true;
cv.notify_all();
}
};
#endif
<|endoftext|>
|
<commit_before>#pragma once
#define AUSS_HPP
#include <sstream>
#ifdef AUSS_USE_OWN_NAMESPACE
#ifndef AUSS_OWN_NAMESPACE_NAME
#define AUSS_OWN_NAMESPACE_NAME auss
#endif
namespace AUSS_OWN_NAMESPACE_NAME {
#endif
class AutoStringStream {
public:
AutoStringStream() : m_stream() {}
virtual ~AutoStringStream() {}
template<typename T>
AutoStringStream& operator<<(const T& arg) {
m_stream << arg;
return *this;
}
AutoStringStream& operator<<(const bool arg) {
m_stream << (arg ? "true" : "false");
return *this;
}
operator std::string() const {
return m_stream.str();
}
const std::string to_string() const {
return m_stream.str();
}
private:
std::stringstream m_stream;
};
typedef AutoStringStream auss_t;
#ifdef AUSS_USE_OWN_NAMESPACE
}
#endif
<commit_msg>AUSS_CUSTOM_TYPEDEF<commit_after>#pragma once
#define AUSS_HPP
#include <sstream>
#ifdef AUSS_USE_OWN_NAMESPACE
#ifndef AUSS_OWN_NAMESPACE_NAME
#define AUSS_OWN_NAMESPACE_NAME auss
#endif
namespace AUSS_OWN_NAMESPACE_NAME {
#endif
class AutoStringStream {
public:
AutoStringStream() : m_stream() {}
virtual ~AutoStringStream() {}
template<typename T>
AutoStringStream& operator<<(const T& arg) {
m_stream << arg;
return *this;
}
AutoStringStream& operator<<(const bool arg) {
m_stream << (arg ? "true" : "false");
return *this;
}
operator std::string() const {
return m_stream.str();
}
const std::string to_string() const {
return m_stream.str();
}
private:
std::stringstream m_stream;
};
#ifndef AUSS_CUSTOM_TYPEDEF
typedef AutoStringStream auss_t;
#endif
#ifdef AUSS_USE_OWN_NAMESPACE
}
#endif
<|endoftext|>
|
<commit_before>#ifndef __JCONER_JSON_HPP__
#define __JCONER_JSON_HPP__
#include "token.hpp"
#include "value.hpp"
#include "stream.hpp"
#include "parser.hpp"
#include "dump.hpp"
#endif
<commit_msg>Add error.hpp in json.hpp<commit_after>#ifndef __JCONER_JSON_HPP__
#define __JCONER_JSON_HPP__
#include "token.hpp"
#include "value.hpp"
#include "stream.hpp"
#include "parser.hpp"
#include "dump.hpp"
#include "error.hpp"
#endif
<|endoftext|>
|
<commit_before>#ifndef _PITO_INTERCEPTOR_LIB_C_
#define _PITO_INTERCEPTOR_LIB_C_
#include <pito/interceptor/lib/c_traits.hpp>
#include <pito/interceptor/SystemCall.hpp>
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdarg.h>
#include <fcntl.h>
#include "config.hpp"
#ifndef PITO_SYSTEM_CALL_BASE
#define PITO_SYSTEM_CALL_BASE SystemCallBase
#endif
#ifndef PITO_JAIL_BASE
#define PITO_JAIL_BASE PITO_SYSTEM_CALL_BASE
#endif
namespace pito { namespace interceptor {
using namespace system_call;
template <>
struct Library<library::c> : LibraryHelper {
Library() : LibraryHelper("libc.so") {}
};
#define PITO_ARGS(idx) type::at<idx, arg_types>::type arg##idx
#define PITO_ARGS_1 PITO_ARGS(0)
#define PITO_ARGS_2 PITO_ARGS(0), PITO_ARGS(1)
#define PITO_ARGS_3 PITO_ARGS(0), PITO_ARGS(1), PITO_ARGS(2)
#define PITO_ARGS_4 PITO_ARGS(0), PITO_ARGS(1), PITO_ARGS(2), PITO_ARGS(3)
#define PITO_ARGS_5 PITO_ARGS(0), PITO_ARGS(1), PITO_ARGS(2), PITO_ARGS(3), PITO_ARGS(4)
#define PITO_SYSTEM_CALL_WITH_BASE(_name, _library, _retVal, _argTypes, _argVals, _argTypeVals, _base) \
template <> \
struct SystemCall<_name> \
: _base <_name, library::_library, _retVal _argTypes> {}; \
extern "C" { \
_retVal _name _argTypeVals { \
return PITO_SUPER(_name) _argVals; \
} \
}
#define PITO_SYSTEM_CALL(_name, _library, _retVal, _argTypes, _argVals, _argTypeVals) \
PITO_SYSTEM_CALL_WITH_BASE(_name, _library, _retVal, _argTypes, _argVals, _argTypeVals, PITO_SYSTEM_CALL_BASE)
////////////////////////////////////////////////////////////////////////////////
// security intercepts
PITO_SYSTEM_CALL(chmod, c, int, (const char *, mode_t), \
(path, mode), \
(char const *path, mode_t mode))
PITO_SYSTEM_CALL(fchmod, c, int, (int, mode_t), \
(fd, mode), \
(int fd, mode_t mode))
PITO_SYSTEM_CALL(fchmodat, c, int, (int, const char *, mode_t, int), \
(dirfd, path, mode, flags), \
(int dirfd, char const *path, mode_t mode, int flags))
PITO_SYSTEM_CALL(chown, c, int, (const char *, uid_t, gid_t), \
(path, owner, group), \
(const char *path, uid_t owner, gid_t group))
PITO_SYSTEM_CALL(fchown, c, int, (int, uid_t, gid_t), \
(fd, owner, group), \
(int fd, uid_t owner, gid_t group))
PITO_SYSTEM_CALL(fchownat, c, int, (int, const char *, uid_t, gid_t, int), \
(dirfd, pathname, owner, group, flags), \
(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags))
template <>
struct SystemCall<open>
: PITO_SYSTEM_CALL_BASE<open, library::c, int(const char *, int)> {};
extern "C" {
int open(const char *pathname, int flags, ...) {
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(open)(pathname, flags, mode);
}
else return PITO_SUPER(open)(pathname, flags);
}
}
template <>
struct SystemCall<openat>
: PITO_SYSTEM_CALL_BASE<openat, library::c, int(int, const char *, int)> {};
extern "C" {
int openat(int dirfd, const char *pathname, int flags, ...) {
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(openat)(dirfd, pathname, flags, mode);
}
else return PITO_SUPER(openat)(dirfd, pathname, flags);
}
}
PITO_SYSTEM_CALL(creat, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(fopen, c, FILE *, (const char *, const char *), \
(path, mode), \
(const char *path, const char *mode))
PITO_SYSTEM_CALL(lchown, c, int, (const char *, uid_t, gid_t), \
(path, owner, group), \
(const char *path, uid_t owner, gid_t group))
PITO_SYSTEM_CALL(link, c, int, (const char *, const char *), \
(oldpath, newpath), \
(const char *oldpath, const char *newpath))
PITO_SYSTEM_CALL(linkat, c, int, (int, const char *, int, const char *, int), \
(olddirfd, oldpath, newdirfd, newpath, flags), \
(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags))
PITO_SYSTEM_CALL(mkdir, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(mkdirat, c, int, (int, const char *, mode_t), \
(dirfd, pathname, mode), \
(int dirfd, const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(opendir, c, DIR *, (const char *), \
(name), \
(const char *name))
PITO_SYSTEM_CALL(mknod, c, int, (const char *, mode_t, dev_t), \
(pathname, mode, dev), \
(const char *pathname, mode_t mode, dev_t dev))
PITO_SYSTEM_CALL(mknodat, c, int, (int, const char *, mode_t, dev_t), \
(dirfd, pathname, mode, dev), \
(int dirfd, const char *pathname, mode_t mode, dev_t dev))
// function todo: __xmknod
PITO_SYSTEM_CALL(mkfifo, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(mkfifoat, c, int, (int, const char *, mode_t), \
(dirfd, pathname, mode), \
(int dirfd, const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(access, c, int, (const char *, int), \
(pathname, mode), \
(const char *pathname, int mode))
PITO_SYSTEM_CALL(faccessat, c, int, (int, const char *, int, int), \
(dirfd, pathname, mode, flags), \
(int dirfd, const char *pathname, int mode, int flags))
PITO_SYSTEM_CALL(rename, c, int, (const char *, const char *), \
(oldpath, newpath), \
(const char *oldpath, const char *newpath))
PITO_SYSTEM_CALL(renameat, c, int, (int, const char *, int, const char *), \
(olddirfd, oldpath, newdirfd, newpath), \
(int olddirfd, const char *oldpath, int newdirfd, const char *newpath))
PITO_SYSTEM_CALL(rmdir, c, int, (const char *), \
(pathname), \
(const char *pathname))
PITO_SYSTEM_CALL(symlink, c, int, (const char *, const char *), \
(oldpath, newpath), \
(const char *oldpath, const char *newpath))
PITO_SYSTEM_CALL(symlinkat, c, int, (const char *, int, const char *), \
(oldpath, newdirfd, newpath), \
(const char *oldpath, int newdirfd, const char *newpath))
PITO_SYSTEM_CALL(truncate, c, int, (const char *, off_t), \
(path, length), \
(const char *path, off_t length))
PITO_SYSTEM_CALL(unlink, c, int, (const char *), \
(pathname), \
(const char *pathname))
PITO_SYSTEM_CALL(unlinkat, c, int, (int, const char *, int), \
(dirfd, pathname, flags), \
(int dirfd, const char *pathname, int flags))
PITO_SYSTEM_CALL(getcwd, c, char *, (char *, size_t), \
(buf, size), \
(char *buf, size_t size))
template <>
struct SystemCall<open64>
: PITO_SYSTEM_CALL_BASE<open64, library::c, int(const char *, int)> {};
extern "C" {
int open64(const char *pathname, int flags, ...) {
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(open64)(pathname, flags, mode);
}
else return PITO_SUPER(open64)(pathname, flags);
}
}
template <>
struct SystemCall<openat64>
: PITO_SYSTEM_CALL_BASE<openat64, library::c, int(int, const char *, int)> {};
extern "C" {
typedef SystemCall<openat64>::arg_types arg_types;
int openat64(PITO_ARGS_3, ...) {
if (arg2 & O_CREAT) {
va_list ap;
va_start(ap, arg2);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(openat64)(arg0, arg1, arg2, mode);
}
else return PITO_SUPER(openat64)(arg0, arg1, arg2);
}
}
PITO_SYSTEM_CALL(creat64, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(fopen64, c, FILE *, (const char *, const char *), \
(path, mode), \
(const char *path, const char *mode))
PITO_SYSTEM_CALL(truncate64, c, int, (const char *, PITO_OFF64_TYPE), \
(path, length), \
(const char *path, PITO_OFF64_TYPE length))
////////////////////////////////////////////////////////////////////////////////
// jail
////////////////////////////////////////////////////////////////////////////////
PITO_SYSTEM_CALL_WITH_BASE(execve, c, int, (const char *, char *const[], char *const[]), \
(filename, argv, envp), \
(const char *filename, char *const argv[], char *const envp[]), \
PITO_JAIL_BASE)
PITO_SYSTEM_CALL_WITH_BASE(execv, c, int, (const char *, char *const[]), \
(filename, argv), \
(const char *filename, char *const argv[]), \
PITO_JAIL_BASE)
PITO_SYSTEM_CALL_WITH_BASE(execvp, c, int, (const char *, char *const[]), \
(filename, argv), \
(const char *filename, char *const argv[]), \
PITO_JAIL_BASE)
////////////////////////////////////////////////////////////////////////////////
// end jail
////////////////////////////////////////////////////////////////////////////////
PITO_SYSTEM_CALL(utime, c, int, (const char *, const struct utimbuf *), \
(filename, times), \
(const char *filename, const struct utimbuf *times))
PITO_SYSTEM_CALL(utimes, c, int, (const char *, const struct timeval[2]), \
(filename, times), \
(const char *filename, const struct timeval times[2]))
PITO_SYSTEM_CALL(utimensat, c, int, (int, const char *, const struct timespec[2], int), \
(dirfd, pathname, times, flags), \
(int dirfd, const char *pathname, const struct timespec times[2], int flags))
PITO_SYSTEM_CALL(futimesat, c, int, (int, const char *, const struct timeval[2]), \
(dirfd, pathname, times), \
(int dirfd, const char *pathname, const struct timeval times[2]))
PITO_SYSTEM_CALL(lutimes, c, int, (const char *, const struct timeval[2]), \
(filename, tv), \
(const char *filename, const struct timeval tv[2]))
PITO_SYSTEM_CALL(getuid, c, int, (void), (), ())
} }
#endif
<commit_msg>make it more flexible, oh<commit_after>#ifndef _PITO_INTERCEPTOR_LIB_C_
#define _PITO_INTERCEPTOR_LIB_C_
#include <pito/interceptor/lib/c_traits.hpp>
#include <pito/interceptor/SystemCall.hpp>
#include <sys/types.h>
#include <sys/time.h>
#include <dirent.h>
#include <stdlib.h>
#include <stdarg.h>
#include <fcntl.h>
#include "config.hpp"
#ifndef PITO_SYSTEM_CALL_BASE
#define PITO_SYSTEM_CALL_BASE SystemCallBase
#endif
#ifndef PITO_JAIL_BASE
#define PITO_JAIL_BASE PITO_SYSTEM_CALL_BASE
#endif
namespace pito { namespace interceptor {
using namespace system_call;
template <>
struct Library<library::c> : LibraryHelper {
Library() : LibraryHelper("libc.so") {}
};
#define PITO_ARG_NAME(idx) arg##idx
#define PITO_ARG_NAMES_1(idx) PITO_ARG_NAME(0)
#define PITO_ARG_NAMES_2(idx) PITO_ARG_NAME_1, PITO_ARG_NAME(1)
#define PITO_ARG_NAMES_3(idx) PITO_ARG_NAME_2, PITO_ARG_NAME(2)
#define PITO_ARG_NAMES_4(idx) PITO_ARG_NAME_3, PITO_ARG_NAME(3)
#define PITO_ARG_NAMES_5(idx) PITO_ARG_NAME_4, PITO_ARG_NAME(4)
#define PITO_ARG(idx, list) type::at<idx, list>::type PITO_ARG_NAME(idx)
#define PITO_ARGS_1(list) PITO_ARG(0, list)
#define PITO_ARGS_2(list) PITO_ARGS_1(list), PITO_ARG(1, list)
#define PITO_ARGS_3(list) PITO_ARGS_2(list), PITO_ARG(2, list)
#define PITO_ARGS_4(list) PITO_ARGS_3(list), PITO_ARG(3, list)
#define PITO_ARGS_5(list) PITO_ARGS_4(list), PITO_ARG(4, list)
#define PITO_SYSTEM_CALL_WITH_BASE(_name, _library, _retVal, _argTypes, _argVals, _argTypeVals, _base) \
template <> \
struct SystemCall<_name> \
: _base <_name, library::_library, _retVal _argTypes> {}; \
extern "C" { \
_retVal _name _argTypeVals { \
return PITO_SUPER(_name) _argVals; \
} \
}
#define PITO_SYSTEM_CALL(_name, _library, _retVal, _argTypes, _argVals, _argTypeVals) \
PITO_SYSTEM_CALL_WITH_BASE(_name, _library, _retVal, _argTypes, _argVals, _argTypeVals, PITO_SYSTEM_CALL_BASE)
////////////////////////////////////////////////////////////////////////////////
// security intercepts
PITO_SYSTEM_CALL(chmod, c, int, (const char *, mode_t), \
(path, mode), \
(char const *path, mode_t mode))
PITO_SYSTEM_CALL(fchmod, c, int, (int, mode_t), \
(fd, mode), \
(int fd, mode_t mode))
PITO_SYSTEM_CALL(fchmodat, c, int, (int, const char *, mode_t, int), \
(dirfd, path, mode, flags), \
(int dirfd, char const *path, mode_t mode, int flags))
PITO_SYSTEM_CALL(chown, c, int, (const char *, uid_t, gid_t), \
(path, owner, group), \
(const char *path, uid_t owner, gid_t group))
PITO_SYSTEM_CALL(fchown, c, int, (int, uid_t, gid_t), \
(fd, owner, group), \
(int fd, uid_t owner, gid_t group))
PITO_SYSTEM_CALL(fchownat, c, int, (int, const char *, uid_t, gid_t, int), \
(dirfd, pathname, owner, group, flags), \
(int dirfd, const char *pathname, uid_t owner, gid_t group, int flags))
template <>
struct SystemCall<open>
: PITO_SYSTEM_CALL_BASE<open, library::c, int(const char *, int)> {};
extern "C" {
int open(const char *pathname, int flags, ...) {
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(open)(pathname, flags, mode);
}
else return PITO_SUPER(open)(pathname, flags);
}
}
template <>
struct SystemCall<openat>
: PITO_SYSTEM_CALL_BASE<openat, library::c, int(int, const char *, int)> {};
extern "C" {
int openat(int dirfd, const char *pathname, int flags, ...) {
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(openat)(dirfd, pathname, flags, mode);
}
else return PITO_SUPER(openat)(dirfd, pathname, flags);
}
}
PITO_SYSTEM_CALL(creat, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(fopen, c, FILE *, (const char *, const char *), \
(path, mode), \
(const char *path, const char *mode))
PITO_SYSTEM_CALL(lchown, c, int, (const char *, uid_t, gid_t), \
(path, owner, group), \
(const char *path, uid_t owner, gid_t group))
PITO_SYSTEM_CALL(link, c, int, (const char *, const char *), \
(oldpath, newpath), \
(const char *oldpath, const char *newpath))
PITO_SYSTEM_CALL(linkat, c, int, (int, const char *, int, const char *, int), \
(olddirfd, oldpath, newdirfd, newpath, flags), \
(int olddirfd, const char *oldpath, int newdirfd, const char *newpath, int flags))
PITO_SYSTEM_CALL(mkdir, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(mkdirat, c, int, (int, const char *, mode_t), \
(dirfd, pathname, mode), \
(int dirfd, const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(opendir, c, DIR *, (const char *), \
(name), \
(const char *name))
PITO_SYSTEM_CALL(mknod, c, int, (const char *, mode_t, dev_t), \
(pathname, mode, dev), \
(const char *pathname, mode_t mode, dev_t dev))
PITO_SYSTEM_CALL(mknodat, c, int, (int, const char *, mode_t, dev_t), \
(dirfd, pathname, mode, dev), \
(int dirfd, const char *pathname, mode_t mode, dev_t dev))
// function todo: __xmknod
PITO_SYSTEM_CALL(mkfifo, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(mkfifoat, c, int, (int, const char *, mode_t), \
(dirfd, pathname, mode), \
(int dirfd, const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(access, c, int, (const char *, int), \
(pathname, mode), \
(const char *pathname, int mode))
PITO_SYSTEM_CALL(faccessat, c, int, (int, const char *, int, int), \
(dirfd, pathname, mode, flags), \
(int dirfd, const char *pathname, int mode, int flags))
PITO_SYSTEM_CALL(rename, c, int, (const char *, const char *), \
(oldpath, newpath), \
(const char *oldpath, const char *newpath))
PITO_SYSTEM_CALL(renameat, c, int, (int, const char *, int, const char *), \
(olddirfd, oldpath, newdirfd, newpath), \
(int olddirfd, const char *oldpath, int newdirfd, const char *newpath))
PITO_SYSTEM_CALL(rmdir, c, int, (const char *), \
(pathname), \
(const char *pathname))
PITO_SYSTEM_CALL(symlink, c, int, (const char *, const char *), \
(oldpath, newpath), \
(const char *oldpath, const char *newpath))
PITO_SYSTEM_CALL(symlinkat, c, int, (const char *, int, const char *), \
(oldpath, newdirfd, newpath), \
(const char *oldpath, int newdirfd, const char *newpath))
PITO_SYSTEM_CALL(truncate, c, int, (const char *, off_t), \
(path, length), \
(const char *path, off_t length))
PITO_SYSTEM_CALL(unlink, c, int, (const char *), \
(pathname), \
(const char *pathname))
PITO_SYSTEM_CALL(unlinkat, c, int, (int, const char *, int), \
(dirfd, pathname, flags), \
(int dirfd, const char *pathname, int flags))
PITO_SYSTEM_CALL(getcwd, c, char *, (char *, size_t), \
(buf, size), \
(char *buf, size_t size))
template <>
struct SystemCall<open64>
: PITO_SYSTEM_CALL_BASE<open64, library::c, int(const char *, int)> {};
extern "C" {
int open64(const char *pathname, int flags, ...) {
if (flags & O_CREAT) {
va_list ap;
va_start(ap, flags);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(open64)(pathname, flags, mode);
}
else return PITO_SUPER(open64)(pathname, flags);
}
}
template <>
struct SystemCall<openat64>
: PITO_SYSTEM_CALL_BASE<openat64, library::c, int(int, const char *, int)> {};
extern "C" {
int openat64(PITO_ARGS_3(SystemCall<openat64>::arg_types), ...) {
if (arg2 & O_CREAT) {
va_list ap;
va_start(ap, arg2);
mode_t mode = va_arg(ap, int);
va_end(ap);
return PITO_SUPER(openat64)(arg0, arg1, arg2, mode);
}
else return PITO_SUPER(openat64)(arg0, arg1, arg2);
}
}
PITO_SYSTEM_CALL(creat64, c, int, (const char *, mode_t), \
(pathname, mode), \
(const char *pathname, mode_t mode))
PITO_SYSTEM_CALL(fopen64, c, FILE *, (const char *, const char *), \
(path, mode), \
(const char *path, const char *mode))
PITO_SYSTEM_CALL(truncate64, c, int, (const char *, PITO_OFF64_TYPE), \
(path, length), \
(const char *path, PITO_OFF64_TYPE length))
////////////////////////////////////////////////////////////////////////////////
// jail
////////////////////////////////////////////////////////////////////////////////
PITO_SYSTEM_CALL_WITH_BASE(execve, c, int, (const char *, char *const[], char *const[]), \
(filename, argv, envp), \
(const char *filename, char *const argv[], char *const envp[]), \
PITO_JAIL_BASE)
PITO_SYSTEM_CALL_WITH_BASE(execv, c, int, (const char *, char *const[]), \
(filename, argv), \
(const char *filename, char *const argv[]), \
PITO_JAIL_BASE)
PITO_SYSTEM_CALL_WITH_BASE(execvp, c, int, (const char *, char *const[]), \
(filename, argv), \
(const char *filename, char *const argv[]), \
PITO_JAIL_BASE)
////////////////////////////////////////////////////////////////////////////////
// end jail
////////////////////////////////////////////////////////////////////////////////
PITO_SYSTEM_CALL(utime, c, int, (const char *, const struct utimbuf *), \
(filename, times), \
(const char *filename, const struct utimbuf *times))
PITO_SYSTEM_CALL(utimes, c, int, (const char *, const struct timeval[2]), \
(filename, times), \
(const char *filename, const struct timeval times[2]))
PITO_SYSTEM_CALL(utimensat, c, int, (int, const char *, const struct timespec[2], int), \
(dirfd, pathname, times, flags), \
(int dirfd, const char *pathname, const struct timespec times[2], int flags))
PITO_SYSTEM_CALL(futimesat, c, int, (int, const char *, const struct timeval[2]), \
(dirfd, pathname, times), \
(int dirfd, const char *pathname, const struct timeval times[2]))
PITO_SYSTEM_CALL(lutimes, c, int, (const char *, const struct timeval[2]), \
(filename, tv), \
(const char *filename, const struct timeval tv[2]))
PITO_SYSTEM_CALL(getuid, c, int, (void), (), ())
} }
#endif
<|endoftext|>
|
<commit_before>#include "PathShortener.h"
#include "simulation/World.h"
#include "RRT.h"
#include "collision/CollisionDetector.h"
#include "dynamics/Skeleton.h"
using namespace std;
using namespace Eigen;
using namespace dart;
using namespace simulation;
#define RAND12(N1,N2) N1 + ((N2-N1) * ((double)rand() / ((double)RAND_MAX + 1))) // random # between N&M
namespace dart {
namespace planning {
PathShortener::PathShortener() {}
PathShortener::PathShortener(World* world, dynamics::Skeleton* robot, const vector<int> &dofs, double stepSize) :
world(world),
robot(robot),
dofs(dofs),
stepSize(stepSize)
{}
PathShortener::~PathShortener()
{}
void PathShortener::shortenPath(list<VectorXd> &path)
{
printf("--> Start Brute Force Shortener \n");
srand(time(NULL));
VectorXd savedDofs = robot->getConfig(dofs);
const int numShortcuts = path.size() * 5;
// Number of checks
for( int count = 0; count < numShortcuts; count++ ) {
if( path.size() < 3 ) { //-- No way we can reduce something leaving out the extremes
return;
}
int node1Index;
int node2Index;
do {
node1Index = (int) RAND12(0, path.size());
node2Index = (int) RAND12(0, path.size());
} while(node2Index <= node1Index + 1);
list<VectorXd>::iterator node1Iter = path.begin();
advance(node1Iter, node1Index);
list<VectorXd>::iterator node2Iter = node1Iter;
advance(node2Iter, node2Index - node1Index);
list<VectorXd> intermediatePoints;
if(localPlanner(intermediatePoints, node1Iter, node2Iter)) {
list<VectorXd>::iterator node1NextIter = node1Iter;
node1NextIter++;
path.erase(node1NextIter, node2Iter);
path.splice(node2Iter, intermediatePoints);
}
}
robot->setConfig(dofs, savedDofs);
printf("End Brute Force Shortener \n");
}
bool PathShortener::localPlanner(list<VectorXd> &intermediatePoints, list<VectorXd>::const_iterator it1, list<VectorXd>::const_iterator it2) {
return segmentCollisionFree(intermediatePoints, *it1, *it2);
}
// true iff collision-free
// does not check endpoints
// interemdiatePoints are only touched if collision-free
bool PathShortener::segmentCollisionFree(list<VectorXd> &intermediatePoints, const VectorXd &config1, const VectorXd &config2) {
const double length = (config1 - config2).norm();
if(length <= stepSize) {
return true;
}
const int n = (int)(length / stepSize) + 1; // number of intermediate segments
int n1 = n / 2;
int n2 = n / 2;
if(n % 2 == 1) {
n2 += 1;
}
VectorXd midpoint = (double)n2 / (double)n * config1 + (double)n1 / (double)n * config2;
list<VectorXd> intermediatePoints1, intermediatePoints2;
robot->setConfig(dofs, midpoint);
if(!world->checkCollision() && segmentCollisionFree(intermediatePoints1, config1, midpoint)
&& segmentCollisionFree(intermediatePoints2, midpoint, config2))
{
intermediatePoints.clear();
intermediatePoints.splice(intermediatePoints.end(), intermediatePoints1);
intermediatePoints.push_back(midpoint);
intermediatePoints.splice(intermediatePoints.end(), intermediatePoints2);
return true;
}
else {
return false;
}
}
} // namespace planning
} // namespace dart
<commit_msg>Fix compiler error on Windows<commit_after>#include "PathShortener.h"
#include "simulation/World.h"
#include "RRT.h"
#include "collision/CollisionDetector.h"
#include "dynamics/Skeleton.h"
#include <ctime>
using namespace std;
using namespace Eigen;
using namespace dart;
using namespace simulation;
#define RAND12(N1,N2) N1 + ((N2-N1) * ((double)rand() / ((double)RAND_MAX + 1))) // random # between N&M
namespace dart {
namespace planning {
PathShortener::PathShortener() {}
PathShortener::PathShortener(World* world, dynamics::Skeleton* robot, const vector<int> &dofs, double stepSize) :
world(world),
robot(robot),
dofs(dofs),
stepSize(stepSize)
{}
PathShortener::~PathShortener()
{}
void PathShortener::shortenPath(list<VectorXd> &path)
{
printf("--> Start Brute Force Shortener \n");
srand(time(NULL));
VectorXd savedDofs = robot->getConfig(dofs);
const int numShortcuts = path.size() * 5;
// Number of checks
for( int count = 0; count < numShortcuts; count++ ) {
if( path.size() < 3 ) { //-- No way we can reduce something leaving out the extremes
return;
}
int node1Index;
int node2Index;
do {
node1Index = (int) RAND12(0, path.size());
node2Index = (int) RAND12(0, path.size());
} while(node2Index <= node1Index + 1);
list<VectorXd>::iterator node1Iter = path.begin();
advance(node1Iter, node1Index);
list<VectorXd>::iterator node2Iter = node1Iter;
advance(node2Iter, node2Index - node1Index);
list<VectorXd> intermediatePoints;
if(localPlanner(intermediatePoints, node1Iter, node2Iter)) {
list<VectorXd>::iterator node1NextIter = node1Iter;
node1NextIter++;
path.erase(node1NextIter, node2Iter);
path.splice(node2Iter, intermediatePoints);
}
}
robot->setConfig(dofs, savedDofs);
printf("End Brute Force Shortener \n");
}
bool PathShortener::localPlanner(list<VectorXd> &intermediatePoints, list<VectorXd>::const_iterator it1, list<VectorXd>::const_iterator it2) {
return segmentCollisionFree(intermediatePoints, *it1, *it2);
}
// true iff collision-free
// does not check endpoints
// interemdiatePoints are only touched if collision-free
bool PathShortener::segmentCollisionFree(list<VectorXd> &intermediatePoints, const VectorXd &config1, const VectorXd &config2) {
const double length = (config1 - config2).norm();
if(length <= stepSize) {
return true;
}
const int n = (int)(length / stepSize) + 1; // number of intermediate segments
int n1 = n / 2;
int n2 = n / 2;
if(n % 2 == 1) {
n2 += 1;
}
VectorXd midpoint = (double)n2 / (double)n * config1 + (double)n1 / (double)n * config2;
list<VectorXd> intermediatePoints1, intermediatePoints2;
robot->setConfig(dofs, midpoint);
if(!world->checkCollision() && segmentCollisionFree(intermediatePoints1, config1, midpoint)
&& segmentCollisionFree(intermediatePoints2, midpoint, config2))
{
intermediatePoints.clear();
intermediatePoints.splice(intermediatePoints.end(), intermediatePoints1);
intermediatePoints.push_back(midpoint);
intermediatePoints.splice(intermediatePoints.end(), intermediatePoints2);
return true;
}
else {
return false;
}
}
} // namespace planning
} // namespace dart
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
void Delete(Node **Tree, T &value)
{
Node *q;
if (*Tree == nullptr) return;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
q = *Tree;
if ((*q).right ==nullptr) { *Tree = (*q).left; delete q; }
else
if ((*q).left == nullptr) { *Tree = (*q).right; delete q; }
else Delete_(&((*q).left), &q);
}
}
void Delete_(Node **r, Node **q)
{
Node *s;
if ((**r).right == nullptr)
{
(**q).value_ = (**r).value_; *q = *r;
s = *r; *r = (**r).left; delete s;
}
else Delete_(&((**r).right), q);
}
public:
Tree()
{
root = nullptr;
};
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool del(T value)
{
try
{
if (find(value) == 0) throw 1;
}
catch (int i = 1)
{
return 0;
}
Delete(&root, value);
return !find(value);
}
void pr(char* name) const;
};
void main()
{
Tree<int>a;
a.add(7);
bool b=a.del(2);
cout << b;
system("pause");
}
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
try
{
if (file.is_open()==0) throw 1;
}
catch (int i = 1)
{
return 0;
}
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<commit_msg>Update tree.hpp<commit_after>#include <fstream>
#include <iostream>
using namespace std;
template <class T>
class Tree
{
private:
struct Node
{
T value_;
Node *left;
Node *right;
Node() {};
Node(const T value) : value_(value) { };
~Node() {};
void show(ostream &out, int level) const;
};
Node *root;
void null_tree(Node *tr_)
{
if (!tr_) return;
if (tr_->left)
{
null_tree(tr_->left);
tr_->left = nullptr;
}
if (tr_->right)
{
null_tree(tr_->right);
tr_->right = nullptr;
}
delete tr_;
}
Node * find_(const T &value) const
{
Node *tr = root;
while (tr)
{
if (tr->value_ != value)
{
if (value < tr->value_)
tr = tr->left;
else tr = tr->right;
}
else break;
}
if (!tr) return nullptr;
else return tr;
}
void add_node(Node *&add_n, T value)
{
add_n = new Node(value);
add_n->left = nullptr;
add_n->right = nullptr;
}
Node* add_(const T &value, Node * tr = 0)
{
if (!root)
{
root = new Node(value);
root->left = nullptr;
root->right = nullptr;
return root;
}
if (!tr) tr = root;
if ((tr) && (tr->value_ != value))
{
if (value < tr->value_)
{
if (tr->left)
add_(value, tr->left);
else
{
add_node(tr->left, value);
return tr->left;
}
}
else
{
if (tr->right)
add_(value, tr->right);
else
{
add_node(tr->right, value);
return tr->right;
}
}
}
return 0;
}
int count(Node* tr) const
{
if (!tr) return 0;
int l = 0, r = 0;
if (tr->left) l = count(tr->left);
if (tr->right) r = count(tr->right);
return l + r + 1;
}
void print_pre(const Node * tr, std::ofstream &file) const
{
try
{
if (!tr) throw 1;
}
catch (int)
{
return;
}
file << tr->value_ << " ";
if (tr->left)
print_pre(tr->left, file);
if (tr->right)
print_pre(tr->right, file);
}
void Delete(Node **Tree, T &value)
{
Node *q;
if (*Tree == nullptr) return;
else
if (value<(**Tree).value_) Delete(&((**Tree).left), value);
else
if (value>(**Tree).value_) Delete(&((**Tree).right), value);
else {
q = *Tree;
if ((*q).right ==nullptr) { *Tree = (*q).left; delete q; }
else
if ((*q).left == nullptr) { *Tree = (*q).right; delete q; }
else Delete_(&((*q).left), &q);
}
}
void Delete_(Node **r, Node **q)
{
Node *s;
if ((**r).right == nullptr)
{
(**q).value_ = (**r).value_; *q = *r;
s = *r; *r = (**r).left; delete s;
}
else Delete_(&((**r).right), q);
}
public:
Tree()
{
root = nullptr;
};
~Tree()
{
null_tree(root);
};
Node* tree_one()
{
return root;
};
void file_tree(char* name);
bool add(const T &value);
bool find(const T &value);
void print(ostream &out) const;
int count_() const;
bool del(T value)
{
try
{
if (find(value) == 0) throw 1;
}
catch (int)
{
return 0;
}
Delete(&root, value);
return !find(value);
}
void pr(char* name) const;
};
template <class T>
void Tree<T>::pr(char* name) const
{
ofstream file(name);
if (file.is_open())
{
file << count_() << " ";
print_pre(root, file);
file.close();
}
}
template <class T>
int Tree<T>::count_() const
{
return count(root);
}
template <class T>
void Tree<T>::print(ostream &out) const
{
root->show(out, 0);
}
template <class T>
void Tree<T>::Node::show(ostream &out, int level) const
{
const Node *tr = this;
if (tr) tr->right->show(out, level + 1);
for (int i = 0; i<level; i++)
out << " ";
if (tr) out << tr->value_ << endl;
else out << "End" << endl;
if (tr) tr->left->show(out, level + 1);
}
template <class T>
bool Tree<T>::add(const T &value)
{
Node *tr = add_(value);
if (tr) return true;
else return false;
}
template <class T>
void Tree<T>::file_tree(char* name)
{
ifstream file(name);
try
{
if (file.is_open()==0) throw 1;
}
catch (int)
{
return 0;
}
if (file.is_open())
{
int i_max;
file >> i_max;
for (int i = 0; i < i_max; ++i)
{
T node;
file >> node;
add(node);
}
file.close();
}
}
template <class T>
bool Tree<T>::find(const T &value)
{
Node *tr = find_(value);
if (tr) return true;
else return false;
}
<|endoftext|>
|
<commit_before>#include "Viewer.hpp"
#include "Physics/Env.hpp"
#include "Config.hpp"
#include <QApplication>
#include <NxPhysics.h>
#include <stdio.h>
using namespace std;
void usage(const char* prog)
{
fprintf(stderr, "usage: %s -c <config file> [--ui] [--sv]\n", prog);
fprintf(stderr, "\t--ui Show GUI\n");
fprintf(stderr, "\t--sv Use shared vision multicast port\n");
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Env* env = new Env();
char* configFile = 0;
bool useGUI = false;
bool sendShared = false;
//loop arguments and look for config file
for (int i=1 ; i<argc ; ++i)
{
if (strcmp(argv[i], "--ui") == 0)
{
useGUI = true;
} else if (strcmp(argv[i], "--sv") == 0)
{
sendShared = true;
} else if (strcmp(argv[i], "-c") == 0)
{
++i;
if (i < argc)
{
configFile = argv[i];
}
else
{
printf ("Expected config file after -c parameter\n");
return 0;
}
} else {
printf("%s is not recognized as a valid flag\n", argv[i]);
return 0;
}
}
env->sendShared = sendShared;
Config* config = 0;
if (configFile)
{
config = new Config(configFile, env);
}
else
{
usage(argv[0]);
exit(0);
}
Viewer *win = 0;
if (useGUI)
{
win = new Viewer(env);
win->setVisible(true);
}
int ret = app.exec();
//cleanup
delete win;
delete env;
delete config;
return ret;
}
<commit_msg>Simulator has default configuration file<commit_after>#include "Viewer.hpp"
#include "Physics/Env.hpp"
#include "Config.hpp"
#include <QApplication>
#include <QFile>
#include <stdio.h>
using namespace std;
void usage(const char* prog)
{
fprintf(stderr, "usage: %s [-c <config file>] [--ui] [--sv]\n", prog);
fprintf(stderr, "\t--ui Show GUI\n");
fprintf(stderr, "\t--sv Use shared vision multicast port\n");
}
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
Env* env = new Env();
QString configFile = "simulator.cfg";
bool useGUI = false;
bool sendShared = false;
//loop arguments and look for config file
for (int i=1 ; i<argc ; ++i)
{
if (strcmp(argv[i], "--ui") == 0)
{
useGUI = true;
} else if (strcmp(argv[i], "--sv") == 0)
{
sendShared = true;
} else if (strcmp(argv[i], "-c") == 0)
{
++i;
if (i < argc)
{
configFile = argv[i];
}
else
{
printf ("Expected config file after -c parameter\n");
return 0;
}
} else {
printf("%s is not recognized as a valid flag\n", argv[i]);
return 0;
}
}
env->sendShared = sendShared;
if (!QFile(configFile).exists())
{
fprintf(stderr, "Configuration file %s does not exist\n", (const char *)configFile.toAscii());
return 1;
}
Config* config = 0;
config = new Config(configFile, env);
Viewer *win = 0;
if (useGUI)
{
win = new Viewer(env);
win->setVisible(true);
}
int ret = app.exec();
//cleanup
delete win;
delete env;
delete config;
return ret;
}
<|endoftext|>
|
<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreMovableObject.h"
#include "OgreSceneNode.h"
#include "OgreTagPoint.h"
#include "OgreLight.h"
#include "OgreEntity.h"
#include "OgreRoot.h"
#include "OgreSceneManager.h"
#include "OgreCamera.h"
#include "OgreLodListener.h"
namespace Ogre {
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
uint32 MovableObject::msDefaultQueryFlags = 0xFFFFFFFF;
uint32 MovableObject::msDefaultVisibilityFlags = 0xFFFFFFFF;
//-----------------------------------------------------------------------
MovableObject::MovableObject()
: mCreator(0)
, mManager(0)
, mParentNode(0)
, mParentIsTagPoint(false)
, mVisible(true)
, mDebugDisplay(false)
, mUpperDistance(0)
, mSquaredUpperDistance(0)
, mBeyondFarDistance(false)
, mRenderQueueID(RENDER_QUEUE_MAIN)
, mRenderQueueIDSet(false)
, mQueryFlags(msDefaultQueryFlags)
, mVisibilityFlags(msDefaultVisibilityFlags)
, mCastShadows(true)
, mRenderingDisabled(false)
, mListener(0)
, mLightListUpdated(0)
, mLightMask(0xFFFFFFFF)
{
}
//-----------------------------------------------------------------------
MovableObject::MovableObject(const String& name)
: mName(name)
, mCreator(0)
, mManager(0)
, mParentNode(0)
, mParentIsTagPoint(false)
, mVisible(true)
, mDebugDisplay(false)
, mUpperDistance(0)
, mSquaredUpperDistance(0)
, mBeyondFarDistance(false)
, mRenderQueueID(RENDER_QUEUE_MAIN)
, mRenderQueueIDSet(false)
, mQueryFlags(msDefaultQueryFlags)
, mVisibilityFlags(msDefaultVisibilityFlags)
, mCastShadows(true)
, mRenderingDisabled(false)
, mListener(0)
, mLightListUpdated(0)
, mLightMask(0xFFFFFFFF)
{
}
//-----------------------------------------------------------------------
MovableObject::~MovableObject()
{
// Call listener (note, only called if there's something to do)
if (mListener)
{
mListener->objectDestroyed(this);
}
if (mParentNode)
{
// detach from parent
if (mParentIsTagPoint)
{
// May be we are a lod entity which not in the parent entity child object list,
// call this method could safely ignore this case.
static_cast<TagPoint*>(mParentNode)->getParentEntity()->detachObjectFromBone(this);
}
else
{
// May be we are a lod entity which not in the parent node child object list,
// call this method could safely ignore this case.
static_cast<SceneNode*>(mParentNode)->detachObject(this);
}
}
}
//-----------------------------------------------------------------------
void MovableObject::_notifyAttached(Node* parent, bool isTagPoint)
{
assert(!mParentNode || !parent);
bool different = (parent != mParentNode);
mParentNode = parent;
mParentIsTagPoint = isTagPoint;
// Mark light list being dirty, simply decrease
// counter by one for minimise overhead
--mLightListUpdated;
// Call listener (note, only called if there's something to do)
if (mListener && different)
{
if (mParentNode)
mListener->objectAttached(this);
else
mListener->objectDetached(this);
}
}
//-----------------------------------------------------------------------
Node* MovableObject::getParentNode(void) const
{
return mParentNode;
}
//-----------------------------------------------------------------------
SceneNode* MovableObject::getParentSceneNode(void) const
{
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
return tp->getParentEntity()->getParentSceneNode();
}
else
{
return static_cast<SceneNode*>(mParentNode);
}
}
//-----------------------------------------------------------------------
bool MovableObject::isAttached(void) const
{
return (mParentNode != 0);
}
//---------------------------------------------------------------------
void MovableObject::detachFromParent(void)
{
if (isAttached())
{
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
tp->getParentEntity()->detachObjectFromBone(this);
}
else
{
SceneNode* sn = static_cast<SceneNode*>(mParentNode);
sn->detachObject(this);
}
}
}
//-----------------------------------------------------------------------
bool MovableObject::isInScene(void) const
{
if (mParentNode != 0)
{
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
return tp->getParentEntity()->isInScene();
}
else
{
SceneNode* sn = static_cast<SceneNode*>(mParentNode);
return sn->isInSceneGraph();
}
}
else
{
return false;
}
}
//-----------------------------------------------------------------------
void MovableObject::_notifyMoved(void)
{
// Mark light list being dirty, simply decrease
// counter by one for minimise overhead
--mLightListUpdated;
// Notify listener if exists
if (mListener)
{
mListener->objectMoved(this);
}
}
//-----------------------------------------------------------------------
void MovableObject::setVisible(bool visible)
{
mVisible = visible;
}
//-----------------------------------------------------------------------
bool MovableObject::getVisible(void) const
{
return mVisible;
}
//-----------------------------------------------------------------------
bool MovableObject::isVisible(void) const
{
if (!mVisible || mBeyondFarDistance || mRenderingDisabled)
return false;
SceneManager* sm = Root::getSingleton()._getCurrentSceneManager();
if (sm && !(getVisibilityFlags() & sm->_getCombinedVisibilityMask()))
return false;
return true;
}
//-----------------------------------------------------------------------
void MovableObject::_notifyCurrentCamera(Camera* cam)
{
if (mParentNode)
{
if (cam->getUseRenderingDistance() && mUpperDistance > 0)
{
Real rad = getBoundingRadius();
Real squaredDepth = mParentNode->getSquaredViewDepth(cam->getLodCamera());
// Max distance to still render
Real maxDist = mUpperDistance + rad;
if (squaredDepth > Math::Sqr(maxDist))
{
mBeyondFarDistance = true;
}
else
{
mBeyondFarDistance = false;
}
}
else
{
mBeyondFarDistance = false;
}
// Construct event object
MovableObjectLodChangedEvent evt;
evt.movableObject = this;
evt.camera = cam;
// Notify lod event listeners
cam->getSceneManager()->_notifyMovableObjectLodChanged(evt);
}
mRenderingDisabled = mListener && !mListener->objectRendering(this, cam);
}
//-----------------------------------------------------------------------
void MovableObject::setRenderQueueGroup(uint8 queueID)
{
assert(queueID <= RENDER_QUEUE_MAX && "Render queue out of range!");
mRenderQueueID = queueID;
mRenderQueueIDSet = true;
}
//-----------------------------------------------------------------------
uint8 MovableObject::getRenderQueueGroup(void) const
{
return mRenderQueueID;
}
//-----------------------------------------------------------------------
const Matrix4& MovableObject::_getParentNodeFullTransform(void) const
{
if(mParentNode)
{
// object attached to a sceneNode
return mParentNode->_getFullTransform();
}
// fallback
return Matrix4::IDENTITY;
}
//-----------------------------------------------------------------------
const AxisAlignedBox& MovableObject::getWorldBoundingBox(bool derive) const
{
if (derive)
{
mWorldAABB = this->getBoundingBox();
mWorldAABB.transformAffine(_getParentNodeFullTransform());
}
return mWorldAABB;
}
//-----------------------------------------------------------------------
const Sphere& MovableObject::getWorldBoundingSphere(bool derive) const
{
if (derive)
{
mWorldBoundingSphere.setRadius(getBoundingRadius());
mWorldBoundingSphere.setCenter(mParentNode->_getDerivedPosition());
}
return mWorldBoundingSphere;
}
//-----------------------------------------------------------------------
const LightList& MovableObject::queryLights(void) const
{
// Try listener first
if (mListener)
{
const LightList* lightList =
mListener->objectQueryLights(this);
if (lightList)
{
return *lightList;
}
}
// Query from parent entity if exists
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
return tp->getParentEntity()->queryLights();
}
if (mParentNode)
{
SceneNode* sn = static_cast<SceneNode*>(mParentNode);
// Make sure we only update this only if need.
ulong frame = sn->getCreator()->_getLightsDirtyCounter();
if (mLightListUpdated != frame)
{
mLightListUpdated = frame;
sn->findLights(mLightList, this->getBoundingRadius(), this->getLightMask());
}
}
else
{
mLightList.clear();
}
return mLightList;
}
//-----------------------------------------------------------------------
ShadowCaster::ShadowRenderableListIterator MovableObject::getShadowVolumeRenderableIterator(
ShadowTechnique shadowTechnique, const Light* light,
HardwareIndexBufferSharedPtr* indexBuffer,
bool extrudeVertices, Real extrusionDist, unsigned long flags )
{
static ShadowRenderableList dummyList;
return ShadowRenderableListIterator(dummyList.begin(), dummyList.end());
}
//-----------------------------------------------------------------------
const AxisAlignedBox& MovableObject::getLightCapBounds(void) const
{
// Same as original bounds
return getWorldBoundingBox();
}
//-----------------------------------------------------------------------
const AxisAlignedBox& MovableObject::getDarkCapBounds(const Light& light, Real extrusionDist) const
{
// Extrude own light cap bounds
mWorldDarkCapBounds = getLightCapBounds();
this->extrudeBounds(mWorldDarkCapBounds, light.getAs4DVector(),
extrusionDist);
return mWorldDarkCapBounds;
}
//-----------------------------------------------------------------------
Real MovableObject::getPointExtrusionDistance(const Light* l) const
{
if (mParentNode)
{
return getExtrusionDistance(mParentNode->_getDerivedPosition(), l);
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------
uint32 MovableObject::getTypeFlags(void) const
{
if (mCreator)
{
return mCreator->getTypeFlags();
}
else
{
return 0xFFFFFFFF;
}
}
//---------------------------------------------------------------------
void MovableObject::setLightMask(uint32 lightMask)
{
this->mLightMask = lightMask;
//make sure to request a new light list from the scene manager if mask changed
mLightListUpdated = 0;
}
//---------------------------------------------------------------------
class MORecvShadVisitor : public Renderable::Visitor
{
public:
bool anyReceiveShadows;
MORecvShadVisitor() : anyReceiveShadows(false)
{
}
void visit(Renderable* rend, ushort lodIndex, bool isDebug,
Any* pAny = 0)
{
Technique* tech = rend->getTechnique();
bool techReceivesShadows = tech && tech->getParent()->getReceiveShadows();
anyReceiveShadows = anyReceiveShadows ||
techReceivesShadows || !tech;
}
};
//---------------------------------------------------------------------
bool MovableObject::getReceivesShadows()
{
MORecvShadVisitor visitor;
visitRenderables(&visitor);
return visitor.anyReceiveShadows;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
MovableObject* MovableObjectFactory::createInstance(
const String& name, SceneManager* manager,
const NameValuePairList* params)
{
MovableObject* m = createInstanceImpl(name, params);
m->_notifyCreator(this);
m->_notifyManager(manager);
return m;
}
}
<commit_msg>Patch 2901062: If you use 2 or more scenemanager and call isVisible() outside of _findVisibleObjects(), current scene manager might be dangling pointer. This change is ok in the current context because a MovableObject is always permanently linked to its parent SceneManager. This may change in future.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreMovableObject.h"
#include "OgreSceneNode.h"
#include "OgreTagPoint.h"
#include "OgreLight.h"
#include "OgreEntity.h"
#include "OgreRoot.h"
#include "OgreSceneManager.h"
#include "OgreCamera.h"
#include "OgreLodListener.h"
namespace Ogre {
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
uint32 MovableObject::msDefaultQueryFlags = 0xFFFFFFFF;
uint32 MovableObject::msDefaultVisibilityFlags = 0xFFFFFFFF;
//-----------------------------------------------------------------------
MovableObject::MovableObject()
: mCreator(0)
, mManager(0)
, mParentNode(0)
, mParentIsTagPoint(false)
, mVisible(true)
, mDebugDisplay(false)
, mUpperDistance(0)
, mSquaredUpperDistance(0)
, mBeyondFarDistance(false)
, mRenderQueueID(RENDER_QUEUE_MAIN)
, mRenderQueueIDSet(false)
, mQueryFlags(msDefaultQueryFlags)
, mVisibilityFlags(msDefaultVisibilityFlags)
, mCastShadows(true)
, mRenderingDisabled(false)
, mListener(0)
, mLightListUpdated(0)
, mLightMask(0xFFFFFFFF)
{
}
//-----------------------------------------------------------------------
MovableObject::MovableObject(const String& name)
: mName(name)
, mCreator(0)
, mManager(0)
, mParentNode(0)
, mParentIsTagPoint(false)
, mVisible(true)
, mDebugDisplay(false)
, mUpperDistance(0)
, mSquaredUpperDistance(0)
, mBeyondFarDistance(false)
, mRenderQueueID(RENDER_QUEUE_MAIN)
, mRenderQueueIDSet(false)
, mQueryFlags(msDefaultQueryFlags)
, mVisibilityFlags(msDefaultVisibilityFlags)
, mCastShadows(true)
, mRenderingDisabled(false)
, mListener(0)
, mLightListUpdated(0)
, mLightMask(0xFFFFFFFF)
{
}
//-----------------------------------------------------------------------
MovableObject::~MovableObject()
{
// Call listener (note, only called if there's something to do)
if (mListener)
{
mListener->objectDestroyed(this);
}
if (mParentNode)
{
// detach from parent
if (mParentIsTagPoint)
{
// May be we are a lod entity which not in the parent entity child object list,
// call this method could safely ignore this case.
static_cast<TagPoint*>(mParentNode)->getParentEntity()->detachObjectFromBone(this);
}
else
{
// May be we are a lod entity which not in the parent node child object list,
// call this method could safely ignore this case.
static_cast<SceneNode*>(mParentNode)->detachObject(this);
}
}
}
//-----------------------------------------------------------------------
void MovableObject::_notifyAttached(Node* parent, bool isTagPoint)
{
assert(!mParentNode || !parent);
bool different = (parent != mParentNode);
mParentNode = parent;
mParentIsTagPoint = isTagPoint;
// Mark light list being dirty, simply decrease
// counter by one for minimise overhead
--mLightListUpdated;
// Call listener (note, only called if there's something to do)
if (mListener && different)
{
if (mParentNode)
mListener->objectAttached(this);
else
mListener->objectDetached(this);
}
}
//-----------------------------------------------------------------------
Node* MovableObject::getParentNode(void) const
{
return mParentNode;
}
//-----------------------------------------------------------------------
SceneNode* MovableObject::getParentSceneNode(void) const
{
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
return tp->getParentEntity()->getParentSceneNode();
}
else
{
return static_cast<SceneNode*>(mParentNode);
}
}
//-----------------------------------------------------------------------
bool MovableObject::isAttached(void) const
{
return (mParentNode != 0);
}
//---------------------------------------------------------------------
void MovableObject::detachFromParent(void)
{
if (isAttached())
{
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
tp->getParentEntity()->detachObjectFromBone(this);
}
else
{
SceneNode* sn = static_cast<SceneNode*>(mParentNode);
sn->detachObject(this);
}
}
}
//-----------------------------------------------------------------------
bool MovableObject::isInScene(void) const
{
if (mParentNode != 0)
{
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
return tp->getParentEntity()->isInScene();
}
else
{
SceneNode* sn = static_cast<SceneNode*>(mParentNode);
return sn->isInSceneGraph();
}
}
else
{
return false;
}
}
//-----------------------------------------------------------------------
void MovableObject::_notifyMoved(void)
{
// Mark light list being dirty, simply decrease
// counter by one for minimise overhead
--mLightListUpdated;
// Notify listener if exists
if (mListener)
{
mListener->objectMoved(this);
}
}
//-----------------------------------------------------------------------
void MovableObject::setVisible(bool visible)
{
mVisible = visible;
}
//-----------------------------------------------------------------------
bool MovableObject::getVisible(void) const
{
return mVisible;
}
//-----------------------------------------------------------------------
bool MovableObject::isVisible(void) const
{
if (!mVisible || mBeyondFarDistance || mRenderingDisabled)
return false;
if (mManager && !(getVisibilityFlags() & mManager->_getCombinedVisibilityMask()))
return false;
return true;
}
//-----------------------------------------------------------------------
void MovableObject::_notifyCurrentCamera(Camera* cam)
{
if (mParentNode)
{
if (cam->getUseRenderingDistance() && mUpperDistance > 0)
{
Real rad = getBoundingRadius();
Real squaredDepth = mParentNode->getSquaredViewDepth(cam->getLodCamera());
// Max distance to still render
Real maxDist = mUpperDistance + rad;
if (squaredDepth > Math::Sqr(maxDist))
{
mBeyondFarDistance = true;
}
else
{
mBeyondFarDistance = false;
}
}
else
{
mBeyondFarDistance = false;
}
// Construct event object
MovableObjectLodChangedEvent evt;
evt.movableObject = this;
evt.camera = cam;
// Notify lod event listeners
cam->getSceneManager()->_notifyMovableObjectLodChanged(evt);
}
mRenderingDisabled = mListener && !mListener->objectRendering(this, cam);
}
//-----------------------------------------------------------------------
void MovableObject::setRenderQueueGroup(uint8 queueID)
{
assert(queueID <= RENDER_QUEUE_MAX && "Render queue out of range!");
mRenderQueueID = queueID;
mRenderQueueIDSet = true;
}
//-----------------------------------------------------------------------
uint8 MovableObject::getRenderQueueGroup(void) const
{
return mRenderQueueID;
}
//-----------------------------------------------------------------------
const Matrix4& MovableObject::_getParentNodeFullTransform(void) const
{
if(mParentNode)
{
// object attached to a sceneNode
return mParentNode->_getFullTransform();
}
// fallback
return Matrix4::IDENTITY;
}
//-----------------------------------------------------------------------
const AxisAlignedBox& MovableObject::getWorldBoundingBox(bool derive) const
{
if (derive)
{
mWorldAABB = this->getBoundingBox();
mWorldAABB.transformAffine(_getParentNodeFullTransform());
}
return mWorldAABB;
}
//-----------------------------------------------------------------------
const Sphere& MovableObject::getWorldBoundingSphere(bool derive) const
{
if (derive)
{
mWorldBoundingSphere.setRadius(getBoundingRadius());
mWorldBoundingSphere.setCenter(mParentNode->_getDerivedPosition());
}
return mWorldBoundingSphere;
}
//-----------------------------------------------------------------------
const LightList& MovableObject::queryLights(void) const
{
// Try listener first
if (mListener)
{
const LightList* lightList =
mListener->objectQueryLights(this);
if (lightList)
{
return *lightList;
}
}
// Query from parent entity if exists
if (mParentIsTagPoint)
{
TagPoint* tp = static_cast<TagPoint*>(mParentNode);
return tp->getParentEntity()->queryLights();
}
if (mParentNode)
{
SceneNode* sn = static_cast<SceneNode*>(mParentNode);
// Make sure we only update this only if need.
ulong frame = sn->getCreator()->_getLightsDirtyCounter();
if (mLightListUpdated != frame)
{
mLightListUpdated = frame;
sn->findLights(mLightList, this->getBoundingRadius(), this->getLightMask());
}
}
else
{
mLightList.clear();
}
return mLightList;
}
//-----------------------------------------------------------------------
ShadowCaster::ShadowRenderableListIterator MovableObject::getShadowVolumeRenderableIterator(
ShadowTechnique shadowTechnique, const Light* light,
HardwareIndexBufferSharedPtr* indexBuffer,
bool extrudeVertices, Real extrusionDist, unsigned long flags )
{
static ShadowRenderableList dummyList;
return ShadowRenderableListIterator(dummyList.begin(), dummyList.end());
}
//-----------------------------------------------------------------------
const AxisAlignedBox& MovableObject::getLightCapBounds(void) const
{
// Same as original bounds
return getWorldBoundingBox();
}
//-----------------------------------------------------------------------
const AxisAlignedBox& MovableObject::getDarkCapBounds(const Light& light, Real extrusionDist) const
{
// Extrude own light cap bounds
mWorldDarkCapBounds = getLightCapBounds();
this->extrudeBounds(mWorldDarkCapBounds, light.getAs4DVector(),
extrusionDist);
return mWorldDarkCapBounds;
}
//-----------------------------------------------------------------------
Real MovableObject::getPointExtrusionDistance(const Light* l) const
{
if (mParentNode)
{
return getExtrusionDistance(mParentNode->_getDerivedPosition(), l);
}
else
{
return 0;
}
}
//-----------------------------------------------------------------------
uint32 MovableObject::getTypeFlags(void) const
{
if (mCreator)
{
return mCreator->getTypeFlags();
}
else
{
return 0xFFFFFFFF;
}
}
//---------------------------------------------------------------------
void MovableObject::setLightMask(uint32 lightMask)
{
this->mLightMask = lightMask;
//make sure to request a new light list from the scene manager if mask changed
mLightListUpdated = 0;
}
//---------------------------------------------------------------------
class MORecvShadVisitor : public Renderable::Visitor
{
public:
bool anyReceiveShadows;
MORecvShadVisitor() : anyReceiveShadows(false)
{
}
void visit(Renderable* rend, ushort lodIndex, bool isDebug,
Any* pAny = 0)
{
Technique* tech = rend->getTechnique();
bool techReceivesShadows = tech && tech->getParent()->getReceiveShadows();
anyReceiveShadows = anyReceiveShadows ||
techReceivesShadows || !tech;
}
};
//---------------------------------------------------------------------
bool MovableObject::getReceivesShadows()
{
MORecvShadVisitor visitor;
visitRenderables(&visitor);
return visitor.anyReceiveShadows;
}
//-----------------------------------------------------------------------
//-----------------------------------------------------------------------
MovableObject* MovableObjectFactory::createInstance(
const String& name, SceneManager* manager,
const NameValuePairList* params)
{
MovableObject* m = createInstanceImpl(name, params);
m->_notifyCreator(this);
m->_notifyManager(manager);
return m;
}
}
<|endoftext|>
|
<commit_before>#ifndef STACK_HPP
#define STACK_HPP
#include <iostream>
template <class T>
class Stack {
public:
Stack ( ) : capacity (13), size (0), stack ( stack = new T*[capacity]) { }
Stack (int c) : capacity (c), size (0), stack (nullptr) {
if (c < 0) { capacity = 0; }
stack = new T*[capacity];
}
Stack (const Stack& rhs) : capacity (rhs.capacity), stack (nullptr) {
stack = new T*[capacity];
for (size = 0; size < rhs.size; ++size) {
stack[size] = new T (*rhs.stack[size]);
}
}
~Stack ( ) {
for (int i = 0; i < size; ++i) {
delete stack[i];
}
delete[] stack;
}
int getSize ( ) const {
return size;
}
int getTotalCapacity ( ) const {
return capacity;
}
bool isEmpty ( ) const {
return size == 0;
}
bool isFull ( ) const {
return size == capacity;
}
T* peek ( ) const {
return stack[size - 1];
}
T* pop ( ) {
if (! isEmpty ( )) {
return stack[--size];
}
return nullptr;
}
void push (T* c) {
if(!isFull()) {
stack[size++] = c;
}
}
Stack& operator=(const Stack& rhs) {
if (this != &rhs) {
for (int i = 0; i < size; ++i) {
delete stack[i];
}
delete[] stack;
capacity = rhs.capacity;
stack = new T*[capacity];
for (size = 0; size < rhs.size; ++size) {
stack[size] = new T (*rhs.stack[size]);
}
}
return *this;
}
friend std::ostream& operator<<(std::ostream& output, const Stack& currentStack) {
for (int i = currentStack.size - 1; i >= 0; --i) {
output << *currentStack.stack[i] << "\n";
}
return output;
}
private:
int capacity;
int size;
T** stack;
};
#endif
<commit_msg>Moves Stack implementation to outside of the class<commit_after>#ifndef STACK_HPP
#define STACK_HPP
#include <iostream>
template <class T>
class Stack {
public:
Stack ( );
Stack(int c);
Stack(const Stack& rhs);
Stack& operator=(const Stack& rhs);
~Stack( );
int getSize( ) const;
int getTotalCapacity( ) const;
bool isEmpty( ) const;
bool isFull( ) const;
T* peek( ) const;
T* pop( );
void push(T* c);
friend std::ostream& operator<<(std::ostream& output, const Stack& currentStack) {
for (int i = currentStack.size - 1; i >= 0; --i) {
output << *currentStack.stack[i] << "\n";
}
return output;
}
private:
int capacity;
int size;
T** stack;
};
template <class T>
Stack<T>::Stack ( ) : capacity (13), size (0), stack (stack = new T*[capacity]) { }
template <class T>
Stack<T>::Stack(int c): capacity (c), size (0), stack (nullptr) {
if (c < 0) { capacity = 0; }
stack = new T*[capacity];
}
template <class T>
Stack<T>::Stack(const Stack& rhs): capacity (rhs.capacity), stack (nullptr) {
stack = new T*[capacity];
for (size = 0; size < rhs.size; ++size) {
stack[size] = new T (*rhs.stack[size]);
}
}
template <class T>
Stack<T>::~Stack( ) {
for (int i = 0; i < size; ++i) {
delete stack[i];
}
delete[] stack;
}
template <class T>
int Stack<T>::getSize( ) const {
return size;
}
template <class T>
int Stack<T>::getTotalCapacity( ) const {
return capacity;
}
template <class T>
bool Stack<T>::isEmpty( ) const {
return size == 0;
}
template <class T>
bool Stack<T>::isFull( ) const {
return size == capacity;
}
template <class T>
T* Stack<T>::peek( ) const {
return stack[size - 1];
}
template <class T>
T* Stack<T>::pop( ) {
if (! isEmpty ( )) {
return stack[--size];
}
return nullptr;
}
template <class T>
void Stack<T>::push(T* c) {
if(!isFull()) {
stack[size++] = c;
}
}
template <class T>
Stack<T>& Stack<T>::operator=(const Stack& rhs) {
if (this != &rhs) {
for (int i = 0; i < size; ++i) {
delete stack[i];
}
delete[] stack;
capacity = rhs.capacity;
stack = new T*[capacity];
for (size = 0; size < rhs.size; ++size) {
stack[size] = new T (*rhs.stack[size]);
}
}
return *this;
}
#endif
<|endoftext|>
|
<commit_before>#ifndef AUTOCHECK_GENERATOR_HPP
#define AUTOCHECK_GENERATOR_HPP
#include <random>
#include <vector>
#include <iterator>
#include <limits>
#include <algorithm>
#include "is_one_of.hpp"
#include "function.hpp"
#include "generator_combinators.hpp"
#include "apply.hpp"
namespace autocheck {
/* Reusable static standard random number generator. */
inline std::mt19937& rng() {
static std::random_device rd;
static std::mt19937 rng(rd());
return rng;
}
template <typename T, typename... Gens, int... Is>
T generate(std::tuple<Gens...>& gens, size_t size,
const range<0, Is...>&)
{
return T(std::get<Is>(gens)(size)...);
}
template <typename T, typename... Gens>
T generate(std::tuple<Gens...>& gens, size_t size) {
return generate<T>(gens, size, range<sizeof...(Gens)>());
}
/* Generators produce an infinite sequence. */
template <typename T, typename Enable = void>
class generator;
template <>
class generator<bool> {
public:
typedef bool result_type;
result_type operator() (size_t = 0) {
static std::bernoulli_distribution dist(0.5);
return dist(rng());
}
};
namespace detail {
static const char alnums[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789";
/* Subtract 1 for NUL terminator. */
static const size_t nalnums = sizeof(alnums) - 1;
static const size_t nprint = '~' - ' ' + 1;
}
enum CharCategory {
ccAlphaNumeric,
ccPrintable,
ccAny
};
template <typename CharType, CharCategory Category = ccPrintable>
class char_generator {
public:
typedef CharType result_type;
result_type operator() (size_t size = 0) {
if (Category == ccAlphaNumeric || size < detail::nalnums) {
size = detail::nalnums - 1;
} else if (Category == ccPrintable || size < detail::nprint) {
size = detail::nprint - 1;
} else {
size = std::numeric_limits<CharType>::max();
}
/* Distribution is non-static. */
std::uniform_int_distribution<int> dist(0, size);
auto i = dist(rng());
auto rv =
(size < detail::nalnums) ? detail::alnums[i] :
((size < detail::nprint) ? ' ' + i :
i);
return rv;
}
};
/* WARNING: wchar_t, char16_t, char32_t, and family are typedefs. They
* cannot be distinguished from regular (un)signed integrals, meaning we
* cannot provide a general `generator` for them with the special char
* consideration of size. If you want that consideration, use
* char_generator specifically. */
template <typename CharType>
class generator<
CharType,
typename std::enable_if<
is_one_of<CharType, unsigned char, char, signed char>::value
>::type
> : public char_generator<CharType> {};
template <typename UnsignedIntegral>
class generator<
UnsignedIntegral,
typename std::enable_if<
is_one_of<UnsignedIntegral, unsigned short, unsigned int,
unsigned long, unsigned long long>::value
>::type
>
{
public:
typedef UnsignedIntegral result_type;
result_type operator() (size_t size = 0) {
/* Distribution is non-static. */
std::uniform_int_distribution<UnsignedIntegral> dist(0, size);
auto rv = dist(rng());
return rv;
}
};
template <typename SignedIntegral>
class generator<
SignedIntegral,
typename std::enable_if<
is_one_of<SignedIntegral, short, int, long, long long>::value
>::type
>
{
public:
typedef SignedIntegral result_type;
result_type operator() (size_t size = 0) {
/* Distribution is non-static. */
std::uniform_int_distribution<SignedIntegral> dist(-size, size);
auto rv = dist(rng());
return rv;
}
};
template <typename Floating>
class generator<
Floating,
typename std::enable_if<
is_one_of<Floating, float, double>::value
>::type
>
{
public:
typedef Floating result_type;
result_type operator() (size_t size = 0) {
/* Distribution is non-static. */
std::uniform_real_distribution<Floating> dist(-size, size);
auto rv = dist(rng());
return rv;
}
};
template <typename CharGen = generator<char>>
class string_generator {
private:
CharGen chargen;
public:
string_generator(const CharGen& chargen = CharGen()) :
chargen(chargen) {}
typedef std::basic_string<typename CharGen::result_type> result_type;
result_type operator() (size_t size = 0) {
result_type rv;
rv.reserve(size);
std::generate_n(std::back_insert_iterator<result_type>(rv), size,
/* Scale characters faster than string size. */
fix(size << 2, chargen));
return rv;
}
};
template <
CharCategory Category = ccPrintable,
typename CharType = char
>
string_generator<char_generator<CharType, Category>> string() {
return string_generator<char_generator<CharType, Category>>();
}
template <typename CharGen>
string_generator<CharGen> string(const CharGen& chargen) {
return string_generator<CharGen>();
}
template <typename CharType>
class generator<std::basic_string<CharType>> :
public string_generator<generator<CharType>> {};
/* TODO: Generic sequence generator. */
template <typename Gen>
class list_generator {
private:
Gen eltgen;
public:
list_generator(const Gen& eltgen = Gen()) :
eltgen(eltgen) {}
typedef std::vector<typename Gen::result_type> result_type;
result_type operator() (size_t size = 0) {
result_type rv;
rv.reserve(size);
std::generate_n(std::back_insert_iterator<result_type>(rv), size,
fix(size, eltgen));
return rv;
}
};
template <typename Gen>
list_generator<Gen> list_of(const Gen& gen) {
return list_generator<Gen>(gen);
}
template <typename T, typename Gen = generator<T>>
list_generator<Gen> list_of() {
return list_of(Gen());
}
template <typename T>
class generator<std::vector<T>> : public list_generator<generator<T>> {};
/* Ordered list combinator. */
namespace detail {
struct sorter {
template <typename T>
std::vector<T> operator() (std::vector<T>&& a, size_t) {
std::sort(a.begin(), a.end());
return a;
}
};
}
template <typename Gen>
detail::mapped_generator<detail::sorter, list_generator<Gen>>
ordered_list(const Gen& gen) {
return map(detail::sorter(), list_of(gen));
}
template <typename T, typename Gen = generator<T>>
detail::mapped_generator<detail::sorter, list_generator<Gen>>
ordered_list() {
return ordered_list(Gen());
}
/* Generic type generator (by construction). */
template <typename T, typename... Gens>
class cons_generator {
private:
std::tuple<Gens...> gens;
public:
cons_generator() :
gens(Gens()...) {}
cons_generator(const Gens&... gens) :
gens(gens...) {}
typedef T result_type;
result_type operator() (size_t size = 0) {
return generate<result_type>(gens, (size > 0) ? (size - 1) : size);
}
};
template <typename T, typename... Gens>
cons_generator<T, Gens...> cons(const Gens&... gens) {
return cons_generator<T, Gens...>(gens...);
}
template <typename T, typename... Args>
cons_generator<T, generator<Args>...> cons() {
return cons_generator<T, generator<Args>...>();
}
}
#endif
<commit_msg>fix ambiguity warnings for autocheck::generate<commit_after>#ifndef AUTOCHECK_GENERATOR_HPP
#define AUTOCHECK_GENERATOR_HPP
#include <random>
#include <vector>
#include <iterator>
#include <limits>
#include <algorithm>
#include "is_one_of.hpp"
#include "function.hpp"
#include "generator_combinators.hpp"
#include "apply.hpp"
namespace autocheck {
/* Reusable static standard random number generator. */
inline std::mt19937& rng() {
static std::random_device rd;
static std::mt19937 rng(rd());
return rng;
}
template <typename T, typename... Gens, int... Is>
T generate(std::tuple<Gens...>& gens, size_t size,
const range<0, Is...>&)
{
return T(std::get<Is>(gens)(size)...);
}
template <typename T, typename... Gens>
T generate(std::tuple<Gens...>& gens, size_t size) {
return autocheck::generate<T>(gens, size, range<sizeof...(Gens)>());
}
/* Generators produce an infinite sequence. */
template <typename T, typename Enable = void>
class generator;
template <>
class generator<bool> {
public:
typedef bool result_type;
result_type operator() (size_t = 0) {
static std::bernoulli_distribution dist(0.5);
return dist(rng());
}
};
namespace detail {
static const char alnums[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789";
/* Subtract 1 for NUL terminator. */
static const size_t nalnums = sizeof(alnums) - 1;
static const size_t nprint = '~' - ' ' + 1;
}
enum CharCategory {
ccAlphaNumeric,
ccPrintable,
ccAny
};
template <typename CharType, CharCategory Category = ccPrintable>
class char_generator {
public:
typedef CharType result_type;
result_type operator() (size_t size = 0) {
if (Category == ccAlphaNumeric || size < detail::nalnums) {
size = detail::nalnums - 1;
} else if (Category == ccPrintable || size < detail::nprint) {
size = detail::nprint - 1;
} else {
size = std::numeric_limits<CharType>::max();
}
/* Distribution is non-static. */
std::uniform_int_distribution<int> dist(0, size);
auto i = dist(rng());
auto rv =
(size < detail::nalnums) ? detail::alnums[i] :
((size < detail::nprint) ? ' ' + i :
i);
return rv;
}
};
/* WARNING: wchar_t, char16_t, char32_t, and family are typedefs. They
* cannot be distinguished from regular (un)signed integrals, meaning we
* cannot provide a general `generator` for them with the special char
* consideration of size. If you want that consideration, use
* char_generator specifically. */
template <typename CharType>
class generator<
CharType,
typename std::enable_if<
is_one_of<CharType, unsigned char, char, signed char>::value
>::type
> : public char_generator<CharType> {};
template <typename UnsignedIntegral>
class generator<
UnsignedIntegral,
typename std::enable_if<
is_one_of<UnsignedIntegral, unsigned short, unsigned int,
unsigned long, unsigned long long>::value
>::type
>
{
public:
typedef UnsignedIntegral result_type;
result_type operator() (size_t size = 0) {
/* Distribution is non-static. */
std::uniform_int_distribution<UnsignedIntegral> dist(0, size);
auto rv = dist(rng());
return rv;
}
};
template <typename SignedIntegral>
class generator<
SignedIntegral,
typename std::enable_if<
is_one_of<SignedIntegral, short, int, long, long long>::value
>::type
>
{
public:
typedef SignedIntegral result_type;
result_type operator() (size_t size = 0) {
/* Distribution is non-static. */
std::uniform_int_distribution<SignedIntegral> dist(-size, size);
auto rv = dist(rng());
return rv;
}
};
template <typename Floating>
class generator<
Floating,
typename std::enable_if<
is_one_of<Floating, float, double>::value
>::type
>
{
public:
typedef Floating result_type;
result_type operator() (size_t size = 0) {
/* Distribution is non-static. */
std::uniform_real_distribution<Floating> dist(-size, size);
auto rv = dist(rng());
return rv;
}
};
template <typename CharGen = generator<char>>
class string_generator {
private:
CharGen chargen;
public:
string_generator(const CharGen& chargen = CharGen()) :
chargen(chargen) {}
typedef std::basic_string<typename CharGen::result_type> result_type;
result_type operator() (size_t size = 0) {
result_type rv;
rv.reserve(size);
std::generate_n(std::back_insert_iterator<result_type>(rv), size,
/* Scale characters faster than string size. */
fix(size << 2, chargen));
return rv;
}
};
template <
CharCategory Category = ccPrintable,
typename CharType = char
>
string_generator<char_generator<CharType, Category>> string() {
return string_generator<char_generator<CharType, Category>>();
}
template <typename CharGen>
string_generator<CharGen> string(const CharGen& chargen) {
return string_generator<CharGen>();
}
template <typename CharType>
class generator<std::basic_string<CharType>> :
public string_generator<generator<CharType>> {};
/* TODO: Generic sequence generator. */
template <typename Gen>
class list_generator {
private:
Gen eltgen;
public:
list_generator(const Gen& eltgen = Gen()) :
eltgen(eltgen) {}
typedef std::vector<typename Gen::result_type> result_type;
result_type operator() (size_t size = 0) {
result_type rv;
rv.reserve(size);
std::generate_n(std::back_insert_iterator<result_type>(rv), size,
fix(size, eltgen));
return rv;
}
};
template <typename Gen>
list_generator<Gen> list_of(const Gen& gen) {
return list_generator<Gen>(gen);
}
template <typename T, typename Gen = generator<T>>
list_generator<Gen> list_of() {
return list_of(Gen());
}
template <typename T>
class generator<std::vector<T>> : public list_generator<generator<T>> {};
/* Ordered list combinator. */
namespace detail {
struct sorter {
template <typename T>
std::vector<T> operator() (std::vector<T>&& a, size_t) {
std::sort(a.begin(), a.end());
return a;
}
};
}
template <typename Gen>
detail::mapped_generator<detail::sorter, list_generator<Gen>>
ordered_list(const Gen& gen) {
return map(detail::sorter(), list_of(gen));
}
template <typename T, typename Gen = generator<T>>
detail::mapped_generator<detail::sorter, list_generator<Gen>>
ordered_list() {
return ordered_list(Gen());
}
/* Generic type generator (by construction). */
template <typename T, typename... Gens>
class cons_generator {
private:
std::tuple<Gens...> gens;
public:
cons_generator() :
gens(Gens()...) {}
cons_generator(const Gens&... gens) :
gens(gens...) {}
typedef T result_type;
result_type operator() (size_t size = 0) {
return autocheck::generate<result_type>(gens, (size > 0) ? (size - 1) : size);
}
};
template <typename T, typename... Gens>
cons_generator<T, Gens...> cons(const Gens&... gens) {
return cons_generator<T, Gens...>(gens...);
}
template <typename T, typename... Args>
cons_generator<T, generator<Args>...> cons() {
return cons_generator<T, generator<Args>...>();
}
}
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include "blackhole/sink.hpp"
namespace blackhole {
class config_t;
template<typename>
struct factory;
} // namespace blackhole
namespace blackhole {
namespace sink {
/// Null sink implementation that drops all incoming events.
class null_t : public sink_t {
public:
auto filter(const record_t& record) -> bool;
auto execute(const record_t& record, const string_view& formatted) -> void;
};
} // namespace sink
template<>
struct factory<sink::null_t> {
static auto from(const config_t& config) -> sink::null_t;
};
} // namespace blackhole
<commit_msg>docs(sink/null): add docs<commit_after>#pragma once
#include "blackhole/sink.hpp"
namespace blackhole {
class config_t;
template<typename>
struct factory;
} // namespace blackhole
namespace blackhole {
namespace sink {
/// A null sink merely exists, it never outputs a message to any device.
///
/// This class exists primarily for benchmarking reasons to measure the entire logging processing
/// pipeline. It never fails and never throws, because it does nothing.
///
/// All methods of this class are thread safe.
class null_t : public sink_t {
public:
/// Returns `false` regardless of a log record value, causing any log event to be dropped.
auto filter(const record_t& record) -> bool;
/// Drops any incoming log event.
auto execute(const record_t& record, const string_view& formatted) -> void;
};
} // namespace sink
template<>
struct factory<sink::null_t> {
static auto from(const config_t& config) -> sink::null_t;
};
} // namespace blackhole
<|endoftext|>
|
<commit_before>#ifndef CAFFE_VISION_LAYERS_HPP_
#define CAFFE_VISION_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/common_layers.hpp"
#include "caffe/data_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/loss_layers.hpp"
#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Convolves the input image with a bank of learned filters,
* and (optionally) adds biases.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class ConvolutionLayer : public Layer<Dtype> {
public:
explicit ConvolutionLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_CONVOLUTION;
}
virtual inline int MinBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline bool EqualNumBottomTopBlobs() const { return true; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int num_;
int channels_;
int pad_h_, pad_w_;
int height_, width_;
int group_;
int num_output_;
int height_out_, width_out_;
bool bias_term_;
// For the Caffe matrix multiplication convolution.
int M_, K_, N_;
Blob<Dtype> col_buffer_;
Blob<Dtype> bias_multiplier_;
};
#ifdef USE_CUDNN
/*
* @brief cuDNN implementation of ConvolutionLayer.
* Fallback to ConvolutionLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNConvolutionLayer : public ConvolutionLayer<Dtype>
{
public:
explicit CuDNNConvolutionLayer(const LayerParameter& param)
: ConvolutionLayer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual ~CuDNNConvolutionLayer();
protected:
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
cudnnHandle_t* handle_;
cudaStream_t* stream_;
vector<cudnnTensor4dDescriptor_t> bottom_descs_, top_descs_;
cudnnTensor4dDescriptor_t bias_desc_;
cudnnFilterDescriptor_t filter_desc_;
vector<cudnnConvolutionDescriptor_t> conv_descs_;
int bottom_offset_, top_offset_, weight_offset_, bias_offset_;
};
#endif
/**
* @brief A helper for image operations that rearranges image regions into
* column vectors. Used by ConvolutionLayer to perform convolution
* by matrix multiplication.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class Im2colLayer : public Layer<Dtype> {
public:
explicit Im2colLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_IM2COL;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int channels_;
int height_, width_;
int pad_h_, pad_w_;
};
// Forward declare PoolingLayer and SplitLayer for use in LRNLayer.
template <typename Dtype> class PoolingLayer;
template <typename Dtype> class SplitLayer;
/**
* @brief Normalize the input in a local region across or within feature maps.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class LRNLayer : public Layer<Dtype> {
public:
explicit LRNLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_LRN;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void CrossChannelForward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void CrossChannelForward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void WithinChannelForward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void CrossChannelBackward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void CrossChannelBackward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void WithinChannelBackward(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int size_;
int pre_pad_;
Dtype alpha_;
Dtype beta_;
int num_;
int channels_;
int height_;
int width_;
// Fields used for normalization ACROSS_CHANNELS
// scale_ stores the intermediate summing results
Blob<Dtype> scale_;
// Fields used for normalization WITHIN_CHANNEL
shared_ptr<SplitLayer<Dtype> > split_layer_;
vector<Blob<Dtype>*> split_top_vec_;
shared_ptr<PowerLayer<Dtype> > square_layer_;
Blob<Dtype> square_input_;
Blob<Dtype> square_output_;
vector<Blob<Dtype>*> square_bottom_vec_;
vector<Blob<Dtype>*> square_top_vec_;
shared_ptr<PoolingLayer<Dtype> > pool_layer_;
Blob<Dtype> pool_output_;
vector<Blob<Dtype>*> pool_top_vec_;
shared_ptr<PowerLayer<Dtype> > power_layer_;
Blob<Dtype> power_output_;
vector<Blob<Dtype>*> power_top_vec_;
shared_ptr<EltwiseLayer<Dtype> > product_layer_;
Blob<Dtype> product_input_;
vector<Blob<Dtype>*> product_bottom_vec_;
};
/**
* @brief Pools the input image by taking the max, average, etc. within regions.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class PoolingLayer : public Layer<Dtype> {
public:
explicit PoolingLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_POOLING;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
// MAX POOL layers can output an extra top blob for the mask;
// others can only output the pooled inputs.
virtual inline int MaxTopBlobs() const {
return (this->layer_param_.pooling_param().pool() ==
PoolingParameter_PoolMethod_MAX) ? 2 : 1;
}
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int pad_h_, pad_w_;
int channels_;
int height_, width_;
int pooled_height_, pooled_width_;
Blob<Dtype> rand_idx_;
Blob<int> max_idx_;
};
#ifdef USE_CUDNN
/*
* @brief cuDNN implementation of PoolingLayer.
* Fallback to PoolingLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNPoolingLayer : public PoolingLayer<Dtype> {
public:
explicit CuDNNPoolingLayer(const LayerParameter& param)
: PoolingLayer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual ~CuDNNPoolingLayer();
protected:
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
cudnnHandle_t handle_;
cudnnTensor4dDescriptor_t bottom_desc_, top_desc_;
cudnnPoolingDescriptor_t pooling_desc_;
cudnnPoolingMode_t mode_;
};
#endif
} // namespace caffe
#endif // CAFFE_VISION_LAYERS_HPP_
<commit_msg>[lint] cuDNN conv declaration<commit_after>#ifndef CAFFE_VISION_LAYERS_HPP_
#define CAFFE_VISION_LAYERS_HPP_
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/common_layers.hpp"
#include "caffe/data_layers.hpp"
#include "caffe/layer.hpp"
#include "caffe/loss_layers.hpp"
#include "caffe/neuron_layers.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Convolves the input image with a bank of learned filters,
* and (optionally) adds biases.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class ConvolutionLayer : public Layer<Dtype> {
public:
explicit ConvolutionLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_CONVOLUTION;
}
virtual inline int MinBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline bool EqualNumBottomTopBlobs() const { return true; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int num_;
int channels_;
int pad_h_, pad_w_;
int height_, width_;
int group_;
int num_output_;
int height_out_, width_out_;
bool bias_term_;
// For the Caffe matrix multiplication convolution.
int M_, K_, N_;
Blob<Dtype> col_buffer_;
Blob<Dtype> bias_multiplier_;
};
#ifdef USE_CUDNN
/*
* @brief cuDNN implementation of ConvolutionLayer.
* Fallback to ConvolutionLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNConvolutionLayer : public ConvolutionLayer<Dtype> {
public:
explicit CuDNNConvolutionLayer(const LayerParameter& param)
: ConvolutionLayer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual ~CuDNNConvolutionLayer();
protected:
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
cudnnHandle_t* handle_;
cudaStream_t* stream_;
vector<cudnnTensor4dDescriptor_t> bottom_descs_, top_descs_;
cudnnTensor4dDescriptor_t bias_desc_;
cudnnFilterDescriptor_t filter_desc_;
vector<cudnnConvolutionDescriptor_t> conv_descs_;
int bottom_offset_, top_offset_, weight_offset_, bias_offset_;
};
#endif
/**
* @brief A helper for image operations that rearranges image regions into
* column vectors. Used by ConvolutionLayer to perform convolution
* by matrix multiplication.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class Im2colLayer : public Layer<Dtype> {
public:
explicit Im2colLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_IM2COL;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int channels_;
int height_, width_;
int pad_h_, pad_w_;
};
// Forward declare PoolingLayer and SplitLayer for use in LRNLayer.
template <typename Dtype> class PoolingLayer;
template <typename Dtype> class SplitLayer;
/**
* @brief Normalize the input in a local region across or within feature maps.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class LRNLayer : public Layer<Dtype> {
public:
explicit LRNLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_LRN;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int ExactNumTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void CrossChannelForward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void CrossChannelForward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void WithinChannelForward(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void CrossChannelBackward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void CrossChannelBackward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void WithinChannelBackward(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int size_;
int pre_pad_;
Dtype alpha_;
Dtype beta_;
int num_;
int channels_;
int height_;
int width_;
// Fields used for normalization ACROSS_CHANNELS
// scale_ stores the intermediate summing results
Blob<Dtype> scale_;
// Fields used for normalization WITHIN_CHANNEL
shared_ptr<SplitLayer<Dtype> > split_layer_;
vector<Blob<Dtype>*> split_top_vec_;
shared_ptr<PowerLayer<Dtype> > square_layer_;
Blob<Dtype> square_input_;
Blob<Dtype> square_output_;
vector<Blob<Dtype>*> square_bottom_vec_;
vector<Blob<Dtype>*> square_top_vec_;
shared_ptr<PoolingLayer<Dtype> > pool_layer_;
Blob<Dtype> pool_output_;
vector<Blob<Dtype>*> pool_top_vec_;
shared_ptr<PowerLayer<Dtype> > power_layer_;
Blob<Dtype> power_output_;
vector<Blob<Dtype>*> power_top_vec_;
shared_ptr<EltwiseLayer<Dtype> > product_layer_;
Blob<Dtype> product_input_;
vector<Blob<Dtype>*> product_bottom_vec_;
};
/**
* @brief Pools the input image by taking the max, average, etc. within regions.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class PoolingLayer : public Layer<Dtype> {
public:
explicit PoolingLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual inline LayerParameter_LayerType type() const {
return LayerParameter_LayerType_POOLING;
}
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
// MAX POOL layers can output an extra top blob for the mask;
// others can only output the pooled inputs.
virtual inline int MaxTopBlobs() const {
return (this->layer_param_.pooling_param().pool() ==
PoolingParameter_PoolMethod_MAX) ? 2 : 1;
}
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
int kernel_h_, kernel_w_;
int stride_h_, stride_w_;
int pad_h_, pad_w_;
int channels_;
int height_, width_;
int pooled_height_, pooled_width_;
Blob<Dtype> rand_idx_;
Blob<int> max_idx_;
};
#ifdef USE_CUDNN
/*
* @brief cuDNN implementation of PoolingLayer.
* Fallback to PoolingLayer for CPU mode.
*/
template <typename Dtype>
class CuDNNPoolingLayer : public PoolingLayer<Dtype> {
public:
explicit CuDNNPoolingLayer(const LayerParameter& param)
: PoolingLayer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual ~CuDNNPoolingLayer();
protected:
virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom);
cudnnHandle_t handle_;
cudnnTensor4dDescriptor_t bottom_desc_, top_desc_;
cudnnPoolingDescriptor_t pooling_desc_;
cudnnPoolingMode_t mode_;
};
#endif
} // namespace caffe
#endif // CAFFE_VISION_LAYERS_HPP_
<|endoftext|>
|
<commit_before>/* DLL export definitions for LASzip */
#ifndef LASZIPEXPORT_H
#define LASZIPEXPORT_H
#ifndef LASZIP_DLL
#if (defined(_MSC_VER) || defined __CYGWIN__) && !defined(LAS_DISABLE_DLL)
#if defined(LASZIP_DLL_EXPORT)
# define LASZIP_DLL __declspec(dllexport)
#elif defined(LASZIP_DLL_IMPORT)
# define LASZIP_DLL __declspec(dllimport)
#else
# define LASZIP_DLL
#endif
#else
# if defined(USE_GCC_VISIBILITY_FLAG)
# define LASZIP_DLL __attribute__ ((visibility("default")))
# else
# define LASZIP_DLL
# endif
#endif
#endif
#endif
<commit_msg>rename copied symbol from liblas<commit_after>/* DLL export definitions for LASzip */
#ifndef LASZIPEXPORT_H
#define LASZIPEXPORT_H
#ifndef LASZIP_DLL
#if (defined(_MSC_VER) || defined __CYGWIN__) && !defined(LASZIP_DISABLE_DLL)
#if defined(LASZIP_DLL_EXPORT)
# define LASZIP_DLL __declspec(dllexport)
#elif defined(LASZIP_DLL_IMPORT)
# define LASZIP_DLL __declspec(dllimport)
#else
# define LASZIP_DLL
#endif
#else
# if defined(USE_GCC_VISIBILITY_FLAG)
# define LASZIP_DLL __attribute__ ((visibility("default")))
# else
# define LASZIP_DLL
# endif
#endif
#endif
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED
#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
#include <boost/cstdint.hpp> // uint32_t
namespace libtorrent
{
// The bitfiled type stores any number of bits as a bitfield
// in a heap allocated or borrowed array.
struct TORRENT_EXPORT bitfield
{
// constructs a new bitfield. The default constructor creates an empty
// bitfield. ``bits`` is the size of the bitfield (specified in bits).
// `` val`` is the value to initialize the bits to. If not specified
// all bits are initialized to 0.
//
// The constructor taking a pointer ``b`` and ``bits`` copies a bitfield
// from the specified buffer, and ``bits`` number of bits (rounded up to
// the nearest byte boundry).
bitfield(): m_bytes(0), m_size(0), m_own(false) {}
bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
{ resize(bits); }
bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
{ resize(bits, val); }
bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
{ assign(b, bits); }
bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
{ assign(rhs.bytes(), rhs.size()); }
#if __cplusplus > 199711L
bitfield(bitfield&& rhs): m_bytes(rhs.m_bytes), m_size(rhs.m_size), m_own(rhs.m_own)
{ rhs.m_bytes = NULL; }
#endif
// assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without
// taking ownership of the buffer. This is a way to avoid copying data and
// yet provide a raw buffer to functions that may operate on the bitfield
// type. It is the user's responsibility to make sure the passed-in buffer's
// life time exceeds all uses of the bitfield.
void borrow_bytes(char* b, int bits)
{
dealloc();
m_bytes = (unsigned char*)b;
m_size = bits;
m_own = false;
}
// hidden
~bitfield() { dealloc(); }
// copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to
// the nearest byte boundary.
void assign(char const* b, int bits)
{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }
// query bit at ``index``. Returns true if bit is 1, otherwise false.
bool operator[](int index) const
{ return get_bit(index); }
bool get_bit(int index) const
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
}
// set bit at ``index`` to 0 (clear_bit) or 1 (set_bit).
void clear_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] &= ~(0x80 >> (index & 7));
}
void set_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] |= (0x80 >> (index & 7));
}
// returns true if all bits in the bitfield are set
bool all_set() const
{
const int num_words = m_size / 32;
const int num_bytes = m_size / 8;
boost::uint32_t* bits = (boost::uint32_t*)m_bytes;
for (int i = 0; i < num_words; ++i)
{
if (bits[i] != 0xffffffff) return false;
}
for (int i = num_words * 4; i < num_bytes; ++i)
{
if (m_bytes[i] != 0xff) return false;
}
int rest = m_size - num_bytes * 8;
boost::uint8_t mask = (0xff << (8-rest)) & 0xff;
if (rest > 0 && (m_bytes[num_bytes] & mask) != mask)
return false;
return true;
}
// returns the size of the bitfield in bits.
std::size_t size() const { return m_size; }
// returns true if the bitfield has zero size.
bool empty() const { return m_size == 0; }
// returns a pointer to the internal buffer of the bitfield.
char const* bytes() const { return (char*)m_bytes; }
// copy operator
bitfield& operator=(bitfield const& rhs)
{
assign(rhs.bytes(), rhs.size());
return *this;
}
// count the number of bits in the bitfield that are set to 1.
int count() const
{
// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
const static char num_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
int ret = 0;
const int num_bytes = m_size / 8;
for (int i = 0; i < num_bytes; ++i)
{
ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
}
int rest = m_size - num_bytes * 8;
for (int i = 0; i < rest; ++i)
{
ret += (m_bytes[num_bytes] >> (7-i)) & 1;
}
TORRENT_ASSERT(ret <= m_size);
TORRENT_ASSERT(ret >= 0);
return ret;
}
struct const_iterator
{
friend struct bitfield;
typedef bool value_type;
typedef ptrdiff_t difference_type;
typedef bool const* pointer;
typedef bool& reference;
typedef std::forward_iterator_tag iterator_category;
bool operator*() { return (*byte & bit) != 0; }
const_iterator& operator++() { inc(); return *this; }
const_iterator operator++(int)
{ const_iterator ret(*this); inc(); return ret; }
const_iterator& operator--() { dec(); return *this; }
const_iterator operator--(int)
{ const_iterator ret(*this); dec(); return ret; }
const_iterator(): byte(0), bit(0x80) {}
bool operator==(const_iterator const& rhs) const
{ return byte == rhs.byte && bit == rhs.bit; }
bool operator!=(const_iterator const& rhs) const
{ return byte != rhs.byte || bit != rhs.bit; }
private:
void inc()
{
TORRENT_ASSERT(byte);
if (bit == 0x01)
{
bit = 0x80;
++byte;
}
else
{
bit >>= 1;
}
}
void dec()
{
TORRENT_ASSERT(byte);
if (bit == 0x80)
{
bit = 0x01;
--byte;
}
else
{
bit <<= 1;
}
}
const_iterator(unsigned char const* ptr, int offset)
: byte(ptr), bit(0x80 >> offset) {}
unsigned char const* byte;
int bit;
};
const_iterator begin() const { return const_iterator(m_bytes, 0); }
const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }
// set the size of the bitfield to ``bits`` length. If the bitfield is extended,
// the new bits are initialized to ``val``.
void resize(int bits, bool val)
{
int s = m_size;
int b = m_size & 7;
resize(bits);
if (s >= m_size) return;
int old_size_bytes = (s + 7) / 8;
int new_size_bytes = (m_size + 7) / 8;
if (val)
{
if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
clear_trailing_bits();
}
else
{
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
}
}
void resize(int bits)
{
TORRENT_ASSERT(bits >= 0);
const int b = (bits + 7) / 8;
if (m_bytes)
{
if (m_own)
{
m_bytes = (unsigned char*)std::realloc(m_bytes, b);
m_own = true;
}
else if (bits > m_size)
{
unsigned char* tmp = (unsigned char*)std::malloc(b);
std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
m_bytes = tmp;
m_own = true;
}
}
else if (bits > 0)
{
m_bytes = (unsigned char*)std::malloc(b);
m_own = true;
}
m_size = bits;
clear_trailing_bits();
}
// set all bits in the bitfield to 1 (set_all) or 0 (clear_all).
void set_all()
{
std::memset(m_bytes, 0xff, (m_size + 7) / 8);
clear_trailing_bits();
}
void clear_all()
{
std::memset(m_bytes, 0x00, (m_size + 7) / 8);
}
// make the bitfield empty, of zero size.
void clear() { dealloc(); m_size = 0; }
private:
void clear_trailing_bits()
{
// clear the tail bits in the last byte
if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
}
void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
unsigned char* m_bytes;
int m_size:31; // in bits
bool m_own:1;
};
}
#endif // TORRENT_BITFIELD_HPP_INCLUDED
<commit_msg>add missing include<commit_after>/*
Copyright (c) 2008-2014, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_BITFIELD_HPP_INCLUDED
#define TORRENT_BITFIELD_HPP_INCLUDED
#include "libtorrent/assert.hpp"
#include "libtorrent/config.hpp"
#include <cstring> // for memset and memcpy
#include <cstdlib> // for malloc, free and realloc
#include <boost/cstdint.hpp> // uint32_t
#include <algorithm> // for min()
namespace libtorrent
{
// The bitfiled type stores any number of bits as a bitfield
// in a heap allocated or borrowed array.
struct TORRENT_EXPORT bitfield
{
// constructs a new bitfield. The default constructor creates an empty
// bitfield. ``bits`` is the size of the bitfield (specified in bits).
// `` val`` is the value to initialize the bits to. If not specified
// all bits are initialized to 0.
//
// The constructor taking a pointer ``b`` and ``bits`` copies a bitfield
// from the specified buffer, and ``bits`` number of bits (rounded up to
// the nearest byte boundry).
bitfield(): m_bytes(0), m_size(0), m_own(false) {}
bitfield(int bits): m_bytes(0), m_size(0), m_own(false)
{ resize(bits); }
bitfield(int bits, bool val): m_bytes(0), m_size(0), m_own(false)
{ resize(bits, val); }
bitfield(char const* b, int bits): m_bytes(0), m_size(0), m_own(false)
{ assign(b, bits); }
bitfield(bitfield const& rhs): m_bytes(0), m_size(0), m_own(false)
{ assign(rhs.bytes(), rhs.size()); }
#if __cplusplus > 199711L
bitfield(bitfield&& rhs): m_bytes(rhs.m_bytes), m_size(rhs.m_size), m_own(rhs.m_own)
{ rhs.m_bytes = NULL; }
#endif
// assigns a bitfield pointed to ``b`` of ``bits`` number of bits, without
// taking ownership of the buffer. This is a way to avoid copying data and
// yet provide a raw buffer to functions that may operate on the bitfield
// type. It is the user's responsibility to make sure the passed-in buffer's
// life time exceeds all uses of the bitfield.
void borrow_bytes(char* b, int bits)
{
dealloc();
m_bytes = (unsigned char*)b;
m_size = bits;
m_own = false;
}
// hidden
~bitfield() { dealloc(); }
// copy bitfield from buffer ``b`` of ``bits`` number of bits, rounded up to
// the nearest byte boundary.
void assign(char const* b, int bits)
{ resize(bits); std::memcpy(m_bytes, b, (bits + 7) / 8); clear_trailing_bits(); }
// query bit at ``index``. Returns true if bit is 1, otherwise false.
bool operator[](int index) const
{ return get_bit(index); }
bool get_bit(int index) const
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
return (m_bytes[index / 8] & (0x80 >> (index & 7))) != 0;
}
// set bit at ``index`` to 0 (clear_bit) or 1 (set_bit).
void clear_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] &= ~(0x80 >> (index & 7));
}
void set_bit(int index)
{
TORRENT_ASSERT(index >= 0);
TORRENT_ASSERT(index < m_size);
m_bytes[index / 8] |= (0x80 >> (index & 7));
}
// returns true if all bits in the bitfield are set
bool all_set() const
{
const int num_words = m_size / 32;
const int num_bytes = m_size / 8;
boost::uint32_t* bits = (boost::uint32_t*)m_bytes;
for (int i = 0; i < num_words; ++i)
{
if (bits[i] != 0xffffffff) return false;
}
for (int i = num_words * 4; i < num_bytes; ++i)
{
if (m_bytes[i] != 0xff) return false;
}
int rest = m_size - num_bytes * 8;
boost::uint8_t mask = (0xff << (8-rest)) & 0xff;
if (rest > 0 && (m_bytes[num_bytes] & mask) != mask)
return false;
return true;
}
// returns the size of the bitfield in bits.
std::size_t size() const { return m_size; }
// returns true if the bitfield has zero size.
bool empty() const { return m_size == 0; }
// returns a pointer to the internal buffer of the bitfield.
char const* bytes() const { return (char*)m_bytes; }
// copy operator
bitfield& operator=(bitfield const& rhs)
{
assign(rhs.bytes(), rhs.size());
return *this;
}
// count the number of bits in the bitfield that are set to 1.
int count() const
{
// 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111,
// 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111
const static char num_bits[] =
{
0, 1, 1, 2, 1, 2, 2, 3,
1, 2, 2, 3, 2, 3, 3, 4
};
int ret = 0;
const int num_bytes = m_size / 8;
for (int i = 0; i < num_bytes; ++i)
{
ret += num_bits[m_bytes[i] & 0xf] + num_bits[m_bytes[i] >> 4];
}
int rest = m_size - num_bytes * 8;
for (int i = 0; i < rest; ++i)
{
ret += (m_bytes[num_bytes] >> (7-i)) & 1;
}
TORRENT_ASSERT(ret <= m_size);
TORRENT_ASSERT(ret >= 0);
return ret;
}
struct const_iterator
{
friend struct bitfield;
typedef bool value_type;
typedef ptrdiff_t difference_type;
typedef bool const* pointer;
typedef bool& reference;
typedef std::forward_iterator_tag iterator_category;
bool operator*() { return (*byte & bit) != 0; }
const_iterator& operator++() { inc(); return *this; }
const_iterator operator++(int)
{ const_iterator ret(*this); inc(); return ret; }
const_iterator& operator--() { dec(); return *this; }
const_iterator operator--(int)
{ const_iterator ret(*this); dec(); return ret; }
const_iterator(): byte(0), bit(0x80) {}
bool operator==(const_iterator const& rhs) const
{ return byte == rhs.byte && bit == rhs.bit; }
bool operator!=(const_iterator const& rhs) const
{ return byte != rhs.byte || bit != rhs.bit; }
private:
void inc()
{
TORRENT_ASSERT(byte);
if (bit == 0x01)
{
bit = 0x80;
++byte;
}
else
{
bit >>= 1;
}
}
void dec()
{
TORRENT_ASSERT(byte);
if (bit == 0x80)
{
bit = 0x01;
--byte;
}
else
{
bit <<= 1;
}
}
const_iterator(unsigned char const* ptr, int offset)
: byte(ptr), bit(0x80 >> offset) {}
unsigned char const* byte;
int bit;
};
const_iterator begin() const { return const_iterator(m_bytes, 0); }
const_iterator end() const { return const_iterator(m_bytes + m_size / 8, m_size & 7); }
// set the size of the bitfield to ``bits`` length. If the bitfield is extended,
// the new bits are initialized to ``val``.
void resize(int bits, bool val)
{
int s = m_size;
int b = m_size & 7;
resize(bits);
if (s >= m_size) return;
int old_size_bytes = (s + 7) / 8;
int new_size_bytes = (m_size + 7) / 8;
if (val)
{
if (old_size_bytes && b) m_bytes[old_size_bytes - 1] |= (0xff >> b);
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0xff, new_size_bytes - old_size_bytes);
clear_trailing_bits();
}
else
{
if (old_size_bytes < new_size_bytes)
std::memset(m_bytes + old_size_bytes, 0x00, new_size_bytes - old_size_bytes);
}
}
void resize(int bits)
{
TORRENT_ASSERT(bits >= 0);
const int b = (bits + 7) / 8;
if (m_bytes)
{
if (m_own)
{
m_bytes = (unsigned char*)std::realloc(m_bytes, b);
m_own = true;
}
else if (bits > m_size)
{
unsigned char* tmp = (unsigned char*)std::malloc(b);
std::memcpy(tmp, m_bytes, (std::min)(int(m_size + 7)/ 8, b));
m_bytes = tmp;
m_own = true;
}
}
else if (bits > 0)
{
m_bytes = (unsigned char*)std::malloc(b);
m_own = true;
}
m_size = bits;
clear_trailing_bits();
}
// set all bits in the bitfield to 1 (set_all) or 0 (clear_all).
void set_all()
{
std::memset(m_bytes, 0xff, (m_size + 7) / 8);
clear_trailing_bits();
}
void clear_all()
{
std::memset(m_bytes, 0x00, (m_size + 7) / 8);
}
// make the bitfield empty, of zero size.
void clear() { dealloc(); m_size = 0; }
private:
void clear_trailing_bits()
{
// clear the tail bits in the last byte
if (m_size & 7) m_bytes[(m_size + 7) / 8 - 1] &= 0xff << (8 - (m_size & 7));
}
void dealloc() { if (m_own) std::free(m_bytes); m_bytes = 0; }
unsigned char* m_bytes;
int m_size:31; // in bits
bool m_own:1;
};
}
#endif // TORRENT_BITFIELD_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_MATH_HELPERS_HPP
#define NOMLIB_MATH_HELPERS_HPP
#include <chrono>
#include <random>
#include <cmath>
#include "nomlib/config.hpp"
#include "nomlib/math/Point2-inl.hpp"
namespace nom {
extern const double PI;
/// Returns a random number between the specified start and end numbers.
int32 rand ( int32 start, int32 end );
/// Rotates a given X & Y coordinate point along a given pivot axis
/// (rotation point) at the given angle (in degrees), clockwise.
const Point2f rotate_points ( float angle, float x, float y, float pivot_x, float pivot_y );
/// ...
double round ( double number );
int abs ( int value );
} // namespace nom
#endif // include guard defined
<commit_msg>Remove abs function (this should have been with previous git commit)<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_MATH_HELPERS_HPP
#define NOMLIB_MATH_HELPERS_HPP
#include <chrono>
#include <random>
#include <cmath>
#include "nomlib/config.hpp"
#include "nomlib/math/Point2-inl.hpp"
namespace nom {
extern const double PI;
/// Returns a random number between the specified start and end numbers.
int32 rand ( int32 start, int32 end );
/// Rotates a given X & Y coordinate point along a given pivot axis
/// (rotation point) at the given angle (in degrees), clockwise.
const Point2f rotate_points ( float angle, float x, float y, float pivot_x, float pivot_y );
/// ...
double round ( double number );
} // namespace nom
#endif // include guard defined
<|endoftext|>
|
<commit_before>#include "SpaceDefiner.h"
#include <cstdlib>
#include <ctime>
SpaceDefiner::SpaceDefiner()
{
//yes
}
SpaceDefiner::~SpaceDefiner()
{
}
//equation must be in terms of X
std::vector<vector3d*>* SpaceDefiner::SpaceDefine(std::string str, float start, float end, float num){
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
equation_factory eqrf;
equation* eqr = eqrf.vector_equation(str);
//void SpaceDefiner::Define(char input[50], struct node nodes[NODE_MAX][NODE_MAX][NODE_MAX])
//{
float* f = new float[3];
for(float k = start; k<end; k += (end-start)/num){
f = eqr->eval(k,0.0f,0.0f,f);
vector3d* v = new vector3d(f[0],f[1],f[2]);
vec->push_back(v);
}
delete f;
delete eqr;
return vec;
}
std::vector<vector3d*>* SpaceDefiner::uv_surface(std::string str, float u_start, float u_end, float v_start, float v_end, float u_num, float v_num){
//what we are returning
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
//make the equation dang namit
equation_factor eqrf;
equation* eqr = eqrf.vector_equation(str);
//needed when we are making vectors
float* f = new float[3];
//this will fill the space with a series of points which collectively will cover the surface.
for(float uk = u_start; uk<u_end; uk += (u_end-u_start)/u_num){
for(float vk = v_start; vk<v_end; vk += (v_end-v_start)/v_num){
f = eqr->eval(uk,uv,0.0f,f);
vector3d* surface_point = new vector3d(f[0], f[1], f[2]);
vec->push_back(surface_point); //add to the list
float mag = surface_point->magnitude();
//creating 5 points which are closer to the origin than this surface point
for(int i=1; i<6; i++){
float mod = (1.0f/6.0f * i) * mag; //(1/6) because then the 6 points in a line will be 0/6, 1/6, 2/6, 3/6, 4/6, 5/6, and line point
vector3d* interior = new vector3d(f[0] * mod, f[1] * mod, f[2] * mod);
vec->push_back(interior); //got dem sweet, sweet points
}
}
}
//cleanup
delete eqr;
delete f;
//return
return vec;
}
//makes a prism centered at (0,0,0) with the specified number of points.
std::vector<vector3d*>* SpaceDefiner::prism(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
//what we are returning
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
for(float x = (0 - x_length/2.0f); x <= (0 + x_length/2.0f); x += (x_length/x_num)){
for(float y = (0 - y_length/2.0f); y <= (0 + y_length/2.0f); y += (y_length/y_num)){
for(float z = (0 - z_length/2.0f); z <= (0 + z_length/2.0f); z += (z_length/z_num)){
vector3d* v = new vector3d(x,y,z);
vec->push_back(v);
}
}
}
//return
return vec;
}
std::vector<vector3d*>* SpaceDefiner::prism_rand(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
//what we are returning
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
srand(time(NULL));
float xleft = 0 - x_length/2.0f;
float yleft = 0 - y_length/2.0f;
float zleft = 0 - z_length/2.0f;
for(int x=0; x<x_num; ++x){
for(int y=0; y<y_num; ++y){
for(int z=0; z<z_num; ++z){
float rx = xleft + ((rand() % RAND_MAX)*x_length);
float ry = yleft + ((rand() % RAND_MAX)*y_length);
float rz = zleft + ((rand() % RAND_MAX)*z_length);
vector3d* v = new vector3d(rx,ry,rz);
vec->push_back(v);
}
}
}
//return
return vec;
}
<commit_msg>fixing space definer<commit_after>#include "SpaceDefiner.h"
#include <cstdlib>
#include <ctime>
SpaceDefiner::SpaceDefiner()
{
//yes
}
SpaceDefiner::~SpaceDefiner()
{
}
//equation must be in terms of X
std::vector<vector3d*>* SpaceDefiner::SpaceDefine(std::string str, float start, float end, float num){
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
equation_factory eqrf;
equation* eqr = eqrf.vector_equation(str);
//void SpaceDefiner::Define(char input[50], struct node nodes[NODE_MAX][NODE_MAX][NODE_MAX])
//{
float* f = new float[3];
for(float k = start; k<end; k += (end-start)/num){
f = eqr->eval(k,0.0f,0.0f,f);
vector3d* v = new vector3d(f[0],f[1],f[2]);
vec->push_back(v);
}
delete f;
delete eqr;
return vec;
}
std::vector<vector3d*>* SpaceDefiner::uv_surface(std::string str, float u_start, float u_end, float v_start, float v_end, float u_num, float v_num){
//what we are returning
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
//make the equation dang namit
equation_factory eqrf;
equation* eqr = eqrf.vector_equation(str);
//needed when we are making vectors
float* f = new float[3];
//this will fill the space with a series of points which collectively will cover the surface.
for(float uk = u_start; uk<u_end; uk += (u_end-u_start)/u_num){
for(float vk = v_start; vk<v_end; vk += (v_end-v_start)/v_num){
f = eqr->eval(uk,vk,0.0f,f);
vector3d* surface_point = new vector3d(f[0], f[1], f[2]);
vec->push_back(surface_point); //add to the list
float mag = surface_point->magnitude();
//creating 5 points which are closer to the origin than this surface point
for(int i=1; i<6; i++){
float mod = (1.0f/6.0f * i) * mag; //(1/6) because then the 6 points in a line will be 0/6, 1/6, 2/6, 3/6, 4/6, 5/6, and line point
vector3d* interior = new vector3d(f[0] * mod, f[1] * mod, f[2] * mod);
vec->push_back(interior); //got dem sweet, sweet points
}
}
}
//cleanup
delete eqr;
delete f;
//return
return vec;
}
//makes a prism centered at (0,0,0) with the specified number of points.
std::vector<vector3d*>* SpaceDefiner::prism(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
//what we are returning
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
for(float x = (0 - x_length/2.0f); x <= (0 + x_length/2.0f); x += (x_length/x_num)){
for(float y = (0 - y_length/2.0f); y <= (0 + y_length/2.0f); y += (y_length/y_num)){
for(float z = (0 - z_length/2.0f); z <= (0 + z_length/2.0f); z += (z_length/z_num)){
vector3d* v = new vector3d(x,y,z);
vec->push_back(v);
}
}
}
//return
return vec;
}
std::vector<vector3d*>* SpaceDefiner::prism_rand(float x_length, float x_num, float y_length, float y_num, float z_length, float z_num){
//what we are returning
std::vector<vector3d*>* vec = new std::vector<vector3d*>();
srand(time(NULL));
float xleft = 0 - x_length/2.0f;
float yleft = 0 - y_length/2.0f;
float zleft = 0 - z_length/2.0f;
for(int x=0; x<x_num; ++x){
for(int y=0; y<y_num; ++y){
for(int z=0; z<z_num; ++z){
float rx = xleft + ((rand() % RAND_MAX)*x_length);
float ry = yleft + ((rand() % RAND_MAX)*y_length);
float rz = zleft + ((rand() % RAND_MAX)*z_length);
vector3d* v = new vector3d(rx,ry,rz);
vec->push_back(v);
}
}
}
//return
return vec;
}
<|endoftext|>
|
<commit_before><commit_msg>Crash fix<commit_after><|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/adr32s_workarounds.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file workarounds/adr32s_workarounds.H
/// @brief Workarounds for the ADR32s logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#ifndef _MSS_WORKAROUNDS_ADR32S_H_
#define _MSS_WORKAROUNDS_ADR32S_H_
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors_manual.H>
namespace mss
{
namespace workarounds
{
namespace adr32s
{
///
/// @brief Clears the FIRs mistakenly set by the DCD calibration
/// @param[in] i_target MCBIST target on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note Always needs to be run for DD1.* parts. unsure for DD2
///
fapi2::ReturnCode clear_dcd_firs( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Perform ADR DCD calibration - Nimbus Only
/// @param[in] i_target the MCBIST (controler) to perform calibration on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Retries to clear the cal update bit, as it has been seen that the bit can be "sticky" in hardware
/// @param[in] i_target MCA target on which to operate
/// @param[in] i_reg the register on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode setup_dll_control_regs( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const uint64_t i_reg );
} // close namespace adr32s
} // close namespace workarounds
} // close namespace mss
#endif
<commit_msg>Update HPW Level for MSS API library<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/adr32s_workarounds.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file workarounds/adr32s_workarounds.H
/// @brief Workarounds for the ADR32s logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#ifndef _MSS_WORKAROUNDS_ADR32S_H_
#define _MSS_WORKAROUNDS_ADR32S_H_
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/mss_attribute_accessors_manual.H>
namespace mss
{
namespace workarounds
{
namespace adr32s
{
///
/// @brief Clears the FIRs mistakenly set by the DCD calibration
/// @param[in] i_target MCBIST target on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note Always needs to be run for DD1.* parts. unsure for DD2
///
fapi2::ReturnCode clear_dcd_firs( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Perform ADR DCD calibration - Nimbus Only
/// @param[in] i_target the MCBIST (controler) to perform calibration on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target );
///
/// @brief Retries to clear the cal update bit, as it has been seen that the bit can be "sticky" in hardware
/// @param[in] i_target MCA target on which to operate
/// @param[in] i_reg the register on which to operate
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode setup_dll_control_regs( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const uint64_t i_reg );
} // close namespace adr32s
} // close namespace workarounds
} // close namespace mss
#endif
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandglcontext.h"
#include "qwaylanddisplay.h"
#include "qwaylandwindow.h"
#include "../../../eglconvenience/qeglconvenience.h"
#include <QtGui/QPlatformGLContext>
#include <QtGui/QPlatformWindowFormat>
#include <QtCore/QMutex>
QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QPlatformWindowFormat &format)
: QPlatformGLContext()
, mEglDisplay(eglDisplay)
, mSurface(EGL_NO_SURFACE)
, mConfig(q_configFromQPlatformWindowFormat(mEglDisplay,format,true))
, mFormat(qt_qPlatformWindowFormatFromConfig(mEglDisplay,mConfig))
{
QPlatformGLContext *sharePlatformContext = 0;
sharePlatformContext = format.sharedGLContext();
mFormat.setSharedContext(sharePlatformContext);
EGLContext shareEGLContext = EGL_NO_CONTEXT;
if (sharePlatformContext)
shareEGLContext = static_cast<const QWaylandGLContext*>(sharePlatformContext)->mContext;
eglBindAPI(EGL_OPENGL_ES_API);
QVector<EGLint> eglContextAttrs;
eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION);
eglContextAttrs.append(2);
eglContextAttrs.append(EGL_NONE);
mContext = eglCreateContext(mEglDisplay, mConfig,
shareEGLContext, eglContextAttrs.constData());
}
QWaylandGLContext::QWaylandGLContext()
: QPlatformGLContext()
, mEglDisplay(0)
, mContext(EGL_NO_CONTEXT)
, mSurface(EGL_NO_SURFACE)
, mConfig(0)
{ }
QWaylandGLContext::~QWaylandGLContext()
{
eglDestroyContext(mEglDisplay,mContext);
}
void QWaylandGLContext::makeCurrent()
{
QPlatformGLContext::makeCurrent();
if (mSurface == EGL_NO_SURFACE) {
qWarning("makeCurrent with EGL_NO_SURFACE");
}
eglMakeCurrent(mEglDisplay, mSurface, mSurface, mContext);
}
void QWaylandGLContext::doneCurrent()
{
QPlatformGLContext::doneCurrent();
eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
void QWaylandGLContext::swapBuffers()
{
eglSwapBuffers(mEglDisplay,mSurface);
}
void *QWaylandGLContext::getProcAddress(const QString &string)
{
return (void *) eglGetProcAddress(string.toLatin1().data());
}
void QWaylandGLContext::setEglSurface(EGLSurface surface)
{
doneCurrent();
mSurface = surface;
}
EGLConfig QWaylandGLContext::eglConfig() const
{
return mConfig;
}
<commit_msg>We need to let the currentContext be in the same state after<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwaylandglcontext.h"
#include "qwaylanddisplay.h"
#include "qwaylandwindow.h"
#include "../../../eglconvenience/qeglconvenience.h"
#include <QtGui/QPlatformGLContext>
#include <QtGui/QPlatformWindowFormat>
#include <QtCore/QMutex>
QWaylandGLContext::QWaylandGLContext(EGLDisplay eglDisplay, const QPlatformWindowFormat &format)
: QPlatformGLContext()
, mEglDisplay(eglDisplay)
, mSurface(EGL_NO_SURFACE)
, mConfig(q_configFromQPlatformWindowFormat(mEglDisplay,format,true))
, mFormat(qt_qPlatformWindowFormatFromConfig(mEglDisplay,mConfig))
{
QPlatformGLContext *sharePlatformContext = 0;
sharePlatformContext = format.sharedGLContext();
mFormat.setSharedContext(sharePlatformContext);
EGLContext shareEGLContext = EGL_NO_CONTEXT;
if (sharePlatformContext)
shareEGLContext = static_cast<const QWaylandGLContext*>(sharePlatformContext)->mContext;
eglBindAPI(EGL_OPENGL_ES_API);
QVector<EGLint> eglContextAttrs;
eglContextAttrs.append(EGL_CONTEXT_CLIENT_VERSION);
eglContextAttrs.append(2);
eglContextAttrs.append(EGL_NONE);
mContext = eglCreateContext(mEglDisplay, mConfig,
shareEGLContext, eglContextAttrs.constData());
}
QWaylandGLContext::QWaylandGLContext()
: QPlatformGLContext()
, mEglDisplay(0)
, mContext(EGL_NO_CONTEXT)
, mSurface(EGL_NO_SURFACE)
, mConfig(0)
{ }
QWaylandGLContext::~QWaylandGLContext()
{
eglDestroyContext(mEglDisplay,mContext);
}
void QWaylandGLContext::makeCurrent()
{
QPlatformGLContext::makeCurrent();
if (mSurface == EGL_NO_SURFACE) {
qWarning("makeCurrent with EGL_NO_SURFACE");
}
eglMakeCurrent(mEglDisplay, mSurface, mSurface, mContext);
}
void QWaylandGLContext::doneCurrent()
{
QPlatformGLContext::doneCurrent();
eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
void QWaylandGLContext::swapBuffers()
{
eglSwapBuffers(mEglDisplay,mSurface);
}
void *QWaylandGLContext::getProcAddress(const QString &string)
{
return (void *) eglGetProcAddress(string.toLatin1().data());
}
void QWaylandGLContext::setEglSurface(EGLSurface surface)
{
bool wasCurrent = false;
if (QPlatformGLContext::currentContext() == this) {
wasCurrent = true;
doneCurrent();
}
mSurface = surface;
if (wasCurrent) {
makeCurrent();
}
}
EGLConfig QWaylandGLContext::eglConfig() const
{
return mConfig;
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <thread>
// class thread
// template <class F, class ...Args> thread(F&& f, Args&&... args);
#include <thread>
#include <new>
#include <cstdlib>
#include <cassert>
unsigned throw_one = 0xFFFF;
void* operator new(std::size_t s) throw(std::bad_alloc)
{
if (throw_one == 0)
throw std::bad_alloc();
--throw_one;
return std::malloc(s);
}
void operator delete(void* p) throw()
{
std::free(p);
}
bool f_run = false;
void f()
{
f_run = true;
}
class G
{
int alive_;
public:
static int n_alive;
static bool op_run;
G() : alive_(1) {++n_alive;}
G(const G& g) : alive_(g.alive_) {++n_alive;}
~G() {alive_ = 0; --n_alive;}
void operator()()
{
assert(alive_ == 1);
assert(n_alive >= 1);
op_run = true;
}
void operator()(int i, double j)
{
assert(alive_ == 1);
assert(n_alive >= 1);
assert(i == 5);
assert(j == 5.5);
op_run = true;
}
};
int G::n_alive = 0;
bool G::op_run = false;
#ifndef _LIBCPP_HAS_NO_VARIADICS
class MoveOnly
{
MoveOnly(const MoveOnly&);
public:
MoveOnly() {}
MoveOnly(MoveOnly&&) {}
void operator()(MoveOnly&&)
{
}
};
#endif
int main()
{
{
std::thread t(f);
t.join();
assert(f_run == true);
}
f_run = false;
{
try
{
throw_one = 0;
std::thread t(f);
assert(false);
}
catch (...)
{
throw_one = 0xFFFF;
assert(!f_run);
}
}
{
assert(G::n_alive == 0);
assert(!G::op_run);
std::thread t((G()));
t.join();
assert(G::n_alive == 0);
assert(G::op_run);
}
G::op_run = false;
{
try
{
throw_one = 0;
assert(G::n_alive == 0);
assert(!G::op_run);
std::thread t((G()));
assert(false);
}
catch (...)
{
throw_one = 0xFFFF;
assert(G::n_alive == 0);
assert(!G::op_run);
}
}
#ifndef _LIBCPP_HAS_NO_VARIADICS
{
assert(G::n_alive == 0);
assert(!G::op_run);
std::thread t(G(), 5, 5.5);
t.join();
assert(G::n_alive == 0);
assert(G::op_run);
}
{
std::thread t = std::thread(MoveOnly(), MoveOnly());
t.join();
}
#endif // _LIBCPP_HAS_NO_VARIADICS
}
<commit_msg>Mark another test as UNSUPPORTED with ASAN and MSAN<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads
// <thread>
// class thread
// template <class F, class ...Args> thread(F&& f, Args&&... args);
// UNSUPPORTED: asan, msan
#include <thread>
#include <new>
#include <cstdlib>
#include <cassert>
unsigned throw_one = 0xFFFF;
void* operator new(std::size_t s) throw(std::bad_alloc)
{
if (throw_one == 0)
throw std::bad_alloc();
--throw_one;
return std::malloc(s);
}
void operator delete(void* p) throw()
{
std::free(p);
}
bool f_run = false;
void f()
{
f_run = true;
}
class G
{
int alive_;
public:
static int n_alive;
static bool op_run;
G() : alive_(1) {++n_alive;}
G(const G& g) : alive_(g.alive_) {++n_alive;}
~G() {alive_ = 0; --n_alive;}
void operator()()
{
assert(alive_ == 1);
assert(n_alive >= 1);
op_run = true;
}
void operator()(int i, double j)
{
assert(alive_ == 1);
assert(n_alive >= 1);
assert(i == 5);
assert(j == 5.5);
op_run = true;
}
};
int G::n_alive = 0;
bool G::op_run = false;
#ifndef _LIBCPP_HAS_NO_VARIADICS
class MoveOnly
{
MoveOnly(const MoveOnly&);
public:
MoveOnly() {}
MoveOnly(MoveOnly&&) {}
void operator()(MoveOnly&&)
{
}
};
#endif
int main()
{
{
std::thread t(f);
t.join();
assert(f_run == true);
}
f_run = false;
{
try
{
throw_one = 0;
std::thread t(f);
assert(false);
}
catch (...)
{
throw_one = 0xFFFF;
assert(!f_run);
}
}
{
assert(G::n_alive == 0);
assert(!G::op_run);
std::thread t((G()));
t.join();
assert(G::n_alive == 0);
assert(G::op_run);
}
G::op_run = false;
{
try
{
throw_one = 0;
assert(G::n_alive == 0);
assert(!G::op_run);
std::thread t((G()));
assert(false);
}
catch (...)
{
throw_one = 0xFFFF;
assert(G::n_alive == 0);
assert(!G::op_run);
}
}
#ifndef _LIBCPP_HAS_NO_VARIADICS
{
assert(G::n_alive == 0);
assert(!G::op_run);
std::thread t(G(), 5, 5.5);
t.join();
assert(G::n_alive == 0);
assert(G::op_run);
}
{
std::thread t = std::thread(MoveOnly(), MoveOnly());
t.join();
}
#endif // _LIBCPP_HAS_NO_VARIADICS
}
<|endoftext|>
|
<commit_before>/*
T0 DA for online calibration
Contact: Alla.Maevskaya@cern.ch
Run Type: AMPLITUDE_CALIBRATION
DA Type: MON
Number of events needed: 5000
Input Files: inLaser.dat, external parameters
Output Files: daLaser.root, to be exported to the DAQ FXS
Trigger types used: CALIBRATION_EVENT
*/
#define FILE_OUT "daLaser.root"
#define FILE_IN "inLaser.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>
#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>
//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TRandom.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TString.h"
#include "TH1.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TVirtualFitter.h"
//AMORE
//
#ifdef ALI_AMORE
#include <AmoreDA.h>
#endif
float lcfd, hcfd;
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
int status;
/* magic line */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
Int_t nEntries = daqDA_ECS_getTotalIteration(); // usually = 11 = Nb of calibration runs
cout<<" nEntries "<<nEntries<<endl;
Int_t nInit=1; // = 0 all DAC values ; = 1 DAC=0 excluded (default=1)
// Reading current iteration
Int_t nIndex = daqDA_ECS_getCurrentIteration();
if(nIndex<0 || nIndex>nEntries) {printf("\n Failed: nIndex = %d\n",nIndex); return -1 ;}
// decode the input line
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
Float_t mipsin[20];
if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
printf("Couldn't get input file >>inLaser.dat<< from DAQ_DB !!!\n");
return -1;
}
ifstream filein(FILE_IN,ios::in);
Int_t k=0;
while (k<nEntries ) {
filein >>mipsin[k] ;
cout<<" "<<mipsin[k]<<endl;
k++; }
filein>>lcfd;
filein>>hcfd;
filein.close();
/*
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
*/
// Char_t inputFile[256]="";
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("T0 monitoring program started\n");
// Allocation of histograms - start
TH1F *hQTC[24]; TH1F *hLED[24]; TH1F *hCFD[24];
printf(" CFD low limit %f high %f",lcfd, hcfd);
for(Int_t ic=0; ic<24; ic++)
{
hQTC[ic] = new TH1F(Form("hQTC%d_%d",ic+1,nIndex),"QTC",1000, 500, 4500);
hLED[ic] = new TH1F(Form("hLED%d_%d",ic+1,nIndex),"LED",300,300,600);
hCFD[ic] = new TH1F(Form("hCFD%d_%d",ic+1,nIndex),"CFD", Int_t ((hcfd-lcfd)/2), lcfd, hcfd);
}
// Allocation of histograms - end
// Reading current iteration
Int_t iev=0;
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==(int)MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
break;
case CALIBRATION_EVENT:
// case PHYSICS_EVENT:
iev++;
if(iev==1) printf("First event %i\n",iev);
// Initalize raw-data reading and decoding
AliRawReader *reader = new AliRawReaderDate((void*)event);
// Enable the following two lines in case of real-data
reader->RequireHeader(kTRUE);
AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);
// Read raw data
Int_t allData[106][5];
for(Int_t i0=0;i0<106;i0++)
for(Int_t j0=0;j0<5;j0++)
allData[i0][j0] = 0;
if(start->Next()){
for (Int_t i=0; i<106; i++) {
for(Int_t iHit=0;iHit<5;iHit++){
allData[i][iHit]= start->GetData(i,iHit);
}
}
}
else
printf("No data for T0 found!!!\n");
// Fill the histograms
for (Int_t ik = 0; ik<24; ik+=2)
{
Int_t cc = ik/2;
if(allData[ik+25][0]>0 && allData[ik+26][0]>0)
hQTC[cc]->Fill((allData[ik+25][0]-allData[ik+26][0]));
if(allData[cc+13][0]>0 && allData[cc+1][0]>0)
hLED[cc]->Fill(allData[cc+13][0]-allData[cc+1][0]);
if(allData[cc+1][0] > 0) hCFD[cc]->Fill(allData[cc+1][0]);
// printf("%i %i CFD %i LED_CFD %i\n",
// ik,cc,allData[cc+1][0],allData[cc+1][0]);
}
for (Int_t ik = 24; ik<48; ik+=2)
{
Int_t cc = ik/2;
if(allData[ik+57][0]>0 && allData[ik+58][0]>0 && allData[cc+45][0]>0)
hQTC[cc]->Fill(allData[ik+57][0]-allData[ik+58][0]);
if(allData[cc+57][0]>0 && allData[cc+45][0]>0)
hLED[cc]->Fill(allData[cc+57][0]-allData[cc+45][0]);
if(allData[cc+45][0] > 0) hCFD[cc]->Fill(allData[cc+45][0]);
// printf("%i %i CFD %i LED_CFD %i\n",
// ik,cc,allData[cc+45][0],allData[cc+45][0]);
}
delete start;
start = 0x0;
delete reader;
reader= 0x0;
// End of fill histograms
}
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
printf("Number of events processed - %i\n ",iev);
break;
}
}
printf("After loop, before writing histos\n");
TH1F* hAmp = new TH1F("hAmpLaser"," Laser amplitude ", 1000, 0.5, 10.5);
for(Int_t k=0; k<nEntries; k++) hAmp->Fill(mipsin[k]);
// write a file with the histograms
TFile *hist=0;
if(nIndex == 1 )
hist = new TFile(FILE_OUT,"RECREATE");
else
hist = new TFile(FILE_OUT,"UPDATE");
hist->cd();
for(Int_t j=0;j<24;j++)
{
if(hQTC[j]->GetEntries()>0) hQTC[j]->Write();
if(hLED[j]->GetEntries()>0) hLED[j]->Write();
if(hCFD[j]->GetEntries()>0) hCFD[j]->Write();
}
hAmp->Write();
hist->Close();
delete hist;
status=0;
/* export file to FXS */
if (daqDA_FES_storeFile(FILE_OUT, "AMPLITUDE_CALIBRATION")) {
status=-2;
}
return status;
}
<commit_msg>amplitude calibration up to 20MIPs<commit_after>/*
T0 DA for online calibration
Contact: Alla.Maevskaya@cern.ch
Run Type: AMPLITUDE_CALIBRATION
DA Type: MON
Number of events needed: 5000
Input Files: inLaser.dat, external parameters
Output Files: daLaser.root, to be exported to the DAQ FXS
Trigger types used: CALIBRATION_EVENT
*/
#define FILE_OUT "daLaser.root"
#define FILE_IN "inLaser.dat"
#include <daqDA.h>
#include <event.h>
#include <monitor.h>
#include <Riostream.h>
#include <stdio.h>
#include <stdlib.h>
//AliRoot
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliT0RawReader.h>
//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include "TFile.h"
#include "TKey.h"
#include "TH2S.h"
#include "TObject.h"
#include "TBenchmark.h"
#include "TRandom.h"
#include "TMath.h"
#include "TCanvas.h"
#include "TString.h"
#include "TH1.h"
#include "TF1.h"
#include "TSpectrum.h"
#include "TVirtualFitter.h"
//AMORE
//
#ifdef ALI_AMORE
#include <AmoreDA.h>
#endif
float lcfd, hcfd;
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
int status;
/* magic line */
gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
"*",
"TStreamerInfo",
"RIO",
"TStreamerInfo()");
Int_t nEntries = daqDA_ECS_getTotalIteration(); // usually = 11 = Nb of calibration runs
cout<<" nEntries "<<nEntries<<endl;
Int_t nInit=1; // = 0 all DAC values ; = 1 DAC=0 excluded (default=1)
// Reading current iteration
Int_t nIndex = daqDA_ECS_getCurrentIteration();
if(nIndex<0 || nIndex>nEntries) {printf("\n Failed: nIndex = %d\n",nIndex); return -1 ;}
// decode the input line
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
Float_t mipsin[20];
if(daqDA_DB_getFile(FILE_IN, FILE_IN)){
printf("Couldn't get input file >>inLaser.dat<< from DAQ_DB !!!\n");
return -1;
}
ifstream filein(FILE_IN,ios::in);
Int_t k=0;
while (k<nEntries ) {
filein >>mipsin[k] ;
cout<<" "<<mipsin[k]<<endl;
k++; }
filein>>lcfd;
filein>>hcfd;
filein.close();
/*
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
*/
// Char_t inputFile[256]="";
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("T0 monitoring program started\n");
// Allocation of histograms - start
TH1F *hQTC[24]; TH1F *hLED[24]; TH1F *hCFD[24];
printf(" CFD low limit %f high %f",lcfd, hcfd);
for(Int_t ic=0; ic<24; ic++)
{
hQTC[ic] = new TH1F(Form("hQTC%d_%d",ic+1,nIndex),"QTC",1000, 500, 4500);
hLED[ic] = new TH1F(Form("hLED%d_%d",ic+1,nIndex),"LED",300,300,600);
hCFD[ic] = new TH1F(Form("hCFD%d_%d",ic+1,nIndex),"CFD", Int_t ((hcfd-lcfd)/2), lcfd, hcfd);
}
// Allocation of histograms - end
// Reading current iteration
Int_t iev=0;
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==(int)MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
switch (event->eventType){
case START_OF_RUN:
break;
case END_OF_RUN:
break;
case CALIBRATION_EVENT:
// case PHYSICS_EVENT:
iev++;
if(iev==1) printf("First event %i\n",iev);
// Initalize raw-data reading and decoding
AliRawReader *reader = new AliRawReaderDate((void*)event);
// Enable the following two lines in case of real-data
reader->RequireHeader(kTRUE);
AliT0RawReader *start = new AliT0RawReader(reader, kTRUE);
// Read raw data
Int_t allData[106][5];
for(Int_t i0=0;i0<106;i0++)
for(Int_t j0=0;j0<5;j0++)
allData[i0][j0] = 0;
if(start->Next()){
for (Int_t i=0; i<106; i++) {
for(Int_t iHit=0;iHit<5;iHit++){
allData[i][iHit]= start->GetData(i,iHit);
}
}
}
else
printf("No data for T0 found!!!\n");
// Fill the histograms
for (Int_t ik = 0; ik<24; ik+=2)
{
Int_t cc = ik/2;
if(allData[ik+25][0]>0 && allData[ik+26][0]>0)
hQTC[cc]->Fill((allData[ik+25][0]-allData[ik+26][0]));
if(allData[cc+13][0]>0 && allData[cc+1][0]>0)
hLED[cc]->Fill(allData[cc+13][0]-allData[cc+1][0]);
if(allData[cc+1][0] > 0) hCFD[cc]->Fill(allData[cc+1][0]);
// printf("%i %i CFD %i LED_CFD %i\n",
// ik,cc,allData[cc+1][0],allData[cc+1][0]);
}
for (Int_t ik = 24; ik<48; ik+=2)
{
Int_t cc = ik/2;
if(allData[ik+57][0]>0 && allData[ik+58][0]>0 && allData[cc+45][0]>0)
hQTC[cc]->Fill(allData[ik+57][0]-allData[ik+58][0]);
if(allData[cc+57][0]>0 && allData[cc+45][0]>0)
hLED[cc]->Fill(allData[cc+57][0]-allData[cc+45][0]);
if(allData[cc+45][0] > 0) hCFD[cc]->Fill(allData[cc+45][0]);
// printf("%i %i CFD %i LED_CFD %i\n",
// ik,cc,allData[cc+45][0],allData[cc+45][0]);
}
delete start;
start = 0x0;
delete reader;
reader= 0x0;
// End of fill histograms
}
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
printf("Number of events processed - %i\n ",iev);
break;
}
}
printf("After loop, before writing histos\n");
TH1F* hAmp = new TH1F("hAmpLaser"," Laser amplitude ", 1000, 0.5, 20.5);
for(Int_t k=0; k<nEntries; k++) hAmp->Fill(mipsin[k]);
// write a file with the histograms
TFile *hist=0;
if(nIndex == 1 )
hist = new TFile(FILE_OUT,"RECREATE");
else
hist = new TFile(FILE_OUT,"UPDATE");
hist->cd();
for(Int_t j=0;j<24;j++)
{
if(hQTC[j]->GetEntries()>0) hQTC[j]->Write();
if(hLED[j]->GetEntries()>0) hLED[j]->Write();
if(hCFD[j]->GetEntries()>0) hCFD[j]->Write();
}
hAmp->Write();
hist->Close();
delete hist;
status=0;
/* export file to FXS */
if (daqDA_FES_storeFile(FILE_OUT, "AMPLITUDE_CALIBRATION")) {
status=-2;
}
return status;
}
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file MechanicRotationalInterfaceQ.hpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2011-05-30
//!
//! @brief Contains a rotational mechanic interface component of Q-type
//!
//$Id$
#ifndef MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
#define MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup MechanicalComponents
//!
class MechanicRotationalInterfaceQ : public ComponentQ
{
private:
Port *mpP1;
public:
static Component *Creator()
{
return new MechanicRotationalInterfaceQ("RotationalInterfaceQ");
}
MechanicRotationalInterfaceQ(const std::string name) : ComponentQ(name)
{
mpP1 = addPowerPort("P1", "NodeMechanicRotational");
}
void initialize()
{
//Interfacing is handled through readnode/writenode from the RT wrapper file
}
void simulateOneTimestep()
{
//Interfacing is handled through readnode/writenode from the RT wrapper file
}
};
}
#endif // MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
<commit_msg>Added torque calculation in q-type rotational interface component<commit_after>/*-----------------------------------------------------------------------------
This source file is part of Hopsan NG
Copyright (c) 2011
Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,
Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack
This file is provided "as is", with no guarantee or warranty for the
functionality or reliability of the contents. All contents in this file is
the original work of the copyright holders at the Division of Fluid and
Mechatronic Systems (Flumes) at Linköping University. Modifying, using or
redistributing any part of this file is prohibited without explicit
permission from the copyright holders.
-----------------------------------------------------------------------------*/
//!
//! @file MechanicRotationalInterfaceQ.hpp
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2011-05-30
//!
//! @brief Contains a rotational mechanic interface component of Q-type
//!
//$Id$
#ifndef MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
#define MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
#include "../../ComponentEssentials.h"
#include "../../ComponentUtilities.h"
namespace hopsan {
//!
//! @brief
//! @ingroup MechanicalComponents
//!
class MechanicRotationalInterfaceQ : public ComponentQ
{
private:
Port *mpP1;
double *mpND_t, *mpND_w, *mpND_c, *mpND_Zx;
public:
static Component *Creator()
{
return new MechanicRotationalInterfaceQ("RotationalInterfaceQ");
}
MechanicRotationalInterfaceQ(const std::string name) : ComponentQ(name)
{
mpP1 = addPowerPort("P1", "NodeMechanicRotational");
}
void initialize()
{
mpND_t = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::TORQUE);
mpND_w = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::ANGULARVELOCITY);
mpND_c = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::WAVEVARIABLE);
mpND_Zx = getSafeNodeDataPtr(mpP1, NodeMechanicRotational::CHARIMP);
}
void simulateOneTimestep()
{
//! @todo If this works, do same in other Q-type interface components
//Calculate torque from c and Zx
double w = (*mpND_w);
double c = (*mpND_c);
double Zx = (*mpND_Zx);
(*mpND_t) = c + Zx*w;
}
};
}
#endif // MECHANICROTATIONALINTERFACEQ_HPP_INCLUDED
<|endoftext|>
|
<commit_before>/*
* VapourSynth D2V Plugin
*
* Copyright (c) 2012 Derek Buitenhuis
*
* This file is part of d2vsource.
*
* d2vsource 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.
*
* d2vsource 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 d2vsource; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
extern "C" {
#include <assert.h>
#include <stdlib.h>
#include <string.h>
}
#include "compat.hpp"
#include "d2v.hpp"
#include "gop.hpp"
#ifdef _WIN32
#include <windows.h>
#endif
using namespace std;
string d2vgetpath(const char *d2v_path, const string& file)
{
string path;
string d2v = d2v_path;
size_t delim_pos = d2v.rfind(PATH_DELIM) + 1;
if ((file.substr(0, 1) == "/" || file.substr(1, 1) == ":") || (d2v.substr(0, 1) != "/" && d2v.substr(1, 1) != ":")) {
path = file;
} else {
path = d2v.substr(0, delim_pos);
path += file;
}
return path;
}
/* Conditionally free all memebers of d2vcontext. */
void d2vfreep(d2vcontext **ctx)
{
d2vcontext *lctx = *ctx;
unsigned int i;
if (!lctx)
return;
lctx->frames.clear();
for(i = 0; i < lctx->gops.size(); i++) {
gop g = lctx->gops[i];
g.flags.clear();
}
lctx->gops.clear();
if (lctx->files)
delete [] lctx->files;
delete lctx;
*ctx = NULL;
}
/* Parse the entire D2V index and build the GOP and frame lists. */
d2vcontext *d2vparse(const char *filename, string& err)
{
string line;
ifstream input;
d2vcontext *ret;
int i;
ret = new d2vcontext;
/* Zero the context to aid in conditional freeing later. */
memset(ret, 0, sizeof(*ret));
ret->stream_type = UNSET;
ret->ts_pid = -1;
ret->loc.startfile = -1;
#ifdef _WIN32
wchar_t wide_filename[_MAX_PATH];
i = MultiByteToWideChar(CP_UTF8, 0, filename, -1, wide_filename, ARRAYSIZE(wide_filename));
if (!i) {
err = "D2V filename is invalid: ";
err += filename;
goto fail;
}
input.open(wide_filename);
#else
input.open(filename);
#endif
if (input.fail()) {
err = "D2V cannot be opened.";
goto fail;
}
/* Check the DGIndexProjectFile version. */
d2vgetline(input, line);
if (line.substr(18, 2) != D2V_VERSION) {
err = "D2V Version is unsupported!";
goto fail;
}
/* Get the number of files. */
d2vgetline(input, line);
ret->num_files = atoi(line.c_str());
if (!ret->num_files) {
err = "Invalid D2V File.";
goto fail;
}
/* Allocate files array. */
ret->files = new string[ret->num_files];
/* Read them all in. */
for(i = 0; i < ret->num_files; i++) {
d2vgetline(input, line);
if (line.length()) {
ret->files[i] = d2vgetpath(filename, line);
} else {
err = "Invalid file set in D2V.";
goto fail;
}
}
/* Next line should be empty. */
d2vgetline(input, line);
if (line.length()) {
err = "Invalid D2V structure.";
goto fail;
}
/* Iterate over the D2V header and fill the context members. */
d2vgetline(input, line);
while(line.length()) {
size_t mid = line.find("=");
string l = line.substr(0, mid);
string r = line.substr(mid + 1, line.length() - 1);
if (l == "Stream_Type") {
int type = atoi(r.c_str());
ret->stream_type = streamtype_conv[type];
} else if (l == "MPEG2_Transport_PID") {
size_t pos = r.find(",");
ret->ts_pid = strtoul(r.substr(0, pos).c_str(), NULL, 16);
} else if (l == "MPEG_Type") {
ret->mpeg_type = atoi(r.c_str());
} else if (l == "iDCT_Algorithm") {
int algo = atoi(r.c_str());
ret->idct_algo = idct_algo_conv[algo];
} else if (l == "YUVRGB_Scale") {
int type = atoi(r.c_str());
ret->yuvrgb_scale = scaletype_conv[type];
} else if (l == "Picture_Size") {
size_t pos = r.find("x");
ret->width = atoi(r.substr( 0, pos ).c_str());
ret->height = atoi(r.substr(pos + 1, r.length() - 1).c_str());
} else if (l == "Frame_Rate") {
size_t start = r.find("(") + 1;
size_t sep = r.find("/");
size_t end = r.find(")");
ret->fps_num = atoi(r.substr( start, sep).c_str());
ret->fps_den = atoi(r.substr(sep + 1, end).c_str());
} else if (l == "Location") {
size_t pos1 = r.find(",");
size_t pos2 = r.find(",", pos1 + 1);
size_t pos3 = r.find(",", pos2 + 1);
ret->loc.startfile = strtoul(r.substr( 0, pos1 ).c_str(), NULL, 16);
ret->loc.startoffset = strtoul(r.substr(pos1 + 1, pos2 ).c_str(), NULL, 16);
ret->loc.endfile = strtoul(r.substr(pos2 + 1, pos3 ).c_str(), NULL, 16);
ret->loc.endoffset = strtoul(r.substr(pos3 + 1, r.length() - 1).c_str(), NULL, 16);
}
d2vgetline(input, line);
}
/* Some basic validation of input headers. */
if (ret->fps_num <= 0 || ret->fps_den <= 0) {
err = "Invalid framerate in D2V header.";
goto fail;
} else if (ret->mpeg_type != 1 && ret->mpeg_type != 2) {
err = "Invalid MPEG type in D2V header.";
goto fail;
} else if (ret->width <= 0 || ret->width <= 0) {
err = "Invalid dimentions in D2V header.";
goto fail;
} else if (ret->stream_type == TRANSPORT && ret->ts_pid < 0) {
err = "Invalid PID in D2V header.";
goto fail;
} else if (ret->stream_type == UNSET) {
err = "Invalid stream type in D2V header.";
goto fail;
} else if (ret->loc.startfile < 0 || ret->loc.startoffset < ret->loc.startfile ||
ret->loc.endfile < ret->loc.startoffset || ret->loc.endoffset > ret->loc.endfile) {
err = "Invalid location in D2V header.";
goto fail;
}
/* Read in all GOPs. */
i = 0;
d2vgetline(input, line);
while(line.length()) {
string tok;
istringstream ss(line);
int offset;
gop cur_gop;
ss >> hex >> cur_gop.info;
ss >> dec >> cur_gop.matrix;
ss >> dec >> cur_gop.file;
ss >> dec >> cur_gop.pos;
ss >> dec >> cur_gop.skip;
ss >> dec >> cur_gop.vob;
ss >> dec >> cur_gop.cell;
offset = 0;
while(!ss.eof()) {
uint16_t flags;
frame f;
ss >> hex >> flags;
/*
* We have to use a 16-bit int to force the stringstream to
* read more than one character, so double check its size.
*/
assert(flags <= 0xFF);
cur_gop.flags.push_back((uint8_t) flags);
f.gop = i;
f.offset = offset;
ret->frames.push_back(f);
offset++;
}
/* The last flag is always 'ff' to signify the end of the stream. */
if (cur_gop.flags.back() == 0xFF) {
cur_gop.flags.pop_back();
ret->frames.pop_back();
}
ret->gops.push_back(cur_gop);
i++;
d2vgetline(input, line);
}
input.close();
if (!ret->frames.size() || !ret->gops.size()) {
err = "No frames in D2V file!";
goto fail;
}
return ret;
fail:
d2vfreep(&ret);
return NULL;
}
<commit_msg>d2v: Fix dimensions check<commit_after>/*
* VapourSynth D2V Plugin
*
* Copyright (c) 2012 Derek Buitenhuis
*
* This file is part of d2vsource.
*
* d2vsource 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.
*
* d2vsource 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 d2vsource; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
extern "C" {
#include <assert.h>
#include <stdlib.h>
#include <string.h>
}
#include "compat.hpp"
#include "d2v.hpp"
#include "gop.hpp"
#ifdef _WIN32
#include <windows.h>
#endif
using namespace std;
string d2vgetpath(const char *d2v_path, const string& file)
{
string path;
string d2v = d2v_path;
size_t delim_pos = d2v.rfind(PATH_DELIM) + 1;
if ((file.substr(0, 1) == "/" || file.substr(1, 1) == ":") || (d2v.substr(0, 1) != "/" && d2v.substr(1, 1) != ":")) {
path = file;
} else {
path = d2v.substr(0, delim_pos);
path += file;
}
return path;
}
/* Conditionally free all memebers of d2vcontext. */
void d2vfreep(d2vcontext **ctx)
{
d2vcontext *lctx = *ctx;
unsigned int i;
if (!lctx)
return;
lctx->frames.clear();
for(i = 0; i < lctx->gops.size(); i++) {
gop g = lctx->gops[i];
g.flags.clear();
}
lctx->gops.clear();
if (lctx->files)
delete [] lctx->files;
delete lctx;
*ctx = NULL;
}
/* Parse the entire D2V index and build the GOP and frame lists. */
d2vcontext *d2vparse(const char *filename, string& err)
{
string line;
ifstream input;
d2vcontext *ret;
int i;
ret = new d2vcontext;
/* Zero the context to aid in conditional freeing later. */
memset(ret, 0, sizeof(*ret));
ret->stream_type = UNSET;
ret->ts_pid = -1;
ret->loc.startfile = -1;
#ifdef _WIN32
wchar_t wide_filename[_MAX_PATH];
i = MultiByteToWideChar(CP_UTF8, 0, filename, -1, wide_filename, ARRAYSIZE(wide_filename));
if (!i) {
err = "D2V filename is invalid: ";
err += filename;
goto fail;
}
input.open(wide_filename);
#else
input.open(filename);
#endif
if (input.fail()) {
err = "D2V cannot be opened.";
goto fail;
}
/* Check the DGIndexProjectFile version. */
d2vgetline(input, line);
if (line.substr(18, 2) != D2V_VERSION) {
err = "D2V Version is unsupported!";
goto fail;
}
/* Get the number of files. */
d2vgetline(input, line);
ret->num_files = atoi(line.c_str());
if (!ret->num_files) {
err = "Invalid D2V File.";
goto fail;
}
/* Allocate files array. */
ret->files = new string[ret->num_files];
/* Read them all in. */
for(i = 0; i < ret->num_files; i++) {
d2vgetline(input, line);
if (line.length()) {
ret->files[i] = d2vgetpath(filename, line);
} else {
err = "Invalid file set in D2V.";
goto fail;
}
}
/* Next line should be empty. */
d2vgetline(input, line);
if (line.length()) {
err = "Invalid D2V structure.";
goto fail;
}
/* Iterate over the D2V header and fill the context members. */
d2vgetline(input, line);
while(line.length()) {
size_t mid = line.find("=");
string l = line.substr(0, mid);
string r = line.substr(mid + 1, line.length() - 1);
if (l == "Stream_Type") {
int type = atoi(r.c_str());
ret->stream_type = streamtype_conv[type];
} else if (l == "MPEG2_Transport_PID") {
size_t pos = r.find(",");
ret->ts_pid = strtoul(r.substr(0, pos).c_str(), NULL, 16);
} else if (l == "MPEG_Type") {
ret->mpeg_type = atoi(r.c_str());
} else if (l == "iDCT_Algorithm") {
int algo = atoi(r.c_str());
ret->idct_algo = idct_algo_conv[algo];
} else if (l == "YUVRGB_Scale") {
int type = atoi(r.c_str());
ret->yuvrgb_scale = scaletype_conv[type];
} else if (l == "Picture_Size") {
size_t pos = r.find("x");
ret->width = atoi(r.substr( 0, pos ).c_str());
ret->height = atoi(r.substr(pos + 1, r.length() - 1).c_str());
} else if (l == "Frame_Rate") {
size_t start = r.find("(") + 1;
size_t sep = r.find("/");
size_t end = r.find(")");
ret->fps_num = atoi(r.substr( start, sep).c_str());
ret->fps_den = atoi(r.substr(sep + 1, end).c_str());
} else if (l == "Location") {
size_t pos1 = r.find(",");
size_t pos2 = r.find(",", pos1 + 1);
size_t pos3 = r.find(",", pos2 + 1);
ret->loc.startfile = strtoul(r.substr( 0, pos1 ).c_str(), NULL, 16);
ret->loc.startoffset = strtoul(r.substr(pos1 + 1, pos2 ).c_str(), NULL, 16);
ret->loc.endfile = strtoul(r.substr(pos2 + 1, pos3 ).c_str(), NULL, 16);
ret->loc.endoffset = strtoul(r.substr(pos3 + 1, r.length() - 1).c_str(), NULL, 16);
}
d2vgetline(input, line);
}
/* Some basic validation of input headers. */
if (ret->fps_num <= 0 || ret->fps_den <= 0) {
err = "Invalid framerate in D2V header.";
goto fail;
} else if (ret->mpeg_type != 1 && ret->mpeg_type != 2) {
err = "Invalid MPEG type in D2V header.";
goto fail;
} else if (ret->width <= 0 || ret->height <= 0) {
err = "Invalid dimensions in D2V header.";
goto fail;
} else if (ret->stream_type == TRANSPORT && ret->ts_pid < 0) {
err = "Invalid PID in D2V header.";
goto fail;
} else if (ret->stream_type == UNSET) {
err = "Invalid stream type in D2V header.";
goto fail;
} else if (ret->loc.startfile < 0 || ret->loc.startoffset < ret->loc.startfile ||
ret->loc.endfile < ret->loc.startoffset || ret->loc.endoffset > ret->loc.endfile) {
err = "Invalid location in D2V header.";
goto fail;
}
/* Read in all GOPs. */
i = 0;
d2vgetline(input, line);
while(line.length()) {
string tok;
istringstream ss(line);
int offset;
gop cur_gop;
ss >> hex >> cur_gop.info;
ss >> dec >> cur_gop.matrix;
ss >> dec >> cur_gop.file;
ss >> dec >> cur_gop.pos;
ss >> dec >> cur_gop.skip;
ss >> dec >> cur_gop.vob;
ss >> dec >> cur_gop.cell;
offset = 0;
while(!ss.eof()) {
uint16_t flags;
frame f;
ss >> hex >> flags;
/*
* We have to use a 16-bit int to force the stringstream to
* read more than one character, so double check its size.
*/
assert(flags <= 0xFF);
cur_gop.flags.push_back((uint8_t) flags);
f.gop = i;
f.offset = offset;
ret->frames.push_back(f);
offset++;
}
/* The last flag is always 'ff' to signify the end of the stream. */
if (cur_gop.flags.back() == 0xFF) {
cur_gop.flags.pop_back();
ret->frames.pop_back();
}
ret->gops.push_back(cur_gop);
i++;
d2vgetline(input, line);
}
input.close();
if (!ret->frames.size() || !ret->gops.size()) {
err = "No frames in D2V file!";
goto fail;
}
return ret;
fail:
d2vfreep(&ret);
return NULL;
}
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "NamespaceOptions.hxx"
#include "Config.hxx"
#include "mount_list.hxx"
#include "pool.hxx"
#include "system/pivot_root.h"
#include "system/bind_mount.h"
#include "pexpand.hxx"
#include <assert.h>
#include <sched.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#ifndef __linux
#error This library requires Linux
#endif
NamespaceOptions::NamespaceOptions(struct pool *pool,
const NamespaceOptions &src)
:enable_user(src.enable_user),
enable_pid(src.enable_pid),
enable_network(src.enable_network),
enable_ipc(src.enable_ipc),
enable_mount(src.enable_mount),
mount_proc(src.mount_proc),
pivot_root(p_strdup_checked(pool, src.pivot_root)),
home(p_strdup_checked(pool, src.home)),
expand_home(p_strdup_checked(pool, src.expand_home)),
mount_home(p_strdup_checked(pool, src.mount_home)),
mount_tmp_tmpfs(p_strdup_checked(pool, src.mount_tmp_tmpfs)),
mount_tmpfs(p_strdup_checked(pool, src.mount_tmpfs)),
mounts(MountList::CloneAll(*pool, src.mounts)),
hostname(p_strdup_checked(pool, src.hostname))
{
}
void
NamespaceOptions::Init()
{
enable_user = false;
enable_pid = false;
enable_network = false;
enable_ipc = false;
enable_mount = false;
mount_proc = false;
pivot_root = nullptr;
home = nullptr;
expand_home = nullptr;
mount_home = nullptr;
mount_tmp_tmpfs = nullptr;
mount_tmpfs = nullptr;
mounts = nullptr;
hostname = nullptr;
}
void
NamespaceOptions::CopyFrom(struct pool &pool, const NamespaceOptions &src)
{
*this = src;
pivot_root = p_strdup_checked(&pool, src.pivot_root);
home = p_strdup_checked(&pool, src.home);
expand_home = p_strdup_checked(&pool, src.expand_home);
mount_home = p_strdup_checked(&pool, src.mount_home);
mount_tmpfs = p_strdup_checked(&pool, src.mount_tmpfs);
mounts = MountList::CloneAll(pool, src.mounts);
hostname = p_strdup_checked(&pool, src.hostname);
}
bool
NamespaceOptions::IsExpandable() const
{
return expand_home != nullptr || MountList::IsAnyExpandable(mounts);
}
bool
NamespaceOptions::Expand(struct pool &pool, const MatchInfo &match_info,
Error &error_r)
{
if (expand_home != nullptr) {
home = expand_string_unescaped(&pool, expand_home, match_info,
error_r);
if (home == nullptr)
return false;
}
return MountList::ExpandAll(pool, mounts, match_info, error_r);
}
int
NamespaceOptions::GetCloneFlags(const SpawnConfig &config, int flags) const
{
// TODO: rewrite the namespace_superuser workaround
if (enable_user && !config.ignore_userns)
flags |= CLONE_NEWUSER;
if (enable_pid)
flags |= CLONE_NEWPID;
if (enable_network)
flags |= CLONE_NEWNET;
if (enable_ipc)
flags |= CLONE_NEWIPC;
if (enable_mount)
flags |= CLONE_NEWNS;
if (hostname != nullptr)
flags |= CLONE_NEWUTS;
return flags;
}
static void
write_file(const char *path, const char *data)
{
int fd = open(path, O_WRONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "open('%s') failed: %s\n",
path, strerror(errno));
_exit(2);
}
if (write(fd, data, strlen(data)) < 0) {
fprintf(stderr, "write('%s') failed: %s\n",
path, strerror(errno));
_exit(2);
}
close(fd);
}
static bool
try_write_file(const char *path, const char *data)
{
int fd = open(path, O_WRONLY|O_CLOEXEC);
if (fd < 0)
return false;
if (write(fd, data, strlen(data)) < 0)
return false;
close(fd);
return true;
}
static void
setup_uid_map(int uid)
{
char buffer[64];
sprintf(buffer, "%d %d 1", uid, uid);
write_file("/proc/self/uid_map", buffer);
}
static void
setup_gid_map(int gid)
{
char buffer[64];
sprintf(buffer, "%d %d 1", gid, gid);
write_file("/proc/self/gid_map", buffer);
}
/**
* Write "deny" to /proc/self/setgroups which is necessary for
* unprivileged processes to set up a gid_map. See Linux commits
* 9cc4651 and 66d2f33 for details.
*/
static void
deny_setgroups()
{
try_write_file("/proc/self/setgroups", "deny");
}
void
NamespaceOptions::Setup(const SpawnConfig &config) const
{
/* set up UID/GID mapping in the old /proc */
if (enable_user && !config.ignore_userns) {
// TODO: rewrite the namespace_superuser workaround
deny_setgroups();
setup_gid_map(config.default_uid_gid.gid);
setup_uid_map(config.default_uid_gid.uid);
}
if (enable_mount)
/* convert all "shared" mounts to "private" mounts */
mount(nullptr, "/", nullptr, MS_PRIVATE|MS_REC, nullptr);
const char *const new_root = pivot_root;
const char *const put_old = "mnt";
if (new_root != nullptr) {
/* first bind-mount the new root onto itself to "unlock" the
kernel's mount object (flag MNT_LOCKED) in our namespace;
without this, the kernel would not allow an unprivileged
process to pivot_root to it */
bind_mount(new_root, new_root, MS_NOSUID|MS_RDONLY);
/* release a reference to the old root */
if (chdir(new_root) < 0) {
fprintf(stderr, "chdir('%s') failed: %s\n",
new_root, strerror(errno));
_exit(2);
}
/* enter the new root */
int result = my_pivot_root(new_root, put_old);
if (result < 0) {
fprintf(stderr, "pivot_root('%s') failed: %s\n",
new_root, strerror(-result));
_exit(2);
}
}
if (mount_proc &&
mount("none", "/proc", "proc", MS_NOEXEC|MS_NOSUID|MS_NODEV|MS_RDONLY, nullptr) < 0) {
fprintf(stderr, "mount('/proc') failed: %s\n",
strerror(errno));
_exit(2);
}
if (mount_home != nullptr || mounts != nullptr) {
/* go to /mnt so we can refer to the old directories with a
relative path */
const char *path = new_root != nullptr ? "/mnt" : "/";
if (chdir(path) < 0) {
fprintf(stderr, "chdir('%s') failed: %s\n", path, strerror(errno));
_exit(2);
}
}
if (mount_home != nullptr) {
assert(home != nullptr);
assert(*home == '/');
bind_mount(home + 1, mount_home, MS_NOSUID|MS_NODEV);
}
MountList::ApplyAll(mounts);
if (new_root != nullptr && (mount_home != nullptr || mounts != nullptr)) {
/* back to the new root */
if (chdir("/") < 0) {
fprintf(stderr, "chdir('/') failed: %s\n", strerror(errno));
_exit(2);
}
}
if (new_root != nullptr) {
/* get rid of the old root */
if (umount2(put_old, MNT_DETACH) < 0) {
fprintf(stderr, "umount('%s') failed: %s",
put_old, strerror(errno));
_exit(2);
}
}
if (mount_tmpfs != nullptr &&
mount("none", mount_tmpfs, "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID,
"size=16M,nr_inodes=256,mode=700") < 0) {
fprintf(stderr, "mount(tmpfs, '%s') failed: %s\n",
mount_tmpfs, strerror(errno));
_exit(2);
}
if (mount_tmp_tmpfs != nullptr) {
const char *options = "size=16M,nr_inodes=256,mode=1777";
char buffer[256];
if (*mount_tmp_tmpfs != 0) {
snprintf(buffer, sizeof(buffer), "%s,%s", options, mount_tmp_tmpfs);
options = buffer;
}
if (mount("none", "/tmp", "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID,
options) < 0) {
fprintf(stderr, "mount('/tmp') failed: %s\n",
strerror(errno));
_exit(2);
}
}
if (hostname != nullptr &&
sethostname(hostname, strlen(hostname)) < 0) {
fprintf(stderr, "sethostname() failed: %s", strerror(errno));
_exit(2);
}
}
char *
NamespaceOptions::MakeId(char *p) const
{
if (enable_user)
p = (char *)mempcpy(p, ";uns", 4);
if (enable_pid)
p = (char *)mempcpy(p, ";pns", 4);
if (enable_network)
p = (char *)mempcpy(p, ";nns", 4);
if (enable_ipc)
p = (char *)mempcpy(p, ";ins", 4);
if (enable_mount) {
p = (char *)(char *)mempcpy(p, ";mns", 4);
if (pivot_root != nullptr) {
p = (char *)mempcpy(p, ";pvr=", 5);
p = stpcpy(p, pivot_root);
}
if (mount_proc)
p = (char *)mempcpy(p, ";proc", 5);
if (mount_proc)
p = (char *)mempcpy(p, ";tmpfs", 6);
if (mount_home != nullptr) {
p = (char *)mempcpy(p, ";h:", 3);
p = stpcpy(p, home);
*p++ = '=';
p = stpcpy(p, mount_home);
}
if (mount_tmpfs != nullptr) {
p = (char *)mempcpy(p, ";t:", 3);
p = stpcpy(p, mount_tmpfs);
}
}
if (hostname != nullptr) {
p = (char *)mempcpy(p, ";uts=", 5);
p = stpcpy(p, hostname);
}
return p;
}
<commit_msg>spawn/NamespaceOptions: fix mount_tmp_tmpfs use in MakeId()<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "NamespaceOptions.hxx"
#include "Config.hxx"
#include "mount_list.hxx"
#include "pool.hxx"
#include "system/pivot_root.h"
#include "system/bind_mount.h"
#include "pexpand.hxx"
#include <assert.h>
#include <sched.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#ifndef __linux
#error This library requires Linux
#endif
NamespaceOptions::NamespaceOptions(struct pool *pool,
const NamespaceOptions &src)
:enable_user(src.enable_user),
enable_pid(src.enable_pid),
enable_network(src.enable_network),
enable_ipc(src.enable_ipc),
enable_mount(src.enable_mount),
mount_proc(src.mount_proc),
pivot_root(p_strdup_checked(pool, src.pivot_root)),
home(p_strdup_checked(pool, src.home)),
expand_home(p_strdup_checked(pool, src.expand_home)),
mount_home(p_strdup_checked(pool, src.mount_home)),
mount_tmp_tmpfs(p_strdup_checked(pool, src.mount_tmp_tmpfs)),
mount_tmpfs(p_strdup_checked(pool, src.mount_tmpfs)),
mounts(MountList::CloneAll(*pool, src.mounts)),
hostname(p_strdup_checked(pool, src.hostname))
{
}
void
NamespaceOptions::Init()
{
enable_user = false;
enable_pid = false;
enable_network = false;
enable_ipc = false;
enable_mount = false;
mount_proc = false;
pivot_root = nullptr;
home = nullptr;
expand_home = nullptr;
mount_home = nullptr;
mount_tmp_tmpfs = nullptr;
mount_tmpfs = nullptr;
mounts = nullptr;
hostname = nullptr;
}
void
NamespaceOptions::CopyFrom(struct pool &pool, const NamespaceOptions &src)
{
*this = src;
pivot_root = p_strdup_checked(&pool, src.pivot_root);
home = p_strdup_checked(&pool, src.home);
expand_home = p_strdup_checked(&pool, src.expand_home);
mount_home = p_strdup_checked(&pool, src.mount_home);
mount_tmpfs = p_strdup_checked(&pool, src.mount_tmpfs);
mounts = MountList::CloneAll(pool, src.mounts);
hostname = p_strdup_checked(&pool, src.hostname);
}
bool
NamespaceOptions::IsExpandable() const
{
return expand_home != nullptr || MountList::IsAnyExpandable(mounts);
}
bool
NamespaceOptions::Expand(struct pool &pool, const MatchInfo &match_info,
Error &error_r)
{
if (expand_home != nullptr) {
home = expand_string_unescaped(&pool, expand_home, match_info,
error_r);
if (home == nullptr)
return false;
}
return MountList::ExpandAll(pool, mounts, match_info, error_r);
}
int
NamespaceOptions::GetCloneFlags(const SpawnConfig &config, int flags) const
{
// TODO: rewrite the namespace_superuser workaround
if (enable_user && !config.ignore_userns)
flags |= CLONE_NEWUSER;
if (enable_pid)
flags |= CLONE_NEWPID;
if (enable_network)
flags |= CLONE_NEWNET;
if (enable_ipc)
flags |= CLONE_NEWIPC;
if (enable_mount)
flags |= CLONE_NEWNS;
if (hostname != nullptr)
flags |= CLONE_NEWUTS;
return flags;
}
static void
write_file(const char *path, const char *data)
{
int fd = open(path, O_WRONLY|O_CLOEXEC);
if (fd < 0) {
fprintf(stderr, "open('%s') failed: %s\n",
path, strerror(errno));
_exit(2);
}
if (write(fd, data, strlen(data)) < 0) {
fprintf(stderr, "write('%s') failed: %s\n",
path, strerror(errno));
_exit(2);
}
close(fd);
}
static bool
try_write_file(const char *path, const char *data)
{
int fd = open(path, O_WRONLY|O_CLOEXEC);
if (fd < 0)
return false;
if (write(fd, data, strlen(data)) < 0)
return false;
close(fd);
return true;
}
static void
setup_uid_map(int uid)
{
char buffer[64];
sprintf(buffer, "%d %d 1", uid, uid);
write_file("/proc/self/uid_map", buffer);
}
static void
setup_gid_map(int gid)
{
char buffer[64];
sprintf(buffer, "%d %d 1", gid, gid);
write_file("/proc/self/gid_map", buffer);
}
/**
* Write "deny" to /proc/self/setgroups which is necessary for
* unprivileged processes to set up a gid_map. See Linux commits
* 9cc4651 and 66d2f33 for details.
*/
static void
deny_setgroups()
{
try_write_file("/proc/self/setgroups", "deny");
}
void
NamespaceOptions::Setup(const SpawnConfig &config) const
{
/* set up UID/GID mapping in the old /proc */
if (enable_user && !config.ignore_userns) {
// TODO: rewrite the namespace_superuser workaround
deny_setgroups();
setup_gid_map(config.default_uid_gid.gid);
setup_uid_map(config.default_uid_gid.uid);
}
if (enable_mount)
/* convert all "shared" mounts to "private" mounts */
mount(nullptr, "/", nullptr, MS_PRIVATE|MS_REC, nullptr);
const char *const new_root = pivot_root;
const char *const put_old = "mnt";
if (new_root != nullptr) {
/* first bind-mount the new root onto itself to "unlock" the
kernel's mount object (flag MNT_LOCKED) in our namespace;
without this, the kernel would not allow an unprivileged
process to pivot_root to it */
bind_mount(new_root, new_root, MS_NOSUID|MS_RDONLY);
/* release a reference to the old root */
if (chdir(new_root) < 0) {
fprintf(stderr, "chdir('%s') failed: %s\n",
new_root, strerror(errno));
_exit(2);
}
/* enter the new root */
int result = my_pivot_root(new_root, put_old);
if (result < 0) {
fprintf(stderr, "pivot_root('%s') failed: %s\n",
new_root, strerror(-result));
_exit(2);
}
}
if (mount_proc &&
mount("none", "/proc", "proc", MS_NOEXEC|MS_NOSUID|MS_NODEV|MS_RDONLY, nullptr) < 0) {
fprintf(stderr, "mount('/proc') failed: %s\n",
strerror(errno));
_exit(2);
}
if (mount_home != nullptr || mounts != nullptr) {
/* go to /mnt so we can refer to the old directories with a
relative path */
const char *path = new_root != nullptr ? "/mnt" : "/";
if (chdir(path) < 0) {
fprintf(stderr, "chdir('%s') failed: %s\n", path, strerror(errno));
_exit(2);
}
}
if (mount_home != nullptr) {
assert(home != nullptr);
assert(*home == '/');
bind_mount(home + 1, mount_home, MS_NOSUID|MS_NODEV);
}
MountList::ApplyAll(mounts);
if (new_root != nullptr && (mount_home != nullptr || mounts != nullptr)) {
/* back to the new root */
if (chdir("/") < 0) {
fprintf(stderr, "chdir('/') failed: %s\n", strerror(errno));
_exit(2);
}
}
if (new_root != nullptr) {
/* get rid of the old root */
if (umount2(put_old, MNT_DETACH) < 0) {
fprintf(stderr, "umount('%s') failed: %s",
put_old, strerror(errno));
_exit(2);
}
}
if (mount_tmpfs != nullptr &&
mount("none", mount_tmpfs, "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID,
"size=16M,nr_inodes=256,mode=700") < 0) {
fprintf(stderr, "mount(tmpfs, '%s') failed: %s\n",
mount_tmpfs, strerror(errno));
_exit(2);
}
if (mount_tmp_tmpfs != nullptr) {
const char *options = "size=16M,nr_inodes=256,mode=1777";
char buffer[256];
if (*mount_tmp_tmpfs != 0) {
snprintf(buffer, sizeof(buffer), "%s,%s", options, mount_tmp_tmpfs);
options = buffer;
}
if (mount("none", "/tmp", "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID,
options) < 0) {
fprintf(stderr, "mount('/tmp') failed: %s\n",
strerror(errno));
_exit(2);
}
}
if (hostname != nullptr &&
sethostname(hostname, strlen(hostname)) < 0) {
fprintf(stderr, "sethostname() failed: %s", strerror(errno));
_exit(2);
}
}
char *
NamespaceOptions::MakeId(char *p) const
{
if (enable_user)
p = (char *)mempcpy(p, ";uns", 4);
if (enable_pid)
p = (char *)mempcpy(p, ";pns", 4);
if (enable_network)
p = (char *)mempcpy(p, ";nns", 4);
if (enable_ipc)
p = (char *)mempcpy(p, ";ins", 4);
if (enable_mount) {
p = (char *)(char *)mempcpy(p, ";mns", 4);
if (pivot_root != nullptr) {
p = (char *)mempcpy(p, ";pvr=", 5);
p = stpcpy(p, pivot_root);
}
if (mount_proc)
p = (char *)mempcpy(p, ";proc", 5);
if (mount_home != nullptr) {
p = (char *)mempcpy(p, ";h:", 3);
p = stpcpy(p, home);
*p++ = '=';
p = stpcpy(p, mount_home);
}
if (mount_tmp_tmpfs != nullptr) {
p = (char *)mempcpy(p, ";tt:", 3);
p = stpcpy(p, mount_tmp_tmpfs);
}
if (mount_tmpfs != nullptr) {
p = (char *)mempcpy(p, ";t:", 3);
p = stpcpy(p, mount_tmpfs);
}
}
if (hostname != nullptr) {
p = (char *)mempcpy(p, ";uts=", 5);
p = stpcpy(p, hostname);
}
return p;
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief PicoJPEG 画像クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdio>
#include <cstdlib>
#include "graphics/img.hpp"
#include "graphics/picojpeg.h"
#include "common/file_io.hpp"
#include "common/format.hpp"
namespace img {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief PicoJPEG 形式ファイルクラス
@param[in] RENDER 描画ファンクタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class RENDER>
class picojpeg_in {
RENDER& render_;
pjpeg_image_info_t image_info_;
uint8_t status_;
bool reduce_;
int16_t width_;
int16_t height_;
int16_t ofs_x_;
int16_t ofs_y_;
struct data_t {
utils::file_io& fin_;
uint32_t file_ofs_;
uint32_t file_size_;
data_t(utils::file_io& fin) : fin_(fin), file_ofs_(0), file_size_(0) { }
};
void render_rgb_(int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b)
{
auto c = RENDER::COLOR::rgb(r, g, b);
render_.plot(ofs_x_ + x, ofs_y_ + y, c);
}
static uint8_t pjpeg_callback_(uint8_t* dst, uint8_t size, uint8_t* acr, void *pdata)
{
data_t* t = static_cast<data_t*>(pdata);
auto len = std::min(t->file_size_ - t->file_ofs_, static_cast<uint32_t>(size));
auto rl = t->fin_.read(dst, len);
// utils::format("Read: %d (%d)\n") % len % rl;
*acr = rl;
t->file_ofs_ += rl;
return 0;
}
bool pixel_(utils::file_io& fin) noexcept
{
int16_t xt = 0;
int16_t yt = 0;
while((status_ = pjpeg_decode_mcu()) == 0) {
if(reduce_) {
auto row_blocks = image_info_.m_MCUWidth >> 3;
auto col_blocks = image_info_.m_MCUHeight >> 3;
int16_t xx = xt * row_blocks + ofs_x_;
int16_t yy = yt * col_blocks + ofs_y_;
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
auto gs = image_info_.m_pMCUBufR[0];
render_rgb_(xx, yy, gs, gs, gs);
} else {
for(int16_t y = 0; y < col_blocks; ++y) {
auto ofs = y * 128;
for(int16_t x = 0; x < row_blocks; ++x) {
auto r = image_info_.m_pMCUBufR[ofs];
auto g = image_info_.m_pMCUBufG[ofs];
auto b = image_info_.m_pMCUBufB[ofs];
ofs += 64;
render_rgb_(xx + x, yy + y, r, g, b);
}
}
}
} else {
for(int16_t y = 0; y < image_info_.m_MCUHeight; y += 8) {
auto yy = yt * image_info_.m_MCUHeight + ofs_y_;
auto by_limit = std::min(8,
image_info_.m_height - (yt * image_info_.m_MCUHeight + y));
for(int16_t x = 0; x < image_info_.m_MCUWidth; x += 8) {
auto bx_limit = std::min(8,
image_info_.m_width - (xt * image_info_.m_MCUWidth + x));
auto xx = xt * image_info_.m_MCUWidth + ofs_x_;
auto ofs = (x * 8) + (y * 16);
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
const uint8_t* pGS = image_info_.m_pMCUBufR + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto gs = *pGS++;
render_rgb_(xx + bx, yy + by, gs, gs, gs);
}
pGS += (8 - bx_limit);
}
} else {
const uint8_t* pR = image_info_.m_pMCUBufR + ofs;
const uint8_t* pG = image_info_.m_pMCUBufG + ofs;
const uint8_t* pB = image_info_.m_pMCUBufB + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto r = *pR++;
auto g = *pG++;
auto b = *pB++;
render_rgb_(xx + bx, yy + by, r, g, b);
}
pR += (8 - bx_limit);
pG += (8 - bx_limit);
pB += (8 - bx_limit);
}
}
}
}
}
++xt;
if(xt == image_info_.m_MCUSPerRow) {
xt = 0;
++yt;
}
}
if(status_ != PJPG_NO_MORE_BLOCKS) {
utils::format("pjpeg_decode_mcu() failed with status: %d\n") % status_;
return false;
}
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
picojpeg_in(RENDER& render) noexcept : render_(render),
image_info_(),
status_(0), reduce_(false),
width_(0), height_(0), ofs_x_(0), ofs_y_(0)
{ }
//-----------------------------------------------------------------//
/*!
@brief ステータスの取得(Error code)
@return ステータス
*/
//-----------------------------------------------------------------//
uint8_t get_status() const noexcept { return status_; }
//-----------------------------------------------------------------//
/*!
@brief 描画オフセットの設定
@param[in] x X 軸オフセット
@param[in] y Y 軸オフセット
*/
//-----------------------------------------------------------------//
void set_draw_offset(int16_t x = 0, int16_t y = 0) noexcept
{
ofs_x_ = x;
ofs_y_ = y;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ファイルか確認する
@param[in] fin file_io クラス
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool probe(utils::file_io& fin) noexcept
{
uint8_t sig[2];
uint32_t pos = fin.tell();
uint32_t l = fin.read(sig, 2);
fin.seek(utils::file_io::SEEK::SET, pos);
if(l == 2) {
if(sig[0] == 0xff && sig[1] == 0xd8) { // SOI Marker, Start image
return true;
}
}
// utils::format("Not JPEG file\n");
return false;
}
//-----------------------------------------------------------------//
/*!
@brief 画像ファイルの情報を取得する
@param[in] fin file_io クラス
@param[in] fo 情報を受け取る構造体
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool info(utils::file_io& fin, img::img_info& fo) noexcept
{
auto pos = fin.tell();
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, false);
if(status_) {
fin.close();
return false;
}
fin.seek(utils::file_io::SEEK::SET, pos);
fo.width = image_info_.m_width;
fo.height = image_info_.m_height;
switch(image_info_.m_comps) {
case 1:
fo.grayscale = true;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 3:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 4:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 8;
fo.clut_num = 0;
break;
default:
fo.i_depth = 0;
fo.r_depth = 0;
fo.g_depth = 0;
fo.b_depth = 0;
fo.a_depth = 0;
fo.clut_num = 0;
return false;
break;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ファイル、ロード
@param[in] fin file_io クラス
@param[in] opt フォーマット固有の設定文字列
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool load(utils::file_io& fin, const char* opt = nullptr)
{
// とりあえず、ヘッダーの検査
if(!probe(fin)) {
return false;
}
reduce_ = false;
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, reduce_);
if(status_) {
if(status_ == PJPG_UNSUPPORTED_MODE) {
// utils::format("Progressive JPEG files are not supported.\n");
} else {
// utils::format("pjpeg_decode_init() failed with status: %d\n") % status_;
}
fin.close();
return false;
}
// In reduce mode output 1 pixel per 8x8 block.
width_ = reduce_ ?
(image_info_.m_MCUSPerRow * image_info_.m_MCUWidth) / 8 : image_info_.m_width;
height_ = reduce_ ?
(image_info_.m_MCUSPerCol * image_info_.m_MCUHeight) / 8 : image_info_.m_height;
auto ret = pixel_(fin);
fin.close();
return ret;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ファイルをロードする
@param[in] fin ファイル I/O クラス
@param[in] opt フォーマット固有の設定文字列
@return エラーがあれば「false」
*/
//-----------------------------------------------------------------//
bool load(const char* fname, const char* opt = nullptr) noexcept
{
if(fname == nullptr) return false;
utils::file_io fin;
if(!fin.open(fname, "rb")) {
return false;
}
auto ret = load(fin, opt);
fin.close();
return ret;
}
};
}
<commit_msg>update: cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief PicoJPEG クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdio>
#include <cstdlib>
#include "graphics/img.hpp"
#include "graphics/picojpeg.h"
#include "common/file_io.hpp"
#include "common/format.hpp"
namespace img {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief PicoJPEG デコード・クラス
@param[in] RENDER 描画ファンクタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class RENDER>
class picojpeg_in {
RENDER& render_;
pjpeg_image_info_t image_info_;
uint8_t status_;
bool reduce_;
int16_t width_;
int16_t height_;
int16_t ofs_x_;
int16_t ofs_y_;
struct data_t {
utils::file_io& fin_;
uint32_t file_ofs_;
uint32_t file_size_;
data_t(utils::file_io& fin) : fin_(fin), file_ofs_(0), file_size_(0) { }
};
void render_rgb_(int16_t x, int16_t y, uint8_t r, uint8_t g, uint8_t b)
{
auto c = RENDER::COLOR::rgb(r, g, b);
render_.plot(ofs_x_ + x, ofs_y_ + y, c);
}
static uint8_t pjpeg_callback_(uint8_t* dst, uint8_t size, uint8_t* acr, void *pdata)
{
data_t* t = static_cast<data_t*>(pdata);
auto len = std::min(t->file_size_ - t->file_ofs_, static_cast<uint32_t>(size));
auto rl = t->fin_.read(dst, len);
// utils::format("Read: %d (%d)\n") % len % rl;
*acr = rl;
t->file_ofs_ += rl;
return 0;
}
bool pixel_(utils::file_io& fin) noexcept
{
int16_t xt = 0;
int16_t yt = 0;
while((status_ = pjpeg_decode_mcu()) == 0) {
if(reduce_) {
auto row_blocks = image_info_.m_MCUWidth >> 3;
auto col_blocks = image_info_.m_MCUHeight >> 3;
int16_t xx = xt * row_blocks + ofs_x_;
int16_t yy = yt * col_blocks + ofs_y_;
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
auto gs = image_info_.m_pMCUBufR[0];
render_rgb_(xx, yy, gs, gs, gs);
} else {
for(int16_t y = 0; y < col_blocks; ++y) {
auto ofs = y * 128;
for(int16_t x = 0; x < row_blocks; ++x) {
auto r = image_info_.m_pMCUBufR[ofs];
auto g = image_info_.m_pMCUBufG[ofs];
auto b = image_info_.m_pMCUBufB[ofs];
ofs += 64;
render_rgb_(xx + x, yy + y, r, g, b);
}
}
}
} else {
for(int16_t y = 0; y < image_info_.m_MCUHeight; y += 8) {
auto yy = yt * image_info_.m_MCUHeight + ofs_y_;
auto by_limit = std::min(8,
image_info_.m_height - (yt * image_info_.m_MCUHeight + y));
for(int16_t x = 0; x < image_info_.m_MCUWidth; x += 8) {
auto bx_limit = std::min(8,
image_info_.m_width - (xt * image_info_.m_MCUWidth + x));
auto xx = xt * image_info_.m_MCUWidth + ofs_x_;
auto ofs = (x * 8) + (y * 16);
if(image_info_.m_scanType == PJPG_GRAYSCALE) {
const uint8_t* pGS = image_info_.m_pMCUBufR + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto gs = *pGS++;
render_rgb_(xx + bx, yy + by, gs, gs, gs);
}
pGS += (8 - bx_limit);
}
} else {
const uint8_t* pR = image_info_.m_pMCUBufR + ofs;
const uint8_t* pG = image_info_.m_pMCUBufG + ofs;
const uint8_t* pB = image_info_.m_pMCUBufB + ofs;
for(int16_t by = 0; by < by_limit; ++by) {
for(int16_t bx = 0; bx < bx_limit; ++bx) {
auto r = *pR++;
auto g = *pG++;
auto b = *pB++;
render_rgb_(xx + bx, yy + by, r, g, b);
}
pR += (8 - bx_limit);
pG += (8 - bx_limit);
pB += (8 - bx_limit);
}
}
}
}
}
++xt;
if(xt == image_info_.m_MCUSPerRow) {
xt = 0;
++yt;
}
}
if(status_ != PJPG_NO_MORE_BLOCKS) {
utils::format("pjpeg_decode_mcu() failed with status: %d\n") % status_;
return false;
}
return true;
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
picojpeg_in(RENDER& render) noexcept : render_(render),
image_info_(),
status_(0), reduce_(false),
width_(0), height_(0), ofs_x_(0), ofs_y_(0)
{ }
//-----------------------------------------------------------------//
/*!
@brief ステータスの取得(Error code)
@return ステータス
*/
//-----------------------------------------------------------------//
uint8_t get_status() const noexcept { return status_; }
//-----------------------------------------------------------------//
/*!
@brief 描画オフセットの設定
@param[in] x X 軸オフセット
@param[in] y Y 軸オフセット
*/
//-----------------------------------------------------------------//
void set_draw_offset(int16_t x = 0, int16_t y = 0) noexcept
{
ofs_x_ = x;
ofs_y_ = y;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ファイルか確認する
@param[in] fin file_io クラス
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool probe(utils::file_io& fin) noexcept
{
uint8_t sig[2];
uint32_t pos = fin.tell();
uint32_t l = fin.read(sig, 2);
fin.seek(utils::file_io::SEEK::SET, pos);
if(l == 2) {
if(sig[0] == 0xff && sig[1] == 0xd8) { // SOI Marker, Start image
return true;
}
}
// utils::format("Not JPEG file\n");
return false;
}
//-----------------------------------------------------------------//
/*!
@brief 画像ファイルの情報を取得する
@param[in] fin file_io クラス
@param[in] fo 情報を受け取る構造体
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool info(utils::file_io& fin, img::img_info& fo) noexcept
{
auto pos = fin.tell();
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, false);
if(status_) {
fin.close();
return false;
}
fin.seek(utils::file_io::SEEK::SET, pos);
fo.width = image_info_.m_width;
fo.height = image_info_.m_height;
switch(image_info_.m_comps) {
case 1:
fo.grayscale = true;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 3:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 0;
fo.clut_num = 0;
break;
case 4:
fo.grayscale = false;
fo.i_depth = 0;
fo.r_depth = 8;
fo.g_depth = 8;
fo.b_depth = 8;
fo.a_depth = 8;
fo.clut_num = 0;
break;
default:
fo.i_depth = 0;
fo.r_depth = 0;
fo.g_depth = 0;
fo.b_depth = 0;
fo.a_depth = 0;
fo.clut_num = 0;
return false;
break;
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ファイル、ロード
@param[in] fin file_io クラス
@param[in] opt フォーマット固有の設定文字列
@return エラーなら「false」を返す
*/
//-----------------------------------------------------------------//
bool load(utils::file_io& fin, const char* opt = nullptr)
{
// とりあえず、ヘッダーの検査
if(!probe(fin)) {
return false;
}
reduce_ = false;
data_t t(fin);
t.file_ofs_ = 0;
t.file_size_ = fin.get_file_size();
status_ = pjpeg_decode_init(&image_info_, pjpeg_callback_, &t, reduce_);
if(status_) {
if(status_ == PJPG_UNSUPPORTED_MODE) {
// utils::format("Progressive JPEG files are not supported.\n");
} else {
// utils::format("pjpeg_decode_init() failed with status: %d\n") % status_;
}
fin.close();
return false;
}
// In reduce mode output 1 pixel per 8x8 block.
width_ = reduce_ ?
(image_info_.m_MCUSPerRow * image_info_.m_MCUWidth) / 8 : image_info_.m_width;
height_ = reduce_ ?
(image_info_.m_MCUSPerCol * image_info_.m_MCUHeight) / 8 : image_info_.m_height;
auto ret = pixel_(fin);
fin.close();
return ret;
}
//-----------------------------------------------------------------//
/*!
@brief JPEG ファイルをロードする
@param[in] fin ファイル I/O クラス
@param[in] opt フォーマット固有の設定文字列
@return エラーがあれば「false」
*/
//-----------------------------------------------------------------//
bool load(const char* fname, const char* opt = nullptr) noexcept
{
if(fname == nullptr) return false;
utils::file_io fin;
if(!fin.open(fname, "rb")) {
return false;
}
auto ret = load(fin, opt);
fin.close();
return ret;
}
};
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2021 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_IFMT_HPP
#define TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_IFMT_HPP
#include <tao/pegtl.hpp>
#include "verify_meta.hpp"
#include "verify_rule.hpp"
namespace TAO_PEGTL_NAMESPACE
{
template< template< typename, typename, typename > class S >
void verify_ifmt( const result_type failure = result_type::local_failure )
{
verify_analyze< S< eof, eof, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< eof, eof, any > >( __LINE__, __FILE__, false, false );
verify_analyze< S< eof, any, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< eof, any, any > >( __LINE__, __FILE__, true, false );
verify_analyze< S< any, eof, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< any, eof, any > >( __LINE__, __FILE__, true, false );
verify_analyze< S< any, any, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< any, any, any > >( __LINE__, __FILE__, true, false );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "", failure, 0 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "b", failure, 1 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "c", result_type::success, 0 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "ab", result_type::success, 0 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "ac", failure, 2 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "", result_type::global_failure, 0 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "a", result_type::global_failure, 0 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "ac", result_type::global_failure, 1 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "b", result_type::global_failure, 1 );
verify_rule< must< S< one< 'a' >, one< 'b' >, seq< one< 'c' >, one< 'd' > > > > >( __LINE__, __FILE__, "c", result_type::global_failure, 0 );
verify_rule< must< S< one< 'a' >, one< 'b' >, seq< one< 'c' >, one< 'd' > > > > >( __LINE__, __FILE__, "cc", result_type::global_failure, 1 );
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
<commit_msg>Allow disabling exceptions<commit_after>// Copyright (c) 2014-2021 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_IFMT_HPP
#define TAO_PEGTL_SRC_TEST_PEGTL_VERIFY_IFMT_HPP
#include <tao/pegtl.hpp>
#include "verify_meta.hpp"
#include "verify_rule.hpp"
namespace TAO_PEGTL_NAMESPACE
{
template< template< typename, typename, typename > class S >
void verify_ifmt( const result_type failure = result_type::local_failure )
{
verify_analyze< S< eof, eof, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< eof, eof, any > >( __LINE__, __FILE__, false, false );
verify_analyze< S< eof, any, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< eof, any, any > >( __LINE__, __FILE__, true, false );
verify_analyze< S< any, eof, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< any, eof, any > >( __LINE__, __FILE__, true, false );
verify_analyze< S< any, any, eof > >( __LINE__, __FILE__, false, false );
verify_analyze< S< any, any, any > >( __LINE__, __FILE__, true, false );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "", failure, 0 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "b", failure, 1 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "c", result_type::success, 0 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "ab", result_type::success, 0 );
verify_rule< S< one< 'a' >, one< 'b' >, one< 'c' > > >( __LINE__, __FILE__, "ac", failure, 2 );
#if defined( __cxx_exceptions )
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "", result_type::global_failure, 0 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "a", result_type::global_failure, 0 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "ac", result_type::global_failure, 1 );
verify_rule< must< S< one< 'a' >, one< 'b' >, one< 'c' > > > >( __LINE__, __FILE__, "b", result_type::global_failure, 1 );
verify_rule< must< S< one< 'a' >, one< 'b' >, seq< one< 'c' >, one< 'd' > > > > >( __LINE__, __FILE__, "c", result_type::global_failure, 0 );
verify_rule< must< S< one< 'a' >, one< 'b' >, seq< one< 'c' >, one< 'd' > > > > >( __LINE__, __FILE__, "cc", result_type::global_failure, 1 );
#endif
}
} // namespace TAO_PEGTL_NAMESPACE
#endif
<|endoftext|>
|
<commit_before>#line 2 "togo/debug_constraints.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file debug_constraints.hpp
@brief Definitions for constraints.
*/
#pragma once
#include <togo/config.hpp>
#if defined(TOGO_USE_CONSTRAINTS)
#include <type_traits>
#define TOGO_CONSTRAIN_IS_POD(T) \
static_assert( \
std::is_standard_layout<T>::value, \
"T is not a POD type" \
)
#define TOGO_CONSTRAIN_SAME(T, U) \
static_assert( \
std::is_same<T, U>::value, \
"T and U are not the same types" \
)
#define TOGO_CONSTRAIN_INTEGRAL(T) \
static_assert( \
std::is_integral<T>::value, \
"T is not an integral type" \
)
#define TOGO_CONSTRAIN_ARITHMETIC(T) \
static_assert( \
std::is_arithmetic<T>::value, \
"T is not an arithmetic type" \
)
#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T) \
static_assert( \
std::is_integral<T>::value && \
std::is_arithmetic<T>::value, \
"T is not an integral arithmetic type" \
)
#define TOGO_CONSTRAIN_COMPARABLE(T) \
static_assert( \
std::is_pointer<T>::value || \
( \
std::is_integral<T>::value && \
std::is_arithmetic<T>::value \
), \
"T is not a permitted built-in comparable type" \
)
#else
/// Statically assert that type T is of standard layout.
#define TOGO_CONSTRAIN_IS_POD(T)
/// Statically assert that type T is the same as type U.
#define TOGO_CONSTRAIN_SAME(T, U)
/// Statically assert that type T is an integral type.
#define TOGO_CONSTRAIN_INTEGRAL(T)
/// Statically assert that type T is an arithmetic type.
#define TOGO_CONSTRAIN_ARITHMETIC(T)
/// Statically assert that type T is an integral arithmetic type.
#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T)
/// Statically assert that type T is a built-in comparable type.
///
/// Comparable types are arithmetic integrals and pointers.
#define TOGO_CONSTRAIN_COMPARABLE(T)
#endif
<commit_msg>debug_constraints: added TOGO_CONSTRAIN_UNSIGNED(T).<commit_after>#line 2 "togo/debug_constraints.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file debug_constraints.hpp
@brief Definitions for constraints.
*/
#pragma once
#include <togo/config.hpp>
#if defined(TOGO_USE_CONSTRAINTS)
#include <type_traits>
#define TOGO_CONSTRAIN_IS_POD(T) \
static_assert( \
std::is_standard_layout<T>::value, \
"T is not a POD type" \
)
#define TOGO_CONSTRAIN_SAME(T, U) \
static_assert( \
std::is_same<T, U>::value, \
"T and U are not the same types" \
)
#define TOGO_CONSTRAIN_INTEGRAL(T) \
static_assert( \
std::is_integral<T>::value, \
"T is not an integral type" \
)
#define TOGO_CONSTRAIN_ARITHMETIC(T) \
static_assert( \
std::is_arithmetic<T>::value, \
"T is not an arithmetic type" \
)
#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T) \
static_assert( \
std::is_integral<T>::value && \
std::is_arithmetic<T>::value, \
"T is not an integral arithmetic type" \
)
#define TOGO_CONSTRAIN_UNSIGNED(T) \
static_assert( \
std::is_unsigned<T>::value, \
"T is not an unsigned arithmetic type" \
)
#define TOGO_CONSTRAIN_COMPARABLE(T) \
static_assert( \
std::is_pointer<T>::value || \
( \
std::is_integral<T>::value && \
std::is_arithmetic<T>::value \
), \
"T is not a permitted built-in comparable type" \
)
#else
/// Statically assert that type T is of standard layout.
#define TOGO_CONSTRAIN_IS_POD(T)
/// Statically assert that type T is the same as type U.
#define TOGO_CONSTRAIN_SAME(T, U)
/// Statically assert that type T is an integral type.
#define TOGO_CONSTRAIN_INTEGRAL(T)
/// Statically assert that type T is an arithmetic type.
#define TOGO_CONSTRAIN_ARITHMETIC(T)
/// Statically assert that type T is an integral arithmetic type.
#define TOGO_CONSTRAIN_INTEGRAL_ARITHMETIC(T)
/// Statically assert that type T is an unsigned arithmetic type.
#define TOGO_CONSTRAIN_UNSIGNED(T)
/// Statically assert that type T is a built-in comparable type.
///
/// Comparable types are arithmetic integrals and pointers.
#define TOGO_CONSTRAIN_COMPARABLE(T)
#endif
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#ifndef ELEKTRA_KDB_IO_HPP
#define ELEKTRA_KDB_IO_HPP
/*
* @brief See examples/cpp_example_userio.cpp for how to use
* USER_DEFINED_IO
*/
#define USER_DEFINED_IO
#include <key.hpp>
#include <iomanip>
#include <ostream>
#include "ansicolors.hpp"
namespace kdb
{
inline std::ostream & printError (std::ostream & os, kdb::Key const & error)
{
try
{
if (!error.getMeta<const kdb::Key> ("error"))
{
// no error available
return os;
}
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::RED) << "Error (#"
<< error.getMeta<std::string> ("error/number") << ") occurred!" << getErrorColor (ANSI_COLOR::RESET) << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Description: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/description") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Ingroup: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/ingroup") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Module: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/module") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "At: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/file") << ":" << error.getMeta<std::string> ("error/line") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Reason: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/reason") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Mountpoint: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/mountpoint") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Configfile: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/configfile") << std::endl;
}
catch (kdb::KeyTypeConversion const & e)
{
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::RED)
<< "Error metadata is not set correctly by a plugin: " << getErrorColor (ANSI_COLOR::RESET) << e.what () << std::endl;
}
return os;
}
inline std::ostream & printWarnings (std::ostream & os, kdb::Key const & error)
{
try
{
if (!error.getMeta<const kdb::Key> ("warnings"))
{
// no warnings were issued
return os;
}
int nr = error.getMeta<int> ("warnings");
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::MAGENTA) << nr + 1 << " Warning" << (!nr ? "" : "s")
<< " were issued:" << getErrorColor (ANSI_COLOR::RESET) << std::endl;
for (int i = 0; i <= nr; i++)
{
std::ostringstream name;
name << "warnings/#" << std::setfill ('0') << std::setw (2) << i;
// os << "\t" << name.str() << ": " << error.getMeta<std::string>(name.str()) << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::MAGENTA)
<< " Warning number: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/number") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tDescription: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/description") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tIngroup: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/ingroup") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tModule: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/module") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tAt: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/file") << ":"
<< error.getMeta<std::string> (name.str () + "/line") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tReason: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/reason") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tMountpoint: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/mountpoint") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tConfigfile: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/configfile") << std::endl;
}
}
catch (kdb::KeyTypeConversion const & e)
{
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::MAGENTA)
<< "Warnings metadata not set correctly by a plugin: " << getErrorColor (ANSI_COLOR::RESET) << e.what () << std::endl;
}
return os;
}
}
#endif
<commit_msg>errormsg: add sorry<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*/
#ifndef ELEKTRA_KDB_IO_HPP
#define ELEKTRA_KDB_IO_HPP
/*
* @brief See examples/cpp_example_userio.cpp for how to use
* USER_DEFINED_IO
*/
#define USER_DEFINED_IO
#include <key.hpp>
#include <iomanip>
#include <ostream>
#include "ansicolors.hpp"
namespace kdb
{
inline std::ostream & printError (std::ostream & os, kdb::Key const & error)
{
try
{
if (!error.getMeta<const kdb::Key> ("error"))
{
// no error available
return os;
}
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::RED) << "Sorry, the error (#"
<< error.getMeta<std::string> ("error/number") << ") occurred ;(" << getErrorColor (ANSI_COLOR::RESET) << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Description: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/description") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Ingroup: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/ingroup") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Module: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/module") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "At: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/file") << ":" << error.getMeta<std::string> ("error/line") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Reason: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/reason") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Mountpoint: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/mountpoint") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "Configfile: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> ("error/configfile") << std::endl;
}
catch (kdb::KeyTypeConversion const & e)
{
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::RED)
<< "Sorry, error metadata is not set correctly by a plugin: " << getErrorColor (ANSI_COLOR::RESET) << e.what () << std::endl;
}
return os;
}
inline std::ostream & printWarnings (std::ostream & os, kdb::Key const & error)
{
try
{
if (!error.getMeta<const kdb::Key> ("warnings"))
{
// no warnings were issued
return os;
}
int nr = error.getMeta<int> ("warnings");
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::MAGENTA) << " Sorry, " << nr + 1 << " warning" << (!nr ? " was" : "s were")
<< " issued:" << getErrorColor (ANSI_COLOR::RESET) << " ;(" << std::endl;
for (int i = 0; i <= nr; i++)
{
std::ostringstream name;
name << "warnings/#" << std::setfill ('0') << std::setw (2) << i;
// os << "\t" << name.str() << ": " << error.getMeta<std::string>(name.str()) << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::MAGENTA)
<< " Warning " << i << getErrorColor (ANSI_COLOR::RESET) << " (#"
<< error.getMeta<std::string> (name.str () + "/number") << ")" << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tDescription: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/description") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tIngroup: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/ingroup") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tModule: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/module") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tAt: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/file") << ":"
<< error.getMeta<std::string> (name.str () + "/line") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tReason: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/reason") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tMountpoint: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/mountpoint") << std::endl;
os << getErrorColor (ANSI_COLOR::BOLD) << "\tConfigfile: " << getErrorColor (ANSI_COLOR::RESET)
<< error.getMeta<std::string> (name.str () + "/configfile") << std::endl;
}
}
catch (kdb::KeyTypeConversion const & e)
{
os << getErrorColor (ANSI_COLOR::BOLD) << getErrorColor (ANSI_COLOR::MAGENTA)
<< "Sorry, warnings metadata not set correctly by a plugin: " << getErrorColor (ANSI_COLOR::RESET) << e.what () << std::endl;
}
return os;
}
}
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include "zlib.h"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/io.hpp"
namespace
{
enum
{
udp_connection_retries = 4,
udp_announce_retries = 15,
udp_connect_timeout = 15,
udp_announce_timeout = 10,
udp_buffer_size = 2048
};
}
using namespace boost::posix_time;
namespace libtorrent
{
udp_tracker_connection::udp_tracker_connection(
tracker_request const& req
, std::string const& hostname
, unsigned short port
, boost::weak_ptr<request_callback> c
, const http_settings& stn)
: tracker_connection(c)
, m_request_time(second_clock::universal_time())
, m_request(req)
, m_transaction_id(0)
, m_connection_id(0)
, m_settings(stn)
, m_attempts(0)
{
// only announce is suppoerted at this time
assert(req.kind == tracker_request::announce_request);
// TODO: this is a problem. DNS-lookup is blocking!
// (may block up to 5 seconds)
address a(hostname.c_str(), port);
if (has_requester()) requester().m_tracker_address = a;
m_socket.reset(new socket(socket::udp, false));
m_socket->connect(a);
send_udp_connect();
}
bool udp_tracker_connection::send_finished() const
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
return (m_transaction_id != 0
&& m_connection_id != 0)
|| d > seconds(m_settings.tracker_timeout);
}
bool udp_tracker_connection::tick()
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
if (m_connection_id == 0
&& d > seconds(udp_connect_timeout))
{
if (m_attempts >= udp_connection_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
send_udp_connect();
return false;
}
if (m_connection_id != 0
&& d > seconds(udp_announce_timeout))
{
if (m_attempts >= udp_announce_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
send_udp_announce();
return false;
}
char buf[udp_buffer_size];
int ret = m_socket->receive(buf, udp_buffer_size);
// if there was nothing to receive, return
if (ret == 0) return false;
if (ret < 0)
{
socket::error_code err = m_socket->last_error();
if (err == socket::would_block) return false;
throw network_error(m_socket->last_error());
}
if (ret == udp_buffer_size)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "tracker reply too big");
return true;
}
if (m_connection_id == 0)
{
return parse_connect_response(buf, ret);
}
else
{
return parse_announce_response(buf, ret);
}
}
void udp_tracker_connection::send_udp_announce()
{
if (m_transaction_id == 0)
m_transaction_id = rand() | (rand() << 16);
std::vector<char> buf;
std::back_insert_iterator<std::vector<char> > out(buf);
// connection_id
detail::write_int64(m_connection_id, out);
// action (announce)
detail::write_int32(announce, out);
// transaction_id
detail::write_int32(m_transaction_id, out);
// info_hash
std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);
// peer_id
std::copy(m_request.id.begin(), m_request.id.end(), out);
// downloaded
detail::write_int64(m_request.downloaded, out);
// left
detail::write_int64(m_request.left, out);
// uploaded
detail::write_int64(m_request.uploaded, out);
// event
detail::write_int32(m_request.event, out);
// ip address
detail::write_int32(0, out);
// key
detail::write_int32(m_request.key, out);
// num_want
detail::write_int32(m_request.num_want, out);
// port
detail::write_uint16(m_request.listen_port, out);
m_socket->send(&buf[0], buf.size());
m_request_time = second_clock::universal_time();
++m_attempts;
}
void udp_tracker_connection::send_udp_connect()
{
char send_buf[16];
char* ptr = send_buf;
if (m_transaction_id == 0)
m_transaction_id = rand() | (rand() << 16);
// connection_id
detail::write_int64(0, ptr);
// action (connect)
detail::write_int32(connect, ptr);
// transaction_id
detail::write_int32(m_transaction_id, ptr);
m_socket->send(send_buf, 16);
m_request_time = second_clock::universal_time();
++m_attempts;
}
bool udp_tracker_connection::parse_announce_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
int action = detail::read_int32(buf);
int transaction = detail::read_int32(buf);
if (transaction != m_transaction_id)
{
return false;
}
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(buf, buf + len - 8));
return true;
}
if (action != announce) return false;
if (len < 24)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 24, ignoring");
#endif
return false;
}
int interval = detail::read_int32(buf);
int incomplete = detail::read_int32(buf);
int complete = detail::read_int32(buf);
int num_peers = (len - 24) / 6;
if ((len - 24) % 6 != 0)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "invalid tracker response");
return true;
}
if (!has_requester()) return true;
std::vector<peer_entry> peer_list;
for (int i = 0; i < num_peers; ++i)
{
peer_entry e;
std::stringstream s;
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf);
e.ip = s.str();
e.port = detail::read_uint16(buf);
e.id.clear();
peer_list.push_back(e);
}
requester().tracker_response(m_request, peer_list, interval
, complete, incomplete);
return true;
}
bool udp_tracker_connection::parse_connect_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
const char* ptr = buf;
int action = detail::read_int32(ptr);
int transaction = detail::read_int32(ptr);
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(ptr, buf + len));
return true;
}
if (action != connect) return false;
if (m_transaction_id != transaction)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with incorrect transaction id, ignoring");
#endif
return false;
}
if (len < 16)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a connection message size < 16, ignoring");
#endif
return false;
}
// reset transaction
m_transaction_id = 0;
m_attempts = 0;
m_connection_id = detail::read_int64(ptr);
send_udp_announce();
return false;
}
}
<commit_msg>fixed udp-tracker connection bug<commit_after>/*
Copyright (c) 2003, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <vector>
#include <iostream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include "zlib.h"
#include "libtorrent/tracker_manager.hpp"
#include "libtorrent/udp_tracker_connection.hpp"
#include "libtorrent/io.hpp"
namespace
{
enum
{
udp_connection_retries = 4,
udp_announce_retries = 15,
udp_connect_timeout = 15,
udp_announce_timeout = 10,
udp_buffer_size = 2048
};
}
using namespace boost::posix_time;
namespace libtorrent
{
udp_tracker_connection::udp_tracker_connection(
tracker_request const& req
, std::string const& hostname
, unsigned short port
, boost::weak_ptr<request_callback> c
, const http_settings& stn)
: tracker_connection(c)
, m_request_time(second_clock::universal_time())
, m_request(req)
, m_transaction_id(0)
, m_connection_id(0)
, m_settings(stn)
, m_attempts(0)
{
// only announce is suppoerted at this time
assert(req.kind == tracker_request::announce_request);
// TODO: this is a problem. DNS-lookup is blocking!
// (may block up to 5 seconds)
address a(hostname.c_str(), port);
if (has_requester()) requester().m_tracker_address = a;
m_socket.reset(new socket(socket::udp, false));
m_socket->connect(a);
send_udp_connect();
}
bool udp_tracker_connection::send_finished() const
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
return (m_transaction_id != 0
&& m_connection_id != 0)
|| d > seconds(m_settings.tracker_timeout);
}
bool udp_tracker_connection::tick()
{
using namespace boost::posix_time;
time_duration d = second_clock::universal_time() - m_request_time;
if (m_connection_id == 0
&& d > seconds(udp_connect_timeout))
{
if (m_attempts >= udp_connection_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
send_udp_connect();
return false;
}
if (m_connection_id != 0
&& d > seconds(udp_announce_timeout))
{
if (m_attempts >= udp_announce_retries)
{
if (has_requester())
requester().tracker_request_timed_out(m_request);
return true;
}
send_udp_announce();
return false;
}
char buf[udp_buffer_size];
int ret = m_socket->receive(buf, udp_buffer_size);
// if there was nothing to receive, return
if (ret == 0) return false;
if (ret < 0)
{
socket::error_code err = m_socket->last_error();
if (err == socket::would_block) return false;
throw network_error(m_socket->last_error());
}
if (ret == udp_buffer_size)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "tracker reply too big");
return true;
}
if (m_connection_id == 0)
{
return parse_connect_response(buf, ret);
}
else
{
return parse_announce_response(buf, ret);
}
}
void udp_tracker_connection::send_udp_announce()
{
if (m_transaction_id == 0)
m_transaction_id = rand() | (rand() << 16);
std::vector<char> buf;
std::back_insert_iterator<std::vector<char> > out(buf);
// connection_id
detail::write_int64(m_connection_id, out);
// action (announce)
detail::write_int32(announce, out);
// transaction_id
detail::write_int32(m_transaction_id, out);
// info_hash
std::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);
// peer_id
std::copy(m_request.id.begin(), m_request.id.end(), out);
// downloaded
detail::write_int64(m_request.downloaded, out);
// left
detail::write_int64(m_request.left, out);
// uploaded
detail::write_int64(m_request.uploaded, out);
// event
detail::write_int32(m_request.event, out);
// ip address
detail::write_int32(0, out);
// key
detail::write_int32(m_request.key, out);
// num_want
detail::write_int32(m_request.num_want, out);
// port
detail::write_uint16(m_request.listen_port, out);
m_socket->send(&buf[0], buf.size());
m_request_time = second_clock::universal_time();
++m_attempts;
}
void udp_tracker_connection::send_udp_connect()
{
char send_buf[16];
char* ptr = send_buf;
if (m_transaction_id == 0)
m_transaction_id = rand() | (rand() << 16);
// connection_id
detail::write_int64(0, ptr);
// action (connect)
detail::write_int32(connect, ptr);
// transaction_id
detail::write_int32(m_transaction_id, ptr);
m_socket->send(send_buf, 16);
m_request_time = second_clock::universal_time();
++m_attempts;
}
bool udp_tracker_connection::parse_announce_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
int action = detail::read_int32(buf);
int transaction = detail::read_int32(buf);
if (transaction != m_transaction_id)
{
return false;
}
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(buf, buf + len - 8));
return true;
}
if (action != announce) return false;
if (len < 24)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 24, ignoring");
#endif
return false;
}
int interval = detail::read_int32(buf);
int incomplete = detail::read_int32(buf);
int complete = detail::read_int32(buf);
int num_peers = (len - 20) / 6;
if ((len - 20) % 6 != 0)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, "invalid tracker response");
return true;
}
if (!has_requester()) return true;
std::vector<peer_entry> peer_list;
for (int i = 0; i < num_peers; ++i)
{
peer_entry e;
std::stringstream s;
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf) << ".";
s << (int)detail::read_uint8(buf);
e.ip = s.str();
e.port = detail::read_uint16(buf);
e.id.clear();
peer_list.push_back(e);
}
requester().tracker_response(m_request, peer_list, interval
, complete, incomplete);
return true;
}
bool udp_tracker_connection::parse_connect_response(const char* buf, int len)
{
assert(buf != 0);
assert(len > 0);
if (len < 8)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with size < 8, ignoring");
#endif
return false;
}
const char* ptr = buf;
int action = detail::read_int32(ptr);
int transaction = detail::read_int32(ptr);
if (action == error)
{
if (has_requester())
requester().tracker_request_error(
m_request, -1, std::string(ptr, buf + len));
return true;
}
if (action != connect) return false;
if (m_transaction_id != transaction)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a message with incorrect transaction id, ignoring");
#endif
return false;
}
if (len < 16)
{
#ifdef TORRENT_VERBOSE_LOGGING
if (has_requester())
requester().debug_log("udp_tracker_connection: "
"got a connection message size < 16, ignoring");
#endif
return false;
}
// reset transaction
m_transaction_id = 0;
m_attempts = 0;
m_connection_id = detail::read_int64(ptr);
send_udp_announce();
return false;
}
}
<|endoftext|>
|
<commit_before>//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <ossim/util/ossimSubImageTool.h>
#include <ossim/base/ossimConstants.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/projection/ossimRpcSolver.h>
#include <ossim/base/ossimXmlDocument.h>
#include <iostream>
using namespace std;
const char* ossimSubImageTool::DESCRIPTION = "Tool for extracting a sub-image from a full image."
" No reprojection is done. Presently, the subimage geometry is represented by an RPC "
"replacement model until generic models can support subimage chipping.";
const char* BBOX_KW = "bbox";
ossimSubImageTool::ossimSubImageTool()
: m_geomFormat (OGEOM)
{
}
ossimSubImageTool::~ossimSubImageTool()
{
}
void ossimSubImageTool::setUsage(ossimArgumentParser& ap)
{
// Add options.
ossimApplicationUsage* au = ap.getApplicationUsage();
ossimString usageString = ap.getApplicationName();
usageString += " subimage [options] <input-image> <output-image>";
au->setCommandLineUsage(usageString);
// Set the command line options:
au->setDescription(DESCRIPTION);
// Base class has its own. Skip the ossimChipProcTool usage as that adds a lot of view-space
// specific stuff not used in this tool:
ossimTool::setUsage(ap);
au->addCommandLineOption(
"--bbox <ulx> <uly> <lrx> <lry>",
"Specify upper-left and lower-right bounds the image rect (in pixels).");
au->addCommandLineOption(
"-e | --entry <N> ",
"For multi image entries which entry do you wish to extract. For list "
"of entries use: \"ossim-info -i <your_image>\" ");
au->addCommandLineOption(
"--geom <format>", "Specifies format of the subimage RPC geometry file."
" Possible values are: \"OGEOM\" (OSSIM geometry, default), \"DG\" (DigitalGlobe WV/QB "
".RPB format), \"JSON\" (MSP-style JSON), or \"XML\". Case insensitive.");
}
bool ossimSubImageTool::initialize(ossimArgumentParser& ap)
{
if (!ossimTool::initialize(ap))
return false;
if (m_helpRequested)
return true;
string tempString1;
ossimArgumentParser::ossimParameter stringParam1(tempString1);
string tempString2;
ossimArgumentParser::ossimParameter stringParam2(tempString2);
string tempString3;
ossimArgumentParser::ossimParameter stringParam3(tempString3);
string tempString4;
ossimArgumentParser::ossimParameter stringParam4(tempString4);
double tempDouble1;
ossimArgumentParser::ossimParameter doubleParam1(tempDouble1);
double tempDouble2;
ossimArgumentParser::ossimParameter doubleParam2(tempDouble2);
vector<ossimString> paramList;
ossim_uint32 readerPropIdx = 0;
ossim_uint32 writerPropIdx = 0;
ostringstream keys;
if ( ap.read("--bbox", stringParam1, stringParam2, stringParam3, stringParam4))
{
ostringstream ostr;
ostr<<tempString1<<" "<<tempString2<<" "<<tempString3<<" "<<tempString4<<ends;
m_kwl.addPair( string(BBOX_KW), ostr.str() );
}
if ( ap.read("-e", stringParam1) || ap.read("--entry", stringParam1) )
m_kwl.addPair( string(ossimKeywordNames::ENTRY_KW), tempString1 );
if ( ap.read("--geom", stringParam1))
{
ossimString formatStr (tempString1);
formatStr.upcase();
if (formatStr == "OGEOM")
m_geomFormat = OGEOM;
else if (formatStr == "DG")
m_geomFormat = DG;
else if (formatStr == "JSON")
m_geomFormat = JSON;
else if (formatStr == "XML")
m_geomFormat = XML;
else
{
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Unknown geometry format <"
<<formatStr<<"> specified. Aborting." << endl;
throw ossimException( errMsg.str() );
}
}
processRemainingArgs(ap);
return true;
}
void ossimSubImageTool::initialize(const ossimKeywordlist& kwl)
{
m_productFilename = m_kwl.find(ossimKeywordNames::OUTPUT_FILE_KW);
// Init chain with handler:
ostringstream key;
key<<ossimKeywordNames::IMAGE_FILE_KW<<"0";
ossimFilename fname = m_kwl.findKey(key.str());
ossimRefPtr<ossimImageHandler> handler =
ossimImageHandlerRegistry::instance()->open(fname, true, false);
if (!handler)
{
ostringstream errMsg;
errMsg<<"ERROR: ossimSubImageTool ["<<__LINE__<<"] Could not open <"<<fname<<">"<<ends;
throw ossimException(errMsg.str());
}
// Look for the entry keyand set it:
ossim_uint32 entryIndex = 0;
ossimString os = m_kwl.find(ossimKeywordNames::ENTRY_KW);
if (os)
entryIndex = os.toUInt32();
if (!handler->setCurrentEntry( entryIndex ))
{
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Entry " << entryIndex << " out of range!" << endl;
throw ossimException( errMsg.str() );
}
m_procChain->add(handler.get());
// And finally the bounding rect:
ossimString lookup = m_kwl.find(BBOX_KW);
lookup.trim();
vector<ossimString> substrings = lookup.split(", ", true);
if (substrings.size() != 4)
{
ostringstream errMsg;
errMsg << "ossimSubImageTool ["<<__LINE__<<"] Incorrect number of values specified for bbox!";
throw( ossimException(errMsg.str()) );
}
int ulx = substrings[0].toInt32();
int uly = substrings[1].toInt32();
int lrx = substrings[2].toInt32();
int lry = substrings[3].toInt32();
// Check for swap:
if ( ulx > lrx )
{
int tmpF = ulx;
ulx = lrx;
lrx = tmpF;
}
if ( uly > lry )
{
int tmpF = uly;
uly = lry;
lry = tmpF;
}
// Use of view rect here is same as image space since there is no renderer:
m_aoiViewRect.set_ul(ossimIpt(ulx, uly));
m_aoiViewRect.set_lr(ossimIpt(lrx, lry));
m_needCutRect = true;
finalizeChain();
}
bool ossimSubImageTool::execute()
{
// Compute RPC representation of subimage:
ossimRefPtr<ossimImageGeometry> inputGeom = m_procChain->getImageGeometry();
if (!inputGeom || !inputGeom->getProjection())
{
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Null projection returned for input "
"image!" << endl;
throw ossimException( errMsg.str() );
}
ossimRefPtr<ossimProjection> inputProj = inputGeom->getProjection();
ossimRefPtr<ossimRpcModel> rpc;
ossimRefPtr<ossimRpcSolver> solver = new ossimRpcSolver(false);
bool converged = false;
// If the input projection itself is an RPC, just copy it. No solving required:
ossimRpcModel* inputRpc = dynamic_cast<ossimRpcModel*>(inputGeom->getProjection());
if (inputRpc)
rpc = inputRpc;
else
{
converged = solver->solve(m_aoiViewRect, inputGeom.get());
rpc = solver->getRpcModel();
}
// The RPC needs to be shifted in image space so that it will work in the subimage coordinates:
rpc->setImageOffset(m_aoiViewRect.ul());
m_geom = new ossimImageGeometry(nullptr, rpc.get());
m_geom->setImageSize(m_aoiViewRect.size());
ossimKeywordlist kwl;
m_geom->saveState(kwl);
bool success = ossimChipProcTool::execute();
if (!success)
return false;
// Need to save the subimage RPC data:
bool write_ok = false;
ossimFilename geomFile (m_productFilename);
if (m_geomFormat == OGEOM) // Default case if none specified
{
geomFile.setExtension("geom");
write_ok = kwl.write(geomFile);
}
else if (m_geomFormat == JSON)
{
#if OSSIM_HAS_JSONCPP
geomFile.setExtension("json");
ofstream jsonStream (geomFile.string());
if (!jsonStream.fail())
{
// Note that only the model/projection is saved here, not the full ossimImageGeometry that
// contains the subimage shift transform. So need to cheat and add the shift to the RPC
// line and sample offsets:
write_ok = rpc->toJSON(jsonStream);
jsonStream.close();
}
#else
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] JSON geometry output requested but JSON is not "
"available in this build! <" << endl;
throw ossimException( errMsg.str() );
#endif
}
else if (m_geomFormat == DG)
{
geomFile.setExtension("RPB");
ofstream rpbStream (geomFile.string());
if (!rpbStream.fail())
{
write_ok = rpc->toRPB(rpbStream);
rpbStream.close();
}
}
else if (m_geomFormat == XML)
{
geomFile.setExtension("xml");
ossimXmlDocument xmlDocument;
xmlDocument.fromKwl(kwl);
write_ok = xmlDocument.write(geomFile);
}
if (write_ok)
ossimNotify(ossimNotifyLevel_INFO) << "Wrote geometry file to <"<<geomFile<<">.\n" << endl;
else
{
ossimNotify(ossimNotifyLevel_FATAL) << "Error encountered writing output RPC geometry file."
<< std::endl;
return false;
}
return true;
}
<commit_msg>Shortenned description<commit_after>//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <ossim/util/ossimSubImageTool.h>
#include <ossim/base/ossimConstants.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimNotify.h>
#include <ossim/base/ossimException.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimKeywordNames.h>
#include <ossim/imaging/ossimImageHandlerRegistry.h>
#include <ossim/imaging/ossimImageGeometry.h>
#include <ossim/projection/ossimRpcSolver.h>
#include <ossim/base/ossimXmlDocument.h>
#include <iostream>
using namespace std;
const char* ossimSubImageTool::DESCRIPTION = "Tool for extracting a sub-image from a full image.";
const char* BBOX_KW = "bbox";
ossimSubImageTool::ossimSubImageTool()
: m_geomFormat (OGEOM)
{
}
ossimSubImageTool::~ossimSubImageTool()
{
}
void ossimSubImageTool::setUsage(ossimArgumentParser& ap)
{
// Add options.
ossimApplicationUsage* au = ap.getApplicationUsage();
ossimString usageString = ap.getApplicationName();
usageString += " subimage [options] <input-image> <output-image>";
au->setCommandLineUsage(usageString);
ostringstream descr;
descr << DESCRIPTION << "\n\n"
<< " No reprojection is done. Presently, the subimage geometry is represented by an RPC "
<< "replacement model until generic models can support subimage chipping.";
au->setDescription(descr.str());
// Set the command line options:
// Base class has its own. Skip the ossimChipProcTool usage as that adds a lot of view-space
// specific stuff not used in this tool:
ossimTool::setUsage(ap);
au->addCommandLineOption(
"--bbox <ulx> <uly> <lrx> <lry>",
"Specify upper-left and lower-right bounds the image rect (in pixels).");
au->addCommandLineOption(
"-e | --entry <N> ",
"For multi image entries which entry do you wish to extract. For list "
"of entries use: \"ossim-info -i <your_image>\" ");
au->addCommandLineOption(
"--geom <format>", "Specifies format of the subimage RPC geometry file."
" Possible values are: \"OGEOM\" (OSSIM geometry, default), \"DG\" (DigitalGlobe WV/QB "
".RPB format), \"JSON\" (MSP-style JSON), or \"XML\". Case insensitive.");
}
bool ossimSubImageTool::initialize(ossimArgumentParser& ap)
{
if (!ossimTool::initialize(ap))
return false;
if (m_helpRequested)
return true;
string tempString1;
ossimArgumentParser::ossimParameter stringParam1(tempString1);
string tempString2;
ossimArgumentParser::ossimParameter stringParam2(tempString2);
string tempString3;
ossimArgumentParser::ossimParameter stringParam3(tempString3);
string tempString4;
ossimArgumentParser::ossimParameter stringParam4(tempString4);
double tempDouble1;
ossimArgumentParser::ossimParameter doubleParam1(tempDouble1);
double tempDouble2;
ossimArgumentParser::ossimParameter doubleParam2(tempDouble2);
vector<ossimString> paramList;
ossim_uint32 readerPropIdx = 0;
ossim_uint32 writerPropIdx = 0;
ostringstream keys;
if ( ap.read("--bbox", stringParam1, stringParam2, stringParam3, stringParam4))
{
ostringstream ostr;
ostr<<tempString1<<" "<<tempString2<<" "<<tempString3<<" "<<tempString4<<ends;
m_kwl.addPair( string(BBOX_KW), ostr.str() );
}
if ( ap.read("-e", stringParam1) || ap.read("--entry", stringParam1) )
m_kwl.addPair( string(ossimKeywordNames::ENTRY_KW), tempString1 );
if ( ap.read("--geom", stringParam1))
{
ossimString formatStr (tempString1);
formatStr.upcase();
if (formatStr == "OGEOM")
m_geomFormat = OGEOM;
else if (formatStr == "DG")
m_geomFormat = DG;
else if (formatStr == "JSON")
m_geomFormat = JSON;
else if (formatStr == "XML")
m_geomFormat = XML;
else
{
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Unknown geometry format <"
<<formatStr<<"> specified. Aborting." << endl;
throw ossimException( errMsg.str() );
}
}
processRemainingArgs(ap);
return true;
}
void ossimSubImageTool::initialize(const ossimKeywordlist& kwl)
{
m_productFilename = m_kwl.find(ossimKeywordNames::OUTPUT_FILE_KW);
// Init chain with handler:
ostringstream key;
key<<ossimKeywordNames::IMAGE_FILE_KW<<"0";
ossimFilename fname = m_kwl.findKey(key.str());
ossimRefPtr<ossimImageHandler> handler =
ossimImageHandlerRegistry::instance()->open(fname, true, false);
if (!handler)
{
ostringstream errMsg;
errMsg<<"ERROR: ossimSubImageTool ["<<__LINE__<<"] Could not open <"<<fname<<">"<<ends;
throw ossimException(errMsg.str());
}
// Look for the entry keyand set it:
ossim_uint32 entryIndex = 0;
ossimString os = m_kwl.find(ossimKeywordNames::ENTRY_KW);
if (os)
entryIndex = os.toUInt32();
if (!handler->setCurrentEntry( entryIndex ))
{
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Entry " << entryIndex << " out of range!" << endl;
throw ossimException( errMsg.str() );
}
m_procChain->add(handler.get());
// And finally the bounding rect:
ossimString lookup = m_kwl.find(BBOX_KW);
lookup.trim();
vector<ossimString> substrings = lookup.split(", ", true);
if (substrings.size() != 4)
{
ostringstream errMsg;
errMsg << "ossimSubImageTool ["<<__LINE__<<"] Incorrect number of values specified for bbox!";
throw( ossimException(errMsg.str()) );
}
int ulx = substrings[0].toInt32();
int uly = substrings[1].toInt32();
int lrx = substrings[2].toInt32();
int lry = substrings[3].toInt32();
// Check for swap:
if ( ulx > lrx )
{
int tmpF = ulx;
ulx = lrx;
lrx = tmpF;
}
if ( uly > lry )
{
int tmpF = uly;
uly = lry;
lry = tmpF;
}
// Use of view rect here is same as image space since there is no renderer:
m_aoiViewRect.set_ul(ossimIpt(ulx, uly));
m_aoiViewRect.set_lr(ossimIpt(lrx, lry));
m_needCutRect = true;
finalizeChain();
}
bool ossimSubImageTool::execute()
{
// Compute RPC representation of subimage:
ossimRefPtr<ossimImageGeometry> inputGeom = m_procChain->getImageGeometry();
if (!inputGeom || !inputGeom->getProjection())
{
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] Null projection returned for input "
"image!" << endl;
throw ossimException( errMsg.str() );
}
ossimRefPtr<ossimProjection> inputProj = inputGeom->getProjection();
ossimRefPtr<ossimRpcModel> rpc;
ossimRefPtr<ossimRpcSolver> solver = new ossimRpcSolver(false);
bool converged = false;
// If the input projection itself is an RPC, just copy it. No solving required:
ossimRpcModel* inputRpc = dynamic_cast<ossimRpcModel*>(inputGeom->getProjection());
if (inputRpc)
rpc = inputRpc;
else
{
converged = solver->solve(m_aoiViewRect, inputGeom.get());
rpc = solver->getRpcModel();
}
// The RPC needs to be shifted in image space so that it will work in the subimage coordinates:
rpc->setImageOffset(m_aoiViewRect.ul());
m_geom = new ossimImageGeometry(nullptr, rpc.get());
m_geom->setImageSize(m_aoiViewRect.size());
ossimKeywordlist kwl;
m_geom->saveState(kwl);
bool success = ossimChipProcTool::execute();
if (!success)
return false;
// Need to save the subimage RPC data:
bool write_ok = false;
ossimFilename geomFile (m_productFilename);
if (m_geomFormat == OGEOM) // Default case if none specified
{
geomFile.setExtension("geom");
write_ok = kwl.write(geomFile);
}
else if (m_geomFormat == JSON)
{
#if OSSIM_HAS_JSONCPP
geomFile.setExtension("json");
ofstream jsonStream (geomFile.string());
if (!jsonStream.fail())
{
// Note that only the model/projection is saved here, not the full ossimImageGeometry that
// contains the subimage shift transform. So need to cheat and add the shift to the RPC
// line and sample offsets:
write_ok = rpc->toJSON(jsonStream);
jsonStream.close();
}
#else
ostringstream errMsg;
errMsg << " ERROR: ossimSubImageTool ["<<__LINE__<<"] JSON geometry output requested but JSON is not "
"available in this build! <" << endl;
throw ossimException( errMsg.str() );
#endif
}
else if (m_geomFormat == DG)
{
geomFile.setExtension("RPB");
ofstream rpbStream (geomFile.string());
if (!rpbStream.fail())
{
write_ok = rpc->toRPB(rpbStream);
rpbStream.close();
}
}
else if (m_geomFormat == XML)
{
geomFile.setExtension("xml");
ossimXmlDocument xmlDocument;
xmlDocument.fromKwl(kwl);
write_ok = xmlDocument.write(geomFile);
}
if (write_ok)
ossimNotify(ossimNotifyLevel_INFO) << "Wrote geometry file to <"<<geomFile<<">.\n" << endl;
else
{
ossimNotify(ossimNotifyLevel_FATAL) << "Error encountered writing output RPC geometry file."
<< std::endl;
return false;
}
return true;
}
<|endoftext|>
|
<commit_before>#include "gunsystem.hpp"
#include "../component/transformcomponent.hpp"
#include "../component/guncomponent.hpp"
#include "../component/lifecomponent.hpp"
#include "../component/physicscomponent.hpp"
#include "../component/modelcomponent.hpp"
#include "../component/rigidbodycomponent.hpp"
#include "../system/bulletphysicssystem.hpp"
#include "../entity.hpp"
#include "../src/gl/mesh.hpp"
#include "../src/engine.hpp"
GunSystem::~GunSystem() {}
void GunSystem::update(World& world, float delta) {
std::vector<Entity*> toAdd;
for (std::unique_ptr<Entity>& entity : world.getEntities()) {
auto currGunComp = entity->getComponent<GunComponent>();
if (!currGunComp)
continue;
if (currGunComp->shoot) {
toAdd.push_back(entity.get());
currGunComp->shoot = false;
currGunComp->cooldown = currGunComp->cooldownLength;
}
if(currGunComp->cooldown > 0)
currGunComp->cooldown -= 1 * delta;
}
for (Entity* entity : toAdd) {
fireProjectile(entity, world.addEntity(sole::uuid4(), "Projectile"));
}
}
void GunSystem::fireProjectile(Entity* me, Entity* projectile) {
auto currTransform = me->getComponent<TransformComponent>();
auto projTransComp = projectile->addComponent<TransformComponent>();
projTransComp->setPosition(currTransform->getPosition());
projTransComp->setRotation(currTransform->getRotation());
projTransComp->setScale(glm::vec3(0.2f));
auto projPhysComp = projectile->addComponent<PhysicsComponent>();
projPhysComp->acceleration = glm::vec3(0,0,1);
projPhysComp->velocity = projPhysComp->acceleration * glm::vec3(2);
auto projLifeComp = projectile->addComponent<LifeComponent>();
projLifeComp->currHP = projLifeComp->maxHP = 2;
auto modelComp = projectile->addComponent<ModelComponent>();
modelComp->meshData = Engine::getInstance().getMeshLoader()->getMesh("assets/objects/player.fbx");
modelComp->meshData->mesh
->addBuffer("m",
[](GLuint id) {
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4), NULL, GL_DYNAMIC_DRAW);
for (int i = 0; i < 4; i++) {
glEnableVertexAttribArray(ShaderAttributeID::m + i);
glVertexAttribPointer(ShaderAttributeID::m + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(sizeof(glm::vec4) * i));
glVertexAttribDivisor(ShaderAttributeID::m + i, 1);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
})
.finalize();
auto rigidbody = projectile->addComponent<RigidBodyComponent>();
rigidbody->setHitboxHalfSize(projTransComp->getScale());
rigidbody->setMass(1);
Engine::getInstance().getSystem<BulletPhyisicsSystem>()->addRigidBody(rigidbody);
}
//bool GunSystem::fireRay(std::unique_ptr<Entity>& target, HitboxComponent::HitboxType inType) {
// bool hit = false;
// switch (inType)
// {
// case HitboxComponent::SPHERE: {
// float t0, t1;
// std::shared_ptr<HitboxComponent::HitboxSphere> hitbox = std::static_pointer_cast<HitboxComponent::HitboxSphere>(target->getComponent<HitboxComponent>()->hitbox);
// std::shared_ptr<GunComponent::RayGun> raygun = std::static_pointer_cast<GunComponent::RayGun>(gun);
// glm::vec3 L = hitbox->center - raygun->ray.o;
// float tca = glm::dot(L, raygun->ray.dir);
// if (tca < 0)
// return false;
// float d2 = glm::dot(L, L) - tca * tca;
// if (d2 > hitbox->radius2)
// return false;
// float thc = sqrt(hitbox->radius2 - d2);
// t0 = tca - thc;
// t1 = tca + thc;
// if (t0 > t1)
// std::swap(t0, t1);
//
// if (t0 < 0) {
// t0 = t1;
// if (t0 < 0)
// return false;
// }
//
// raygun->ray.t[0] = raygun->ray.o + t0 * raygun->ray.dir;
// raygun->ray.t[1] = raygun->ray.o + t1 * raygun->ray.dir;
// gun = raygun;
// printf("Entry: %f %f %f\n, Exit: %f %f %f\n\n", raygun->ray.t[0].x, raygun->ray.t[0].y, raygun->ray.t[0].z,
// raygun->ray.t[1].x, raygun->ray.t[1].y, raygun->ray.t[1].z);
// hit = true;
// break;
// }
// case HitboxComponent::TETRAHEDRON: {
//
// break;
// }
// case HitboxComponent::AABB: {
//
// break;
// }
// default:
// break;
// }
// return hit;
//}
void GunSystem::registerImGui() {
}<commit_msg>Fixed some things<commit_after>#include "gunsystem.hpp"
#include "../component/transformcomponent.hpp"
#include "../component/guncomponent.hpp"
#include "../component/lifecomponent.hpp"
#include "../component/physicscomponent.hpp"
#include "../component/modelcomponent.hpp"
#include "../component/rigidbodycomponent.hpp"
#include "../system/bulletphysicssystem.hpp"
#include "../entity.hpp"
#include "../src/gl/mesh.hpp"
#include "../src/engine.hpp"
GunSystem::~GunSystem() {}
void GunSystem::update(World& world, float delta) {
std::vector<Entity*> toAdd;
for (std::unique_ptr<Entity>& entity : world.getEntities()) {
auto currGunComp = entity->getComponent<GunComponent>();
if (!currGunComp)
continue;
if (currGunComp->shoot) {
toAdd.push_back(entity.get());
currGunComp->shoot = false;
currGunComp->cooldown = currGunComp->cooldownLength;
}
if(currGunComp->cooldown > 0)
currGunComp->cooldown -= 1 * delta;
}
for (Entity* entity : toAdd) {
fireProjectile(entity, world.addEntity(sole::uuid4(), "Projectile"));
}
}
void GunSystem::fireProjectile(Entity* me, Entity* projectile) {
auto transComp = me->getComponent<TransformComponent>();
auto transProj = projectile->addComponent<TransformComponent>();
transProj->setPosition(transComp->getPosition());
transProj->setRotation(transComp->getRotation());
transProj->setScale(transComp->getScale() * 0.5f);
transProj->setDirection(glm::vec3(0,0,1)); // should be transComp->getDirection() instead of 0,0,1 but the direction is weird.
auto currRdbComp = me->getComponent<RigidBodyComponent>();
auto projRdbComp = projectile->addComponent<RigidBodyComponent>();
auto projMs = projRdbComp->getMotionState();
btTransform projRdbTrans = currRdbComp->getRigidBody()->getWorldTransform();
printf("x: %f, y: %f, z: %f\n", cast(projRdbTrans.getOrigin()).x, cast(projRdbTrans.getOrigin()).y, cast(projRdbTrans.getOrigin()).z);
projRdbComp->setHitboxHalfSize(currRdbComp->getHitboxHalfSize() * 0.5f);
projRdbComp->setMass(1);
projRdbComp->setFriction(0);
projRdbComp->getRigidBody()->applyCentralImpulse(cast(transProj->getDirection() * 5.0f));
projRdbComp->getRigidBody()->setWorldTransform(projRdbTrans);
//projMs->setWorldTransform(projRdbTrans);
//rdbComp->getRigidBody()->applyCentralImpulse(cast(glm::vec3(4)));
auto projLifeComp = projectile->addComponent<LifeComponent>();
projLifeComp->currHP = projLifeComp->maxHP = 2;
auto modelComp = projectile->addComponent<ModelComponent>();
modelComp->meshData = Engine::getInstance().getMeshLoader()->getMesh("assets/objects/player.fbx");
modelComp->meshData->mesh
->addBuffer("m",
[](GLuint id) {
glBindBuffer(GL_ARRAY_BUFFER, id);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::mat4), NULL, GL_DYNAMIC_DRAW);
for (int i = 0; i < 4; i++) {
glEnableVertexAttribArray(ShaderAttributeID::m + i);
glVertexAttribPointer(ShaderAttributeID::m + i, 4, GL_FLOAT, GL_FALSE, sizeof(glm::mat4), (GLvoid*)(sizeof(glm::vec4) * i));
glVertexAttribDivisor(ShaderAttributeID::m + i, 1);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
})
.finalize();
Engine::getInstance().getSystem<BulletPhyisicsSystem>()->addRigidBody(projRdbComp);
}
//bool GunSystem::fireRay(std::unique_ptr<Entity>& target, HitboxComponent::HitboxType inType) {
// bool hit = false;
// switch (inType)
// {
// case HitboxComponent::SPHERE: {
// float t0, t1;
// std::shared_ptr<HitboxComponent::HitboxSphere> hitbox = std::static_pointer_cast<HitboxComponent::HitboxSphere>(target->getComponent<HitboxComponent>()->hitbox);
// std::shared_ptr<GunComponent::RayGun> raygun = std::static_pointer_cast<GunComponent::RayGun>(gun);
// glm::vec3 L = hitbox->center - raygun->ray.o;
// float tca = glm::dot(L, raygun->ray.dir);
// if (tca < 0)
// return false;
// float d2 = glm::dot(L, L) - tca * tca;
// if (d2 > hitbox->radius2)
// return false;
// float thc = sqrt(hitbox->radius2 - d2);
// t0 = tca - thc;
// t1 = tca + thc;
// if (t0 > t1)
// std::swap(t0, t1);
//
// if (t0 < 0) {
// t0 = t1;
// if (t0 < 0)
// return false;
// }
//
// raygun->ray.t[0] = raygun->ray.o + t0 * raygun->ray.dir;
// raygun->ray.t[1] = raygun->ray.o + t1 * raygun->ray.dir;
// gun = raygun;
// printf("Entry: %f %f %f\n, Exit: %f %f %f\n\n", raygun->ray.t[0].x, raygun->ray.t[0].y, raygun->ray.t[0].z,
// raygun->ray.t[1].x, raygun->ray.t[1].y, raygun->ray.t[1].z);
// hit = true;
// break;
// }
// case HitboxComponent::TETRAHEDRON: {
//
// break;
// }
// case HitboxComponent::AABB: {
//
// break;
// }
// default:
// break;
// }
// return hit;
//}
void GunSystem::registerImGui() {
}<|endoftext|>
|
<commit_before>// Copyright (c) 2015-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <streams.h>
#include <zmq/zmqpublishnotifier.h>
#include <validation.h>
#include <util/system.h>
#include <rpc/server.h>
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
// SYSCOIN
static const char *MSG_RAWMEMPOOLTX = "rawmempooltx";
static const char *MSG_HASHGVOTE = "hashgovernancevote";
static const char *MSG_HASHGOBJ = "hashgovernanceobject";
static const char *MSG_RAWGVOTE = "rawgovernancevote";
static const char *MSG_RAWGOBJ = "rawgovernanceobject";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
int rc = zmq_setsockopt(psocket, ZMQ_SNDHWM, &outbound_message_high_water_mark, sizeof(outbound_message_high_water_mark));
if (rc != 0)
{
zmqError("Failed to set outbound message high water mark");
zmq_close(psocket);
return false;
}
rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
// Early return if Initialize was not called
if (!psocket) return;
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "zmq: Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
// SYSCOIN
bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 hash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernancevote %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGVOTE, data, 32);
}
bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object)
{
uint256 hash = object.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernanceobject %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGOBJ, data, 32);
}
bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 nHash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vote;
return SendMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj)
{
uint256 nHash = govobj.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << govobj;
return SendMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawMempoolTransactionNotifier::NotifyTransactionMempool(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawmempooltx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWMEMPOOLTX, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawSyscoinNotifier::NotifySyscoinUpdate(const char * value, const char * topic)
{
LogPrint(BCLog::ZMQ, "zmq: Publish raw syscoin payload for topic %s: %s\n", topic, value);
return SendMessage(topic, value, strlen(value));
}<commit_msg>incl<commit_after>// Copyright (c) 2015-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <streams.h>
#include <zmq/zmqpublishnotifier.h>
#include <validation.h>
#include <util/system.h>
#include <rpc/server.h>
#include <governance/governance-vote.h>
#include <governance/governance-object.h>
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
// SYSCOIN
static const char *MSG_RAWMEMPOOLTX = "rawmempooltx";
static const char *MSG_HASHGVOTE = "hashgovernancevote";
static const char *MSG_HASHGOBJ = "hashgovernanceobject";
static const char *MSG_RAWGVOTE = "rawgovernancevote";
static const char *MSG_RAWGOBJ = "rawgovernanceobject";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
int rc = zmq_setsockopt(psocket, ZMQ_SNDHWM, &outbound_message_high_water_mark, sizeof(outbound_message_high_water_mark));
if (rc != 0)
{
zmqError("Failed to set outbound message high water mark");
zmq_close(psocket);
return false;
}
rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
LogPrint(BCLog::ZMQ, "zmq: Outbound message high water mark for %s at %s is %d\n", type, address, outbound_message_high_water_mark);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
// Early return if Initialize was not called
if (!psocket) return;
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "zmq: Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
// SYSCOIN
bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 hash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernancevote %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGVOTE, data, 32);
}
bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object)
{
uint256 hash = object.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashgovernanceobject %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGOBJ, data, 32);
}
bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 nHash = vote.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vote;
return SendMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj)
{
uint256 nHash = govobj.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << govobj;
return SendMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawMempoolTransactionNotifier::NotifyTransactionMempool(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawmempooltx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWMEMPOOLTX, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawSyscoinNotifier::NotifySyscoinUpdate(const char * value, const char * topic)
{
LogPrint(BCLog::ZMQ, "zmq: Publish raw syscoin payload for topic %s: %s\n", topic, value);
return SendMessage(topic, value, strlen(value));
}<|endoftext|>
|
<commit_before>// Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2015-2018 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zmqpublishnotifier.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
static std::multimap<std::string, CZMQAbstractPublishNotifier *> mapPublishNotifiers;
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void *data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void *);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier *>::iterator i = mapPublishNotifiers.find(address);
if (i == mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
int rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
zmqError("Failed to bind address");
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LOG(ZMQ, "zmq: Reusing socket for address %s\n", address);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
assert(psocket);
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier *>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second == this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LOG(ZMQ, "Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = 0;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LOG(ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
int rc = zmq_send_multipart(psocket, "hashblock", 9, data, 32, 0);
return rc == 0;
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransactionRef &ptx)
{
uint256 hash = ptx->GetHash();
LOG(ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
int rc = zmq_send_multipart(psocket, "hashtx", 6, data, 32, 0);
return rc == 0;
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LOG(ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params &consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
{
LOCK(cs_main);
CBlock block;
if (!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
int rc = zmq_send_multipart(psocket, "rawblock", 8, &(*ss.begin()), ss.size(), 0);
return rc == 0;
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransactionRef &ptx)
{
uint256 hash = ptx->GetHash();
LOG(ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *ptx;
int rc = zmq_send_multipart(psocket, "rawtx", 5, &(*ss.begin()), ss.size(), 0);
return rc == 0;
}
<commit_msg>[zmq] Call va_end() on va_start()ed args.<commit_after>// Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2015-2018 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "zmqpublishnotifier.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
static std::multimap<std::string, CZMQAbstractPublishNotifier *> mapPublishNotifiers;
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void *data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void *);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier *>::iterator i = mapPublishNotifiers.find(address);
if (i == mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
int rc = zmq_bind(psocket, address.c_str());
if (rc != 0)
{
zmqError("Failed to bind address");
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LOG(ZMQ, "zmq: Reusing socket for address %s\n", address);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
assert(psocket);
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier *>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second == this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LOG(ZMQ, "Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = 0;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LOG(ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
int rc = zmq_send_multipart(psocket, "hashblock", 9, data, 32, 0);
return rc == 0;
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransactionRef &ptx)
{
uint256 hash = ptx->GetHash();
LOG(ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
int rc = zmq_send_multipart(psocket, "hashtx", 6, data, 32, 0);
return rc == 0;
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LOG(ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params &consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
{
LOCK(cs_main);
CBlock block;
if (!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
int rc = zmq_send_multipart(psocket, "rawblock", 8, &(*ss.begin()), ss.size(), 0);
return rc == 0;
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransactionRef &ptx)
{
uint256 hash = ptx->GetHash();
LOG(ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << *ptx;
int rc = zmq_send_multipart(psocket, "rawtx", 5, &(*ss.begin()), ss.size(), 0);
return rc == 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2015-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <streams.h>
#include <zmq/zmqpublishnotifier.h>
#include <validation.h>
#include <util.h>
#include <rpc/server.h>
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_HASHGVOTE = "hashgovernancevote";
static const char *MSG_HASHGOBJ = "hashgovernanceobject";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
static const char *MSG_RAWGVOTE = "rawgovernancevote";
static const char *MSG_RAWGOBJ = "rawgovernanceobject";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
int rc = zmq_bind(psocket, address.c_str());
if (rc!=0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
assert(psocket);
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 hash = vote.GetHash();
LogPrint("zmq", "zmq: Publish hashgovernancevote %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGVOTE, data, 32);
}
bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object)
{
uint256 hash = object.GetHash();
LogPrint("zmq", "zmq: Publish hashgovernanceobject %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGOBJ, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 nHash = vote.GetHash();
LogPrint("gobject", "gobject: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vote;
return SendMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj)
{
uint256 nHash = govobj.GetHash();
LogPrint("gobject", "gobject: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << govobj;
return SendMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size());
}
<commit_msg>fix logging in ZMQ<commit_after>// Copyright (c) 2015-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <chain.h>
#include <chainparams.h>
#include <streams.h>
#include <zmq/zmqpublishnotifier.h>
#include <validation.h>
#include <util.h>
#include <rpc/server.h>
static std::multimap<std::string, CZMQAbstractPublishNotifier*> mapPublishNotifiers;
static const char *MSG_HASHBLOCK = "hashblock";
static const char *MSG_HASHTX = "hashtx";
static const char *MSG_HASHGVOTE = "hashgovernancevote";
static const char *MSG_HASHGOBJ = "hashgovernanceobject";
static const char *MSG_RAWBLOCK = "rawblock";
static const char *MSG_RAWTX = "rawtx";
static const char *MSG_RAWGVOTE = "rawgovernancevote";
static const char *MSG_RAWGOBJ = "rawgovernanceobject";
// Internal function to send multipart message
static int zmq_send_multipart(void *sock, const void* data, size_t size, ...)
{
va_list args;
va_start(args, size);
while (1)
{
zmq_msg_t msg;
int rc = zmq_msg_init_size(&msg, size);
if (rc != 0)
{
zmqError("Unable to initialize ZMQ msg");
va_end(args);
return -1;
}
void *buf = zmq_msg_data(&msg);
memcpy(buf, data, size);
data = va_arg(args, const void*);
rc = zmq_msg_send(&msg, sock, data ? ZMQ_SNDMORE : 0);
if (rc == -1)
{
zmqError("Unable to send ZMQ msg");
zmq_msg_close(&msg);
va_end(args);
return -1;
}
zmq_msg_close(&msg);
if (!data)
break;
size = va_arg(args, size_t);
}
va_end(args);
return 0;
}
bool CZMQAbstractPublishNotifier::Initialize(void *pcontext)
{
assert(!psocket);
// check if address is being used by other publish notifier
std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator i = mapPublishNotifiers.find(address);
if (i==mapPublishNotifiers.end())
{
psocket = zmq_socket(pcontext, ZMQ_PUB);
if (!psocket)
{
zmqError("Failed to create socket");
return false;
}
int rc = zmq_bind(psocket, address.c_str());
if (rc!=0)
{
zmqError("Failed to bind address");
zmq_close(psocket);
return false;
}
// register this notifier for the address, so it can be reused for other publish notifier
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
else
{
LogPrint(BCLog::ZMQ, "zmq: Reusing socket for address %s\n", address);
psocket = i->second->psocket;
mapPublishNotifiers.insert(std::make_pair(address, this));
return true;
}
}
void CZMQAbstractPublishNotifier::Shutdown()
{
assert(psocket);
int count = mapPublishNotifiers.count(address);
// remove this notifier from the list of publishers using this address
typedef std::multimap<std::string, CZMQAbstractPublishNotifier*>::iterator iterator;
std::pair<iterator, iterator> iterpair = mapPublishNotifiers.equal_range(address);
for (iterator it = iterpair.first; it != iterpair.second; ++it)
{
if (it->second==this)
{
mapPublishNotifiers.erase(it);
break;
}
}
if (count == 1)
{
LogPrint(BCLog::ZMQ, "Close socket at address %s\n", address);
int linger = 0;
zmq_setsockopt(psocket, ZMQ_LINGER, &linger, sizeof(linger));
zmq_close(psocket);
}
psocket = nullptr;
}
bool CZMQAbstractPublishNotifier::SendMessage(const char *command, const void* data, size_t size)
{
assert(psocket);
/* send three parts, command & data & a LE 4byte sequence number */
unsigned char msgseq[sizeof(uint32_t)];
WriteLE32(&msgseq[0], nSequence);
int rc = zmq_send_multipart(psocket, command, strlen(command), data, size, msgseq, (size_t)sizeof(uint32_t), nullptr);
if (rc == -1)
return false;
/* increment memory only sequence number after sending */
nSequence++;
return true;
}
bool CZMQPublishHashBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
uint256 hash = pindex->GetBlockHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashblock %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHBLOCK, data, 32);
}
bool CZMQPublishHashTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish hashtx %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHTX, data, 32);
}
bool CZMQPublishHashGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 hash = vote.GetHash();
LogPrint("zmq", "zmq: Publish hashgovernancevote %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGVOTE, data, 32);
}
bool CZMQPublishHashGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &object)
{
uint256 hash = object.GetHash();
LogPrint("zmq", "zmq: Publish hashgovernanceobject %s\n", hash.GetHex());
char data[32];
for (unsigned int i = 0; i < 32; i++)
data[31 - i] = hash.begin()[i];
return SendMessage(MSG_HASHGOBJ, data, 32);
}
bool CZMQPublishRawBlockNotifier::NotifyBlock(const CBlockIndex *pindex)
{
LogPrint(BCLog::ZMQ, "zmq: Publish rawblock %s\n", pindex->GetBlockHash().GetHex());
const Consensus::Params& consensusParams = Params().GetConsensus();
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
{
LOCK(cs_main);
CBlock block;
if(!ReadBlockFromDisk(block, pindex, consensusParams))
{
zmqError("Can't read block from disk");
return false;
}
ss << block;
}
return SendMessage(MSG_RAWBLOCK, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawTransactionNotifier::NotifyTransaction(const CTransaction &transaction)
{
uint256 hash = transaction.GetHash();
LogPrint(BCLog::ZMQ, "zmq: Publish rawtx %s\n", hash.GetHex());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
ss << transaction;
return SendMessage(MSG_RAWTX, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceVoteNotifier::NotifyGovernanceVote(const CGovernanceVote &vote)
{
uint256 nHash = vote.GetHash();
LogPrint(BCLog::GOV, "gobject: Publish rawgovernanceobject: hash = %s, vote = %d\n", nHash.ToString(), vote.ToString());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << vote;
return SendMessage(MSG_RAWGVOTE, &(*ss.begin()), ss.size());
}
bool CZMQPublishRawGovernanceObjectNotifier::NotifyGovernanceObject(const CGovernanceObject &govobj)
{
uint256 nHash = govobj.GetHash();
LogPrint(BCLog::GOV, "gobject: Publish rawgovernanceobject: hash = %s, type = %d\n", nHash.ToString(), govobj.GetObjectType());
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << govobj;
return SendMessage(MSG_RAWGOBJ, &(*ss.begin()), ss.size());
}
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho,
* Johns Hopkins University
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
namespace pcl {
namespace poisson {
//////////////////////
// Polynomial Roots //
//////////////////////
#include <math.h>
#include "pcl/surface/poisson/factor.h"
int Factor(double a1,double a0,double roots[1][2],const double& EPS){
if(fabs(a1)<=EPS){return 0;}
roots[0][0]=-a0/a1;
roots[0][1]=0;
return 1;
}
int Factor(double a2,double a1,double a0,double roots[2][2],const double& EPS){
double d;
if(fabs(a2)<=EPS){return Factor(a1,a0,roots,EPS);}
d=a1*a1-4*a0*a2;
a1/=(2*a2);
if(d<0){
d=sqrt(-d)/(2*a2);
roots[0][0]=roots[1][0]=-a1;
roots[0][1]=-d;
roots[1][1]= d;
}
else{
d=sqrt(d)/(2*a2);
roots[0][1]=roots[1][1]=0;
roots[0][0]=-a1-d;
roots[1][0]=-a1+d;
}
return 2;
}
// Solution taken from: http://mathworld.wolfram.com/CubicFormula.html
// and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90
int Factor(double a3,double a2,double a1,double a0,double roots[3][2],const double& EPS){
double q,r,r2,q3;
if(fabs(a3)<=EPS){return Factor(a2,a1,a0,roots,EPS);}
a2/=a3;
a1/=a3;
a0/=a3;
q=-(3*a1-a2*a2)/9;
r=-(9*a2*a1-27*a0-2*a2*a2*a2)/54;
r2=r*r;
q3=q*q*q;
if(r2<q3){
double sqrQ=sqrt(q);
double theta = acos ( r / (sqrQ*q) );
double cTheta=cos(theta/3)*sqrQ;
double sTheta=sin(theta/3)*sqrQ*SQRT_3/2;
roots[0][1]=roots[1][1]=roots[2][1]=0;
roots[0][0]=-2*cTheta;
roots[1][0]=-2*(-cTheta*0.5-sTheta);
roots[2][0]=-2*(-cTheta*0.5+sTheta);
}
else{
double s1,s2,sqr=sqrt(r2-q3);
double t;
t=-r+sqr;
if(t<0){s1=-pow(-t,1.0/3);}
else{s1=pow(t,1.0/3);}
t=-r-sqr;
if(t<0){s2=-pow(-t,1.0/3);}
else{s2=pow(t,1.0/3);}
roots[0][1]=0;
roots[0][0]=s1+s2;
s1/=2;
s2/=2;
roots[1][0]= roots[2][0]=-s1-s2;
roots[1][1]= SQRT_3*(s1-s2);
roots[2][1]=-roots[1][1];
}
roots[0][0]-=a2/3;
roots[1][0]-=a2/3;
roots[2][0]-=a2/3;
return 3;
}
double ArcTan2(const double& y,const double& x){
/* This first case should never happen */
if(y==0 && x==0){return 0;}
if(x==0){
if(y>0){return PI/2.0;}
else{return -PI/2.0;}
}
if(x>=0){return atan(y/x);}
else{
if(y>=0){return atan(y/x)+PI;}
else{return atan(y/x)-PI;}
}
}
double Angle(const double in[2]){
if((in[0]*in[0]+in[1]*in[1])==0.0){return 0;}
else{return ArcTan2(in[1],in[0]);}
}
void Sqrt(const double in[2],double out[2]){
double r=sqrt(sqrt(in[0]*in[0]+in[1]*in[1]));
double a=Angle(in)*0.5;
out[0]=r*cos(a);
out[1]=r*sin(a);
}
void Add(const double in1[2],const double in2[2],double out[2]){
out[0]=in1[0]+in2[0];
out[1]=in1[1]+in2[1];
}
void Subtract(const double in1[2],const double in2[2],double out[2]){
out[0]=in1[0]-in2[0];
out[1]=in1[1]-in2[1];
}
void Multiply(const double in1[2],const double in2[2],double out[2]){
out[0]=in1[0]*in2[0]-in1[1]*in2[1];
out[1]=in1[0]*in2[1]+in1[1]*in2[0];
}
void Divide(const double in1[2],const double in2[2],double out[2]){
double temp[2];
double l=in2[0]*in2[0]+in2[1]*in2[1];
temp[0]= in2[0]/l;
temp[1]=-in2[1]/l;
Multiply(in1,temp,out);
}
// Solution taken from: http://mathworld.wolfram.com/QuarticEquation.html
// and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90
int Factor(double a4,double a3,double a2,double a1,double a0,double roots[4][2],const double& EPS){
double R[2],D[2],E[2],R2[2];
if(fabs(a4)<EPS){return Factor(a3,a2,a1,a0,roots,EPS);}
a3/=a4;
a2/=a4;
a1/=a4;
a0/=a4;
Factor(1.0,-a2,a3*a1-4.0*a0,-a3*a3*a0+4.0*a2*a0-a1*a1,roots,EPS);
R2[0]=a3*a3/4.0-a2+roots[0][0];
R2[1]=0;
Sqrt(R2,R);
if(fabs(R[0])>10e-8){
double temp1[2],temp2[2];
double p1[2],p2[2];
p1[0]=a3*a3*0.75-2.0*a2-R2[0];
p1[1]=0;
temp2[0]=((4.0*a3*a2-8.0*a1-a3*a3*a3)/4.0);
temp2[1]=0;
Divide(temp2,R,p2);
Add (p1,p2,temp1);
Subtract(p1,p2,temp2);
Sqrt(temp1,D);
Sqrt(temp2,E);
}
else{
R[0]=R[1]=0;
double temp1[2],temp2[2];
temp1[0]=roots[0][0]*roots[0][0]-4.0*a0;
temp1[1]=0;
Sqrt(temp1,temp2);
temp1[0]=a3*a3*0.75-2.0*a2+2.0*temp2[0];
temp1[1]= 2.0*temp2[1];
Sqrt(temp1,D);
temp1[0]=a3*a3*0.75-2.0*a2-2.0*temp2[0];
temp1[1]= -2.0*temp2[1];
Sqrt(temp1,E);
}
roots[0][0]=-a3/4.0+R[0]/2.0+D[0]/2.0;
roots[0][1]= R[1]/2.0+D[1]/2.0;
roots[1][0]=-a3/4.0+R[0]/2.0-D[0]/2.0;
roots[1][1]= R[1]/2.0-D[1]/2.0;
roots[2][0]=-a3/4.0-R[0]/2.0+E[0]/2.0;
roots[2][1]= -R[1]/2.0+E[1]/2.0;
roots[3][0]=-a3/4.0-R[0]/2.0-E[0]/2.0;
roots[3][1]= -R[1]/2.0-E[1]/2.0;
return 4;
}
int Solve(const double* eqns,const double* values,double* solutions,const int& dim){
int i,j,eIndex;
double v,m;
int *index=new int[dim];
int *set=new int[dim];
double* myEqns=new double[dim*dim];
double* myValues=new double[dim];
for(i=0;i<dim*dim;i++){myEqns[i]=eqns[i];}
for(i=0;i<dim;i++){
myValues[i]=values[i];
set[i]=0;
}
for(i=0;i<dim;i++){
// Find the largest equation that has a non-zero entry in the i-th index
m=-1;
eIndex=-1;
for(j=0;j<dim;j++){
if(set[j]){continue;}
if(myEqns[j*dim+i]!=0 && fabs(myEqns[j*dim+i])>m){
m=fabs(myEqns[j*dim+i]);
eIndex=j;
}
}
if(eIndex==-1){
delete[] index;
delete[] myValues;
delete[] myEqns;
delete[] set;
return 0;
}
// The position in which the solution for the i-th variable can be found
index[i]=eIndex;
set[eIndex]=1;
// Normalize the equation
v=myEqns[eIndex*dim+i];
for(j=0;j<dim;j++){myEqns[eIndex*dim+j]/=v;}
myValues[eIndex]/=v;
// Subtract it off from everything else
for(j=0;j<dim;j++){
if(j==eIndex){continue;}
double vv=myEqns[j*dim+i];
for(int k=0;k<dim;k++){myEqns[j*dim+k]-=myEqns[eIndex*dim+k]*vv;}
myValues[j]-=myValues[eIndex]*vv;
}
}
for(i=0;i<dim;i++){solutions[i]=myValues[index[i]];}
delete[] index;
delete[] myValues;
delete[] myEqns;
delete[] set;
return 1;
}
}
}
<commit_msg>move the includes out of the namespaces<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho,
* Johns Hopkins University
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
#include <math.h>
#include "pcl/surface/poisson/factor.h"
namespace pcl {
namespace poisson {
//////////////////////
// Polynomial Roots //
//////////////////////
int Factor(double a1,double a0,double roots[1][2],const double& EPS){
if(fabs(a1)<=EPS){return 0;}
roots[0][0]=-a0/a1;
roots[0][1]=0;
return 1;
}
int Factor(double a2,double a1,double a0,double roots[2][2],const double& EPS){
double d;
if(fabs(a2)<=EPS){return Factor(a1,a0,roots,EPS);}
d=a1*a1-4*a0*a2;
a1/=(2*a2);
if(d<0){
d=sqrt(-d)/(2*a2);
roots[0][0]=roots[1][0]=-a1;
roots[0][1]=-d;
roots[1][1]= d;
}
else{
d=sqrt(d)/(2*a2);
roots[0][1]=roots[1][1]=0;
roots[0][0]=-a1-d;
roots[1][0]=-a1+d;
}
return 2;
}
// Solution taken from: http://mathworld.wolfram.com/CubicFormula.html
// and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90
int Factor(double a3,double a2,double a1,double a0,double roots[3][2],const double& EPS){
double q,r,r2,q3;
if(fabs(a3)<=EPS){return Factor(a2,a1,a0,roots,EPS);}
a2/=a3;
a1/=a3;
a0/=a3;
q=-(3*a1-a2*a2)/9;
r=-(9*a2*a1-27*a0-2*a2*a2*a2)/54;
r2=r*r;
q3=q*q*q;
if(r2<q3){
double sqrQ=sqrt(q);
double theta = acos ( r / (sqrQ*q) );
double cTheta=cos(theta/3)*sqrQ;
double sTheta=sin(theta/3)*sqrQ*SQRT_3/2;
roots[0][1]=roots[1][1]=roots[2][1]=0;
roots[0][0]=-2*cTheta;
roots[1][0]=-2*(-cTheta*0.5-sTheta);
roots[2][0]=-2*(-cTheta*0.5+sTheta);
}
else{
double s1,s2,sqr=sqrt(r2-q3);
double t;
t=-r+sqr;
if(t<0){s1=-pow(-t,1.0/3);}
else{s1=pow(t,1.0/3);}
t=-r-sqr;
if(t<0){s2=-pow(-t,1.0/3);}
else{s2=pow(t,1.0/3);}
roots[0][1]=0;
roots[0][0]=s1+s2;
s1/=2;
s2/=2;
roots[1][0]= roots[2][0]=-s1-s2;
roots[1][1]= SQRT_3*(s1-s2);
roots[2][1]=-roots[1][1];
}
roots[0][0]-=a2/3;
roots[1][0]-=a2/3;
roots[2][0]-=a2/3;
return 3;
}
double ArcTan2(const double& y,const double& x){
/* This first case should never happen */
if(y==0 && x==0){return 0;}
if(x==0){
if(y>0){return PI/2.0;}
else{return -PI/2.0;}
}
if(x>=0){return atan(y/x);}
else{
if(y>=0){return atan(y/x)+PI;}
else{return atan(y/x)-PI;}
}
}
double Angle(const double in[2]){
if((in[0]*in[0]+in[1]*in[1])==0.0){return 0;}
else{return ArcTan2(in[1],in[0]);}
}
void Sqrt(const double in[2],double out[2]){
double r=sqrt(sqrt(in[0]*in[0]+in[1]*in[1]));
double a=Angle(in)*0.5;
out[0]=r*cos(a);
out[1]=r*sin(a);
}
void Add(const double in1[2],const double in2[2],double out[2]){
out[0]=in1[0]+in2[0];
out[1]=in1[1]+in2[1];
}
void Subtract(const double in1[2],const double in2[2],double out[2]){
out[0]=in1[0]-in2[0];
out[1]=in1[1]-in2[1];
}
void Multiply(const double in1[2],const double in2[2],double out[2]){
out[0]=in1[0]*in2[0]-in1[1]*in2[1];
out[1]=in1[0]*in2[1]+in1[1]*in2[0];
}
void Divide(const double in1[2],const double in2[2],double out[2]){
double temp[2];
double l=in2[0]*in2[0]+in2[1]*in2[1];
temp[0]= in2[0]/l;
temp[1]=-in2[1]/l;
Multiply(in1,temp,out);
}
// Solution taken from: http://mathworld.wolfram.com/QuarticEquation.html
// and http://www.csit.fsu.edu/~burkardt/f_src/subpak/subpak.f90
int Factor(double a4,double a3,double a2,double a1,double a0,double roots[4][2],const double& EPS){
double R[2],D[2],E[2],R2[2];
if(fabs(a4)<EPS){return Factor(a3,a2,a1,a0,roots,EPS);}
a3/=a4;
a2/=a4;
a1/=a4;
a0/=a4;
Factor(1.0,-a2,a3*a1-4.0*a0,-a3*a3*a0+4.0*a2*a0-a1*a1,roots,EPS);
R2[0]=a3*a3/4.0-a2+roots[0][0];
R2[1]=0;
Sqrt(R2,R);
if(fabs(R[0])>10e-8){
double temp1[2],temp2[2];
double p1[2],p2[2];
p1[0]=a3*a3*0.75-2.0*a2-R2[0];
p1[1]=0;
temp2[0]=((4.0*a3*a2-8.0*a1-a3*a3*a3)/4.0);
temp2[1]=0;
Divide(temp2,R,p2);
Add (p1,p2,temp1);
Subtract(p1,p2,temp2);
Sqrt(temp1,D);
Sqrt(temp2,E);
}
else{
R[0]=R[1]=0;
double temp1[2],temp2[2];
temp1[0]=roots[0][0]*roots[0][0]-4.0*a0;
temp1[1]=0;
Sqrt(temp1,temp2);
temp1[0]=a3*a3*0.75-2.0*a2+2.0*temp2[0];
temp1[1]= 2.0*temp2[1];
Sqrt(temp1,D);
temp1[0]=a3*a3*0.75-2.0*a2-2.0*temp2[0];
temp1[1]= -2.0*temp2[1];
Sqrt(temp1,E);
}
roots[0][0]=-a3/4.0+R[0]/2.0+D[0]/2.0;
roots[0][1]= R[1]/2.0+D[1]/2.0;
roots[1][0]=-a3/4.0+R[0]/2.0-D[0]/2.0;
roots[1][1]= R[1]/2.0-D[1]/2.0;
roots[2][0]=-a3/4.0-R[0]/2.0+E[0]/2.0;
roots[2][1]= -R[1]/2.0+E[1]/2.0;
roots[3][0]=-a3/4.0-R[0]/2.0-E[0]/2.0;
roots[3][1]= -R[1]/2.0-E[1]/2.0;
return 4;
}
int Solve(const double* eqns,const double* values,double* solutions,const int& dim){
int i,j,eIndex;
double v,m;
int *index=new int[dim];
int *set=new int[dim];
double* myEqns=new double[dim*dim];
double* myValues=new double[dim];
for(i=0;i<dim*dim;i++){myEqns[i]=eqns[i];}
for(i=0;i<dim;i++){
myValues[i]=values[i];
set[i]=0;
}
for(i=0;i<dim;i++){
// Find the largest equation that has a non-zero entry in the i-th index
m=-1;
eIndex=-1;
for(j=0;j<dim;j++){
if(set[j]){continue;}
if(myEqns[j*dim+i]!=0 && fabs(myEqns[j*dim+i])>m){
m=fabs(myEqns[j*dim+i]);
eIndex=j;
}
}
if(eIndex==-1){
delete[] index;
delete[] myValues;
delete[] myEqns;
delete[] set;
return 0;
}
// The position in which the solution for the i-th variable can be found
index[i]=eIndex;
set[eIndex]=1;
// Normalize the equation
v=myEqns[eIndex*dim+i];
for(j=0;j<dim;j++){myEqns[eIndex*dim+j]/=v;}
myValues[eIndex]/=v;
// Subtract it off from everything else
for(j=0;j<dim;j++){
if(j==eIndex){continue;}
double vv=myEqns[j*dim+i];
for(int k=0;k<dim;k++){myEqns[j*dim+k]-=myEqns[eIndex*dim+k]*vv;}
myValues[j]-=myValues[eIndex]*vv;
}
}
for(i=0;i<dim;i++){solutions[i]=myValues[index[i]];}
delete[] index;
delete[] myValues;
delete[] myEqns;
delete[] set;
return 1;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: wizdlg.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2008-03-06 19:23:09 $
*
* 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 _SVT_WIZDLG_HXX
#define _SVT_WIZDLG_HXX
#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif
#ifndef _VCL_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
class TabPage;
class Button;
class PushButton;
class FixedLine;
struct ImplWizPageData;
struct ImplWizButtonData;
/*************************************************************************
Beschreibung
============
class WizardDialog
Diese Klasse dient als Basis fuer einen WizardDialog. Als
Basisfunktionalitaet wird das Anordnen der Controls angeboten und
Hilfesmethoden fuer das Umschalten von TabPages. Der Dialog
ordnet bei einer Groessenanderung die Controls auch wieder
entsprechend an.
--------------------------------------------------------------------------
Mit SetPageSizePixel() kann als Groesse die Groesse der groessten
TabPage vorgegeben werden. Wenn der Dialog angezeigt wird, wird
zu dem Zeitpunkt wenn noch keine Groesse gesetzt wurde, dafuer
die entsprechende Dialoggroesse berechnet und gesetzt. Wenn mit
SetPageSizePixel() keine Groesse gesetzt wurde, wird als Groesse
die maximale Groesse der zu diesem Zeitpunkt zugewiesenen TabPages
berechnet und genommen.
ShowPrevPage()/ShowNextPage() zeigt die vorherige/naechste TabPage
an. Dazu wird zuerst der Deactivate-Handler vom Dialog gerufen und
wenn dieser TRUE zurueckgegeben hat, wird der Acivate-Handler
vom Dialog gerufen und die entsprechende TabPage angezeigt.
Finnsh() kann gerufen werden, wenn der Finnish-Button betaetigt
wird. Dort wird dann auch noch der Deactivate-Page-Handler vom
Dialog und der aktuellen TabPage gerufen und dann der Dialog
beendet (Close() oder EndDialog()).
Mit AddPage()/RemovePage()/SetPage() koennen die TabPages dem Wizard
bekannt gemacht werden. Es wird immer die TabPage des aktuellen Levels
angezeigt, wenn fuer den aktuellen Level keine TabPage zugewiesen
ist, wird die TabPages des hoechsten Levels angezeigt. Somit kann auch
immer die aktuelle TabPage ausgetauscht werden, wobei zu
beruecksichtigen ist, das im Activate-Handler die aktuelle TabPage
nicht zerstoert werden darf.
Mit SetPrevButton()/SetNextButton() werden der Prev-Button und der
Next-Button dem Dialog bekannt gemacht. In dem Fall loest der
Dialog bei Ctr+Tab, Shift+Ctrl+Tab den entsprechenden Click-Handler
am zugewiesenen Button aus. Die Button werden nicht vom WizardDialog
disablte. Eine entsprechende Steuerung muss der Benutzer dieses
Dialoges selber programieren.
Mit AddButton()/RemoveButton() koennen Buttons dem Wizard bekannt
gemacht werden, die in der Reihenfolge der Hinzufuegung angeordnet
werden. Die Buttons werden unabhengig von ihrem sichtbarkeitsstatus
angeordnet, so das auch spaeter ein entsprechender Button angezeigt/
gehidet werden kann. Der Offset wird in Pixeln angegeben und bezieht
sich immer auf den nachfolgenden Button. Damit der Abstand zwischen
den Buttons bei allen Dialogen gleich ist, gibt es das Define
WIZARDDIALOG_BUTTON_STDOFFSET_X, welches als Standard-Offset genommen
werden sollte.
Mit ShowButtonFixedLine() kann gesteuert werden, ob die zwischen den
Buttons und der TabPage eine Trennlinie angezeigt werden soll.
Mit SetViewWindow() und SetViewAlign() kann ein Control gesetzt werden,
welches als PreView-Window oder fuer die Anzeige von schoenen Bitmaps
genutzt werden kann.
--------------------------------------------------------------------------
Der ActivatePage()-Handler wird gerufen, wenn eine neue TabPages
angezeigt wird. In diesem Handler kann beispielsweise die neue
TabPage erzeugt werden, wenn diese zu diesem Zeitpunkt noch nicht
erzeugt wurde. Der Handler kann auch als Link gesetzt werden. Mit
GetCurLevel() kann die aktuelle ebene abgefragt werden, wobei
Level 0 die erste Seite ist.
Der DeactivatePage()-Handler wird gerufen, wenn eine neue TabPage
angezeigt werden soll. In diesem Handler kann noch eine Fehler-
ueberprufung stattfinden und das Umschalten gegebenenfalls verhindert
werden, indem FALSE zurueckgegeben wird. Der Handler kann auch als
Link gesetzt werden. Die Defaultimplementierung ruft den Link und
gibt den Rueckgabewert des Links zurueck und wenn kein Link gesetzt
ist, wird TRUE zurueckgegeben.
--------------------------------------------------------------------------
Beispiel:
MyWizardDlg-Ctor
----------------
// add buttons
AddButton( &maHelpBtn, WIZARDDIALOG_BUTTON_STDOFFSET_X );
AddButton( &maCancelBtn, WIZARDDIALOG_BUTTON_STDOFFSET_X );
AddButton( &maPrevBtn );
AddButton( &maNextBtn, WIZARDDIALOG_BUTTON_STDOFFSET_X );
AddButton( &maFinnishBtn );
SetPrevButton( &maPrevBtn );
SetNextButton( &maNextBtn );
// SetHandler
maPrevBtn.SetClickHdl( LINK( this, MyWizardDlg, ImplPrevHdl ) );
maNextBtn.SetClickHdl( LINK( this, MyWizardDlg, ImplNextHdl ) );
// Set PreviewWindow
SetViewWindow( &maPreview );
// Show line between Buttons and Page
ShowButtonFixedLine( TRUE );
// Call ActivatePage, because the first page should be created an activated
ActivatePage();
MyWizardDlg-ActivatePage-Handler
--------------------------------
void MyWizardDlg::ActivatePage()
{
WizardDialog::ActivatePage();
// Test, if Page is created already
if ( !GetPage( GetCurLevel() ) )
{
// Create and add new page
TabPage* pNewTabPage;
switch ( GetCurLevel() )
{
case 0:
pNewTabPage = CreateIntroPage();
break;
case 1:
pNewTabPage = CreateSecondPage();
break;
case 2:
pNewTabPage = CreateThirdPage();
break;
case 3:
pNewTabPage = CreateFinnishedPage();
break;
}
AddPage( pNewTabPage );
}
}
MyWizardDlg-Prev/Next-Handler
-----------------------------
IMPL_LINK( MyWizardDlg, ImplPrevHdl, PushButton*, pBtn )
{
ShowPrevPage();
if ( !GetCurLevel() )
pBtn->Disable();
return 0;
}
IMPL_LINK( MyWizardDlg, ImplNextHdl, PushButton*, pBtn )
{
ShowNextPage();
if ( GetCurLevel() < 3 )
pBtn->Disable();
return 0;
}
*************************************************************************/
// ----------------------
// - WizardDialog-Types -
// ----------------------
#define WIZARDDIALOG_BUTTON_STDOFFSET_X 6
#define WIZARDDIALOG_BUTTON_SMALLSTDOFFSET_X 3
#define WIZARDDIALOG_BUTTON_STDOFFSETLEFT_X -10
// ----------------
// - WizardDialog -
// ----------------
class SVT_DLLPUBLIC WizardDialog : public ModalDialog
{
private:
Size maPageSize;
ImplWizPageData* mpFirstPage;
ImplWizButtonData* mpFirstBtn;
FixedLine* mpFixedLine;
TabPage* mpCurTabPage;
PushButton* mpPrevBtn;
PushButton* mpNextBtn;
Window* mpViewWindow;
USHORT mnCurLevel;
WindowAlign meViewAlign;
Link maActivateHdl;
Link maDeactivateHdl;
sal_Int16 mnLeftAlignCount;
bool mbEmptyViewMargin;
protected:
long LogicalCoordinateToPixel(int iCoordinate);
/**sets the number of buttons which should be left-aligned. Normally, buttons are right-aligned.
only to be used during construction, before any layouting happened
*/
void SetLeftAlignedButtonCount( sal_Int16 _nCount );
/** declares the view area to have an empty margin
Normally, the view area has a certain margin to the top/left/bottom/right of the
dialog. By calling this method, you can reduce this margin to 0.
*/
void SetEmptyViewMargin();
#ifdef _SVT_WIZDLG_CXX
private:
SVT_DLLPRIVATE void ImplInitData();
SVT_DLLPRIVATE void ImplCalcSize( Size& rSize );
SVT_DLLPRIVATE void ImplPosCtrls();
SVT_DLLPRIVATE void ImplPosTabPage();
SVT_DLLPRIVATE void ImplShowTabPage( TabPage* pPage );
SVT_DLLPRIVATE TabPage* ImplGetPage( USHORT nLevel ) const;
#endif
public:
WizardDialog( Window* pParent, WinBits nStyle = WB_STDTABDIALOG );
WizardDialog( Window* pParent, const ResId& rResId );
~WizardDialog();
virtual void Resize();
virtual void StateChanged( StateChangedType nStateChange );
virtual long Notify( NotifyEvent& rNEvt );
virtual void ActivatePage();
virtual long DeactivatePage();
BOOL ShowPrevPage();
BOOL ShowNextPage();
BOOL ShowPage( USHORT nLevel );
BOOL Finnish( long nResult = 0 );
USHORT GetCurLevel() const { return mnCurLevel; }
void AddPage( TabPage* pPage );
void RemovePage( TabPage* pPage );
void SetPage( USHORT nLevel, TabPage* pPage );
TabPage* GetPage( USHORT nLevel ) const;
void AddButton( Button* pButton, long nOffset = 0 );
void RemoveButton( Button* pButton );
void SetPrevButton( PushButton* pButton ) { mpPrevBtn = pButton; }
PushButton* GetPrevButton() const { return mpPrevBtn; }
void SetNextButton( PushButton* pButton ) { mpNextBtn = pButton; }
PushButton* GetNextButton() const { return mpNextBtn; }
void ShowButtonFixedLine( BOOL bVisible );
BOOL IsButtonFixedLineVisible();
void SetViewWindow( Window* pWindow ) { mpViewWindow = pWindow; }
Window* GetViewWindow() const { return mpViewWindow; }
void SetViewAlign( WindowAlign eAlign ) { meViewAlign = eAlign; }
WindowAlign GetViewAlign() const { return meViewAlign; }
void SetPageSizePixel( const Size& rSize ) { maPageSize = rSize; }
const Size& GetPageSizePixel() const { return maPageSize; }
void SetActivatePageHdl( const Link& rLink ) { maActivateHdl = rLink; }
const Link& GetActivatePageHdl() const { return maActivateHdl; }
void SetDeactivatePageHdl( const Link& rLink ) { maDeactivateHdl = rLink; }
const Link& GetDeactivatePageHdl() const { return maDeactivateHdl; }
};
#endif // _SVT_WIZDLG_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.3.26); FILE MERGED 2008/04/01 12:43:17 thb 1.3.26.2: #i85898# Stripping all external header guards 2008/03/31 13:01:10 rt 1.3.26.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: wizdlg.hxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVT_WIZDLG_HXX
#define _SVT_WIZDLG_HXX
#include "svtools/svtdllapi.h"
#ifndef _VCL_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
class TabPage;
class Button;
class PushButton;
class FixedLine;
struct ImplWizPageData;
struct ImplWizButtonData;
/*************************************************************************
Beschreibung
============
class WizardDialog
Diese Klasse dient als Basis fuer einen WizardDialog. Als
Basisfunktionalitaet wird das Anordnen der Controls angeboten und
Hilfesmethoden fuer das Umschalten von TabPages. Der Dialog
ordnet bei einer Groessenanderung die Controls auch wieder
entsprechend an.
--------------------------------------------------------------------------
Mit SetPageSizePixel() kann als Groesse die Groesse der groessten
TabPage vorgegeben werden. Wenn der Dialog angezeigt wird, wird
zu dem Zeitpunkt wenn noch keine Groesse gesetzt wurde, dafuer
die entsprechende Dialoggroesse berechnet und gesetzt. Wenn mit
SetPageSizePixel() keine Groesse gesetzt wurde, wird als Groesse
die maximale Groesse der zu diesem Zeitpunkt zugewiesenen TabPages
berechnet und genommen.
ShowPrevPage()/ShowNextPage() zeigt die vorherige/naechste TabPage
an. Dazu wird zuerst der Deactivate-Handler vom Dialog gerufen und
wenn dieser TRUE zurueckgegeben hat, wird der Acivate-Handler
vom Dialog gerufen und die entsprechende TabPage angezeigt.
Finnsh() kann gerufen werden, wenn der Finnish-Button betaetigt
wird. Dort wird dann auch noch der Deactivate-Page-Handler vom
Dialog und der aktuellen TabPage gerufen und dann der Dialog
beendet (Close() oder EndDialog()).
Mit AddPage()/RemovePage()/SetPage() koennen die TabPages dem Wizard
bekannt gemacht werden. Es wird immer die TabPage des aktuellen Levels
angezeigt, wenn fuer den aktuellen Level keine TabPage zugewiesen
ist, wird die TabPages des hoechsten Levels angezeigt. Somit kann auch
immer die aktuelle TabPage ausgetauscht werden, wobei zu
beruecksichtigen ist, das im Activate-Handler die aktuelle TabPage
nicht zerstoert werden darf.
Mit SetPrevButton()/SetNextButton() werden der Prev-Button und der
Next-Button dem Dialog bekannt gemacht. In dem Fall loest der
Dialog bei Ctr+Tab, Shift+Ctrl+Tab den entsprechenden Click-Handler
am zugewiesenen Button aus. Die Button werden nicht vom WizardDialog
disablte. Eine entsprechende Steuerung muss der Benutzer dieses
Dialoges selber programieren.
Mit AddButton()/RemoveButton() koennen Buttons dem Wizard bekannt
gemacht werden, die in der Reihenfolge der Hinzufuegung angeordnet
werden. Die Buttons werden unabhengig von ihrem sichtbarkeitsstatus
angeordnet, so das auch spaeter ein entsprechender Button angezeigt/
gehidet werden kann. Der Offset wird in Pixeln angegeben und bezieht
sich immer auf den nachfolgenden Button. Damit der Abstand zwischen
den Buttons bei allen Dialogen gleich ist, gibt es das Define
WIZARDDIALOG_BUTTON_STDOFFSET_X, welches als Standard-Offset genommen
werden sollte.
Mit ShowButtonFixedLine() kann gesteuert werden, ob die zwischen den
Buttons und der TabPage eine Trennlinie angezeigt werden soll.
Mit SetViewWindow() und SetViewAlign() kann ein Control gesetzt werden,
welches als PreView-Window oder fuer die Anzeige von schoenen Bitmaps
genutzt werden kann.
--------------------------------------------------------------------------
Der ActivatePage()-Handler wird gerufen, wenn eine neue TabPages
angezeigt wird. In diesem Handler kann beispielsweise die neue
TabPage erzeugt werden, wenn diese zu diesem Zeitpunkt noch nicht
erzeugt wurde. Der Handler kann auch als Link gesetzt werden. Mit
GetCurLevel() kann die aktuelle ebene abgefragt werden, wobei
Level 0 die erste Seite ist.
Der DeactivatePage()-Handler wird gerufen, wenn eine neue TabPage
angezeigt werden soll. In diesem Handler kann noch eine Fehler-
ueberprufung stattfinden und das Umschalten gegebenenfalls verhindert
werden, indem FALSE zurueckgegeben wird. Der Handler kann auch als
Link gesetzt werden. Die Defaultimplementierung ruft den Link und
gibt den Rueckgabewert des Links zurueck und wenn kein Link gesetzt
ist, wird TRUE zurueckgegeben.
--------------------------------------------------------------------------
Beispiel:
MyWizardDlg-Ctor
----------------
// add buttons
AddButton( &maHelpBtn, WIZARDDIALOG_BUTTON_STDOFFSET_X );
AddButton( &maCancelBtn, WIZARDDIALOG_BUTTON_STDOFFSET_X );
AddButton( &maPrevBtn );
AddButton( &maNextBtn, WIZARDDIALOG_BUTTON_STDOFFSET_X );
AddButton( &maFinnishBtn );
SetPrevButton( &maPrevBtn );
SetNextButton( &maNextBtn );
// SetHandler
maPrevBtn.SetClickHdl( LINK( this, MyWizardDlg, ImplPrevHdl ) );
maNextBtn.SetClickHdl( LINK( this, MyWizardDlg, ImplNextHdl ) );
// Set PreviewWindow
SetViewWindow( &maPreview );
// Show line between Buttons and Page
ShowButtonFixedLine( TRUE );
// Call ActivatePage, because the first page should be created an activated
ActivatePage();
MyWizardDlg-ActivatePage-Handler
--------------------------------
void MyWizardDlg::ActivatePage()
{
WizardDialog::ActivatePage();
// Test, if Page is created already
if ( !GetPage( GetCurLevel() ) )
{
// Create and add new page
TabPage* pNewTabPage;
switch ( GetCurLevel() )
{
case 0:
pNewTabPage = CreateIntroPage();
break;
case 1:
pNewTabPage = CreateSecondPage();
break;
case 2:
pNewTabPage = CreateThirdPage();
break;
case 3:
pNewTabPage = CreateFinnishedPage();
break;
}
AddPage( pNewTabPage );
}
}
MyWizardDlg-Prev/Next-Handler
-----------------------------
IMPL_LINK( MyWizardDlg, ImplPrevHdl, PushButton*, pBtn )
{
ShowPrevPage();
if ( !GetCurLevel() )
pBtn->Disable();
return 0;
}
IMPL_LINK( MyWizardDlg, ImplNextHdl, PushButton*, pBtn )
{
ShowNextPage();
if ( GetCurLevel() < 3 )
pBtn->Disable();
return 0;
}
*************************************************************************/
// ----------------------
// - WizardDialog-Types -
// ----------------------
#define WIZARDDIALOG_BUTTON_STDOFFSET_X 6
#define WIZARDDIALOG_BUTTON_SMALLSTDOFFSET_X 3
#define WIZARDDIALOG_BUTTON_STDOFFSETLEFT_X -10
// ----------------
// - WizardDialog -
// ----------------
class SVT_DLLPUBLIC WizardDialog : public ModalDialog
{
private:
Size maPageSize;
ImplWizPageData* mpFirstPage;
ImplWizButtonData* mpFirstBtn;
FixedLine* mpFixedLine;
TabPage* mpCurTabPage;
PushButton* mpPrevBtn;
PushButton* mpNextBtn;
Window* mpViewWindow;
USHORT mnCurLevel;
WindowAlign meViewAlign;
Link maActivateHdl;
Link maDeactivateHdl;
sal_Int16 mnLeftAlignCount;
bool mbEmptyViewMargin;
protected:
long LogicalCoordinateToPixel(int iCoordinate);
/**sets the number of buttons which should be left-aligned. Normally, buttons are right-aligned.
only to be used during construction, before any layouting happened
*/
void SetLeftAlignedButtonCount( sal_Int16 _nCount );
/** declares the view area to have an empty margin
Normally, the view area has a certain margin to the top/left/bottom/right of the
dialog. By calling this method, you can reduce this margin to 0.
*/
void SetEmptyViewMargin();
#ifdef _SVT_WIZDLG_CXX
private:
SVT_DLLPRIVATE void ImplInitData();
SVT_DLLPRIVATE void ImplCalcSize( Size& rSize );
SVT_DLLPRIVATE void ImplPosCtrls();
SVT_DLLPRIVATE void ImplPosTabPage();
SVT_DLLPRIVATE void ImplShowTabPage( TabPage* pPage );
SVT_DLLPRIVATE TabPage* ImplGetPage( USHORT nLevel ) const;
#endif
public:
WizardDialog( Window* pParent, WinBits nStyle = WB_STDTABDIALOG );
WizardDialog( Window* pParent, const ResId& rResId );
~WizardDialog();
virtual void Resize();
virtual void StateChanged( StateChangedType nStateChange );
virtual long Notify( NotifyEvent& rNEvt );
virtual void ActivatePage();
virtual long DeactivatePage();
BOOL ShowPrevPage();
BOOL ShowNextPage();
BOOL ShowPage( USHORT nLevel );
BOOL Finnish( long nResult = 0 );
USHORT GetCurLevel() const { return mnCurLevel; }
void AddPage( TabPage* pPage );
void RemovePage( TabPage* pPage );
void SetPage( USHORT nLevel, TabPage* pPage );
TabPage* GetPage( USHORT nLevel ) const;
void AddButton( Button* pButton, long nOffset = 0 );
void RemoveButton( Button* pButton );
void SetPrevButton( PushButton* pButton ) { mpPrevBtn = pButton; }
PushButton* GetPrevButton() const { return mpPrevBtn; }
void SetNextButton( PushButton* pButton ) { mpNextBtn = pButton; }
PushButton* GetNextButton() const { return mpNextBtn; }
void ShowButtonFixedLine( BOOL bVisible );
BOOL IsButtonFixedLineVisible();
void SetViewWindow( Window* pWindow ) { mpViewWindow = pWindow; }
Window* GetViewWindow() const { return mpViewWindow; }
void SetViewAlign( WindowAlign eAlign ) { meViewAlign = eAlign; }
WindowAlign GetViewAlign() const { return meViewAlign; }
void SetPageSizePixel( const Size& rSize ) { maPageSize = rSize; }
const Size& GetPageSizePixel() const { return maPageSize; }
void SetActivatePageHdl( const Link& rLink ) { maActivateHdl = rLink; }
const Link& GetActivatePageHdl() const { return maActivateHdl; }
void SetDeactivatePageHdl( const Link& rLink ) { maDeactivateHdl = rLink; }
const Link& GetDeactivatePageHdl() const { return maDeactivateHdl; }
};
#endif // _SVT_WIZDLG_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: measctrl.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2007-06-27 17:20:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ---------------------------------------------------------------
#include <svx/xoutx.hxx>
#include <svx/svdomeas.hxx>
#include <svx/svdmodel.hxx>
//#include "svdrwobj.hxx" // SdrPaintInfoRec
#include "measctrl.hxx"
#include <svx/dialmgr.hxx>
#include "dlgutil.hxx"
/*************************************************************************
|*
|* Ctor SvxXMeasurePreview
|*
*************************************************************************/
SvxXMeasurePreview::SvxXMeasurePreview
(
Window* pParent,
const ResId& rResId,
const SfxItemSet& rInAttrs
) :
Control ( pParent, rResId ),
rAttrs ( rInAttrs )
{
pExtOutDev = new XOutputDevice( this );
SetMapMode( MAP_100TH_MM );
Size aSize = GetOutputSize();
// Massstab: 1:2
MapMode aMapMode = GetMapMode();
aMapMode.SetScaleX( Fraction( 1, 2 ) );
aMapMode.SetScaleY( Fraction( 1, 2 ) );
SetMapMode( aMapMode );
aSize = GetOutputSize();
Rectangle aRect = Rectangle( Point(), aSize );
Point aPt1 = Point( aSize.Width() / 5, (long) ( aSize.Height() / 2 ) );
Point aPt2 = Point( aSize.Width() * 4 / 5, (long) ( aSize.Height() / 2 ) );
pMeasureObj = new SdrMeasureObj( aPt1, aPt2 );
pModel = new SdrModel();
pMeasureObj->SetModel( pModel );
//pMeasureObj->SetItemSetAndBroadcast(rInAttrs);
pMeasureObj->SetMergedItemSetAndBroadcast(rInAttrs);
SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );
Invalidate();
}
/*************************************************************************
|*
|* Dtor SvxXMeasurePreview
|*
*************************************************************************/
SvxXMeasurePreview::~SvxXMeasurePreview()
{
delete pExtOutDev;
// #111111#
// No one is deleting the MeasureObj? This is not only an error but also
// a memory leak (!). Main problem is that this object is still listening to
// a StyleSheet of the model which was set. Thus, if You want to keep the obnject,
// set the modfel to 0L, if object is not needed (seems to be the case here),
// delete it.
delete pMeasureObj;
delete pModel;
}
/*************************************************************************
|*
|* SvxXMeasurePreview: Paint()
|*
*************************************************************************/
void SvxXMeasurePreview::Paint( const Rectangle& )
{
SdrPaintInfoRec aInfoRec;
pMeasureObj->SingleObjectPainter( *pExtOutDev, aInfoRec ); // #110094#-17
}
/*************************************************************************
|*
|* SvxXMeasurePreview: SetAttributes()
|*
*************************************************************************/
void SvxXMeasurePreview::SetAttributes( const SfxItemSet& rInAttrs )
{
//pMeasureObj->SetItemSetAndBroadcast(rInAttrs);
pMeasureObj->SetMergedItemSetAndBroadcast(rInAttrs);
Invalidate();
}
/*************************************************************************
|*
|* SvxXMeasurePreview: SetAttributes()
|*
*************************************************************************/
void SvxXMeasurePreview::MouseButtonDown( const MouseEvent& rMEvt )
{
BOOL bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift();
BOOL bZoomOut = rMEvt.IsRight() || rMEvt.IsShift();
BOOL bCtrl = rMEvt.IsMod1();
if( bZoomIn || bZoomOut )
{
MapMode aMapMode = GetMapMode();
Fraction aXFrac = aMapMode.GetScaleX();
Fraction aYFrac = aMapMode.GetScaleY();
Fraction* pMultFrac;
if( bZoomIn )
{
if( bCtrl )
pMultFrac = new Fraction( 3, 2 );
else
pMultFrac = new Fraction( 11, 10 );
}
else
{
if( bCtrl )
pMultFrac = new Fraction( 2, 3 );
else
pMultFrac = new Fraction( 10, 11 );
}
aXFrac *= *pMultFrac;
aYFrac *= *pMultFrac;
if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 &&
(double)aYFrac > 0.001 && (double)aYFrac < 1000.0 )
{
aMapMode.SetScaleX( aXFrac );
aMapMode.SetScaleY( aYFrac );
SetMapMode( aMapMode );
Size aOutSize( GetOutputSize() );
Point aPt( aMapMode.GetOrigin() );
long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
aPt.X() += nX;
aPt.Y() += nY;
aMapMode.SetOrigin( aPt );
SetMapMode( aMapMode );
Invalidate();
}
delete pMultFrac;
}
}
// -----------------------------------------------------------------------
void SvxXMeasurePreview::DataChanged( const DataChangedEvent& rDCEvt )
{
Control::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.10.368); FILE MERGED 2008/03/31 14:19:55 rt 1.10.368.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: measctrl.cxx,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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
// include ---------------------------------------------------------------
#include <svx/xoutx.hxx>
#include <svx/svdomeas.hxx>
#include <svx/svdmodel.hxx>
//#include "svdrwobj.hxx" // SdrPaintInfoRec
#include "measctrl.hxx"
#include <svx/dialmgr.hxx>
#include "dlgutil.hxx"
/*************************************************************************
|*
|* Ctor SvxXMeasurePreview
|*
*************************************************************************/
SvxXMeasurePreview::SvxXMeasurePreview
(
Window* pParent,
const ResId& rResId,
const SfxItemSet& rInAttrs
) :
Control ( pParent, rResId ),
rAttrs ( rInAttrs )
{
pExtOutDev = new XOutputDevice( this );
SetMapMode( MAP_100TH_MM );
Size aSize = GetOutputSize();
// Massstab: 1:2
MapMode aMapMode = GetMapMode();
aMapMode.SetScaleX( Fraction( 1, 2 ) );
aMapMode.SetScaleY( Fraction( 1, 2 ) );
SetMapMode( aMapMode );
aSize = GetOutputSize();
Rectangle aRect = Rectangle( Point(), aSize );
Point aPt1 = Point( aSize.Width() / 5, (long) ( aSize.Height() / 2 ) );
Point aPt2 = Point( aSize.Width() * 4 / 5, (long) ( aSize.Height() / 2 ) );
pMeasureObj = new SdrMeasureObj( aPt1, aPt2 );
pModel = new SdrModel();
pMeasureObj->SetModel( pModel );
//pMeasureObj->SetItemSetAndBroadcast(rInAttrs);
pMeasureObj->SetMergedItemSetAndBroadcast(rInAttrs);
SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );
Invalidate();
}
/*************************************************************************
|*
|* Dtor SvxXMeasurePreview
|*
*************************************************************************/
SvxXMeasurePreview::~SvxXMeasurePreview()
{
delete pExtOutDev;
// #111111#
// No one is deleting the MeasureObj? This is not only an error but also
// a memory leak (!). Main problem is that this object is still listening to
// a StyleSheet of the model which was set. Thus, if You want to keep the obnject,
// set the modfel to 0L, if object is not needed (seems to be the case here),
// delete it.
delete pMeasureObj;
delete pModel;
}
/*************************************************************************
|*
|* SvxXMeasurePreview: Paint()
|*
*************************************************************************/
void SvxXMeasurePreview::Paint( const Rectangle& )
{
SdrPaintInfoRec aInfoRec;
pMeasureObj->SingleObjectPainter( *pExtOutDev, aInfoRec ); // #110094#-17
}
/*************************************************************************
|*
|* SvxXMeasurePreview: SetAttributes()
|*
*************************************************************************/
void SvxXMeasurePreview::SetAttributes( const SfxItemSet& rInAttrs )
{
//pMeasureObj->SetItemSetAndBroadcast(rInAttrs);
pMeasureObj->SetMergedItemSetAndBroadcast(rInAttrs);
Invalidate();
}
/*************************************************************************
|*
|* SvxXMeasurePreview: SetAttributes()
|*
*************************************************************************/
void SvxXMeasurePreview::MouseButtonDown( const MouseEvent& rMEvt )
{
BOOL bZoomIn = rMEvt.IsLeft() && !rMEvt.IsShift();
BOOL bZoomOut = rMEvt.IsRight() || rMEvt.IsShift();
BOOL bCtrl = rMEvt.IsMod1();
if( bZoomIn || bZoomOut )
{
MapMode aMapMode = GetMapMode();
Fraction aXFrac = aMapMode.GetScaleX();
Fraction aYFrac = aMapMode.GetScaleY();
Fraction* pMultFrac;
if( bZoomIn )
{
if( bCtrl )
pMultFrac = new Fraction( 3, 2 );
else
pMultFrac = new Fraction( 11, 10 );
}
else
{
if( bCtrl )
pMultFrac = new Fraction( 2, 3 );
else
pMultFrac = new Fraction( 10, 11 );
}
aXFrac *= *pMultFrac;
aYFrac *= *pMultFrac;
if( (double)aXFrac > 0.001 && (double)aXFrac < 1000.0 &&
(double)aYFrac > 0.001 && (double)aYFrac < 1000.0 )
{
aMapMode.SetScaleX( aXFrac );
aMapMode.SetScaleY( aYFrac );
SetMapMode( aMapMode );
Size aOutSize( GetOutputSize() );
Point aPt( aMapMode.GetOrigin() );
long nX = (long)( ( (double)aOutSize.Width() - ( (double)aOutSize.Width() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
long nY = (long)( ( (double)aOutSize.Height() - ( (double)aOutSize.Height() * (double)*pMultFrac ) ) / 2.0 + 0.5 );
aPt.X() += nX;
aPt.Y() += nY;
aMapMode.SetOrigin( aPt );
SetMapMode( aMapMode );
Invalidate();
}
delete pMultFrac;
}
}
// -----------------------------------------------------------------------
void SvxXMeasurePreview::DataChanged( const DataChangedEvent& rDCEvt )
{
Control::DataChanged( rDCEvt );
if ( (rDCEvt.GetType() == DATACHANGED_SETTINGS) && (rDCEvt.GetFlags() & SETTINGS_STYLE) )
{
SetDrawMode( GetDisplayBackground().GetColor().IsDark() ? OUTPUT_DRAWMODE_CONTRAST : OUTPUT_DRAWMODE_COLOR );
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: pagectrl.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: dr $ $Date: 2001-06-22 16:15:54 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// include ---------------------------------------------------------------
#pragma hdrstop
#define ITEMID_BOX 0
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#include "pageitem.hxx"
#include "pagectrl.hxx"
#include "boxitem.hxx"
#include <algorithm>
// struct PageWindow_Impl ------------------------------------------------
struct PageWindow_Impl
{
SvxBoxItem* pBorder;
Bitmap aBitmap;
FASTBOOL bBitmap;
PageWindow_Impl() : pBorder(0), bBitmap(FALSE) {}
};
// STATIC DATA -----------------------------------------------------------
#define CELL_WIDTH 1600L
#define CELL_HEIGHT 800L
// class SvxPageWindow ---------------------------------------------------
SvxPageWindow::SvxPageWindow( Window* pParent, const ResId& rId ) :
Window( pParent, rId ),
nTop ( 0 ),
nBottom ( 0 ),
nLeft ( 0 ),
nRight ( 0 ),
aColor ( COL_WHITE ),
nHdLeft ( 0 ),
nHdRight ( 0 ),
nHdDist ( 0 ),
nHdHeight ( 0 ),
aHdColor ( COL_WHITE ),
pHdBorder ( 0 ),
nFtLeft ( 0 ),
nFtRight ( 0 ),
nFtDist ( 0 ),
nFtHeight ( 0 ),
aFtColor ( COL_WHITE ),
pFtBorder ( 0 ),
bFooter ( FALSE ),
bHeader ( FALSE ),
bTable ( FALSE ),
bHorz ( FALSE ),
bVert ( FALSE ),
eUsage ( SVX_PAGE_ALL )
{
pImpl = new PageWindow_Impl;
// defaultmaessing in Twips rechnen
SetMapMode( MapMode( MAP_TWIP ) );
aWinSize = GetOutputSizePixel();
aWinSize.Height() -= 4;
aWinSize.Width() -= 4;
aWinSize = PixelToLogic( aWinSize );
aSolidLineColor = Color( COL_BLACK );
aDotLineColor = Color( COL_BLACK );
aGrayLineColor = Color( COL_GRAY );
aNormalFillColor = GetFillColor();
aDisabledFillColor = Color( COL_GRAY );
aGrayFillColor = Color( COL_LIGHTGRAY );
}
// -----------------------------------------------------------------------
SvxPageWindow::~SvxPageWindow()
{
delete pImpl;
delete pHdBorder;
delete pFtBorder;
}
// -----------------------------------------------------------------------
void __EXPORT SvxPageWindow::Paint( const Rectangle& rRect )
{
Fraction aXScale( aWinSize.Width(), std::max( (long) (aSize.Width() * 2 + aSize.Width() / 8), 1L ) );
Fraction aYScale( aWinSize.Height(), std::max( aSize.Height(), 1L ) );
MapMode aMapMode( GetMapMode() );
if ( aYScale < aXScale )
{
aMapMode.SetScaleX( aYScale );
aMapMode.SetScaleY( aYScale );
}
else
{
aMapMode.SetScaleX( aXScale );
aMapMode.SetScaleY( aXScale );
}
SetMapMode( aMapMode );
Size aSz( PixelToLogic( GetSizePixel() ) );
long nYPos = ( aSz.Height() - aSize.Height() ) / 2;
if ( eUsage == SVX_PAGE_ALL )
{
// alle Seiten gleich -> eine Seite malen
if ( aSize.Width() > aSize.Height() )
{
// Querformat in gleicher Gr"osse zeichnen
Fraction aX = aMapMode.GetScaleX();
Fraction aY = aMapMode.GetScaleY();
Fraction a2( 1.5 );
aX *= a2;
aY *= a2;
aMapMode.SetScaleX( aX );
aMapMode.SetScaleY( aY );
SetMapMode( aMapMode );
aSz = PixelToLogic( GetSizePixel() );
nYPos = ( aSz.Height() - aSize.Height() ) / 2;
long nXPos = ( aSz.Width() - aSize.Width() ) / 2;
DrawPage( Point( nXPos, nYPos ), TRUE, TRUE );
}
else
// Hochformat
DrawPage( Point( ( aSz.Width() - aSize.Width() ) / 2, nYPos ), TRUE, TRUE );
}
else
{
// Linke und rechte Seite unterschiedlich -> ggf. zwei Seiten malen
DrawPage( Point( 0, nYPos ), FALSE, (BOOL)( eUsage & SVX_PAGE_LEFT ) );
DrawPage( Point( aSize.Width() + aSize.Width() / 8, nYPos ), TRUE,
(BOOL)( eUsage & SVX_PAGE_RIGHT ) );
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::DrawPage( const Point& rOrg, const BOOL bSecond, const BOOL bEnabled )
{
// Schatten
Size aTempSize = aSize;
// if ( aTempSize.Height() > aTempSize.Width() )
// // Beim Hochformat die H"ohe etwas verkleinern, damit der Schatten passt.
// aTempSize.Height() -= PixelToLogic( Size( 0, 2 ) ).Height();
// Point aShadowPt( rOrg );
// aShadowPt += PixelToLogic( Point( 2, 2 ) );
// SetLineColor( Color( COL_GRAY ) );
// SetFillColor( Color( COL_GRAY ) );
// DrawRect( Rectangle( aShadowPt, aTempSize ) );
// Seite
SetLineColor( Color( COL_BLACK ) );
if ( !bEnabled )
{
SetFillColor( Color( COL_GRAY ) );
DrawRect( Rectangle( rOrg, aTempSize ) );
return;
}
SetFillColor( Color( COL_WHITE ) );
DrawRect( Rectangle( rOrg, aTempSize ) );
// Border Top Bottom Left Right
Point aBegin( rOrg );
Point aEnd( rOrg );
long nL = nLeft;
long nR = nRight;
if ( eUsage == SVX_PAGE_MIRROR && !bSecond )
{
// f"ur gespiegelt drehen
nL = nRight;
nR = nLeft;
}
Rectangle aRect;
aRect.Left() = rOrg.X() + nL;
aRect.Right() = rOrg.X() + aTempSize.Width() - nR;
aRect.Top() = rOrg.Y() + nTop;
aRect.Bottom()= rOrg.Y() + aTempSize.Height() - nBottom;
Rectangle aHdRect( aRect );
Rectangle aFtRect( aRect );
if ( bHeader )
{
// ggf. Header anzeigen
aHdRect.Left() += nHdLeft;
aHdRect.Right() -= nHdRight;
aHdRect.Bottom() = aRect.Top() + nHdHeight;
aRect.Top() += nHdHeight + nHdDist;
SetFillColor( aHdColor );
DrawRect( aHdRect );
}
if ( bFooter )
{
// ggf. Footer anzeigen
aFtRect.Left() += nFtLeft;
aFtRect.Right() -= nFtRight;
aFtRect.Top() = aRect.Bottom() - nFtHeight;
aRect.Bottom() -= nFtHeight + nFtDist;
SetFillColor( aFtColor );
DrawRect( aFtRect );
}
// Body malen
SetFillColor( aColor );
if ( pImpl->bBitmap )
{
DrawRect( aRect );
Point aBmpPnt = aRect.TopLeft();
Size aBmpSiz = aRect.GetSize();
long nDeltaX = aBmpSiz.Width() / 15;
long nDeltaY = aBmpSiz.Height() / 15;
aBmpPnt.X() += nDeltaX;
aBmpPnt.Y() += nDeltaY;
aBmpSiz.Width() -= nDeltaX * 2;
aBmpSiz.Height() -= nDeltaY * 2;
DrawBitmap( aBmpPnt, aBmpSiz, pImpl->aBitmap );
}
else
DrawRect( aRect );
if ( bTable )
{
// Tabelle malen, ggf. zentrieren
SetLineColor( Color(COL_LIGHTGRAY) );
long nW = aRect.GetWidth(), nH = aRect.GetHeight();
long nTW = CELL_WIDTH * 3, nTH = CELL_HEIGHT * 3;
long nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left();
long nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top();
Rectangle aCellRect( Point( nLeft, nTop ), Size( CELL_WIDTH, CELL_HEIGHT ) );
for ( USHORT i = 0; i < 3; ++i )
{
aCellRect.Left() = nLeft;
aCellRect.Right() = nLeft + CELL_WIDTH;
if ( i > 0 )
aCellRect.Move( 0, CELL_HEIGHT );
for ( USHORT j = 0; j < 3; ++j )
{
if ( j > 0 )
aCellRect.Move( CELL_WIDTH, 0 );
DrawRect( aCellRect );
}
}
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBorder( const SvxBoxItem& rNew )
{
delete pImpl->pBorder;
pImpl->pBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBitmap( Bitmap* pBmp )
{
if ( pBmp )
{
pImpl->aBitmap = *pBmp;
pImpl->bBitmap = TRUE;
}
else
pImpl->bBitmap = FALSE;
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetHdBorder( const SvxBoxItem& rNew )
{
delete pHdBorder;
pHdBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetFtBorder( const SvxBoxItem& rNew )
{
delete pFtBorder;
pFtBorder = new SvxBoxItem( rNew );
}
<commit_msg>#97576# page preview colors are high contrast aware<commit_after>/*************************************************************************
*
* $RCSfile: pagectrl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: os $ $Date: 2002-02-27 13:43:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// include ---------------------------------------------------------------
#pragma hdrstop
#define ITEMID_BOX 0
#ifndef _SV_BITMAP_HXX
#include <vcl/bitmap.hxx>
#endif
#include "pageitem.hxx"
#include "pagectrl.hxx"
#include "boxitem.hxx"
#include <algorithm>
// struct PageWindow_Impl ------------------------------------------------
struct PageWindow_Impl
{
SvxBoxItem* pBorder;
Bitmap aBitmap;
FASTBOOL bBitmap;
PageWindow_Impl() : pBorder(0), bBitmap(FALSE) {}
};
// STATIC DATA -----------------------------------------------------------
#define CELL_WIDTH 1600L
#define CELL_HEIGHT 800L
// class SvxPageWindow ---------------------------------------------------
SvxPageWindow::SvxPageWindow( Window* pParent, const ResId& rId ) :
Window( pParent, rId ),
nTop ( 0 ),
nBottom ( 0 ),
nLeft ( 0 ),
nRight ( 0 ),
aColor ( COL_TRANSPARENT ),
nHdLeft ( 0 ),
nHdRight ( 0 ),
nHdDist ( 0 ),
nHdHeight ( 0 ),
aHdColor ( COL_TRANSPARENT ),
pHdBorder ( 0 ),
nFtLeft ( 0 ),
nFtRight ( 0 ),
nFtDist ( 0 ),
nFtHeight ( 0 ),
aFtColor ( COL_TRANSPARENT ),
pFtBorder ( 0 ),
bFooter ( FALSE ),
bHeader ( FALSE ),
bTable ( FALSE ),
bHorz ( FALSE ),
bVert ( FALSE ),
eUsage ( SVX_PAGE_ALL )
{
pImpl = new PageWindow_Impl;
// defaultmaessing in Twips rechnen
SetMapMode( MapMode( MAP_TWIP ) );
aWinSize = GetOutputSizePixel();
aWinSize.Height() -= 4;
aWinSize.Width() -= 4;
aWinSize = PixelToLogic( aWinSize );
}
// -----------------------------------------------------------------------
SvxPageWindow::~SvxPageWindow()
{
delete pImpl;
delete pHdBorder;
delete pFtBorder;
}
// -----------------------------------------------------------------------
void __EXPORT SvxPageWindow::Paint( const Rectangle& rRect )
{
Fraction aXScale( aWinSize.Width(), std::max( (long) (aSize.Width() * 2 + aSize.Width() / 8), 1L ) );
Fraction aYScale( aWinSize.Height(), std::max( aSize.Height(), 1L ) );
MapMode aMapMode( GetMapMode() );
if ( aYScale < aXScale )
{
aMapMode.SetScaleX( aYScale );
aMapMode.SetScaleY( aYScale );
}
else
{
aMapMode.SetScaleX( aXScale );
aMapMode.SetScaleY( aXScale );
}
SetMapMode( aMapMode );
Size aSz( PixelToLogic( GetSizePixel() ) );
long nYPos = ( aSz.Height() - aSize.Height() ) / 2;
if ( eUsage == SVX_PAGE_ALL )
{
// alle Seiten gleich -> eine Seite malen
if ( aSize.Width() > aSize.Height() )
{
// Querformat in gleicher Gr"osse zeichnen
Fraction aX = aMapMode.GetScaleX();
Fraction aY = aMapMode.GetScaleY();
Fraction a2( 1.5 );
aX *= a2;
aY *= a2;
aMapMode.SetScaleX( aX );
aMapMode.SetScaleY( aY );
SetMapMode( aMapMode );
aSz = PixelToLogic( GetSizePixel() );
nYPos = ( aSz.Height() - aSize.Height() ) / 2;
long nXPos = ( aSz.Width() - aSize.Width() ) / 2;
DrawPage( Point( nXPos, nYPos ), TRUE, TRUE );
}
else
// Hochformat
DrawPage( Point( ( aSz.Width() - aSize.Width() ) / 2, nYPos ), TRUE, TRUE );
}
else
{
// Linke und rechte Seite unterschiedlich -> ggf. zwei Seiten malen
DrawPage( Point( 0, nYPos ), FALSE, (BOOL)( eUsage & SVX_PAGE_LEFT ) );
DrawPage( Point( aSize.Width() + aSize.Width() / 8, nYPos ), TRUE,
(BOOL)( eUsage & SVX_PAGE_RIGHT ) );
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::DrawPage( const Point& rOrg, const BOOL bSecond, const BOOL bEnabled )
{
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
const Color& rFieldColor = rStyleSettings.GetFieldColor();
const Color& rFieldTextColor = rStyleSettings.GetFieldTextColor();
const Color& rDisableColor = rStyleSettings.GetDisableColor();
const Color& rDlgColor = rStyleSettings.GetDialogColor();
// background
if(!bSecond)
{
SetLineColor( Color(COL_TRANSPARENT) );
SetFillColor( rDlgColor );
Size aWinSize(GetOutputSize());
DrawRect( Rectangle( Point(0,0), aWinSize ) );
}
SetLineColor( rFieldTextColor );
// Schatten
Size aTempSize = aSize;
// Seite
if ( !bEnabled )
{
SetFillColor( rDisableColor );
DrawRect( Rectangle( rOrg, aTempSize ) );
return;
}
SetFillColor( rFieldColor );
DrawRect( Rectangle( rOrg, aTempSize ) );
// Border Top Bottom Left Right
Point aBegin( rOrg );
Point aEnd( rOrg );
long nL = nLeft;
long nR = nRight;
if ( eUsage == SVX_PAGE_MIRROR && !bSecond )
{
// f"ur gespiegelt drehen
nL = nRight;
nR = nLeft;
}
Rectangle aRect;
aRect.Left() = rOrg.X() + nL;
aRect.Right() = rOrg.X() + aTempSize.Width() - nR;
aRect.Top() = rOrg.Y() + nTop;
aRect.Bottom()= rOrg.Y() + aTempSize.Height() - nBottom;
Rectangle aHdRect( aRect );
Rectangle aFtRect( aRect );
if ( bHeader )
{
// ggf. Header anzeigen
aHdRect.Left() += nHdLeft;
aHdRect.Right() -= nHdRight;
aHdRect.Bottom() = aRect.Top() + nHdHeight;
aRect.Top() += nHdHeight + nHdDist;
SetFillColor( aHdColor );
DrawRect( aHdRect );
}
if ( bFooter )
{
// ggf. Footer anzeigen
aFtRect.Left() += nFtLeft;
aFtRect.Right() -= nFtRight;
aFtRect.Top() = aRect.Bottom() - nFtHeight;
aRect.Bottom() -= nFtHeight + nFtDist;
SetFillColor( aFtColor );
DrawRect( aFtRect );
}
// Body malen
SetFillColor( aColor );
if ( pImpl->bBitmap )
{
DrawRect( aRect );
Point aBmpPnt = aRect.TopLeft();
Size aBmpSiz = aRect.GetSize();
long nDeltaX = aBmpSiz.Width() / 15;
long nDeltaY = aBmpSiz.Height() / 15;
aBmpPnt.X() += nDeltaX;
aBmpPnt.Y() += nDeltaY;
aBmpSiz.Width() -= nDeltaX * 2;
aBmpSiz.Height() -= nDeltaY * 2;
DrawBitmap( aBmpPnt, aBmpSiz, pImpl->aBitmap );
}
else
DrawRect( aRect );
if ( bTable )
{
// Tabelle malen, ggf. zentrieren
SetLineColor( Color(COL_LIGHTGRAY) );
long nW = aRect.GetWidth(), nH = aRect.GetHeight();
long nTW = CELL_WIDTH * 3, nTH = CELL_HEIGHT * 3;
long nLeft = bHorz ? aRect.Left() + ((nW - nTW) / 2) : aRect.Left();
long nTop = bVert ? aRect.Top() + ((nH - nTH) / 2) : aRect.Top();
Rectangle aCellRect( Point( nLeft, nTop ), Size( CELL_WIDTH, CELL_HEIGHT ) );
for ( USHORT i = 0; i < 3; ++i )
{
aCellRect.Left() = nLeft;
aCellRect.Right() = nLeft + CELL_WIDTH;
if ( i > 0 )
aCellRect.Move( 0, CELL_HEIGHT );
for ( USHORT j = 0; j < 3; ++j )
{
if ( j > 0 )
aCellRect.Move( CELL_WIDTH, 0 );
DrawRect( aCellRect );
}
}
}
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBorder( const SvxBoxItem& rNew )
{
delete pImpl->pBorder;
pImpl->pBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetBitmap( Bitmap* pBmp )
{
if ( pBmp )
{
pImpl->aBitmap = *pBmp;
pImpl->bBitmap = TRUE;
}
else
pImpl->bBitmap = FALSE;
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetHdBorder( const SvxBoxItem& rNew )
{
delete pHdBorder;
pHdBorder = new SvxBoxItem( rNew );
}
// -----------------------------------------------------------------------
void SvxPageWindow::SetFtBorder( const SvxBoxItem& rNew )
{
delete pFtBorder;
pFtBorder = new SvxBoxItem( rNew );
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
// INCLUDE -------------------------------------------------------------------
#include <svx/simptabl.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/intlwrapper.hxx>
// SvxSimpleTableContainer ------------------------------------------------------
SvxSimpleTableContainer::SvxSimpleTableContainer( Window* pParent, const ResId& rResId)
: Control(pParent, rResId)
, m_pTable(NULL)
{
SetBorderStyle(WINDOW_BORDER_NOBORDER);
}
void SvxSimpleTableContainer::SetTable(SvxSimpleTable* pTable)
{
m_pTable = pTable;
}
long SvxSimpleTableContainer::PreNotify( NotifyEvent& rNEvt )
{
long nResult = sal_True;
if ( rNEvt.GetType() == EVENT_KEYINPUT )
{
const KeyCode& aKeyCode = rNEvt.GetKeyEvent()->GetKeyCode();
sal_uInt16 nKey = aKeyCode.GetCode();
if (nKey == KEY_TAB)
GetParent()->Notify( rNEvt );
else if (m_pTable && m_pTable->IsFocusOnCellEnabled() && ( nKey == KEY_LEFT || nKey == KEY_RIGHT))
return 0;
else
nResult = Control::PreNotify( rNEvt );
}
else
nResult = Control::PreNotify( rNEvt );
return nResult;
}
void SvxSimpleTableContainer::SetSizePixel(const Size& rNewSize )
{
Control::SetSizePixel(rNewSize);
if (m_pTable)
m_pTable->UpdateViewSize();
}
void SvxSimpleTableContainer::GetFocus()
{
Control::GetFocus();
if (m_pTable)
m_pTable->GrabFocus();
}
// SvxSimpleTable ------------------------------------------------------------
SvxSimpleTable::SvxSimpleTable(SvxSimpleTableContainer& rParent, WinBits nBits):
SvHeaderTabListBox(&rParent, nBits | WB_CLIPCHILDREN | WB_HSCROLL | WB_TABSTOP),
m_rParentTableContainer(rParent),
aHeaderBar(&rParent,WB_BUTTONSTYLE | WB_BORDER | WB_TABSTOP),
nHeaderItemId(1),
bResizeFlag(sal_False),
bPaintFlag(sal_True)
{
m_rParentTableContainer.SetTable(this);
bSortDirection=sal_True;
nSortCol=0xFFFF;
nOldPos=0;
aHeaderBar.SetStartDragHdl(LINK( this, SvxSimpleTable, StartDragHdl));
aHeaderBar.SetDragHdl(LINK( this, SvxSimpleTable, DragHdl));
aHeaderBar.SetEndDragHdl(LINK( this, SvxSimpleTable, EndDragHdl));
aHeaderBar.SetSelectHdl(LINK( this, SvxSimpleTable, HeaderBarClick));
aHeaderBar.SetDoubleClickHdl(LINK( this, SvxSimpleTable, HeaderBarDblClick));
EnableCellFocus();
DisableTransientChildren();
InitHeaderBar( &aHeaderBar );
UpdateViewSize();
aHeaderBar.Show();
SvHeaderTabListBox::Show();
}
SvxSimpleTable::~SvxSimpleTable()
{
}
void SvxSimpleTable::UpdateViewSize()
{
Size theWinSize=m_rParentTableContainer.GetSizePixel();
Size HbSize=aHeaderBar.GetSizePixel();
HbSize.Width()=theWinSize.Width();
theWinSize.Height()-=HbSize.Height();
Point thePos(0,0);
aHeaderBar.SetPosPixel(thePos);
aHeaderBar.SetSizePixel(HbSize);
thePos.Y()+=HbSize.Height();
SvHeaderTabListBox::SetPosPixel(thePos);
SvHeaderTabListBox::SetSizePixel(theWinSize);
Invalidate();
}
void SvxSimpleTable::NotifyScrolled()
{
long nOffset=-GetXOffset();
if(nOldPos!=nOffset)
{
aHeaderBar.SetOffset(nOffset);
aHeaderBar.Invalidate();
aHeaderBar.Update();
nOldPos=nOffset;
}
SvHeaderTabListBox::NotifyScrolled();
}
void SvxSimpleTable::SetTabs()
{
SvHeaderTabListBox::SetTabs();
sal_uInt16 nPrivTabCount = TabCount();
if ( nPrivTabCount )
{
if ( nPrivTabCount > aHeaderBar.GetItemCount() )
nPrivTabCount = aHeaderBar.GetItemCount();
sal_uInt16 i, nNewSize = static_cast< sal_uInt16 >( GetTab(0) ), nPos = 0;
for ( i = 1; i < nPrivTabCount; ++i )
{
nNewSize = static_cast< sal_uInt16 >( GetTab(i) ) - nPos;
aHeaderBar.SetItemSize( i, nNewSize );
nPos = (sal_uInt16)GetTab(i);
}
aHeaderBar.SetItemSize( i, HEADERBAR_FULLSIZE ); // because no tab for last entry
}
}
void SvxSimpleTable::SetTabs( long* pTabs, MapUnit eMapUnit)
{
SvHeaderTabListBox::SetTabs(pTabs,eMapUnit);
}
void SvxSimpleTable::Paint( const Rectangle& rRect )
{
SvHeaderTabListBox::Paint(rRect );
sal_uInt16 nPrivTabCount = TabCount();
sal_uInt16 nNewSize = ( nPrivTabCount > 0 ) ? (sal_uInt16)GetTab(0) : 0;
long nOffset=-GetXOffset();
nOldPos=nOffset;
aHeaderBar.SetOffset(nOffset);
aHeaderBar.Invalidate();
if(nPrivTabCount && bPaintFlag)
{
if(nPrivTabCount>aHeaderBar.GetItemCount())
nPrivTabCount=aHeaderBar.GetItemCount();
sal_uInt16 nPos = 0;
for(sal_uInt16 i=1;i<nPrivTabCount;i++)
{
nNewSize = static_cast< sal_uInt16 >( GetTab(i) ) - nPos;
aHeaderBar.SetItemSize( i, nNewSize );
nPos= static_cast< sal_uInt16 >( GetTab(i) );
}
}
bPaintFlag=sal_True;
}
void SvxSimpleTable::InsertHeaderEntry(const rtl::OUString& rText,
sal_uInt16 nCol, HeaderBarItemBits nBits)
{
sal_Int32 nEnd = rText.indexOf( sal_Unicode( '\t' ) );
if( nEnd == -1 )
{
aHeaderBar.InsertItem(nHeaderItemId++, rText, 0, nBits, nCol);
}
else
{
sal_Int32 nIndex = 0;
do
{
rtl::OUString aString = rText.getToken(0, '\t', nIndex);
aHeaderBar.InsertItem(nHeaderItemId++, aString, 0, nBits, nCol);
}
while ( nIndex >= 0 );
}
SetTabs();
}
void SvxSimpleTable::ClearHeader()
{
aHeaderBar.Clear();
}
void SvxSimpleTable::ShowTable()
{
m_rParentTableContainer.Show();
}
void SvxSimpleTable::HideTable()
{
m_rParentTableContainer.Hide();
}
sal_Bool SvxSimpleTable::IsVisible() const
{
return m_rParentTableContainer.IsVisible();
}
void SvxSimpleTable::EnableTable()
{
m_rParentTableContainer.Enable();
}
void SvxSimpleTable::DisableTable()
{
m_rParentTableContainer.Disable();
}
sal_Bool SvxSimpleTable::IsEnabled() const
{
return m_rParentTableContainer.IsEnabled();
}
sal_uInt16 SvxSimpleTable::GetSelectedCol()
{
return (aHeaderBar.GetCurItemId()-1);
}
void SvxSimpleTable::SortByCol(sal_uInt16 nCol,sal_Bool bDir)
{
bSortDirection=bDir;
if(nSortCol!=0xFFFF)
aHeaderBar.SetItemBits(nSortCol+1,HIB_STDSTYLE);
if (nCol != 0xFFFF)
{
if(bDir)
{
aHeaderBar.SetItemBits( nCol+1, HIB_STDSTYLE | HIB_DOWNARROW);
GetModel()->SetSortMode(SortAscending);
}
else
{
aHeaderBar.SetItemBits( nCol+1, HIB_STDSTYLE | HIB_UPARROW);
GetModel()->SetSortMode(SortDescending);
}
nSortCol=nCol;
GetModel()->SetCompareHdl( LINK( this, SvxSimpleTable, CompareHdl));
GetModel()->Resort();
}
else
GetModel()->SetSortMode(SortNone);
nSortCol=nCol;
}
void SvxSimpleTable::HBarClick()
{
sal_uInt16 nId=aHeaderBar.GetCurItemId();
if (aHeaderBar.GetItemBits(nId) & HIB_CLICKABLE)
{
if(nId==nSortCol+1)
{
SortByCol(nId-1,!bSortDirection);
}
else
{
SortByCol(nId-1,bSortDirection);
}
aHeaderBarClickLink.Call(this);
}
}
void SvxSimpleTable::HBarDblClick()
{
aHeaderBarDblClickLink.Call(this);
}
void SvxSimpleTable::HBarStartDrag()
{
if(!aHeaderBar.IsItemMode())
{
Rectangle aSizeRect(Point(0,0),
SvHeaderTabListBox::GetOutputSizePixel());
aSizeRect.Left()=-GetXOffset()+aHeaderBar.GetDragPos();
aSizeRect.Right()=-GetXOffset()+aHeaderBar.GetDragPos();
ShowTracking( aSizeRect, SHOWTRACK_SPLIT );
}
}
void SvxSimpleTable::HBarDrag()
{
HideTracking();
if(!aHeaderBar.IsItemMode())
{
Rectangle aSizeRect(Point(0,0),
SvHeaderTabListBox::GetOutputSizePixel());
aSizeRect.Left()=-GetXOffset()+aHeaderBar.GetDragPos();
aSizeRect.Right()=-GetXOffset()+aHeaderBar.GetDragPos();
ShowTracking( aSizeRect, SHOWTRACK_SPLIT );
}
}
void SvxSimpleTable::HBarEndDrag()
{
HideTracking();
sal_uInt16 nPrivTabCount=TabCount();
if(nPrivTabCount)
{
if(nPrivTabCount>aHeaderBar.GetItemCount())
nPrivTabCount=aHeaderBar.GetItemCount();
sal_uInt16 nPos=0;
sal_uInt16 nNewSize=0;
for(sal_uInt16 i=1;i<nPrivTabCount;i++)
{
nNewSize = static_cast< sal_uInt16 >( aHeaderBar.GetItemSize(i) ) + nPos;
SetTab( i, nNewSize, MAP_PIXEL );
nPos = nNewSize;
}
}
bPaintFlag=sal_False;
Invalidate();
Update();
}
CommandEvent SvxSimpleTable::GetCommandEvent() const
{
return aCEvt;
}
void SvxSimpleTable::Command( const CommandEvent& rCEvt )
{
aCEvt=rCEvt;
aCommandLink.Call(this);
SvHeaderTabListBox::Command(rCEvt);
}
IMPL_LINK( SvxSimpleTable, StartDragHdl, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarStartDrag();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, DragHdl, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarDrag();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, EndDragHdl, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarEndDrag();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, HeaderBarClick, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarClick();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, HeaderBarDblClick, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarDblClick();
}
return 0;
}
SvLBoxItem* SvxSimpleTable::GetEntryAtPos( SvLBoxEntry* pEntry, sal_uInt16 nPos ) const
{
DBG_ASSERT(pEntry,"GetEntryText:Invalid Entry");
SvLBoxItem* pItem = NULL;
if( pEntry )
{
sal_uInt16 nCount = pEntry->ItemCount();
nPos++;
if( nTreeFlags & TREEFLAG_CHKBTN ) nPos++;
if( nPos < nCount )
{
pItem = pEntry->GetItem( nPos);
}
}
return pItem;
}
StringCompare SvxSimpleTable::ColCompare(SvLBoxEntry* pLeft,SvLBoxEntry* pRight)
{
StringCompare eCompare=COMPARE_EQUAL;
SvLBoxItem* pLeftItem = GetEntryAtPos( pLeft, nSortCol);
SvLBoxItem* pRightItem = GetEntryAtPos( pRight, nSortCol);
if(pLeftItem != NULL && pRightItem != NULL)
{
sal_uInt16 nLeftKind=pLeftItem->IsA();
sal_uInt16 nRightKind=pRightItem->IsA();
if(nRightKind == SV_ITEM_ID_LBOXSTRING &&
nLeftKind == SV_ITEM_ID_LBOXSTRING )
{
IntlWrapper aIntlWrapper( ::comphelper::getProcessServiceFactory(), Application::GetSettings().GetLocale() );
const CollatorWrapper* pCollator = aIntlWrapper.getCaseCollator();
eCompare=(StringCompare)pCollator->compareString( ((SvLBoxString*)pLeftItem)->GetText(),
((SvLBoxString*)pRightItem)->GetText());
if(eCompare==COMPARE_EQUAL) eCompare=COMPARE_LESS;
}
}
return eCompare;
}
IMPL_LINK( SvxSimpleTable, CompareHdl, SvSortData*, pData)
{
SvLBoxEntry* pLeft = (SvLBoxEntry*)(pData->pLeft );
SvLBoxEntry* pRight = (SvLBoxEntry*)(pData->pRight );
return (long) ColCompare(pLeft,pRight);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Resolves: fdo#49340 GetFocus during dtoring causes reentry to dying window<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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.
*
************************************************************************/
// INCLUDE -------------------------------------------------------------------
#include <svx/simptabl.hxx>
#include <vcl/svapp.hxx>
#include <comphelper/processfactory.hxx>
#include <unotools/intlwrapper.hxx>
// SvxSimpleTableContainer ------------------------------------------------------
SvxSimpleTableContainer::SvxSimpleTableContainer( Window* pParent, const ResId& rResId)
: Control(pParent, rResId)
, m_pTable(NULL)
{
SetBorderStyle(WINDOW_BORDER_NOBORDER);
}
void SvxSimpleTableContainer::SetTable(SvxSimpleTable* pTable)
{
m_pTable = pTable;
}
long SvxSimpleTableContainer::PreNotify( NotifyEvent& rNEvt )
{
long nResult = sal_True;
if ( rNEvt.GetType() == EVENT_KEYINPUT )
{
const KeyCode& aKeyCode = rNEvt.GetKeyEvent()->GetKeyCode();
sal_uInt16 nKey = aKeyCode.GetCode();
if (nKey == KEY_TAB)
GetParent()->Notify( rNEvt );
else if (m_pTable && m_pTable->IsFocusOnCellEnabled() && ( nKey == KEY_LEFT || nKey == KEY_RIGHT))
return 0;
else
nResult = Control::PreNotify( rNEvt );
}
else
nResult = Control::PreNotify( rNEvt );
return nResult;
}
void SvxSimpleTableContainer::SetSizePixel(const Size& rNewSize )
{
Control::SetSizePixel(rNewSize);
if (m_pTable)
m_pTable->UpdateViewSize();
}
void SvxSimpleTableContainer::GetFocus()
{
Control::GetFocus();
if (m_pTable)
m_pTable->GrabFocus();
}
// SvxSimpleTable ------------------------------------------------------------
SvxSimpleTable::SvxSimpleTable(SvxSimpleTableContainer& rParent, WinBits nBits):
SvHeaderTabListBox(&rParent, nBits | WB_CLIPCHILDREN | WB_HSCROLL | WB_TABSTOP),
m_rParentTableContainer(rParent),
aHeaderBar(&rParent,WB_BUTTONSTYLE | WB_BORDER | WB_TABSTOP),
nHeaderItemId(1),
bResizeFlag(sal_False),
bPaintFlag(sal_True)
{
m_rParentTableContainer.SetTable(this);
bSortDirection=sal_True;
nSortCol=0xFFFF;
nOldPos=0;
aHeaderBar.SetStartDragHdl(LINK( this, SvxSimpleTable, StartDragHdl));
aHeaderBar.SetDragHdl(LINK( this, SvxSimpleTable, DragHdl));
aHeaderBar.SetEndDragHdl(LINK( this, SvxSimpleTable, EndDragHdl));
aHeaderBar.SetSelectHdl(LINK( this, SvxSimpleTable, HeaderBarClick));
aHeaderBar.SetDoubleClickHdl(LINK( this, SvxSimpleTable, HeaderBarDblClick));
EnableCellFocus();
DisableTransientChildren();
InitHeaderBar( &aHeaderBar );
UpdateViewSize();
aHeaderBar.Show();
SvHeaderTabListBox::Show();
}
SvxSimpleTable::~SvxSimpleTable()
{
m_rParentTableContainer.SetTable(NULL);
}
void SvxSimpleTable::UpdateViewSize()
{
Size theWinSize=m_rParentTableContainer.GetSizePixel();
Size HbSize=aHeaderBar.GetSizePixel();
HbSize.Width()=theWinSize.Width();
theWinSize.Height()-=HbSize.Height();
Point thePos(0,0);
aHeaderBar.SetPosPixel(thePos);
aHeaderBar.SetSizePixel(HbSize);
thePos.Y()+=HbSize.Height();
SvHeaderTabListBox::SetPosPixel(thePos);
SvHeaderTabListBox::SetSizePixel(theWinSize);
Invalidate();
}
void SvxSimpleTable::NotifyScrolled()
{
long nOffset=-GetXOffset();
if(nOldPos!=nOffset)
{
aHeaderBar.SetOffset(nOffset);
aHeaderBar.Invalidate();
aHeaderBar.Update();
nOldPos=nOffset;
}
SvHeaderTabListBox::NotifyScrolled();
}
void SvxSimpleTable::SetTabs()
{
SvHeaderTabListBox::SetTabs();
sal_uInt16 nPrivTabCount = TabCount();
if ( nPrivTabCount )
{
if ( nPrivTabCount > aHeaderBar.GetItemCount() )
nPrivTabCount = aHeaderBar.GetItemCount();
sal_uInt16 i, nNewSize = static_cast< sal_uInt16 >( GetTab(0) ), nPos = 0;
for ( i = 1; i < nPrivTabCount; ++i )
{
nNewSize = static_cast< sal_uInt16 >( GetTab(i) ) - nPos;
aHeaderBar.SetItemSize( i, nNewSize );
nPos = (sal_uInt16)GetTab(i);
}
aHeaderBar.SetItemSize( i, HEADERBAR_FULLSIZE ); // because no tab for last entry
}
}
void SvxSimpleTable::SetTabs( long* pTabs, MapUnit eMapUnit)
{
SvHeaderTabListBox::SetTabs(pTabs,eMapUnit);
}
void SvxSimpleTable::Paint( const Rectangle& rRect )
{
SvHeaderTabListBox::Paint(rRect );
sal_uInt16 nPrivTabCount = TabCount();
sal_uInt16 nNewSize = ( nPrivTabCount > 0 ) ? (sal_uInt16)GetTab(0) : 0;
long nOffset=-GetXOffset();
nOldPos=nOffset;
aHeaderBar.SetOffset(nOffset);
aHeaderBar.Invalidate();
if(nPrivTabCount && bPaintFlag)
{
if(nPrivTabCount>aHeaderBar.GetItemCount())
nPrivTabCount=aHeaderBar.GetItemCount();
sal_uInt16 nPos = 0;
for(sal_uInt16 i=1;i<nPrivTabCount;i++)
{
nNewSize = static_cast< sal_uInt16 >( GetTab(i) ) - nPos;
aHeaderBar.SetItemSize( i, nNewSize );
nPos= static_cast< sal_uInt16 >( GetTab(i) );
}
}
bPaintFlag=sal_True;
}
void SvxSimpleTable::InsertHeaderEntry(const rtl::OUString& rText,
sal_uInt16 nCol, HeaderBarItemBits nBits)
{
sal_Int32 nEnd = rText.indexOf( sal_Unicode( '\t' ) );
if( nEnd == -1 )
{
aHeaderBar.InsertItem(nHeaderItemId++, rText, 0, nBits, nCol);
}
else
{
sal_Int32 nIndex = 0;
do
{
rtl::OUString aString = rText.getToken(0, '\t', nIndex);
aHeaderBar.InsertItem(nHeaderItemId++, aString, 0, nBits, nCol);
}
while ( nIndex >= 0 );
}
SetTabs();
}
void SvxSimpleTable::ClearHeader()
{
aHeaderBar.Clear();
}
void SvxSimpleTable::ShowTable()
{
m_rParentTableContainer.Show();
}
void SvxSimpleTable::HideTable()
{
m_rParentTableContainer.Hide();
}
sal_Bool SvxSimpleTable::IsVisible() const
{
return m_rParentTableContainer.IsVisible();
}
void SvxSimpleTable::EnableTable()
{
m_rParentTableContainer.Enable();
}
void SvxSimpleTable::DisableTable()
{
m_rParentTableContainer.Disable();
}
sal_Bool SvxSimpleTable::IsEnabled() const
{
return m_rParentTableContainer.IsEnabled();
}
sal_uInt16 SvxSimpleTable::GetSelectedCol()
{
return (aHeaderBar.GetCurItemId()-1);
}
void SvxSimpleTable::SortByCol(sal_uInt16 nCol,sal_Bool bDir)
{
bSortDirection=bDir;
if(nSortCol!=0xFFFF)
aHeaderBar.SetItemBits(nSortCol+1,HIB_STDSTYLE);
if (nCol != 0xFFFF)
{
if(bDir)
{
aHeaderBar.SetItemBits( nCol+1, HIB_STDSTYLE | HIB_DOWNARROW);
GetModel()->SetSortMode(SortAscending);
}
else
{
aHeaderBar.SetItemBits( nCol+1, HIB_STDSTYLE | HIB_UPARROW);
GetModel()->SetSortMode(SortDescending);
}
nSortCol=nCol;
GetModel()->SetCompareHdl( LINK( this, SvxSimpleTable, CompareHdl));
GetModel()->Resort();
}
else
GetModel()->SetSortMode(SortNone);
nSortCol=nCol;
}
void SvxSimpleTable::HBarClick()
{
sal_uInt16 nId=aHeaderBar.GetCurItemId();
if (aHeaderBar.GetItemBits(nId) & HIB_CLICKABLE)
{
if(nId==nSortCol+1)
{
SortByCol(nId-1,!bSortDirection);
}
else
{
SortByCol(nId-1,bSortDirection);
}
aHeaderBarClickLink.Call(this);
}
}
void SvxSimpleTable::HBarDblClick()
{
aHeaderBarDblClickLink.Call(this);
}
void SvxSimpleTable::HBarStartDrag()
{
if(!aHeaderBar.IsItemMode())
{
Rectangle aSizeRect(Point(0,0),
SvHeaderTabListBox::GetOutputSizePixel());
aSizeRect.Left()=-GetXOffset()+aHeaderBar.GetDragPos();
aSizeRect.Right()=-GetXOffset()+aHeaderBar.GetDragPos();
ShowTracking( aSizeRect, SHOWTRACK_SPLIT );
}
}
void SvxSimpleTable::HBarDrag()
{
HideTracking();
if(!aHeaderBar.IsItemMode())
{
Rectangle aSizeRect(Point(0,0),
SvHeaderTabListBox::GetOutputSizePixel());
aSizeRect.Left()=-GetXOffset()+aHeaderBar.GetDragPos();
aSizeRect.Right()=-GetXOffset()+aHeaderBar.GetDragPos();
ShowTracking( aSizeRect, SHOWTRACK_SPLIT );
}
}
void SvxSimpleTable::HBarEndDrag()
{
HideTracking();
sal_uInt16 nPrivTabCount=TabCount();
if(nPrivTabCount)
{
if(nPrivTabCount>aHeaderBar.GetItemCount())
nPrivTabCount=aHeaderBar.GetItemCount();
sal_uInt16 nPos=0;
sal_uInt16 nNewSize=0;
for(sal_uInt16 i=1;i<nPrivTabCount;i++)
{
nNewSize = static_cast< sal_uInt16 >( aHeaderBar.GetItemSize(i) ) + nPos;
SetTab( i, nNewSize, MAP_PIXEL );
nPos = nNewSize;
}
}
bPaintFlag=sal_False;
Invalidate();
Update();
}
CommandEvent SvxSimpleTable::GetCommandEvent() const
{
return aCEvt;
}
void SvxSimpleTable::Command( const CommandEvent& rCEvt )
{
aCEvt=rCEvt;
aCommandLink.Call(this);
SvHeaderTabListBox::Command(rCEvt);
}
IMPL_LINK( SvxSimpleTable, StartDragHdl, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarStartDrag();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, DragHdl, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarDrag();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, EndDragHdl, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarEndDrag();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, HeaderBarClick, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarClick();
}
return 0;
}
IMPL_LINK( SvxSimpleTable, HeaderBarDblClick, HeaderBar*, pCtr)
{
if(pCtr==&aHeaderBar)
{
HBarDblClick();
}
return 0;
}
SvLBoxItem* SvxSimpleTable::GetEntryAtPos( SvLBoxEntry* pEntry, sal_uInt16 nPos ) const
{
DBG_ASSERT(pEntry,"GetEntryText:Invalid Entry");
SvLBoxItem* pItem = NULL;
if( pEntry )
{
sal_uInt16 nCount = pEntry->ItemCount();
nPos++;
if( nTreeFlags & TREEFLAG_CHKBTN ) nPos++;
if( nPos < nCount )
{
pItem = pEntry->GetItem( nPos);
}
}
return pItem;
}
StringCompare SvxSimpleTable::ColCompare(SvLBoxEntry* pLeft,SvLBoxEntry* pRight)
{
StringCompare eCompare=COMPARE_EQUAL;
SvLBoxItem* pLeftItem = GetEntryAtPos( pLeft, nSortCol);
SvLBoxItem* pRightItem = GetEntryAtPos( pRight, nSortCol);
if(pLeftItem != NULL && pRightItem != NULL)
{
sal_uInt16 nLeftKind=pLeftItem->IsA();
sal_uInt16 nRightKind=pRightItem->IsA();
if(nRightKind == SV_ITEM_ID_LBOXSTRING &&
nLeftKind == SV_ITEM_ID_LBOXSTRING )
{
IntlWrapper aIntlWrapper( ::comphelper::getProcessServiceFactory(), Application::GetSettings().GetLocale() );
const CollatorWrapper* pCollator = aIntlWrapper.getCaseCollator();
eCompare=(StringCompare)pCollator->compareString( ((SvLBoxString*)pLeftItem)->GetText(),
((SvLBoxString*)pRightItem)->GetText());
if(eCompare==COMPARE_EQUAL) eCompare=COMPARE_LESS;
}
}
return eCompare;
}
IMPL_LINK( SvxSimpleTable, CompareHdl, SvSortData*, pData)
{
SvLBoxEntry* pLeft = (SvLBoxEntry*)(pData->pLeft );
SvLBoxEntry* pRight = (SvLBoxEntry*)(pData->pRight );
return (long) ColCompare(pLeft,pRight);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdtxhdl.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: ihi $ $Date: 2006-11-14 13:50:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVDTXHDL_HXX
#define _SVDTXHDL_HXX
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
//************************************************************
// Vorausdeklarationen
//************************************************************
class SdrOutliner;
class DrawPortionInfo;
class SdrTextObj;
class SdrObjGroup;
class SdrModel;
class XOutputDevice;
//************************************************************
// ImpTextPortionHandler
//************************************************************
class ImpTextPortionHandler
{
VirtualDevice aVDev;
Rectangle aFormTextBoundRect;
SdrOutliner& rOutliner;
const SdrTextObj& rTextObj;
XOutputDevice* pXOut;
// Variablen fuer ConvertToPathObj
SdrObjGroup* pGroup;
SdrModel* pModel;
FASTBOOL bToPoly;
// Variablen fuer DrawFitText
Point aPos;
Fraction aXFact;
Fraction aYFact;
// Variablen fuer DrawTextToPath
ULONG nParagraph;
BOOL bToLastPoint;
bool bDraw;
void* mpRecordPortions;
private:
// #101498#
void SortedAddFormTextRecordPortion(DrawPortionInfo* pInfo);
void DrawFormTextRecordPortions(Polygon aPoly);
void ClearFormTextRecordPortions();
sal_uInt32 GetFormTextPortionsLength(OutputDevice* pOut);
public:
ImpTextPortionHandler(SdrOutliner& rOutln, const SdrTextObj& rTxtObj);
void ConvertToPathObj(SdrObjGroup& rGroup, FASTBOOL bToPoly);
void DrawFitText(XOutputDevice& rXOut, const Point& rPos, const Fraction& rXFact);
void DrawTextToPath(XOutputDevice& rXOut, FASTBOOL bDrawEffect=TRUE);
// wird von DrawTextToPath() gesetzt:
const Rectangle& GetFormTextBoundRect() { return aFormTextBoundRect; }
DECL_LINK(ConvertHdl,DrawPortionInfo*);
DECL_LINK(FitTextDrawHdl,DrawPortionInfo*);
// #101498#
DECL_LINK(FormTextRecordPortionHdl, DrawPortionInfo*);
};
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDTXHDL_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.7.636); FILE MERGED 2008/04/01 15:51:45 thb 1.7.636.2: #i85898# Stripping all external header guards 2008/03/31 14:23:36 rt 1.7.636.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: svdtxhdl.hxx,v $
* $Revision: 1.8 $
*
* 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 _SVDTXHDL_HXX
#define _SVDTXHDL_HXX
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#include <tools/poly.hxx>
#include <tools/link.hxx>
//************************************************************
// Vorausdeklarationen
//************************************************************
class SdrOutliner;
class DrawPortionInfo;
class SdrTextObj;
class SdrObjGroup;
class SdrModel;
class XOutputDevice;
//************************************************************
// ImpTextPortionHandler
//************************************************************
class ImpTextPortionHandler
{
VirtualDevice aVDev;
Rectangle aFormTextBoundRect;
SdrOutliner& rOutliner;
const SdrTextObj& rTextObj;
XOutputDevice* pXOut;
// Variablen fuer ConvertToPathObj
SdrObjGroup* pGroup;
SdrModel* pModel;
FASTBOOL bToPoly;
// Variablen fuer DrawFitText
Point aPos;
Fraction aXFact;
Fraction aYFact;
// Variablen fuer DrawTextToPath
ULONG nParagraph;
BOOL bToLastPoint;
bool bDraw;
void* mpRecordPortions;
private:
// #101498#
void SortedAddFormTextRecordPortion(DrawPortionInfo* pInfo);
void DrawFormTextRecordPortions(Polygon aPoly);
void ClearFormTextRecordPortions();
sal_uInt32 GetFormTextPortionsLength(OutputDevice* pOut);
public:
ImpTextPortionHandler(SdrOutliner& rOutln, const SdrTextObj& rTxtObj);
void ConvertToPathObj(SdrObjGroup& rGroup, FASTBOOL bToPoly);
void DrawFitText(XOutputDevice& rXOut, const Point& rPos, const Fraction& rXFact);
void DrawTextToPath(XOutputDevice& rXOut, FASTBOOL bDrawEffect=TRUE);
// wird von DrawTextToPath() gesetzt:
const Rectangle& GetFormTextBoundRect() { return aFormTextBoundRect; }
DECL_LINK(ConvertHdl,DrawPortionInfo*);
DECL_LINK(FitTextDrawHdl,DrawPortionInfo*);
// #101498#
DECL_LINK(FormTextRecordPortionHdl, DrawPortionInfo*);
};
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDTXHDL_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: prtopt.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:46:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#pragma hdrstop
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Content/Graphic", // 0
"Content/Table", // 1
"Content/Control", // 2
"Content/Background", // 3
"Content/PrintBlack", // 4
"Content/Note", // 5
"Page/Reversed", // 6
"Page/Brochure", // 7
"Output/SinglePrintJob", // 8
"Output/Fax", // 9
"Papertray/FromPrinterSetup", // 10
"Content/Drawing", // 11 not in SW/Web
"Page/LeftPage", // 12 not in SW/Web
"Page/RightPage" // 13 not in SW/Web
};
const int nCount = bIsWeb ? 11 : 14;
Sequence<OUString> aNames(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
{
pNames[i] = OUString::createFromAscii(aPropNames[i]);
}
return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") : C2U("Office.Writer/Print"),
CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
bIsWeb(bWeb)
{
bPrintPageBackground = !bWeb;
bPrintBlackFont = bWeb;
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case 0: bPrintGraphic = *(sal_Bool*)pValues[nProp].getValue(); break;
case 1: bPrintTable = *(sal_Bool*)pValues[nProp].getValue(); break;
case 2: bPrintControl = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue(); break;
case 4: bPrintBlackFont = *(sal_Bool*)pValues[nProp].getValue(); break;
case 5:
{
sal_Int32 nTmp;
pValues[nProp] >>= nTmp;
nPrintPostIts = (sal_Int16)nTmp;
}
break;
case 6: bPrintReverse = *(sal_Bool*)pValues[nProp].getValue(); break;
case 7: bPrintProspect = *(sal_Bool*)pValues[nProp].getValue(); break;
case 8: bPrintSingleJobs = *(sal_Bool*)pValues[nProp].getValue(); break;
case 9: pValues[nProp] >>= sFaxName; break;
case 10: bPaperFromSetup = *(sal_Bool*)pValues[nProp].getValue(); break;
case 11: bPrintDraw = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 12: bPrintLeftPage = *(sal_Bool*)pValues[nProp].getValue(); break;
case 13: bPrintRightPage = *(sal_Bool*)pValues[nProp].getValue(); break;
}
}
}
}
}
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------
---------------------------------------------------------------------------*/
void SwPrintOptions::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
BOOL bVal;
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
switch(nProp)
{
case 0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
case 1: bVal = bPrintTable ;pValues[nProp].setValue(&bVal, rType); break;
case 2: bVal = bPrintControl ; pValues[nProp].setValue(&bVal, rType); break;
case 3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType); break;
case 4: bVal = bPrintBlackFont ; pValues[nProp].setValue(&bVal, rType); break;
case 5: pValues[nProp] <<= (sal_Int32)nPrintPostIts ; break;
case 6: bVal = bPrintReverse ; pValues[nProp].setValue(&bVal, rType); break;
case 7: bVal = bPrintProspect ; pValues[nProp].setValue(&bVal, rType); break;
case 8: bVal = bPrintSingleJobs ; pValues[nProp].setValue(&bVal, rType); break;
case 9: pValues[nProp] <<= sFaxName; break;
case 10: bVal = bPaperFromSetup ; pValues[nProp].setValue(&bVal, rType); break;
case 11: bVal = bPrintDraw ; pValues[nProp].setValue(&bVal, rType); break;
case 12: bVal = bPrintLeftPage ; pValues[nProp].setValue(&bVal, rType); break;
case 13: bVal = bPrintRightPage ; pValues[nProp].setValue(&bVal, rType); break;
}
}
PutProperties(aNames, aValues);
}
<commit_msg>INTEGRATION: CWS emptypage (1.7.154); FILE MERGED 2005/12/13 15:27:26 fme 1.7.154.1: #b6354161# Feature - Print empty pages<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: prtopt.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2005-12-21 15:12:19 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif
#ifndef _PRTOPT_HXX
#include <prtopt.hxx>
#endif
#ifndef _SWPRTOPT_HXX
#include <swprtopt.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
#define C2U(cChar) OUString::createFromAscii(cChar)
/*--------------------------------------------------------------------
Beschreibung: Ctor
--------------------------------------------------------------------*/
Sequence<OUString> SwPrintOptions::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Content/Graphic", // 0
"Content/Table", // 1
"Content/Control", // 2
"Content/Background", // 3
"Content/PrintBlack", // 4
"Content/Note", // 5
"Page/Reversed", // 6
"Page/Brochure", // 7
"Output/SinglePrintJob", // 8
"Output/Fax", // 9
"Papertray/FromPrinterSetup", // 10
"Content/Drawing", // 11 not in SW/Web
"Page/LeftPage", // 12 not in SW/Web
"Page/RightPage", // 13 not in SW/Web
"EmptyPages" // 14 not in SW/Web
};
const int nCount = bIsWeb ? 11 : 15;
Sequence<OUString> aNames(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
{
pNames[i] = OUString::createFromAscii(aPropNames[i]);
}
return aNames;
}
/* -----------------------------06.09.00 16:44--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::SwPrintOptions(sal_Bool bWeb) :
ConfigItem(bWeb ? C2U("Office.WriterWeb/Print") : C2U("Office.Writer/Print"),
CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE),
bIsWeb(bWeb)
{
bPrintPageBackground = !bWeb;
bPrintBlackFont = bWeb;
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
switch(nProp)
{
case 0: bPrintGraphic = *(sal_Bool*)pValues[nProp].getValue(); break;
case 1: bPrintTable = *(sal_Bool*)pValues[nProp].getValue(); break;
case 2: bPrintControl = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 3: bPrintPageBackground= *(sal_Bool*)pValues[nProp].getValue(); break;
case 4: bPrintBlackFont = *(sal_Bool*)pValues[nProp].getValue(); break;
case 5:
{
sal_Int32 nTmp;
pValues[nProp] >>= nTmp;
nPrintPostIts = (sal_Int16)nTmp;
}
break;
case 6: bPrintReverse = *(sal_Bool*)pValues[nProp].getValue(); break;
case 7: bPrintProspect = *(sal_Bool*)pValues[nProp].getValue(); break;
case 8: bPrintSingleJobs = *(sal_Bool*)pValues[nProp].getValue(); break;
case 9: pValues[nProp] >>= sFaxName; break;
case 10: bPaperFromSetup = *(sal_Bool*)pValues[nProp].getValue(); break;
case 11: bPrintDraw = *(sal_Bool*)pValues[nProp].getValue() ; break;
case 12: bPrintLeftPage = *(sal_Bool*)pValues[nProp].getValue(); break;
case 13: bPrintRightPage = *(sal_Bool*)pValues[nProp].getValue(); break;
case 14: bPrintEmptyPages = *(sal_Bool*)pValues[nProp].getValue(); break;
}
}
}
}
}
/* -----------------------------06.09.00 16:50--------------------------------
---------------------------------------------------------------------------*/
SwPrintOptions::~SwPrintOptions()
{
}
/* -----------------------------06.09.00 16:43--------------------------------
---------------------------------------------------------------------------*/
void SwPrintOptions::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
BOOL bVal;
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
switch(nProp)
{
case 0: bVal = bPrintGraphic; pValues[nProp].setValue(&bVal, rType);break;
case 1: bVal = bPrintTable ;pValues[nProp].setValue(&bVal, rType); break;
case 2: bVal = bPrintControl ; pValues[nProp].setValue(&bVal, rType); break;
case 3: bVal = bPrintPageBackground; pValues[nProp].setValue(&bVal, rType); break;
case 4: bVal = bPrintBlackFont ; pValues[nProp].setValue(&bVal, rType); break;
case 5: pValues[nProp] <<= (sal_Int32)nPrintPostIts ; break;
case 6: bVal = bPrintReverse ; pValues[nProp].setValue(&bVal, rType); break;
case 7: bVal = bPrintProspect ; pValues[nProp].setValue(&bVal, rType); break;
case 8: bVal = bPrintSingleJobs ; pValues[nProp].setValue(&bVal, rType); break;
case 9: pValues[nProp] <<= sFaxName; break;
case 10: bVal = bPaperFromSetup ; pValues[nProp].setValue(&bVal, rType); break;
case 11: bVal = bPrintDraw ; pValues[nProp].setValue(&bVal, rType); break;
case 12: bVal = bPrintLeftPage ; pValues[nProp].setValue(&bVal, rType); break;
case 13: bVal = bPrintRightPage ; pValues[nProp].setValue(&bVal, rType); break;
case 14: bVal = bPrintEmptyPages ; pValues[nProp].setValue(&bVal, rType); break;
}
}
PutProperties(aNames, aValues);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: envprt.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2004-08-23 08:50:51 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#pragma hdrstop
#ifndef _SV_PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif
#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif
#include "swtypes.hxx"
#include "cmdid.h"
#include "envprt.hxx"
#include "envlop.hxx"
#include "uitool.hxx"
#include "envprt.hrc"
SwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet) :
SfxTabPage(pParent, SW_RES(TP_ENV_PRT), rSet),
aAlignBox (this, SW_RES(BOX_ALIGN )),
aTopButton (this, SW_RES(BTN_TOP )),
aBottomButton(this, SW_RES(BTN_BOTTOM )),
aRightText (this, SW_RES(TXT_RIGHT )),
aRightField (this, SW_RES(FLD_RIGHT )),
aDownText (this, SW_RES(TXT_DOWN )),
aDownField (this, SW_RES(FLD_DOWN )),
aPrinterInfo (this, SW_RES(TXT_PRINTER)),
aNoNameFL (this, SW_RES(FL_NONAME )),
aPrinterFL (this, SW_RES(FL_PRINTER )),
aPrtSetup (this, SW_RES(BTN_PRTSETUP))
{
FreeResource();
SetExchangeSupport();
// Metriken
FieldUnit eUnit = ::GetDfltMetric(FALSE);
SetMetric(aRightField, eUnit);
SetMetric(aDownField , eUnit);
// Handler installieren
aTopButton .SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aBottomButton.SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aPrtSetup .SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));
// Bitmaps
aBottomButton.GetClickHdl().Call(&aBottomButton);
// ToolBox
Size aSz = aAlignBox.CalcWindowSizePixel();
aAlignBox.SetSizePixel(aSz);
// aAlignBox.SetPosPixel(Point(aNoNameFL.GetPosPixel().X() + (aNoNameFL.GetSizePixel().Width() - aSz.Width()) / 2, aAlignBox.GetPosPixel().Y()));
aAlignBox.SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));
}
// --------------------------------------------------------------------------
SwEnvPrtPage::~SwEnvPrtPage()
{
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ClickHdl, Button *, EMPTYARG )
{
sal_Bool bHC = GetDisplayBackground().GetColor().IsDark();
if (aBottomButton.IsChecked())
{
// Briefumschlaege von unten
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_LOWER_H : BMP_HOR_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_LOWER_H : BMP_HOR_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_LOWER_H : BMP_HOR_RGHT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_LOWER_H : BMP_VER_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_LOWER_H : BMP_VER_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_LOWER_H : BMP_VER_RGHT_LOWER)));
}
else
{
// Briefumschlaege von oben
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_UPPER_H : BMP_HOR_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_UPPER_H : BMP_HOR_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_UPPER_H : BMP_HOR_RGHT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_UPPER_H : BMP_VER_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_UPPER_H : BMP_VER_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_UPPER_H : BMP_VER_RGHT_UPPER)));
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )
{
if (pBtn == &aPrtSetup)
{
// Druck-Setup aufrufen
if (pPrt)
{
PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
pDlg->SetPrinter(pPrt);
pDlg->Execute();
delete pDlg;
GrabFocus();
aPrinterInfo.SetText(pPrt->GetName());
}
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, AlignHdl, ToolBox *, EMPTYARG )
{
if (aAlignBox.GetCurItemId())
{
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT; i++)
aAlignBox.CheckItem(i, FALSE);
aAlignBox.CheckItem(aAlignBox.GetCurItemId(), TRUE);
}
else
{
// GetCurItemId() == 0 ist moeglich!
const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT, TRUE);
}
return 0;
}
// --------------------------------------------------------------------------
SfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
return new SwEnvPrtPage(pParent, rSet);
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::ActivatePage(const SfxItemSet& rSet)
{
if (pPrt)
aPrinterInfo.SetText(pPrt->GetName());
}
// --------------------------------------------------------------------------
int SwEnvPrtPage::DeactivatePage(SfxItemSet* pSet)
{
if( pSet )
FillItemSet(*pSet);
return SfxTabPage::LEAVE_PAGE;
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::FillItem(SwEnvItem& rItem)
{
USHORT nID = 0;
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT && !nID; i++)
if (aAlignBox.IsItemChecked(i))
nID = i;
rItem.eAlign = (SwEnvAlign) (nID - ITM_HOR_LEFT);
rItem.bPrintFromAbove = aTopButton.IsChecked();
rItem.lShiftRight = GetFldVal(aRightField);
rItem.lShiftDown = GetFldVal(aDownField );
}
// --------------------------------------------------------------------------
BOOL SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)
{
FillItem(GetParent()->aEnvItem);
rSet.Put(GetParent()->aEnvItem);
return TRUE;
}
// ----------------------------------------------------------------------------
void SwEnvPrtPage::Reset(const SfxItemSet& rSet)
{
// SfxItemSet aSet(rSet);
// aSet.Put(GetParent()->aEnvItem);
// Item auslesen
const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT);
if (rItem.bPrintFromAbove)
aTopButton .Check();
else
aBottomButton.Check();
SetFldVal(aRightField, rItem.lShiftRight);
SetFldVal(aDownField , rItem.lShiftDown );
ActivatePage(rSet);
ClickHdl(&aTopButton);
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.8.596); FILE MERGED 2005/09/05 13:44:12 rt 1.8.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: envprt.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-09 07:26:25 $
*
* 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
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#pragma hdrstop
#ifndef _SV_PRINT_HXX //autogen
#include <vcl/print.hxx>
#endif
#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif
#include "swtypes.hxx"
#include "cmdid.h"
#include "envprt.hxx"
#include "envlop.hxx"
#include "uitool.hxx"
#include "envprt.hrc"
SwEnvPrtPage::SwEnvPrtPage(Window* pParent, const SfxItemSet& rSet) :
SfxTabPage(pParent, SW_RES(TP_ENV_PRT), rSet),
aAlignBox (this, SW_RES(BOX_ALIGN )),
aTopButton (this, SW_RES(BTN_TOP )),
aBottomButton(this, SW_RES(BTN_BOTTOM )),
aRightText (this, SW_RES(TXT_RIGHT )),
aRightField (this, SW_RES(FLD_RIGHT )),
aDownText (this, SW_RES(TXT_DOWN )),
aDownField (this, SW_RES(FLD_DOWN )),
aPrinterInfo (this, SW_RES(TXT_PRINTER)),
aNoNameFL (this, SW_RES(FL_NONAME )),
aPrinterFL (this, SW_RES(FL_PRINTER )),
aPrtSetup (this, SW_RES(BTN_PRTSETUP))
{
FreeResource();
SetExchangeSupport();
// Metriken
FieldUnit eUnit = ::GetDfltMetric(FALSE);
SetMetric(aRightField, eUnit);
SetMetric(aDownField , eUnit);
// Handler installieren
aTopButton .SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aBottomButton.SetClickHdl(LINK(this, SwEnvPrtPage, ClickHdl));
aPrtSetup .SetClickHdl(LINK(this, SwEnvPrtPage, ButtonHdl));
// Bitmaps
aBottomButton.GetClickHdl().Call(&aBottomButton);
// ToolBox
Size aSz = aAlignBox.CalcWindowSizePixel();
aAlignBox.SetSizePixel(aSz);
// aAlignBox.SetPosPixel(Point(aNoNameFL.GetPosPixel().X() + (aNoNameFL.GetSizePixel().Width() - aSz.Width()) / 2, aAlignBox.GetPosPixel().Y()));
aAlignBox.SetClickHdl(LINK(this, SwEnvPrtPage, AlignHdl));
}
// --------------------------------------------------------------------------
SwEnvPrtPage::~SwEnvPrtPage()
{
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ClickHdl, Button *, EMPTYARG )
{
sal_Bool bHC = GetDisplayBackground().GetColor().IsDark();
if (aBottomButton.IsChecked())
{
// Briefumschlaege von unten
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_LOWER_H : BMP_HOR_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_LOWER_H : BMP_HOR_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_LOWER_H : BMP_HOR_RGHT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_LOWER_H : BMP_VER_LEFT_LOWER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_LOWER_H : BMP_VER_CNTR_LOWER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_LOWER_H : BMP_VER_RGHT_LOWER)));
}
else
{
// Briefumschlaege von oben
aAlignBox.SetItemImage(ITM_HOR_LEFT, Bitmap(SW_RES(bHC ? BMP_HOR_LEFT_UPPER_H : BMP_HOR_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_CNTR, Bitmap(SW_RES(bHC ? BMP_HOR_CNTR_UPPER_H : BMP_HOR_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_HOR_RGHT, Bitmap(SW_RES(bHC ? BMP_HOR_RGHT_UPPER_H : BMP_HOR_RGHT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_LEFT, Bitmap(SW_RES(bHC ? BMP_VER_LEFT_UPPER_H : BMP_VER_LEFT_UPPER)));
aAlignBox.SetItemImage(ITM_VER_CNTR, Bitmap(SW_RES(bHC ? BMP_VER_CNTR_UPPER_H : BMP_VER_CNTR_UPPER)));
aAlignBox.SetItemImage(ITM_VER_RGHT, Bitmap(SW_RES(bHC ? BMP_VER_RGHT_UPPER_H : BMP_VER_RGHT_UPPER)));
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, ButtonHdl, Button *, pBtn )
{
if (pBtn == &aPrtSetup)
{
// Druck-Setup aufrufen
if (pPrt)
{
PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
pDlg->SetPrinter(pPrt);
pDlg->Execute();
delete pDlg;
GrabFocus();
aPrinterInfo.SetText(pPrt->GetName());
}
}
return 0;
}
// --------------------------------------------------------------------------
IMPL_LINK( SwEnvPrtPage, AlignHdl, ToolBox *, EMPTYARG )
{
if (aAlignBox.GetCurItemId())
{
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT; i++)
aAlignBox.CheckItem(i, FALSE);
aAlignBox.CheckItem(aAlignBox.GetCurItemId(), TRUE);
}
else
{
// GetCurItemId() == 0 ist moeglich!
const SwEnvItem& rItem = (const SwEnvItem&) GetItemSet().Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT, TRUE);
}
return 0;
}
// --------------------------------------------------------------------------
SfxTabPage* SwEnvPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
return new SwEnvPrtPage(pParent, rSet);
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::ActivatePage(const SfxItemSet& rSet)
{
if (pPrt)
aPrinterInfo.SetText(pPrt->GetName());
}
// --------------------------------------------------------------------------
int SwEnvPrtPage::DeactivatePage(SfxItemSet* pSet)
{
if( pSet )
FillItemSet(*pSet);
return SfxTabPage::LEAVE_PAGE;
}
// --------------------------------------------------------------------------
void SwEnvPrtPage::FillItem(SwEnvItem& rItem)
{
USHORT nID = 0;
for (USHORT i = ITM_HOR_LEFT; i <= ITM_VER_RGHT && !nID; i++)
if (aAlignBox.IsItemChecked(i))
nID = i;
rItem.eAlign = (SwEnvAlign) (nID - ITM_HOR_LEFT);
rItem.bPrintFromAbove = aTopButton.IsChecked();
rItem.lShiftRight = GetFldVal(aRightField);
rItem.lShiftDown = GetFldVal(aDownField );
}
// --------------------------------------------------------------------------
BOOL SwEnvPrtPage::FillItemSet(SfxItemSet& rSet)
{
FillItem(GetParent()->aEnvItem);
rSet.Put(GetParent()->aEnvItem);
return TRUE;
}
// ----------------------------------------------------------------------------
void SwEnvPrtPage::Reset(const SfxItemSet& rSet)
{
// SfxItemSet aSet(rSet);
// aSet.Put(GetParent()->aEnvItem);
// Item auslesen
const SwEnvItem& rItem = (const SwEnvItem&) rSet.Get(FN_ENVELOP);
aAlignBox.CheckItem((USHORT) rItem.eAlign + ITM_HOR_LEFT);
if (rItem.bPrintFromAbove)
aTopButton .Check();
else
aBottomButton.Check();
SetFldVal(aRightField, rItem.lShiftRight);
SetFldVal(aDownField , rItem.lShiftDown );
ActivatePage(rSet);
ClickHdl(&aTopButton);
}
<|endoftext|>
|
<commit_before>createTriggerDescriptor_pp()
{
// create Trigger Descriptor for p-p interactions
AliTriggerDescriptor descrip( "p-p", "Default p-p Descriptor" );
// Define a Cluster Detector
//descrip.AddDetectorCluster( "ALL" );
descrip.AddDetectorCluster( "ITS START VZERO TOF" ); // no CRT yet
descrip.AddCondition( "VZERO_LEFT", "VZERO_LEFT", "VZERO A (Left)", (ULong64_t)0x1 );
descrip.AddCondition( "VZERO_RIGHT", "VZERO_RIGHT", "VZERO C (Right)", (ULong64_t)0x1 << 1 );
descrip.AddCondition( "VZERO_BEAMGAS", "VZERO_BEAMGAS", "VZERO beam gas rejection", (ULong64_t)0x1 << 2 );
descrip.AddCondition( "START_A_L0", "START_A_L0", "START A (Left)", (ULong64_t)0x1 << 3 );
descrip.AddCondition( "START_C_L0", "START_C_L0", "START C (Right)", (ULong64_t)0x1 << 4 );
descrip.AddCondition( "ITS_SPD_GFO_L0", "ITS_SPD_GFO_L0", "SPD global fast-or", (ULong64_t)0x1 << 5 );
descrip.AddCondition( "ITS_SPD_HMULT_L0","ITS_SPD_HMULT_L0","SPD high mult. 100 ", (ULong64_t)0x1 << 6 );
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND",
"MB",
"Minimum Bias",
(ULong64_t)0x1 << 7 );
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND | TOF_pp_MB_L0",
"MB-TOF",
"Minimum Bias with TOF",
(ULong64_t)0x1 << 8 );
cout << endl << endl;
if( !descrip.CheckInputsConditions("Config.C") ) {
cerr << "\n ERROR: There are some problems on descriptor definition..." << endl;
return;
}
cout << endl << endl;
cout << "************************************************************" << endl;
cout << "New Trigger descriptor" << endl;
cout << "************************************************************" << endl;
descrip.Print();
// save the descriptor to file
descrip.WriteDescriptor();
cout << endl << endl << endl;
cout << "************************************************************" << endl;
cout << "Available Trigger descriptors" << endl;
cout << "************************************************************" << endl;
// Get and print all available descriptors
TObjArray* desc = AliTriggerDescriptor::GetAvailableDescriptors();
if( !desc || !desc->GetEntriesFast() ) {
cerr << "Not descriptors availables" << endl;
return;
}
Int_t ndesc = desc->GetEntriesFast();
for( Int_t j=0; j<ndesc; j++ ) {
AliTriggerDescriptor* de = (AliTriggerDescriptor*)desc->At(j);
de->Print();
}
}
<commit_msg>MUON trigger inputs added to proton-proton CTP configuration<commit_after>createTriggerDescriptor_pp()
{
// create Trigger Descriptor for p-p interactions
AliTriggerDescriptor descrip( "p-p", "Default p-p Descriptor" );
// Define a Cluster Detector
//descrip.AddDetectorCluster( "ALL" );
descrip.AddDetectorCluster( "ITS START VZERO MUON TOF" ); // no CRT yet
// standalong V0 inputs
descrip.AddCondition( "VZERO_LEFT", "VZERO_LEFT", "VZERO A (Left)", (ULong64_t)0x1 );
descrip.AddCondition( "VZERO_RIGHT", "VZERO_RIGHT", "VZERO C (Right)", (ULong64_t)0x1 << 1 );
descrip.AddCondition( "VZERO_BEAMGAS", "VZERO_BEAMGAS", "VZERO beam gas rejection", (ULong64_t)0x1 << 2 );
// standalong T0 inputs
descrip.AddCondition( "START_A_L0", "START_A_L0", "START A (Left)", (ULong64_t)0x1 << 3 );
descrip.AddCondition( "START_C_L0", "START_C_L0", "START C (Right)", (ULong64_t)0x1 << 4 );
// standalong ITS-SPD inputs
descrip.AddCondition( "ITS_SPD_GFO_L0", "ITS_SPD_GFO_L0", "SPD global fast-or", (ULong64_t)0x1 << 5 );
descrip.AddCondition( "ITS_SPD_HMULT_L0","ITS_SPD_HMULT_L0","SPD high mult. 100 ", (ULong64_t)0x1 << 6 );
// standalong MUON inputs
descrip.AddCondition( "MUON_SPlus_LPt_L0",
"MUON_SPlus_LPt_L0", "Muon Plus Low Pt",
(ULong64_t)0x1 << 7 );
descrip.AddCondition( "MUON_Unlike_LPt_L0",
"MUON_Unlike_LPt_L0", "Di Muon Unlike sign Low Pt",
(ULong64_t)0x1 << 8 );
descrip.AddCondition( "MUON_Unlike_HPt_L0",
"MUON_Unlike_HPt_L0", "Di Muon Unlike sign High Pt",
(ULong64_t)0x1 << 9 );
descrip.AddCondition( "MUON_Like_LPt_L0",
"MUON_Like_LPt_L0", "Di Muon Like sign Low Pt",
(ULong64_t)0x1 << 10 );
descrip.AddCondition( "MUON_Like_HPt_L0",
"MUON_Like_HPt_L0", "Di Muon Like sign High Pt",
(ULong64_t)0x1 << 11 );
// combinations
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND",
"MB", "Minimum Bias",
(ULong64_t)0x1 << 12 );
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND | TOF_pp_MB_L0",
"MB-TOF",
"Minimum Bias with TOF",
(ULong64_t)0x1 << 13 );
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND & MUON_SPlus_LPt_L0",
"MUONSingle_MB", "Muon Single Low Pt Minimum Bias",
(ULong64_t)0x1 << 14 );
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND & MUON_Unlike_LPt_L0",
"MUONUnlikeLPt_MB", "Muon Unlike Low Pt Minimum Bias",
(ULong64_t)0x1 << 15 );
descrip.AddCondition( "ITS_SPD_GFO_L0 & VZERO_AND & MUON_Like_LPt_L0",
"MUONLikeLPt_MB", "Muon Like Low Pt Minimum Bias",
(ULong64_t)0x1 << 16 );
cout << endl << endl;
if( !descrip.CheckInputsConditions("Config.C") ) {
cerr << "\n ERROR: There are some problems on descriptor definition..." << endl;
return;
}
cout << endl << endl;
cout << "************************************************************" << endl;
cout << "New Trigger descriptor" << endl;
cout << "************************************************************" << endl;
descrip.Print();
// save the descriptor to file
descrip.WriteDescriptor();
cout << endl << endl << endl;
cout << "************************************************************" << endl;
cout << "Available Trigger descriptors" << endl;
cout << "************************************************************" << endl;
// Get and print all available descriptors
TObjArray* desc = AliTriggerDescriptor::GetAvailableDescriptors();
if( !desc || !desc->GetEntriesFast() ) {
cerr << "Not descriptors availables" << endl;
return;
}
Int_t ndesc = desc->GetEntriesFast();
for( Int_t j=0; j<ndesc; j++ ) {
AliTriggerDescriptor* de = (AliTriggerDescriptor*)desc->At(j);
de->Print();
}
}
<|endoftext|>
|
<commit_before>//
// MFMDiskController.hpp
// Clock Signal
//
// Created by Thomas Harte on 05/08/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef MFMDiskController_hpp
#define MFMDiskController_hpp
#include "DiskController.hpp"
#include "../../NumberTheory/CRC.hpp"
#include "../../ClockReceiver/ClockReceiver.hpp"
namespace Storage {
namespace Disk {
/*!
Extends Controller with a built-in shift register and FM/MFM decoding logic,
being able to post event messages to subclasses.
*/
class MFMController: public Controller {
public:
MFMController(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute);
protected:
void set_is_double_density(bool);
bool get_is_double_density();
enum DataMode {
Scanning,
Reading,
Writing
};
void set_data_mode(DataMode);
struct Token {
enum Type {
Index, ID, Data, DeletedData, Sync, Byte
} type;
uint8_t byte_value;
};
Token get_latest_token();
// Events
enum class Event: int {
Command = (1 << 0), // Indicates receipt of a new command.
Token = (1 << 1), // Indicates recognition of a new token in the flux stream. Use get_latest_token() for more details.
IndexHole = (1 << 2), // Indicates the passing of a physical index hole.
HeadLoad = (1 << 3), // Indicates the head has been loaded.
DataWritten = (1 << 4), // Indicates that all queued bits have been written
};
virtual void posit_event(Event type) = 0;
private:
// Storage::Disk::Controller
virtual void process_input_bit(int value, unsigned int cycles_since_index_hole);
virtual void process_index_hole();
virtual void process_write_completed();
// PLL input state
int bits_since_token_;
int shift_register_;
bool is_awaiting_marker_value_;
// input configuration
bool is_double_density_;
DataMode data_mode_;
// output
Token latest_token_;
// CRC generator
NumberTheory::CRC16 crc_generator_;
};
}
}
#endif /* MFMDiskController_hpp */
<commit_msg>Documented, and removed a couple of Event types that are WD-specific but had accidentally flown into here. Will need to figure out how best to expose the CRC result too, but I'm willing to let that one drop out naturally as I implement the 8272.<commit_after>//
// MFMDiskController.hpp
// Clock Signal
//
// Created by Thomas Harte on 05/08/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#ifndef MFMDiskController_hpp
#define MFMDiskController_hpp
#include "DiskController.hpp"
#include "../../NumberTheory/CRC.hpp"
#include "../../ClockReceiver/ClockReceiver.hpp"
namespace Storage {
namespace Disk {
/*!
Extends Controller with a built-in shift register and FM/MFM decoding logic,
being able to post event messages to subclasses.
*/
class MFMController: public Controller {
public:
MFMController(Cycles clock_rate, int clock_rate_multiplier, int revolutions_per_minute);
protected:
/// Indicates whether the controller should try to decode double-density MFM content, or single-density FM content.
void set_is_double_density(bool);
/// @returns @c true if currently decoding MFM content; @c false otherwise.
bool get_is_double_density();
enum DataMode {
/// When the controller is scanning it will obey all synchronisation marks found, even if in the middle of data.
Scanning,
/// When the controller is reading it will ignore synchronisation marks and simply return a new token every sixteen PLL clocks.
Reading,
/// When the controller is writing, it will replace the underlying data with that which has been enqueued, posting Event::DataWritten when the queue is empty.
Writing
};
/// Sets the current data mode.
void set_data_mode(DataMode);
/*!
Describes a token found in the incoming PLL bit stream. Tokens can be one of:
Index: the bit pattern usually encoded at the start of a track to denote the position of the index hole;
ID: the pattern that begins an ID section, i.e. a sector header, announcing sector number, track number, etc.
Data: the pattern that begins a data section, i.e. sector contents.
DeletedData: the pattern that begins a deleted data section, i.e. deleted sector contents.
Sync: MFM only; the same synchronisation mark is used in MFM to denote the bottom three of the four types
of token listed above; this class combines notification of that mark and the distinct index sync mark.
Both are followed by a byte to indicate type. When scanning an MFM stream, subclasses will receive an
announcement of sync followed by an announcement of one of the above four types of token.
Byte: reports reading of an ordinary byte, with expected timing bits.
When the data mode is set to 'reading', only Byte tokens are returned; detection of the other kinds of token
is suppressed. Controllers will likely want to switch data mode when receiving ID and sector contents, as
spurious sync signals can otherwise be found in ordinary data, causing framing errors.
*/
struct Token {
enum Type {
Index, ID, Data, DeletedData, Sync, Byte
} type;
uint8_t byte_value;
};
/// @returns The most-recently read token from the surface of the disk.
Token get_latest_token();
// Events
enum class Event: int {
Token = (1 << 0), // Indicates recognition of a new token in the flux stream. Use get_latest_token() for more details.
IndexHole = (1 << 1), // Indicates the passing of a physical index hole.
DataWritten = (1 << 2), // Indicates that all queued bits have been written
};
/*!
Subclasses should implement this. It is called every time a new @c Event is discovered in the incoming data stream.
Therefore it is called to announce when:
(i) a new token is discovered in the incoming stream: an index, ID, data or deleted data, a sync mark or a new byte of data.
(ii) the index hole passes; or
(iii) the queue of data to be written has been exhausted.
*/
virtual void posit_event(Event type) = 0;
private:
// Storage::Disk::Controller
virtual void process_input_bit(int value, unsigned int cycles_since_index_hole);
virtual void process_index_hole();
virtual void process_write_completed();
// PLL input state
int bits_since_token_;
int shift_register_;
bool is_awaiting_marker_value_;
// input configuration
bool is_double_density_;
DataMode data_mode_;
// output
Token latest_token_;
// CRC generator
NumberTheory::CRC16 crc_generator_;
};
}
}
#endif /* MFMDiskController_hpp */
<|endoftext|>
|
<commit_before>//
// lexer_stage.cpp
// Parse
//
// Created by Andrew Hunter on 21/08/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
// TODO: it'd be nice to have a way of designing this so it's not dependent on the language_stage stage
// (we don't do this at the moment to keep things reasonably simple, there's a lot of dependencies that means that DI
// wouldn't really fix the problem, and would just create a new 'giant constructor of doom' problem)
#include <sstream>
#include "TameParse/Compiler/lexer_stage.h"
using namespace std;
using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace compiler;
/// \brief Creates a new lexer compiler
///
/// The compiler will not 'own' the objects passed in to this constructor; however, they must have a lifespan
/// that is at least as long as the compiler itself (it's safe to call the destructor but no other call if they
/// have been destroyed)
lexer_stage::lexer_stage(console_container& console, const std::wstring& filename, language_stage* languageCompiler)
: compilation_stage(console, filename)
, m_Language(languageCompiler)
, m_WeakSymbols(languageCompiler->grammar())
, m_Dfa(NULL)
, m_Lexer(NULL) {
}
/// \brief Destroys the lexer compiler
lexer_stage::~lexer_stage() {
// Destroy the DFA if it exists
if (m_Dfa) {
delete m_Dfa;
}
if (m_Lexer) {
delete m_Lexer;
}
}
/// \brief Compiles the lexer
void lexer_stage::compile() {
// Grab the input
const lexer_data* lex = m_Language->lexer();
terminal_dictionary* terminals = m_Language->terminals();
const set<int>* weakSymbolIds = m_Language->weak_symbols();
// Reset the weak symbols
m_WeakSymbols = lr::weak_symbols(m_Language->grammar());
// Sanity check
if (!lex || !terminals || !weakSymbolIds) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_LEXER_BAD_PARAMETERS", L"Missing input for the lexer stage", position(-1, -1, -1)));
return;
}
// Output a staging message
cons().verbose_stream() << L" = Constructing final lexer" << endl;
// Create the ndfa
typedef lexer_data::item_list item_list;
dfa::ndfa_regex* stage0 = new ndfa_regex();
// Iterate through the definition lists for each item
for (lexer_data::iterator itemList = lex->begin(); itemList != lex->end(); itemList++) {
// Iterate through the individual definitions for this item
for (item_list::const_iterator item = itemList->second.begin(); item != itemList->second.end(); item++) {
// Add the corresponding items
switch (item->type) {
case lexer_item::regex:
stage0->set_case_insensitive(item->case_insensitive);
stage0->add_regex(0, item->definition, *item->accept);
break;
case lexer_item::literal:
stage0->set_case_insensitive(item->case_insensitive);
stage0->add_literal(0, item->definition, *item->accept);
break;
}
}
}
// Write out some stats about the ndfa
cons().verbose_stream() << L" Number states in the NDFA: " << stage0->count_states() << endl;
// Compile the NDFA to a NDFA without overlapping symbol sets
dfa::ndfa* stage1 = stage0->to_ndfa_with_unique_symbols();
if (!stage1) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_CONVERT", L"Failed to create an NDFA with unique symbols", position(-1, -1, -1)));
return;
}
// Write some information about the first stage
cons().verbose_stream() << L" Initial number of character sets: " << stage0->symbols().count_sets() << endl;
cons().verbose_stream() << L" Final number of character sets: " << stage1->symbols().count_sets() << endl;
delete stage0;
stage0 = NULL;
// Compile the NDFA to a DFA
dfa::ndfa* stage2 = stage1->to_dfa();
delete stage1;
stage1 = NULL;
if (!stage2) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_COMPILE", L"Failed to compile DFA", position(-1, -1, -1)));
return;
}
// Identify any terminals that are always replaced by other terminals (warning)
set<int> unusedTerminals;
map<int, set<int> > clashes;
for (int terminalId = 0; terminalId < m_Language->terminals()->count_symbols(); terminalId++) {
unusedTerminals.insert(terminalId);
}
for (int stateId = 0; stateId < stage2->count_states(); stateId++) {
// Get the actions for this state
const ndfa::accept_action_list& acceptActions = stage2->actions_for_state(stateId);
// Ignore empty action sets
if (acceptActions.empty()) continue;
// Pick the highest action
ndfa::accept_action_list::const_iterator action = acceptActions.begin();
accept_action* highest = *action;
action++;
for (; action != acceptActions.end(); action++) {
if (*highest < **action) {
clashes[highest->symbol()].insert((*action)->symbol());
highest = *action;
} else {
clashes[(*action)->symbol()].insert(highest->symbol());
}
}
// Remove from the set of unused terminals
unusedTerminals.erase(highest->symbol());
}
// Report warnings for any terminals that are never generated by the lexer
for (set<int>::const_iterator unusedSymbol = unusedTerminals.begin(); unusedSymbol != unusedTerminals.end(); unusedSymbol++) {
// Get the position of this terminal
position pos = m_Language->terminal_definition_pos(*unusedSymbol);
const wstring& file = m_Language->terminal_definition_file(*unusedSymbol);
// Get the name of the terminal
const wstring& name = m_Language->terminals()->name_for_symbol(*unusedSymbol);
// Build the warning message
wstringstream msg;
msg << L"Lexer symbol can never be generated: " << name;
cons().report_error(error(error::sev_warning, file, L"SYMBOL_CANNOT_BE_GENERATED", msg.str(), pos));
// Get the symbols that clash with this one
set<int>& clashSet = clashes[*unusedSymbol];
if (!clashSet.empty()) {
// Write out the symbols that are generated instead
for (set<int>::iterator clashSymbol = clashSet.begin(); clashSymbol != clashSet.end(); clashSymbol++) {
wstringstream msg2;
msg2 << L"'" << name << L"' clashes with: " << m_Language->terminals()->name_for_symbol(*clashSymbol);
cons().report_error(error(error::sev_detail, m_Language->terminal_definition_file(*clashSymbol), L"SYMBOL_CLASHES_WITH", msg2.str(), m_Language->terminal_definition_pos(*clashSymbol)));
}
}
}
// TODO: also identify any terminals that clash with terminals at the same level (warning)
// Build up the weak symbols set if there are any
if (weakSymbolIds->size() > 0) {
// Build up the weak symbol set as a series of items
item_set weakSymSet(m_Language->grammar());
// Count how many symbols there were initially
int initialSymCount = terminals->count_symbols();
// Iterate through the symbol IDs
for (set<int>::const_iterator weakSymId = weakSymbolIds->begin(); weakSymId != weakSymbolIds->end(); weakSymId++) {
weakSymSet.insert(item_container(new terminal(*weakSymId), true));
}
// Add these symbols to the weak symbols object
m_WeakSymbols.add_symbols(*stage2, weakSymSet, *terminals);
// Display how many new terminal symbols were added
int finalSymCount = terminals->count_symbols();
cons().verbose_stream() << L" Number of extra weak symbols: " << finalSymCount - initialSymCount << endl;
}
// Compact the resulting DFA
cons().verbose_stream() << L" Number of states in the lexer DFA: " << stage2->count_states() << endl;
dfa::ndfa* stage3 = stage2->to_compact_dfa();
delete stage2;
stage2 = NULL;
// Write some information about the DFA we just produced
cons().verbose_stream() << L" Number of states in the compacted DFA: " << stage3->count_states() << endl;
// Eliminate any unnecessary symbol sets
dfa::ndfa* stage4 = stage3->to_ndfa_with_merged_symbols();
delete stage3;
stage3 = NULL;
// Write some information about the DFA we just produced
cons().verbose_stream() << L" Number of symbols in the compacted DFA: " << stage4->symbols().count_sets() << endl;
m_Dfa = stage4;
// Build the final lexer
m_Lexer = new lexer(*m_Dfa);
// Write some parting words
// (Well, this is really kibibytes but I can't take blibblebytes seriously as a unit of measurement)
cons().verbose_stream() << L" Approximate size of final lexer: " << (m_Lexer->size() + 512) / 1024 << L" kilobytes" << endl;
}
<commit_msg>Added detection for a particular kind of bug with the new way of generating lexer data<commit_after>//
// lexer_stage.cpp
// Parse
//
// Created by Andrew Hunter on 21/08/2011.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
// TODO: it'd be nice to have a way of designing this so it's not dependent on the language_stage stage
// (we don't do this at the moment to keep things reasonably simple, there's a lot of dependencies that means that DI
// wouldn't really fix the problem, and would just create a new 'giant constructor of doom' problem)
#include <sstream>
#include "TameParse/Compiler/lexer_stage.h"
using namespace std;
using namespace dfa;
using namespace contextfree;
using namespace lr;
using namespace compiler;
/// \brief Creates a new lexer compiler
///
/// The compiler will not 'own' the objects passed in to this constructor; however, they must have a lifespan
/// that is at least as long as the compiler itself (it's safe to call the destructor but no other call if they
/// have been destroyed)
lexer_stage::lexer_stage(console_container& console, const std::wstring& filename, language_stage* languageCompiler)
: compilation_stage(console, filename)
, m_Language(languageCompiler)
, m_WeakSymbols(languageCompiler->grammar())
, m_Dfa(NULL)
, m_Lexer(NULL) {
}
/// \brief Destroys the lexer compiler
lexer_stage::~lexer_stage() {
// Destroy the DFA if it exists
if (m_Dfa) {
delete m_Dfa;
}
if (m_Lexer) {
delete m_Lexer;
}
}
/// \brief Compiles the lexer
void lexer_stage::compile() {
// Grab the input
const lexer_data* lex = m_Language->lexer();
terminal_dictionary* terminals = m_Language->terminals();
const set<int>* weakSymbolIds = m_Language->weak_symbols();
// Reset the weak symbols
m_WeakSymbols = lr::weak_symbols(m_Language->grammar());
// Sanity check
if (!lex || !terminals || !weakSymbolIds) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_LEXER_BAD_PARAMETERS", L"Missing input for the lexer stage", position(-1, -1, -1)));
return;
}
// Output a staging message
cons().verbose_stream() << L" = Constructing final lexer" << endl;
// Create the ndfa
typedef lexer_data::item_list item_list;
dfa::ndfa_regex* stage0 = new ndfa_regex();
// Iterate through the definition lists for each item
for (lexer_data::iterator itemList = lex->begin(); itemList != lex->end(); itemList++) {
// Iterate through the individual definitions for this item
for (item_list::const_iterator item = itemList->second.begin(); item != itemList->second.end(); item++) {
// Ignore items without a valid accept action (this is a bug)
if (!item->accept) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_MISSING_ACTION", L"Missing action for lexer symbol", position(-1, -1, -1)));
continue;
}
// Add the corresponding items
switch (item->type) {
case lexer_item::regex:
stage0->set_case_insensitive(item->case_insensitive);
stage0->add_regex(0, item->definition, *item->accept);
break;
case lexer_item::literal:
stage0->set_case_insensitive(item->case_insensitive);
stage0->add_literal(0, item->definition, *item->accept);
break;
}
}
}
// Write out some stats about the ndfa
cons().verbose_stream() << L" Number states in the NDFA: " << stage0->count_states() << endl;
// Compile the NDFA to a NDFA without overlapping symbol sets
dfa::ndfa* stage1 = stage0->to_ndfa_with_unique_symbols();
if (!stage1) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_CONVERT", L"Failed to create an NDFA with unique symbols", position(-1, -1, -1)));
return;
}
// Write some information about the first stage
cons().verbose_stream() << L" Initial number of character sets: " << stage0->symbols().count_sets() << endl;
cons().verbose_stream() << L" Final number of character sets: " << stage1->symbols().count_sets() << endl;
delete stage0;
stage0 = NULL;
// Compile the NDFA to a DFA
dfa::ndfa* stage2 = stage1->to_dfa();
delete stage1;
stage1 = NULL;
if (!stage2) {
cons().report_error(error(error::sev_bug, filename(), L"BUG_DFA_FAILED_TO_COMPILE", L"Failed to compile DFA", position(-1, -1, -1)));
return;
}
// Identify any terminals that are always replaced by other terminals (warning)
set<int> unusedTerminals;
map<int, set<int> > clashes;
for (int terminalId = 0; terminalId < m_Language->terminals()->count_symbols(); terminalId++) {
unusedTerminals.insert(terminalId);
}
for (int stateId = 0; stateId < stage2->count_states(); stateId++) {
// Get the actions for this state
const ndfa::accept_action_list& acceptActions = stage2->actions_for_state(stateId);
// Ignore empty action sets
if (acceptActions.empty()) continue;
// Pick the highest action
ndfa::accept_action_list::const_iterator action = acceptActions.begin();
accept_action* highest = *action;
action++;
for (; action != acceptActions.end(); action++) {
if (*highest < **action) {
clashes[highest->symbol()].insert((*action)->symbol());
highest = *action;
} else {
clashes[(*action)->symbol()].insert(highest->symbol());
}
}
// Remove from the set of unused terminals
unusedTerminals.erase(highest->symbol());
}
// Report warnings for any terminals that are never generated by the lexer
for (set<int>::const_iterator unusedSymbol = unusedTerminals.begin(); unusedSymbol != unusedTerminals.end(); unusedSymbol++) {
// Get the position of this terminal
position pos = m_Language->terminal_definition_pos(*unusedSymbol);
const wstring& file = m_Language->terminal_definition_file(*unusedSymbol);
// Get the name of the terminal
const wstring& name = m_Language->terminals()->name_for_symbol(*unusedSymbol);
// Build the warning message
wstringstream msg;
msg << L"Lexer symbol can never be generated: " << name;
cons().report_error(error(error::sev_warning, file, L"SYMBOL_CANNOT_BE_GENERATED", msg.str(), pos));
// Get the symbols that clash with this one
set<int>& clashSet = clashes[*unusedSymbol];
if (!clashSet.empty()) {
// Write out the symbols that are generated instead
for (set<int>::iterator clashSymbol = clashSet.begin(); clashSymbol != clashSet.end(); clashSymbol++) {
wstringstream msg2;
msg2 << L"'" << name << L"' clashes with: " << m_Language->terminals()->name_for_symbol(*clashSymbol);
cons().report_error(error(error::sev_detail, m_Language->terminal_definition_file(*clashSymbol), L"SYMBOL_CLASHES_WITH", msg2.str(), m_Language->terminal_definition_pos(*clashSymbol)));
}
}
}
// TODO: also identify any terminals that clash with terminals at the same level (warning)
// Build up the weak symbols set if there are any
if (weakSymbolIds->size() > 0) {
// Build up the weak symbol set as a series of items
item_set weakSymSet(m_Language->grammar());
// Count how many symbols there were initially
int initialSymCount = terminals->count_symbols();
// Iterate through the symbol IDs
for (set<int>::const_iterator weakSymId = weakSymbolIds->begin(); weakSymId != weakSymbolIds->end(); weakSymId++) {
weakSymSet.insert(item_container(new terminal(*weakSymId), true));
}
// Add these symbols to the weak symbols object
m_WeakSymbols.add_symbols(*stage2, weakSymSet, *terminals);
// Display how many new terminal symbols were added
int finalSymCount = terminals->count_symbols();
cons().verbose_stream() << L" Number of extra weak symbols: " << finalSymCount - initialSymCount << endl;
}
// Compact the resulting DFA
cons().verbose_stream() << L" Number of states in the lexer DFA: " << stage2->count_states() << endl;
dfa::ndfa* stage3 = stage2->to_compact_dfa();
delete stage2;
stage2 = NULL;
// Write some information about the DFA we just produced
cons().verbose_stream() << L" Number of states in the compacted DFA: " << stage3->count_states() << endl;
// Eliminate any unnecessary symbol sets
dfa::ndfa* stage4 = stage3->to_ndfa_with_merged_symbols();
delete stage3;
stage3 = NULL;
// Write some information about the DFA we just produced
cons().verbose_stream() << L" Number of symbols in the compacted DFA: " << stage4->symbols().count_sets() << endl;
m_Dfa = stage4;
// Build the final lexer
m_Lexer = new lexer(*m_Dfa);
// Write some parting words
// (Well, this is really kibibytes but I can't take blibblebytes seriously as a unit of measurement)
cons().verbose_stream() << L" Approximate size of final lexer: " << (m_Lexer->size() + 512) / 1024 << L" kilobytes" << endl;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"
using namespace std;
namespace bohrium {
/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
* theoretically execute the two instructions in a single operation,
* thus accepts broadcast, reduction, extension methods, etc. */
BROADEST,
/* A very simple mode that only fuses same shaped arrays thus no
* broadcast, reduction, extension methods, etc. */
SAME_SHAPE,
/* The sentinel */
NONE
};
/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;
/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;
/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/
static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
return false;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned_and_same_shape(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned_and_same_shape(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/
/* Get the selected fuse model by reading the environment
* variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
using namespace boost;
//Check enviroment variable
const char *env = getenv("BH_FUSE_MODEL");
if(env != NULL)
{
string e(env);
if(iequals(e, string("broadest")))
{
cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return BROADEST;
}
else if(iequals(e, string("same_shape")))
{
cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
return SAME_SHAPE;
}
else
{
cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
cerr << "', using the default model instead" << endl;
}
}
cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return default_fuse_model;
}
/* Determines whether it is legal to fuse two instructions into one
* kernel using the 'selected_fuse_model'.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
switch(selected_fuse_model)
{
case NONE:
selected_fuse_model = get_selected_fuse_model();
return check_fusible(a, b);
case BROADEST:
return fuse_broadest(a,b);
case SAME_SHAPE:
return fuse_same_shape(a,b);
default:
throw runtime_error("No fuse module is selected!");
}
}
} //namespace bohrium
<commit_msg>core-fuse: Commented out verbose notifying about selected fuser.<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium 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.
Bohrium 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 Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#include <string>
#include <stdexcept>
#include <boost/algorithm/string/predicate.hpp> //For iequals()
#include <bh.h>
#include "bh_fuse.h"
using namespace std;
namespace bohrium {
/* The possible fuse models */
enum fuse_model
{
/* The broadest possible model. I.e. a SIMD machine can
* theoretically execute the two instructions in a single operation,
* thus accepts broadcast, reduction, extension methods, etc. */
BROADEST,
/* A very simple mode that only fuses same shaped arrays thus no
* broadcast, reduction, extension methods, etc. */
SAME_SHAPE,
/* The sentinel */
NONE
};
/* The default fuse model */
static const fuse_model default_fuse_model = BROADEST;
/* The current selected fuse model */
static fuse_model selected_fuse_model = NONE;
/************************************************************************/
/*************** Specific fuse model implementations ********************/
/************************************************************************/
static bool fuse_broadest(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
static bool fuse_same_shape(const bh_instruction *a, const bh_instruction *b)
{
if(bh_opcode_is_system(a->opcode) || bh_opcode_is_system(b->opcode))
return true;
if(!bh_opcode_is_elementwise(a->opcode) || !bh_opcode_is_elementwise(b->opcode))
return false;
const int a_nop = bh_operands(a->opcode);
for(int i=0; i<a_nop; ++i)
{
if(not bh_view_disjoint(&b->operand[0], &a->operand[i])
&& not bh_view_aligned_and_same_shape(&b->operand[0], &a->operand[i]))
return false;
}
const int b_nop = bh_operands(b->opcode);
for(int i=0; i<b_nop; ++i)
{
if(not bh_view_disjoint(&a->operand[0], &b->operand[i])
&& not bh_view_aligned_and_same_shape(&a->operand[0], &b->operand[i]))
return false;
}
return true;
}
/************************************************************************/
/*************** The public interface implementation ********************/
/************************************************************************/
/* Get the selected fuse model by reading the environment
* variable 'BH_FUSE_MODEL' */
static fuse_model get_selected_fuse_model()
{
using namespace boost;
//Check enviroment variable
const char *env = getenv("BH_FUSE_MODEL");
if(env != NULL)
{
string e(env);
if(iequals(e, string("broadest")))
{
//cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return BROADEST;
}
else if(iequals(e, string("same_shape")))
{
//cout << "[FUSE] info: selected fuse model: 'SAME_SHAPE'" << endl;
return SAME_SHAPE;
}
else
{
cerr << "[FUSE] WARNING: unknown fuse model: '" << e;
cerr << "', using the default model instead" << endl;
}
}
//cout << "[FUSE] info: selected fuse model: 'BROADEST'" << endl;
return default_fuse_model;
}
/* Determines whether it is legal to fuse two instructions into one
* kernel using the 'selected_fuse_model'.
*
* @a The first instruction
* @b The second instruction
* @return The boolean answer
*/
bool check_fusible(const bh_instruction *a, const bh_instruction *b)
{
switch(selected_fuse_model)
{
case NONE:
selected_fuse_model = get_selected_fuse_model();
return check_fusible(a, b);
case BROADEST:
return fuse_broadest(a,b);
case SAME_SHAPE:
return fuse_same_shape(a,b);
default:
throw runtime_error("No fuse module is selected!");
}
}
} //namespace bohrium
<|endoftext|>
|
<commit_before>#include "unit_tests.h"
#include "universal_crc.h"
//------------- tests for CRC_Type_helper -------------
int test_crc_type_helper_uint8(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (1-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (2-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (3-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (4-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (5-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (6-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (7-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (8-1)/8 >::value_type) != sizeof(uint8_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint16(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (9 -1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (10-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (11-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (12-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (13-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (14-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (15-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (16-1)/8 >::value_type) != sizeof(uint16_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint32(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (17-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (18-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (19-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (20-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (21-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (22-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (23-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (24-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (25-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (26-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (27-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (28-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (29-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (30-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (31-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (32-1)/8 >::value_type) != sizeof(uint32_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint64(struct test_info_t *test_info)
{
TEST_INIT;
//Template CRC_Type_helper default is uint64_t
if( sizeof(CRC_Type_helper<100>::value_type) != sizeof(uint64_t) )
return TEST_BROKEN;
return TEST_PASSED;
}
//------------- tests for Universal_CRC methods -------------
int test_universal_crc_name(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc;
if( ucrc.name != "" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
Universal_CRC<1, 0, 0, true, true, 0> ucrc(name);
if( ucrc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc_1;
if( ucrc_1.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_Type_Helper
test_crc_type_helper_uint8,
test_crc_type_helper_uint16,
test_crc_type_helper_uint32,
test_crc_type_helper_uint64,
//Universal_CRC methods
test_universal_crc_name,
test_universal_crc_name_2,
test_universal_crc_get_bits
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
<commit_msg>add test for get_poly()<commit_after>#include "unit_tests.h"
#include "universal_crc.h"
//------------- tests for CRC_Type_helper -------------
int test_crc_type_helper_uint8(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (1-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (2-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (3-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (4-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (5-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (6-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (7-1)/8 >::value_type) != sizeof(uint8_t) ||
sizeof(CRC_Type_helper< (8-1)/8 >::value_type) != sizeof(uint8_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint16(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (9 -1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (10-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (11-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (12-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (13-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (14-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (15-1)/8 >::value_type) != sizeof(uint16_t) ||
sizeof(CRC_Type_helper< (16-1)/8 >::value_type) != sizeof(uint16_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint32(struct test_info_t *test_info)
{
TEST_INIT;
if(
sizeof(CRC_Type_helper< (17-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (18-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (19-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (20-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (21-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (22-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (23-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (24-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (25-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (26-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (27-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (28-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (29-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (30-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (31-1)/8 >::value_type) != sizeof(uint32_t) ||
sizeof(CRC_Type_helper< (32-1)/8 >::value_type) != sizeof(uint32_t)
)
return TEST_BROKEN;
return TEST_PASSED;
}
int test_crc_type_helper_uint64(struct test_info_t *test_info)
{
TEST_INIT;
//Template CRC_Type_helper default is uint64_t
if( sizeof(CRC_Type_helper<100>::value_type) != sizeof(uint64_t) )
return TEST_BROKEN;
return TEST_PASSED;
}
//------------- tests for Universal_CRC methods -------------
int test_universal_crc_name(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc;
if( ucrc.name != "" )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_name_2(struct test_info_t *test_info)
{
TEST_INIT;
const char* name = "some_name";
Universal_CRC<1, 0, 0, true, true, 0> ucrc(name);
if( ucrc.name != name )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_bits(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<1, 0, 0, true, true, 0> ucrc_1;
if( ucrc_1.get_bits() != 1 )
return TEST_BROKEN;
return TEST_PASSED;
}
int test_universal_crc_get_poly(struct test_info_t *test_info)
{
TEST_INIT;
Universal_CRC<16, 1234, 0, true, true, 0> ucrc;
if( ucrc.get_poly() != 1234 )
return TEST_BROKEN;
return TEST_PASSED;
}
ptest_func tests[] =
{
//CRC_Type_Helper
test_crc_type_helper_uint8,
test_crc_type_helper_uint16,
test_crc_type_helper_uint32,
test_crc_type_helper_uint64,
//Universal_CRC methods
test_universal_crc_name,
test_universal_crc_name_2,
test_universal_crc_get_bits,
test_universal_crc_get_poly
};
int main(void)
{
RUN_TESTS(tests);
return 0;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
int sum = 0;
int i = 0;
for (i; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
printf("%d\n", sum);
return 0;
}
<commit_msg>Fix warnings<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
int sum = 0;
int i;
for (i = 0; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
printf("%d\n", sum);
return 0;
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <sys/time.h>
#include <cstring>
#include "sess.h"
IUINT32 iclock();
int main() {
struct timeval time;
gettimeofday(&time, NULL);
srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
UDPSession *sess = UDPSession::DialWithOptions("127.0.0.1", 9999, 2,2);
sess->NoDelay(1, 20, 2, 1);
sess->WndSize(128, 128);
sess->SetMtu(1400);
sess->SetStreamMode(true);
sess->SetDSCP(46);
assert(sess != nullptr);
ssize_t nsent = 0;
ssize_t nrecv = 0;
char *buf = (char *) malloc(128);
for (int i = 0; i < 10; i++) {
sprintf(buf, "message:%d", i);
auto sz = strlen(buf);
sess->Write(buf, sz);
sess->Update(iclock());
memset(buf, 0, 128);
ssize_t n = 0;
do {
n = sess->Read(buf, 128);
if (n > 0) { printf("%s\n", buf); }
usleep(33000);
sess->Update(iclock());
} while(n==0);
}
UDPSession::Destroy(sess);
}
void
itimeofday(long *sec, long *usec) {
struct timeval time;
gettimeofday(&time, NULL);
if (sec) *sec = time.tv_sec;
if (usec) *usec = time.tv_usec;
}
IUINT64 iclock64(void) {
long s, u;
IUINT64 value;
itimeofday(&s, &u);
value = ((IUINT64) s) * 1000 + (u / 1000);
return value;
}
IUINT32 iclock() {
return (IUINT32) (iclock64() & 0xfffffffful);
}
<commit_msg>upd import<commit_after>#include <unistd.h>
#include <sys/time.h>
#include <cstring>
#include <cstdio>
#include "sess.h"
IUINT32 iclock();
int main() {
struct timeval time;
gettimeofday(&time, NULL);
srand((time.tv_sec * 1000) + (time.tv_usec / 1000));
UDPSession *sess = UDPSession::DialWithOptions("127.0.0.1", 9999, 2,2);
sess->NoDelay(1, 20, 2, 1);
sess->WndSize(128, 128);
sess->SetMtu(1400);
sess->SetStreamMode(true);
sess->SetDSCP(46);
assert(sess != nullptr);
ssize_t nsent = 0;
ssize_t nrecv = 0;
char *buf = (char *) malloc(128);
for (int i = 0; i < 10; i++) {
sprintf(buf, "message:%d", i);
auto sz = strlen(buf);
sess->Write(buf, sz);
sess->Update(iclock());
memset(buf, 0, 128);
ssize_t n = 0;
do {
n = sess->Read(buf, 128);
if (n > 0) { printf("%s\n", buf); }
usleep(33000);
sess->Update(iclock());
} while(n==0);
}
UDPSession::Destroy(sess);
}
void
itimeofday(long *sec, long *usec) {
struct timeval time;
gettimeofday(&time, NULL);
if (sec) *sec = time.tv_sec;
if (usec) *usec = time.tv_usec;
}
IUINT64 iclock64(void) {
long s, u;
IUINT64 value;
itimeofday(&s, &u);
value = ((IUINT64) s) * 1000 + (u / 1000);
return value;
}
IUINT32 iclock() {
return (IUINT32) (iclock64() & 0xfffffffful);
}
<|endoftext|>
|
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "korganizer_part.h"
#include "calendarview.h"
#include "actionmanager.h"
#include "koglobals.h"
#include "koprefs.h"
#include "resourceview.h"
#include "aboutdata.h"
#include "kocore.h"
#include "korganizerifaceimpl.h"
#include "stdcalendar.h"
#include "kalarmd/alarmdaemoniface_stub.h"
#include <libkcal/calendarlocal.h>
#include <libkcal/calendarresources.h>
#include <libkcal/resourcecalendar.h>
#include <libkcal/resourcelocal.h>
#include <kpopupmenu.h>
#include <kinstance.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kaction.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kprocess.h>
#include <ktempfile.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kparts/genericfactory.h>
#include <kparts/statusbarextension.h>
#include <sidebarextension.h>
#include <infoextension.h>
#include <qapplication.h>
#include <qfile.h>
#include <qtimer.h>
#include <qlayout.h>
typedef KParts::GenericFactory< KOrganizerPart > KOrganizerFactory;
K_EXPORT_COMPONENT_FACTORY( libkorganizerpart, KOrganizerFactory )
KOrganizerPart::KOrganizerPart( QWidget *parentWidget, const char *widgetName,
QObject *parent, const char *name,
const QStringList & ) :
KParts::ReadOnlyPart(parent, name)
{
KOCore::self()->setXMLGUIClient( this );
QString pname( name );
// create a canvas to insert our widget
QWidget *canvas = new QWidget( parentWidget, widgetName );
canvas->setFocusPolicy( QWidget::ClickFocus );
setWidget( canvas );
mView = new CalendarView( canvas );
mActionManager = new ActionManager( this, mView, this, this, true );
(void)new KOrganizerIfaceImpl( mActionManager, this, "IfaceImpl" );
if ( pname == "kontact" ) {
mActionManager->createCalendarResources();
setHasDocument( false );
KOrg::StdCalendar::self()->load();
mView->updateCategories();
} else {
mActionManager->createCalendarLocal();
setHasDocument( true );
}
mBrowserExtension = new KOrganizerBrowserExtension( this );
mStatusBarExtension = new KParts::StatusBarExtension( this );
setInstance( KOrganizerFactory::instance() );
QVBoxLayout *topLayout = new QVBoxLayout( canvas );
topLayout->addWidget( mView );
KGlobal::iconLoader()->addAppDir( "korganizer" );
new KParts::SideBarExtension( mView->leftFrame(), this, "SBE" );
KParts::InfoExtension *ie = new KParts::InfoExtension( this,
"KOrganizerInfo" );
connect( mView, SIGNAL( incidenceSelected( Incidence * ) ),
SLOT( slotChangeInfo( Incidence * ) ) );
connect( this, SIGNAL( textChanged( const QString & ) ),
ie, SIGNAL( textChanged( const QString & ) ) );
mView->show();
mActionManager->init();
mActionManager->readSettings();
connect( mActionManager, SIGNAL( actionKeyBindings() ),
SLOT( configureKeyBindings() ) );
setXMLFile( "korganizer_part.rc" );
mActionManager->loadParts();
}
KOrganizerPart::~KOrganizerPart()
{
mActionManager->saveCalendar();
mActionManager->writeSettings();
delete mActionManager;
mActionManager = 0;
closeURL();
}
KAboutData *KOrganizerPart::createAboutData()
{
return KOrg::AboutData::self();
}
void KOrganizerPart::startCompleted( KProcess *process )
{
delete process;
}
void KOrganizerPart::slotChangeInfo( Incidence *incidence )
{
if ( incidence ) {
emit textChanged( incidence->summary() + " / " +
incidence->dtStartTimeStr() );
} else {
emit textChanged( QString::null );
}
}
QWidget *KOrganizerPart::topLevelWidget()
{
return mView->topLevelWidget();
}
ActionManager *KOrganizerPart::actionManager()
{
return mActionManager;
}
void KOrganizerPart::showStatusMessage( const QString &message )
{
KStatusBar *statusBar = mStatusBarExtension->statusBar();
if ( statusBar ) statusBar->message( message );
}
KOrg::CalendarViewBase *KOrganizerPart::view() const
{
return mView;
}
bool KOrganizerPart::openURL( const KURL &url, bool merge )
{
return mActionManager->openURL( url, merge );
}
bool KOrganizerPart::saveURL()
{
return mActionManager->saveURL();
}
bool KOrganizerPart::saveAsURL( const KURL &kurl )
{
return mActionManager->saveAsURL( kurl );
}
KURL KOrganizerPart::getCurrentURL() const
{
return mActionManager->url();
}
bool KOrganizerPart::openFile()
{
mView->openCalendar( m_file );
mView->show();
return true;
}
void KOrganizerPart::configureKeyBindings()
{
KKeyDialog::configure( actionCollection(), true );
}
KOrganizerBrowserExtension::KOrganizerBrowserExtension(KOrganizerPart *parent) :
KParts::BrowserExtension(parent, "KOrganizerBrowserExtension")
{
}
KOrganizerBrowserExtension::~KOrganizerBrowserExtension()
{
}
using namespace KParts;
#include "korganizer_part.moc"
<commit_msg>When run as kontact part, korganizer didn't start the alarm daemon so far. In the standalone case this was done in KOrganizerApp, but for a Part we have to do it in the constructor of KOrganizerPart.<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 2000 Cornelius Schumacher <schumacher@kde.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include "korganizer_part.h"
#include "calendarview.h"
#include "actionmanager.h"
#include "koglobals.h"
#include "koprefs.h"
#include "resourceview.h"
#include "aboutdata.h"
#include "kocore.h"
#include "korganizerifaceimpl.h"
#include "stdcalendar.h"
#include "kalarmd/alarmdaemoniface_stub.h"
#include <libkcal/calendarlocal.h>
#include <libkcal/calendarresources.h>
#include <libkcal/resourcecalendar.h>
#include <libkcal/resourcelocal.h>
#include <kpopupmenu.h>
#include <kinstance.h>
#include <klocale.h>
#include <kaboutdata.h>
#include <kiconloader.h>
#include <kaction.h>
#include <kdebug.h>
#include <kstandarddirs.h>
#include <kconfig.h>
#include <kprocess.h>
#include <ktempfile.h>
#include <kstatusbar.h>
#include <kkeydialog.h>
#include <kparts/genericfactory.h>
#include <kparts/statusbarextension.h>
#include <sidebarextension.h>
#include <infoextension.h>
#include <qapplication.h>
#include <qfile.h>
#include <qtimer.h>
#include <qlayout.h>
typedef KParts::GenericFactory< KOrganizerPart > KOrganizerFactory;
K_EXPORT_COMPONENT_FACTORY( libkorganizerpart, KOrganizerFactory )
KOrganizerPart::KOrganizerPart( QWidget *parentWidget, const char *widgetName,
QObject *parent, const char *name,
const QStringList & ) :
KParts::ReadOnlyPart(parent, name)
{
KOCore::self()->setXMLGUIClient( this );
QString pname( name );
// create a canvas to insert our widget
QWidget *canvas = new QWidget( parentWidget, widgetName );
canvas->setFocusPolicy( QWidget::ClickFocus );
setWidget( canvas );
mView = new CalendarView( canvas );
mActionManager = new ActionManager( this, mView, this, this, true );
(void)new KOrganizerIfaceImpl( mActionManager, this, "IfaceImpl" );
if ( pname == "kontact" ) {
mActionManager->createCalendarResources();
setHasDocument( false );
KOrg::StdCalendar::self()->load();
mView->updateCategories();
} else {
mActionManager->createCalendarLocal();
setHasDocument( true );
}
mBrowserExtension = new KOrganizerBrowserExtension( this );
mStatusBarExtension = new KParts::StatusBarExtension( this );
setInstance( KOrganizerFactory::instance() );
QVBoxLayout *topLayout = new QVBoxLayout( canvas );
topLayout->addWidget( mView );
KGlobal::iconLoader()->addAppDir( "korganizer" );
new KParts::SideBarExtension( mView->leftFrame(), this, "SBE" );
KParts::InfoExtension *ie = new KParts::InfoExtension( this,
"KOrganizerInfo" );
connect( mView, SIGNAL( incidenceSelected( Incidence * ) ),
SLOT( slotChangeInfo( Incidence * ) ) );
connect( this, SIGNAL( textChanged( const QString & ) ),
ie, SIGNAL( textChanged( const QString & ) ) );
mView->show();
mActionManager->init();
mActionManager->readSettings();
connect( mActionManager, SIGNAL( actionKeyBindings() ),
SLOT( configureKeyBindings() ) );
setXMLFile( "korganizer_part.rc" );
mActionManager->loadParts();
// If korganizer is run as part inside kontact, the alarmdaemon
// is not started by KOrganizerApp, so we have to start it here.
KOGlobals::self()->alarmClient()->startDaemon();
}
KOrganizerPart::~KOrganizerPart()
{
mActionManager->saveCalendar();
mActionManager->writeSettings();
delete mActionManager;
mActionManager = 0;
closeURL();
}
KAboutData *KOrganizerPart::createAboutData()
{
return KOrg::AboutData::self();
}
void KOrganizerPart::startCompleted( KProcess *process )
{
delete process;
}
void KOrganizerPart::slotChangeInfo( Incidence *incidence )
{
if ( incidence ) {
emit textChanged( incidence->summary() + " / " +
incidence->dtStartTimeStr() );
} else {
emit textChanged( QString::null );
}
}
QWidget *KOrganizerPart::topLevelWidget()
{
return mView->topLevelWidget();
}
ActionManager *KOrganizerPart::actionManager()
{
return mActionManager;
}
void KOrganizerPart::showStatusMessage( const QString &message )
{
KStatusBar *statusBar = mStatusBarExtension->statusBar();
if ( statusBar ) statusBar->message( message );
}
KOrg::CalendarViewBase *KOrganizerPart::view() const
{
return mView;
}
bool KOrganizerPart::openURL( const KURL &url, bool merge )
{
return mActionManager->openURL( url, merge );
}
bool KOrganizerPart::saveURL()
{
return mActionManager->saveURL();
}
bool KOrganizerPart::saveAsURL( const KURL &kurl )
{
return mActionManager->saveAsURL( kurl );
}
KURL KOrganizerPart::getCurrentURL() const
{
return mActionManager->url();
}
bool KOrganizerPart::openFile()
{
mView->openCalendar( m_file );
mView->show();
return true;
}
void KOrganizerPart::configureKeyBindings()
{
KKeyDialog::configure( actionCollection(), true );
}
KOrganizerBrowserExtension::KOrganizerBrowserExtension(KOrganizerPart *parent) :
KParts::BrowserExtension(parent, "KOrganizerBrowserExtension")
{
}
KOrganizerBrowserExtension::~KOrganizerBrowserExtension()
{
}
using namespace KParts;
#include "korganizer_part.moc"
<|endoftext|>
|
<commit_before>// A work-in-progress llvm backend
#include <taichi/common/util.h>
#include <taichi/io/io.h>
#include <set>
#include "cuda_context.h"
#include "../util.h"
#include "codegen_cuda.h"
#include "../program.h"
#include "../ir.h"
#if defined(TLANG_WITH_LLVM)
#include "codegen_llvm.h"
#endif
TLANG_NAMESPACE_BEGIN
#if defined(TLANG_WITH_LLVM)
using namespace llvm;
// NVVM IR Spec:
// https://docs.nvidia.com/cuda/archive/10.0/pdf/NVVM_IR_Specification.pdf
class CodeGenLLVMGPU : public CodeGenLLVM {
public:
int kernel_grid_dim;
int kernel_block_dim;
CodeGenLLVMGPU(CodeGenBase *codegen_base, Kernel *kernel)
: CodeGenLLVM(codegen_base, kernel) {
}
FunctionType compile_module_to_executable() override {
#if defined(TLANG_WITH_CUDA)
llvm::Function *func = module->getFunction("test_kernel");
/*******************************************************************
Example annotation from llvm PTX doc:
define void @kernel(float addrspace(1)* %A,
float addrspace(1)* %B,
float addrspace(1)* %C);
!nvvm.annotations = !{!0}
!0 = !{void (float addrspace(1)*,
float addrspace(1)*,
float addrspace(1)*)* @kernel, !"kernel", i32 1}
*******************************************************************/
// Mark kernel function as a CUDA __global__ function
// Add the nvvm annotation that it is considered a kernel function.
llvm::Metadata *md_args[] = {
llvm::ValueAsMetadata::get(func),
MDString::get(*llvm_context, "kernel"),
llvm::ValueAsMetadata::get(tlctx->get_constant(1))};
MDNode *md_node = MDNode::get(*llvm_context, md_args);
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(md_node);
auto ptx = compile_module_to_ptx(module);
auto cuda_kernel = cuda_context.compile(ptx, kernel_name);
return [=](Context context) {
cuda_context.launch(cuda_kernel, &context, kernel_grid_dim,
kernel_block_dim);
};
#else
TC_NOT_IMPLEMENTED;
return nullptr;
#endif
}
void visit(PrintStmt *stmt) override {
TC_ASSERT(stmt->width() == 1);
auto value_type = tlctx->get_data_type(stmt->stmt->ret_type.data_type);
std::string format;
auto value = stmt->stmt->value;
if (stmt->stmt->ret_type.data_type == DataType::i32) {
format = "%d";
} else if (stmt->stmt->ret_type.data_type == DataType::f32) {
value_type = llvm::Type::getDoubleTy(*llvm_context);
value = builder->CreateFPExt(value, value_type);
format = "%f";
} else if (stmt->stmt->ret_type.data_type == DataType::f64) {
format = "%f";
} else {
TC_NOT_IMPLEMENTED
}
std::vector<llvm::Type *> types{value_type};
auto stype = llvm::StructType::get(*llvm_context, types, false);
auto values = builder->CreateAlloca(stype);
auto value_ptr = builder->CreateGEP(
values, {tlctx->get_constant(0), tlctx->get_constant(0)});
builder->CreateStore(value, value_ptr);
auto format_str = "[debug] " + stmt->str + " = " + format + "\n";
stmt->value = ModuleBuilder::call(
builder, "vprintf",
builder->CreateGlobalStringPtr(format_str, "format_string"),
builder->CreateBitCast(values,
llvm::Type::getInt8PtrTy(*llvm_context)));
}
void visit(RangeForStmt *for_stmt) override {
if (offloaded) {
create_naive_range_for(for_stmt);
} else {
offloaded = true;
auto loop_begin = for_stmt->begin->as<ConstStmt>()->val[0].val_int32();
auto loop_end = for_stmt->end->as<ConstStmt>()->val[0].val_int32();
auto loop_block_dim = for_stmt->block_size;
kernel_grid_dim =
(loop_end - loop_begin + loop_block_dim - 1) / loop_block_dim;
kernel_block_dim = loop_block_dim;
BasicBlock *body = BasicBlock::Create(*llvm_context, "loop_body", func);
BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "block", func);
auto threadIdx =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {});
auto blockIdx = builder->CreateIntrinsic(
Intrinsic::nvvm_read_ptx_sreg_ctaid_x, {}, {});
auto blockDim = builder->CreateIntrinsic(
Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {});
auto loop_id = builder->CreateAdd(
for_stmt->begin->value,
builder->CreateAdd(threadIdx,
builder->CreateMul(blockIdx, blockDim)));
builder->CreateStore(loop_id, for_stmt->loop_var->value);
auto cond = builder->CreateICmp(
llvm::CmpInst::Predicate::ICMP_SLT,
builder->CreateLoad(for_stmt->loop_var->value), for_stmt->end->value);
builder->CreateCondBr(cond, body, after_loop);
{
// body cfg
builder->SetInsertPoint(body);
for_stmt->body->accept(this);
builder->CreateBr(after_loop);
}
// create_increment(for_stmt->loop_var->value, tlctx->get_constant(1));
builder->SetInsertPoint(after_loop);
// builder->CreateRetVoid();
offloaded = false;
}
}
};
FunctionType GPUCodeGen::codegen_llvm() {
return CodeGenLLVMGPU(this, kernel).gen();
}
#else
FunctionType GPUCodeGen::codegen_llvm() {
TC_ERROR("LLVM not found");
}
#endif
TLANG_NAMESPACE_END
<commit_msg>fixed cuda loop block size<commit_after>// A work-in-progress llvm backend
#include <taichi/common/util.h>
#include <taichi/io/io.h>
#include <set>
#include "cuda_context.h"
#include "../util.h"
#include "codegen_cuda.h"
#include "../program.h"
#include "../ir.h"
#if defined(TLANG_WITH_LLVM)
#include "codegen_llvm.h"
#endif
TLANG_NAMESPACE_BEGIN
#if defined(TLANG_WITH_LLVM)
using namespace llvm;
// NVVM IR Spec:
// https://docs.nvidia.com/cuda/archive/10.0/pdf/NVVM_IR_Specification.pdf
class CodeGenLLVMGPU : public CodeGenLLVM {
public:
int kernel_grid_dim;
int kernel_block_dim;
CodeGenLLVMGPU(CodeGenBase *codegen_base, Kernel *kernel)
: CodeGenLLVM(codegen_base, kernel) {
}
FunctionType compile_module_to_executable() override {
#if defined(TLANG_WITH_CUDA)
llvm::Function *func = module->getFunction("test_kernel");
/*******************************************************************
Example annotation from llvm PTX doc:
define void @kernel(float addrspace(1)* %A,
float addrspace(1)* %B,
float addrspace(1)* %C);
!nvvm.annotations = !{!0}
!0 = !{void (float addrspace(1)*,
float addrspace(1)*,
float addrspace(1)*)* @kernel, !"kernel", i32 1}
*******************************************************************/
// Mark kernel function as a CUDA __global__ function
// Add the nvvm annotation that it is considered a kernel function.
llvm::Metadata *md_args[] = {
llvm::ValueAsMetadata::get(func),
MDString::get(*llvm_context, "kernel"),
llvm::ValueAsMetadata::get(tlctx->get_constant(1))};
MDNode *md_node = MDNode::get(*llvm_context, md_args);
module->getOrInsertNamedMetadata("nvvm.annotations")->addOperand(md_node);
auto ptx = compile_module_to_ptx(module);
auto cuda_kernel = cuda_context.compile(ptx, kernel_name);
return [=](Context context) {
cuda_context.launch(cuda_kernel, &context, kernel_grid_dim,
kernel_block_dim);
};
#else
TC_NOT_IMPLEMENTED;
return nullptr;
#endif
}
void visit(PrintStmt *stmt) override {
TC_ASSERT(stmt->width() == 1);
auto value_type = tlctx->get_data_type(stmt->stmt->ret_type.data_type);
std::string format;
auto value = stmt->stmt->value;
if (stmt->stmt->ret_type.data_type == DataType::i32) {
format = "%d";
} else if (stmt->stmt->ret_type.data_type == DataType::f32) {
value_type = llvm::Type::getDoubleTy(*llvm_context);
value = builder->CreateFPExt(value, value_type);
format = "%f";
} else if (stmt->stmt->ret_type.data_type == DataType::f64) {
format = "%f";
} else {
TC_NOT_IMPLEMENTED
}
std::vector<llvm::Type *> types{value_type};
auto stype = llvm::StructType::get(*llvm_context, types, false);
auto values = builder->CreateAlloca(stype);
auto value_ptr = builder->CreateGEP(
values, {tlctx->get_constant(0), tlctx->get_constant(0)});
builder->CreateStore(value, value_ptr);
auto format_str = "[debug] " + stmt->str + " = " + format + "\n";
stmt->value = ModuleBuilder::call(
builder, "vprintf",
builder->CreateGlobalStringPtr(format_str, "format_string"),
builder->CreateBitCast(values,
llvm::Type::getInt8PtrTy(*llvm_context)));
}
void visit(RangeForStmt *for_stmt) override {
if (offloaded) {
create_naive_range_for(for_stmt);
} else {
offloaded = true;
auto loop_begin = for_stmt->begin->as<ConstStmt>()->val[0].val_int32();
auto loop_end = for_stmt->end->as<ConstStmt>()->val[0].val_int32();
auto loop_block_dim = for_stmt->block_size;
if (loop_block_dim == 0) {
loop_block_dim = default_gpu_block_size;
}
kernel_grid_dim =
(loop_end - loop_begin + loop_block_dim - 1) / loop_block_dim;
kernel_block_dim = loop_block_dim;
BasicBlock *body = BasicBlock::Create(*llvm_context, "loop_body", func);
BasicBlock *after_loop = BasicBlock::Create(*llvm_context, "block", func);
auto threadIdx =
builder->CreateIntrinsic(Intrinsic::nvvm_read_ptx_sreg_tid_x, {}, {});
auto blockIdx = builder->CreateIntrinsic(
Intrinsic::nvvm_read_ptx_sreg_ctaid_x, {}, {});
auto blockDim = builder->CreateIntrinsic(
Intrinsic::nvvm_read_ptx_sreg_ntid_x, {}, {});
auto loop_id = builder->CreateAdd(
for_stmt->begin->value,
builder->CreateAdd(threadIdx,
builder->CreateMul(blockIdx, blockDim)));
builder->CreateStore(loop_id, for_stmt->loop_var->value);
auto cond = builder->CreateICmp(
llvm::CmpInst::Predicate::ICMP_SLT,
builder->CreateLoad(for_stmt->loop_var->value), for_stmt->end->value);
builder->CreateCondBr(cond, body, after_loop);
{
// body cfg
builder->SetInsertPoint(body);
for_stmt->body->accept(this);
builder->CreateBr(after_loop);
}
// create_increment(for_stmt->loop_var->value, tlctx->get_constant(1));
builder->SetInsertPoint(after_loop);
// builder->CreateRetVoid();
offloaded = false;
}
}
};
FunctionType GPUCodeGen::codegen_llvm() {
return CodeGenLLVMGPU(this, kernel).gen();
}
#else
FunctionType GPUCodeGen::codegen_llvm() {
TC_ERROR("LLVM not found");
}
#endif
TLANG_NAMESPACE_END
<|endoftext|>
|
<commit_before>//===--- FixItRewriter.cpp - Fix-It Rewriter Diagnostic Client --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a diagnostic client adaptor that performs rewrites as
// suggested by code modification hints attached to diagnostics. It
// then forwards any diagnostics to the adapted diagnostic client.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FixItRewriter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Path.h"
#include "llvm/ADT/OwningPtr.h"
#include <cstdio>
using namespace clang;
FixItRewriter::FixItRewriter(Diagnostic &Diags, SourceManager &SourceMgr,
const LangOptions &LangOpts,
FixItPathRewriter *PathRewriter)
: Diags(Diags),
Rewrite(SourceMgr, LangOpts),
PathRewriter(PathRewriter),
NumFailures(0) {
Client = Diags.getClient();
Diags.setClient(this);
}
FixItRewriter::~FixItRewriter() {
Diags.setClient(Client);
}
bool FixItRewriter::WriteFixedFile(FileID ID, llvm::raw_ostream &OS) {
const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(ID);
if (!RewriteBuf) return true;
RewriteBuf->write(OS);
OS.flush();
return false;
}
bool FixItRewriter::WriteFixedFiles() {
if (NumFailures > 0) {
Diag(FullSourceLoc(), diag::warn_fixit_no_changes);
return true;
}
for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first);
std::string Filename = Entry->getName();
if (PathRewriter)
Filename = PathRewriter->RewriteFilename(Filename);
std::string Err;
llvm::raw_fd_ostream OS(Filename.c_str(), Err,
llvm::raw_fd_ostream::F_Binary);
if (!Err.empty()) {
Diags.Report(clang::diag::err_fe_unable_to_open_output)
<< Filename << Err;
continue;
}
RewriteBuffer &RewriteBuf = I->second;
OS << std::string(RewriteBuf.begin(), RewriteBuf.end());
OS.flush();
}
return false;
}
bool FixItRewriter::IncludeInDiagnosticCounts() const {
return Client ? Client->IncludeInDiagnosticCounts() : true;
}
void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info) {
Client->HandleDiagnostic(DiagLevel, Info);
// Skip over any diagnostics that are ignored or notes.
if (DiagLevel <= Diagnostic::Note)
return;
// Make sure that we can perform all of the modifications we
// in this diagnostic.
bool CanRewrite = Info.getNumFixItHints() > 0;
for (unsigned Idx = 0, Last = Info.getNumFixItHints();
Idx < Last; ++Idx) {
const FixItHint &Hint = Info.getFixItHint(Idx);
if (Hint.RemoveRange.isValid() &&
Rewrite.getRangeSize(Hint.RemoveRange) == -1) {
CanRewrite = false;
break;
}
if (Hint.InsertionLoc.isValid() &&
!Rewrite.isRewritable(Hint.InsertionLoc)) {
CanRewrite = false;
break;
}
}
if (!CanRewrite) {
if (Info.getNumFixItHints() > 0)
Diag(Info.getLocation(), diag::note_fixit_in_macro);
// If this was an error, refuse to perform any rewriting.
if (DiagLevel == Diagnostic::Error || DiagLevel == Diagnostic::Fatal) {
if (++NumFailures == 1)
Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
}
return;
}
bool Failed = false;
for (unsigned Idx = 0, Last = Info.getNumFixItHints();
Idx < Last; ++Idx) {
const FixItHint &Hint = Info.getFixItHint(Idx);
if (!Hint.RemoveRange.isValid()) {
// We're adding code.
if (Rewrite.InsertTextBefore(Hint.InsertionLoc, Hint.CodeToInsert))
Failed = true;
continue;
}
if (Hint.CodeToInsert.empty()) {
// We're removing code.
if (Rewrite.RemoveText(Hint.RemoveRange.getBegin(),
Rewrite.getRangeSize(Hint.RemoveRange)))
Failed = true;
continue;
}
// We're replacing code.
if (Rewrite.ReplaceText(Hint.RemoveRange.getBegin(),
Rewrite.getRangeSize(Hint.RemoveRange),
Hint.CodeToInsert))
Failed = true;
}
if (Failed) {
++NumFailures;
Diag(Info.getLocation(), diag::note_fixit_failed);
return;
}
Diag(Info.getLocation(), diag::note_fixit_applied);
}
/// \brief Emit a diagnostic via the adapted diagnostic client.
void FixItRewriter::Diag(FullSourceLoc Loc, unsigned DiagID) {
// When producing this diagnostic, we temporarily bypass ourselves,
// clear out any current diagnostic, and let the downstream client
// format the diagnostic.
Diags.setClient(Client);
Diags.Clear();
Diags.Report(Loc, DiagID);
Diags.setClient(this);
}
FixItPathRewriter::~FixItPathRewriter() {}
<commit_msg>Switch this to new API.<commit_after>//===--- FixItRewriter.cpp - Fix-It Rewriter Diagnostic Client --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a diagnostic client adaptor that performs rewrites as
// suggested by code modification hints attached to diagnostics. It
// then forwards any diagnostics to the adapted diagnostic client.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FixItRewriter.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Path.h"
#include "llvm/ADT/OwningPtr.h"
#include <cstdio>
using namespace clang;
FixItRewriter::FixItRewriter(Diagnostic &Diags, SourceManager &SourceMgr,
const LangOptions &LangOpts,
FixItPathRewriter *PathRewriter)
: Diags(Diags),
Rewrite(SourceMgr, LangOpts),
PathRewriter(PathRewriter),
NumFailures(0) {
Client = Diags.getClient();
Diags.setClient(this);
}
FixItRewriter::~FixItRewriter() {
Diags.setClient(Client);
}
bool FixItRewriter::WriteFixedFile(FileID ID, llvm::raw_ostream &OS) {
const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(ID);
if (!RewriteBuf) return true;
RewriteBuf->write(OS);
OS.flush();
return false;
}
bool FixItRewriter::WriteFixedFiles() {
if (NumFailures > 0) {
Diag(FullSourceLoc(), diag::warn_fixit_no_changes);
return true;
}
for (iterator I = buffer_begin(), E = buffer_end(); I != E; ++I) {
const FileEntry *Entry = Rewrite.getSourceMgr().getFileEntryForID(I->first);
std::string Filename = Entry->getName();
if (PathRewriter)
Filename = PathRewriter->RewriteFilename(Filename);
std::string Err;
llvm::raw_fd_ostream OS(Filename.c_str(), Err,
llvm::raw_fd_ostream::F_Binary);
if (!Err.empty()) {
Diags.Report(clang::diag::err_fe_unable_to_open_output)
<< Filename << Err;
continue;
}
RewriteBuffer &RewriteBuf = I->second;
RewriteBuf.write(OS);
OS.flush();
}
return false;
}
bool FixItRewriter::IncludeInDiagnosticCounts() const {
return Client ? Client->IncludeInDiagnosticCounts() : true;
}
void FixItRewriter::HandleDiagnostic(Diagnostic::Level DiagLevel,
const DiagnosticInfo &Info) {
Client->HandleDiagnostic(DiagLevel, Info);
// Skip over any diagnostics that are ignored or notes.
if (DiagLevel <= Diagnostic::Note)
return;
// Make sure that we can perform all of the modifications we
// in this diagnostic.
bool CanRewrite = Info.getNumFixItHints() > 0;
for (unsigned Idx = 0, Last = Info.getNumFixItHints();
Idx < Last; ++Idx) {
const FixItHint &Hint = Info.getFixItHint(Idx);
if (Hint.RemoveRange.isValid() &&
Rewrite.getRangeSize(Hint.RemoveRange) == -1) {
CanRewrite = false;
break;
}
if (Hint.InsertionLoc.isValid() &&
!Rewrite.isRewritable(Hint.InsertionLoc)) {
CanRewrite = false;
break;
}
}
if (!CanRewrite) {
if (Info.getNumFixItHints() > 0)
Diag(Info.getLocation(), diag::note_fixit_in_macro);
// If this was an error, refuse to perform any rewriting.
if (DiagLevel == Diagnostic::Error || DiagLevel == Diagnostic::Fatal) {
if (++NumFailures == 1)
Diag(Info.getLocation(), diag::note_fixit_unfixed_error);
}
return;
}
bool Failed = false;
for (unsigned Idx = 0, Last = Info.getNumFixItHints();
Idx < Last; ++Idx) {
const FixItHint &Hint = Info.getFixItHint(Idx);
if (!Hint.RemoveRange.isValid()) {
// We're adding code.
if (Rewrite.InsertTextBefore(Hint.InsertionLoc, Hint.CodeToInsert))
Failed = true;
continue;
}
if (Hint.CodeToInsert.empty()) {
// We're removing code.
if (Rewrite.RemoveText(Hint.RemoveRange.getBegin(),
Rewrite.getRangeSize(Hint.RemoveRange)))
Failed = true;
continue;
}
// We're replacing code.
if (Rewrite.ReplaceText(Hint.RemoveRange.getBegin(),
Rewrite.getRangeSize(Hint.RemoveRange),
Hint.CodeToInsert))
Failed = true;
}
if (Failed) {
++NumFailures;
Diag(Info.getLocation(), diag::note_fixit_failed);
return;
}
Diag(Info.getLocation(), diag::note_fixit_applied);
}
/// \brief Emit a diagnostic via the adapted diagnostic client.
void FixItRewriter::Diag(FullSourceLoc Loc, unsigned DiagID) {
// When producing this diagnostic, we temporarily bypass ourselves,
// clear out any current diagnostic, and let the downstream client
// format the diagnostic.
Diags.setClient(Client);
Diags.Clear();
Diags.Report(Loc, DiagID);
Diags.setClient(this);
}
FixItPathRewriter::~FixItPathRewriter() {}
<|endoftext|>
|
<commit_before>//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass transforms loops by placing phi nodes at the end of the loops for
// all values that are live across the loop boundary. For example, it turns
// the left into the right code:
//
// for (...) for (...)
// if (c) if (c)
// X1 = ... X1 = ...
// else else
// X2 = ... X2 = ...
// X3 = phi(X1, X2) X3 = phi(X1, X2)
// ... = X3 + 4 X4 = phi(X3)
// ... = X4 + 4
//
// This is still valid LLVM; the extra phi nodes are purely redundant, and will
// be trivially eliminated by InstCombine. The major benefit of this
// transformation is that it makes many other loop optimizations, such as
// LoopUnswitching, simpler.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lcssa"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>
#include <map>
using namespace llvm;
STATISTIC(NumLCSSA, "Number of live out of a loop variables");
namespace {
struct VISIBILITY_HIDDEN LCSSA : public LoopPass {
static char ID; // Pass identification, replacement for typeid
LCSSA() : LoopPass((intptr_t)&ID) {}
// Cached analysis information for the current function.
LoopInfo *LI;
DominatorTree *DT;
std::vector<BasicBlock*> LoopBlocks;
virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
void ProcessInstruction(Instruction* Instr,
const std::vector<BasicBlock*>& exitBlocks);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG. It maintains both of these,
/// as well as the CFG. It also requires dominator information.
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequiredID(LoopSimplifyID);
AU.addPreservedID(LoopSimplifyID);
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
AU.addRequired<DominatorTree>();
AU.addPreserved<ScalarEvolution>();
}
private:
void getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues);
Value *GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis);
/// inLoop - returns true if the given block is within the current loop
const bool inLoop(BasicBlock* B) {
return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
}
};
char LCSSA::ID = 0;
RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
}
LoopPass *llvm::createLCSSAPass() { return new LCSSA(); }
const PassInfo *llvm::LCSSAID = X.getPassInfo();
/// runOnFunction - Process all loops in the function, inner-most out.
bool LCSSA::runOnLoop(Loop *L, LPPassManager &LPM) {
LI = &LPM.getAnalysis<LoopInfo>();
DT = &getAnalysis<DominatorTree>();
// Speed up queries by creating a sorted list of blocks
LoopBlocks.clear();
LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
std::sort(LoopBlocks.begin(), LoopBlocks.end());
SetVector<Instruction*> AffectedValues;
getLoopValuesUsedOutsideLoop(L, AffectedValues);
// If no values are affected, we can save a lot of work, since we know that
// nothing will be changed.
if (AffectedValues.empty())
return false;
std::vector<BasicBlock*> exitBlocks;
L->getExitBlocks(exitBlocks);
// Iterate over all affected values for this loop and insert Phi nodes
// for them in the appropriate exit blocks
for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
E = AffectedValues.end(); I != E; ++I)
ProcessInstruction(*I, exitBlocks);
assert(L->isLCSSAForm());
return true;
}
/// processInstruction - Given a live-out instruction, insert LCSSA Phi nodes,
/// eliminate all out-of-loop uses.
void LCSSA::ProcessInstruction(Instruction *Instr,
const std::vector<BasicBlock*>& exitBlocks) {
++NumLCSSA; // We are applying the transformation
// Keep track of the blocks that have the value available already.
std::map<DomTreeNode*, Value*> Phis;
DomTreeNode *InstrNode = DT->getNode(Instr->getParent());
// Insert the LCSSA phi's into the exit blocks (dominated by the value), and
// add them to the Phi's map.
for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
DomTreeNode *ExitBBNode = DT->getNode(BB);
Value *&Phi = Phis[ExitBBNode];
if (!Phi && DT->dominates(InstrNode, ExitBBNode)) {
PHINode *PN = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
BB->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
// Remember that this phi makes the value alive in this block.
Phi = PN;
// Add inputs from inside the loop for this PHI.
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
PN->addIncoming(Instr, *PI);
}
}
// Record all uses of Instr outside the loop. We need to rewrite these. The
// LCSSA phis won't be included because they use the value in the loop.
for (Value::use_iterator UI = Instr->use_begin(), E = Instr->use_end();
UI != E;) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode *P = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = P->getIncomingBlock(OperandNo/2);
}
// If the user is in the loop, don't rewrite it!
if (UserBB == Instr->getParent() || inLoop(UserBB)) {
++UI;
continue;
}
// Otherwise, patch up uses of the value with the appropriate LCSSA Phi,
// inserting PHI nodes into join points where needed.
Value *Val = GetValueForBlock(DT->getNode(UserBB), Instr, Phis);
// Preincrement the iterator to avoid invalidating it when we change the
// value.
Use &U = UI.getUse();
++UI;
U.set(Val);
}
}
/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
/// are used by instructions outside of it.
void LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues) {
// FIXME: For large loops, we may be able to avoid a lot of use-scanning
// by using dominance information. In particular, if a block does not
// dominate any of the loop exits, then none of the values defined in the
// block could be used outside the loop.
for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
BB != E; ++BB) {
for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
++UI) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode* p = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = p->getIncomingBlock(OperandNo/2);
}
if (*BB != UserBB && !inLoop(UserBB)) {
AffectedValues.insert(I);
break;
}
}
}
}
/// GetValueForBlock - Get the value to use within the specified basic block.
/// available values are in Phis.
Value *LCSSA::GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis) {
// If there is no dominator info for this BB, it is unreachable.
if (BB == 0)
return UndefValue::get(OrigInst->getType());
// If we have already computed this value, return the previously computed val.
Value *&V = Phis[BB];
if (V) return V;
DomTreeNode *IDom = BB->getIDom();
// Otherwise, there are two cases: we either have to insert a PHI node or we
// don't. We need to insert a PHI node if this block is not dominated by one
// of the exit nodes from the loop (the loop could have multiple exits, and
// though the value defined *inside* the loop dominated all its uses, each
// exit by itself may not dominate all the uses).
//
// The simplest way to check for this condition is by checking to see if the
// idom is in the loop. If so, we *know* that none of the exit blocks
// dominate this block. Note that we *know* that the block defining the
// original instruction is in the idom chain, because if it weren't, then the
// original value didn't dominate this use.
if (!inLoop(IDom->getBlock())) {
// Idom is not in the loop, we must still be "below" the exit block and must
// be fully dominated by the value live in the idom.
return V = GetValueForBlock(IDom, OrigInst, Phis);
}
BasicBlock *BBN = BB->getBlock();
// Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
// now, then get values to fill in the incoming values for the PHI.
PHINode *PN = new PHINode(OrigInst->getType(), OrigInst->getName()+".lcssa",
BBN->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BBN), pred_end(BBN)));
V = PN;
// Fill in the incoming values for the block.
for (pred_iterator PI = pred_begin(BBN), E = pred_end(BBN); PI != E; ++PI)
PN->addIncoming(GetValueForBlock(DT->getNode(*PI), OrigInst, Phis), *PI);
return PN;
}
<commit_msg>LCSSA preserves dom info.<commit_after>//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by Owen Anderson and is distributed under the
// University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass transforms loops by placing phi nodes at the end of the loops for
// all values that are live across the loop boundary. For example, it turns
// the left into the right code:
//
// for (...) for (...)
// if (c) if (c)
// X1 = ... X1 = ...
// else else
// X2 = ... X2 = ...
// X3 = phi(X1, X2) X3 = phi(X1, X2)
// ... = X3 + 4 X4 = phi(X3)
// ... = X4 + 4
//
// This is still valid LLVM; the extra phi nodes are purely redundant, and will
// be trivially eliminated by InstCombine. The major benefit of this
// transformation is that it makes many other loop optimizations, such as
// LoopUnswitching, simpler.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "lcssa"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/Pass.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/Compiler.h"
#include <algorithm>
#include <map>
using namespace llvm;
STATISTIC(NumLCSSA, "Number of live out of a loop variables");
namespace {
struct VISIBILITY_HIDDEN LCSSA : public LoopPass {
static char ID; // Pass identification, replacement for typeid
LCSSA() : LoopPass((intptr_t)&ID) {}
// Cached analysis information for the current function.
LoopInfo *LI;
DominatorTree *DT;
std::vector<BasicBlock*> LoopBlocks;
virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
void ProcessInstruction(Instruction* Instr,
const std::vector<BasicBlock*>& exitBlocks);
/// This transformation requires natural loop information & requires that
/// loop preheaders be inserted into the CFG. It maintains both of these,
/// as well as the CFG. It also requires dominator information.
///
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
AU.addRequiredID(LoopSimplifyID);
AU.addPreservedID(LoopSimplifyID);
AU.addRequired<LoopInfo>();
AU.addPreserved<LoopInfo>();
AU.addRequired<DominatorTree>();
AU.addPreserved<ScalarEvolution>();
AU.addPreserved<DominatorTree>();
// Request DominanceFrontier now, even though LCSSA does
// not use it. This allows Pass Manager to schedule Dominance
// Frontier early enough such that one LPPassManager can handle
// multiple loop transformation passes.
AU.addRequired<DominanceFrontier>();
AU.addPreserved<DominanceFrontier>();
}
private:
void getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues);
Value *GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis);
/// inLoop - returns true if the given block is within the current loop
const bool inLoop(BasicBlock* B) {
return std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), B);
}
};
char LCSSA::ID = 0;
RegisterPass<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
}
LoopPass *llvm::createLCSSAPass() { return new LCSSA(); }
const PassInfo *llvm::LCSSAID = X.getPassInfo();
/// runOnFunction - Process all loops in the function, inner-most out.
bool LCSSA::runOnLoop(Loop *L, LPPassManager &LPM) {
LI = &LPM.getAnalysis<LoopInfo>();
DT = &getAnalysis<DominatorTree>();
// Speed up queries by creating a sorted list of blocks
LoopBlocks.clear();
LoopBlocks.insert(LoopBlocks.end(), L->block_begin(), L->block_end());
std::sort(LoopBlocks.begin(), LoopBlocks.end());
SetVector<Instruction*> AffectedValues;
getLoopValuesUsedOutsideLoop(L, AffectedValues);
// If no values are affected, we can save a lot of work, since we know that
// nothing will be changed.
if (AffectedValues.empty())
return false;
std::vector<BasicBlock*> exitBlocks;
L->getExitBlocks(exitBlocks);
// Iterate over all affected values for this loop and insert Phi nodes
// for them in the appropriate exit blocks
for (SetVector<Instruction*>::iterator I = AffectedValues.begin(),
E = AffectedValues.end(); I != E; ++I)
ProcessInstruction(*I, exitBlocks);
assert(L->isLCSSAForm());
return true;
}
/// processInstruction - Given a live-out instruction, insert LCSSA Phi nodes,
/// eliminate all out-of-loop uses.
void LCSSA::ProcessInstruction(Instruction *Instr,
const std::vector<BasicBlock*>& exitBlocks) {
++NumLCSSA; // We are applying the transformation
// Keep track of the blocks that have the value available already.
std::map<DomTreeNode*, Value*> Phis;
DomTreeNode *InstrNode = DT->getNode(Instr->getParent());
// Insert the LCSSA phi's into the exit blocks (dominated by the value), and
// add them to the Phi's map.
for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
DomTreeNode *ExitBBNode = DT->getNode(BB);
Value *&Phi = Phis[ExitBBNode];
if (!Phi && DT->dominates(InstrNode, ExitBBNode)) {
PHINode *PN = new PHINode(Instr->getType(), Instr->getName()+".lcssa",
BB->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BB), pred_end(BB)));
// Remember that this phi makes the value alive in this block.
Phi = PN;
// Add inputs from inside the loop for this PHI.
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
PN->addIncoming(Instr, *PI);
}
}
// Record all uses of Instr outside the loop. We need to rewrite these. The
// LCSSA phis won't be included because they use the value in the loop.
for (Value::use_iterator UI = Instr->use_begin(), E = Instr->use_end();
UI != E;) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode *P = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = P->getIncomingBlock(OperandNo/2);
}
// If the user is in the loop, don't rewrite it!
if (UserBB == Instr->getParent() || inLoop(UserBB)) {
++UI;
continue;
}
// Otherwise, patch up uses of the value with the appropriate LCSSA Phi,
// inserting PHI nodes into join points where needed.
Value *Val = GetValueForBlock(DT->getNode(UserBB), Instr, Phis);
// Preincrement the iterator to avoid invalidating it when we change the
// value.
Use &U = UI.getUse();
++UI;
U.set(Val);
}
}
/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
/// are used by instructions outside of it.
void LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
SetVector<Instruction*> &AffectedValues) {
// FIXME: For large loops, we may be able to avoid a lot of use-scanning
// by using dominance information. In particular, if a block does not
// dominate any of the loop exits, then none of the values defined in the
// block could be used outside the loop.
for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
BB != E; ++BB) {
for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
++UI) {
BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
if (PHINode* p = dyn_cast<PHINode>(*UI)) {
unsigned OperandNo = UI.getOperandNo();
UserBB = p->getIncomingBlock(OperandNo/2);
}
if (*BB != UserBB && !inLoop(UserBB)) {
AffectedValues.insert(I);
break;
}
}
}
}
/// GetValueForBlock - Get the value to use within the specified basic block.
/// available values are in Phis.
Value *LCSSA::GetValueForBlock(DomTreeNode *BB, Instruction *OrigInst,
std::map<DomTreeNode*, Value*> &Phis) {
// If there is no dominator info for this BB, it is unreachable.
if (BB == 0)
return UndefValue::get(OrigInst->getType());
// If we have already computed this value, return the previously computed val.
Value *&V = Phis[BB];
if (V) return V;
DomTreeNode *IDom = BB->getIDom();
// Otherwise, there are two cases: we either have to insert a PHI node or we
// don't. We need to insert a PHI node if this block is not dominated by one
// of the exit nodes from the loop (the loop could have multiple exits, and
// though the value defined *inside* the loop dominated all its uses, each
// exit by itself may not dominate all the uses).
//
// The simplest way to check for this condition is by checking to see if the
// idom is in the loop. If so, we *know* that none of the exit blocks
// dominate this block. Note that we *know* that the block defining the
// original instruction is in the idom chain, because if it weren't, then the
// original value didn't dominate this use.
if (!inLoop(IDom->getBlock())) {
// Idom is not in the loop, we must still be "below" the exit block and must
// be fully dominated by the value live in the idom.
return V = GetValueForBlock(IDom, OrigInst, Phis);
}
BasicBlock *BBN = BB->getBlock();
// Otherwise, the idom is the loop, so we need to insert a PHI node. Do so
// now, then get values to fill in the incoming values for the PHI.
PHINode *PN = new PHINode(OrigInst->getType(), OrigInst->getName()+".lcssa",
BBN->begin());
PN->reserveOperandSpace(std::distance(pred_begin(BBN), pred_end(BBN)));
V = PN;
// Fill in the incoming values for the block.
for (pred_iterator PI = pred_begin(BBN), E = pred_end(BBN); PI != E; ++PI)
PN->addIncoming(GetValueForBlock(DT->getNode(*PI), OrigInst, Phis), *PI);
return PN;
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QString>
#include <QStandardItemModel>
#include <QAction>
#include <QMenu>
#include <QHeaderView>
#include <QTimer>
#include "common.h"
#include "event.h"
#include "task_board.h"
namespace Plow {
namespace Gui {
QStringList TaskBoardModel::HeaderLabels = QStringList()
<< "Name"
<< "State"
<< "Node"
<< "Duration"
<< "Log";
const int COLUMNS = 5;
// Return this rather than creating empty variants
// all the time.
const QVariant EMPTY_VARIANT;
/* TaskBoardWidget
**------------------------------------------------*/
TaskBoardWidget::TaskBoardWidget(QWidget* parent) :
QWidget(parent),
m_filter(new TaskFilterT()),
m_layers(new QPushButton(this)),
m_states(new QPushButton(this)),
m_job_name(new QLabel(this)),
m_view(new TaskBoardView(this))
{
m_layers->setText("Layers");
m_layers->setMenu(new QMenu(this));
m_states->setText("States");
m_states->setMenu(new QMenu(this));
m_view->horizontalHeader()->setStretchLastSection(true);
std::map<int, const char*>::const_iterator iter;
for (iter = _TaskState_VALUES_TO_NAMES.begin();
iter != _TaskState_VALUES_TO_NAMES.end(); ++iter)
{
QAction* action = new QAction(
QString(iter->second), m_states->menu());
action->setData(iter->first);
action->setCheckable(true);
m_states->menu()->addAction(action);
}
QHBoxLayout* ctl_layout = new QHBoxLayout();
ctl_layout->addWidget(m_layers);
ctl_layout->addWidget(m_states);
ctl_layout->addStretch();
ctl_layout->addWidget(m_job_name);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addLayout(ctl_layout);
layout->addWidget(m_view);
connect(EventManager::getInstance(), SIGNAL(jobSelected(QString)),
this, SLOT(handleJobSelected(QString)));
m_model = 0;
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(refreshModel()));
}
TaskBoardWidget::~TaskBoardWidget()
{
delete m_timer;
}
void TaskBoardWidget::refreshModel()
{
if (m_model)
{
m_model->refresh();
}
}
void TaskBoardWidget::handleJobSelected(const QString& id)
{
JobT job;
getJobById(job, id.toStdString());
setJob(job);
}
void TaskBoardWidget::setJob(const JobT& job)
{
// Stop the timer
m_timer->stop();
std::vector<LayerT> layers;
Plow::getLayers(layers, job);
// Update the layer display
m_layers->menu()->clear();
for (int r = 0; r < layers.size(); ++r)
{
QAction* action = new QAction(
QString::fromStdString(layers[r].name), m_layers->menu());
action->setCheckable(true);
m_layers->menu()->addAction(action);
}
// Set up a new model
m_filter->jobId = job.id;
TaskBoardModel* model = new TaskBoardModel(*m_filter, this);
model->init();
m_job_name->setText(QString::fromStdString(job.name));
m_view->setModel(model);
m_view->setColumnWidth(0, 350);
// If we have an old model set, delete it.
if (m_model) {
delete m_model;
m_model = 0;
}
// Set the model and restart the timer.
m_model = model;
m_timer->start(3000);
}
TaskFilterT* TaskBoardWidget::getTaskFilter() const
{
return m_filter;
}
/* TaskBoardView
**------------------------------------------------*/
TaskBoardView::TaskBoardView(QWidget* parent) :
QTableView(parent)
{
connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
this, SLOT(taskDoubleClickedHandler(const QModelIndex&)));
}
TaskBoardView::~TaskBoardView()
{
}
void TaskBoardView::taskDoubleClickedHandler(const QModelIndex& index)
{
QString taskId = model()->data(index, Qt::UserRole).toString();
//TODO: add log file viewer.
}
/* TaskBoardModel
**------------------------------------------------*/
TaskBoardModel::TaskBoardModel(TaskFilterT filter, QObject* parent) :
QAbstractTableModel(parent),
m_filter(filter)
{
}
TaskBoardModel::~TaskBoardModel()
{
m_timer->stop();
delete m_timer;
}
void TaskBoardModel::init()
{
uint64_t qtime = getPlowTime();
getTasks(m_tasks, m_filter);
m_filter.lastUpdateTime = qtime;
for(int i=0; i<m_tasks.size(); i++) {
m_index[m_tasks[i].id] = i;
}
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(refreshRunningTime()));
m_timer->start(1000);
}
void TaskBoardModel::refresh()
{
// Get the time from the server.
uint64_t plow_time = getPlowTime();
// Make a query to get the tasks since the last update time.
std::vector<TaskT> updated;
getTasks(updated, m_filter);
// Set the update time for the next query;
m_filter.lastUpdateTime = plow_time;
std::vector<TaskT>::iterator iter;
for (iter = updated.begin(); iter != updated.end(); ++iter)
{
int idx = m_index[iter->id];
m_tasks[idx] = *iter;
emit dataChanged(index(idx, 0), index(idx, COLUMNS-1));
}
}
void TaskBoardModel::refreshRunningTime()
{
std::vector<TaskT>::iterator iter;
for (iter = m_tasks.begin(); iter != m_tasks.end(); ++iter)
{
if (iter->state == TaskState::RUNNING)
{
emit dataChanged(index(m_index[iter->id], 0),
index(m_index[iter->id], COLUMNS-1));
}
}
}
int TaskBoardModel::rowCount(const QModelIndex& parent) const
{
return m_tasks.size();
}
int TaskBoardModel::columnCount (const QModelIndex& parent) const
{
return COLUMNS;
}
QVariant TaskBoardModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal) {
return EMPTY_VARIANT;
}
switch(role)
{
case Qt::DisplayRole:
return TaskBoardModel::HeaderLabels[section];
}
return EMPTY_VARIANT;
}
QVariant TaskBoardModel::data (const QModelIndex & index, int role) const
{
int row = index.row();
int col = index.column();
const TaskT& task = m_tasks[row];
switch(role)
{
case Qt::DisplayRole:
if (col == 0)
{
return QString(task.name.c_str());
}
else if (col == 1)
{
int state = task.state;
return QString(_TaskState_VALUES_TO_NAMES.find(state)->second);
}
else if (col == 2)
{
return QString(task.lastNodeName.c_str());
}
else if (col == 3)
{
std::string duration;
formatDuration(duration, task.startTime, task.stopTime);
return QString::fromStdString(duration);
}
else if (col == 4) {
return QString(task.lastLogLine.c_str());
}
break;
case Qt::BackgroundRole:
if (col == 1)
{
int state = task.state;
return PlowStyle::TaskColors[state];
}
break;
case Qt::UserRole:
return QString::fromStdString(task.id);
}
return EMPTY_VARIANT;
}
} //
} //<commit_msg>Simplified the horizontal header code.<commit_after>#include <vector>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QString>
#include <QStandardItemModel>
#include <QAction>
#include <QMenu>
#include <QHeaderView>
#include <QTimer>
#include "common.h"
#include "event.h"
#include "task_board.h"
namespace Plow {
namespace Gui {
QStringList TaskBoardModel::HeaderLabels = QStringList()
<< "Name"
<< "State"
<< "Node"
<< "Duration"
<< "Log";
const int COLUMNS = TaskBoardModel::HeaderLabels.size();
// Return this rather than creating empty variants
// all the time.
const QVariant EMPTY_VARIANT;
/* TaskBoardWidget
**------------------------------------------------*/
TaskBoardWidget::TaskBoardWidget(QWidget* parent) :
QWidget(parent),
m_filter(new TaskFilterT()),
m_layers(new QPushButton(this)),
m_states(new QPushButton(this)),
m_job_name(new QLabel(this)),
m_view(new TaskBoardView(this))
{
m_layers->setText("Layers");
m_layers->setMenu(new QMenu(this));
m_states->setText("States");
m_states->setMenu(new QMenu(this));
m_view->horizontalHeader()->setStretchLastSection(true);
std::map<int, const char*>::const_iterator iter;
for (iter = _TaskState_VALUES_TO_NAMES.begin();
iter != _TaskState_VALUES_TO_NAMES.end(); ++iter)
{
QAction* action = new QAction(
QString(iter->second), m_states->menu());
action->setData(iter->first);
action->setCheckable(true);
m_states->menu()->addAction(action);
}
QHBoxLayout* ctl_layout = new QHBoxLayout();
ctl_layout->addWidget(m_layers);
ctl_layout->addWidget(m_states);
ctl_layout->addStretch();
ctl_layout->addWidget(m_job_name);
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addLayout(ctl_layout);
layout->addWidget(m_view);
connect(EventManager::getInstance(), SIGNAL(jobSelected(QString)),
this, SLOT(handleJobSelected(QString)));
m_model = 0;
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(refreshModel()));
}
TaskBoardWidget::~TaskBoardWidget()
{
delete m_timer;
}
void TaskBoardWidget::refreshModel()
{
if (m_model)
{
m_model->refresh();
}
}
void TaskBoardWidget::handleJobSelected(const QString& id)
{
JobT job;
getJobById(job, id.toStdString());
setJob(job);
}
void TaskBoardWidget::setJob(const JobT& job)
{
// Stop the timer
m_timer->stop();
std::vector<LayerT> layers;
Plow::getLayers(layers, job);
// Update the layer display
m_layers->menu()->clear();
for (int r = 0; r < layers.size(); ++r)
{
QAction* action = new QAction(
QString::fromStdString(layers[r].name), m_layers->menu());
action->setCheckable(true);
m_layers->menu()->addAction(action);
}
// Set up a new model
m_filter->jobId = job.id;
TaskBoardModel* model = new TaskBoardModel(*m_filter, this);
model->init();
m_job_name->setText(QString::fromStdString(job.name));
m_view->setModel(model);
m_view->setColumnWidth(0, 350);
// If we have an old model set, delete it.
if (m_model) {
delete m_model;
m_model = 0;
}
// Set the model and restart the timer.
m_model = model;
m_timer->start(3000);
}
TaskFilterT* TaskBoardWidget::getTaskFilter() const
{
return m_filter;
}
/* TaskBoardView
**------------------------------------------------*/
TaskBoardView::TaskBoardView(QWidget* parent) :
QTableView(parent)
{
connect(this, SIGNAL(doubleClicked(const QModelIndex&)),
this, SLOT(taskDoubleClickedHandler(const QModelIndex&)));
}
TaskBoardView::~TaskBoardView()
{
}
void TaskBoardView::taskDoubleClickedHandler(const QModelIndex& index)
{
QString taskId = model()->data(index, Qt::UserRole).toString();
//TODO: add log file viewer.
}
/* TaskBoardModel
**------------------------------------------------*/
TaskBoardModel::TaskBoardModel(TaskFilterT filter, QObject* parent) :
QAbstractTableModel(parent),
m_filter(filter)
{
}
TaskBoardModel::~TaskBoardModel()
{
m_timer->stop();
delete m_timer;
}
void TaskBoardModel::init()
{
uint64_t qtime = getPlowTime();
getTasks(m_tasks, m_filter);
m_filter.lastUpdateTime = qtime;
for(int i=0; i<m_tasks.size(); i++) {
m_index[m_tasks[i].id] = i;
}
m_timer = new QTimer(this);
connect(m_timer, SIGNAL(timeout()), this, SLOT(refreshRunningTime()));
m_timer->start(1000);
}
void TaskBoardModel::refresh()
{
// Get the time from the server.
uint64_t plow_time = getPlowTime();
// Make a query to get the tasks since the last update time.
std::vector<TaskT> updated;
getTasks(updated, m_filter);
// Set the update time for the next query;
m_filter.lastUpdateTime = plow_time;
std::vector<TaskT>::iterator iter;
for (iter = updated.begin(); iter != updated.end(); ++iter)
{
int idx = m_index[iter->id];
m_tasks[idx] = *iter;
emit dataChanged(index(idx, 0), index(idx, COLUMNS-1));
}
}
void TaskBoardModel::refreshRunningTime()
{
std::vector<TaskT>::iterator iter;
for (iter = m_tasks.begin(); iter != m_tasks.end(); ++iter)
{
if (iter->state == TaskState::RUNNING)
{
emit dataChanged(index(m_index[iter->id], 0),
index(m_index[iter->id], COLUMNS-1));
}
}
}
int TaskBoardModel::rowCount(const QModelIndex& parent) const
{
return m_tasks.size();
}
int TaskBoardModel::columnCount (const QModelIndex& parent) const
{
return COLUMNS;
}
QVariant TaskBoardModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal)
{
return TaskBoardModel::HeaderLabels[section];
}
return EMPTY_VARIANT;
}
QVariant TaskBoardModel::data (const QModelIndex & index, int role) const
{
int row = index.row();
int col = index.column();
const TaskT& task = m_tasks[row];
switch(role)
{
case Qt::DisplayRole:
if (col == 0)
{
return QString(task.name.c_str());
}
else if (col == 1)
{
int state = task.state;
return QString(_TaskState_VALUES_TO_NAMES.find(state)->second);
}
else if (col == 2)
{
return QString(task.lastNodeName.c_str());
}
else if (col == 3)
{
std::string duration;
formatDuration(duration, task.startTime, task.stopTime);
return QString::fromStdString(duration);
}
else if (col == 4) {
return QString(task.lastLogLine.c_str());
}
break;
case Qt::BackgroundRole:
if (col == 1)
{
int state = task.state;
return PlowStyle::TaskColors[state];
}
break;
case Qt::UserRole:
return QString::fromStdString(task.id);
}
return EMPTY_VARIANT;
}
} //
} //<|endoftext|>
|
<commit_before>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_TRACE_HH
#define PEGTL_TRACE_HH
#include <iostream>
#include "parse.hh"
#include "normal.hh"
#include "nothing.hh"
#include "position_info.hh"
#include "internal/demangle.hh"
namespace pegtl
{
template< typename Rule >
struct tracer
: normal< Rule >
{
template< typename Input, typename ... States >
static void start( const Input & in, States && ... )
{
std::cerr << position_info( in ) << " start " << internal::demangle< Rule >() << std::endl;
}
template< typename Input, typename ... States >
static void success( const Input & in, States && ... )
{
std::cerr << position_info( in ) << " success " << internal::demangle< Rule >() << std::endl;
}
template< typename Input, typename ... States >
static void failure( const Input & in, States && ... )
{
std::cerr << position_info( in ) << " failure " << internal::demangle< Rule >() << std::endl;
}
};
template< typename Rule, template< typename ... > class Action = nothing, typename ... Args >
void trace( Args && ... args )
{
parse< Rule, Action, tracer >( std::forward< Args >( args ) ... );
}
} // pegtl
#endif
<commit_msg>Pass result from parse() to trace()<commit_after>// Copyright (c) 2014-2015 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/ColinH/PEGTL/
#ifndef PEGTL_TRACE_HH
#define PEGTL_TRACE_HH
#include <iostream>
#include "parse.hh"
#include "normal.hh"
#include "nothing.hh"
#include "position_info.hh"
#include "internal/demangle.hh"
namespace pegtl
{
template< typename Rule >
struct tracer
: normal< Rule >
{
template< typename Input, typename ... States >
static void start( const Input & in, States && ... )
{
std::cerr << position_info( in ) << " start " << internal::demangle< Rule >() << std::endl;
}
template< typename Input, typename ... States >
static void success( const Input & in, States && ... )
{
std::cerr << position_info( in ) << " success " << internal::demangle< Rule >() << std::endl;
}
template< typename Input, typename ... States >
static void failure( const Input & in, States && ... )
{
std::cerr << position_info( in ) << " failure " << internal::demangle< Rule >() << std::endl;
}
};
template< typename Rule, template< typename ... > class Action = nothing, typename ... Args >
bool trace( Args && ... args )
{
return parse< Rule, Action, tracer >( std::forward< Args >( args ) ... );
}
} // pegtl
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright (C) 2016 Felix Rohrbach <kde@fxrh.de>
*
* 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 "mediathumbnailjob.h"
using namespace Quotient;
QUrl MediaThumbnailJob::makeRequestUrl(QUrl baseUrl, const QUrl& mxcUri,
QSize requestedSize)
{
return makeRequestUrl(std::move(baseUrl), mxcUri.authority(),
mxcUri.path().mid(1), requestedSize.width(),
requestedSize.height());
}
MediaThumbnailJob::MediaThumbnailJob(const QString& serverName,
const QString& mediaId, QSize requestedSize)
: GetContentThumbnailJob(serverName, mediaId, requestedSize.width(),
requestedSize.height())
{}
MediaThumbnailJob::MediaThumbnailJob(const QUrl& mxcUri, QSize requestedSize)
: MediaThumbnailJob(mxcUri.authority(),
mxcUri.path().mid(1), // sans leading '/'
requestedSize)
{}
QImage MediaThumbnailJob::thumbnail() const { return _thumbnail; }
QImage MediaThumbnailJob::scaledThumbnail(QSize toSize) const
{
return _thumbnail.scaled(toSize, Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
BaseJob::Status MediaThumbnailJob::parseReply(QNetworkReply* reply)
{
auto result = GetContentThumbnailJob::parseReply(reply);
if (!result.good())
return result;
if (_thumbnail.loadFromData(data()->readAll()))
return Success;
return { IncorrectResponseError,
QStringLiteral("Could not read image data") };
}
<commit_msg>MediaThumbnailJob: be specific about the transform<commit_after>/******************************************************************************
* Copyright (C) 2016 Felix Rohrbach <kde@fxrh.de>
*
* 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 "mediathumbnailjob.h"
using namespace Quotient;
QUrl MediaThumbnailJob::makeRequestUrl(QUrl baseUrl, const QUrl& mxcUri,
QSize requestedSize)
{
return makeRequestUrl(std::move(baseUrl), mxcUri.authority(),
mxcUri.path().mid(1), requestedSize.width(),
requestedSize.height());
}
MediaThumbnailJob::MediaThumbnailJob(const QString& serverName,
const QString& mediaId, QSize requestedSize)
: GetContentThumbnailJob(serverName, mediaId, requestedSize.width(),
requestedSize.height(), "scale")
{}
MediaThumbnailJob::MediaThumbnailJob(const QUrl& mxcUri, QSize requestedSize)
: MediaThumbnailJob(mxcUri.authority(),
mxcUri.path().mid(1), // sans leading '/'
requestedSize)
{}
QImage MediaThumbnailJob::thumbnail() const { return _thumbnail; }
QImage MediaThumbnailJob::scaledThumbnail(QSize toSize) const
{
return _thumbnail.scaled(toSize, Qt::KeepAspectRatio,
Qt::SmoothTransformation);
}
BaseJob::Status MediaThumbnailJob::parseReply(QNetworkReply* reply)
{
auto result = GetContentThumbnailJob::parseReply(reply);
if (!result.good())
return result;
if (_thumbnail.loadFromData(data()->readAll()))
return Success;
return { IncorrectResponseError,
QStringLiteral("Could not read image data") };
}
<|endoftext|>
|
<commit_before>#include "pgxconsole.h"
#include "queryview.h"
#include "explainview.h"
#include <QSqlQueryModel>
#include <QSqlQuery>
PgxConsole::PgxConsole(QWidget *parent) : QPlainTextEdit(parent)
{
setViewportMargins(10, 0, 0, 0);
setTabStopWidth(40);
setUndoRedoEnabled(false);
setCaption(QApplication::translate("PgxConsole", "SQL console", 0, QApplication::UnicodeUTF8));
setGeometry(100,100,640,480);
setStyleSheet("QPlainTextEdit{background-color: white; font: bold 14px;}");
highlighter = new Highlighter(document());
prompt = new Prompt(this);
QShortcut *shortcut_paste = new QShortcut(QKeySequence::Paste, this);
connect(shortcut_paste, SIGNAL(activated()), this, SLOT(paste_cmd()));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(curChanged()));
connect(this, SIGNAL(cmd(QKeyEvent *)), this, SLOT(showView(QKeyEvent *)));
connect(this, SIGNAL(histUp()), this, SLOT(histUpCmd()));
connect(this, SIGNAL(histDn()), this, SLOT(histDnCmd()));
//connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updatePromptWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updatePrompt(QRect,int)));
//updatePromptWidth(0);
}
/*
void PgxConsole::updatePromptWidth(int)
{
setViewportMargins(10, 0, 0, 0);
}
*/
void PgxConsole::updatePrompt(const QRect &rect, int dy)
{
if (dy)
prompt->scroll(0, dy);
else
prompt->update(0, rect.y(), prompt->width(), rect.height());
//if (rect.contains(viewport()->rect()))
// updatePromptWidth(0);
}
void PgxConsole::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
prompt->setGeometry(QRect(cr.left(), cr.top(), 10, cr.height()));
}
void PgxConsole::promptPaintEvent(QPaintEvent *event)
{
QPainter painter(prompt);
//painter.fillRect(event->rect(), Qt::white);
QTextBlock block = firstVisibleBlock();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString pr;
if(block.text().startsWith("ERROR")) {
pr = QString("x");
painter.setPen(QColor(255,127,127));
}
else if(block.text().startsWith("Driver not loaded")) {
pr = QString("x");
painter.setPen(QColor(255,127,127));
}
else if(block.text().startsWith("WARNING")) {
pr = QString(" ");
painter.setPen(QColor(255,127,127));
}
else if(block.text().startsWith("MESSAGE")) {
pr = QString(" ");
painter.setPen(QColor(255,127,127));
}
else// if(block == firstVisibleBlock()) {
{
pr = QString(">");
painter.setPen(Qt::lightGray);
}
painter.drawText(0, top, prompt->width(), fontMetrics().height(),
Qt::AlignCenter, pr);
}
QTextBlock prevBlock = block.previous();
block = block.next();
//if(prevBlock.isVisible() && prevBlock.isValid())
//{
// if (prevBlock.text().endsWith("\\")) {
// painter.setPen(Qt::lightGray);
// painter.drawText(0, top, prompt->width(), fontMetrics().height(),
// Qt::AlignRight, "+");
// }
// else if(prevBlock.text().startsWith("ERROR"))
// {
// painter.setPen(Qt::red);
// painter.drawText(0, top, prompt->width(), fontMetrics().height(),
// Qt::AlignRight, "x");
// }
// else
// {
// painter.setPen(Qt::lightGray);
// painter.drawText(0, top, prompt->width(), fontMetrics().height(),
// Qt::AlignRight, ">");
// }
//}
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
}
}
void PgxConsole::keyPressEvent(QKeyEvent * e)
{
switch(e->key()) {
case Qt::Key_Up:
emit histUp();
break;
case Qt::Key_Down:
emit histDn();
break;
case Qt::Key_Left:
if(!textCursor().atBlockStart())
QPlainTextEdit::keyPressEvent(e);
break;
case Qt::Key_Backspace:
if(!textCursor().atBlockStart())
QPlainTextEdit::keyPressEvent(e);
break;
case Qt::Key_Return:
case Qt::Key_Enter:
emit cmd(e);
//QPlainTextEdit::keyPressEvent(e);
break;
case Qt::Key_Backslash:
QPlainTextEdit::keyPressEvent(e);
appendPlainText("");
break;
default:
QPlainTextEdit::keyPressEvent(e);
}
}
void PgxConsole::wheelEvent(QWheelEvent *wheelEvent)
{
// BEGIN TODO 2
wheelEvent->accept();
QFontMetrics df = fontMetrics();
// END TODO 2
}
void PgxConsole::showView(QKeyEvent * e)
{
if(!textCursor().atEnd()) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
}
QTextBlock block = document()->end();
if(!block.isValid())
block = block.previous();
QString cmd = block.text().trimmed();
for (block = block.previous(); block.text().endsWith("\\"); block = block.previous())
cmd.insert(0, block.text().trimmed().replace(QString("\\"), QString(" ")));
// Do nothing on whitespace input.
if(cmd.trimmed().isEmpty()) {
appendPlainText("");
return;
}
// Save the command into the command history and
// reassign the history iterator.
history << cmd;
hit = history.size();
// 'clear' command to clear the console keeping the
// history intact.
if(cmd.compare("clear", Qt::CaseInsensitive) == 0) {
clear();
return;
}
// 'clear' command to clear the history alone. Console
// is not cleared.
else if(cmd.compare("clearh", Qt::CaseInsensitive) == 0) {
history.clear();
hit = 0;
appendPlainText("");
return;
}
// 'clearall' command to clear console and history
else if(cmd.compare("clearall", Qt::CaseInsensitive) == 0) {
history.clear();
hit =0;
clear();
return;
}
// Reduce all groups of whitespace characters
// to a single space between words.
cmd = cmd.simplified();
// Start a timer to count the seconds taken to display the
// required output (used for queries and tables only).
QTime t;
t.start();
// Don't execute SELECT INTO queries.
// Suggest CREATE TABLE AS construct.
QRegExp rx("\\bINTO\\b\\s+[\\w]*\\s+\\bFROM\\b", Qt::CaseInsensitive);
if(cmd.startsWith("select", Qt::CaseInsensitive) &&
cmd.contains(rx)) {
appendPlainText(QApplication::translate(
"PgxConsole", "WARNING: SELECT INTO deprecated. Use CREATE TABLE AS construct instead.\n",
0, QApplication::UnicodeUTF8));
return;
}
// EXPLAIN queries display.
else if(cmd.startsWith("explain", Qt::CaseInsensitive))
{
/*!
@todo EXPLAIN ANALYZE on DML statements.
* Explain analyze executes the DML thereby altering data.
* This can be potentially hazardous when the intention is
* to only check the query run time, rows affected, etc.
* The proper way to implement this is to enclose the DML
* in a transaction block like so:
* @code
* BEGIN;
* {DML};
* ROLLBACK;
* @endcode
* Yet to be implemented. EXPLAIN ANALYZE on
* DML are disabled for now.
*/
if(cmd.startsWith("explain analyze update", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze insert", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze delete", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze verbose update", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze verbose insert", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze verbose delete", Qt::CaseInsensitive))
{
appendPlainText(QApplication::translate("PgxConsole", "WARNING: EXPLAIN ANAYZE for DML not supported at this time.\n", 0, QApplication::UnicodeUTF8));
return;
}
QSqlQueryModel* model = new QSqlQueryModel;
model->setQuery(cmd);
if (model->lastError().isValid()) {
appendHtml(model->lastError().databaseText());
appendPlainText("");
return;
}
ExplainView* eview = new ExplainView(model, cmd, Qt::WA_DeleteOnClose);
int width = eview->verticalHeader()->width();
if(eview->verticalScrollBar()->isVisible()) {
width += eview->verticalScrollBar()->width();
}
eview->setColumnWidth(0, eview->width() - width);
eview->resizeRowsToContents();
eview->show();
}
// DDL, DML queries display.
else
{
if((cmd.startsWith("update", Qt::CaseInsensitive) ||
cmd.startsWith("insert", Qt::CaseInsensitive) ||
cmd.startsWith("delete", Qt::CaseInsensitive) ||
cmd.startsWith("truncate", Qt::CaseInsensitive)) &&
!cmd.contains("returning", Qt::CaseInsensitive))
{
QSqlQuery* sqlqry = new QSqlQuery;
sqlqry->exec(cmd);
if (sqlqry->lastError().isValid()) {
appendHtml(sqlqry->lastError().databaseText());
appendPlainText("");
return;
}
QString mesg = QApplication::translate("PgxConsole", "MESSAGE: Rows affected = ", 0, QApplication::UnicodeUTF8);
appendHtml(mesg.append(QString::number(sqlqry->numRowsAffected())));
appendPlainText("");
return;
}
else
{
QSqlQueryModel* model = new QSqlQueryModel;
model->setQuery(cmd);
if (model->lastError().isValid()) {
appendHtml(model->lastError().databaseText());
appendPlainText("");
return;
}
if(model->rowCount() == 0) {
appendPlainText(QApplication::translate("PgxConsole", "MESSAGE: No rows to display.\n", 0, QApplication::UnicodeUTF8));
return;
}
QueryView* qview = new QueryView(0, model, cmd, t.elapsed(), model->rowCount(),
model->columnCount(), Qt::WA_DeleteOnClose);
qview->show();
}
}
appendPlainText("");
}
void PgxConsole::curChanged()
{
if(textCursor().block().next().isValid())
setReadOnly(true);
else
setReadOnly(false);
}
void PgxConsole::paste_cmd()
{
QTextCursor cursor = textCursor();
if(textCursor().block().next().isValid()) {
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
paste();
}
else
paste();
}
void PgxConsole::histUpCmd()
{
if(!history.isEmpty() && hit > 0) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
cursor.select(QTextCursor::BlockUnderCursor);
if(cursor.hasSelection()) {
cursor.removeSelectedText();
appendPlainText(history.at(--hit));
}
else {
insertPlainText(history.at(--hit));
}
}
}
void PgxConsole::histDnCmd()
{
if(!history.isEmpty() && hit < history.size()) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
cursor.select(QTextCursor::BlockUnderCursor);
if(cursor.hasSelection()) {
cursor.removeSelectedText();
appendPlainText(history.value(++hit));
}
else {
insertPlainText(history.value(++hit));
}
}
ensureCursorVisible();
}
void PgxConsole::createWidgets()
{
QStringList wordList;
wordList << "alpha" << "omega" << "omicron" << "zeta";
completer = new QCompleter(wordList, this);
completer->setWidget(this);
completer->setCompletionMode(QCompleter::PopupCompletion);
completer->setWrapAround(true);
}
Highlighter::Highlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
classFormat.setFontWeight(QFont::Bold);
classFormat.setForeground(Qt::darkBlue);
rule.pattern = QRegExp("\\b[A-Za-z]+\\b");
rule.format = classFormat;
highlightingRules.append(rule);
keywordFormat.setForeground(Qt::darkCyan);
keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns;
keywordPatterns << "\\bselect\\b" << "\\bupdate\\b" << "\\bdelete\\b"
<< "\\btruncate\\b" << "\\bunion\\b" << "\\ball\\b"
<< "\\bintersect\\b" << "\\bexcept\\b";
foreach (const QString &pattern, keywordPatterns) {
rule.pattern = QRegExp(pattern, Qt::CaseInsensitive);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
keywordFormat2.setForeground(Qt::darkGreen);
keywordFormat2.setFontItalic(true);
QStringList keywordPatterns2;
keywordPatterns2 << "\\bfrom\\b" << "\\bin\\b" << "\\bwith\\b"
<< "\\bjoin\\b" << "\\bon\\b" << "\\bgroup by\\b"
<< "\\bleft\\b" << "\\right\\b" << "\\bfull\\b" << "\\bcross\\b"
<< "\\binner\\b" << "\\bouter\\b" << "\\bnatural\\b"
<< "\\border by\\b" << "\\blimit\\b" << "\\bfetch\\b"
<< "\\bhaving\\b" << "\\bwindow\\b" << "\\boffset\\b";
foreach (const QString &pattern, keywordPatterns2) {
rule.pattern = QRegExp(pattern, Qt::CaseInsensitive);
rule.format = keywordFormat2;
highlightingRules.append(rule);
}
singleQuotFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegExp("\'([^\']*)\'");
rule.format = singleQuotFormat;
highlightingRules.append(rule);
doubleQuotFormat.setForeground(Qt::darkGray);
rule.pattern = QRegExp("\"([^\"]*)\"");
rule.format = doubleQuotFormat;
highlightingRules.append(rule);
functionFormat.setFontWeight(QFont::Bold);
functionFormat.setForeground(Qt::blue);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
}
void Highlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
}
<commit_msg>Edited pgxconsole.cpp via GitHub<commit_after>#include "pgxconsole.h"
#include "queryview.h"
#include "explainview.h"
#include <QSqlQueryModel>
#include <QSqlQuery>
PgxConsole::PgxConsole(QWidget *parent) : QPlainTextEdit(parent)
{
setViewportMargins(10, 0, 0, 0);
setTabStopWidth(40);
setUndoRedoEnabled(false);
setCaption(QApplication::translate("PgxConsole", "SQL console", 0, QApplication::UnicodeUTF8));
setGeometry(100,100,640,480);
setStyleSheet("QPlainTextEdit{background-color: white; font: bold 14px;}");
highlighter = new Highlighter(document());
prompt = new Prompt(this);
QShortcut *shortcut_paste = new QShortcut(QKeySequence::Paste, this);
connect(shortcut_paste, SIGNAL(activated()), this, SLOT(paste_cmd()));
connect(this, SIGNAL(cursorPositionChanged()), this, SLOT(curChanged()));
connect(this, SIGNAL(cmd(QKeyEvent *)), this, SLOT(showView(QKeyEvent *)));
connect(this, SIGNAL(histUp()), this, SLOT(histUpCmd()));
connect(this, SIGNAL(histDn()), this, SLOT(histDnCmd()));
//connect(this, SIGNAL(blockCountChanged(int)), this, SLOT(updatePromptWidth(int)));
connect(this, SIGNAL(updateRequest(QRect,int)), this, SLOT(updatePrompt(QRect,int)));
//updatePromptWidth(0);
}
/*
void PgxConsole::updatePromptWidth(int)
{
setViewportMargins(10, 0, 0, 0);
}
*/
void PgxConsole::updatePrompt(const QRect &rect, int dy)
{
if (dy)
prompt->scroll(0, dy);
else
prompt->update(0, rect.y(), prompt->width(), rect.height());
//if (rect.contains(viewport()->rect()))
// updatePromptWidth(0);
}
void PgxConsole::resizeEvent(QResizeEvent *e)
{
QPlainTextEdit::resizeEvent(e);
QRect cr = contentsRect();
prompt->setGeometry(QRect(cr.left(), cr.top(), 10, cr.height()));
}
void PgxConsole::promptPaintEvent(QPaintEvent *event)
{
QPainter painter(prompt);
//painter.fillRect(event->rect(), Qt::white);
QTextBlock block = firstVisibleBlock();
int top = (int) blockBoundingGeometry(block).translated(contentOffset()).top();
int bottom = top + (int) blockBoundingRect(block).height();
while (block.isValid() && top <= event->rect().bottom()) {
if (block.isVisible() && bottom >= event->rect().top()) {
QString pr;
if(block.text().startsWith("ERROR")) {
pr = QString("x");
painter.setPen(QColor(255,127,127));
}
else if(block.text().startsWith("Driver not loaded")) {
pr = QString("x");
painter.setPen(QColor(255,127,127));
}
else if(block.text().startsWith("WARNING")) {
pr = QString(" ");
painter.setPen(QColor(255,127,127));
}
else if(block.text().startsWith("MESSAGE")) {
pr = QString(" ");
painter.setPen(QColor(255,127,127));
}
else// if(block == firstVisibleBlock()) {
{
pr = QString(">");
painter.setPen(Qt::lightGray);
}
painter.drawText(0, top, prompt->width(), fontMetrics().height(),
Qt::AlignCenter, pr);
}
QTextBlock prevBlock = block.previous();
block = block.next();
//if(prevBlock.isVisible() && prevBlock.isValid())
//{
// if (prevBlock.text().endsWith("\\")) {
// painter.setPen(Qt::lightGray);
// painter.drawText(0, top, prompt->width(), fontMetrics().height(),
// Qt::AlignRight, "+");
// }
// else if(prevBlock.text().startsWith("ERROR"))
// {
// painter.setPen(Qt::red);
// painter.drawText(0, top, prompt->width(), fontMetrics().height(),
// Qt::AlignRight, "x");
// }
// else
// {
// painter.setPen(Qt::lightGray);
// painter.drawText(0, top, prompt->width(), fontMetrics().height(),
// Qt::AlignRight, ">");
// }
//}
top = bottom;
bottom = top + (int) blockBoundingRect(block).height();
}
}
void PgxConsole::keyPressEvent(QKeyEvent * e)
{
switch(e->key()) {
case Qt::Key_Up:
emit histUp();
break;
case Qt::Key_Down:
emit histDn();
break;
case Qt::Key_Left:
if(!textCursor().atBlockStart())
QPlainTextEdit::keyPressEvent(e);
break;
case Qt::Key_Backspace:
if(!textCursor().atBlockStart())
QPlainTextEdit::keyPressEvent(e);
break;
case Qt::Key_Return:
case Qt::Key_Enter:
emit cmd(e);
//QPlainTextEdit::keyPressEvent(e);
break;
case Qt::Key_Backslash:
QPlainTextEdit::keyPressEvent(e);
appendPlainText("");
break;
default:
QPlainTextEdit::keyPressEvent(e);
}
}
void PgxConsole::wheelEvent(QWheelEvent *wheelEvent)
{
// BEGIN TODO 2
wheelEvent->accept();
QFontMetrics df = fontMetrics();
// END TODO 2
}
void PgxConsole::showView(QKeyEvent * e)
{
if(!textCursor().atEnd()) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
}
QTextBlock block = document()->end();
if(!block.isValid())
block = block.previous();
QString cmd = block.text().trimmed();
for (block = block.previous(); block.text().endsWith("\\"); block = block.previous())
cmd.insert(0, block.text().trimmed().replace(QString("\\"), QString(" ")));
// Do nothing on whitespace input.
if(cmd.trimmed().isEmpty()) {
appendPlainText("");
return;
}
// Save the command into the command history and
// reassign the history iterator.
history << cmd;
hit = history.size();
// 'clear' command to clear the console keeping the
// history intact.
if(cmd.compare("clear", Qt::CaseInsensitive) == 0) {
clear();
return;
}
// 'clear' command to clear the history alone. Console
// is not cleared.
else if(cmd.compare("clearh", Qt::CaseInsensitive) == 0) {
history.clear();
hit = 0;
appendPlainText("");
return;
}
// 'clearall' command to clear console and history
else if(cmd.compare("clearall", Qt::CaseInsensitive) == 0) {
history.clear();
hit =0;
clear();
return;
}
// 'quit' command to clear console and history
else if(cmd.compare("quit", Qt::CaseInsensitive) == 0) {
history.clear();
hit =0;
clear();
this->close();
}
// 'exit' command to clear console and history
else if(cmd.compare("exit", Qt::CaseInsensitive) == 0) {
history.clear();
hit =0;
clear();
this->close();
}
// Reduce all groups of whitespace characters
// to a single space between words.
cmd = cmd.simplified();
// Start a timer to count the seconds taken to display the
// required output (used for queries and tables only).
QTime t;
t.start();
// Don't execute SELECT INTO queries.
// Suggest CREATE TABLE AS construct.
QRegExp rx("\\bINTO\\b\\s+[\\w]*\\s+\\bFROM\\b", Qt::CaseInsensitive);
if(cmd.startsWith("select", Qt::CaseInsensitive) &&
cmd.contains(rx)) {
appendPlainText(QApplication::translate(
"PgxConsole", "WARNING: SELECT INTO deprecated. Use CREATE TABLE AS construct instead.\n",
0, QApplication::UnicodeUTF8));
return;
}
// EXPLAIN queries display.
else if(cmd.startsWith("explain", Qt::CaseInsensitive))
{
/*!
@todo EXPLAIN ANALYZE on DML statements.
* Explain analyze executes the DML thereby altering data.
* This can be potentially hazardous when the intention is
* to only check the query run time, rows affected, etc.
* The proper way to implement this is to enclose the DML
* in a transaction block like so:
* @code
* BEGIN;
* {DML};
* ROLLBACK;
* @endcode
* Yet to be implemented. EXPLAIN ANALYZE on
* DML are disabled for now.
*/
if(cmd.startsWith("explain analyze update", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze insert", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze delete", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze verbose update", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze verbose insert", Qt::CaseInsensitive) ||
cmd.startsWith("explain analyze verbose delete", Qt::CaseInsensitive))
{
appendPlainText(QApplication::translate("PgxConsole", "WARNING: EXPLAIN ANAYZE for DML not supported at this time.\n", 0, QApplication::UnicodeUTF8));
return;
}
QSqlQueryModel* model = new QSqlQueryModel;
model->setQuery(cmd);
if (model->lastError().isValid()) {
appendHtml(model->lastError().databaseText());
appendPlainText("");
return;
}
ExplainView* eview = new ExplainView(model, cmd, Qt::WA_DeleteOnClose);
int width = eview->verticalHeader()->width();
if(eview->verticalScrollBar()->isVisible()) {
width += eview->verticalScrollBar()->width();
}
eview->setColumnWidth(0, eview->width() - width);
eview->resizeRowsToContents();
eview->show();
}
// DDL, DML queries display.
else
{
if((cmd.startsWith("update", Qt::CaseInsensitive) ||
cmd.startsWith("insert", Qt::CaseInsensitive) ||
cmd.startsWith("delete", Qt::CaseInsensitive) ||
cmd.startsWith("truncate", Qt::CaseInsensitive)) &&
!cmd.contains("returning", Qt::CaseInsensitive))
{
QSqlQuery* sqlqry = new QSqlQuery;
sqlqry->exec(cmd);
if (sqlqry->lastError().isValid()) {
appendHtml(sqlqry->lastError().databaseText());
appendPlainText("");
return;
}
QString mesg = QApplication::translate("PgxConsole", "MESSAGE: Rows affected = ", 0, QApplication::UnicodeUTF8);
appendHtml(mesg.append(QString::number(sqlqry->numRowsAffected())));
appendPlainText("");
return;
}
else
{
QSqlQueryModel* model = new QSqlQueryModel;
model->setQuery(cmd);
if (model->lastError().isValid()) {
appendHtml(model->lastError().databaseText());
appendPlainText("");
return;
}
if(model->rowCount() == 0) {
appendPlainText(QApplication::translate("PgxConsole", "MESSAGE: No rows to display.\n", 0, QApplication::UnicodeUTF8));
return;
}
QueryView* qview = new QueryView(0, model, cmd, t.elapsed(), model->rowCount(),
model->columnCount(), Qt::WA_DeleteOnClose);
qview->show();
}
}
appendPlainText("");
}
void PgxConsole::curChanged()
{
if(textCursor().block().next().isValid())
setReadOnly(true);
else
setReadOnly(false);
}
void PgxConsole::paste_cmd()
{
QTextCursor cursor = textCursor();
if(textCursor().block().next().isValid()) {
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
paste();
}
else {
/*QClipboard *clipboard = QApplication::clipboard();
QString cb = clipboard->text();
QStringList cbl = cb.split("\n");
siz = cbl.size();
for(int i = 0; i < siz; i++) {
appendPlainText(cbl.at(i));
}*/
paste();
}
}
void PgxConsole::histUpCmd()
{
if(!history.isEmpty() && hit > 0) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
cursor.select(QTextCursor::BlockUnderCursor);
if(cursor.hasSelection()) {
cursor.removeSelectedText();
appendPlainText(history.at(--hit));
}
else {
insertPlainText(history.at(--hit));
}
}
}
void PgxConsole::histDnCmd()
{
if(!history.isEmpty() && hit < history.size()) {
QTextCursor cursor = textCursor();
cursor.movePosition(QTextCursor::End);
setTextCursor(cursor);
cursor.select(QTextCursor::BlockUnderCursor);
if(cursor.hasSelection()) {
cursor.removeSelectedText();
appendPlainText(history.value(++hit));
}
else {
insertPlainText(history.value(++hit));
}
}
ensureCursorVisible();
}
void PgxConsole::createWidgets()
{
QStringList wordList;
wordList << "alpha" << "omega" << "omicron" << "zeta";
completer = new QCompleter(wordList, this);
completer->setWidget(this);
completer->setCompletionMode(QCompleter::PopupCompletion);
completer->setWrapAround(true);
}
Highlighter::Highlighter(QTextDocument *parent)
: QSyntaxHighlighter(parent)
{
HighlightingRule rule;
classFormat.setFontWeight(QFont::Bold);
classFormat.setForeground(Qt::darkBlue);
rule.pattern = QRegExp("\\b[A-Za-z]+\\b");
rule.format = classFormat;
highlightingRules.append(rule);
keywordFormat.setForeground(Qt::darkCyan);
keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns;
keywordPatterns << "\\bselect\\b" << "\\bupdate\\b" << "\\bdelete\\b"
<< "\\btruncate\\b" << "\\bunion\\b" << "\\ball\\b"
<< "\\bintersect\\b" << "\\bexcept\\b";
foreach (const QString &pattern, keywordPatterns) {
rule.pattern = QRegExp(pattern, Qt::CaseInsensitive);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
keywordFormat2.setForeground(Qt::darkGreen);
keywordFormat2.setFontItalic(true);
QStringList keywordPatterns2;
keywordPatterns2 << "\\bfrom\\b" << "\\bin\\b" << "\\bwith\\b"
<< "\\bjoin\\b" << "\\bon\\b" << "\\bgroup by\\b"
<< "\\bleft\\b" << "\\right\\b" << "\\bfull\\b" << "\\bcross\\b"
<< "\\binner\\b" << "\\bouter\\b" << "\\bnatural\\b"
<< "\\border by\\b" << "\\blimit\\b" << "\\bfetch\\b"
<< "\\bhaving\\b" << "\\bwindow\\b" << "\\boffset\\b";
foreach (const QString &pattern, keywordPatterns2) {
rule.pattern = QRegExp(pattern, Qt::CaseInsensitive);
rule.format = keywordFormat2;
highlightingRules.append(rule);
}
singleQuotFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegExp("\'([^\']*)\'");
rule.format = singleQuotFormat;
highlightingRules.append(rule);
doubleQuotFormat.setForeground(Qt::darkGray);
rule.pattern = QRegExp("\"([^\"]*)\"");
rule.format = doubleQuotFormat;
highlightingRules.append(rule);
functionFormat.setFontWeight(QFont::Bold);
functionFormat.setForeground(Qt::blue);
rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
rule.format = functionFormat;
highlightingRules.append(rule);
}
void Highlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules) {
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0) {
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
}<|endoftext|>
|
<commit_before>#include <cthun-client/connector/connector.hpp>
#include <cthun-client/connector/uuid.hpp>
#include <cthun-client/protocol/message.hpp>
#include <cthun-client/protocol/schemas.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".connector"
#include <leatherman/logging/logging.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cstdio>
#include <chrono>
namespace CthunClient {
//
// Constants
//
static const uint CONNECTION_CHECK_S { 15 }; // [s]
static const int DEFAULT_MSG_TIMEOUT { 10 }; // [s]
static const std::string MY_SERVER_URI { "cth:///server" };
//
// Utility functions
//
// TODO(ale): move this to leatherman
std::string getISO8601Time(unsigned int modifier_in_seconds) {
boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time()
+ boost::posix_time::seconds(modifier_in_seconds);
return boost::posix_time::to_iso_extended_string(t) + "Z";
}
// TODO(ale): move plural from the common StringUtils in leatherman
template<typename T>
std::string plural(std::vector<T> things);
std::string plural(int num_of_things) {
return num_of_things > 1 ? "s" : "";
}
//
// Public api
//
Connector::Connector(const std::string& server_url,
const std::string& client_type,
const std::string& ca_crt_path,
const std::string& client_crt_path,
const std::string& client_key_path)
: server_url_ { server_url },
client_metadata_ { client_type,
ca_crt_path,
client_crt_path,
client_key_path },
connection_ptr_ { nullptr },
validator_ {},
schema_callback_pairs_ {},
mutex_ {},
cond_var_ {},
is_destructing_ { false },
is_monitoring_ { false } {
addEnvelopeSchemaToValidator();
}
Connector::~Connector() {
if (connection_ptr_ != nullptr) {
// reset callbacks to avoid breaking the Connection instance
// due to callbacks having an invalid reference context
LOG_INFO("Resetting the WebSocket event callbacks");
connection_ptr_->resetCallbacks();
}
{
std::lock_guard<std::mutex> the_lock { mutex_ };
is_destructing_ = true;
cond_var_.notify_one();
}
}
// Register schemas and onMessage callbacks
void Connector::registerMessageCallback(const Schema schema,
MessageCallback callback) {
validator_.registerSchema(schema);
auto p = std::pair<std::string, MessageCallback>(schema.getName(), callback);
schema_callback_pairs_.insert(p);
}
// Manage the connection state
void Connector::connect(int max_connect_attempts) {
if (connection_ptr_ == nullptr) {
// Initialize the WebSocket connection
connection_ptr_.reset(new Connection(server_url_, client_metadata_));
connection_ptr_->setOnMessageCallback(
[this](std::string message) {
processMessage(message);
});
connection_ptr_->setOnOpenCallback(
[this]() {
associateSession();
});
}
try {
// Open the WebSocket connection
connection_ptr_->connect(max_connect_attempts);
} catch (connection_processing_error& e) {
// NB: connection_fatal_errors are propagated whereas
// connection_processing_errors are converted to
// connection_config_errors (they can be thrown after
// websocketpp::Endpoint::connect() or ::send() failures)
LOG_ERROR("Failed to connect: %1%", e.what());
throw connection_config_error { e.what() };
}
}
bool Connector::isConnected() const {
// TODO(ale): make this consistent with the associate transaction
// as in the protocol specs (perhaps with an associated flag)
return connection_ptr_ != nullptr
&& connection_ptr_->getConnectionState() == ConnectionStateValues::open;
}
void Connector::monitorConnection(int max_connect_attempts) {
checkConnectionInitialization();
if (!is_monitoring_) {
is_monitoring_ = true;
startMonitorTask(max_connect_attempts);
} else {
LOG_WARNING("The monitorConnection has already been called");
}
}
// Send messages
void Connector::send(const Message& msg) {
checkConnectionInitialization();
auto serialized_msg = msg.getSerialized();
LOG_DEBUG("Sending message of %1% bytes:\n%2%",
serialized_msg.size(), msg.toString());
connection_ptr_->send(&serialized_msg[0], serialized_msg.size());
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_binary,
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_binary,
debug);
}
//
// Private interface
//
// Utility functions
void Connector::checkConnectionInitialization() {
if (connection_ptr_ == nullptr) {
throw connection_not_init_error { "connection not initialized" };
}
}
void Connector::addEnvelopeSchemaToValidator() {
auto schema = Protocol::EnvelopeSchema();
validator_.registerSchema(schema);
}
MessageChunk Connector::createEnvelope(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report) {
auto msg_id = UUID::getUUID();
auto expires = getISO8601Time(timeout);
LOG_INFO("Creating message with id %1% for %2% receiver%3%",
msg_id, targets.size(), plural(targets.size()));
DataContainer envelope_content {};
envelope_content.set<std::string>("id", msg_id);
envelope_content.set<std::string>("message_type", message_type);
envelope_content.set<std::vector<std::string>>("targets", targets);
envelope_content.set<std::string>("expires", expires);
envelope_content.set<std::string>("sender", client_metadata_.uri);
if (destination_report) {
envelope_content.set<bool>("destination_report", true);
}
return MessageChunk { ChunkDescriptor::ENVELOPE, envelope_content.toString() };
}
void Connector::sendMessage(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_txt,
const std::vector<DataContainer>& debug) {
auto envelope_chunk = createEnvelope(targets, message_type, timeout, destination_report);
MessageChunk data_chunk { ChunkDescriptor::DATA, data_txt };
Message msg { envelope_chunk, data_chunk };
for (auto debug_content : debug) {
MessageChunk d_c { ChunkDescriptor::DEBUG, debug_content.toString() };
msg.addDebugChunk(d_c);
}
send(msg);
}
// Login
void Connector::associateSession() {
// Envelope
auto envelope = createEnvelope(std::vector<std::string> { MY_SERVER_URI },
Protocol::ASSOCIATE_REQ_TYPE,
DEFAULT_MSG_TIMEOUT,
false);
// Create and send message
Message msg { envelope };
LOG_INFO("Sending Associate Session request");
send(msg);
}
// WebSocket onMessage callback
void Connector::processMessage(const std::string& msg_txt) {
LOG_DEBUG("Received message of %1% bytes:\n%2%", msg_txt.size(), msg_txt);
// Deserialize the incoming message
std::unique_ptr<Message> msg_ptr;
try {
msg_ptr.reset(new Message(msg_txt));
} catch (message_error& e) {
LOG_ERROR("Failed to deserialize message: %1%", e.what());
return;
}
// Parse message chunks
ParsedChunks parsed_chunks;
try {
parsed_chunks = msg_ptr->getParsedChunks(validator_);
} catch (validator_error& e) {
LOG_ERROR("Invalid message - content not conform to schema: %1%", e.what());
return;
} catch (data_parse_error& e) {
LOG_ERROR("Invalid message - invalid JSON content: %1%", e.what());
return;
} catch (schema_not_found_error& e) {
LOG_ERROR("Invalid message - unknown schema: %1%", e.what());
return;
}
// Execute the callback associated with the data schema
auto schema_name = parsed_chunks.envelope.get<std::string>("message_type");
if (schema_callback_pairs_.find(schema_name) != schema_callback_pairs_.end()) {
auto c_b = schema_callback_pairs_.at(schema_name);
LOG_TRACE("Executing callback for a message with '%1%' schema",
schema_name);
c_b(parsed_chunks);
} else {
LOG_WARNING("No message callback has be registered for '%1%' schema",
schema_name);
}
}
// Monitor task
void Connector::startMonitorTask(int max_connect_attempts) {
assert(connection_ptr_ != nullptr);
while (true) {
std::unique_lock<std::mutex> the_lock { mutex_ };
auto now = std::chrono::system_clock::now();
cond_var_.wait_until(the_lock,
now + std::chrono::seconds(CONNECTION_CHECK_S));
if (is_destructing_) {
// The dtor has been invoked
LOG_INFO("Stopping the monitor task");
is_monitoring_ = false;
the_lock.unlock();
return;
}
try {
if (!isConnected()) {
LOG_WARNING("Connection to Cthun server lost; retrying");
connection_ptr_->connect(max_connect_attempts);
} else {
LOG_DEBUG("Sending heartbeat ping");
connection_ptr_->ping();
}
} catch (connection_processing_error& e) {
// Connection::connect() or ping() failure - keep trying
LOG_ERROR("Connection monitor failure: %1%", e.what());
} catch (connection_fatal_error& e) {
// Failed to reconnect after max_connect_attempts - stop
LOG_ERROR("The connection monitor task will stop - failure: %1%",
e.what());
is_monitoring_ = false;
the_lock.unlock();
throw;
}
the_lock.unlock();
}
}
} // namespace CthunClient
<commit_msg>(maint) Catch validation_error in Connector::processMessage<commit_after>#include <cthun-client/connector/connector.hpp>
#include <cthun-client/connector/uuid.hpp>
#include <cthun-client/protocol/message.hpp>
#include <cthun-client/protocol/schemas.hpp>
#define LEATHERMAN_LOGGING_NAMESPACE CTHUN_CLIENT_LOGGING_PREFIX".connector"
#include <leatherman/logging/logging.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cstdio>
#include <chrono>
namespace CthunClient {
//
// Constants
//
static const uint CONNECTION_CHECK_S { 15 }; // [s]
static const int DEFAULT_MSG_TIMEOUT { 10 }; // [s]
static const std::string MY_SERVER_URI { "cth:///server" };
//
// Utility functions
//
// TODO(ale): move this to leatherman
std::string getISO8601Time(unsigned int modifier_in_seconds) {
boost::posix_time::ptime t = boost::posix_time::microsec_clock::universal_time()
+ boost::posix_time::seconds(modifier_in_seconds);
return boost::posix_time::to_iso_extended_string(t) + "Z";
}
// TODO(ale): move plural from the common StringUtils in leatherman
template<typename T>
std::string plural(std::vector<T> things);
std::string plural(int num_of_things) {
return num_of_things > 1 ? "s" : "";
}
//
// Public api
//
Connector::Connector(const std::string& server_url,
const std::string& client_type,
const std::string& ca_crt_path,
const std::string& client_crt_path,
const std::string& client_key_path)
: server_url_ { server_url },
client_metadata_ { client_type,
ca_crt_path,
client_crt_path,
client_key_path },
connection_ptr_ { nullptr },
validator_ {},
schema_callback_pairs_ {},
mutex_ {},
cond_var_ {},
is_destructing_ { false },
is_monitoring_ { false } {
addEnvelopeSchemaToValidator();
}
Connector::~Connector() {
if (connection_ptr_ != nullptr) {
// reset callbacks to avoid breaking the Connection instance
// due to callbacks having an invalid reference context
LOG_INFO("Resetting the WebSocket event callbacks");
connection_ptr_->resetCallbacks();
}
{
std::lock_guard<std::mutex> the_lock { mutex_ };
is_destructing_ = true;
cond_var_.notify_one();
}
}
// Register schemas and onMessage callbacks
void Connector::registerMessageCallback(const Schema schema,
MessageCallback callback) {
validator_.registerSchema(schema);
auto p = std::pair<std::string, MessageCallback>(schema.getName(), callback);
schema_callback_pairs_.insert(p);
}
// Manage the connection state
void Connector::connect(int max_connect_attempts) {
if (connection_ptr_ == nullptr) {
// Initialize the WebSocket connection
connection_ptr_.reset(new Connection(server_url_, client_metadata_));
connection_ptr_->setOnMessageCallback(
[this](std::string message) {
processMessage(message);
});
connection_ptr_->setOnOpenCallback(
[this]() {
associateSession();
});
}
try {
// Open the WebSocket connection
connection_ptr_->connect(max_connect_attempts);
} catch (connection_processing_error& e) {
// NB: connection_fatal_errors are propagated whereas
// connection_processing_errors are converted to
// connection_config_errors (they can be thrown after
// websocketpp::Endpoint::connect() or ::send() failures)
LOG_ERROR("Failed to connect: %1%", e.what());
throw connection_config_error { e.what() };
}
}
bool Connector::isConnected() const {
// TODO(ale): make this consistent with the associate transaction
// as in the protocol specs (perhaps with an associated flag)
return connection_ptr_ != nullptr
&& connection_ptr_->getConnectionState() == ConnectionStateValues::open;
}
void Connector::monitorConnection(int max_connect_attempts) {
checkConnectionInitialization();
if (!is_monitoring_) {
is_monitoring_ = true;
startMonitorTask(max_connect_attempts);
} else {
LOG_WARNING("The monitorConnection has already been called");
}
}
// Send messages
void Connector::send(const Message& msg) {
checkConnectionInitialization();
auto serialized_msg = msg.getSerialized();
LOG_DEBUG("Sending message of %1% bytes:\n%2%",
serialized_msg.size(), msg.toString());
connection_ptr_->send(&serialized_msg[0], serialized_msg.size());
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
false,
data_binary,
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const DataContainer& data_json,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_json.toString(),
debug);
}
void Connector::send(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_binary,
const std::vector<DataContainer>& debug) {
sendMessage(targets,
message_type,
timeout,
destination_report,
data_binary,
debug);
}
//
// Private interface
//
// Utility functions
void Connector::checkConnectionInitialization() {
if (connection_ptr_ == nullptr) {
throw connection_not_init_error { "connection not initialized" };
}
}
void Connector::addEnvelopeSchemaToValidator() {
auto schema = Protocol::EnvelopeSchema();
validator_.registerSchema(schema);
}
MessageChunk Connector::createEnvelope(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report) {
auto msg_id = UUID::getUUID();
auto expires = getISO8601Time(timeout);
LOG_INFO("Creating message with id %1% for %2% receiver%3%",
msg_id, targets.size(), plural(targets.size()));
DataContainer envelope_content {};
envelope_content.set<std::string>("id", msg_id);
envelope_content.set<std::string>("message_type", message_type);
envelope_content.set<std::vector<std::string>>("targets", targets);
envelope_content.set<std::string>("expires", expires);
envelope_content.set<std::string>("sender", client_metadata_.uri);
if (destination_report) {
envelope_content.set<bool>("destination_report", true);
}
return MessageChunk { ChunkDescriptor::ENVELOPE, envelope_content.toString() };
}
void Connector::sendMessage(const std::vector<std::string>& targets,
const std::string& message_type,
unsigned int timeout,
bool destination_report,
const std::string& data_txt,
const std::vector<DataContainer>& debug) {
auto envelope_chunk = createEnvelope(targets, message_type, timeout, destination_report);
MessageChunk data_chunk { ChunkDescriptor::DATA, data_txt };
Message msg { envelope_chunk, data_chunk };
for (auto debug_content : debug) {
MessageChunk d_c { ChunkDescriptor::DEBUG, debug_content.toString() };
msg.addDebugChunk(d_c);
}
send(msg);
}
// Login
void Connector::associateSession() {
// Envelope
auto envelope = createEnvelope(std::vector<std::string> { MY_SERVER_URI },
Protocol::ASSOCIATE_REQ_TYPE,
DEFAULT_MSG_TIMEOUT,
false);
// Create and send message
Message msg { envelope };
LOG_INFO("Sending Associate Session request");
send(msg);
}
// WebSocket onMessage callback
void Connector::processMessage(const std::string& msg_txt) {
LOG_DEBUG("Received message of %1% bytes:\n%2%", msg_txt.size(), msg_txt);
// Deserialize the incoming message
std::unique_ptr<Message> msg_ptr;
try {
msg_ptr.reset(new Message(msg_txt));
} catch (message_error& e) {
LOG_ERROR("Failed to deserialize message: %1%", e.what());
return;
}
// Parse message chunks
ParsedChunks parsed_chunks;
try {
parsed_chunks = msg_ptr->getParsedChunks(validator_);
} catch (validation_error& e) {
LOG_ERROR("Invalid message - bad content: %1%", e.what());
return;
} catch (data_parse_error& e) {
LOG_ERROR("Invalid message - invalid JSON content: %1%", e.what());
return;
} catch (schema_not_found_error& e) {
LOG_ERROR("Invalid message - unknown schema: %1%", e.what());
return;
}
// Execute the callback associated with the data schema
auto schema_name = parsed_chunks.envelope.get<std::string>("message_type");
if (schema_callback_pairs_.find(schema_name) != schema_callback_pairs_.end()) {
auto c_b = schema_callback_pairs_.at(schema_name);
LOG_TRACE("Executing callback for a message with '%1%' schema",
schema_name);
c_b(parsed_chunks);
} else {
LOG_WARNING("No message callback has be registered for '%1%' schema",
schema_name);
}
}
// Monitor task
void Connector::startMonitorTask(int max_connect_attempts) {
assert(connection_ptr_ != nullptr);
while (true) {
std::unique_lock<std::mutex> the_lock { mutex_ };
auto now = std::chrono::system_clock::now();
cond_var_.wait_until(the_lock,
now + std::chrono::seconds(CONNECTION_CHECK_S));
if (is_destructing_) {
// The dtor has been invoked
LOG_INFO("Stopping the monitor task");
is_monitoring_ = false;
the_lock.unlock();
return;
}
try {
if (!isConnected()) {
LOG_WARNING("Connection to Cthun server lost; retrying");
connection_ptr_->connect(max_connect_attempts);
} else {
LOG_DEBUG("Sending heartbeat ping");
connection_ptr_->ping();
}
} catch (connection_processing_error& e) {
// Connection::connect() or ping() failure - keep trying
LOG_ERROR("Connection monitor failure: %1%", e.what());
} catch (connection_fatal_error& e) {
// Failed to reconnect after max_connect_attempts - stop
LOG_ERROR("The connection monitor task will stop - failure: %1%",
e.what());
is_monitoring_ = false;
the_lock.unlock();
throw;
}
the_lock.unlock();
}
}
} // namespace CthunClient
<|endoftext|>
|
<commit_before>// ModelNeurons Class C++
// ModelNeurons.cpp
//
// Author: Nasir Ahmad
// Date: 7/12/2015
//
// Adapted from NeuronPopulations by Nasir Ahmad and James Isbister
// Date: 6/4/2016
#include "ModelNeurons.h"
#include <stdlib.h>
#include <stdio.h>
// ModelNeurons Constructor
ModelNeurons::ModelNeurons() {
total_number_of_neurons = 0;
total_number_of_groups = 0;
group_shapes = NULL;
group_parameters = NULL;
last_neuron_indices_for_each_group = NULL;
}
// ModelNeurons Destructor
ModelNeurons::~ModelNeurons() {
// Just need to free up the memory
free(group_shapes);
free(group_parameters);
free(last_neuron_indices_for_each_group);
}
// Add Group Function
// INPUT:
// Izhikevich parameter list {a, b, c, d}
// Group Shape
int ModelNeurons::AddGroup(neuron_struct params, int group_shape[2]){
// Check that it is within bounds
int number_of_neurons_in_group = group_shape[0]*group_shape[1];
if (number_of_neurons_in_group < 0) {
printf("\nError: Population must have at least 1 neuron.\n\n");
exit(-1);
}
// Update the totals
total_number_of_neurons += number_of_neurons_in_group;
++total_number_of_groups;
printf("total_number_of_groups: %d\n", total_number_of_groups);
int new_group_id = total_number_of_groups - 1;
last_neuron_indices_for_each_group = (int*)realloc(last_neuron_indices_for_each_group,(total_number_of_groups*sizeof(int)));
last_neuron_indices_for_each_group[new_group_id] = total_number_of_neurons;
// Allocate space for the new neurons
group_shapes = (int**)realloc(group_shapes,(total_number_of_groups*sizeof(int*)));
group_shapes[new_group_id] = (int*)malloc(2*sizeof(int));
group_parameters = (neuron_struct*)realloc(group_parameters, (total_number_of_neurons*sizeof(neuron_struct)));
// Fill the new entries in the pointers
group_shapes[new_group_id] = group_shape;
for (int i = (total_number_of_neurons - number_of_neurons_in_group); i < total_number_of_neurons; i++){
group_parameters[i] = params;
}
return new_group_id;
}
<commit_msg>Further ModelNeuron tidy up<commit_after>// ModelNeurons Class C++
// ModelNeurons.cpp
//
// Author: Nasir Ahmad
// Date: 7/12/2015
//
// Adapted from NeuronPopulations by Nasir Ahmad and James Isbister
// Date: 6/4/2016
#include "ModelNeurons.h"
#include <stdlib.h>
#include <stdio.h>
// ModelNeurons Constructor
ModelNeurons::ModelNeurons() {
// Set totals to zero
total_number_of_neurons = 0;
total_number_of_groups = 0;
// Initialise pointers
group_shapes = NULL;
group_parameters = NULL;
last_neuron_indices_for_each_group = NULL;
}
// ModelNeurons Destructor
ModelNeurons::~ModelNeurons() {
// Free up memory
free(group_shapes);
free(group_parameters);
free(last_neuron_indices_for_each_group);
}
int ModelNeurons::AddGroup(neuron_struct params, int group_shape[2]){
int number_of_neurons_in_group = group_shape[0]*group_shape[1];
if (number_of_neurons_in_group < 0) {
printf("\nError: Population must have at least 1 neuron.\n\n");
exit(-1);
}
// Update totals
total_number_of_neurons += number_of_neurons_in_group;
++total_number_of_groups;
printf("total_number_of_groups: %d\n", total_number_of_groups); // Temp helper
// Calculate new group id
int new_group_id = total_number_of_groups - 1;
// Add last neuron index for new group
last_neuron_indices_for_each_group = (int*)realloc(last_neuron_indices_for_each_group,(total_number_of_groups*sizeof(int)));
last_neuron_indices_for_each_group[new_group_id] = total_number_of_neurons;
// Add new group shape
group_shapes = (int**)realloc(group_shapes,(total_number_of_groups*sizeof(int*)));
group_shapes[new_group_id] = (int*)malloc(2*sizeof(int));
group_shapes[new_group_id] = group_shape;
// Add new group parameters
group_parameters = (neuron_struct*)realloc(group_parameters, (total_number_of_neurons*sizeof(neuron_struct)));
for (int i = (total_number_of_neurons - number_of_neurons_in_group); i < total_number_of_neurons; i++){
group_parameters[i] = params;
}
return new_group_id;
}
<|endoftext|>
|
<commit_before>#include "Server.h"
/*******************************************************************************/
int my_send(SOCKET& client_socket, string& message)
{
int result = 0;
result = send(client_socket, message.c_str(), message.size(), 0);
return result;
}
/*******************************************************************************/
int my_recv(SOCKET& client_socket, string& message)
{
int result = 0;
char buffer[1024] = {0};
result = recv(client_socket, buffer, 1024, 0);
message = buffer;
//delete buffer;
return result;
}
<commit_msg>Delete My_namespace.cpp<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/flags/usage.h>
#include <QApplication>
#include <QDir>
#include <QFontDatabase>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <QProgressDialog>
#include <QStyleFactory>
#include "App.h"
#include "ApplicationOptions.h"
#include "CrashHandler.h"
#include "CrashOptions.h"
#include "Error.h"
#include "GlutContext.h"
#include "OrbitBase/Logging.h"
#include "OrbitGgp/Error.h"
#include "OrbitSsh/Context.h"
#include "OrbitSsh/Credentials.h"
#include "OrbitSshQt/Session.h"
#include "OrbitStartupWindow.h"
#include "Path.h"
#include "deploymentconfigurations.h"
#include "opengldetect.h"
#include "orbitmainwindow.h"
#include "servicedeploymanager.h"
#include "version.h"
ABSL_FLAG(bool, enable_stale_features, false,
"Enable obsolete features that are not working or are not "
"implemented in the client's UI");
ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI");
ABSL_FLAG(uint16_t, asio_port, 44766,
"The service's Asio tcp_server port (use default value if unsure)");
ABSL_FLAG(uint16_t, grpc_port, 44765,
"The service's GRPC server port (use default value if unsure)");
ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService");
// TODO: remove this once we deprecated legacy parameters
static void ParseLegacyCommandLine(int argc, char* argv[],
ApplicationOptions* options) {
for (size_t i = 0; i < static_cast<size_t>(argc); ++i) {
const char* arg = argv[i];
if (absl::StartsWith(arg, "gamelet:")) {
ERROR(
"the 'gamelet:<host>:<port>' option is deprecated and will be "
"removed soon, please use -remote <host> instead.");
options->asio_server_address = arg + std::strlen("gamelet:");
}
}
}
using ServiceDeployManager = OrbitQt::ServiceDeployManager;
using DeploymentConfiguration = OrbitQt::DeploymentConfiguration;
using OrbitStartupWindow = OrbitQt::OrbitStartupWindow;
using Error = OrbitQt::Error;
using ScopedConnection = OrbitSshQt::ScopedConnection;
using Ports = ServiceDeployManager::Ports;
using SshCredentials = OrbitSsh::Credentials;
using Context = OrbitSsh::Context;
static outcome::result<Ports> DeployOrbitService(
std::optional<ServiceDeployManager>& service_deploy_manager,
const DeploymentConfiguration& deployment_configuration, Context* context,
const SshCredentials& ssh_credentials, const Ports& remote_ports) {
QProgressDialog progress_dialog{};
service_deploy_manager.emplace(deployment_configuration, context,
ssh_credentials, remote_ports);
QObject::connect(&progress_dialog, &QProgressDialog::canceled,
&service_deploy_manager.value(),
&ServiceDeployManager::Cancel);
QObject::connect(&service_deploy_manager.value(),
&ServiceDeployManager::statusMessage, &progress_dialog,
&QProgressDialog::setLabelText);
QObject::connect(
&service_deploy_manager.value(), &ServiceDeployManager::statusMessage,
[](const QString& msg) { LOG("Status message: %s", msg.toStdString()); });
return service_deploy_manager->Exec();
}
static outcome::result<void> RunUiInstance(
QApplication* app,
std::optional<DeploymentConfiguration> deployment_configuration,
Context* context, ApplicationOptions options) {
std::optional<OrbitQt::ServiceDeployManager> service_deploy_manager;
OUTCOME_TRY(result, [&]() -> outcome::result<std::tuple<Ports, QString>> {
const Ports remote_ports{/*.asio_port =*/absl::GetFlag(FLAGS_asio_port),
/*.grpc_port =*/absl::GetFlag(FLAGS_grpc_port)};
if (deployment_configuration) {
OrbitStartupWindow sw{};
OUTCOME_TRY(result, sw.Run<OrbitSsh::Credentials>());
if (std::holds_alternative<OrbitSsh::Credentials>(result)) {
// The user chose a remote profiling target.
OUTCOME_TRY(
tunnel_ports,
DeployOrbitService(service_deploy_manager,
deployment_configuration.value(), context,
std::get<SshCredentials>(result), remote_ports));
return std::make_tuple(tunnel_ports, QString{});
} else {
// The user chose to open a capture.
return std::make_tuple(remote_ports, std::get<QString>(result));
}
} else {
// When the local flag is present
return std::make_tuple(remote_ports, QString{});
}
}());
const auto& [ports, capture_path] = result;
options.asio_server_address =
absl::StrFormat("127.0.0.1:%d", ports.asio_port);
options.grpc_server_address =
absl::StrFormat("127.0.0.1:%d", ports.grpc_port);
OrbitMainWindow w(app, std::move(options));
w.showMaximized();
w.PostInit();
std::optional<std::error_code> error;
auto error_handler = [&]() -> ScopedConnection {
if (service_deploy_manager) {
return OrbitSshQt::ScopedConnection{QObject::connect(
&service_deploy_manager.value(),
&ServiceDeployManager::socketErrorOccurred,
&service_deploy_manager.value(), [&](std::error_code e) {
error = e;
w.close();
app->quit();
})};
} else {
return ScopedConnection();
}
}();
if (!capture_path.isEmpty()) {
OUTCOME_TRY(w.OpenCapture(capture_path.toStdString()));
}
app->exec();
GOrbitApp->OnExit();
if (error) {
return outcome::failure(error.value());
} else {
return outcome::success();
}
}
static void StyleOrbit(QApplication& app) {
app.setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
app.setPalette(darkPalette);
app.setStyleSheet(
"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px "
"solid white; }");
}
static std::optional<OrbitQt::DeploymentConfiguration>
FigureOutDeploymentConfiguration() {
if (absl::GetFlag(FLAGS_local)) {
return std::nullopt;
}
auto env = QProcessEnvironment::systemEnvironment();
const char* const kEnvExecutablePath = "ORBIT_COLLECTOR_EXECUTABLE_PATH";
const char* const kEnvRootPassword = "ORBIT_COLLECTOR_ROOT_PASSWORD";
const char* const kEnvPackagePath = "ORBIT_COLLECTOR_PACKAGE_PATH";
const char* const kEnvSignaturePath = "ORBIT_COLLECTOR_SIGNATURE_PATH";
const char* const kEnvNoDeployment = "ORBIT_COLLECTOR_NO_DEPLOYMENT";
if (env.contains(kEnvExecutablePath) && env.contains(kEnvRootPassword)) {
return OrbitQt::BareExecutableAndRootPasswordDeployment{
env.value(kEnvExecutablePath).toStdString(),
env.value(kEnvRootPassword).toStdString()};
} else if (env.contains(kEnvPackagePath) && env.contains(kEnvSignaturePath)) {
return OrbitQt::SignedDebianPackageDeployment{
env.value(kEnvPackagePath).toStdString(),
env.value(kEnvSignaturePath).toStdString()};
} else if (env.contains(kEnvNoDeployment)) {
return OrbitQt::NoDeployment{};
} else {
return OrbitQt::SignedDebianPackageDeployment{};
}
}
static void DisplayErrorToUser(const QString& message) {
QMessageBox::critical(nullptr, QApplication::applicationName(), message);
}
int main(int argc, char* argv[]) {
const std::string log_file_path = Path::GetLogFilePath();
InitLogFile(log_file_path);
absl::SetProgramUsageMessage("CPU Profiler");
absl::ParseCommandLine(argc, argv);
#if __linux__
QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
#endif
OrbitGl::GlutContext glut_context{&argc, argv};
QApplication app(argc, argv);
QCoreApplication::setApplicationName("Orbit Profiler [BETA]");
QCoreApplication::setApplicationVersion(OrbitQt::kVersionString);
const std::string dump_path = Path::GetDumpPath();
#ifdef _WIN32
const char* handler_name = "crashpad_handler.exe";
#else
const char* handler_name = "crashpad_handler";
#endif
const std::string handler_path = QDir(QCoreApplication::applicationDirPath())
.absoluteFilePath(handler_name)
.toStdString();
const std::string crash_server_url = CrashServerOptions::GetUrl();
const std::vector<std::string> attachments = {Path::GetLogFilePath()};
CrashHandler crash_handler(dump_path, handler_path, crash_server_url,
attachments);
ApplicationOptions options;
ParseLegacyCommandLine(argc, argv, &options);
StyleOrbit(app);
const auto deployment_configuration = FigureOutDeploymentConfiguration();
const auto open_gl_version = OrbitQt::DetectOpenGlVersion();
if (!open_gl_version) {
DisplayErrorToUser(
"OpenGL support was not found. Please make sure you're not trying to "
"start Orbit in a remote session and make sure you have a recent "
"graphics driver installed. Then try again!");
return -1;
}
LOG("Detected OpenGL version: %i.%i", open_gl_version->major,
open_gl_version->minor);
if (open_gl_version->major < 2) {
DisplayErrorToUser(
QString(
"The minimum required version of OpenGL is 2.0. But this machine "
"only supports up to version %1.%2. Please make sure you're not "
"trying to start Orbit in a remote session and make sure you have "
"a recent graphics driver installed. Then try again!")
.arg(open_gl_version->major)
.arg(open_gl_version->minor));
return -1;
}
auto context = Context::Create();
if (!context) {
DisplayErrorToUser(
QString("An error occurred while initializing ssh: %1")
.arg(QString::fromStdString(context.error().message())));
return -1;
}
while (true) {
const auto result = RunUiInstance(&app, deployment_configuration,
&(context.value()), options);
if (result ||
result.error() == make_error_code(Error::kUserClosedStartUpWindow) ||
!deployment_configuration) {
// It was either a clean shutdown or the deliberately closed the
// dialog, or we started with the --local flag.
return 0;
} else if (result.error() ==
make_error_code(OrbitGgp::Error::kCouldNotUseGgpCli)) {
DisplayErrorToUser(QString::fromStdString(result.error().message()));
return 1;
} else if (result.error() !=
make_error_code(Error::kUserCanceledServiceDeployment)) {
DisplayErrorToUser(
QString("An error occurred: %1")
.arg(QString::fromStdString(result.error().message())));
}
}
}
<commit_msg>Set QPalette::Disabled colors<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <absl/flags/flag.h>
#include <absl/flags/parse.h>
#include <absl/flags/usage.h>
#include <QApplication>
#include <QDir>
#include <QFontDatabase>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <QProgressDialog>
#include <QStyleFactory>
#include "App.h"
#include "ApplicationOptions.h"
#include "CrashHandler.h"
#include "CrashOptions.h"
#include "Error.h"
#include "GlutContext.h"
#include "OrbitBase/Logging.h"
#include "OrbitGgp/Error.h"
#include "OrbitSsh/Context.h"
#include "OrbitSsh/Credentials.h"
#include "OrbitSshQt/Session.h"
#include "OrbitStartupWindow.h"
#include "Path.h"
#include "deploymentconfigurations.h"
#include "opengldetect.h"
#include "orbitmainwindow.h"
#include "servicedeploymanager.h"
#include "version.h"
ABSL_FLAG(bool, enable_stale_features, false,
"Enable obsolete features that are not working or are not "
"implemented in the client's UI");
ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI");
ABSL_FLAG(uint16_t, asio_port, 44766,
"The service's Asio tcp_server port (use default value if unsure)");
ABSL_FLAG(uint16_t, grpc_port, 44765,
"The service's GRPC server port (use default value if unsure)");
ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService");
// TODO: remove this once we deprecated legacy parameters
static void ParseLegacyCommandLine(int argc, char* argv[],
ApplicationOptions* options) {
for (size_t i = 0; i < static_cast<size_t>(argc); ++i) {
const char* arg = argv[i];
if (absl::StartsWith(arg, "gamelet:")) {
ERROR(
"the 'gamelet:<host>:<port>' option is deprecated and will be "
"removed soon, please use -remote <host> instead.");
options->asio_server_address = arg + std::strlen("gamelet:");
}
}
}
using ServiceDeployManager = OrbitQt::ServiceDeployManager;
using DeploymentConfiguration = OrbitQt::DeploymentConfiguration;
using OrbitStartupWindow = OrbitQt::OrbitStartupWindow;
using Error = OrbitQt::Error;
using ScopedConnection = OrbitSshQt::ScopedConnection;
using Ports = ServiceDeployManager::Ports;
using SshCredentials = OrbitSsh::Credentials;
using Context = OrbitSsh::Context;
static outcome::result<Ports> DeployOrbitService(
std::optional<ServiceDeployManager>& service_deploy_manager,
const DeploymentConfiguration& deployment_configuration, Context* context,
const SshCredentials& ssh_credentials, const Ports& remote_ports) {
QProgressDialog progress_dialog{};
service_deploy_manager.emplace(deployment_configuration, context,
ssh_credentials, remote_ports);
QObject::connect(&progress_dialog, &QProgressDialog::canceled,
&service_deploy_manager.value(),
&ServiceDeployManager::Cancel);
QObject::connect(&service_deploy_manager.value(),
&ServiceDeployManager::statusMessage, &progress_dialog,
&QProgressDialog::setLabelText);
QObject::connect(
&service_deploy_manager.value(), &ServiceDeployManager::statusMessage,
[](const QString& msg) { LOG("Status message: %s", msg.toStdString()); });
return service_deploy_manager->Exec();
}
static outcome::result<void> RunUiInstance(
QApplication* app,
std::optional<DeploymentConfiguration> deployment_configuration,
Context* context, ApplicationOptions options) {
std::optional<OrbitQt::ServiceDeployManager> service_deploy_manager;
OUTCOME_TRY(result, [&]() -> outcome::result<std::tuple<Ports, QString>> {
const Ports remote_ports{/*.asio_port =*/absl::GetFlag(FLAGS_asio_port),
/*.grpc_port =*/absl::GetFlag(FLAGS_grpc_port)};
if (deployment_configuration) {
OrbitStartupWindow sw{};
OUTCOME_TRY(result, sw.Run<OrbitSsh::Credentials>());
if (std::holds_alternative<OrbitSsh::Credentials>(result)) {
// The user chose a remote profiling target.
OUTCOME_TRY(
tunnel_ports,
DeployOrbitService(service_deploy_manager,
deployment_configuration.value(), context,
std::get<SshCredentials>(result), remote_ports));
return std::make_tuple(tunnel_ports, QString{});
} else {
// The user chose to open a capture.
return std::make_tuple(remote_ports, std::get<QString>(result));
}
} else {
// When the local flag is present
return std::make_tuple(remote_ports, QString{});
}
}());
const auto& [ports, capture_path] = result;
options.asio_server_address =
absl::StrFormat("127.0.0.1:%d", ports.asio_port);
options.grpc_server_address =
absl::StrFormat("127.0.0.1:%d", ports.grpc_port);
OrbitMainWindow w(app, std::move(options));
w.showMaximized();
w.PostInit();
std::optional<std::error_code> error;
auto error_handler = [&]() -> ScopedConnection {
if (service_deploy_manager) {
return OrbitSshQt::ScopedConnection{QObject::connect(
&service_deploy_manager.value(),
&ServiceDeployManager::socketErrorOccurred,
&service_deploy_manager.value(), [&](std::error_code e) {
error = e;
w.close();
app->quit();
})};
} else {
return ScopedConnection();
}
}();
if (!capture_path.isEmpty()) {
OUTCOME_TRY(w.OpenCapture(capture_path.toStdString()));
}
app->exec();
GOrbitApp->OnExit();
if (error) {
return outcome::failure(error.value());
} else {
return outcome::success();
}
}
static void StyleOrbit(QApplication& app) {
QApplication::setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
QColor light_gray{160, 160, 160};
QColor dark_gray{90, 90, 90};
QColor darker_gray{80, 80, 80};
darkPalette.setColor(QPalette::Disabled, QPalette::Window, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Base, darker_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, dark_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Button, darker_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Link, light_gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, dark_gray);
QApplication::setPalette(darkPalette);
app.setStyleSheet(
"QToolTip { color: #ffffff; background-color: #2a82da; border: 1px "
"solid white; }");
}
static std::optional<OrbitQt::DeploymentConfiguration>
FigureOutDeploymentConfiguration() {
if (absl::GetFlag(FLAGS_local)) {
return std::nullopt;
}
auto env = QProcessEnvironment::systemEnvironment();
const char* const kEnvExecutablePath = "ORBIT_COLLECTOR_EXECUTABLE_PATH";
const char* const kEnvRootPassword = "ORBIT_COLLECTOR_ROOT_PASSWORD";
const char* const kEnvPackagePath = "ORBIT_COLLECTOR_PACKAGE_PATH";
const char* const kEnvSignaturePath = "ORBIT_COLLECTOR_SIGNATURE_PATH";
const char* const kEnvNoDeployment = "ORBIT_COLLECTOR_NO_DEPLOYMENT";
if (env.contains(kEnvExecutablePath) && env.contains(kEnvRootPassword)) {
return OrbitQt::BareExecutableAndRootPasswordDeployment{
env.value(kEnvExecutablePath).toStdString(),
env.value(kEnvRootPassword).toStdString()};
} else if (env.contains(kEnvPackagePath) && env.contains(kEnvSignaturePath)) {
return OrbitQt::SignedDebianPackageDeployment{
env.value(kEnvPackagePath).toStdString(),
env.value(kEnvSignaturePath).toStdString()};
} else if (env.contains(kEnvNoDeployment)) {
return OrbitQt::NoDeployment{};
} else {
return OrbitQt::SignedDebianPackageDeployment{};
}
}
static void DisplayErrorToUser(const QString& message) {
QMessageBox::critical(nullptr, QApplication::applicationName(), message);
}
int main(int argc, char* argv[]) {
const std::string log_file_path = Path::GetLogFilePath();
InitLogFile(log_file_path);
absl::SetProgramUsageMessage("CPU Profiler");
absl::ParseCommandLine(argc, argv);
#if __linux__
QCoreApplication::setAttribute(Qt::AA_DontUseNativeDialogs);
#endif
OrbitGl::GlutContext glut_context{&argc, argv};
QApplication app(argc, argv);
QCoreApplication::setApplicationName("Orbit Profiler [BETA]");
QCoreApplication::setApplicationVersion(OrbitQt::kVersionString);
const std::string dump_path = Path::GetDumpPath();
#ifdef _WIN32
const char* handler_name = "crashpad_handler.exe";
#else
const char* handler_name = "crashpad_handler";
#endif
const std::string handler_path = QDir(QCoreApplication::applicationDirPath())
.absoluteFilePath(handler_name)
.toStdString();
const std::string crash_server_url = CrashServerOptions::GetUrl();
const std::vector<std::string> attachments = {Path::GetLogFilePath()};
CrashHandler crash_handler(dump_path, handler_path, crash_server_url,
attachments);
ApplicationOptions options;
ParseLegacyCommandLine(argc, argv, &options);
StyleOrbit(app);
const auto deployment_configuration = FigureOutDeploymentConfiguration();
const auto open_gl_version = OrbitQt::DetectOpenGlVersion();
if (!open_gl_version) {
DisplayErrorToUser(
"OpenGL support was not found. Please make sure you're not trying to "
"start Orbit in a remote session and make sure you have a recent "
"graphics driver installed. Then try again!");
return -1;
}
LOG("Detected OpenGL version: %i.%i", open_gl_version->major,
open_gl_version->minor);
if (open_gl_version->major < 2) {
DisplayErrorToUser(
QString(
"The minimum required version of OpenGL is 2.0. But this machine "
"only supports up to version %1.%2. Please make sure you're not "
"trying to start Orbit in a remote session and make sure you have "
"a recent graphics driver installed. Then try again!")
.arg(open_gl_version->major)
.arg(open_gl_version->minor));
return -1;
}
auto context = Context::Create();
if (!context) {
DisplayErrorToUser(
QString("An error occurred while initializing ssh: %1")
.arg(QString::fromStdString(context.error().message())));
return -1;
}
while (true) {
const auto result = RunUiInstance(&app, deployment_configuration,
&(context.value()), options);
if (result ||
result.error() == make_error_code(Error::kUserClosedStartUpWindow) ||
!deployment_configuration) {
// It was either a clean shutdown or the deliberately closed the
// dialog, or we started with the --local flag.
return 0;
} else if (result.error() ==
make_error_code(OrbitGgp::Error::kCouldNotUseGgpCli)) {
DisplayErrorToUser(QString::fromStdString(result.error().message()));
return 1;
} else if (result.error() !=
make_error_code(Error::kUserCanceledServiceDeployment)) {
DisplayErrorToUser(
QString("An error occurred: %1")
.arg(QString::fromStdString(result.error().message())));
}
}
}
<|endoftext|>
|
<commit_before>/// \file PasskeyEntry.cpp
//-----------------------------------------------------------------------------
/*
Passkey? That's Russian for 'pass'. You know, passkey
down the streetsky. [Groucho Marx]
*/
#include "PasswordSafe.h"
#include "corelib/PwsPlatform.h"
#include "ThisMfcApp.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#include "pocketpc/PocketPC.h"
#else
#include "resource.h"
#endif
#include "corelib/MyString.h"
#include "SysColStatic.h"
#include "PasskeyEntry.h"
#include "PwFont.h"
#include "TryAgainDlg.h"
#include "DboxMain.h" // for CheckPassword()
#include "corelib/Util.h"
//-----------------------------------------------------------------------------
CPasskeyEntry::CPasskeyEntry(CWnd* pParent,
const CString& a_filespec,
bool first)
: super(first ? CPasskeyEntry::IDD : CPasskeyEntry::IDD_BASIC,
pParent),
m_first(first),
m_filespec(a_filespec),
m_tries(0),
m_status(TAR_INVALID)
{
const int FILE_DISP_LEN = 45;
//{{AFX_DATA_INIT(CPasskeyEntry)
//}}AFX_DATA_INIT
DBGMSG("CPasskeyEntry()\n");
if (first) {
DBGMSG("** FIRST **\n");
}
m_passkey = _T("");
m_hIcon = app.LoadIcon(IDI_CORNERICON);
if (a_filespec.GetLength() > FILE_DISP_LEN) {
// m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display
// m_message.Insert(0, _T("..."));
// changed by karel@VanderGucht.de to see beginning + ending of 'a_filespec'
m_message = a_filespec.Left(FILE_DISP_LEN/2-5) + " ... " + a_filespec.Right(FILE_DISP_LEN/2);
}
else
{
m_message = a_filespec;
}
}
void CPasskeyEntry::DoDataExchange(CDataExchange* pDX)
{
super::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PASSKEY, (CString &)m_passkey);
#if !defined(POCKET_PC)
if ( m_first )
DDX_Control(pDX, IDC_STATIC_LOGOTEXT, m_ctlLogoText);
#endif
//{{AFX_DATA_MAP(CPasskeyEntry)
#if !defined(POCKET_PC)
DDX_Control(pDX, IDC_STATIC_LOGO, m_ctlLogo);
DDX_Control(pDX, IDOK, m_ctlOK);
#endif
DDX_Control(pDX, IDC_PASSKEY, m_ctlPasskey);
DDX_Text(pDX, IDC_MESSAGE, m_message);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPasskeyEntry, super)
//{{AFX_MSG_MAP(CPasskeyEntry)
ON_BN_CLICKED(ID_HELP, OnHelp)
ON_BN_CLICKED(ID_BROWSE, OnBrowse)
ON_BN_CLICKED(ID_CREATE_DB, OnCreateDb)
#if defined(POCKET_PC)
ON_EN_SETFOCUS(IDC_PASSKEY, OnPasskeySetfocus)
ON_EN_KILLFOCUS(IDC_PASSKEY, OnPasskeyKillfocus)
#endif
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL
CPasskeyEntry::OnInitDialog(void)
{
SetPasswordFont(GetDlgItem(IDC_PASSKEY));
#if defined(POCKET_PC)
// If displaying IDD_PASSKEYENTRY_FIRST then bypass superclass and go
// directly to CDialog::OnInitDialog() and display the dialog fullscreen
// otherwise display as a centred dialogue.
if ( m_nIDHelp == IDD )
{
super::super::OnInitDialog();
}
else
{
#endif
super::OnInitDialog();
#if defined(POCKET_PC)
}
#endif
if (m_message.IsEmpty() && m_first)
{
m_ctlPasskey.EnableWindow(FALSE);
#if !defined(POCKET_PC)
m_ctlOK.EnableWindow(FALSE);
#endif
m_message = _T("[No current database]");
}
/*
* this bit makes the background come out right on
* the bitmaps
*/
#if !defined(POCKET_PC)
if (m_first)
{
m_ctlLogoText.ReloadBitmap(IDB_PSLOGO);
m_ctlLogo.ReloadBitmap(IDB_CLOGO);
}
else
{
m_ctlLogo.ReloadBitmap(IDB_CLOGO_SMALL);
}
#endif
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
return TRUE;
}
#if defined(POCKET_PC)
/************************************************************************/
/* Restore the state of word completion when the password field loses */
/* focus. */
/************************************************************************/
void CPasskeyEntry::OnPasskeyKillfocus()
{
EnableWordCompletion( m_hWnd );
}
/************************************************************************/
/* When the password field is activated, pull up the SIP and disable */
/* word completion. */
/************************************************************************/
void CPasskeyEntry::OnPasskeySetfocus()
{
DisableWordCompletion( m_hWnd );
}
#endif
void
CPasskeyEntry::OnBrowse()
{
m_status = TAR_OPEN;
app.m_pMainWnd = NULL;
super::OnCancel();
}
void
CPasskeyEntry::OnCreateDb()
{
m_status = TAR_NEW;
app.m_pMainWnd = NULL;
super::OnCancel();
}
void
CPasskeyEntry::OnCancel()
{
app.m_pMainWnd = NULL;
super::OnCancel();
}
void
CPasskeyEntry::OnOK()
{
UpdateData(TRUE);
if (m_passkey.IsEmpty())
{
AfxMessageBox("The combination cannot be blank.");
m_ctlPasskey.SetFocus();
return;
}
DboxMain* pParent = (DboxMain*) GetParent();
ASSERT(pParent != NULL);
if (pParent->CheckPassword(m_filespec, m_passkey) != PWScore::SUCCESS)
{
if (m_tries >= 2)
{
CTryAgainDlg errorDlg(this);
int nResponse = errorDlg.DoModal();
if (nResponse == IDOK)
{
}
else if (nResponse == IDCANCEL)
{
m_status = errorDlg.GetCancelReturnValue();
app.m_pMainWnd = NULL;
super::OnCancel();
}
}
else
{
m_tries++;
AfxMessageBox(_T("Incorrect passkey"));
m_ctlPasskey.SetSel(MAKEWORD(-1, 0));
m_ctlPasskey.SetFocus();
}
}
else
{
app.m_pMainWnd = NULL;
super::OnOK();
}
}
void
CPasskeyEntry::OnHelp()
{
#if defined(POCKET_PC)
CreateProcess( _T("PegHelp.exe"), _T("pws_ce_help.html#comboentry"), NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL );
#else
//WinHelp(0x200B9, HELP_CONTEXT);
::HtmlHelp(NULL,
"pwsafe.chm::/html/pws_combo_entry.htm",
HH_DISPLAY_TOPIC, 0);
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>[1006234] Choosing "Cancel" in the Enter Password dialog box now exits the application.<commit_after>/// \file PasskeyEntry.cpp
//-----------------------------------------------------------------------------
/*
Passkey? That's Russian for 'pass'. You know, passkey
down the streetsky. [Groucho Marx]
*/
#include "PasswordSafe.h"
#include "corelib/PwsPlatform.h"
#include "ThisMfcApp.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#include "pocketpc/PocketPC.h"
#else
#include "resource.h"
#endif
#include "corelib/MyString.h"
#include "SysColStatic.h"
#include "PasskeyEntry.h"
#include "PwFont.h"
#include "TryAgainDlg.h"
#include "DboxMain.h" // for CheckPassword()
#include "corelib/Util.h"
//-----------------------------------------------------------------------------
CPasskeyEntry::CPasskeyEntry(CWnd* pParent,
const CString& a_filespec,
bool first)
: super(first ? CPasskeyEntry::IDD : CPasskeyEntry::IDD_BASIC,
pParent),
m_first(first),
m_filespec(a_filespec),
m_tries(0),
m_status(TAR_INVALID)
{
const int FILE_DISP_LEN = 45;
//{{AFX_DATA_INIT(CPasskeyEntry)
//}}AFX_DATA_INIT
DBGMSG("CPasskeyEntry()\n");
if (first) {
DBGMSG("** FIRST **\n");
}
m_passkey = _T("");
m_hIcon = app.LoadIcon(IDI_CORNERICON);
if (a_filespec.GetLength() > FILE_DISP_LEN) {
// m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display
// m_message.Insert(0, _T("..."));
// changed by karel@VanderGucht.de to see beginning + ending of 'a_filespec'
m_message = a_filespec.Left(FILE_DISP_LEN/2-5) + " ... " + a_filespec.Right(FILE_DISP_LEN/2);
}
else
{
m_message = a_filespec;
}
}
void CPasskeyEntry::DoDataExchange(CDataExchange* pDX)
{
super::DoDataExchange(pDX);
DDX_Text(pDX, IDC_PASSKEY, (CString &)m_passkey);
#if !defined(POCKET_PC)
if ( m_first )
DDX_Control(pDX, IDC_STATIC_LOGOTEXT, m_ctlLogoText);
#endif
//{{AFX_DATA_MAP(CPasskeyEntry)
#if !defined(POCKET_PC)
DDX_Control(pDX, IDC_STATIC_LOGO, m_ctlLogo);
DDX_Control(pDX, IDOK, m_ctlOK);
#endif
DDX_Control(pDX, IDC_PASSKEY, m_ctlPasskey);
DDX_Text(pDX, IDC_MESSAGE, m_message);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CPasskeyEntry, super)
//{{AFX_MSG_MAP(CPasskeyEntry)
ON_BN_CLICKED(ID_HELP, OnHelp)
ON_BN_CLICKED(ID_BROWSE, OnBrowse)
ON_BN_CLICKED(ID_CREATE_DB, OnCreateDb)
#if defined(POCKET_PC)
ON_EN_SETFOCUS(IDC_PASSKEY, OnPasskeySetfocus)
ON_EN_KILLFOCUS(IDC_PASSKEY, OnPasskeyKillfocus)
#endif
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
BOOL
CPasskeyEntry::OnInitDialog(void)
{
SetPasswordFont(GetDlgItem(IDC_PASSKEY));
#if defined(POCKET_PC)
// If displaying IDD_PASSKEYENTRY_FIRST then bypass superclass and go
// directly to CDialog::OnInitDialog() and display the dialog fullscreen
// otherwise display as a centred dialogue.
if ( m_nIDHelp == IDD )
{
super::super::OnInitDialog();
}
else
{
#endif
super::OnInitDialog();
#if defined(POCKET_PC)
}
#endif
if (m_message.IsEmpty() && m_first)
{
m_ctlPasskey.EnableWindow(FALSE);
#if !defined(POCKET_PC)
m_ctlOK.EnableWindow(FALSE);
#endif
m_message = _T("[No current database]");
}
/*
* this bit makes the background come out right on
* the bitmaps
*/
#if !defined(POCKET_PC)
if (m_first)
{
m_ctlLogoText.ReloadBitmap(IDB_PSLOGO);
m_ctlLogo.ReloadBitmap(IDB_CLOGO);
}
else
{
m_ctlLogo.ReloadBitmap(IDB_CLOGO_SMALL);
}
#endif
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
return TRUE;
}
#if defined(POCKET_PC)
/************************************************************************/
/* Restore the state of word completion when the password field loses */
/* focus. */
/************************************************************************/
void CPasskeyEntry::OnPasskeyKillfocus()
{
EnableWordCompletion( m_hWnd );
}
/************************************************************************/
/* When the password field is activated, pull up the SIP and disable */
/* word completion. */
/************************************************************************/
void CPasskeyEntry::OnPasskeySetfocus()
{
DisableWordCompletion( m_hWnd );
}
#endif
void
CPasskeyEntry::OnBrowse()
{
m_status = TAR_OPEN;
app.m_pMainWnd = NULL;
super::OnCancel();
}
void
CPasskeyEntry::OnCreateDb()
{
m_status = TAR_NEW;
app.m_pMainWnd = NULL;
super::OnCancel();
}
void
CPasskeyEntry::OnCancel()
{
app.m_pMainWnd = NULL;
m_status = TAR_CANCEL;
super::OnCancel();
}
void
CPasskeyEntry::OnOK()
{
UpdateData(TRUE);
if (m_passkey.IsEmpty())
{
AfxMessageBox("The combination cannot be blank.");
m_ctlPasskey.SetFocus();
return;
}
DboxMain* pParent = (DboxMain*) GetParent();
ASSERT(pParent != NULL);
if (pParent->CheckPassword(m_filespec, m_passkey) != PWScore::SUCCESS)
{
if (m_tries >= 2)
{
CTryAgainDlg errorDlg(this);
int nResponse = errorDlg.DoModal();
if (nResponse == IDOK)
{
}
else if (nResponse == IDCANCEL)
{
m_status = errorDlg.GetCancelReturnValue();
app.m_pMainWnd = NULL;
super::OnCancel();
}
}
else
{
m_tries++;
AfxMessageBox(_T("Incorrect passkey"));
m_ctlPasskey.SetSel(MAKEWORD(-1, 0));
m_ctlPasskey.SetFocus();
}
}
else
{
app.m_pMainWnd = NULL;
super::OnOK();
}
}
void
CPasskeyEntry::OnHelp()
{
#if defined(POCKET_PC)
CreateProcess( _T("PegHelp.exe"), _T("pws_ce_help.html#comboentry"), NULL, NULL, FALSE, 0, NULL, NULL, NULL, NULL );
#else
//WinHelp(0x200B9, HELP_CONTEXT);
::HtmlHelp(NULL,
"pwsafe.chm::/html/pws_combo_entry.htm",
HH_DISPLAY_TOPIC, 0);
#endif
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
using std::pair;
using std::make_pair;
using std::vector;
using std::string;
using std::cout;
using std::ifstream;
using std::istringstream;
using std::basic_istringstream;
/*
Dado un caracter, separa un string en substring que almacena en un vector dado,
cada vez que se encuentre con el caracter dado.
*/
void split(const string &s, char c, vector<string> &v){
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos){
v.push_back(s.substr(i, j - i));
i = ++j;
j = s.find(c, j);
if (j == string::npos){
v.push_back(s.substr(i, s.length()));
}
}
}
/*
Estructura que contiene un cojunto de palabras para un grupo de palabras prohibidas
determinada.
*/
class ACMCase{
public:
int numCases, numRestrictedWords;
vector<vector<string>> words; // Vector con los las oraciones a evaluar(vectores de string).
vector<string> restrictedWords; // Vector con las palbras a ignorar
ACMCase(){
this->numCases = 0;
this->numRestrictedWords = 0;
};
~ACMCase(){};
void solveWord(vector<string> statement){
pair<int, int> sp; // Par <numero de letras confirmadas de la abreviacion, numero de ultima palbra usada para completar abreviacion>
vector<pair<int, int>> solutions; // Vector con las posibles abreviaciones
int numSolution = 0; // Numero de abreviaciones confirmadas
int as = statement[0].size();
int checkSolUntil;
solutions.clear();
// Recorro las palabras de la oracion a abreviar
for (unsigned int i = 1; i < statement.size(); i++){
// Recorro cada caracter de la palabra
for (unsigned int j = 0; j < statement[i].size(); j++){
// Recorro las soluciones actuales
checkSolUntil = solutions.size();
for (unsigned int k = 0; k < checkSolUntil; k++){
// Si hubo una palabra en la solucion de la cual no se extrajo al
// menos una letra para la abreviacion se elimina del vector de soluciones
if (i > (solutions[k].second + 1)){
solutions.erase(solutions.begin() + k);
checkSolUntil-=1;
k = k - 1;
continue;
}
// Si encuentro un caracter que completa la abreviacio, agrego una nueva solucion.
//cout << solutions[k].first << " " << statement[0].size() << "\n";
if ((solutions[k].first < statement[0].size()) &&
((statement[i][j] == statement[0][solutions[k].first + 1]) || (toupper(statement[i][j]) == statement[0][solutions[k].first + 1]))){
// Si es el ultimo caracter de la abreviacion y esta en la ultima palabra, incremento en 1 el numero de soluciones.
if ((i == (statement.size() - 1)) && ((solutions[k].first + 2) == as)){
numSolution++;
}
else {
sp = make_pair(solutions[k].first + 1, i);
solutions.push_back(sp);
}
}
}
// Si se consigue el comienza de la abreviacion en la primera palabra, se agrega la posible solucion.
// cout << statement[i][j] << " " << statement[0][0] << "\n";
if (((statement[i][j] == statement[0][0]) || (toupper(statement[i][j]) == statement[0][0])) && (i == 1)){
sp = make_pair(0, 1);
solutions.push_back(sp);
}
}
}
cout << statement[0];
if (numSolution > 0){
cout << " can be formed in " << numSolution << " ways\n";
}
else {
cout << " is not valid abbreviation\n";
}
}
void solveMyself(){
unsigned int i;
for (i = 0; i < words.size(); i++){
solveWord(this->words[i]);
}
}
};
/*
Procedimiento que dado el nombre de un archivo, lo lee y devuelve un vector
con los casosa evaluar.
*/
vector<ACMCase> readFile(char *fileName){
ifstream fileStream(fileName); // stream del archivo
string currentLine; // ultima linea leida
ACMCase *currentCase = NULL; // Caso en construccion
vector<ACMCase> out; // Vector de casos a evaluar
vector<string> validWords, auxVector; // Vector con las palabras utiles en cada subcaso.
// Vecotr Auxiliuar
int proxyInt, numWords = 0; // Enteros auxiliar
bool endReading = false; // Guardia para salir del ciclo
while (getline(fileStream, currentLine)){
switch (currentLine[0]){
// Casos en que es cualquier numero mayor a cero.
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// Se agrega el caso anterior de exitir
if (currentCase){
out.push_back(*currentCase);
}
// obtengo el numero de palabras a omitir
proxyInt = atoi(currentLine.c_str());
// Se crea un nuevo caso
currentCase = new ACMCase;
currentCase->numRestrictedWords = proxyInt;
currentCase->numCases = 0;
// Se lee las palabras a omitir
for (int i = 0; i < proxyInt; i++){
getline(fileStream, currentLine);
currentCase->restrictedWords.push_back(currentLine);
}
break;
case '0':
// Se agrega el caso anterior de exitir
if (currentCase){
out.push_back(*currentCase);
}
// Indica el final de lo casos e indica a la guardia que salga del ciclo de lectura
endReading = true;
break;
default:
// Se lee un una abreviacion con su palabra y se asigna al caso actual.
if (currentLine!="LAST CASE"){
currentCase->numCases++;
auxVector.clear();
validWords.clear();
split(currentLine,' ',auxVector);
validWords.push_back(auxVector[0]);
unsigned int i;
unsigned int j;
for (i = 1; i < auxVector.size(); i++){
bool valid = true;
for (j = 0; j < currentCase->restrictedWords.size(); j++){
// Se verifica que las palabras sean validas
if (auxVector[i].compare(currentCase->restrictedWords[j]) == 0){
valid = false;
break;
}
}
// Se almacenn solo las palabras validas
if (valid) { validWords.push_back(auxVector[i]); };
}
currentCase->words.push_back(validWords);
break;
}
}
// Salgo del ciclo en cuanto lea cero.
if (endReading) { break; };
}
return out;
}
int main(int argc, char *argv[]){
char *fileName;
int nodeNum = 0;
vector<ACMCase> cases;
if (argc >= 2) {
fileName = argv[1];
}
else {
fileName = "prueba1.in";
}
// Llamo a la lectura de archivo
cases = readFile(fileName);
/*
unsigned int i = 0;
unsigned int j = 0;
unsigned int k = 0;
for (i = 0; i < cases.size(); i++){
for (j = 0; j < cases[i].restrictedWords.size(); j++){
cout << cases[i].restrictedWords[j] << '\n';
}
for (j = 0; j < cases[i].words.size(); j++){
for (k = 0; k < cases[i].words[j].size(); k++){
cout << cases[i].words[j][k] << ' ';
}
cout << "\n";
}
}
*/
for (int x = 0; x < cases.size(); x++){
cases[x].solveMyself();
}
/*while (1){
};*/
}<commit_msg>Arreglado peo de compilacion<commit_after>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
using std::pair;
using std::make_pair;
using std::vector;
using std::string;
using std::cout;
using std::ifstream;
using std::istringstream;
using std::basic_istringstream;
/*
Dado un caracter, separa un string en substring que almacena en un vector dado,
cada vez que se encuentre con el caracter dado.
*/
void split(const string &s, char c, vector<string> &v){
string::size_type i = 0;
string::size_type j = s.find(c);
while (j != string::npos){
v.push_back(s.substr(i, j - i));
i = ++j;
j = s.find(c, j);
if (j == string::npos){
v.push_back(s.substr(i, s.length()));
}
}
}
/*
Estructura que contiene un cojunto de palabras para un grupo de palabras prohibidas
determinada.
*/
class ACMCase{
public:
int numCases, numRestrictedWords;
vector< vector<string> > words; // Vector con los las oraciones a evaluar(vectores de string).
vector<string> restrictedWords; // Vector con las palbras a ignorar
ACMCase(){
this->numCases = 0;
this->numRestrictedWords = 0;
};
~ACMCase(){};
void solveWord(vector<string> statement){
pair<int, int> sp; // Par <numero de letras confirmadas de la abreviacion, numero de ultima palbra usada para completar abreviacion>
vector<pair<int, int> > solutions; // Vector con las posibles abreviaciones
int numSolution = 0; // Numero de abreviaciones confirmadas
int as = statement[0].size();
int checkSolUntil;
solutions.clear();
// Recorro las palabras de la oracion a abreviar
for (unsigned int i = 1; i < statement.size(); i++){
// Recorro cada caracter de la palabra
for (unsigned int j = 0; j < statement[i].size(); j++){
// Recorro las soluciones actuales
checkSolUntil = solutions.size();
for (unsigned int k = 0; k < checkSolUntil; k++){
// Si hubo una palabra en la solucion de la cual no se extrajo al
// menos una letra para la abreviacion se elimina del vector de soluciones
if (i > (solutions[k].second + 1)){
solutions.erase(solutions.begin() + k);
checkSolUntil-=1;
k = k - 1;
continue;
}
// Si encuentro un caracter que completa la abreviacio, agrego una nueva solucion.
//cout << solutions[k].first << " " << statement[0].size() << "\n";
if ((solutions[k].first < statement[0].size()) &&
((statement[i][j] == statement[0][solutions[k].first + 1]) || (toupper(statement[i][j]) == statement[0][solutions[k].first + 1]))){
// Si es el ultimo caracter de la abreviacion y esta en la ultima palabra, incremento en 1 el numero de soluciones.
if ((i == (statement.size() - 1)) && ((solutions[k].first + 2) == as)){
numSolution++;
}
else {
sp = make_pair(solutions[k].first + 1, i);
solutions.push_back(sp);
}
}
}
// Si se consigue el comienza de la abreviacion en la primera palabra, se agrega la posible solucion.
// cout << statement[i][j] << " " << statement[0][0] << "\n";
if (((statement[i][j] == statement[0][0]) || (toupper(statement[i][j]) == statement[0][0])) && (i == 1)){
sp = make_pair(0, 1);
solutions.push_back(sp);
}
}
}
cout << statement[0];
if (numSolution > 0){
cout << " can be formed in " << numSolution << " ways\n";
}
else {
cout << " is not valid abbreviation\n";
}
}
void solveMyself(){
unsigned int i;
for (i = 0; i < words.size(); i++){
solveWord(this->words[i]);
}
}
};
/*
Procedimiento que dado el nombre de un archivo, lo lee y devuelve un vector
con los casosa evaluar.
*/
vector<ACMCase> readFile(const char *fileName){
ifstream fileStream(fileName); // stream del archivo
string currentLine; // ultima linea leida
ACMCase *currentCase = NULL; // Caso en construccion
vector<ACMCase> out; // Vector de casos a evaluar
vector<string> validWords, auxVector; // Vector con las palabras utiles en cada subcaso.
// Vecotr Auxiliuar
int proxyInt, numWords = 0; // Enteros auxiliar
bool endReading = false; // Guardia para salir del ciclo
while (getline(fileStream, currentLine)){
switch (currentLine[0]){
// Casos en que es cualquier numero mayor a cero.
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// Se agrega el caso anterior de exitir
if (currentCase){
out.push_back(*currentCase);
}
// obtengo el numero de palabras a omitir
proxyInt = atoi(currentLine.c_str());
// Se crea un nuevo caso
currentCase = new ACMCase;
currentCase->numRestrictedWords = proxyInt;
currentCase->numCases = 0;
// Se lee las palabras a omitir
for (int i = 0; i < proxyInt; i++){
getline(fileStream, currentLine);
currentCase->restrictedWords.push_back(currentLine);
}
break;
case '0':
// Se agrega el caso anterior de exitir
if (currentCase){
out.push_back(*currentCase);
}
// Indica el final de lo casos e indica a la guardia que salga del ciclo de lectura
endReading = true;
break;
default:
// Se lee un una abreviacion con su palabra y se asigna al caso actual.
if (currentLine!="LAST CASE"){
currentCase->numCases++;
auxVector.clear();
validWords.clear();
split(currentLine,' ',auxVector);
validWords.push_back(auxVector[0]);
unsigned int i;
unsigned int j;
for (i = 1; i < auxVector.size(); i++){
bool valid = true;
for (j = 0; j < currentCase->restrictedWords.size(); j++){
// Se verifica que las palabras sean validas
if (auxVector[i].compare(currentCase->restrictedWords[j]) == 0){
valid = false;
break;
}
}
// Se almacenn solo las palabras validas
if (valid) { validWords.push_back(auxVector[i]); };
}
currentCase->words.push_back(validWords);
break;
}
}
// Salgo del ciclo en cuanto lea cero.
if (endReading) { break; };
}
return out;
}
int main(int argc, char *argv[]){
const char *fileName;
int nodeNum = 0;
vector<ACMCase> cases;
if (argc >= 2) {
fileName = argv[1];
}
else {
fileName = "prueba1.in";
}
// Llamo a la lectura de archivo
cases = readFile(fileName);
/*
unsigned int i = 0;
unsigned int j = 0;
unsigned int k = 0;
for (i = 0; i < cases.size(); i++){
for (j = 0; j < cases[i].restrictedWords.size(); j++){
cout << cases[i].restrictedWords[j] << '\n';
}
for (j = 0; j < cases[i].words.size(); j++){
for (k = 0; k < cases[i].words[j].size(); k++){
cout << cases[i].words[j][k] << ' ';
}
cout << "\n";
}
}
*/
for (int x = 0; x < cases.size(); x++){
cases[x].solveMyself();
}
/*while (1){
};*/
}
<|endoftext|>
|
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ MTU3 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/icu_mgr.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/mtu3.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"
#include "common/format.hpp"
/// F_PCLKA は変換パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKA
# error "mtu_io.hpp requires F_PCLKA to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MTU 制御クラス
@param[in] MTU MTU ユニット
@param[in] MTASK メイン割り込みタスク
@param[in] OTASK オーバーフロー割り込みタスク
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class MTUX, class MTASK = utils::null_task, class OTASK = utils::null_task>
class mtu_io {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エッジ・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class edge_type : uint8_t {
positive, ///< 立ち上がり
negative, ///< 立下り
dual, ///< 両エッジ
};
private:
struct task_t {
volatile uint16_t cap_tick_;
volatile uint16_t ovf_tick_;
volatile uint32_t tgr_adr_;
volatile uint32_t cap_count_;
volatile uint16_t ovf_limit_;
volatile uint16_t ovf_count_;
task_t() : cap_tick_(0), ovf_tick_(0),
tgr_adr_(MTUX::TGRA.address()), cap_count_(0),
ovf_limit_(1221), ovf_count_(0) { }
void clear() {
cap_tick_ = 0;
ovf_tick_ = 0;
cap_count_ = 0;
ovf_count_ = 0;
}
void load_cap() {
cap_count_ = rd16_(tgr_adr_);
cap_count_ |= static_cast<uint32_t>(ovf_tick_) << 16;
}
};
static task_t task_t_;
static MTASK mtask_;
static OTASK otask_;
uint32_t clk_limit_;
static INTERRUPT_FUNC void cap_task_()
{
++task_t_.cap_tick_;
task_t_.load_cap();
mtask_();
task_t_.ovf_tick_ = 0;
}
static INTERRUPT_FUNC void ovf_task_()
{
++task_t_.ovf_tick_;
if(task_t_.ovf_tick_ >= task_t_.ovf_limit_) {
task_t_.ovf_tick_ = 0;
MTUX::TCNT = 0;
++task_t_.ovf_count_;
}
otask_();
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
mtu_io() : clk_limit_(F_PCLKA) { }
//-----------------------------------------------------------------//
/*!
@brief リミット・クロックの設定
@param[in] clk リミット・クロック
*/
//-----------------------------------------------------------------//
void set_limit_clock(uint32_t clk) { clk_limit_ = clk; }
//-----------------------------------------------------------------//
/*!
@brief インプットキャプチャ開始 @n
※カウントクロックは「set_limit_clock」により @n
変更が可能。
@param[in] ch 入力チャネル
@param[in] et エッジ・タイプ
@param[in] level 割り込みレベル
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start_capture(typename MTUX::channel ch, edge_type et, uint8_t level = 0)
{
if(MTUX::get_peripheral() == peripheral::MTU5) { // MTU5 はインプットキャプチャとして利用不可
return false;
}
uint8_t idx = static_cast<uint8_t>(ch);
if(idx >= 4) return false;
power_cfg::turn(MTUX::get_peripheral());
MTUX::enable_port(ch);
uint8_t etd = 0;
switch(et) {
case edge_type::positive: etd = 0b1000; break;
case edge_type::negative: etd = 0b1001; break;
case edge_type::dual: etd = 0b1011; break;
default: break;
}
MTUX::TIOR.set(ch, etd);
uint8_t dv = 0;
static const uint8_t cclr[4] = { 0b001, 0b010, 0b101, 0b110 };
// CKEG: 立ち上がりエッジでカウントアップ
MTUX::TCR = MTUX::TCR.TPSC.b(dv)
| MTUX::TCR.CKEG.b(0b00)
| MTUX::TCR.CCLR.b(cclr[idx]); // ※インプットキャプチャ入力で TCNT はクリア
MTUX::TCR2 = 0x00;
MTUX::TMDR1 = 0x00; // 通常動作
if(level > 0) {
set_interrupt_task(ovf_task_, static_cast<uint32_t>(MTUX::get_vec(MTUX::interrupt::OVF)));
icu_mgr::set_level(MTUX::get_vec(MTUX::interrupt::OVF), level);
ICU::VECTOR cvec = MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch));
set_interrupt_task(cap_task_, static_cast<uint32_t>(cvec));
icu_mgr::set_level(MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch)), level);
MTUX::TIER = (1 << static_cast<uint8_t>(ch)) | MTUX::TIER.TCIEV.b();
}
task_t_.clear();
// 各チャネルに相当するジャネラルレジスタ
task_t_.tgr_adr_ = MTUX::TGRA.address() + static_cast<uint32_t>(ch) * 2;
wr16_(task_t_.tgr_adr_, 0x0000);
MTUX::TCNT = 0;
MTUX::enable();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャ、リミットの設定
@param[in] limit インプット・キャプチャ、リミット
*/
//-----------------------------------------------------------------//
void set_capture_limit(uint16_t limit)
{
task_t_.limit_ovf_ = limit;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャのオーバーフローカウント取得
@return インプット・キャプチャのオーバーフローカウント
*/
//-----------------------------------------------------------------//
uint16_t get_capture_ovf() const
{
return task_t_.ovf_count_;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャカウント取得
@return インプット・キャプチャカウント
*/
//-----------------------------------------------------------------//
uint16_t get_capture_tick() const
{
return task_t_.cap_tick_;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャ値を取得
@return インプット・キャプチャ値
*/
//-----------------------------------------------------------------//
uint32_t get_capture() const
{
return task_t_.cap_count_;
}
//-----------------------------------------------------------------//
/*!
@brief MTASK クラスの参照
@return MTASK クラス
*/
//-----------------------------------------------------------------//
static MTASK& at_main_task() { return mtask_; }
//-----------------------------------------------------------------//
/*!
@brief OTASK クラスの参照
@return OTASK クラス
*/
//-----------------------------------------------------------------//
static OTASK& at_ovfl_task() { return otask_; }
};
template <class MTUX, class MTASK, class OTASK>
typename mtu_io<MTUX, MTASK, OTASK>::task_t mtu_io<MTUX, MTASK, OTASK>::task_t_;
template <class MTUX, class MTASK, class OTASK> MTASK mtu_io<MTUX, MTASK, OTASK>::mtask_;
template <class MTUX, class MTASK, class OTASK> OTASK mtu_io<MTUX, MTASK, OTASK>::otask_;
}
<commit_msg>cleanup<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ MTU3 制御
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "RX24T/icu_mgr.hpp"
#include "RX24T/port_map.hpp"
#include "RX24T/power_cfg.hpp"
#include "RX24T/mtu3.hpp"
#include "common/intr_utils.hpp"
#include "common/vect.h"
#include "common/format.hpp"
/// F_PCLKA は変換パラメーター計算で必要で、設定が無いとエラーにします。
#ifndef F_PCLKA
# error "mtu_io.hpp requires F_PCLKA to be defined"
#endif
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief MTU 制御クラス
@param[in] MTU MTU ユニット
@param[in] MTASK メイン割り込みタスク
@param[in] OTASK オーバーフロー割り込みタスク
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <class MTUX, class MTASK = utils::null_task, class OTASK = utils::null_task>
class mtu_io {
public:
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief エッジ・タイプ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class edge_type : uint8_t {
positive, ///< 立ち上がり
negative, ///< 立下り
dual, ///< 両エッジ
};
private:
struct task_t {
volatile uint32_t tgr_adr_;
volatile uint32_t cap_count_;
volatile uint16_t cap_tick_;
volatile uint16_t ovf_tick_;
volatile uint16_t ovf_limit_;
volatile uint16_t ovf_count_;
task_t() : tgr_adr_(MTUX::TGRA.address()), cap_count_(0),
cap_tick_(0), ovf_tick_(0),
ovf_limit_(1221), ovf_count_(0) { }
void clear() {
cap_tick_ = 0;
ovf_tick_ = 0;
cap_count_ = 0;
ovf_count_ = 0;
}
void load_cap() {
cap_count_ = (static_cast<uint32_t>(ovf_tick_) << 16) | rd16_(tgr_adr_);
}
};
static task_t task_t_;
static MTASK mtask_;
static OTASK otask_;
uint32_t clk_base_;
static INTERRUPT_FUNC void cap_task_()
{
++task_t_.cap_tick_;
task_t_.load_cap();
mtask_();
task_t_.ovf_tick_ = 0;
}
static INTERRUPT_FUNC void ovf_task_()
{
++task_t_.ovf_tick_;
if(task_t_.ovf_tick_ >= task_t_.ovf_limit_) {
task_t_.ovf_tick_ = 0;
MTUX::TCNT = 0;
++task_t_.ovf_count_;
}
otask_();
}
public:
//-----------------------------------------------------------------//
/*!
@brief コンストラクター
*/
//-----------------------------------------------------------------//
mtu_io() noexcept : clk_base_(F_PCLKA) { }
//-----------------------------------------------------------------//
/*!
@brief ベース・クロックの設定
@param[in] clk ベース・クロック
*/
//-----------------------------------------------------------------//
void set_base_clock(uint32_t clk) noexcept { clk_base_ = clk; }
//-----------------------------------------------------------------//
/*!
@brief ベース・クロックの取得
@return ベース・クロック
*/
//-----------------------------------------------------------------//
uint32_t get_base_clock() const noexcept { return clk_base_; }
//-----------------------------------------------------------------//
/*!
@brief インプットキャプチャ開始 @n
※カウントクロックは「set_limit_clock」により @n
変更が可能。
@param[in] ch 入力チャネル
@param[in] et エッジ・タイプ
@param[in] level 割り込みレベル(割り込みを使わない場合エラー)
@return 成功なら「true」
*/
//-----------------------------------------------------------------//
bool start_capture(typename MTUX::channel ch, edge_type et, uint8_t level) noexcept
{
if(level == 0) return false;
if(MTUX::get_peripheral() == peripheral::MTU5) { // MTU5 はインプットキャプチャとして利用不可
return false;
}
uint8_t idx = static_cast<uint8_t>(ch);
if(idx >= 4) return false;
power_cfg::turn(MTUX::get_peripheral());
MTUX::enable_port(ch);
uint8_t etd = 0;
switch(et) {
case edge_type::positive: etd = 0b1000; break;
case edge_type::negative: etd = 0b1001; break;
case edge_type::dual: etd = 0b1011; break;
default: break;
}
MTUX::TIOR.set(ch, etd);
uint8_t dv = 0;
static const uint8_t cclr[4] = { 0b001, 0b010, 0b101, 0b110 };
// CKEG: 立ち上がりエッジでカウントアップ
MTUX::TCR = MTUX::TCR.TPSC.b(dv)
| MTUX::TCR.CKEG.b(0b00)
| MTUX::TCR.CCLR.b(cclr[idx]); // ※インプットキャプチャ入力で TCNT はクリア
MTUX::TCR2 = 0x00;
MTUX::TMDR1 = 0x00; // 通常動作
if(level > 0) {
set_interrupt_task(ovf_task_, static_cast<uint32_t>(MTUX::get_vec(MTUX::interrupt::OVF)));
icu_mgr::set_level(MTUX::get_vec(MTUX::interrupt::OVF), level);
ICU::VECTOR cvec = MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch));
set_interrupt_task(cap_task_, static_cast<uint32_t>(cvec));
icu_mgr::set_level(MTUX::get_vec(static_cast<typename MTUX::interrupt>(ch)), level);
MTUX::TIER = (1 << static_cast<uint8_t>(ch)) | MTUX::TIER.TCIEV.b();
}
task_t_.clear();
// 各チャネルに相当するジャネラルレジスタ
task_t_.tgr_adr_ = MTUX::TGRA.address() + static_cast<uint32_t>(ch) * 2;
wr16_(task_t_.tgr_adr_, 0x0000);
MTUX::TCNT = 0;
MTUX::enable();
return true;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャ、リミットの設定
@param[in] limit インプット・キャプチャ、リミット
*/
//-----------------------------------------------------------------//
void set_capture_limit(uint16_t limit) noexcept
{
task_t_.limit_ovf_ = limit;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャのオーバーフローカウント取得
@return インプット・キャプチャのオーバーフローカウント
*/
//-----------------------------------------------------------------//
uint16_t get_capture_ovf() const noexcept
{
return task_t_.ovf_count_;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャカウント取得
@return インプット・キャプチャカウント
*/
//-----------------------------------------------------------------//
uint16_t get_capture_tick() const noexcept
{
return task_t_.cap_tick_;
}
//-----------------------------------------------------------------//
/*!
@brief インプット・キャプチャ値を取得
@return インプット・キャプチャ値
*/
//-----------------------------------------------------------------//
uint32_t get_capture() const noexcept
{
return task_t_.cap_count_;
}
//-----------------------------------------------------------------//
/*!
@brief MTASK クラスの参照
@return MTASK クラス
*/
//-----------------------------------------------------------------//
static MTASK& at_main_task() noexcept { return mtask_; }
//-----------------------------------------------------------------//
/*!
@brief OTASK クラスの参照
@return OTASK クラス
*/
//-----------------------------------------------------------------//
static OTASK& at_ovfl_task() noexcept { return otask_; }
};
template <class MTUX, class MTASK, class OTASK>
typename mtu_io<MTUX, MTASK, OTASK>::task_t mtu_io<MTUX, MTASK, OTASK>::task_t_;
template <class MTUX, class MTASK, class OTASK> MTASK mtu_io<MTUX, MTASK, OTASK>::mtask_;
template <class MTUX, class MTASK, class OTASK> OTASK mtu_io<MTUX, MTASK, OTASK>::otask_;
}
<|endoftext|>
|
<commit_before>#include "SecureSocket.hpp"
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sstream>
#include <iostream>
#include "Timer.hpp"
using namespace Kite;
//#define debugprintf(...) fprintf(stderr, __VA_ARGS__)
#define debugprintf(...)
//TODO: not thread safe
static std::map<SSL *, SecureSocket *> rebind_map;
class Kite::SecureSocketPrivate : public Kite::Evented {
public:
SSL_CTX *ssl_ctx;
BIO *bio;
SSL *ssl; //do note delete, is a ref from bio
SecureSocket::SocketState state;
std::string errorMessage;
bool useTls;
bool hasTimeout;
Timer connectionTimout;
SecureSocket *p;
void d_connect();
SecureSocketPrivate(std::weak_ptr<Kite::EventLoop> ev)
: Kite::Evented(ev)
, connectionTimout(ev)
{
KITE_TIMER_DEBUG_NAME(&connectionTimout, "Kite::SecureSocketPrivate::connectionTimout");
}
virtual void onActivated (int)
{
if (state == Kite::SecureSocket::Connecting) {
d_connect();
} else if (state == Kite::SecureSocket::Connected) {
p->onActivated(0);
}
}
friend class Kite::SecureSocket;
};
void apps_ssl_info_callback(const SSL *s, int where, int ret)
{
const char *str;
int w;
w=where& ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) str="SSL_connect";
else if (w & SSL_ST_ACCEPT) str="SSL_accept";
else str="undefined";
if (where & SSL_CB_LOOP)
{
debugprintf("%s:%s\n",str,SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT)
{
str=(where & SSL_CB_READ)?"read":"write";
debugprintf("SSL3 alert %s:%s:%s\n",
str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT)
{
if (ret == 0)
debugprintf("%s:failed in %s\n",
str,SSL_state_string_long(s));
else if (ret < 0)
{
debugprintf("%s:error in %s\n",
str,SSL_state_string_long(s));
}
}
}
SecureSocket::SecureSocket(std::weak_ptr<Kite::EventLoop> ev)
: p(new SecureSocketPrivate(ev))
{
static bool sslIsInit = false;
if (!sslIsInit) {
SSL_load_error_strings();
SSL_library_init();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
}
p->p = this;
p->ssl_ctx = 0;
p->bio = 0;
p->ssl = 0;
p->state = Disconnected;
// init ssl context
p->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if (p->ssl_ctx == NULL)
{
ERR_print_errors_fp(stderr);
return;
}
SSL_CTX_set_info_callback(p->ssl_ctx, apps_ssl_info_callback);
}
SecureSocket::~SecureSocket()
{
disconnect();
if (p->bio)
BIO_free_all(p->bio);
if (p->ssl_ctx)
SSL_CTX_free(p->ssl_ctx);
delete p;
}
bool SecureSocket::setCaDir (const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, NULL, path.c_str());
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setCaFile(const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, path.c_str(), NULL);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientCertificateFile(const std::string &path)
{
int r = SSL_CTX_use_certificate_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientKeyFile(const std::string &path)
{
int r = SSL_CTX_use_PrivateKey_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
void SecureSocket::disconnect()
{
int fd = 0;
BIO_get_fd(p->bio, &fd);
if (fd != 0)
p->evRemove(fd);
if (p->ssl) {
auto e = rebind_map.find(p->ssl);
if (e != rebind_map.end())
rebind_map.erase(e);
}
if (p->bio)
BIO_ssl_shutdown(p->bio);
if (p->state == Connected || p->state == Connecting)
p->state = Disconnected;
onDisconnected(p->state);
}
void SecureSocket::connect(const std::string &hostname, int port, uint64_t timeout, bool tls)
{
p->useTls = tls;
if (timeout > 0) {
p->hasTimeout = true;
p->connectionTimout.reset(timeout);
}
p->state = Connecting;
int r = 0;
if (p->useTls) {
p->bio = BIO_new_ssl_connect(p->ssl_ctx);
} else {
std::vector<char> host_c(hostname.begin(), hostname.end());
host_c.push_back('\0');
p->bio = BIO_new_connect(&host_c[0]);
}
if (!p->bio) {
p->errorMessage = "BIO_new_ssl_connect returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
BIO_set_nbio(p->bio, 1);
if (p->useTls) {
BIO_get_ssl(p->bio, &p->ssl);
if (!(p->ssl)) {
p->errorMessage = "BIO_get_ssl returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
rebind_map.insert(std::make_pair(p->ssl, this));
auto cb = [](SSL *ssl, X509 **x509, EVP_PKEY **pkey) {
SecureSocket *that = rebind_map[ssl];
that->p->errorMessage = "Client Certificate Requested\n";
that->p->state = SecureClientCertificateRequired;
that->disconnect();
return 0;
};
SSL_CTX_set_client_cert_cb(p->ssl_ctx, cb);
SSL_set_mode(p->ssl, SSL_MODE_AUTO_RETRY);
}
BIO_set_conn_hostname(p->bio, hostname.c_str());
BIO_set_conn_int_port(p->bio, &port);
p->d_connect();
}
void SecureSocketPrivate::d_connect()
{
if (hasTimeout) {
if (connectionTimout.expires() < 1) {
errorMessage = "Connection timed out";
state = SecureSocket::TransportErrror;
p->disconnect();
return;
}
}
int r = BIO_do_connect(bio);
if (r < 1) {
if (BIO_should_retry(bio)) {
// rety imidiately.
// this seems how to do it properly, but i cant get it working:
// https://github.com/jmckaskill/bio_poll/blob/master/poll.c
// probably because BIO_get_fd is garbage before connect?
Timer::later(ev(), [this](){
d_connect();
return false;
}, 100, "BIO_should_retry");
return;
}
if (state != SecureSocket::SecureClientCertificateRequired) {
const char *em = ERR_reason_error_string(ERR_get_error());
debugprintf( "BIO_new_ssl_connect failed: %u (0x%x)\n", r, r);
debugprintf( "Error: %s\n", em);
debugprintf( "%s\n", ERR_error_string(ERR_get_error(), NULL));
if (useTls) {
debugprintf("p_ssl state: %s\n",SSL_state_string_long(ssl));
}
ERR_print_errors_fp(stderr);
errorMessage = std::string(em ? strdup(em) : "??");
state = SecureSocket::TransportErrror;
}
p->disconnect();
return;
}
if (useTls) {
auto result = SSL_get_verify_result(ssl);
if (result != X509_V_OK) {
std::stringstream str;
str << "Secure Peer Verification Errror " << result;
errorMessage = str.str();
state = SecureSocket::SecurePeerNotVerified;
p->disconnect();
return;
}
}
int fd = 0;
BIO_get_fd(bio, &fd);
if (fd == 0) {
errorMessage = "BIO_get_fd returned 0";
state = SecureSocket::SecureSetupError;
p->disconnect();
return;
}
evAdd(fd);
state = SecureSocket::Connected;
p->onConnected();
}
int SecureSocket::write(const char *data, int len)
{
if (p->state != Connected)
return 0;
int r;
do {
r = BIO_write(p->bio, data, len);
} while (r < 0 && BIO_should_retry(p->bio));
return len;
}
int SecureSocket::read (char *data, int len)
{
if (p->state != Connected)
return 0;
int e = BIO_read(p->bio, data, len);
if (e > -1)
return e;
if (BIO_should_retry(p->bio))
return -1;
return -2;
}
const std::string &SecureSocket::errorMessage() const
{
return p->errorMessage;
}
void SecureSocket::flush()
{
BIO_flush(p->bio);
}
const std::shared_ptr<EventLoop> SecureSocket::ev() const
{
return p->ev();
}
<commit_msg>Schedule activations for unread data in sockets<commit_after>#include "SecureSocket.hpp"
#include <stdio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <sstream>
#include <iostream>
#include "Timer.hpp"
using namespace Kite;
//#define debugprintf(...) fprintf(stderr, __VA_ARGS__)
#define debugprintf(...)
//TODO: not thread safe
static std::map<SSL *, SecureSocket *> rebind_map;
class Kite::SecureSocketPrivate : public Kite::Evented {
public:
SSL_CTX *ssl_ctx;
BIO *bio;
SSL *ssl; //do note delete, is a ref from bio
SecureSocket::SocketState state;
std::string errorMessage;
bool useTls;
bool hasTimeout;
Timer connectionTimout;
SecureSocket *p;
void d_connect();
SecureSocketPrivate(std::weak_ptr<Kite::EventLoop> ev)
: Kite::Evented(ev)
, connectionTimout(ev)
{
KITE_TIMER_DEBUG_NAME(&connectionTimout, "Kite::SecureSocketPrivate::connectionTimout");
}
virtual void onActivated (int)
{
if (state == Kite::SecureSocket::Connecting) {
d_connect();
} else if (state == Kite::SecureSocket::Connected) {
p->onActivated(0);
if (BIO_pending(bio)) {
Timer::later(ev(), [this](){
onActivated(0);
return false;
}, 1, "BIO_pending after read");
}
}
}
friend class Kite::SecureSocket;
};
void apps_ssl_info_callback(const SSL *s, int where, int ret)
{
const char *str;
int w;
w=where& ~SSL_ST_MASK;
if (w & SSL_ST_CONNECT) str="SSL_connect";
else if (w & SSL_ST_ACCEPT) str="SSL_accept";
else str="undefined";
if (where & SSL_CB_LOOP)
{
debugprintf("%s:%s\n",str,SSL_state_string_long(s));
}
else if (where & SSL_CB_ALERT)
{
str=(where & SSL_CB_READ)?"read":"write";
debugprintf("SSL3 alert %s:%s:%s\n",
str,
SSL_alert_type_string_long(ret),
SSL_alert_desc_string_long(ret));
}
else if (where & SSL_CB_EXIT)
{
if (ret == 0)
debugprintf("%s:failed in %s\n",
str,SSL_state_string_long(s));
else if (ret < 0)
{
debugprintf("%s:error in %s\n",
str,SSL_state_string_long(s));
}
}
}
SecureSocket::SecureSocket(std::weak_ptr<Kite::EventLoop> ev)
: p(new SecureSocketPrivate(ev))
{
static bool sslIsInit = false;
if (!sslIsInit) {
SSL_load_error_strings();
SSL_library_init();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
}
p->p = this;
p->ssl_ctx = 0;
p->bio = 0;
p->ssl = 0;
p->state = Disconnected;
// init ssl context
p->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
if (p->ssl_ctx == NULL)
{
ERR_print_errors_fp(stderr);
return;
}
SSL_CTX_set_info_callback(p->ssl_ctx, apps_ssl_info_callback);
}
SecureSocket::~SecureSocket()
{
disconnect();
if (p->bio)
BIO_free_all(p->bio);
if (p->ssl_ctx)
SSL_CTX_free(p->ssl_ctx);
delete p;
}
bool SecureSocket::setCaDir (const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, NULL, path.c_str());
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setCaFile(const std::string &path)
{
int r = SSL_CTX_load_verify_locations(p->ssl_ctx, path.c_str(), NULL);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientCertificateFile(const std::string &path)
{
int r = SSL_CTX_use_certificate_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
bool SecureSocket::setClientKeyFile(const std::string &path)
{
int r = SSL_CTX_use_PrivateKey_file(p->ssl_ctx, path.c_str(), SSL_FILETYPE_PEM);
if (r == 0) {
return false;
}
return true;
}
void SecureSocket::disconnect()
{
int fd = 0;
BIO_get_fd(p->bio, &fd);
if (fd != 0)
p->evRemove(fd);
if (p->ssl) {
auto e = rebind_map.find(p->ssl);
if (e != rebind_map.end())
rebind_map.erase(e);
}
if (p->bio)
BIO_ssl_shutdown(p->bio);
if (p->state == Connected || p->state == Connecting)
p->state = Disconnected;
onDisconnected(p->state);
}
void SecureSocket::connect(const std::string &hostname, int port, uint64_t timeout, bool tls)
{
p->useTls = tls;
if (timeout > 0) {
p->hasTimeout = true;
p->connectionTimout.reset(timeout);
}
p->state = Connecting;
int r = 0;
if (p->useTls) {
p->bio = BIO_new_ssl_connect(p->ssl_ctx);
} else {
std::vector<char> host_c(hostname.begin(), hostname.end());
host_c.push_back('\0');
p->bio = BIO_new_connect(&host_c[0]);
}
if (!p->bio) {
p->errorMessage = "BIO_new_ssl_connect returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
BIO_set_nbio(p->bio, 1);
if (p->useTls) {
BIO_get_ssl(p->bio, &p->ssl);
if (!(p->ssl)) {
p->errorMessage = "BIO_get_ssl returned NULL";
p->state = SecureSetupError;
disconnect();
return;
}
rebind_map.insert(std::make_pair(p->ssl, this));
auto cb = [](SSL *ssl, X509 **x509, EVP_PKEY **pkey) {
SecureSocket *that = rebind_map[ssl];
that->p->errorMessage = "Client Certificate Requested\n";
that->p->state = SecureClientCertificateRequired;
that->disconnect();
return 0;
};
SSL_CTX_set_client_cert_cb(p->ssl_ctx, cb);
SSL_set_mode(p->ssl, SSL_MODE_AUTO_RETRY);
}
BIO_set_conn_hostname(p->bio, hostname.c_str());
BIO_set_conn_int_port(p->bio, &port);
p->d_connect();
}
void SecureSocketPrivate::d_connect()
{
if (hasTimeout) {
if (connectionTimout.expires() < 1) {
errorMessage = "Connection timed out";
state = SecureSocket::TransportErrror;
p->disconnect();
return;
}
}
int r = BIO_do_connect(bio);
if (r < 1) {
if (BIO_should_retry(bio)) {
// rety imidiately.
// this seems how to do it properly, but i cant get it working:
// https://github.com/jmckaskill/bio_poll/blob/master/poll.c
// probably because BIO_get_fd is garbage before connect?
Timer::later(ev(), [this](){
d_connect();
return false;
}, 100, "BIO_should_retry");
return;
}
if (state != SecureSocket::SecureClientCertificateRequired) {
const char *em = ERR_reason_error_string(ERR_get_error());
debugprintf( "BIO_new_ssl_connect failed: %u (0x%x)\n", r, r);
debugprintf( "Error: %s\n", em);
debugprintf( "%s\n", ERR_error_string(ERR_get_error(), NULL));
if (useTls) {
debugprintf("p_ssl state: %s\n",SSL_state_string_long(ssl));
}
ERR_print_errors_fp(stderr);
errorMessage = std::string(em ? strdup(em) : "??");
state = SecureSocket::TransportErrror;
}
p->disconnect();
return;
}
if (useTls) {
auto result = SSL_get_verify_result(ssl);
if (result != X509_V_OK) {
std::stringstream str;
str << "Secure Peer Verification Errror " << result;
errorMessage = str.str();
state = SecureSocket::SecurePeerNotVerified;
p->disconnect();
return;
}
}
int fd = 0;
BIO_get_fd(bio, &fd);
if (fd == 0) {
errorMessage = "BIO_get_fd returned 0";
state = SecureSocket::SecureSetupError;
p->disconnect();
return;
}
evAdd(fd);
state = SecureSocket::Connected;
p->onConnected();
}
int SecureSocket::write(const char *data, int len)
{
if (p->state != Connected)
return 0;
int r;
do {
r = BIO_write(p->bio, data, len);
} while (r < 0 && BIO_should_retry(p->bio));
return len;
}
int SecureSocket::read (char *data, int len)
{
if (p->state != Connected)
return 0;
int e = BIO_read(p->bio, data, len);
if (e > -1)
return e;
if (BIO_should_retry(p->bio))
return -1;
return -2;
}
const std::string &SecureSocket::errorMessage() const
{
return p->errorMessage;
}
void SecureSocket::flush()
{
BIO_flush(p->bio);
}
const std::shared_ptr<EventLoop> SecureSocket::ev() const
{
return p->ev();
}
<|endoftext|>
|
<commit_before>/* Cycript - Optimizing JavaScript Compiler/Runtime
* Copyright (C) 2009-2013 Jay Freeman (saurik)
*/
/* GNU General Public License, Version 3 {{{ */
/*
* Cycript 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.
*
* Cycript 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 Cycript. If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */
#define _PTHREAD_ATTR_T
#include <pthread_internals.h>
#include <mach-o/dyld.h>
#include <mach-o/dyld_images.h>
#include <mach-o/loader.h>
extern "C" {
#include <mach-o/nlist.h>
}
#include "Standard.hpp"
#include "Baton.hpp"
static void $bzero(void *data, size_t size) {
char *bytes(reinterpret_cast<char *>(data));
for (size_t i(0); i != size; ++i)
bytes[i] = 0;
}
static int $strcmp(const char *lhs, const char *rhs) {
while (*lhs == *rhs) {
if (*lhs == '\0')
return 0;
++lhs, ++rhs;
} return *lhs < *rhs ? -1 : 1;
}
#ifdef __LP64__
typedef struct mach_header_64 mach_header_xx;
typedef struct nlist_64 nlist_xx;
typedef struct segment_command_64 segment_command_xx;
static const uint32_t LC_SEGMENT_XX = LC_SEGMENT_64;
static const uint32_t MH_MAGIC_XX = MH_MAGIC_64;
#else
typedef struct mach_header mach_header_xx;
typedef struct nlist nlist_xx;
typedef struct segment_command segment_command_xx;
static const uint32_t LC_SEGMENT_XX = LC_SEGMENT;
static const uint32_t MH_MAGIC_XX = MH_MAGIC;
#endif
#define forlc(command, mach, lc, type) \
if (const struct load_command *load_commands = reinterpret_cast<const struct load_command *>(mach + 1)) \
if (const struct load_command *lcp = load_commands) \
for (uint32_t i(0); i != mach->ncmds; ++i, lcp = reinterpret_cast<const struct load_command *>(reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize)) \
if ( \
lcp->cmdsize % sizeof(long) != 0 || lcp->cmdsize <= 0 || \
reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize > reinterpret_cast<const uint8_t *>(load_commands) + mach->sizeofcmds \
) \
return NULL; \
else if (lcp->cmd != lc) \
continue; \
else if (lcp->cmdsize < sizeof(type)) \
return NULL; \
else if (const type *command = reinterpret_cast<const type *>(lcp))
static void *Symbol(struct dyld_all_image_infos *infos, const char *library, const char *name) {
const dyld_image_info *info(NULL);
for (uint32_t i(0); i != infos->infoArrayCount; ++i)
if ($strcmp(infos->infoArray[i].imageFilePath, library) == 0)
info = &infos->infoArray[i];
if (info == NULL)
return NULL;
const mach_header_xx *mach(reinterpret_cast<const mach_header_xx *>(info->imageLoadAddress));
if (mach->magic != MH_MAGIC_XX)
return NULL;
const struct symtab_command *stp(NULL);
forlc (command, mach, LC_SYMTAB, struct symtab_command)
stp = command;
if (stp == NULL)
return NULL;
size_t slide(_not(size_t));
const nlist_xx *symbols(NULL);
const char *strings(NULL);
forlc (segment, mach, LC_SEGMENT_XX, segment_command_xx) {
if (segment->fileoff == 0)
slide = reinterpret_cast<size_t>(mach) - segment->vmaddr;
if (stp->symoff >= segment->fileoff && stp->symoff < segment->fileoff + segment->filesize)
symbols = reinterpret_cast<const nlist_xx *>(stp->symoff - segment->fileoff + segment->vmaddr + slide);
if (stp->stroff >= segment->fileoff && stp->stroff < segment->fileoff + segment->filesize)
strings = reinterpret_cast<const char *>(stp->stroff - segment->fileoff + segment->vmaddr + slide);
}
if (slide == _not(size_t) || symbols == NULL || strings == NULL)
return NULL;
for (size_t i(0); i != stp->nsyms; ++i) {
const nlist_xx *symbol(&symbols[i]);
if (symbol->n_un.n_strx == 0 || (symbol->n_type & N_STAB) != 0)
continue;
const char *nambuf(strings + symbol->n_un.n_strx);
if ($strcmp(name, nambuf) != 0)
continue;
uintptr_t value(symbol->n_value);
if (value == 0)
continue;
value += slide;
return reinterpret_cast<void *>(value);
}
return NULL;
}
struct Dynamic {
char *(*dlerror)();
void *(*dlsym)(void *, const char *);
};
template <typename Type_>
static _finline void dlset(Dynamic *dynamic, Type_ &function, const char *name, void *handle = RTLD_DEFAULT) {
function = reinterpret_cast<Type_>(dynamic->dlsym(handle, name));
if (function == NULL)
dynamic->dlerror();
}
template <typename Type_>
static _finline void cyset(Baton *baton, Type_ &function, const char *name, const char *library) {
struct dyld_all_image_infos *infos(reinterpret_cast<struct dyld_all_image_infos *>(baton->dyld));
function = reinterpret_cast<Type_>(Symbol(infos, library, name));
}
// XXX: where you find this needs to be relative to CoreFoundation (or something)
// XXX: this needs to check if the framework is under PrivateFrameworks instead
#define Framework(framework) \
"/System/Library/Frameworks/" #framework ".framework/" #framework
void *Routine(void *arg) {
Baton *baton(reinterpret_cast<Baton *>(arg));
Dynamic dynamic;
cyset(baton, dynamic.dlerror, "_dlerror", "/usr/lib/system/libdyld.dylib");
cyset(baton, dynamic.dlsym, "_dlsym", "/usr/lib/system/libdyld.dylib");
int (*pthread_detach)(pthread_t);
dlset(&dynamic, pthread_detach, "pthread_detach");
pthread_t (*pthread_self)();
dlset(&dynamic, pthread_self, "pthread_self");
pthread_detach(pthread_self());
void *(*dlopen)(const char *, int);
dlset(&dynamic, dlopen, "dlopen");
if (dynamic.dlsym(RTLD_DEFAULT, "JSEvaluateScript") == NULL)
dlopen(Framework(JavaScriptCore), RTLD_GLOBAL | RTLD_LAZY);
void *(*objc_getClass)(const char *);
dlset(&dynamic, objc_getClass, "objc_getClass");
if (objc_getClass("WebUndefined") == NULL)
dlopen(Framework(WebKit), RTLD_GLOBAL | RTLD_LAZY);
void *handle(dlopen(baton->library, RTLD_LAZY | RTLD_LOCAL));
if (handle == NULL) {
dynamic.dlerror();
return NULL;
}
void (*CYHandleServer)(pid_t);
dlset(&dynamic, CYHandleServer, "CYHandleServer", handle);
if (CYHandleServer == NULL) {
dynamic.dlerror();
return NULL;
}
CYHandleServer(baton->pid);
return NULL;
}
extern "C" void Start(Baton *baton) {
struct _pthread self;
$bzero(&self, sizeof(self));
void (*$__pthread_set_self)(pthread_t);
cyset(baton, $__pthread_set_self, "___pthread_set_self", "/usr/lib/system/libsystem_c.dylib");
self.tsd[0] = &self;
$__pthread_set_self(&self);
int (*$pthread_create)(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *);
cyset(baton, $pthread_create, "_pthread_create", "/usr/lib/system/libsystem_c.dylib");
pthread_t thread;
$pthread_create(&thread, NULL, &Routine, baton);
mach_port_t (*$mach_thread_self)();
cyset(baton, $mach_thread_self, "_mach_thread_self", "/usr/lib/system/libsystem_kernel.dylib");
kern_return_t (*$thread_terminate)(thread_act_t);
cyset(baton, $thread_terminate, "_thread_terminate", "/usr/lib/system/libsystem_kernel.dylib");
$thread_terminate($mach_thread_self());
}
<commit_msg>Remove obsolete attempts to support the Simulator.<commit_after>/* Cycript - Optimizing JavaScript Compiler/Runtime
* Copyright (C) 2009-2013 Jay Freeman (saurik)
*/
/* GNU General Public License, Version 3 {{{ */
/*
* Cycript 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.
*
* Cycript 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 Cycript. If not, see <http://www.gnu.org/licenses/>.
**/
/* }}} */
#define _PTHREAD_ATTR_T
#include <pthread_internals.h>
#include <mach-o/dyld.h>
#include <mach-o/dyld_images.h>
#include <mach-o/loader.h>
extern "C" {
#include <mach-o/nlist.h>
}
#include "Standard.hpp"
#include "Baton.hpp"
static void $bzero(void *data, size_t size) {
char *bytes(reinterpret_cast<char *>(data));
for (size_t i(0); i != size; ++i)
bytes[i] = 0;
}
static int $strcmp(const char *lhs, const char *rhs) {
while (*lhs == *rhs) {
if (*lhs == '\0')
return 0;
++lhs, ++rhs;
} return *lhs < *rhs ? -1 : 1;
}
#ifdef __LP64__
typedef struct mach_header_64 mach_header_xx;
typedef struct nlist_64 nlist_xx;
typedef struct segment_command_64 segment_command_xx;
static const uint32_t LC_SEGMENT_XX = LC_SEGMENT_64;
static const uint32_t MH_MAGIC_XX = MH_MAGIC_64;
#else
typedef struct mach_header mach_header_xx;
typedef struct nlist nlist_xx;
typedef struct segment_command segment_command_xx;
static const uint32_t LC_SEGMENT_XX = LC_SEGMENT;
static const uint32_t MH_MAGIC_XX = MH_MAGIC;
#endif
#define forlc(command, mach, lc, type) \
if (const struct load_command *load_commands = reinterpret_cast<const struct load_command *>(mach + 1)) \
if (const struct load_command *lcp = load_commands) \
for (uint32_t i(0); i != mach->ncmds; ++i, lcp = reinterpret_cast<const struct load_command *>(reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize)) \
if ( \
lcp->cmdsize % sizeof(long) != 0 || lcp->cmdsize <= 0 || \
reinterpret_cast<const uint8_t *>(lcp) + lcp->cmdsize > reinterpret_cast<const uint8_t *>(load_commands) + mach->sizeofcmds \
) \
return NULL; \
else if (lcp->cmd != lc) \
continue; \
else if (lcp->cmdsize < sizeof(type)) \
return NULL; \
else if (const type *command = reinterpret_cast<const type *>(lcp))
static void *Symbol(struct dyld_all_image_infos *infos, const char *library, const char *name) {
const dyld_image_info *info(NULL);
for (uint32_t i(0); i != infos->infoArrayCount; ++i)
if ($strcmp(infos->infoArray[i].imageFilePath, library) == 0)
info = &infos->infoArray[i];
if (info == NULL)
return NULL;
const mach_header_xx *mach(reinterpret_cast<const mach_header_xx *>(info->imageLoadAddress));
if (mach->magic != MH_MAGIC_XX)
return NULL;
const struct symtab_command *stp(NULL);
forlc (command, mach, LC_SYMTAB, struct symtab_command)
stp = command;
if (stp == NULL)
return NULL;
size_t slide(_not(size_t));
const nlist_xx *symbols(NULL);
const char *strings(NULL);
forlc (segment, mach, LC_SEGMENT_XX, segment_command_xx) {
if (segment->fileoff == 0)
slide = reinterpret_cast<size_t>(mach) - segment->vmaddr;
if (stp->symoff >= segment->fileoff && stp->symoff < segment->fileoff + segment->filesize)
symbols = reinterpret_cast<const nlist_xx *>(stp->symoff - segment->fileoff + segment->vmaddr + slide);
if (stp->stroff >= segment->fileoff && stp->stroff < segment->fileoff + segment->filesize)
strings = reinterpret_cast<const char *>(stp->stroff - segment->fileoff + segment->vmaddr + slide);
}
if (slide == _not(size_t) || symbols == NULL || strings == NULL)
return NULL;
for (size_t i(0); i != stp->nsyms; ++i) {
const nlist_xx *symbol(&symbols[i]);
if (symbol->n_un.n_strx == 0 || (symbol->n_type & N_STAB) != 0)
continue;
const char *nambuf(strings + symbol->n_un.n_strx);
if ($strcmp(name, nambuf) != 0)
continue;
uintptr_t value(symbol->n_value);
if (value == 0)
continue;
value += slide;
return reinterpret_cast<void *>(value);
}
return NULL;
}
struct Dynamic {
char *(*dlerror)();
void *(*dlsym)(void *, const char *);
};
template <typename Type_>
static _finline void dlset(Dynamic *dynamic, Type_ &function, const char *name, void *handle = RTLD_DEFAULT) {
function = reinterpret_cast<Type_>(dynamic->dlsym(handle, name));
if (function == NULL)
dynamic->dlerror();
}
template <typename Type_>
static _finline void cyset(Baton *baton, Type_ &function, const char *name, const char *library) {
struct dyld_all_image_infos *infos(reinterpret_cast<struct dyld_all_image_infos *>(baton->dyld));
function = reinterpret_cast<Type_>(Symbol(infos, library, name));
}
void *Routine(void *arg) {
Baton *baton(reinterpret_cast<Baton *>(arg));
Dynamic dynamic;
cyset(baton, dynamic.dlerror, "_dlerror", "/usr/lib/system/libdyld.dylib");
cyset(baton, dynamic.dlsym, "_dlsym", "/usr/lib/system/libdyld.dylib");
int (*pthread_detach)(pthread_t);
dlset(&dynamic, pthread_detach, "pthread_detach");
pthread_t (*pthread_self)();
dlset(&dynamic, pthread_self, "pthread_self");
pthread_detach(pthread_self());
void *(*dlopen)(const char *, int);
dlset(&dynamic, dlopen, "dlopen");
void *handle(dlopen(baton->library, RTLD_LAZY | RTLD_LOCAL));
if (handle == NULL) {
dynamic.dlerror();
return NULL;
}
void (*CYHandleServer)(pid_t);
dlset(&dynamic, CYHandleServer, "CYHandleServer", handle);
if (CYHandleServer == NULL) {
dynamic.dlerror();
return NULL;
}
CYHandleServer(baton->pid);
return NULL;
}
extern "C" void Start(Baton *baton) {
struct _pthread self;
$bzero(&self, sizeof(self));
void (*$__pthread_set_self)(pthread_t);
cyset(baton, $__pthread_set_self, "___pthread_set_self", "/usr/lib/system/libsystem_c.dylib");
self.tsd[0] = &self;
$__pthread_set_self(&self);
int (*$pthread_create)(pthread_t *, const pthread_attr_t *, void *(*)(void *), void *);
cyset(baton, $pthread_create, "_pthread_create", "/usr/lib/system/libsystem_c.dylib");
pthread_t thread;
$pthread_create(&thread, NULL, &Routine, baton);
mach_port_t (*$mach_thread_self)();
cyset(baton, $mach_thread_self, "_mach_thread_self", "/usr/lib/system/libsystem_kernel.dylib");
kern_return_t (*$thread_terminate)(thread_act_t);
cyset(baton, $thread_terminate, "_thread_terminate", "/usr/lib/system/libsystem_kernel.dylib");
$thread_terminate($mach_thread_self());
}
<|endoftext|>
|
<commit_before>#include <PCU.h>
#include "phBC.h"
#include <apf.h>
#include <apfMesh.h>
#include <fstream>
#include <sstream>
#include <gmi.h>
namespace ph {
BC::BC()
{
values = 0;
}
BC::~BC()
{
delete [] values;
}
bool BC::operator<(const BC& other) const
{
if (dim != other.dim)
return dim < other.dim;
return tag < other.tag;
}
static struct { const char* name; int size; } const knownSizes[4] =
{{"initial velocity", 3}
,{"comp1", 4}
,{"comp3", 4}
,{"traction vector", 3}
};
static int getSize(std::string const& name)
{
for (int i = 0; i < 4; ++i)
if (name == knownSizes[i].name)
return knownSizes[i].size;
return 1;
}
static void readBC(std::string const& line, BCs& bcs)
{
std::stringstream ss(line);
std::string name;
std::getline(ss, name, ':');
if (!bcs.fields.count(name)) {
FieldBCs fbcs;
fbcs.size = getSize(name);
bcs.fields[name] = fbcs;
}
FieldBCs& fbcs = bcs.fields[name];
BC bc;
ss >> bc.tag >> bc.dim;
bc.values = new double[fbcs.size];
for (int i = 0; i < fbcs.size; ++i)
ss >> bc.values[i];
fbcs.bcs.insert(bc);
bc.values = 0; //ownership of pointer transferred, prevent delete from here
}
void readBCs(const char* filename, BCs& bcs)
{
double t0 = MPI_Wtime();
std::ifstream file(filename);
std::string line;
while (std::getline(file, line, '\n')) {
if (line[0] == '#')
continue;
readBC(line, bcs);
}
double t1 = MPI_Wtime();
if (!PCU_Comm_Self())
printf("\"%s\" loaded in %f seconds\n", filename, t1 - t0);
}
struct KnownBC
{
const char* name;
int offset;
int bit;
void (*apply)(double* values, int* bits,
struct KnownBC const& bc, double* inval);
};
static bool applyBit2(int* bits, int bit)
{
if (bit == -1)
return true;
int mask = (1<<bit);
if (*bits & mask)
return false;
*bits |= mask;
return true;
}
static void applyBit(double*, int* bits,
KnownBC const& bc, double*)
{
applyBit2(bits, bc.bit);
}
static void applyScalar2(double* values, int* bits,
double value, int offset, int bit)
{
bool alreadySet = ! applyBit2(bits, bit);
/* only zero values override existing values */
if (( ! alreadySet) || ( ! value))
values[offset] = value;
}
static void applyScalar(double* outval, int* bits,
KnownBC const& bc, double* inval)
{
applyScalar2(outval, bits, *inval, bc.offset, bc.bit);
}
static void applyVector2(double* values, int* bits,
double* inval, int offset, int bit)
{
bool alreadySet = ! applyBit2(bits, bit);
if (alreadySet)
/* nonzero vectors cannot override */
if (inval[0] || inval[1] || inval[2])
return;
for (int i = 0; i < 3; ++i)
values[offset + i] = inval[i];
}
static void applyVector(double* outval, int* bits,
KnownBC const& bc, double* inval)
{
applyVector2(outval, bits, inval, bc.offset, bc.bit);
}
static void applySurfID(double*, int* bits,
KnownBC const&, double* inval)
{
bits[1] = *inval;
}
static KnownBC const essentialBCs[7] = {
{"density", 0, 0, applyScalar},
{"temperature", 1, 1, applyScalar},
{"pressure", 2, 2, applyScalar},
/* these conditions are too complex to be dealt with
here, see phConstraint.cc */
//{"comp1", 3, 3, applyComp1},
//{"comp3", 3, 3, applyComp3},
{"scalar_1", 12, 6, applyScalar},
{"scalar_2", 13, 7, applyScalar},
{"scalar_3", 14, 8, applyScalar},
{"scalar_4", 15, 9, applyScalar},
};
static KnownBC const naturalBCs[10] = {
{"mass flux", 0, 0, applyScalar},
{"natural pressure", 1, 1, applyScalar},
{"traction vector", 2, 2, applyVector},
{"heat flux", 5, 3, applyScalar},
{"turbulence wall", -1, 4, applyBit},
{"scalar_1 flux", 6, 5, applyScalar},
{"scalar_2 flux", 7, 6, applyScalar},
{"scalar_3 flux", 8, 7, applyScalar},
{"scalar_4 flux", 9, 8, applyScalar},
{"surf ID", -1,-1, applySurfID},
};
static KnownBC const solutionBCs[7] = {
{"initial pressure", 0,-1, applyScalar},
{"initial velocity", 1,-1, applyVector},
{"initial temperature", 4,-1, applyScalar},
{"initial scalar_1", 5,-1, applyScalar},
{"initial scalar_2", 6,-1, applyScalar},
{"initial scalar_3", 7,-1, applyScalar},
{"initial scalar_4", 8,-1, applyScalar},
};
bool hasBC(BCs& bcs, std::string const& name)
{
return bcs.fields.count(name);
}
double* getValuesOn(gmi_model* gm, FieldBCs& bcs, gmi_ent* ge)
{
BC key;
key.tag = gmi_tag(gm, ge);
key.dim = gmi_dim(gm, ge);
FieldBCs::Set::iterator it = bcs.bcs.find(key);
if (it == bcs.bcs.end())
return 0;
BC& bc = const_cast<BC&>(*it);
return bc.values;
}
/* starting from the current geometric entity,
try to find attribute (kbc) attached to
geometric entities by searching all upward
adjacencies.
we use depth first search starting from
the model entity of origin, using upward
adjacencies as graph edges.
if an attached attribute is found on an
entity, the search continues without looking
at its upward adjacencies */
static bool applyBC(gmi_model* gm, gmi_ent* ge,
FieldBCs& bcs,
KnownBC const& kbc,
double* values, int* bits)
{
double* v = getValuesOn(gm, bcs, ge);
if (v) {
kbc.apply(values, bits, kbc, v);
return true;
}
bool appliedAny = false;
gmi_set* up = gmi_adjacent(gm, ge, gmi_dim(gm, ge) + 1);
for (int i = 0; i < up->n; ++i)
if ( applyBC(gm, up->e[i], bcs, kbc, values, bits) )
appliedAny = true;
gmi_free_set(up);
return appliedAny;
}
static bool applyBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs,
KnownBC const* knownBCs,
int nKnownBCs,
double* values, int* bits)
{
bool appliedAny = false;
for (int i = 0; i < nKnownBCs; ++i) {
std::string s(knownBCs[i].name);
if ( ! hasBC(appliedBCs, s))
continue;
FieldBCs& fbcs = appliedBCs.fields[s];
if ( applyBC(gm, ge, fbcs, knownBCs[i], values, bits) )
appliedAny = true;
}
return appliedAny;
}
bool applyNaturalBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs, double* values, int* bits)
{
return applyBCs(gm, ge, appliedBCs, naturalBCs,
sizeof(naturalBCs) / sizeof(KnownBC), values, bits);
}
bool applyEssentialBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs, double* values, int* bits)
{
bool didSimple = applyBCs(gm, ge, appliedBCs, essentialBCs,
sizeof(essentialBCs) / sizeof(KnownBC), values, bits);
/* the complexity of velocity constraints is delegated to
the code in phConstraint.cc */
bool didVelocity = applyVelocityConstaints(gm, appliedBCs,
ge, values, bits);
return didSimple || didVelocity;
}
bool applySolutionBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs, double* values)
{
return applyBCs(gm, ge, appliedBCs, solutionBCs,
sizeof(solutionBCs) / sizeof(KnownBC), values, 0);
}
}
<commit_msg>Check test for the spj file<commit_after>#include <PCU.h>
#include "phBC.h"
#include <apf.h>
#include <apfMesh.h>
#include <fstream>
#include <sstream>
#include <gmi.h>
namespace ph {
BC::BC()
{
values = 0;
}
BC::~BC()
{
delete [] values;
}
bool BC::operator<(const BC& other) const
{
if (dim != other.dim)
return dim < other.dim;
return tag < other.tag;
}
static struct { const char* name; int size; } const knownSizes[4] =
{{"initial velocity", 3}
,{"comp1", 4}
,{"comp3", 4}
,{"traction vector", 3}
};
static int getSize(std::string const& name)
{
for (int i = 0; i < 4; ++i)
if (name == knownSizes[i].name)
return knownSizes[i].size;
return 1;
}
static void readBC(std::string const& line, BCs& bcs)
{
std::stringstream ss(line);
std::string name;
std::getline(ss, name, ':');
if (!bcs.fields.count(name)) {
FieldBCs fbcs;
fbcs.size = getSize(name);
bcs.fields[name] = fbcs;
}
FieldBCs& fbcs = bcs.fields[name];
BC bc;
ss >> bc.tag >> bc.dim;
bc.values = new double[fbcs.size];
for (int i = 0; i < fbcs.size; ++i)
ss >> bc.values[i];
fbcs.bcs.insert(bc);
bc.values = 0; //ownership of pointer transferred, prevent delete from here
}
void readBCs(const char* filename, BCs& bcs)
{
double t0 = MPI_Wtime();
std::ifstream file(filename);
assert(file.is_open()); //check if the spj file could be opened successfully
std::string line;
while (std::getline(file, line, '\n')) {
if (line[0] == '#')
continue;
readBC(line, bcs);
}
double t1 = MPI_Wtime();
if (!PCU_Comm_Self())
printf("\"%s\" loaded in %f seconds\n", filename, t1 - t0);
}
struct KnownBC
{
const char* name;
int offset;
int bit;
void (*apply)(double* values, int* bits,
struct KnownBC const& bc, double* inval);
};
static bool applyBit2(int* bits, int bit)
{
if (bit == -1)
return true;
int mask = (1<<bit);
if (*bits & mask)
return false;
*bits |= mask;
return true;
}
static void applyBit(double*, int* bits,
KnownBC const& bc, double*)
{
applyBit2(bits, bc.bit);
}
static void applyScalar2(double* values, int* bits,
double value, int offset, int bit)
{
bool alreadySet = ! applyBit2(bits, bit);
/* only zero values override existing values */
if (( ! alreadySet) || ( ! value))
values[offset] = value;
}
static void applyScalar(double* outval, int* bits,
KnownBC const& bc, double* inval)
{
applyScalar2(outval, bits, *inval, bc.offset, bc.bit);
}
static void applyVector2(double* values, int* bits,
double* inval, int offset, int bit)
{
bool alreadySet = ! applyBit2(bits, bit);
if (alreadySet)
/* nonzero vectors cannot override */
if (inval[0] || inval[1] || inval[2])
return;
for (int i = 0; i < 3; ++i)
values[offset + i] = inval[i];
}
static void applyVector(double* outval, int* bits,
KnownBC const& bc, double* inval)
{
applyVector2(outval, bits, inval, bc.offset, bc.bit);
}
static void applySurfID(double*, int* bits,
KnownBC const&, double* inval)
{
bits[1] = *inval;
}
static KnownBC const essentialBCs[7] = {
{"density", 0, 0, applyScalar},
{"temperature", 1, 1, applyScalar},
{"pressure", 2, 2, applyScalar},
/* these conditions are too complex to be dealt with
here, see phConstraint.cc */
//{"comp1", 3, 3, applyComp1},
//{"comp3", 3, 3, applyComp3},
{"scalar_1", 12, 6, applyScalar},
{"scalar_2", 13, 7, applyScalar},
{"scalar_3", 14, 8, applyScalar},
{"scalar_4", 15, 9, applyScalar},
};
static KnownBC const naturalBCs[10] = {
{"mass flux", 0, 0, applyScalar},
{"natural pressure", 1, 1, applyScalar},
{"traction vector", 2, 2, applyVector},
{"heat flux", 5, 3, applyScalar},
{"turbulence wall", -1, 4, applyBit},
{"scalar_1 flux", 6, 5, applyScalar},
{"scalar_2 flux", 7, 6, applyScalar},
{"scalar_3 flux", 8, 7, applyScalar},
{"scalar_4 flux", 9, 8, applyScalar},
{"surf ID", -1,-1, applySurfID},
};
static KnownBC const solutionBCs[7] = {
{"initial pressure", 0,-1, applyScalar},
{"initial velocity", 1,-1, applyVector},
{"initial temperature", 4,-1, applyScalar},
{"initial scalar_1", 5,-1, applyScalar},
{"initial scalar_2", 6,-1, applyScalar},
{"initial scalar_3", 7,-1, applyScalar},
{"initial scalar_4", 8,-1, applyScalar},
};
bool hasBC(BCs& bcs, std::string const& name)
{
return bcs.fields.count(name);
}
double* getValuesOn(gmi_model* gm, FieldBCs& bcs, gmi_ent* ge)
{
BC key;
key.tag = gmi_tag(gm, ge);
key.dim = gmi_dim(gm, ge);
FieldBCs::Set::iterator it = bcs.bcs.find(key);
if (it == bcs.bcs.end())
return 0;
BC& bc = const_cast<BC&>(*it);
return bc.values;
}
/* starting from the current geometric entity,
try to find attribute (kbc) attached to
geometric entities by searching all upward
adjacencies.
we use depth first search starting from
the model entity of origin, using upward
adjacencies as graph edges.
if an attached attribute is found on an
entity, the search continues without looking
at its upward adjacencies */
static bool applyBC(gmi_model* gm, gmi_ent* ge,
FieldBCs& bcs,
KnownBC const& kbc,
double* values, int* bits)
{
double* v = getValuesOn(gm, bcs, ge);
if (v) {
kbc.apply(values, bits, kbc, v);
return true;
}
bool appliedAny = false;
gmi_set* up = gmi_adjacent(gm, ge, gmi_dim(gm, ge) + 1);
for (int i = 0; i < up->n; ++i)
if ( applyBC(gm, up->e[i], bcs, kbc, values, bits) )
appliedAny = true;
gmi_free_set(up);
return appliedAny;
}
static bool applyBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs,
KnownBC const* knownBCs,
int nKnownBCs,
double* values, int* bits)
{
bool appliedAny = false;
for (int i = 0; i < nKnownBCs; ++i) {
std::string s(knownBCs[i].name);
if ( ! hasBC(appliedBCs, s))
continue;
FieldBCs& fbcs = appliedBCs.fields[s];
if ( applyBC(gm, ge, fbcs, knownBCs[i], values, bits) )
appliedAny = true;
}
return appliedAny;
}
bool applyNaturalBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs, double* values, int* bits)
{
return applyBCs(gm, ge, appliedBCs, naturalBCs,
sizeof(naturalBCs) / sizeof(KnownBC), values, bits);
}
bool applyEssentialBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs, double* values, int* bits)
{
bool didSimple = applyBCs(gm, ge, appliedBCs, essentialBCs,
sizeof(essentialBCs) / sizeof(KnownBC), values, bits);
/* the complexity of velocity constraints is delegated to
the code in phConstraint.cc */
bool didVelocity = applyVelocityConstaints(gm, appliedBCs,
ge, values, bits);
return didSimple || didVelocity;
}
bool applySolutionBCs(gmi_model* gm, gmi_ent* ge,
BCs& appliedBCs, double* values)
{
return applyBCs(gm, ge, appliedBCs, solutionBCs,
sizeof(solutionBCs) / sizeof(KnownBC), values, 0);
}
}
<|endoftext|>
|
<commit_before>#include "geom.hpp"
#include "plat2d.hpp"
#include "../utils/utils.hpp"
#include <SDL/SDL.h>
#include <unistd.h> // sleep()
#include <vector>
#include <cstdlib>
#include <cerrno>
enum {
Width = 640,
Height = 480,
};
static unsigned int frametime = 20;
static unsigned int echo = false;
static int nextctrl = -1;
static std::vector<unsigned int> controls;
SDL_Surface *screen;
Point tr(0, 0);
static void parseargs(int, const char*[]);
static void helpmsg(int);
static Lvl *getlvl(void);
static void handlepair(const char*, const char*, void*);
static void initsdl(void);
static unsigned int keys(void);
static unsigned int sdlkeys(void);
static void scroll(const Point&, const Point&);
static void draw(const Lvl&, const Player&);
static void drawlvl(unsigned int z, const Lvl&);
static void drawplayer(const Player&);
static void clear(void);
static void fillrect(SDL_Rect*, Color);
int main(int argc, const char *argv[]) {
parseargs(argc, argv);
Lvl *lvl = getlvl();
initsdl();
Player p(2 * Tile::Width + Player::Offx, 2 * Tile::Height + Player::Offy,
0, Player::Width, Player::Height);
for ( ; ; ) {
unsigned int next = SDL_GetTicks() + frametime;
draw(*lvl, p);
Point l0(p.loc());
p.act(*lvl, keys());
scroll(l0, p.loc());
SDL_PumpEvents();
while (SDL_GetTicks() < next)
;
}
delete lvl;
return 0;
}
static void parseargs(int argc, const char *argv[]) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0)
helpmsg(0);
else if (i < argc - 1 && strcmp(argv[i], "-t") == 0)
frametime = strtol(argv[++i], NULL, 10);
else if (strcmp(argv[i], "-e") == 0)
echo = true;
else {
printf("Unknown option %s\n", argv[i]);
helpmsg(1);
}
}
}
static void helpmsg(int res) {
puts("Usage: play <options>");
puts("Options:");
puts("-h display this help message");
puts("-e echo the input back to the output if the input is a datafile");
puts("-t <num> sets the frame time in milliseconds");
exit(res);
}
static Lvl *getlvl(void) {
int c = fgetc(stdin);
if (c == EOF)
return NULL;
ungetc(c, stdin);
if (c != '#')
return new Lvl(stdin);
char *path = NULL;
dfreadpairs(stdin, handlepair, &path, echo);
if (!path)
fatal("No level key found");
FILE *f = fopen(path, "r");
if (!f)
fatalx(errno, "Failed to open %s for reading", path);
Lvl *lvl = new Lvl(f);
fclose(f);
return lvl;
}
static void handlepair(const char *key, const char *val, void *_pathp) {
if (strcmp(key, "level") == 0) {
char **pathp = (char**) _pathp;
unsigned int sz = sizeof(val[0]) * (strlen(val) + 1);
*pathp = (char*) malloc(sz);
memcpy(*pathp, val, sz);
} else if (strcmp(key, "controls") == 0) {
nextctrl = 0;
controls = controlvec(val);
}
}
static void initsdl(void) {
if (SDL_Init(SDL_INIT_VIDEO) < 0)
fatal("Failed to init SDL: %s\n", SDL_GetError());
unsigned int flags = SDL_HWSURFACE | SDL_DOUBLEBUF;
screen = SDL_SetVideoMode(Width, Height, 0, flags);
if (!screen)
fatal("Failed to set video mode: %s\n", SDL_GetError());
SDL_WM_SetCaption("play", "play");
}
static unsigned int keys(void) {
if (nextctrl < 0)
return sdlkeys();
if (nextctrl >= (int) controls.size())
exit(0);
return controls[nextctrl++];
}
#if SDLVER == 13
static unsigned int sdlkeys(void) {
int nkeys;
const Uint8 *state = SDL_GetKeyboardState(&nkeys);
unsigned int keys = 0;
if (state[SDL_SCANCODE_LEFT])
keys |= Player::Left;
if (state[SDL_SCANCODE_RIGHT])
keys |= Player::Right;
if (state[SDL_SCANCODE_UP])
keys |= Player::Jump;
if (state[SDL_SCANCODE_SPACE])
keys |= Player::Act;
if (state[SDL_SCANCODE_Q])
exit(0);
return keys;
}
#else
static unsigned int sdlkeys(void) {
int nkeys;
const Uint8 *state = SDL_GetKeyState(&nkeys);
unsigned int keys = 0;
if (state[SDLK_LEFT])
keys |= Player::Left;
if (state[SDLK_RIGHT])
keys |= Player::Right;
if (state[SDLK_UP])
keys |= Player::Jump;
if (state[SDLK_SPACE])
keys |= Player::Act;
if (state[SDLK_q])
exit(0);
return keys;
}
#endif
static void scroll(const Point &l0, const Point &l1) {
Point delta(l1.x - l0.x, l1.y - l0.y);
if ((delta.x > 0 && l1.x + tr.x > Width * 0.75) ||
(delta.x < 0 && l1.x + tr.x < Width * 0.25))
tr.x -= delta.x;
if ((delta.y > 0 && l1.y + tr.y > Height * 0.75) ||
(delta.y < 0 && l1.y + tr.y < Height * 0.25))
tr.y -= delta.y;
}
static void draw(const Lvl &lvl, const Player &p) {
clear();
drawlvl(p.z(), lvl);
drawplayer(p);
SDL_Flip(screen);
}
static void drawlvl(unsigned int z, const Lvl &lvl) {
for (unsigned int x = 0; x < lvl.width(); x++) {
for (unsigned int y = 0; y < lvl.height(); y++) {
Lvl::Blkinfo bi(lvl.at(x, y, z));
SDL_Rect r;
r.w = Tile::Width;
r.h = Tile::Height;
r.x = x * Tile::Width + tr.x;
r.y = y * Tile::Height + tr.y;
if (bi.tile.flags & Tile::Collide)
fillrect(&r, Image::black);
else if (bi.tile.flags & Tile::Water)
fillrect(&r, Image::blue);
else if (bi.tile.flags & Tile::Down)
fillrect(&r, Image::red);
}
}
}
static void drawplayer(const Player &p) {
SDL_Rect r;
Rect bbox(p.bbox());
r.w = bbox.b.x - bbox.a.x;
r.h = bbox.b.y - bbox.a.y;
r.x = bbox.a.x + tr.x;
r.y = bbox.a.y + tr.y;
fillrect(&r, Image::green);
}
static void clear(void) {
SDL_Rect r;
r.x = r.y = 0;
r.w = Width;
r.h = Height;
fillrect(&r, Image::white);
}
static void fillrect(SDL_Rect *rect, Color color) {
unsigned char r = color.getred255();
unsigned char g = color.getgreen255();
unsigned char b = color.getblue255();
SDL_FillRect(screen, rect, SDL_MapRGB(screen->format, b, g, r));
}<commit_msg>plat2d: play can display paths from searches. Just pipe the datafile into play and if it has a level key and a control key then it will play it.<commit_after>#include "geom.hpp"
#include "plat2d.hpp"
#include "../utils/utils.hpp"
#include <SDL/SDL.h>
#include <unistd.h> // sleep()
#include <vector>
#include <cstdlib>
#include <cerrno>
enum {
Width = 640,
Height = 480,
};
static unsigned int frametime = 20;
static unsigned int echo = false;
static int nextctrl = -1;
static std::vector<unsigned int> controls;
SDL_Surface *screen;
Point tr(0, 0);
static void parseargs(int, const char*[]);
static void helpmsg(int);
static Lvl *getlvl(void);
static void handlepair(const char*, const char*, void*);
static void initsdl(void);
static unsigned int keys(void);
static unsigned int sdlkeys(void);
static void scroll(const Point&, const Point&);
static void draw(const Lvl&, const Player&);
static void drawlvl(unsigned int, const Lvl&);
static void drawplayer(const Player&);
static void clear(void);
static void fillrect(SDL_Rect*, Color);
int main(int argc, const char *argv[]) {
parseargs(argc, argv);
Lvl *lvl = getlvl();
initsdl();
Player p(2 * Tile::Width + Player::Offx, 2 * Tile::Height + Player::Offy,
0, Player::Width, Player::Height);
for ( ; ; ) {
unsigned int next = SDL_GetTicks() + frametime;
draw(*lvl, p);
Point l0(p.loc());
p.act(*lvl, keys());
scroll(l0, p.loc());
SDL_PumpEvents();
while (SDL_GetTicks() < next)
;
}
delete lvl;
return 0;
}
static void parseargs(int argc, const char *argv[]) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "-h") == 0)
helpmsg(0);
else if (i < argc - 1 && strcmp(argv[i], "-t") == 0)
frametime = strtol(argv[++i], NULL, 10);
else if (strcmp(argv[i], "-e") == 0)
echo = true;
else {
printf("Unknown option %s\n", argv[i]);
helpmsg(1);
}
}
}
static void helpmsg(int res) {
puts("Usage: play <options>");
puts("Options:");
puts("-h display this help message");
puts("-e echo the input back to the output if the input is a datafile");
puts("-t <num> sets the frame time in milliseconds");
exit(res);
}
static Lvl *getlvl(void) {
int c = fgetc(stdin);
if (c == EOF)
return NULL;
ungetc(c, stdin);
if (c != '#')
return new Lvl(stdin);
char *path = NULL;
dfreadpairs(stdin, handlepair, &path, echo);
if (!path)
fatal("No level key found");
FILE *f = fopen(path, "r");
if (!f)
fatalx(errno, "Failed to open %s for reading", path);
Lvl *lvl = new Lvl(f);
fclose(f);
return lvl;
}
static void handlepair(const char *key, const char *val, void *_pathp) {
if (strcmp(key, "level") == 0) {
char **pathp = (char**) _pathp;
unsigned int sz = sizeof(val[0]) * (strlen(val) + 1);
*pathp = (char*) malloc(sz);
memcpy(*pathp, val, sz);
} else if (strcmp(key, "controls") == 0) {
nextctrl = 0;
controls = controlvec(val);
}
}
static void initsdl(void) {
if (SDL_Init(SDL_INIT_VIDEO) < 0)
fatal("Failed to init SDL: %s\n", SDL_GetError());
unsigned int flags = SDL_HWSURFACE | SDL_DOUBLEBUF;
screen = SDL_SetVideoMode(Width, Height, 0, flags);
if (!screen)
fatal("Failed to set video mode: %s\n", SDL_GetError());
SDL_WM_SetCaption("play", "play");
}
static unsigned int keys(void) {
if (nextctrl < 0)
return sdlkeys();
if (nextctrl >= (int) controls.size()) {
SDL_Delay(1000);
exit(0);
}
return controls[nextctrl++];
}
#if SDLVER == 13
static unsigned int sdlkeys(void) {
int nkeys;
const Uint8 *state = SDL_GetKeyboardState(&nkeys);
unsigned int keys = 0;
if (state[SDL_SCANCODE_LEFT])
keys |= Player::Left;
if (state[SDL_SCANCODE_RIGHT])
keys |= Player::Right;
if (state[SDL_SCANCODE_UP])
keys |= Player::Jump;
if (state[SDL_SCANCODE_SPACE])
keys |= Player::Act;
if (state[SDL_SCANCODE_Q])
exit(0);
return keys;
}
#else
static unsigned int sdlkeys(void) {
int nkeys;
const Uint8 *state = SDL_GetKeyState(&nkeys);
unsigned int keys = 0;
if (state[SDLK_LEFT])
keys |= Player::Left;
if (state[SDLK_RIGHT])
keys |= Player::Right;
if (state[SDLK_UP])
keys |= Player::Jump;
if (state[SDLK_SPACE])
keys |= Player::Act;
if (state[SDLK_q])
exit(0);
return keys;
}
#endif
static void scroll(const Point &l0, const Point &l1) {
Point delta(l1.x - l0.x, l1.y - l0.y);
if ((delta.x > 0 && l1.x + tr.x > Width * 0.75) ||
(delta.x < 0 && l1.x + tr.x < Width * 0.25))
tr.x -= delta.x;
if ((delta.y > 0 && l1.y + tr.y > Height * 0.75) ||
(delta.y < 0 && l1.y + tr.y < Height * 0.25))
tr.y -= delta.y;
}
static void draw(const Lvl &lvl, const Player &p) {
clear();
drawlvl(p.z(), lvl);
drawplayer(p);
SDL_Flip(screen);
}
static void drawlvl(unsigned int z, const Lvl &lvl) {
for (unsigned int x = 0; x < lvl.width(); x++) {
for (unsigned int y = 0; y < lvl.height(); y++) {
Lvl::Blkinfo bi(lvl.at(x, y, z));
SDL_Rect r;
r.w = Tile::Width;
r.h = Tile::Height;
r.x = x * Tile::Width + tr.x;
r.y = y * Tile::Height + tr.y;
if (bi.tile.flags & Tile::Collide)
fillrect(&r, Image::black);
else if (bi.tile.flags & Tile::Water)
fillrect(&r, Image::blue);
else if (bi.tile.flags & Tile::Down)
fillrect(&r, Image::red);
}
}
}
static void drawplayer(const Player &p) {
SDL_Rect r;
Rect bbox(p.bbox());
r.w = bbox.b.x - bbox.a.x;
r.h = bbox.b.y - bbox.a.y;
r.x = bbox.a.x + tr.x;
r.y = bbox.a.y + tr.y;
fillrect(&r, Image::green);
}
static void clear(void) {
SDL_Rect r;
r.x = r.y = 0;
r.w = Width;
r.h = Height;
fillrect(&r, Image::white);
}
static void fillrect(SDL_Rect *rect, Color color) {
unsigned char r = color.getred255();
unsigned char g = color.getgreen255();
unsigned char b = color.getblue255();
SDL_FillRect(screen, rect, SDL_MapRGB(screen->format, b, g, r));
}<|endoftext|>
|
<commit_before>//---------------------------------------------------------------------------
//
// kPPP: A pppd front end for the KDE project
//
//---------------------------------------------------------------------------
//
// (c) 1997-1998 Bernd Johannes Wuebben <wuebben@kde.org>
// (c) 1997-1999 Mario Weilguni <mweilguni@kde.org>
// (c) 1998-1999 Harri Porten <porten@kde.org>
//
// derived from Jay Painters "ezppp"
//
//---------------------------------------------------------------------------
//
// $Id$
//
//---------------------------------------------------------------------------
//
// This program 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 program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//---------------------------------------------------------------------------
#include <qdir.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlistbox.h>
#include <kwm.h>
#include <qregexp.h>
#include <kapp.h>
#include <qlineedit.h>
#include "providerdb.h"
#include "newwidget.h"
#include "pppdata.h"
#include "log.h"
#define UNENCODED_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
ProviderDB::ProviderDB(QWidget *parent) :
KWizard(parent, 0, true),
cfg(0)
{
KWM::setMiniIcon(winId(), kapp->getMiniIcon());
setCaption(i18n("Create new account..."));
KWizardPage *p1 = new KWizardPage;
page1 = new PDB_Intro(this);
p1->w = page1;
addPage(p1);
p1->w->setFocusPolicy(StrongFocus);
KWizardPage *p2 = new KWizardPage;
page2 = new PDB_Country(this);
p2->w = page2;
addPage(p2);
KWizardPage *p3 = new KWizardPage;
page3 = new PDB_Provider(this);
p3->w = page3;
addPage(p3);
KWizardPage *p4 = new KWizardPage;
page4 = new PDB_UserInfo(this);
p4->w = page4;
addPage(p4);
KWizardPage *p5 = new KWizardPage;
page5 = new PDB_DialPrefix(this);
p5->w = page5;
addPage(p5);
KWizardPage *p9 = new KWizardPage;
page9 = new PDB_Finished(this);
p9->w = page9;
addPage(p9);
connect(this, SIGNAL(selected(int)),
this, SLOT(pageSelected(int)));
connect(this, SIGNAL(cancelclicked()),
this, SLOT(reject()));
setCancelButton();
setOkButton();
setHelpButton();
getOkButton()->setEnabled(false);
connect(getOkButton(), SIGNAL(clicked()),
this, SLOT(accept()));
connect(getCancelButton(), SIGNAL(clicked()),
this, SLOT(reject()));
resize(minimumSize());
}
ProviderDB::~ProviderDB() {
if(cfg)
delete cfg;
}
void ProviderDB::pageSelected(int idx) {
bool prev = true;
bool next = true;
int nextPage = idx;
switch(idx+1) {
case 1:
break;
case 2:
next = page2->lb->currentItem() != -1;
break;
case 3:
page3->setDir(page2->lb->text(page2->lb->currentItem()));
next = page3->lb->currentItem() != -1;
break;
case 4:
loadProviderInfo();
next = page4->username().length() > 0 &&
page4->password().length() > 0;
page4->activate();
break;
case 5:
page5->activate();
break;
case 6:
getOkButton()->setEnabled(true);
prev = false;
break;
}
getPreviousButton()->setEnabled(prev);
getNextButton()->setEnabled(next);
if(idx != nextPage)
gotoPage(nextPage);
}
void ProviderDB::loadProviderInfo() {
if(cfg)
delete cfg;
QRegExp re(" ");
QString loc = page2->lb->text(page2->lb->currentItem());
loc = loc.replace(re, "_");
QString provider = page3->lb->text(page3->lb->currentItem());
urlEncode(provider);
QString fname = kapp->kde_datadir();
fname += "/kppp/Provider/" + loc;
fname += "/" + provider;
Debug("Providerfile=%s\n", fname.data());
cfg = new KSimpleConfig(fname, true);
}
void ProviderDB::accept() {
QRegExp re_username("%USERNAME%");
QRegExp re_password("%PASSWORD%");
KEntryIterator *it = cfg->entryIterator("<Default>");
while(it->current() != 0) {
QString key = it->currentKey();
QString value = it->current()->aValue;
if(value.contains(re_username))
value.replace(re_username, page4->username());
if(value.contains(re_password))
value.replace(re_password, page4->password());
gpppdata.writeConfig(gpppdata.currentGroup(),
key.data(),
value.data());
if(key == "Name")
gpppdata.setAccname(value);
++(*it);
}
gpppdata.writeConfig(gpppdata.currentGroup(), "DialPrefix", page5->prefix());
done(Accepted);
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Intro::PDB_Intro(QWidget *parent) : QWidget(parent) {
QLabel *l = new QLabel(i18n("You will be asked a few questions on informations\n"
"which are needed to establish an Internet connection\n"
"with your Internet Service Provider (ISP).\n\n"
"Make sure you have the registration form from your\n"
"ISP handy. If you have any problems, try the online\n"
"help first. If any information is missing, contact\n"
"your ISP."),
this);
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
tl->addWidget(l);
tl->activate();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Country::PDB_Country(QWidget *parent) : QWidget(parent) {
QLabel *l = new QLabel(i18n("Select the location where you plan to use this\n"
"account from the list below. If your country or\n"
"location is not listed, you have to create the\n"
"account with the normal, dialog based setup.\n\n"
"If you hit \"Cancel\", the dialog based setup\n"
"will start."),
this);
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
tl->addWidget(l);
QHBoxLayout *l1 = new QHBoxLayout;
tl->addLayout(l1);
l1->addStretch(1);
lb = new QListBox(this);
connect(lb, SIGNAL(highlighted(int)),
this, SLOT(selectionChanged(int)));
lb->setMinimumSize(220, 100);
l1->addWidget(lb, 2);
l1->addStretch(1);
// fill the listbox
// set up filter
QDir d(kapp->kde_datadir() + "/kppp/Provider/");
d.setFilter(QDir::Dirs);
d.setSorting(QDir::Name);
// read the list of files
const QFileInfoList *list = d.entryInfoList();
if(list) {
QFileInfoListIterator it( *list );
QFileInfo *fi;
// traverse the list and insert into the widget
QRegExp re("_");
while((fi = it.current()) != NULL) {
QString fname = fi->fileName();
if(fname.length() && fname[0] != '.') {
fname = fname.replace(re, " ");
lb->insertItem(fname);
}
++it;
}
}
tl->activate();
}
void PDB_Country::selectionChanged(int idx) {
KWizard *w = (KWizard *)parent();
w->getNextButton()->setEnabled(idx != -1);
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Provider::PDB_Provider(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("Select your Internet Service Provider (ISP) from\n"
"the list below. If the ISP is not in this list,\n"
"you have to click on \"Cancel\" and create this\n"
"account using the normal, dialog-based setup.\n\n"
"Click on \"Next\" when you have finished your\n"
"selection."), this);
tl->addWidget(l);
QHBoxLayout *l1 = new QHBoxLayout;
tl->addLayout(l1);
l1->addStretch(1);
lb = new QListBox(this);
connect(lb, SIGNAL(highlighted(int)),
this, SLOT(selectionChanged(int)));
lb->setMinimumSize(220, 100);
l1->addWidget(lb, 2);
l1->addStretch(1);
}
void PDB_Provider::selectionChanged(int idx) {
KWizard *w = (KWizard *)parent();
w->getNextButton()->setEnabled(idx != -1);
}
void PDB_Provider::setDir(const char *_dir) {
if(dir != _dir) {
lb->clear();
// fill the listbox
// set up filter
dir = _dir;
QString dir1 = kapp->kde_datadir();
dir1 += "/kppp/Provider/";
QRegExp re1(" ");
dir = dir.replace(re1, "_");
dir1 += dir;
QDir d(dir1);
d.setFilter(QDir::Files);
d.setSorting(QDir::Name);
// read the list of files
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
// traverse the list and insert into the widget
QRegExp re("_");
while((fi = it.current()) != NULL) {
QString fname = fi->fileName();
if(fname.length() && fname[0] != '.') {
urlDecode(fname);
lb->insertItem(fname);
}
++it;
}
// TODO: Qt 1.x needs this if list is empty
lb->update();
}
}
const char *PDB_Provider::getDir() {
return dir.data();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_UserInfo::PDB_UserInfo(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("To log on to your ISP, kppp needs the username\n"
"and the password you got from your ISP. Type\n"
"in this information in the fields below.\n\n"
"Word case is important here."),
this);
tl->addWidget(l);
QGridLayout *l1 = new QGridLayout(2, 2);
tl->addLayout(l1);
l = new QLabel(i18n("Username:"), this);
l1->addWidget(l, 0, 0);
l = new QLabel(i18n("Password:"), this);
l1->addWidget(l, 1, 0);
_username = newLineEdit(24, this);
connect(_username, SIGNAL(textChanged(const QString &)),
this, SLOT(textChanged(const QString &)));
l1->addWidget(_username, 0, 1);
_password = newLineEdit(24, this);
_password->setEchoMode(QLineEdit::Password);
connect(_password, SIGNAL(textChanged(const QString &)),
this, SLOT(textChanged(const QString &)));
l1->addWidget(_password, 1, 1);
tl->activate();
};
void PDB_UserInfo::textChanged(const QString &) {
KWizard *w = (KWizard*)parent();
w->getNextButton()->setEnabled(strlen(_password->text()) > 0 &&
strlen(_username->text()) > 0);
}
QString PDB_UserInfo::username() {
QString s = _username->text();
return s;
}
QString PDB_UserInfo::password() {
QString s = _password->text();
return s;
}
void PDB_UserInfo::activate() {
_username->setFocus();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_DialPrefix::PDB_DialPrefix(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("If you need a special dial prefix (e.g. if you\n"
"are using a telephone switch) you can specify\n"
"this here. This prefix is dialed just before the\n"
"phone number.\n\n"
"If you have a telephone switch, you probly need\n"
"to write \"0\" or \"0,\" here."),
this);
tl->addWidget(l);
QGridLayout *l1 = new QGridLayout(1, 2);
tl->addLayout(l1);
l = new QLabel(i18n("Dial prefix:"), this);
l1->addWidget(l, 0, 0);
_prefix = newLineEdit(24, this);
l1->addWidget(_prefix, 0, 1);
tl->activate();
}
QString PDB_DialPrefix::prefix() {
QString s = _prefix->text();
return s;
}
void PDB_DialPrefix::activate() {
_prefix->setFocus();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Finished::PDB_Finished(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("Finished!\n\n"
"A new account has been created. Hit \"OK\" to\n"
"go back to the setup dialog. If you want to\n"
"check the settings of the newly created account,\n"
"you can use \"Edit\" in the setup dialog."),
this);
tl->addWidget(l);
tl->addStretch(1);
};
void urlDecode(QString &s) {
QString s1;
int i = 0;
while(s[i]) {
if(s[i] == '%') {
s1 += 100*(s[i+1]-'0') + 10*(s[i+2]-'0') + (s[i+3]-'0');
i += 4;
} else {
s1 += s[i];
i++;
}
}
s = s1;
}
void urlEncode(QString &s) {
QString s1;
for(uint i = 0; i < s.length(); i++) {
if(strchr(UNENCODED_CHARS, s[i]))
s1 += s[i];
else {
unsigned char ch=(unsigned char)s[i];
s1 += "%";
s1 += ch / 100 + '0';
s1 += (ch / 10)%10 + '0';
s1 += ch % 10 + '0';
}
}
s = s1;
}
#include "providerdb.moc"
<commit_msg>fixed compilation with latest QCharRef<commit_after>//---------------------------------------------------------------------------
//
// kPPP: A pppd front end for the KDE project
//
//---------------------------------------------------------------------------
//
// (c) 1997-1998 Bernd Johannes Wuebben <wuebben@kde.org>
// (c) 1997-1999 Mario Weilguni <mweilguni@kde.org>
// (c) 1998-1999 Harri Porten <porten@kde.org>
//
// derived from Jay Painters "ezppp"
//
//---------------------------------------------------------------------------
//
// $Id$
//
//---------------------------------------------------------------------------
//
// This program 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 program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this program; if not, write to the Free
// Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//---------------------------------------------------------------------------
#include <qdir.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qlistbox.h>
#include <kwm.h>
#include <qregexp.h>
#include <kapp.h>
#include <qlineedit.h>
#include "providerdb.h"
#include "newwidget.h"
#include "pppdata.h"
#include "log.h"
#define UNENCODED_CHARS "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"
ProviderDB::ProviderDB(QWidget *parent) :
KWizard(parent, 0, true),
cfg(0)
{
KWM::setMiniIcon(winId(), kapp->getMiniIcon());
setCaption(i18n("Create new account..."));
KWizardPage *p1 = new KWizardPage;
page1 = new PDB_Intro(this);
p1->w = page1;
addPage(p1);
p1->w->setFocusPolicy(StrongFocus);
KWizardPage *p2 = new KWizardPage;
page2 = new PDB_Country(this);
p2->w = page2;
addPage(p2);
KWizardPage *p3 = new KWizardPage;
page3 = new PDB_Provider(this);
p3->w = page3;
addPage(p3);
KWizardPage *p4 = new KWizardPage;
page4 = new PDB_UserInfo(this);
p4->w = page4;
addPage(p4);
KWizardPage *p5 = new KWizardPage;
page5 = new PDB_DialPrefix(this);
p5->w = page5;
addPage(p5);
KWizardPage *p9 = new KWizardPage;
page9 = new PDB_Finished(this);
p9->w = page9;
addPage(p9);
connect(this, SIGNAL(selected(int)),
this, SLOT(pageSelected(int)));
connect(this, SIGNAL(cancelclicked()),
this, SLOT(reject()));
setCancelButton();
setOkButton();
setHelpButton();
getOkButton()->setEnabled(false);
connect(getOkButton(), SIGNAL(clicked()),
this, SLOT(accept()));
connect(getCancelButton(), SIGNAL(clicked()),
this, SLOT(reject()));
resize(minimumSize());
}
ProviderDB::~ProviderDB() {
if(cfg)
delete cfg;
}
void ProviderDB::pageSelected(int idx) {
bool prev = true;
bool next = true;
int nextPage = idx;
switch(idx+1) {
case 1:
break;
case 2:
next = page2->lb->currentItem() != -1;
break;
case 3:
page3->setDir(page2->lb->text(page2->lb->currentItem()));
next = page3->lb->currentItem() != -1;
break;
case 4:
loadProviderInfo();
next = page4->username().length() > 0 &&
page4->password().length() > 0;
page4->activate();
break;
case 5:
page5->activate();
break;
case 6:
getOkButton()->setEnabled(true);
prev = false;
break;
}
getPreviousButton()->setEnabled(prev);
getNextButton()->setEnabled(next);
if(idx != nextPage)
gotoPage(nextPage);
}
void ProviderDB::loadProviderInfo() {
if(cfg)
delete cfg;
QRegExp re(" ");
QString loc = page2->lb->text(page2->lb->currentItem());
loc = loc.replace(re, "_");
QString provider = page3->lb->text(page3->lb->currentItem());
urlEncode(provider);
QString fname = kapp->kde_datadir();
fname += "/kppp/Provider/" + loc;
fname += "/" + provider;
Debug("Providerfile=%s\n", fname.data());
cfg = new KSimpleConfig(fname, true);
}
void ProviderDB::accept() {
QRegExp re_username("%USERNAME%");
QRegExp re_password("%PASSWORD%");
KEntryIterator *it = cfg->entryIterator("<Default>");
while(it->current() != 0) {
QString key = it->currentKey();
QString value = it->current()->aValue;
if(value.contains(re_username))
value.replace(re_username, page4->username());
if(value.contains(re_password))
value.replace(re_password, page4->password());
gpppdata.writeConfig(gpppdata.currentGroup(),
key.data(),
value.data());
if(key == "Name")
gpppdata.setAccname(value);
++(*it);
}
gpppdata.writeConfig(gpppdata.currentGroup(), "DialPrefix", page5->prefix());
done(Accepted);
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Intro::PDB_Intro(QWidget *parent) : QWidget(parent) {
QLabel *l = new QLabel(i18n("You will be asked a few questions on informations\n"
"which are needed to establish an Internet connection\n"
"with your Internet Service Provider (ISP).\n\n"
"Make sure you have the registration form from your\n"
"ISP handy. If you have any problems, try the online\n"
"help first. If any information is missing, contact\n"
"your ISP."),
this);
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
tl->addWidget(l);
tl->activate();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Country::PDB_Country(QWidget *parent) : QWidget(parent) {
QLabel *l = new QLabel(i18n("Select the location where you plan to use this\n"
"account from the list below. If your country or\n"
"location is not listed, you have to create the\n"
"account with the normal, dialog based setup.\n\n"
"If you hit \"Cancel\", the dialog based setup\n"
"will start."),
this);
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
tl->addWidget(l);
QHBoxLayout *l1 = new QHBoxLayout;
tl->addLayout(l1);
l1->addStretch(1);
lb = new QListBox(this);
connect(lb, SIGNAL(highlighted(int)),
this, SLOT(selectionChanged(int)));
lb->setMinimumSize(220, 100);
l1->addWidget(lb, 2);
l1->addStretch(1);
// fill the listbox
// set up filter
QDir d(kapp->kde_datadir() + "/kppp/Provider/");
d.setFilter(QDir::Dirs);
d.setSorting(QDir::Name);
// read the list of files
const QFileInfoList *list = d.entryInfoList();
if(list) {
QFileInfoListIterator it( *list );
QFileInfo *fi;
// traverse the list and insert into the widget
QRegExp re("_");
while((fi = it.current()) != NULL) {
QString fname = fi->fileName();
if(fname.length() && fname[0] != '.') {
fname = fname.replace(re, " ");
lb->insertItem(fname);
}
++it;
}
}
tl->activate();
}
void PDB_Country::selectionChanged(int idx) {
KWizard *w = (KWizard *)parent();
w->getNextButton()->setEnabled(idx != -1);
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Provider::PDB_Provider(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("Select your Internet Service Provider (ISP) from\n"
"the list below. If the ISP is not in this list,\n"
"you have to click on \"Cancel\" and create this\n"
"account using the normal, dialog-based setup.\n\n"
"Click on \"Next\" when you have finished your\n"
"selection."), this);
tl->addWidget(l);
QHBoxLayout *l1 = new QHBoxLayout;
tl->addLayout(l1);
l1->addStretch(1);
lb = new QListBox(this);
connect(lb, SIGNAL(highlighted(int)),
this, SLOT(selectionChanged(int)));
lb->setMinimumSize(220, 100);
l1->addWidget(lb, 2);
l1->addStretch(1);
}
void PDB_Provider::selectionChanged(int idx) {
KWizard *w = (KWizard *)parent();
w->getNextButton()->setEnabled(idx != -1);
}
void PDB_Provider::setDir(const char *_dir) {
if(dir != _dir) {
lb->clear();
// fill the listbox
// set up filter
dir = _dir;
QString dir1 = kapp->kde_datadir();
dir1 += "/kppp/Provider/";
QRegExp re1(" ");
dir = dir.replace(re1, "_");
dir1 += dir;
QDir d(dir1);
d.setFilter(QDir::Files);
d.setSorting(QDir::Name);
// read the list of files
const QFileInfoList *list = d.entryInfoList();
QFileInfoListIterator it( *list );
QFileInfo *fi;
// traverse the list and insert into the widget
QRegExp re("_");
while((fi = it.current()) != NULL) {
QString fname = fi->fileName();
if(fname.length() && fname[0] != '.') {
urlDecode(fname);
lb->insertItem(fname);
}
++it;
}
// TODO: Qt 1.x needs this if list is empty
lb->update();
}
}
const char *PDB_Provider::getDir() {
return dir.data();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_UserInfo::PDB_UserInfo(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("To log on to your ISP, kppp needs the username\n"
"and the password you got from your ISP. Type\n"
"in this information in the fields below.\n\n"
"Word case is important here."),
this);
tl->addWidget(l);
QGridLayout *l1 = new QGridLayout(2, 2);
tl->addLayout(l1);
l = new QLabel(i18n("Username:"), this);
l1->addWidget(l, 0, 0);
l = new QLabel(i18n("Password:"), this);
l1->addWidget(l, 1, 0);
_username = newLineEdit(24, this);
connect(_username, SIGNAL(textChanged(const QString &)),
this, SLOT(textChanged(const QString &)));
l1->addWidget(_username, 0, 1);
_password = newLineEdit(24, this);
_password->setEchoMode(QLineEdit::Password);
connect(_password, SIGNAL(textChanged(const QString &)),
this, SLOT(textChanged(const QString &)));
l1->addWidget(_password, 1, 1);
tl->activate();
};
void PDB_UserInfo::textChanged(const QString &) {
KWizard *w = (KWizard*)parent();
w->getNextButton()->setEnabled(strlen(_password->text()) > 0 &&
strlen(_username->text()) > 0);
}
QString PDB_UserInfo::username() {
QString s = _username->text();
return s;
}
QString PDB_UserInfo::password() {
QString s = _password->text();
return s;
}
void PDB_UserInfo::activate() {
_username->setFocus();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_DialPrefix::PDB_DialPrefix(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("If you need a special dial prefix (e.g. if you\n"
"are using a telephone switch) you can specify\n"
"this here. This prefix is dialed just before the\n"
"phone number.\n\n"
"If you have a telephone switch, you probly need\n"
"to write \"0\" or \"0,\" here."),
this);
tl->addWidget(l);
QGridLayout *l1 = new QGridLayout(1, 2);
tl->addLayout(l1);
l = new QLabel(i18n("Dial prefix:"), this);
l1->addWidget(l, 0, 0);
_prefix = newLineEdit(24, this);
l1->addWidget(_prefix, 0, 1);
tl->activate();
}
QString PDB_DialPrefix::prefix() {
QString s = _prefix->text();
return s;
}
void PDB_DialPrefix::activate() {
_prefix->setFocus();
}
/////////////////////////////////////////////////////////////////////////////
//
/////////////////////////////////////////////////////////////////////////////
PDB_Finished::PDB_Finished(QWidget *parent) : QWidget(parent) {
QVBoxLayout *tl = new QVBoxLayout(this, 10, 10);
QLabel *l = new QLabel(i18n("Finished!\n\n"
"A new account has been created. Hit \"OK\" to\n"
"go back to the setup dialog. If you want to\n"
"check the settings of the newly created account,\n"
"you can use \"Edit\" in the setup dialog."),
this);
tl->addWidget(l);
tl->addStretch(1);
};
void urlDecode(QString &s) {
QString s1;
for(uint i = 0; i < s.length(); i++) {
if(s[i] == '%') {
s1 += 100*s[i+1].digitValue() + 10*s[i+2].digitValue()
+ s[i+3].digitValue();
i += 4;
} else {
s1 += s[i];
i++;
}
}
s = s1;
}
void urlEncode(QString &s) {
QString s1, tmp;
for(uint i = 0; i < s.length(); i++) {
if(QString(UNENCODED_CHARS).find(s[i]) >= 0)
s1 += s[i];
else {
tmp.sprintf("\%03i", s[i].unicode());
s1 += tmp;
}
}
s = s1;
}
#include "providerdb.moc"
<|endoftext|>
|
<commit_before>#pragma once
#include <string>
#include <unordered_map>
namespace AnyODE {
template<class T> void ignore( const T& ) { } // ignore compiler warnings about unused parameter
enum class Status : int {success = 0, recoverable_error = 1, unrecoverable_error = -1};
struct OdeSysBase {
void * integrator = nullptr;
std::unordered_map<std::string, int> last_integration_info;
virtual ~OdeSysBase() {}
virtual int get_ny() const = 0;
virtual int get_mlower() const { return -1; } // -1 denotes "not banded"
virtual int get_mupper() const { return -1; } // -1 denotes "not banded"
virtual int get_nroots() const { return 0; } // Do not look for roots by default;
virtual Status rhs(double t, const double * const y, double * const f) = 0;
virtual Status roots(double xval, const double * const y, double * const out) {
ignore(xval); ignore(y); ignore(out);
return Status::unrecoverable_error;
}
virtual Status dense_jac_cmaj(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
double * const __restrict__ jac,
long int ldim){
ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
return Status::unrecoverable_error;
}
virtual Status dense_jac_rmaj(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
double * const __restrict__ jac,
long int ldim,
double * const __restrict__ dfdt=nullptr){
ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
return Status::unrecoverable_error;
}
virtual Status banded_jac_cmaj(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
double * const __restrict__ jac,
long int ldim){
ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
throw std::runtime_error("banded_jac_cmaj not implemented.");
return Status::unrecoverable_error;
}
virtual Status jac_times_vec(const double * const __restrict__ vec,
double * const __restrict__ out,
double t,
const double * const __restrict__ y,
const double * const __restrict__ fy
)
{
ignore(vec);
ignore(out);
ignore(t);
ignore(y);
ignore(fy);
return Status::unrecoverable_error;
}
virtual Status prec_setup(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
bool jok,
bool& jac_recomputed,
double gamma)
{
ignore(t);
ignore(y);
ignore(fy);
ignore(jok);
ignore(jac_recomputed);
ignore(gamma);
return Status::unrecoverable_error;
}
virtual Status prec_solve_left(const double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
const double * const __restrict__ r,
double * const __restrict__ z,
double gamma,
double delta,
const double * const __restrict__ ewt)
{
ignore(t);
ignore(y);
ignore(fy);
ignore(r);
ignore(z);
ignore(gamma);
ignore(delta);
ignore(ewt);
return Status::unrecoverable_error;
}
};
}
<commit_msg>Versioning of anyode.hpp<commit_after>#ifdef ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37
#if ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 != 2
#error "Multiple anyode.hpp files included with version mismatch"
#endif
#define ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 2
#include <string>
#include <unordered_map>
namespace AnyODE {
template<class T> void ignore( const T& ) { } // ignore compiler warnings about unused parameter
enum class Status : int {success = 0, recoverable_error = 1, unrecoverable_error = -1};
struct OdeSysBase {
void * integrator = nullptr;
std::unordered_map<std::string, int> last_integration_info;
virtual ~OdeSysBase() {}
virtual int get_ny() const = 0;
virtual int get_mlower() const { return -1; } // -1 denotes "not banded"
virtual int get_mupper() const { return -1; } // -1 denotes "not banded"
virtual int get_nroots() const { return 0; } // Do not look for roots by default;
virtual Status rhs(double t, const double * const y, double * const f) = 0;
virtual Status roots(double xval, const double * const y, double * const out) {
ignore(xval); ignore(y); ignore(out);
return Status::unrecoverable_error;
}
virtual Status dense_jac_cmaj(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
double * const __restrict__ jac,
long int ldim,
double * const __restrict__ dfdt=nullptr){
ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
return Status::unrecoverable_error;
}
virtual Status dense_jac_rmaj(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
double * const __restrict__ jac,
long int ldim,
double * const __restrict__ dfdt=nullptr){
ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim); ignore(dfdt);
return Status::unrecoverable_error;
}
virtual Status banded_jac_cmaj(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
double * const __restrict__ jac,
long int ldim){
ignore(t); ignore(y); ignore(fy); ignore(jac); ignore(ldim);
throw std::runtime_error("banded_jac_cmaj not implemented.");
return Status::unrecoverable_error;
}
virtual Status jac_times_vec(const double * const __restrict__ vec,
double * const __restrict__ out,
double t,
const double * const __restrict__ y,
const double * const __restrict__ fy
)
{
ignore(vec);
ignore(out);
ignore(t);
ignore(y);
ignore(fy);
return Status::unrecoverable_error;
}
virtual Status prec_setup(double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
bool jok,
bool& jac_recomputed,
double gamma)
{
ignore(t);
ignore(y);
ignore(fy);
ignore(jok);
ignore(jac_recomputed);
ignore(gamma);
return Status::unrecoverable_error;
}
virtual Status prec_solve_left(const double t,
const double * const __restrict__ y,
const double * const __restrict__ fy,
const double * const __restrict__ r,
double * const __restrict__ z,
double gamma,
double delta,
const double * const __restrict__ ewt)
{
ignore(t);
ignore(y);
ignore(fy);
ignore(r);
ignore(z);
ignore(gamma);
ignore(delta);
ignore(ewt);
return Status::unrecoverable_error;
}
};
}
#endif /* ANYODE_HPP_D47BAD58870311E6B95F2F58DEFE6E37 */
<|endoftext|>
|
<commit_before>/*********************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2015 Viktor Richter *
* *
* 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 "hungarian/hungarian.hpp"
#include <map>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <cassert>
typedef unsigned int uint;
typedef int Cost;
typedef std::vector<std::vector<Cost> > CostMatrix;
typedef std::string Id;
typedef std::vector<int> Preferences;
typedef std::pair<Id,Preferences> Entity;
std::vector<std::string> split(const std::string& data, char delimiter) {
std::vector<std::string> result;
std::stringstream stream(data);
std::string element;
while(std::getline(stream, element, delimiter)){
result.push_back(element);
}
return result;
}
template<typename T>
T parse(const std::string& data){
std::istringstream istream(data);
T result;
istream >> result;
return result;
}
template<typename T>
std::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){
std::vector<T> result;
for(uint i = start_at; i < data.size(); ++i){
result.push_back(parse<T>(data[i]));
}
return result;
}
Entity parseEntity(const std::string& csv){
std::vector<std::string> vector = split(csv,',');
Entity result;
result.first = parse<std::string>(vector.front());
result.second = parse_vector<int>(vector,1);
return result;
}
void process_args(int arg_num, char** args){
for(int i = 1; i < arg_num; ++i){
std::string arg = args[i];
if(arg == "--help" || arg == "-h"){
std::cout << "This application uses preferences to sort entities into groups. Input data is read from stdin.\n"\
<< "Usage: assign < preferences.csv\n\n"
<< "Parameters:\n"
<< "\t -h | --help \t\t print this message and leave.\n"
<< "\t -e | --example \t print an example preferences document in the correct format and leave."
<< std::endl;
std::exit(0);
} else if (arg == "--example" || arg == "-e"){
std::cout << "jack,1,5,6,2,3" << std::endl;
std::cout << "jill,6,2,4,6,2" << std::endl;
std::cout << "paul,3,3,5,2,1" << std::endl;
std::cout << "will,2,9,7,4,3" << std::endl;
std::cout << "jenn,5,6,3,7,1" << std::endl;
std::exit(0);
}
}
}
void parse_csv_data(std::vector<Id>& entity_ids, std::vector<Preferences>& entity_preferences){
uint group_count = 0;
uint line = 1;
while(std::cin) {
std::string entity_csv;
std::getline(std::cin, entity_csv);
if(std::cin.eof()) break;
Entity entity = parseEntity(entity_csv);
entity_ids.push_back(entity.first);
entity_preferences.push_back(entity.second);
if(line == 1){
group_count = entity.second.size();
} else {
if(entity.second.size() != group_count){
std::cerr << "Error: Group count in line #" << line << " is defferent from previous. "
<< entity.second.size() << " != " << group_count << "(previous)." << std::endl;
std::exit(-1);
}
}
++line;
}
}
void print_data(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences, std::ostream& dst){
assert(entity_ids.size() == entity_preferences.size());
for(uint i = 0; i < entity_ids.size(); ++i){
dst << entity_ids[i] << ":\t";
for (int j = 0; j < entity_preferences[i].size(); ++j){
dst << entity_preferences[i][j] << " ";
}
dst << std::endl;
}
}
void fill_cost_matrix(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences,
uint group_count,
CostMatrix& cost_matrix)
{
uint group_size = entity_ids.size() / group_count;
if(entity_ids.size() % group_count) { ++group_size; } // rounding up
uint columns = entity_ids.size(); // true count of entities
uint rows = group_count * group_size;
cost_matrix.clear();
cost_matrix.reserve(columns);
// fill the first rows with preferences
for(uint row = 0; row < group_count; ++row){
cost_matrix.push_back(std::vector<Cost>(columns,0));
for(uint column = 0; column < entity_preferences.size(); ++column){
cost_matrix[row][column] = entity_preferences[column][row]; // transposing
}
}
// fill the other rows by copying the first ones.
for(uint row = group_count; row < rows; ++row){
cost_matrix.push_back(cost_matrix[row % group_count]);
}
}
int main(int arg_num, char** args) {
process_args(arg_num,args);
std::vector<Id> entity_ids;
std::vector<Preferences> entity_preferences;
parse_csv_data(entity_ids, entity_preferences);
print_data(entity_ids,entity_preferences,std::cout);
// create cost matrix
CostMatrix cost_matrix;
uint group_count = entity_preferences.front().size(); // #groups == #group preferences
fill_cost_matrix(entity_ids,entity_preferences,group_count,cost_matrix);
/* initialize the hungarian_problem using the cost matrix*/
Hungarian hungarian(cost_matrix, cost_matrix.size(), cost_matrix.front().size(), HUNGARIAN_MODE_MINIMIZE_COST) ;
/* some output */
fprintf(stderr, "cost-matrix:");
hungarian.print_cost();
/* solve the assignement problem */
hungarian.solve();
/* some output */
fprintf(stderr, "assignment:");
hungarian.print_assignment();
return 0;
}
<commit_msg>Switch hungarian for munkres in assign.cpp<commit_after>/*********************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2015 Viktor Richter *
* *
* 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 <map>
#include <vector>
#include <sstream>
#include <algorithm>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include "munkres.h"
#include "matrix.h"
typedef unsigned int uint;
typedef int Cost;
typedef std::vector<std::vector<Cost> > CostMatrix;
typedef std::string Id;
typedef std::vector<int> Preferences;
typedef std::pair<Id,Preferences> Entity;
std::vector<std::string> split(const std::string& data, char delimiter) {
std::vector<std::string> result;
std::stringstream stream(data);
std::string element;
while(std::getline(stream, element, delimiter)){
result.push_back(element);
}
return result;
}
template<typename T>
T parse(const std::string& data){
std::istringstream istream(data);
T result;
istream >> result;
return result;
}
template<typename T>
std::vector<T> parse_vector(const std::vector<std::string>& data, uint start_at=0){
std::vector<T> result;
for(uint i = start_at; i < data.size(); ++i){
result.push_back(parse<T>(data[i]));
}
return result;
}
Entity parseEntity(const std::string& csv){
std::vector<std::string> vector = split(csv,',');
Entity result;
result.first = parse<std::string>(vector.front());
result.second = parse_vector<int>(vector,1);
return result;
}
void process_args(int arg_num, char** args){
for(int i = 1; i < arg_num; ++i){
std::string arg = args[i];
if(arg == "--help" || arg == "-h"){
std::cout << "This application uses preferences to sort entities into groups. Input data is read from stdin.\n"\
<< "Usage: assign < preferences.csv\n\n"
<< "Parameters:\n"
<< "\t -h | --help \t\t print this message and leave.\n"
<< "\t -e | --example \t print an example preferences document in the correct format and leave."
<< std::endl;
std::exit(0);
} else if (arg == "--example" || arg == "-e"){
std::cout << "jack,1,5,6,2,3" << std::endl;
std::cout << "jill,6,2,4,6,2" << std::endl;
std::cout << "paul,3,3,5,2,1" << std::endl;
std::cout << "will,2,9,7,4,3" << std::endl;
std::cout << "jenn,5,6,3,7,1" << std::endl;
std::exit(0);
}
}
}
void parse_csv_data(std::vector<Id>& entity_ids, std::vector<Preferences>& entity_preferences){
uint group_count = 0;
uint line = 1;
while(std::cin) {
std::string entity_csv;
std::getline(std::cin, entity_csv);
if(std::cin.eof()) break;
Entity entity = parseEntity(entity_csv);
entity_ids.push_back(entity.first);
entity_preferences.push_back(entity.second);
if(line == 1){
group_count = entity.second.size();
} else {
if(entity.second.size() != group_count){
std::cerr << "Error: Group count in line #" << line << " is defferent from previous. "
<< entity.second.size() << " != " << group_count << "(previous)." << std::endl;
std::exit(-1);
}
}
++line;
}
}
void print_data(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences, std::ostream& dst){
assert(entity_ids.size() == entity_preferences.size());
for(uint i = 0; i < entity_ids.size(); ++i){
dst << entity_ids[i] << ":\t";
for (int j = 0; j < entity_preferences[i].size(); ++j){
dst << entity_preferences[i][j] << " ";
}
dst << std::endl;
}
}
template<typename T>
void print_matrix(const Matrix<T>& matrix, std::ostream& stream){
// Display solved matrix.
for ( int row = 0 ; row < matrix.rows() ; row++ ) {
for ( int col = 0 ; col < matrix.columns() ; col++ ) {
stream << matrix(row,col) << ",";
}
stream << "\n";
}
stream << std::endl;
}
Matrix<double> create_matrix(const std::vector<Id>& entity_ids, const std::vector<Preferences>& entity_preferences,
uint group_count)
{
uint group_size = entity_ids.size() / group_count;
if(entity_ids.size() % group_count) { ++group_size; } // rounding up
uint columns = entity_ids.size(); // true count of entities
uint rows = group_count * group_size;
Matrix<double> result(rows,columns);
for(uint row = 0; row < rows; ++row){
for(uint column = 0; column < columns; ++column){
uint looped_row = row % group_count;
result(row, column) = entity_preferences[column][looped_row]; // transposing
}
}
return result;
}
int main(int arg_num, char** args) {
process_args(arg_num,args);
std::vector<Id> entity_ids;
std::vector<Preferences> entity_preferences;
parse_csv_data(entity_ids, entity_preferences);
print_data(entity_ids,entity_preferences,std::cout);
Matrix<double> cost_matrix = std::move(create_matrix(entity_ids,entity_preferences,entity_preferences.front().size()));
Matrix<double> solution = cost_matrix;
Munkres munkres;
munkres.solve(solution);
print_matrix<double>(solution,std::cerr);
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Concrete_SparseDataHyperRectangle_stdmap_inl_
#define _Stroika_Foundation_Containers_Concrete_SparseDataHyperRectangle_stdmap_inl_
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <map>
#include "../../Debug/Cast.h"
#include "../../Memory/BlockAllocated.h"
#include "../DataStructures/STLContainerWrapper.h"
#include "../Private/IteratorImplHelper.h"
namespace Stroika::Foundation::Containers::Concrete {
using Traversal::IteratorOwnerID;
/*
********************************************************************************
*********** SparseDataHyperRectangle_stdmap<T, INDEXES...>::Rep_ ***************
********************************************************************************
*/
template <typename T, typename... INDEXES>
class SparseDataHyperRectangle_stdmap<T, INDEXES...>::Rep_ : public DataHyperRectangle<T, INDEXES...>::_IRep, public Memory::UseBlockAllocationIfAppropriate<Rep_> {
private:
using inherited = typename DataHyperRectangle<T, INDEXES...>::_IRep;
public:
using _IterableRepSharedPtr = typename Iterable<tuple<T, INDEXES...>>::_IterableRepSharedPtr;
using _DataHyperRectangleRepSharedPtr = typename inherited::_IRepSharedPtr;
using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE;
using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE;
public:
Rep_ (Configuration::ArgByValueType<T> defaultItem)
: fDefaultValue_{defaultItem}
{
}
Rep_ (const Rep_& from) = delete;
Rep_ (Rep_* from, [[maybe_unused]] IteratorOwnerID forIterableEnvelope)
: fData_{from->fData_}
{
RequireNotNull (from);
}
public:
nonvirtual Rep_& operator= (const Rep_&) = delete;
// Iterable<tuple<T, INDEXES...>>::_IRep overrides
public:
virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override
{
// const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists
return Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope);
}
virtual Iterator<tuple<T, INDEXES...>> MakeIterator (IteratorOwnerID suggestedOwner) const override
{
Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API
return Iterator<tuple<T, INDEXES...>> (Iterator<tuple<T, INDEXES...>>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_));
}
virtual size_t GetLength () const override
{
return fData_.size ();
}
virtual bool IsEmpty () const override
{
return fData_.empty ();
}
virtual void Apply (_APPLY_ARGTYPE doToElement) const override
{
fData_.Apply (
[&] (const pair<tuple<INDEXES...>, T>& item) {
doToElement (tuple_cat (tuple<T>{item.second}, item.first));
});
}
virtual Iterator<tuple<T, INDEXES...>> FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const override
{
shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_};
using RESULT_TYPE = Iterator<tuple<T, INDEXES...>>;
using SHARED_REP_TYPE = Traversal::IteratorBase::PtrImplementationTemplate<IteratorRep_>;
auto iLink = const_cast<DataStructureImplType_&> (fData_).FindFirstThat (
[&] (const pair<tuple<INDEXES...>, T>& item) {
return doToElement (tuple_cat (tuple<T>{item.second}, item.first));
});
if (iLink == fData_.end ()) {
return RESULT_TYPE::GetEmptyIterator ();
}
Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API
SHARED_REP_TYPE resultRep = Iterator<T>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_);
resultRep->fIterator.SetCurrentLink (iLink);
// because Iterator<T> locks rep (non recursive mutex) - this CTOR needs to happen outside CONTAINER_LOCK_HELPER_START()
return RESULT_TYPE (move (resultRep));
}
// DataHyperRectangle<T, INDEXES...>::_IRep overrides
public:
virtual _DataHyperRectangleRepSharedPtr CloneEmpty ([[maybe_unused]] IteratorOwnerID forIterableEnvelope) const override
{
#if 0
if (fData_.HasActiveIterators ()) {
// const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists
auto r = Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope);
r->fData_.clear ();
return r;
}
else {
return Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (fDefaultValue_);
}
#endif
return Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (fDefaultValue_);
}
virtual T GetAt (INDEXES... indexes) const override
{
shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_};
auto i = fData_.find (tuple<INDEXES...>{indexes...});
if (i != fData_.end ()) {
return i->second;
}
return fDefaultValue_;
}
virtual void SetAt (INDEXES... indexes, Configuration::ArgByValueType<T> v) override
{
lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_};
if (v == fDefaultValue_) {
auto i = fData_.find (tuple<INDEXES...> (indexes...));
if (i != fData_.end ()) {
fData_.erase (i);
}
}
else {
// @todo - add patching...
#if qCompilerAndStdLib_insert_or_assign_Buggy
fData_.erase (tuple<INDEXES...> (indexes...));
fData_.insert (typename map<tuple<INDEXES...>, T>::value_type (tuple<INDEXES...> (indexes...), v));
#else
fData_.insert_or_assign (tuple<INDEXES...> (indexes...), v);
#endif
}
}
private:
template <typename PATCHABLE_CONTAINER, typename PATCHABLE_CONTAINER_ITERATOR = typename PATCHABLE_CONTAINER::ForwardIterator>
class MyIteratorImplHelper_ : public Iterator<tuple<T, INDEXES...>>::IRep, public Memory::UseBlockAllocationIfAppropriate<MyIteratorImplHelper_<PATCHABLE_CONTAINER, PATCHABLE_CONTAINER_ITERATOR>> {
private:
using inherited = typename Iterator<tuple<T, INDEXES...>>::IRep;
public:
using RepSmartPtr = typename Iterator<tuple<T, INDEXES...>>::RepSmartPtr;
public:
MyIteratorImplHelper_ () = delete;
MyIteratorImplHelper_ (const MyIteratorImplHelper_&) = default;
explicit MyIteratorImplHelper_ ([[maybe_unused]] IteratorOwnerID owner, PATCHABLE_CONTAINER* data)
: fIterator{data}
{
RequireNotNull (data);
fIterator.More (static_cast<pair<tuple<INDEXES...>, T>*> (nullptr), true); //tmphack cuz current backend iterators require a first more() - fix that!
}
public:
virtual ~MyIteratorImplHelper_ () = default;
// Iterator<tuple<T, INDEXES...>>::IRep
public:
virtual RepSmartPtr Clone () const override
{
return Iterator<tuple<T, INDEXES...>>::template MakeSmartPtr<MyIteratorImplHelper_> (*this);
}
virtual IteratorOwnerID GetOwner () const override
{
return nullptr;
//return fIterator.GetOwner ();
}
virtual void More (optional<tuple<T, INDEXES...>>* result, bool advance) override
{
RequireNotNull (result);
// NOTE: the reason this is Debug::AssertExternallySynchronizedLock, is because we only modify data on the newly cloned (breakreferences)
// iterator, and that must be in the thread (so externally synchronized) of the modifier
// shared_lock<const Debug::AssertExternallySynchronizedLock> lg (*fIterator.GetPatchableContainerHelper ());
More_SFINAE_ (result, advance);
}
virtual bool Equals (const typename Iterator<tuple<T, INDEXES...>>::IRep* rhs) const override
{
RequireNotNull (rhs);
using ActualIterImplType_ = MyIteratorImplHelper_<PATCHABLE_CONTAINER, PATCHABLE_CONTAINER_ITERATOR>;
const ActualIterImplType_* rrhs = Debug::UncheckedDynamicCast<const ActualIterImplType_*> (rhs);
AssertNotNull (rrhs);
// shared_lock<const Debug::AssertExternallySynchronizedLock> critSec1 (*fIterator.GetPatchableContainerHelper ());
// shared_lock<const Debug::AssertExternallySynchronizedLock> critSec2 (*rrhs->fIterator.GetPatchableContainerHelper ());
return fIterator.Equals (rrhs->fIterator);
}
private:
/*
* More_SFINAE_ () trick is cuz if types are the same, we can just pass pointer, but if they differ, we need
* a temporary, and to copy.
*/
template <typename CHECK_KEY = typename PATCHABLE_CONTAINER::value_type>
nonvirtual void More_SFINAE_ (optional<tuple<T, INDEXES...>>* result, bool advance, enable_if_t<is_same_v<T, CHECK_KEY>>* = 0)
{
RequireNotNull (result);
fIterator.More (result, advance);
}
template <typename CHECK_KEY = typename PATCHABLE_CONTAINER::value_type>
nonvirtual void More_SFINAE_ (optional<tuple<T, INDEXES...>>* result, bool advance, enable_if_t<!is_same_v<T, CHECK_KEY>>* = 0)
{
RequireNotNull (result);
optional<pair<tuple<INDEXES...>, T>> tmp;
fIterator.More (&tmp, advance);
if (tmp.has_value ()) {
*result = tuple_cat (tuple<T>{tmp->second}, tmp->first);
}
else {
*result = nullopt;
}
}
public:
mutable PATCHABLE_CONTAINER_ITERATOR fIterator;
};
private:
using DataStructureImplType_ = DataStructures::STLContainerWrapper<map<tuple<INDEXES...>, T>>;
using IteratorRep_ = MyIteratorImplHelper_<DataStructureImplType_>;
private:
T fDefaultValue_;
DataStructureImplType_ fData_;
};
/*
********************************************************************************
************** SparseDataHyperRectangle_stdmap<T, INDEXES...> ******************
********************************************************************************
*/
template <typename T, typename... INDEXES>
SparseDataHyperRectangle_stdmap<T, INDEXES...>::SparseDataHyperRectangle_stdmap (Configuration::ArgByValueType<T> defaultItem)
: inherited (inherited::template MakeSmartPtr<Rep_> (defaultItem))
{
AssertRepValidType_ ();
}
template <typename T, typename... INDEXES>
inline SparseDataHyperRectangle_stdmap<T, INDEXES...>::SparseDataHyperRectangle_stdmap (const SparseDataHyperRectangle_stdmap<T, INDEXES...>& src)
: inherited (static_cast<const inherited&> (src))
{
AssertRepValidType_ ();
}
template <typename T, typename... INDEXES>
inline SparseDataHyperRectangle_stdmap<T, INDEXES...>& SparseDataHyperRectangle_stdmap<T, INDEXES...>::operator= (const SparseDataHyperRectangle_stdmap<T, INDEXES...>& rhs)
{
AssertRepValidType_ ();
inherited::operator= (static_cast<const inherited&> (rhs));
AssertRepValidType_ ();
return *this;
}
template <typename T, typename... INDEXES>
inline void SparseDataHyperRectangle_stdmap<T, INDEXES...>::AssertRepValidType_ () const
{
#if qDebug
typename inherited::template _SafeReadRepAccessor<Rep_> tmp{this}; // for side-effect of AssertMember
#endif
}
}
#endif /* _Stroika_Foundation_Containers_Concrete_SparseDataHyperRectangle_stdmap_inl_ */
<commit_msg>workaround weird syntax issue afflicting g++8 - not worth bug define<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Concrete_SparseDataHyperRectangle_stdmap_inl_
#define _Stroika_Foundation_Containers_Concrete_SparseDataHyperRectangle_stdmap_inl_
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <map>
#include "../../Debug/Cast.h"
#include "../../Memory/BlockAllocated.h"
#include "../DataStructures/STLContainerWrapper.h"
#include "../Private/IteratorImplHelper.h"
namespace Stroika::Foundation::Containers::Concrete {
using Traversal::IteratorOwnerID;
/*
********************************************************************************
*********** SparseDataHyperRectangle_stdmap<T, INDEXES...>::Rep_ ***************
********************************************************************************
*/
template <typename T, typename... INDEXES>
class SparseDataHyperRectangle_stdmap<T, INDEXES...>::Rep_ : public DataHyperRectangle<T, INDEXES...>::_IRep, public Memory::UseBlockAllocationIfAppropriate<Rep_> {
private:
using inherited = typename DataHyperRectangle<T, INDEXES...>::_IRep;
public:
using _IterableRepSharedPtr = typename Iterable<tuple<T, INDEXES...>>::_IterableRepSharedPtr;
using _DataHyperRectangleRepSharedPtr = typename inherited::_IRepSharedPtr;
using _APPLY_ARGTYPE = typename inherited::_APPLY_ARGTYPE;
using _APPLYUNTIL_ARGTYPE = typename inherited::_APPLYUNTIL_ARGTYPE;
public:
Rep_ (Configuration::ArgByValueType<T> defaultItem)
: fDefaultValue_{defaultItem}
{
}
Rep_ (const Rep_& from) = delete;
Rep_ (Rep_* from, [[maybe_unused]] IteratorOwnerID forIterableEnvelope)
: fData_{from->fData_}
{
RequireNotNull (from);
}
public:
nonvirtual Rep_& operator= (const Rep_&) = delete;
// Iterable<tuple<T, INDEXES...>>::_IRep overrides
public:
virtual _IterableRepSharedPtr Clone (IteratorOwnerID forIterableEnvelope) const override
{
// const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists
return Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope);
}
virtual Iterator<tuple<T, INDEXES...>> MakeIterator (IteratorOwnerID suggestedOwner) const override
{
Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API
return Iterator<tuple<T, INDEXES...>> (Iterator<tuple<T, INDEXES...>>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_));
}
virtual size_t GetLength () const override
{
return fData_.size ();
}
virtual bool IsEmpty () const override
{
return fData_.empty ();
}
virtual void Apply (_APPLY_ARGTYPE doToElement) const override
{
fData_.Apply (
[&] (const pair<tuple<INDEXES...>, T>& item) {
doToElement (tuple_cat (tuple<T>{item.second}, item.first));
});
}
virtual Iterator<tuple<T, INDEXES...>> FindFirstThat (_APPLYUNTIL_ARGTYPE doToElement, IteratorOwnerID suggestedOwner) const override
{
shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_};
using RESULT_TYPE = Iterator<tuple<T, INDEXES...>>;
using SHARED_REP_TYPE = Traversal::IteratorBase::PtrImplementationTemplate<IteratorRep_>;
auto iLink = const_cast<DataStructureImplType_&> (fData_).FindFirstThat (
[&] (const pair<tuple<INDEXES...>, T>& item) {
return doToElement (tuple_cat (tuple<T>{item.second}, item.first));
});
if (iLink == fData_.end ()) {
return RESULT_TYPE::GetEmptyIterator ();
}
Rep_* NON_CONST_THIS = const_cast<Rep_*> (this); // logically const, but non-const cast cuz re-using iterator API
SHARED_REP_TYPE resultRep = Iterator<T>::template MakeSmartPtr<IteratorRep_> (suggestedOwner, &NON_CONST_THIS->fData_);
resultRep->fIterator.SetCurrentLink (iLink);
// because Iterator<T> locks rep (non recursive mutex) - this CTOR needs to happen outside CONTAINER_LOCK_HELPER_START()
return RESULT_TYPE (move (resultRep));
}
// DataHyperRectangle<T, INDEXES...>::_IRep overrides
public:
virtual _DataHyperRectangleRepSharedPtr CloneEmpty ([[maybe_unused]] IteratorOwnerID forIterableEnvelope) const override
{
#if 0
if (fData_.HasActiveIterators ()) {
// const cast because though cloning LOGICALLY makes no changes in reality we have to patch iterator lists
auto r = Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (const_cast<Rep_*> (this), forIterableEnvelope);
r->fData_.clear ();
return r;
}
else {
return Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (fDefaultValue_);
}
#endif
return Iterable<tuple<T, INDEXES...>>::template MakeSmartPtr<Rep_> (fDefaultValue_);
}
virtual T GetAt (INDEXES... indexes) const override
{
shared_lock<const Debug::AssertExternallySynchronizedLock> critSec{fData_};
auto i = fData_.find (tuple<INDEXES...>{indexes...});
if (i != fData_.end ()) {
return i->second;
}
return fDefaultValue_;
}
virtual void SetAt (INDEXES... indexes, Configuration::ArgByValueType<T> v) override
{
lock_guard<const Debug::AssertExternallySynchronizedLock> critSec{fData_};
if (v == fDefaultValue_) {
auto i = fData_.find (tuple<INDEXES...> (indexes...));
if (i != fData_.end ()) {
fData_.erase (i);
}
}
else {
// @todo - add patching...
#if qCompilerAndStdLib_insert_or_assign_Buggy
fData_.erase (tuple<INDEXES...> (indexes...));
fData_.insert (typename map<tuple<INDEXES...>, T>::value_type (tuple<INDEXES...> (indexes...), v));
#else
fData_.insert_or_assign (tuple<INDEXES...> (indexes...), v);
#endif
}
}
private:
template <typename PATCHABLE_CONTAINER, typename PATCHABLE_CONTAINER_ITERATOR = typename PATCHABLE_CONTAINER::ForwardIterator>
class MyIteratorImplHelper_ : public Iterator<tuple<T, INDEXES...>>::IRep, public Memory::UseBlockAllocationIfAppropriate<MyIteratorImplHelper_<PATCHABLE_CONTAINER, PATCHABLE_CONTAINER_ITERATOR>> {
private:
using inherited = typename Iterator<tuple<T, INDEXES...>>::IRep;
public:
using RepSmartPtr = typename Iterator<tuple<T, INDEXES...>>::RepSmartPtr;
public:
MyIteratorImplHelper_ () = delete;
MyIteratorImplHelper_ (const MyIteratorImplHelper_&) = default;
explicit MyIteratorImplHelper_ (IteratorOwnerID /*owner*/, PATCHABLE_CONTAINER* data)
: fIterator{data}
{
RequireNotNull (data);
fIterator.More (static_cast<pair<tuple<INDEXES...>, T>*> (nullptr), true); //tmphack cuz current backend iterators require a first more() - fix that!
}
public:
virtual ~MyIteratorImplHelper_ () = default;
// Iterator<tuple<T, INDEXES...>>::IRep
public:
virtual RepSmartPtr Clone () const override
{
return Iterator<tuple<T, INDEXES...>>::template MakeSmartPtr<MyIteratorImplHelper_> (*this);
}
virtual IteratorOwnerID GetOwner () const override
{
return nullptr;
//return fIterator.GetOwner ();
}
virtual void More (optional<tuple<T, INDEXES...>>* result, bool advance) override
{
RequireNotNull (result);
// NOTE: the reason this is Debug::AssertExternallySynchronizedLock, is because we only modify data on the newly cloned (breakreferences)
// iterator, and that must be in the thread (so externally synchronized) of the modifier
// shared_lock<const Debug::AssertExternallySynchronizedLock> lg (*fIterator.GetPatchableContainerHelper ());
More_SFINAE_ (result, advance);
}
virtual bool Equals (const typename Iterator<tuple<T, INDEXES...>>::IRep* rhs) const override
{
RequireNotNull (rhs);
using ActualIterImplType_ = MyIteratorImplHelper_<PATCHABLE_CONTAINER, PATCHABLE_CONTAINER_ITERATOR>;
const ActualIterImplType_* rrhs = Debug::UncheckedDynamicCast<const ActualIterImplType_*> (rhs);
AssertNotNull (rrhs);
// shared_lock<const Debug::AssertExternallySynchronizedLock> critSec1 (*fIterator.GetPatchableContainerHelper ());
// shared_lock<const Debug::AssertExternallySynchronizedLock> critSec2 (*rrhs->fIterator.GetPatchableContainerHelper ());
return fIterator.Equals (rrhs->fIterator);
}
private:
/*
* More_SFINAE_ () trick is cuz if types are the same, we can just pass pointer, but if they differ, we need
* a temporary, and to copy.
*/
template <typename CHECK_KEY = typename PATCHABLE_CONTAINER::value_type>
nonvirtual void More_SFINAE_ (optional<tuple<T, INDEXES...>>* result, bool advance, enable_if_t<is_same_v<T, CHECK_KEY>>* = 0)
{
RequireNotNull (result);
fIterator.More (result, advance);
}
template <typename CHECK_KEY = typename PATCHABLE_CONTAINER::value_type>
nonvirtual void More_SFINAE_ (optional<tuple<T, INDEXES...>>* result, bool advance, enable_if_t<!is_same_v<T, CHECK_KEY>>* = 0)
{
RequireNotNull (result);
optional<pair<tuple<INDEXES...>, T>> tmp;
fIterator.More (&tmp, advance);
if (tmp.has_value ()) {
*result = tuple_cat (tuple<T>{tmp->second}, tmp->first);
}
else {
*result = nullopt;
}
}
public:
mutable PATCHABLE_CONTAINER_ITERATOR fIterator;
};
private:
using DataStructureImplType_ = DataStructures::STLContainerWrapper<map<tuple<INDEXES...>, T>>;
using IteratorRep_ = MyIteratorImplHelper_<DataStructureImplType_>;
private:
T fDefaultValue_;
DataStructureImplType_ fData_;
};
/*
********************************************************************************
************** SparseDataHyperRectangle_stdmap<T, INDEXES...> ******************
********************************************************************************
*/
template <typename T, typename... INDEXES>
SparseDataHyperRectangle_stdmap<T, INDEXES...>::SparseDataHyperRectangle_stdmap (Configuration::ArgByValueType<T> defaultItem)
: inherited (inherited::template MakeSmartPtr<Rep_> (defaultItem))
{
AssertRepValidType_ ();
}
template <typename T, typename... INDEXES>
inline SparseDataHyperRectangle_stdmap<T, INDEXES...>::SparseDataHyperRectangle_stdmap (const SparseDataHyperRectangle_stdmap<T, INDEXES...>& src)
: inherited (static_cast<const inherited&> (src))
{
AssertRepValidType_ ();
}
template <typename T, typename... INDEXES>
inline SparseDataHyperRectangle_stdmap<T, INDEXES...>& SparseDataHyperRectangle_stdmap<T, INDEXES...>::operator= (const SparseDataHyperRectangle_stdmap<T, INDEXES...>& rhs)
{
AssertRepValidType_ ();
inherited::operator= (static_cast<const inherited&> (rhs));
AssertRepValidType_ ();
return *this;
}
template <typename T, typename... INDEXES>
inline void SparseDataHyperRectangle_stdmap<T, INDEXES...>::AssertRepValidType_ () const
{
#if qDebug
typename inherited::template _SafeReadRepAccessor<Rep_> tmp{this}; // for side-effect of AssertMember
#endif
}
}
#endif /* _Stroika_Foundation_Containers_Concrete_SparseDataHyperRectangle_stdmap_inl_ */
<|endoftext|>
|
<commit_before>// Copyright 2013 Sean McKenna
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// a ray tracer in C++
// libraries, namespace
#include <thread>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
#include <random>
#include "library/loadXML.cpp"
#include "library/scene.cpp"
using namespace std;
// scene to load (project #), variables to set, & debug options
string xml = "scenes/prj9.xml";
bool printXML = false;
bool zBuffer = false;
bool sampleCount = false;
int bounceCount = 5;
int sampleMin = 4;
int sampleMax = 32;
float varThreshold = 0.001;
// variables for ray tracing
int w;
int h;
int size;
Color24* img;
float* zImg;
float* sampleImg;
// variables for anti-aliasing brightness calculations (XYZ, Lab)
float perR = 0.2126;
float perG = 0.7152;
float perB = 0.0722;
float Ycutoff = pow(6.0 / 29.0, 3.0);
float Yprecalc = (1.0 / 3.0) * pow(29.0 / 6.0, 2.0);
// setup threading
static const int numThreads = 8;
void rayTracing(int i);
// for camera ray generation
void cameraRayVars();
float imageDistance = 1.0;
Point *imageTopLeftV;
Point *dXV;
Point *dYV;
Point firstPixel;
Transformation* c;
Point cameraRay(float pX, float pY);
mt19937 rnd;
uniform_real_distribution<float> dist(0.0, 1.0);
// ray tracer
int main(){
// load scene: root node, camera, image
loadScene(xml, printXML);
// set the scene as the root node
setScene(rootNode);
// set variables for ray tracing
w = render.getWidth();
h = render.getHeight();
size = render.getSize();
img = render.getRender();
zImg = render.getZBuffer();
sampleImg = render.getSample();
// set variables for generating camera rays
cameraRayVars();
// start ray tracing loop (in parallel with threads)
thread t[numThreads];
for(int i = 0; i < numThreads; i++)
t[i] = thread(rayTracing, i);
// when finished, join all threads back to main
for(int i = 0; i < numThreads; i++)
t[i].join();
// output ray-traced image & z-buffer & sample count image (if set)
render.save("images/image.ppm");
if(zBuffer){
render.computeZImage();
render.saveZImage("images/imageZ.ppm");
}
if(sampleCount){
render.computeSampleImage();
render.saveSampleImage("images/imageSample.ppm");
}
}
// ray tracing loop (for an individual pixel)
void rayTracing(int i){
// initial starting pixel
int pixel = i;
// thread continuation condition
while(pixel < size){
// number of samples
int s = 0;
// establish pixel location (center)
float pX = pixel % w;
float pY = pixel / w;
// color values to store across samples
Color col;
Color colAvg;
float zAvg = 0.0;
float rVar = 0.0;
float gVar = 0.0;
float bVar = 0.0;
float var = varThreshold;
float brightness = 0.0;
// random rotation of Halton sequence on circle of confusion
float dcR = dist(rnd) * 2.0 * M_PI;
// compute multi-adaptive sampling for each pixel (anti-aliasing)
while(s < sampleMin || (s != sampleMax && (rVar * perR > var + brightness * var || gVar * perG > var + brightness * var || bVar * perB > var + brightness * var))){
// grab Halton sequence to shift point by on image plane
float dpX = centerHalton(Halton(s, 3));
float dpY = centerHalton(Halton(s, 2));
// grab Halton sequence to shift point along circle of confusion
float dcS = sqrt(Halton(s, 5));
// grab Halton sequence to shift point around circle of confusion
float dcT = Halton(s, 7) * 2.0 * M_PI;
// transform ray into world space (offset by Halton seqeunce for sampling)
Point rayDir = cameraRay(pX + dpX, pY + dpY);
Cone *ray = new Cone();
ray->pos = camera.pos;
ray->dir = c->transformFrom(rayDir);
ray->radius = 0.0;
ray->tan = dXV->x / (2.0 * imageDistance);
// traverse through scene DOM
// transform rays into model space
// detect ray intersections and get back HitInfo
HitInfo hi = HitInfo();
bool hit = traceRay(*ray, hi);
// update z-buffer, if necessary
if(zBuffer)
zAvg = (zAvg * s + hi.z) / (float) (s + 1);
// if hit, get the node's material
if(hit){
Node *n = hi.node;
Material *m;
if(n)
m = n->getMaterial();
// if there is a material, shade the pixel
// 5-passes for reflections and refractions
if(m)
col = m->shade(*ray, hi, lights, bounceCount);
// otherwise color it white (as a hit)
else
col.Set(0.929, 0.929, 0.929);
// if we hit nothing, draw the background
}else{
Point p = Point((float) pX / w, (float) pY / h, 0.0);
Color b = background.sample(p);
col = b;
}
// compute average color
float rAvg = (colAvg.r * s + col.r) / (float) (s + 1);
float gAvg = (colAvg.g * s + col.g) / (float) (s + 1);
float bAvg = (colAvg.b * s + col.b) / (float) (s + 1);
colAvg.Set(rAvg, gAvg, bAvg);
// compute color variances
rVar = (rVar * s + (col.r - rAvg) * (col.r - rAvg)) / (float) (s + 1);
gVar = (gVar * s + (col.g - gAvg) * (col.g - gAvg)) / (float) (s + 1);
bVar = (bVar * s + (col.b - bAvg) * (col.b - bAvg)) / (float) (s + 1);
// calculate and update brightness average using XYZ and Lab space
float Y = perR * rAvg + perG * gAvg + perB * bAvg;
float Y13 = Y;
if(Y13 > Ycutoff)
Y13 = pow(Y13, 1.0 / 3.0);
else
Y13 = Yprecalc * Y13 + (4.0 / 29.0);
brightness = (116.0 * Y13 - 16.0) / 100.0;
// increment sample count
s++;
}
// color the pixel image
img[pixel] = Color24(colAvg);
// update the z-buffer image, if necessary
if(zBuffer)
zImg[pixel] = zAvg;
// update the sample count image, if necessary
if(sampleCount)
sampleImg[pixel] = s;
// re-assign next pixel (naive, but works)
pixel += numThreads;
}
}
// create variables for camera ray generation
void cameraRayVars(){
float fov = camera.fov * M_PI / 180.0;
float aspectRatio = (float) w / (float) h;
imageDistance = camera.focalDist;
float imageTipY = imageDistance * tan(fov / 2.0);
float imageTipX = imageTipY * aspectRatio;
float dX = (2.0 * imageTipX) / (float) w;
float dY = (2.0 * imageTipY) / (float) h;
imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);
dXV = new Point(dX, 0.0, 0.0);
dYV = new Point(0.0, -dY, 0.0);
firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
// set up camera transformation (only need to rotate coordinates)
c = new Transformation();
Matrix *rotate = new cyMatrix3f();
rotate->Set(camera.cross, camera.up, -camera.dir);
c->transform(*rotate);
}
// compute camera rays
Point cameraRay(float pX, float pY){
Point ray = firstPixel + (*dXV * pX) + (*dYV * pY);
ray.Normalize();
return ray;
}
<commit_msg>add partially working depth of field, a bit grainy though<commit_after>// Copyright 2013 Sean McKenna
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// a ray tracer in C++
// libraries, namespace
#include <thread>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
#include <random>
#include "library/loadXML.cpp"
#include "library/scene.cpp"
using namespace std;
// scene to load (project #), variables to set, & debug options
string xml = "scenes/prj9.xml";
bool printXML = false;
bool zBuffer = false;
bool sampleCount = false;
int bounceCount = 5;
int sampleMin = 4;
int sampleMax = 32;
float varThreshold = 0.001;
// variables for ray tracing
int w;
int h;
int size;
Color24* img;
float* zImg;
float* sampleImg;
// variables for anti-aliasing brightness calculations (XYZ, Lab)
float perR = 0.2126;
float perG = 0.7152;
float perB = 0.0722;
float Ycutoff = pow(6.0 / 29.0, 3.0);
float Yprecalc = (1.0 / 3.0) * pow(29.0 / 6.0, 2.0);
// setup threading
static const int numThreads = 8;
void rayTracing(int i);
// for camera ray generation
void cameraRayVars();
float imageDistance = 1.0;
Point *imageTopLeftV;
Point *dXV;
Point *dYV;
Point *dVx;
Point *dVy;
Point firstPixel;
Transformation* c;
Point cameraRay(float pX, float pY, Point offset);
mt19937 rnd;
uniform_real_distribution<float> dist(0.0, 1.0);
// ray tracer
int main(){
// load scene: root node, camera, image
loadScene(xml, printXML);
// set the scene as the root node
setScene(rootNode);
// set variables for ray tracing
w = render.getWidth();
h = render.getHeight();
size = render.getSize();
img = render.getRender();
zImg = render.getZBuffer();
sampleImg = render.getSample();
// set variables for generating camera rays
cameraRayVars();
// start ray tracing loop (in parallel with threads)
thread t[numThreads];
for(int i = 0; i < numThreads; i++)
t[i] = thread(rayTracing, i);
// when finished, join all threads back to main
for(int i = 0; i < numThreads; i++)
t[i].join();
// output ray-traced image & z-buffer & sample count image (if set)
render.save("images/image.ppm");
if(zBuffer){
render.computeZImage();
render.saveZImage("images/imageZ.ppm");
}
if(sampleCount){
render.computeSampleImage();
render.saveSampleImage("images/imageSample.ppm");
}
}
// ray tracing loop (for an individual pixel)
void rayTracing(int i){
// initial starting pixel
int pixel = i;
// thread continuation condition
while(pixel < size){
// number of samples
int s = 0;
// establish pixel location (center)
float pX = pixel % w;
float pY = pixel / w;
// color values to store across samples
Color col;
Color colAvg;
float zAvg = 0.0;
float rVar = 0.0;
float gVar = 0.0;
float bVar = 0.0;
float var = varThreshold;
float brightness = 0.0;
// random rotation of Halton sequence on circle of confusion
float dcR = dist(rnd) * 2.0 * M_PI;
// compute multi-adaptive sampling for each pixel (anti-aliasing)
while(s < sampleMin || (s != sampleMax && (rVar * perR > var + brightness * var || gVar * perG > var + brightness * var || bVar * perB > var + brightness * var))){
// grab Halton sequence to shift point by on image plane
float dpX = centerHalton(Halton(s, 3));
float dpY = centerHalton(Halton(s, 2));
// grab Halton sequence to shift point along circle of confusion
float dcS = sqrt(Halton(s, 5)) * camera.dof;
// grab Halton sequence to shift point around circle of confusion
float dcT = Halton(s, 7) * 2.0 * M_PI;
// compute the offset for depth of field sampling
Point posOffset = (*dVx * cos(dcR + dcT) + *dVy * sin(dcR + dcT)) * dcS;
// transform ray into world space (offset by Halton seqeunce for sampling)
Point rayDir = cameraRay(pX + dpX, pY + dpY, posOffset);
Cone *ray = new Cone();
ray->pos = camera.pos + c->transformFrom(posOffset);
ray->dir = c->transformFrom(rayDir);
ray->radius = 0.0;
ray->tan = dXV->x / (2.0 * imageDistance);
// traverse through scene DOM
// transform rays into model space
// detect ray intersections and get back HitInfo
HitInfo hi = HitInfo();
bool hit = traceRay(*ray, hi);
// update z-buffer, if necessary
if(zBuffer)
zAvg = (zAvg * s + hi.z) / (float) (s + 1);
// if hit, get the node's material
if(hit){
Node *n = hi.node;
Material *m;
if(n)
m = n->getMaterial();
// if there is a material, shade the pixel
// 5-passes for reflections and refractions
if(m)
col = m->shade(*ray, hi, lights, bounceCount);
// otherwise color it white (as a hit)
else
col.Set(0.929, 0.929, 0.929);
// if we hit nothing, draw the background
}else{
Point p = Point((float) pX / w, (float) pY / h, 0.0);
Color b = background.sample(p);
col = b;
}
// compute average color
float rAvg = (colAvg.r * s + col.r) / (float) (s + 1);
float gAvg = (colAvg.g * s + col.g) / (float) (s + 1);
float bAvg = (colAvg.b * s + col.b) / (float) (s + 1);
colAvg.Set(rAvg, gAvg, bAvg);
// compute color variances
rVar = (rVar * s + (col.r - rAvg) * (col.r - rAvg)) / (float) (s + 1);
gVar = (gVar * s + (col.g - gAvg) * (col.g - gAvg)) / (float) (s + 1);
bVar = (bVar * s + (col.b - bAvg) * (col.b - bAvg)) / (float) (s + 1);
// calculate and update brightness average using XYZ and Lab space
float Y = perR * rAvg + perG * gAvg + perB * bAvg;
float Y13 = Y;
if(Y13 > Ycutoff)
Y13 = pow(Y13, 1.0 / 3.0);
else
Y13 = Yprecalc * Y13 + (4.0 / 29.0);
brightness = (116.0 * Y13 - 16.0) / 100.0;
// increment sample count
s++;
}
// color the pixel image
img[pixel] = Color24(colAvg);
// update the z-buffer image, if necessary
if(zBuffer)
zImg[pixel] = zAvg;
// update the sample count image, if necessary
if(sampleCount)
sampleImg[pixel] = s;
// re-assign next pixel (naive, but works)
pixel += numThreads;
}
}
// create variables for camera ray generation
void cameraRayVars(){
float fov = camera.fov * M_PI / 180.0;
float aspectRatio = (float) w / (float) h;
imageDistance = camera.focalDist;
float imageTipY = imageDistance * tan(fov / 2.0);
float imageTipX = imageTipY * aspectRatio;
float dX = (2.0 * imageTipX) / (float) w;
float dY = (2.0 * imageTipY) / (float) h;
imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance);
dXV = new Point(dX, 0.0, 0.0);
dYV = new Point(0.0, -dY, 0.0);
firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
// set up camera transformation (only need to rotate coordinates)
c = new Transformation();
Matrix *rotate = new cyMatrix3f();
rotate->Set(camera.cross, camera.up, -camera.dir);
c->transform(*rotate);
// get normalized rays on the focal plane
dVx = new Point(1.0, 0.0, 0.0);
dVy = new Point(0.0, 1.0, 0.0);
}
// compute camera ray direction
Point cameraRay(float pX, float pY, Point offset){
Point ray = firstPixel + (*dXV * pX) + (*dYV * pY) - offset;
ray.Normalize();
return ray;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
class Profile;
namespace {
const int kRightColumnWidth = 210;
const int kIconSize = 69;
// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
public:
InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
Extension* extension, SkBitmap* icon, ExtensionInstallUI::PromptType type)
: delegate_(delegate), icon_(NULL), type_(type) {
// Scale down to icon size, but allow smaller icons (don't scale up).
gfx::Size size(icon->width(), icon->height());
if (size.width() > kIconSize || size.height() > kIconSize)
size = gfx::Size(kIconSize, kIconSize);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
heading_ = new views::Label(
l10n_util::GetStringF(ExtensionInstallUI::kHeadingIds[type_],
UTF8ToWide(extension->name())));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
}
private:
// DialogDelegate
virtual std::wstring GetDialogButtonLabel(
MessageBoxFlags::DialogButton button) const {
switch (button) {
case MessageBoxFlags::DIALOGBUTTON_OK:
return l10n_util::GetString(ExtensionInstallUI::kButtonIds[type_]);
case MessageBoxFlags::DIALOGBUTTON_CANCEL:
return l10n_util::GetString(IDS_CANCEL);
default:
NOTREACHED();
return L"";
}
}
virtual int GetDefaultDialogButton() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
virtual bool Accept() {
delegate_->InstallUIProceed();
return true;
}
virtual bool Cancel() {
delegate_->InstallUIAbort();
return true;
}
// WindowDelegate
virtual bool IsModal() const { return true; }
virtual std::wstring GetWindowTitle() const {
return l10n_util::GetString(ExtensionInstallUI::kTitleIds[type_]);
}
virtual views::View* GetContentsView() { return this; }
// View
virtual gfx::Size GetPreferredSize() {
int width = kRightColumnWidth;
width += kIconSize;
width += kPanelHorizMargin * 3;
int height = kPanelVertMargin * 2;
height += heading_->GetHeightForWidth(kRightColumnWidth);
return gfx::Size(width,
std::max(height, kIconSize + kPanelVertMargin * 2));
}
virtual void Layout() {
int x = kPanelHorizMargin;
int y = kPanelVertMargin;
heading_->SizeToFit(kRightColumnWidth);
if (heading_->height() <= kIconSize) {
icon_->SetBounds(x, y, kIconSize, kIconSize);
x += kIconSize;
x += kPanelHorizMargin;
heading_->SetX(x);
heading_->SetY(y + (kIconSize - heading_->height()) / 2);
} else {
icon_->SetBounds(x,
y + (heading_->height() - kIconSize) / 2,
kIconSize,
kIconSize);
x += kIconSize;
x += kPanelHorizMargin;
heading_->SetX(x);
heading_->SetY(y);
}
}
ExtensionInstallUI::Delegate* delegate_;
views::ImageView* icon_;
views::Label* heading_;
ExtensionInstallUI::PromptType type_;
DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};
} // namespace
// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
PromptType type) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser) {
delegate->InstallUIAbort();
return;
}
BrowserWindow* window = browser->window();
if (!window) {
delegate->InstallUIAbort();
return;
}
views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
new InstallDialogContent(delegate, extension, icon,
type))->Show();
}
<commit_msg>Use browser::CreateViewsWindow for ExtensionInstallUI.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/views/window.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
class Profile;
namespace {
const int kRightColumnWidth = 210;
const int kIconSize = 69;
// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
public:
InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
Extension* extension, SkBitmap* icon, ExtensionInstallUI::PromptType type)
: delegate_(delegate), icon_(NULL), type_(type) {
// Scale down to icon size, but allow smaller icons (don't scale up).
gfx::Size size(icon->width(), icon->height());
if (size.width() > kIconSize || size.height() > kIconSize)
size = gfx::Size(kIconSize, kIconSize);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
heading_ = new views::Label(
l10n_util::GetStringF(ExtensionInstallUI::kHeadingIds[type_],
UTF8ToWide(extension->name())));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
}
private:
// DialogDelegate
virtual std::wstring GetDialogButtonLabel(
MessageBoxFlags::DialogButton button) const {
switch (button) {
case MessageBoxFlags::DIALOGBUTTON_OK:
return l10n_util::GetString(ExtensionInstallUI::kButtonIds[type_]);
case MessageBoxFlags::DIALOGBUTTON_CANCEL:
return l10n_util::GetString(IDS_CANCEL);
default:
NOTREACHED();
return L"";
}
}
virtual int GetDefaultDialogButton() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
virtual bool Accept() {
delegate_->InstallUIProceed();
return true;
}
virtual bool Cancel() {
delegate_->InstallUIAbort();
return true;
}
// WindowDelegate
virtual bool IsModal() const { return true; }
virtual std::wstring GetWindowTitle() const {
return l10n_util::GetString(ExtensionInstallUI::kTitleIds[type_]);
}
virtual views::View* GetContentsView() { return this; }
// View
virtual gfx::Size GetPreferredSize() {
int width = kRightColumnWidth;
width += kIconSize;
width += kPanelHorizMargin * 3;
int height = kPanelVertMargin * 2;
height += heading_->GetHeightForWidth(kRightColumnWidth);
return gfx::Size(width,
std::max(height, kIconSize + kPanelVertMargin * 2));
}
virtual void Layout() {
int x = kPanelHorizMargin;
int y = kPanelVertMargin;
heading_->SizeToFit(kRightColumnWidth);
if (heading_->height() <= kIconSize) {
icon_->SetBounds(x, y, kIconSize, kIconSize);
x += kIconSize;
x += kPanelHorizMargin;
heading_->SetX(x);
heading_->SetY(y + (kIconSize - heading_->height()) / 2);
} else {
icon_->SetBounds(x,
y + (heading_->height() - kIconSize) / 2,
kIconSize,
kIconSize);
x += kIconSize;
x += kPanelHorizMargin;
heading_->SetX(x);
heading_->SetY(y);
}
}
ExtensionInstallUI::Delegate* delegate_;
views::ImageView* icon_;
views::Label* heading_;
ExtensionInstallUI::PromptType type_;
DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};
} // namespace
// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
PromptType type) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser) {
delegate->InstallUIAbort();
return;
}
BrowserWindow* window = browser->window();
if (!window) {
delegate->InstallUIAbort();
return;
}
browser::CreateViewsWindow(window->GetNativeHandle(), gfx::Rect(),
new InstallDialogContent(delegate, extension, icon,
type))->Show();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
class Profile;
namespace {
// Since apps don't (currently) have any privilege disclosure text, the dialog
// looks a bit empty if it is sized the same as extensions. So we scale
// everything down a bit for apps for the time being.
const int kRightColumnWidthApp = 210;
const int kRightColumnWidthExtension = 270;
const int kIconSizeApp = 69;
const int kIconSizeExtension = 85;
// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
public:
InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
bool is_uninstall)
: delegate_(delegate), icon_(NULL), warning_(NULL),
is_uninstall_(NULL), create_shortcut_(NULL) {
if (extension->IsApp()) {
icon_size_ = kIconSizeApp;
right_column_width_ = kRightColumnWidthApp;
} else {
icon_size_ = kIconSizeExtension;
right_column_width_ = kRightColumnWidthExtension;
}
// Scale down to icon size, but allow smaller icons (don't scale up).
gfx::Size size(icon->width(), icon->height());
if (size.width() > icon_size_ || size.height() > icon_size_)
size = gfx::Size(icon_size_, icon_size_);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
heading_ = new views::Label(
l10n_util::GetStringF(is_uninstall ?
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
UTF8ToWide(extension->name())));
heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
if (!is_uninstall && extension->IsApp()) {
create_shortcut_ = new views::Checkbox(
l10n_util::GetString(IDS_EXTENSION_PROMPT_CREATE_SHORTCUT));
create_shortcut_->SetChecked(true);
create_shortcut_->SetMultiLine(true);
AddChildView(create_shortcut_);
} else {
warning_ = new views::Label(warning_text);
warning_->SetMultiLine(true);
warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(warning_);
}
}
private:
// DialogDelegate
virtual std::wstring GetDialogButtonLabel(
MessageBoxFlags::DialogButton button) const {
switch (button) {
case MessageBoxFlags::DIALOGBUTTON_OK:
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
case MessageBoxFlags::DIALOGBUTTON_CANCEL:
return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
default:
NOTREACHED();
return L"";
}
}
virtual int GetDefaultDialogButton() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
virtual bool Accept() {
delegate_->InstallUIProceed(
create_shortcut_ && create_shortcut_->checked());
return true;
}
virtual bool Cancel() {
delegate_->InstallUIAbort();
return true;
}
// WindowDelegate
virtual bool IsModal() const { return true; }
virtual std::wstring GetWindowTitle() const {
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
else
return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
}
virtual views::View* GetContentsView() { return this; }
// View
virtual gfx::Size GetPreferredSize() {
int width = right_column_width_ + kPanelHorizMargin + kPanelHorizMargin;
width += icon_size_;
width += kPanelHorizMargin;
int height = kPanelVertMargin * 2;
height += heading_->GetHeightForWidth(right_column_width_);
height += kPanelVertMargin;
if (warning_)
height += warning_->GetHeightForWidth(right_column_width_);
else
height += create_shortcut_->GetPreferredSize().height();
height += kPanelVertMargin;
return gfx::Size(width, std::max(height, icon_size_ + kPanelVertMargin * 2));
}
virtual void Layout() {
int x = kPanelHorizMargin;
int y = kPanelVertMargin;
icon_->SetBounds(x, y, icon_size_, icon_size_);
x += icon_size_;
x += kPanelHorizMargin;
heading_->SizeToFit(right_column_width_);
heading_->SetX(x);
heading_->SetY(y);
y += heading_->height();
y += kPanelVertMargin;
if (create_shortcut_) {
create_shortcut_->SetBounds(x, y, right_column_width_, 0);
create_shortcut_->SetBounds(x, y, right_column_width_,
create_shortcut_->GetPreferredSize().height());
int bottom_aligned = icon_->y() + icon_->height() -
create_shortcut_->height();
if (bottom_aligned > y) {
create_shortcut_->SetY(bottom_aligned);
y = bottom_aligned;
}
y += create_shortcut_->height();
} else {
warning_->SizeToFit(right_column_width_);
warning_->SetX(x);
warning_->SetY(y);
y += warning_->height();
}
y += kPanelVertMargin;
}
ExtensionInstallUI::Delegate* delegate_;
views::ImageView* icon_;
views::Label* heading_;
views::Label* warning_;
views::Checkbox* create_shortcut_;
bool is_uninstall_;
int right_column_width_;
int icon_size_;
DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};
} // namespace
// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
const string16& warning_text, bool is_uninstall) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser) {
delegate->InstallUIAbort();
return;
}
BrowserWindow* window = browser->window();
if (!window) {
delegate->InstallUIAbort();
return;
}
views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
new InstallDialogContent(delegate, extension, icon,
UTF16ToWideHack(warning_text),
is_uninstall))->Show();
}
<commit_msg>Fix compile error from 36513.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "base/rand_util.h"
#include "base/string_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/common/extensions/extension.h"
#include "grit/generated_resources.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/controls/link.h"
#include "views/standard_layout.h"
#include "views/view.h"
#include "views/window/dialog_delegate.h"
#include "views/window/window.h"
#if defined(OS_WIN)
#include "app/win_util.h"
#endif
class Profile;
namespace {
// Since apps don't (currently) have any privilege disclosure text, the dialog
// looks a bit empty if it is sized the same as extensions. So we scale
// everything down a bit for apps for the time being.
const int kRightColumnWidthApp = 210;
const int kRightColumnWidthExtension = 270;
const int kIconSizeApp = 69;
const int kIconSizeExtension = 85;
// Implements the extension installation prompt for Windows.
class InstallDialogContent : public views::View, public views::DialogDelegate {
public:
InstallDialogContent(ExtensionInstallUI::Delegate* delegate,
Extension* extension, SkBitmap* icon, const std::wstring& warning_text,
bool is_uninstall)
: delegate_(delegate), icon_(NULL), warning_(NULL),
create_shortcut_(NULL), is_uninstall_(false) {
if (extension->IsApp()) {
icon_size_ = kIconSizeApp;
right_column_width_ = kRightColumnWidthApp;
} else {
icon_size_ = kIconSizeExtension;
right_column_width_ = kRightColumnWidthExtension;
}
// Scale down to icon size, but allow smaller icons (don't scale up).
gfx::Size size(icon->width(), icon->height());
if (size.width() > icon_size_ || size.height() > icon_size_)
size = gfx::Size(icon_size_, icon_size_);
icon_ = new views::ImageView();
icon_->SetImageSize(size);
icon_->SetImage(*icon);
AddChildView(icon_);
heading_ = new views::Label(
l10n_util::GetStringF(is_uninstall ?
IDS_EXTENSION_UNINSTALL_PROMPT_HEADING :
IDS_EXTENSION_INSTALL_PROMPT_HEADING,
UTF8ToWide(extension->name())));
heading_->SetFont(heading_->GetFont().DeriveFont(1, gfx::Font::BOLD));
heading_->SetMultiLine(true);
heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(heading_);
if (!is_uninstall && extension->IsApp()) {
create_shortcut_ = new views::Checkbox(
l10n_util::GetString(IDS_EXTENSION_PROMPT_CREATE_SHORTCUT));
create_shortcut_->SetChecked(true);
create_shortcut_->SetMultiLine(true);
AddChildView(create_shortcut_);
} else {
warning_ = new views::Label(warning_text);
warning_->SetMultiLine(true);
warning_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
AddChildView(warning_);
}
}
private:
// DialogDelegate
virtual std::wstring GetDialogButtonLabel(
MessageBoxFlags::DialogButton button) const {
switch (button) {
case MessageBoxFlags::DIALOGBUTTON_OK:
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON);
else
return l10n_util::GetString(IDS_EXTENSION_PROMPT_INSTALL_BUTTON);
case MessageBoxFlags::DIALOGBUTTON_CANCEL:
return l10n_util::GetString(IDS_EXTENSION_PROMPT_CANCEL_BUTTON);
default:
NOTREACHED();
return L"";
}
}
virtual int GetDefaultDialogButton() const {
return MessageBoxFlags::DIALOGBUTTON_CANCEL;
}
virtual bool Accept() {
delegate_->InstallUIProceed(
create_shortcut_ && create_shortcut_->checked());
return true;
}
virtual bool Cancel() {
delegate_->InstallUIAbort();
return true;
}
// WindowDelegate
virtual bool IsModal() const { return true; }
virtual std::wstring GetWindowTitle() const {
if (is_uninstall_)
return l10n_util::GetString(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
else
return l10n_util::GetString(IDS_EXTENSION_INSTALL_PROMPT_TITLE);
}
virtual views::View* GetContentsView() { return this; }
// View
virtual gfx::Size GetPreferredSize() {
int width = right_column_width_ + kPanelHorizMargin + kPanelHorizMargin;
width += icon_size_;
width += kPanelHorizMargin;
int height = kPanelVertMargin * 2;
height += heading_->GetHeightForWidth(right_column_width_);
height += kPanelVertMargin;
if (warning_)
height += warning_->GetHeightForWidth(right_column_width_);
else
height += create_shortcut_->GetPreferredSize().height();
height += kPanelVertMargin;
return gfx::Size(width, std::max(height, icon_size_ + kPanelVertMargin * 2));
}
virtual void Layout() {
int x = kPanelHorizMargin;
int y = kPanelVertMargin;
icon_->SetBounds(x, y, icon_size_, icon_size_);
x += icon_size_;
x += kPanelHorizMargin;
heading_->SizeToFit(right_column_width_);
heading_->SetX(x);
heading_->SetY(y);
y += heading_->height();
y += kPanelVertMargin;
if (create_shortcut_) {
create_shortcut_->SetBounds(x, y, right_column_width_, 0);
create_shortcut_->SetBounds(x, y, right_column_width_,
create_shortcut_->GetPreferredSize().height());
int bottom_aligned = icon_->y() + icon_->height() -
create_shortcut_->height();
if (bottom_aligned > y) {
create_shortcut_->SetY(bottom_aligned);
y = bottom_aligned;
}
y += create_shortcut_->height();
} else {
warning_->SizeToFit(right_column_width_);
warning_->SetX(x);
warning_->SetY(y);
y += warning_->height();
}
y += kPanelVertMargin;
}
ExtensionInstallUI::Delegate* delegate_;
views::ImageView* icon_;
views::Label* heading_;
views::Label* warning_;
views::Checkbox* create_shortcut_;
bool is_uninstall_;
int right_column_width_;
int icon_size_;
DISALLOW_COPY_AND_ASSIGN(InstallDialogContent);
};
} // namespace
// static
void ExtensionInstallUI::ShowExtensionInstallUIPromptImpl(
Profile* profile, Delegate* delegate, Extension* extension, SkBitmap* icon,
const string16& warning_text, bool is_uninstall) {
Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
if (!browser) {
delegate->InstallUIAbort();
return;
}
BrowserWindow* window = browser->window();
if (!window) {
delegate->InstallUIAbort();
return;
}
views::Window::CreateChromeWindow(window->GetNativeHandle(), gfx::Rect(),
new InstallDialogContent(delegate, extension, icon,
UTF16ToWideHack(warning_text),
is_uninstall))->Show();
}
<|endoftext|>
|
<commit_before>#include "WindowDX.h"
vector<bool> WindowDX::keys;
int WindowDX::mouseDeltaX;
int WindowDX::mouseDeltaY;
HWND WindowDX::hWnd;
WindowDX::WindowDX(HINSTANCE hInstance, int cmdShow)
{
this->hInstance = hInstance;
this->cmdShow = cmdShow;
this->active = true;
keys.resize(NUM_KEYS, false);
SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}
WindowDX::~WindowDX()
{
ReleaseCapture();
ShowCursor(true);
}
LRESULT CALLBACK WindowDX::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}break;
case WM_KEYDOWN:
{
if(wParam == VK_ESCAPE)
{
DestroyWindow(hWnd);
}
keys[wParam] = true;
return 0;
}break;
case WM_KEYUP:
{
keys[wParam] = false;
return 0;
}break;
case WM_MOUSEMOVE:
{
//mouseDeltaMove(lParam);
return 0;
}break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void WindowDX::createWindow()
{
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = "WindowClass";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL,
"WindowClass",
"PACMANIA",
WS_OVERLAPPEDWINDOW,
100,
100,
SCREEN_WIDTH,
SCREEN_HEIGHT,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hWnd, cmdShow);
}
void WindowDX::initCursor()
{
SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
SetCapture(hWnd);
ShowCursor(false);
}
void WindowDX::init()
{
createWindow();
initCursor();
MsgDXWindowHandle* msg = new MsgDXWindowHandle(&hWnd);
Singleton<ObserverDirector>::get().push(msg);
}
void WindowDX::update(double delta)
{
//Returns true if the applications is to be destroyed
//bool quit = false;
MSG msg = {0};
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if(msg.message == WM_QUIT)
active = false;
}
//return quit;
}
HWND WindowDX::getWindowHandle()
{
return hWnd;
}
bool WindowDX::isActive()
{
return active;
}<commit_msg>Added a function mouseDeltaMove that records mouse movement<commit_after>#include "WindowDX.h"
vector<bool> WindowDX::keys;
int WindowDX::mouseDeltaX;
int WindowDX::mouseDeltaY;
HWND WindowDX::hWnd;
WindowDX::WindowDX(HINSTANCE hInstance, int cmdShow)
{
this->hInstance = hInstance;
this->cmdShow = cmdShow;
this->active = true;
keys.resize(NUM_KEYS, false);
SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}
WindowDX::~WindowDX()
{
ReleaseCapture();
ShowCursor(true);
}
void WindowDX::mouseDeltaMove(LPARAM lParam)
{
//Find the upper left corner of the window's client area in screen coordinates
POINT point;
point.x = 0;
point.y = 0;
MapWindowPoints(hWnd, NULL, &point, 1);
//Get current mouse position
int mouseX = GET_X_LPARAM(lParam)+point.x;
int mouseY = GET_Y_LPARAM(lParam)+point.y;
//Calculate relative mouse movement
mouseDeltaX = mouseX - SCREEN_WIDTH/2;
mouseDeltaY = mouseY - SCREEN_HEIGHT/2;
//Return cursor to screen center
SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
}
LRESULT CALLBACK WindowDX::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}break;
case WM_KEYDOWN:
{
if(wParam == VK_ESCAPE)
{
DestroyWindow(hWnd);
}
keys[wParam] = true;
return 0;
}break;
case WM_KEYUP:
{
keys[wParam] = false;
return 0;
}break;
case WM_MOUSEMOVE:
{
mouseDeltaMove(lParam);
return 0;
}break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
void WindowDX::createWindow()
{
WNDCLASSEX wc;
ZeroMemory(&wc, sizeof(WNDCLASSEX));
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = "WindowClass";
RegisterClassEx(&wc);
hWnd = CreateWindowEx(NULL,
"WindowClass",
"PACMANIA",
WS_OVERLAPPEDWINDOW,
100,
100,
SCREEN_WIDTH,
SCREEN_HEIGHT,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hWnd, cmdShow);
}
void WindowDX::initCursor()
{
SetCursorPos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2);
SetCapture(hWnd);
ShowCursor(false);
}
void WindowDX::init()
{
createWindow();
initCursor();
MsgDXWindowHandle* msg = new MsgDXWindowHandle(&hWnd);
Singleton<ObserverDirector>::get().push(msg);
}
void WindowDX::update(double delta)
{
//Returns true if the applications is to be destroyed
//bool quit = false;
MSG msg = {0};
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if(msg.message == WM_QUIT)
active = false;
}
//return quit;
}
HWND WindowDX::getWindowHandle()
{
return hWnd;
}
bool WindowDX::isActive()
{
return active;
}<|endoftext|>
|
<commit_before>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
HadesMem 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.
HadesMem 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 HadesMem. If not, see <http://www.gnu.org/licenses/>.
*/
// Hades
#include "Loader.hpp"
#include "HadesCommon/Logger.hpp"
namespace Hades
{
namespace Kernel
{
Kernel* Loader::m_pKernel = nullptr;
std::shared_ptr<Hades::Memory::PatchDetour> Loader::m_pCreateProcessInternalWHk;
void Loader::Initialize(Kernel& MyKernel)
{
m_pKernel = &MyKernel;
}
void Loader::Hook()
{
HMODULE Kernel32Mod = GetModuleHandle(L"kernel32.dll");
if (!Kernel32Mod)
{
std::error_code const LastError = GetLastErrorCode();
BOOST_THROW_EXCEPTION(Error() <<
ErrorFunction("Loader::Hook") <<
ErrorString("Could not find Kernel32.dll") <<
ErrorCode(LastError));
}
FARPROC const pCreateProcessInternalW = GetProcAddress(Kernel32Mod,
"CreateProcessInternalW");
if (!pCreateProcessInternalW)
{
std::error_code const LastError = GetLastErrorCode();
BOOST_THROW_EXCEPTION(Error() <<
ErrorFunction("Loader::Hook") <<
ErrorString("Could not find Kernel32!CreateProcessInternalW") <<
ErrorCode(LastError));
}
HADES_LOG_THREAD_SAFE(std::wcout << boost::wformat(L"Loader::"
L"Hook: pCreateProcessInternalW = %p.") %pCreateProcessInternalW
<< std::endl);
Memory::MemoryMgr const MyMemory(GetCurrentProcessId());
m_pCreateProcessInternalWHk.reset(new Memory::PatchDetour(MyMemory,
pCreateProcessInternalW, &CreateProcessInternalW_Hook));
m_pCreateProcessInternalWHk->Apply();
}
void Loader::Unhook()
{
if (m_pCreateProcessInternalWHk)
{
m_pCreateProcessInternalWHk->Remove();
}
}
BOOL WINAPI Loader::CreateProcessInternalW_Hook(
HANDLE hToken,
LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
PHANDLE hNewToken)
{
HADES_LOG_THREAD_SAFE(std::wcout <<
"Loader::CreateProcessInternalW_Hook: Called." << std::endl);
typedef BOOL (WINAPI* tCreateProcessInternalW)(
HANDLE hToken,
LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
PHANDLE hNewToken);
auto pCreateProcessInternalW = reinterpret_cast<tCreateProcessInternalW>(
m_pCreateProcessInternalWHk->GetTrampoline());
return pCreateProcessInternalW(hToken, lpApplicationName, lpCommandLine,
lpProcessAttributes, lpThreadAttributes, bInheritHandles,
dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo,
lpProcessInformation, hNewToken);
}
}
}
<commit_msg>* Note to self.<commit_after>/*
This file is part of HadesMem.
Copyright (C) 2010 Joshua Boyce (aka RaptorFactor, Cypherjb, Cypher, Chazwazza).
<http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com>
HadesMem 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.
HadesMem 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 HadesMem. If not, see <http://www.gnu.org/licenses/>.
*/
// Hades
#include "Loader.hpp"
#include "HadesCommon/Logger.hpp"
namespace Hades
{
namespace Kernel
{
// Todo: Hook other process creation APIs such as ShellExecuteEx after
// confirming they don't use already hooked APIs internally.
Kernel* Loader::m_pKernel = nullptr;
std::shared_ptr<Hades::Memory::PatchDetour> Loader::m_pCreateProcessInternalWHk;
void Loader::Initialize(Kernel& MyKernel)
{
m_pKernel = &MyKernel;
}
void Loader::Hook()
{
HMODULE Kernel32Mod = GetModuleHandle(L"kernel32.dll");
if (!Kernel32Mod)
{
std::error_code const LastError = GetLastErrorCode();
BOOST_THROW_EXCEPTION(Error() <<
ErrorFunction("Loader::Hook") <<
ErrorString("Could not find Kernel32.dll") <<
ErrorCode(LastError));
}
FARPROC const pCreateProcessInternalW = GetProcAddress(Kernel32Mod,
"CreateProcessInternalW");
if (!pCreateProcessInternalW)
{
std::error_code const LastError = GetLastErrorCode();
BOOST_THROW_EXCEPTION(Error() <<
ErrorFunction("Loader::Hook") <<
ErrorString("Could not find Kernel32!CreateProcessInternalW") <<
ErrorCode(LastError));
}
HADES_LOG_THREAD_SAFE(std::wcout << boost::wformat(L"Loader::"
L"Hook: pCreateProcessInternalW = %p.") %pCreateProcessInternalW
<< std::endl);
Memory::MemoryMgr const MyMemory(GetCurrentProcessId());
m_pCreateProcessInternalWHk.reset(new Memory::PatchDetour(MyMemory,
pCreateProcessInternalW, &CreateProcessInternalW_Hook));
m_pCreateProcessInternalWHk->Apply();
}
void Loader::Unhook()
{
if (m_pCreateProcessInternalWHk)
{
m_pCreateProcessInternalWHk->Remove();
}
}
BOOL WINAPI Loader::CreateProcessInternalW_Hook(
HANDLE hToken,
LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
PHANDLE hNewToken)
{
HADES_LOG_THREAD_SAFE(std::wcout <<
"Loader::CreateProcessInternalW_Hook: Called." << std::endl);
typedef BOOL (WINAPI* tCreateProcessInternalW)(
HANDLE hToken,
LPCWSTR lpApplicationName,
LPWSTR lpCommandLine,
LPSECURITY_ATTRIBUTES lpProcessAttributes,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
BOOL bInheritHandles,
DWORD dwCreationFlags,
LPVOID lpEnvironment,
LPCWSTR lpCurrentDirectory,
LPSTARTUPINFOW lpStartupInfo,
LPPROCESS_INFORMATION lpProcessInformation,
PHANDLE hNewToken);
auto pCreateProcessInternalW = reinterpret_cast<tCreateProcessInternalW>(
m_pCreateProcessInternalWHk->GetTrampoline());
return pCreateProcessInternalW(hToken, lpApplicationName, lpCommandLine,
lpProcessAttributes, lpThreadAttributes, bInheritHandles,
dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo,
lpProcessInformation, hNewToken);
}
}
}
<|endoftext|>
|
<commit_before>//
// Created by Ulrich Eck on 20/07/16.
//
#ifdef WIN32
#include <utUtil/CleanWindows.h>
#endif
#include <utVision/TextureUpdate.h>
#include <utVision/OpenCLManager.h>
#include <utUtil/Exception.h>
#include <GL/glut.h>
#include <log4cpp/Category.hh>
// get a logger
static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.TextureUpdate" ) );
namespace Ubitrack {
namespace Vision {
bool TextureUpdate::getImageFormat(const Measurement::ImageMeasurement& image, bool use_gpu, int& umatConvertCode,
GLenum& imgFormat, int& numOfChannels)
{
bool ret = true;
switch (image->pixelFormat()) {
case Image::LUMINANCE:
imgFormat = GL_LUMINANCE;
numOfChannels = 1;
break;
case Image::RGB:
numOfChannels = use_gpu ? 4 : 3;
imgFormat = use_gpu ? GL_RGBA : GL_RGB;
umatConvertCode = cv::COLOR_RGB2RGBA;
break;
#ifndef GL_BGR_EXT
case Image::BGR:
imgFormat = image_isOnGPU ? GL_RGBA : GL_RGB;
numOfChannels = use_gpu ? 4 : 3;
umatConvertCode = cv::COLOR_BGR2RGBA;
break;
case Image::BGRA:
numOfChannels = 4;
imgFormat = use_gpu ? GL_RGBA : GL_BGRA;
umatConvertCode = cv::COLOR_BGRA2RGBA;
break;
#else
case Image::BGR:
numOfChannels = use_gpu ? 4 : 3;
imgFormat = use_gpu ? GL_RGBA : GL_BGR_EXT;
umatConvertCode = cv::COLOR_BGR2RGBA;
break;
case Image::BGRA:
numOfChannels = 4;
imgFormat = use_gpu ? GL_RGBA : GL_BGRA_EXT;
umatConvertCode = cv::COLOR_BGRA2RGBA;
break;
#endif
case Image::RGBA:
numOfChannels = 4;
imgFormat = GL_RGBA;
break;
default:
// Log Error ?
ret = false;
break;
}
return ret;
}
void TextureUpdate::cleanupTexture() {
if (m_bTextureInitialized ) {
glBindTexture( GL_TEXTURE_2D, 0 );
glDisable( GL_TEXTURE_2D );
glDeleteTextures( 1, &(m_texture) );
}
}
void TextureUpdate::initializeTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
// access OCL Manager and initialize if needed
Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();
if (!image) {
// LOG4CPP_WARN ??
return;
}
// if OpenCL is enabled and image is on GPU, then use OCL codepath
bool image_isOnGPU = oclManager.isEnabled() & image->isOnGPU();
// find out texture format
int umatConvertCode = -1;
GLenum imgFormat = GL_LUMINANCE;
int numOfChannels = 1;
getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);
if ( !m_bTextureInitialized )
{
// generate power-of-two sizes
m_pow2Width = 1;
while ( m_pow2Width < (unsigned)image->width() )
m_pow2Width <<= 1;
m_pow2Height = 1;
while ( m_pow2Height < (unsigned)image->height() )
m_pow2Height <<= 1;
glGenTextures( 1, &(m_texture) );
glBindTexture( GL_TEXTURE_2D, m_texture );
// define texture parameters
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );
// load empty texture image (defines texture size)
glTexImage2D( GL_TEXTURE_2D, 0, numOfChannels, m_pow2Width, m_pow2Height, 0, imgFormat, GL_UNSIGNED_BYTE, 0 );
LOG4CPP_DEBUG( logger, "glTexImage2D( width=" << m_pow2Width << ", height=" << m_pow2Height << " ): " << glGetError() );
LOG4CPP_INFO( logger, "initalized texture ( " << imgFormat << " ) OnGPU: " << image_isOnGPU);
if (oclManager.isInitialized()) {
#ifdef HAVE_OPENCL
//Get an image Object from the OpenGL texture
cl_int err;
// windows specific or opencl version specific ??
#ifdef WIN32
m_clImage = clCreateFromGLTexture2D( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#else
m_clImage = clCreateFromGLTexture( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#endif
if (err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clCreateFromGLTexture2D:" << err );
}
#endif
}
m_bTextureInitialized = true;
}
#endif // HAVE_OPENCV
}
/*
* Update Texture - requires valid OpenGL Context
*/
void TextureUpdate::updateTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
// access OCL Manager and initialize if needed
Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();
if (!image) {
// LOG4CPP_WARN ??
return;
}
// if OpenCL is enabled and image is on GPU, then use OCL codepath
bool image_isOnGPU = oclManager.isInitialized() & image->isOnGPU();
if ( m_bTextureInitialized )
{
// check if received image fits into the allocated texture
// find out texture format
int umatConvertCode = -1;
GLenum imgFormat = GL_LUMINANCE;
int numOfChannels = 1;
getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);
if (image_isOnGPU) {
#ifdef HAVE_OPENCL
glBindTexture( GL_TEXTURE_2D, m_texture );
if (umatConvertCode != -1) {
cv::cvtColor(image->uMat(), m_convertedImage, umatConvertCode );
} else {
m_convertedImage = image->uMat();
}
cv::ocl::finish();
glFinish();
cl_command_queue commandQueue = oclManager.getCommandQueue();
cl_int err;
clFinish(commandQueue);
err = clEnqueueAcquireGLObjects(commandQueue, 1, &(m_clImage), 0, NULL, NULL);
if(err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clEnqueueAcquireGLObjects:" << err );
}
cl_mem clBuffer = (cl_mem) m_convertedImage.handle(cv::ACCESS_READ);
cl_command_queue cv_ocl_queue = (cl_command_queue)cv::ocl::Queue::getDefault().ptr();
size_t offset = 0;
size_t dst_origin[3] = {0, 0, 0};
size_t region[3] = {static_cast<size_t>(m_convertedImage.cols), static_cast<size_t>(m_convertedImage.rows), 1};
err = clEnqueueCopyBufferToImage(cv_ocl_queue, clBuffer, m_clImage, offset, dst_origin, region, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clEnqueueCopyBufferToImage:" << err );
}
err = clEnqueueReleaseGLObjects(commandQueue, 1, &m_clImage, 0, NULL, NULL);
if(err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clEnqueueReleaseGLObjects:" << err );
}
cv::ocl::finish();
#else // HAVE_OPENCL
LOG4CPP_ERROR( logger, "Image isOnGPU but OpenCL is disabled!!");
#endif // HAVE_OPENCL
} else {
// load image from CPU buffer into texture
glBindTexture( GL_TEXTURE_2D, m_texture );
glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, image->width(), image->height(),
imgFormat, GL_UNSIGNED_BYTE, image->Mat().data );
}
}
#endif // HAVE_OPENCV
}
}} // Ubitrack::Vision<commit_msg>remove glut dependency - was unused<commit_after>//
// Created by Ulrich Eck on 20/07/16.
//
#ifdef WIN32
#include <utUtil/CleanWindows.h>
#endif
#include <utVision/TextureUpdate.h>
#include <utVision/OpenCLManager.h>
#include <utUtil/Exception.h>
#include <log4cpp/Category.hh>
#ifdef _WIN32
#include <GL/gl.h>
#include <GL/glu.h>
#include <utUtil/CleanWindows.h>
#elif __APPLE__
#include <OpenGL/OpenGL.h>
#include <OpenGL/glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#endif
// get a logger
static log4cpp::Category& logger( log4cpp::Category::getInstance( "Ubitrack.Vision.TextureUpdate" ) );
namespace Ubitrack {
namespace Vision {
bool TextureUpdate::getImageFormat(const Measurement::ImageMeasurement& image, bool use_gpu, int& umatConvertCode,
GLenum& imgFormat, int& numOfChannels)
{
bool ret = true;
switch (image->pixelFormat()) {
case Image::LUMINANCE:
imgFormat = GL_LUMINANCE;
numOfChannels = 1;
break;
case Image::RGB:
numOfChannels = use_gpu ? 4 : 3;
imgFormat = use_gpu ? GL_RGBA : GL_RGB;
umatConvertCode = cv::COLOR_RGB2RGBA;
break;
#ifndef GL_BGR_EXT
case Image::BGR:
imgFormat = image_isOnGPU ? GL_RGBA : GL_RGB;
numOfChannels = use_gpu ? 4 : 3;
umatConvertCode = cv::COLOR_BGR2RGBA;
break;
case Image::BGRA:
numOfChannels = 4;
imgFormat = use_gpu ? GL_RGBA : GL_BGRA;
umatConvertCode = cv::COLOR_BGRA2RGBA;
break;
#else
case Image::BGR:
numOfChannels = use_gpu ? 4 : 3;
imgFormat = use_gpu ? GL_RGBA : GL_BGR_EXT;
umatConvertCode = cv::COLOR_BGR2RGBA;
break;
case Image::BGRA:
numOfChannels = 4;
imgFormat = use_gpu ? GL_RGBA : GL_BGRA_EXT;
umatConvertCode = cv::COLOR_BGRA2RGBA;
break;
#endif
case Image::RGBA:
numOfChannels = 4;
imgFormat = GL_RGBA;
break;
default:
// Log Error ?
ret = false;
break;
}
return ret;
}
void TextureUpdate::cleanupTexture() {
if (m_bTextureInitialized ) {
glBindTexture( GL_TEXTURE_2D, 0 );
glDisable( GL_TEXTURE_2D );
glDeleteTextures( 1, &(m_texture) );
}
}
void TextureUpdate::initializeTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
// access OCL Manager and initialize if needed
Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();
if (!image) {
// LOG4CPP_WARN ??
return;
}
// if OpenCL is enabled and image is on GPU, then use OCL codepath
bool image_isOnGPU = oclManager.isEnabled() & image->isOnGPU();
// find out texture format
int umatConvertCode = -1;
GLenum imgFormat = GL_LUMINANCE;
int numOfChannels = 1;
getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);
if ( !m_bTextureInitialized )
{
// generate power-of-two sizes
m_pow2Width = 1;
while ( m_pow2Width < (unsigned)image->width() )
m_pow2Width <<= 1;
m_pow2Height = 1;
while ( m_pow2Height < (unsigned)image->height() )
m_pow2Height <<= 1;
glGenTextures( 1, &(m_texture) );
glBindTexture( GL_TEXTURE_2D, m_texture );
// define texture parameters
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL );
// load empty texture image (defines texture size)
glTexImage2D( GL_TEXTURE_2D, 0, numOfChannels, m_pow2Width, m_pow2Height, 0, imgFormat, GL_UNSIGNED_BYTE, 0 );
LOG4CPP_DEBUG( logger, "glTexImage2D( width=" << m_pow2Width << ", height=" << m_pow2Height << " ): " << glGetError() );
LOG4CPP_INFO( logger, "initalized texture ( " << imgFormat << " ) OnGPU: " << image_isOnGPU);
if (oclManager.isInitialized()) {
#ifdef HAVE_OPENCL
//Get an image Object from the OpenGL texture
cl_int err;
// windows specific or opencl version specific ??
#ifdef WIN32
m_clImage = clCreateFromGLTexture2D( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#else
m_clImage = clCreateFromGLTexture( oclManager.getContext(), CL_MEM_WRITE_ONLY, GL_TEXTURE_2D, 0, m_texture, &err);
#endif
if (err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clCreateFromGLTexture2D:" << err );
}
#endif
}
m_bTextureInitialized = true;
}
#endif // HAVE_OPENCV
}
/*
* Update Texture - requires valid OpenGL Context
*/
void TextureUpdate::updateTexture(const Measurement::ImageMeasurement& image) {
#ifdef HAVE_OPENCV
// access OCL Manager and initialize if needed
Vision::OpenCLManager& oclManager = Vision::OpenCLManager::singleton();
if (!image) {
// LOG4CPP_WARN ??
return;
}
// if OpenCL is enabled and image is on GPU, then use OCL codepath
bool image_isOnGPU = oclManager.isInitialized() & image->isOnGPU();
if ( m_bTextureInitialized )
{
// check if received image fits into the allocated texture
// find out texture format
int umatConvertCode = -1;
GLenum imgFormat = GL_LUMINANCE;
int numOfChannels = 1;
getImageFormat(image, image_isOnGPU, umatConvertCode, imgFormat, numOfChannels);
if (image_isOnGPU) {
#ifdef HAVE_OPENCL
glBindTexture( GL_TEXTURE_2D, m_texture );
if (umatConvertCode != -1) {
cv::cvtColor(image->uMat(), m_convertedImage, umatConvertCode );
} else {
m_convertedImage = image->uMat();
}
cv::ocl::finish();
glFinish();
cl_command_queue commandQueue = oclManager.getCommandQueue();
cl_int err;
clFinish(commandQueue);
err = clEnqueueAcquireGLObjects(commandQueue, 1, &(m_clImage), 0, NULL, NULL);
if(err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clEnqueueAcquireGLObjects:" << err );
}
cl_mem clBuffer = (cl_mem) m_convertedImage.handle(cv::ACCESS_READ);
cl_command_queue cv_ocl_queue = (cl_command_queue)cv::ocl::Queue::getDefault().ptr();
size_t offset = 0;
size_t dst_origin[3] = {0, 0, 0};
size_t region[3] = {static_cast<size_t>(m_convertedImage.cols), static_cast<size_t>(m_convertedImage.rows), 1};
err = clEnqueueCopyBufferToImage(cv_ocl_queue, clBuffer, m_clImage, offset, dst_origin, region, 0, NULL, NULL);
if (err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clEnqueueCopyBufferToImage:" << err );
}
err = clEnqueueReleaseGLObjects(commandQueue, 1, &m_clImage, 0, NULL, NULL);
if(err != CL_SUCCESS)
{
LOG4CPP_ERROR( logger, "error at clEnqueueReleaseGLObjects:" << err );
}
cv::ocl::finish();
#else // HAVE_OPENCL
LOG4CPP_ERROR( logger, "Image isOnGPU but OpenCL is disabled!!");
#endif // HAVE_OPENCL
} else {
// load image from CPU buffer into texture
glBindTexture( GL_TEXTURE_2D, m_texture );
glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, image->width(), image->height(),
imgFormat, GL_UNSIGNED_BYTE, image->Mat().data );
}
}
#endif // HAVE_OPENCV
}
}} // Ubitrack::Vision<|endoftext|>
|
<commit_before>#include "vast/util/configuration.h"
#include <algorithm>
#include <cstring>
#include <iostream>
#include <fstream>
namespace vast {
namespace util {
// TODO: Implement this function.
void configuration::load(std::string const& filename)
{
std::ifstream ifs(filename);
if (! ifs)
throw error::config("could not open configuration file");
verify();
}
void configuration::load(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
{
std::string arg(argv[i]);
if (arg.size() < 2)
{
throw error::config("ill-formed option specificiation", argv[i]);
}
else if (arg.size() == 2)
{
// Argument must be of the form '-*'.
if (arg[0] != '-')
throw error::config("ill-formed option specificiation", argv[i]);
arg = arg[1];
auto s = shortcuts_.find(arg);
if (s == shortcuts_.end())
throw error::config("unknown short option", arg[0]);
arg = s->second;
}
else
{
// Argument must be of the form '--*'.
if (! (arg[0] == '-' && arg[1] == '-'))
throw error::config("ill-formed option specification", argv[i]);
arg = arg.substr(2);
}
auto o = find_option(arg);
if (! o)
throw error::config("unknown option", arg);
o->defaulted_ = false;
std::vector<std::string> values;
while (i + 1 < argc && std::strlen(argv[i + 1]) > 0 && argv[i + 1][0] != '-')
values.emplace_back(argv[++i]);
if (values.size() > o->max_vals_)
throw error::config("too many values", arg);
if (o->max_vals_ == 1 && values.size() != 1)
throw error::config("option value required", arg);
if (! values.empty())
o->values_ = std::move(values);
}
verify();
}
bool configuration::check(std::string const& opt) const
{
auto o = find_option(opt);
return o && ! o->defaulted_;
}
std::string const& configuration::get(char const* opt) const
{
auto o = find_option(opt);
if (! o)
throw error::config("invalid option cast", opt);
if (o->values().empty())
throw error::config("option has no value", opt);
if (o->max_vals_ > 1)
throw error::config("cannot get multi-value option", opt);
return o->values_[0];
}
void configuration::usage(std::ostream& sink, bool show_all)
{
sink << banner_ << "\n";
for (auto& b : blocks_)
{
if (! show_all && ! b.visible_)
continue;
sink << "\n " << b.name_ << ":\n";
auto has_shortcut = std::any_of(
b.options_.begin(),
b.options_.end(),
[](option const& o) { return o.shortcut_ != '\0'; });
auto max = std::max_element(
b.options_.begin(),
b.options_.end(),
[](option const& o1, option const& o2)
{
return o1.name_.size() < o2.name_.size();
});
auto max_len = max->name_.size();
for (auto& opt : b.options_)
{
sink << " --" << opt.name_;
sink << std::string(max_len - opt.name_.size(), ' ');
if (has_shortcut)
sink << (opt.shortcut_ ? std::string(" | -") + opt.shortcut_ : " ");
sink << " " << opt.description_ << "\n";
}
}
sink << std::endl;
}
configuration::option::option(std::string name,
std::string desc, char shortcut)
: name_(std::move(name)),
description_(std::move(desc)),
shortcut_(shortcut)
{
}
configuration::option& configuration::option::multi(size_t n)
{
max_vals_ = n;
return *this;
}
configuration::option& configuration::option::single()
{
return multi(1);
}
std::vector<std::string> const& configuration::option::values() const
{
return values_;
}
configuration::block::block(block&& other)
: visible_(other.visible_),
name_(std::move(other.name_)),
prefix_(std::move(other.prefix_)),
options_(std::move(other.options_)),
config_(other.config_)
{
other.visible_ = true;
other.config_ = nullptr;
}
configuration::option&
configuration::block::add(std::string name, std::string desc)
{
std::string fqn = qualify(name);
if (config_->find_option(fqn))
throw error::config("option already exists", std::move(fqn));
options_.emplace_back(std::move(fqn), std::move(desc));
return options_.back();
}
configuration::option&
configuration::block::add(char shortcut, std::string name, std::string desc)
{
if (config_->shortcuts_.count({shortcut}))
throw error::config("option shortcut already exists", shortcut);
config_->shortcuts_.insert({{shortcut}, std::move(qualify(name))});
std::string fqn = qualify(name);
if (config_->find_option(fqn))
throw error::config("option already exists", std::move(fqn));
options_.emplace_back(std::move(fqn), std::move(desc), shortcut);
return options_.back();
}
configuration::block& configuration::create_block(std::string name,
std::string prefix)
{
block b(std::move(name), std::move(prefix), this);
blocks_.push_back(std::move(b));
return blocks_.back();
}
bool configuration::block::visible() const
{
return visible_;
}
void configuration::block::visible(bool flag)
{
visible_ = flag;
}
configuration::block::block(std::string name,
std::string prefix,
configuration* config)
: name_(std::move(name)),
prefix_(std::move(prefix)),
config_(config)
{
}
std::string configuration::block::qualify(std::string const& name) const
{
return ! prefix_.empty() ? prefix_ + separator + name : name;
}
void configuration::conflicts(std::string const& opt1, std::string const& opt2) const
{
if (check(opt1) && check(opt2))
throw error::config("conflicting options", opt1, opt2);
}
void configuration::depends(std::string const& needy, std::string const& required) const
{
if (check(needy) && ! check(required))
throw error::config("missing option dependency", needy, required);
}
void configuration::banner(std::string banner)
{
banner_ = std::move(banner);
}
void configuration::verify()
{
// The default implementation doesn't do anything.
}
configuration::option*
configuration::find_option(std::string const& opt)
{
for (auto& b : blocks_)
for (size_t i = 0; i < b.options_.size(); ++i)
if (b.options_[i].name_ == opt)
return &b.options_[i];
return nullptr;
}
configuration::option const*
configuration::find_option(std::string const& opt) const
{
for (auto& b : blocks_)
for (size_t i = 0; i < b.options_.size(); ++i)
if (b.options_[i].name_ == opt)
return &b.options_[i];
return nullptr;
}
} // namespace util
} // namespace vast
<commit_msg>Allow omitting whitespace for short options.<commit_after>#include "vast/util/configuration.h"
#include <algorithm>
#include <cstring>
#include <iostream>
#include <fstream>
namespace vast {
namespace util {
// TODO: Implement this function.
void configuration::load(std::string const& filename)
{
std::ifstream ifs(filename);
if (! ifs)
throw error::config("could not open configuration file");
verify();
}
void configuration::load(int argc, char *argv[])
{
for (int i = 1; i < argc; ++i)
{
std::vector<std::string> values;
std::string arg(argv[i]);
if (arg.size() < 2)
{
throw error::config("ill-formed option specificiation", argv[i]);
}
else if (arg[0] == '-' && arg[1] == '-')
{
// Argument must begin with '--'.
if (arg.size() == 2)
throw error::config("ill-formed option specification", argv[i]);
arg = arg.substr(2);
}
else if (arg[0] == '-')
{
if (arg.size() > 2)
// The short option comes with a value.
values.push_back(arg.substr(2));
arg = arg[1];
auto s = shortcuts_.find(arg);
if (s == shortcuts_.end())
throw error::config("unknown short option", arg[0]);
arg = s->second;
}
auto o = find_option(arg);
if (! o)
throw error::config("unknown option", arg);
o->defaulted_ = false;
while (i + 1 < argc && std::strlen(argv[i + 1]) > 0 && argv[i + 1][0] != '-')
values.emplace_back(argv[++i]);
if (values.size() > o->max_vals_)
throw error::config("too many values", arg);
if (o->max_vals_ == 1 && values.size() != 1)
throw error::config("option value required", arg);
if (! values.empty())
o->values_ = std::move(values);
}
verify();
}
bool configuration::check(std::string const& opt) const
{
auto o = find_option(opt);
return o && ! o->defaulted_;
}
std::string const& configuration::get(char const* opt) const
{
auto o = find_option(opt);
if (! o)
throw error::config("invalid option cast", opt);
if (o->values().empty())
throw error::config("option has no value", opt);
if (o->max_vals_ > 1)
throw error::config("cannot get multi-value option", opt);
return o->values_[0];
}
void configuration::usage(std::ostream& sink, bool show_all)
{
sink << banner_ << "\n";
for (auto& b : blocks_)
{
if (! show_all && ! b.visible_)
continue;
sink << "\n " << b.name_ << ":\n";
auto has_shortcut = std::any_of(
b.options_.begin(),
b.options_.end(),
[](option const& o) { return o.shortcut_ != '\0'; });
auto max = std::max_element(
b.options_.begin(),
b.options_.end(),
[](option const& o1, option const& o2)
{
return o1.name_.size() < o2.name_.size();
});
auto max_len = max->name_.size();
for (auto& opt : b.options_)
{
sink << " --" << opt.name_;
sink << std::string(max_len - opt.name_.size(), ' ');
if (has_shortcut)
sink << (opt.shortcut_ ? std::string(" | -") + opt.shortcut_ : " ");
sink << " " << opt.description_ << "\n";
}
}
sink << std::endl;
}
configuration::option::option(std::string name,
std::string desc, char shortcut)
: name_(std::move(name)),
description_(std::move(desc)),
shortcut_(shortcut)
{
}
configuration::option& configuration::option::multi(size_t n)
{
max_vals_ = n;
return *this;
}
configuration::option& configuration::option::single()
{
return multi(1);
}
std::vector<std::string> const& configuration::option::values() const
{
return values_;
}
configuration::block::block(block&& other)
: visible_(other.visible_),
name_(std::move(other.name_)),
prefix_(std::move(other.prefix_)),
options_(std::move(other.options_)),
config_(other.config_)
{
other.visible_ = true;
other.config_ = nullptr;
}
configuration::option&
configuration::block::add(std::string name, std::string desc)
{
std::string fqn = qualify(name);
if (config_->find_option(fqn))
throw error::config("option already exists", std::move(fqn));
options_.emplace_back(std::move(fqn), std::move(desc));
return options_.back();
}
configuration::option&
configuration::block::add(char shortcut, std::string name, std::string desc)
{
if (config_->shortcuts_.count({shortcut}))
throw error::config("option shortcut already exists", shortcut);
config_->shortcuts_.insert({{shortcut}, std::move(qualify(name))});
std::string fqn = qualify(name);
if (config_->find_option(fqn))
throw error::config("option already exists", std::move(fqn));
options_.emplace_back(std::move(fqn), std::move(desc), shortcut);
return options_.back();
}
configuration::block& configuration::create_block(std::string name,
std::string prefix)
{
block b(std::move(name), std::move(prefix), this);
blocks_.push_back(std::move(b));
return blocks_.back();
}
bool configuration::block::visible() const
{
return visible_;
}
void configuration::block::visible(bool flag)
{
visible_ = flag;
}
configuration::block::block(std::string name,
std::string prefix,
configuration* config)
: name_(std::move(name)),
prefix_(std::move(prefix)),
config_(config)
{
}
std::string configuration::block::qualify(std::string const& name) const
{
return ! prefix_.empty() ? prefix_ + separator + name : name;
}
void configuration::conflicts(std::string const& opt1, std::string const& opt2) const
{
if (check(opt1) && check(opt2))
throw error::config("conflicting options", opt1, opt2);
}
void configuration::depends(std::string const& needy, std::string const& required) const
{
if (check(needy) && ! check(required))
throw error::config("missing option dependency", needy, required);
}
void configuration::banner(std::string banner)
{
banner_ = std::move(banner);
}
void configuration::verify()
{
// The default implementation doesn't do anything.
}
configuration::option*
configuration::find_option(std::string const& opt)
{
for (auto& b : blocks_)
for (size_t i = 0; i < b.options_.size(); ++i)
if (b.options_[i].name_ == opt)
return &b.options_[i];
return nullptr;
}
configuration::option const*
configuration::find_option(std::string const& opt) const
{
for (auto& b : blocks_)
for (size_t i = 0; i < b.options_.size(); ++i)
if (b.options_[i].name_ == opt)
return &b.options_[i];
return nullptr;
}
} // namespace util
} // namespace vast
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.