text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "Config.h"
#include "common/FileNameTools.h"
#include <fstream>
namespace d2d
{
Config* Config::m_instance = NULL;
const char* FILENAME = "config.json";
Config::Config()
{
m_use_dtex = true;
}
Config* Config::Instance()
{
if (!m_instance)
{
m_instance = new Config();
if (FilenameTools::isExist(FILENAME)) {
m_instance->LoadFromFile(FILENAME);
}
}
return m_instance;
}
void Config::GetStrings(const std::string& key,
std::vector<std::string>& val) const
{
Json::Value str_list = m_value[key];
if (!str_list.isNull())
{
int i = 0;
Json::Value str = str_list[i++];
while (!str.isNull()) {
val.push_back(str.asString());
str = str_list[i++];
}
}
}
void Config::LoadFromFile(const char* filename)
{
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filename);
std::locale::global(std::locale("C"));
reader.parse(fin, m_value);
fin.close();
m_use_dtex = m_value["use_dtex"].asBool();
}
}<commit_msg>[CHANGED] 默认关闭dtex<commit_after>#include "Config.h"
#include "common/FileNameTools.h"
#include <fstream>
namespace d2d
{
Config* Config::m_instance = NULL;
const char* FILENAME = "config.json";
Config::Config()
{
m_use_dtex = false;
}
Config* Config::Instance()
{
if (!m_instance)
{
m_instance = new Config();
if (FilenameTools::isExist(FILENAME)) {
m_instance->LoadFromFile(FILENAME);
}
}
return m_instance;
}
void Config::GetStrings(const std::string& key,
std::vector<std::string>& val) const
{
Json::Value str_list = m_value[key];
if (!str_list.isNull())
{
int i = 0;
Json::Value str = str_list[i++];
while (!str.isNull()) {
val.push_back(str.asString());
str = str_list[i++];
}
}
}
void Config::LoadFromFile(const char* filename)
{
Json::Reader reader;
std::locale::global(std::locale(""));
std::ifstream fin(filename);
std::locale::global(std::locale("C"));
reader.parse(fin, m_value);
fin.close();
m_use_dtex = m_value["use_dtex"].asBool();
}
}<|endoftext|>
|
<commit_before><commit_msg>[drape] [tracks] Allow to render tracks for 20 zoomLevel MAPSME-12900<commit_after><|endoftext|>
|
<commit_before>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* local */
#include "stateval/StateMachineThread.h"
#include "stateval/StateMachine.h"
#include "Logger.h"
/* STD */
#include <iostream>
#include <string>
#include <map>
#include <cassert>
using namespace std;
static Logger logger ("stateval.StateMachineThread");
StateMachineThread::StateMachineThread (StateMachine &sm) :
Threading::Thread(),
mEventMutex(),
mEventsInQueue(),
mSM(&sm),
mSignalList(),
mSignalBroadcast()
{
}
StateMachineThread::~StateMachineThread ()
{
LOG4CXX_TRACE (logger, "~StateMachineThread");
cancel ();
}
void StateMachineThread::start ()
{
LOG4CXX_TRACE (logger, "+StateMachineThread::start ()");
Thread::start();
LOG4CXX_TRACE (logger, "-StateMachineThread::start ()");
}
void StateMachineThread::signal_cancel() // from thread
{
mEventsInQueue.signal ();
}
void StateMachineThread::run ()
{
LOG4CXX_TRACE (logger, "+run");
while (isRunning())
{
LOG4CXX_TRACE (logger, "+run::running while");
mEventMutex.lock ();
// this waiting loop runs until someone pushed an event to the event queue
while (mSM->eventQueue.empty())
{
LOG4CXX_TRACE (logger, "!mSM->eventQueue.empty()");
// here is the point the loop waits if no event is in the event queue
mEventsInQueue.wait (mEventMutex);
if (!isRunning())
{
mEventMutex.unlock ();
LOG4CXX_TRACE (logger, "!isRunning()");
return;
}
}
LOG4CXX_TRACE (logger, "mSM->eventQueue.empty()");
int event = mSM->eventQueue.front();
mEventMutex.unlock ();
LOG4CXX_DEBUG (logger, "EventQueue size: " << mSM->eventQueue.size ());
mSM->evaluateState (event);
// pop element after working
LOG4CXX_DEBUG (logger, "EventQueue size: " << mSM->eventQueue.size ());
// emit event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// emit also multible signals...
for ( ; findResult != lastElement; ++findResult)
{
LOG4CXX_DEBUG (logger, "call event '" << event << "' to app");
SignalSignal *signal = (*findResult).second;
signal->emit (event);
}
}
LOG4CXX_TRACE (logger, "-run::running while");
// emit the signal broadcast
// this is e.g. useful to dispatch signals to another thread
mSignalBroadcast.emit (event);
mEventMutex.lock ();
mSM->popEvent ();
mEventMutex.unlock ();
LOG4CXX_TRACE (logger, "-run");
}
}
void StateMachineThread::pushEvent (int event)
{
mEventMutex.lock ();
mSM->pushEvent (event);
mEventsInQueue.signal ();
mEventMutex.unlock ();
}
void StateMachineThread::pushEvent (const std::string &event)
{
pushEvent (mSM->findMapingEvent (event));
}
void StateMachineThread::connect (int event, const SignalSlot& slot)
{
SignalSignal* signal = new SignalSignal();
mSignalList.insert (pair <int, SignalSignal*> (event, signal));
signal->connect (slot);
}
void StateMachineThread::connect (const SignalSlot& slot)
{
mSignalBroadcast.connect (slot);
}
void StateMachineThread::disconnect (int event)
{
// delete event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// delete all connected handlers
for ( ; findResult != lastElement; ++findResult)
{
SignalSignal *signal = findResult->second;
delete signal;
// TODO from hdusel: Forget to remove the element from the multimap?
// Discuss this with Andreas.
}
}
}
void StateMachineThread::disconnectAll ()
{
for (std::multimap <int, SignalSignal*>::iterator s_it = mSignalList.begin ();
s_it != mSignalList.end ();
++s_it)
{
int event = (*s_it).first;
SignalSignal *signal = (*s_it).second;
delete signal;
}
}
<commit_msg>logging cosmetic<commit_after>#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* local */
#include "stateval/StateMachineThread.h"
#include "stateval/StateMachine.h"
#include "Logger.h"
/* STD */
#include <iostream>
#include <string>
#include <map>
#include <cassert>
using namespace std;
static Logger logger ("stateval.StateMachineThread");
StateMachineThread::StateMachineThread (StateMachine &sm) :
Threading::Thread(),
mEventMutex(),
mEventsInQueue(),
mSM(&sm),
mSignalList(),
mSignalBroadcast()
{
}
StateMachineThread::~StateMachineThread ()
{
LOG4CXX_TRACE (logger, "~StateMachineThread");
cancel ();
LOG4CXX_TRACE (logger, "~StateMachineThread (canceled)");
join ();
LOG4CXX_TRACE (logger, "~StateMachineThread (joined)");
}
void StateMachineThread::start ()
{
LOG4CXX_TRACE (logger, "+StateMachineThread::start ()");
Thread::start();
LOG4CXX_TRACE (logger, "-StateMachineThread::start ()");
}
void StateMachineThread::signal_cancel() // from thread
{
mEventsInQueue.signal ();
}
void StateMachineThread::run ()
{
LOG4CXX_TRACE (logger, "+run");
while (isRunning())
{
LOG4CXX_TRACE (logger, "+run::running while");
mEventMutex.lock ();
// this waiting loop runs until someone pushed an event to the event queue
while (mSM->eventQueue.empty())
{
LOG4CXX_TRACE (logger, "!mSM->eventQueue.empty()");
// here is the point the loop waits if no event is in the event queue
mEventsInQueue.wait (mEventMutex);
if (!isRunning())
{
mEventMutex.unlock ();
LOG4CXX_TRACE (logger, "!isRunning()");
return;
}
}
LOG4CXX_TRACE (logger, "mSM->eventQueue.empty()");
int event = mSM->eventQueue.front();
mEventMutex.unlock ();
LOG4CXX_DEBUG (logger, "+EventQueue size: " << mSM->eventQueue.size ());
mSM->evaluateState (event);
// pop element after working
LOG4CXX_DEBUG (logger, "-EventQueue size: " << mSM->eventQueue.size ());
// emit event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// emit also multible signals...
for ( ; findResult != lastElement; ++findResult)
{
LOG4CXX_DEBUG (logger, "call event '" << event << "' to app");
SignalSignal *signal = (*findResult).second;
signal->emit (event);
}
}
LOG4CXX_TRACE (logger, "-run::running while");
// emit the signal broadcast
// this is e.g. useful to dispatch signals to another thread
mSignalBroadcast.emit (event);
mEventMutex.lock ();
mSM->popEvent ();
mEventMutex.unlock ();
LOG4CXX_TRACE (logger, "-run");
}
}
void StateMachineThread::pushEvent (int event)
{
mEventMutex.lock ();
mSM->pushEvent (event);
mEventsInQueue.signal ();
mEventMutex.unlock ();
}
void StateMachineThread::pushEvent (const std::string &event)
{
pushEvent (mSM->findMapingEvent (event));
}
void StateMachineThread::connect (int event, const SignalSlot& slot)
{
SignalSignal* signal = new SignalSignal();
mSignalList.insert (pair <int, SignalSignal*> (event, signal));
signal->connect (slot);
}
void StateMachineThread::connect (const SignalSlot& slot)
{
mSignalBroadcast.connect (slot);
}
void StateMachineThread::disconnect (int event)
{
// delete event signals
multimap <int, SignalSignal*>::iterator findResult = mSignalList.find (event);
multimap <int, SignalSignal*>::iterator lastElement = mSignalList.upper_bound (event);
if (findResult != mSignalList.end ())
{
// delete all connected handlers
for ( ; findResult != lastElement; ++findResult)
{
SignalSignal *signal = findResult->second;
delete signal;
// TODO from hdusel: Forget to remove the element from the multimap?
// Discuss this with Andreas.
}
}
}
void StateMachineThread::disconnectAll ()
{
for (std::multimap <int, SignalSignal*>::iterator s_it = mSignalList.begin ();
s_it != mSignalList.end ();
++s_it)
{
int event = (*s_it).first;
SignalSignal *signal = (*s_it).second;
delete signal;
}
}
<|endoftext|>
|
<commit_before>/**
* \file
* \brief SpiMasterLowLevelInterruptBased class header for SPIv2 in STM32
*
* \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_SPIMASTERLOWLEVELINTERRUPTBASED_HPP_
#define SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_SPIMASTERLOWLEVELINTERRUPTBASED_HPP_
#include "distortos/devices/communication/SpiMasterLowLevel.hpp"
namespace distortos
{
namespace chip
{
class SpiPeripheral;
/**
* SpiMasterLowLevelInterruptBased class is a low-level SPI master driver for SPIv2 in STM32.
*
* This driver uses interrupts for data transfers.
*
* \ingroup devices
*/
class SpiMasterLowLevelInterruptBased : public devices::SpiMasterLowLevel
{
public:
/**
* \brief SpiMasterLowLevelInterruptBased's constructor
*
* \param [in] spiPeripheral is a reference to raw SPI peripheral
*/
constexpr explicit SpiMasterLowLevelInterruptBased(const SpiPeripheral& spiPeripheral) :
spiPeripheral_{spiPeripheral},
spiMasterBase_{},
readBuffer_{},
writeBuffer_{},
size_{},
readPosition_{},
writePosition_{},
dummyData_{},
started_{},
wordLength_{8}
{
}
/**
* \brief SpiMasterLowLevel's destructor
*
* Does nothing if driver is already stopped. If it's not, performs forced stop of operation.
*/
~SpiMasterLowLevelInterruptBased() override;
/**
* \brief Configures parameters of low-level SPI master driver.
*
* \param [in] mode is the desired SPI mode
* \param [in] clockFrequency is the desired clock frequency, Hz
* \param [in] wordLength selects word length, bits, [4; 16] or [minSpiWordLength; maxSpiWordLength]
* \param [in] lsbFirst selects whether MSB (false) or LSB (true) is transmitted first
* \param [in] dummyData is the dummy data that will be sent if write buffer of transfer is nullptr
*
* \return pair with return code (0 on success, error code otherwise) and real clock frequency; error codes:
* - EBADF - the driver is not started;
* - EBUSY - transfer is in progress;
* - error codes returned by configureSpi();
*/
std::pair<int, uint32_t> configure(devices::SpiMode mode, uint32_t clockFrequency, uint8_t wordLength,
bool lsbFirst, uint32_t dummyData) override;
/**
* \brief Interrupt handler
*
* \note this must not be called by user code
*/
void interruptHandler();
/**
* \brief Starts low-level SPI master driver.
*
* \return 0 on success, error code otherwise:
* - EBADF - the driver is not stopped;
*/
int start() override;
/**
* \brief Starts asynchronous transfer.
*
* This function returns immediately. When the transfer is physically finished (either expected number of bytes were
* written and read or an error was detected), SpiMasterBase::transferCompleteEvent() will be executed.
*
* \param [in] spiMasterBase is a reference to SpiMasterBase object that will be notified about completed transfer
* \param [in] writeBuffer is the buffer with data that will be written, nullptr to send dummy data
* \param [out] readBuffer is the buffer with data that will be read, nullptr to ignore received data
* \param [in] size is the size of transfer (size of \a writeBuffer and/or \a readBuffer), bytes, must be even if
* number of data bits is in range (8; 16], divisible by 3 if number of data bits is in range (16; 24] or divisible
* by 4 if number of data bits is in range (24; 32]
*
* \return 0 on success, error code otherwise:
* - EBADF - the driver is not started;
* - EBUSY - transfer is in progress;
* - EINVAL - \a size is invalid;
*/
int startTransfer(devices::SpiMasterBase& spiMasterBase, const void* writeBuffer, void* readBuffer,
size_t size) override;
/**
* \brief Stops low-level SPI master driver.
*
* \return 0 on success, error code otherwise:
* - EBADF - the driver is not started;
* - EBUSY - transfer is in progress;
*/
int stop() override;
private:
/**
* \return true if driver is started, false otherwise
*/
bool isStarted() const
{
return started_;
}
/**
* \return true if transfer is in progress, false otherwise
*/
bool isTransferInProgress() const
{
return size_ != 0;
}
/**
* \brief Writes next item to SPI peripheral.
*/
void writeNextItem();
/// reference to raw SPI peripheral
const SpiPeripheral& spiPeripheral_;
/// pointer to SpiMasterBase object associated with this one
devices::SpiMasterBase* volatile spiMasterBase_;
/// buffer to which the data is being written, nullptr to ignore received data
uint8_t* volatile readBuffer_;
/// buffer with data that is being transmitted, nullptr to send dummy data
const uint8_t* volatile writeBuffer_;
/// size of transfer (size of \a readBuffer_ and/or \a writeBuffer_), bytes
volatile size_t size_;
/// current position in \a readBuffer_
volatile size_t readPosition_;
/// current position in \a writeBuffer_
volatile size_t writePosition_;
/// dummy data that will be sent if write buffer of transfer is nullptr
uint16_t dummyData_;
/// true if driver is started, false otherwise
bool started_;
/// selected word length, bits, {8, 16}
uint8_t wordLength_;
};
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_SPIMASTERLOWLEVELINTERRUPTBASED_HPP_
<commit_msg>Fix comment in STM32 SPIv2 SpiMasterLowLevelInterruptBased<commit_after>/**
* \file
* \brief SpiMasterLowLevelInterruptBased class header for SPIv2 in STM32
*
* \author Copyright (C) 2016-2018 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_SPIMASTERLOWLEVELINTERRUPTBASED_HPP_
#define SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_SPIMASTERLOWLEVELINTERRUPTBASED_HPP_
#include "distortos/devices/communication/SpiMasterLowLevel.hpp"
namespace distortos
{
namespace chip
{
class SpiPeripheral;
/**
* SpiMasterLowLevelInterruptBased class is a low-level SPI master driver for SPIv2 in STM32.
*
* This driver uses interrupts for data transfers.
*
* \ingroup devices
*/
class SpiMasterLowLevelInterruptBased : public devices::SpiMasterLowLevel
{
public:
/**
* \brief SpiMasterLowLevelInterruptBased's constructor
*
* \param [in] spiPeripheral is a reference to raw SPI peripheral
*/
constexpr explicit SpiMasterLowLevelInterruptBased(const SpiPeripheral& spiPeripheral) :
spiPeripheral_{spiPeripheral},
spiMasterBase_{},
readBuffer_{},
writeBuffer_{},
size_{},
readPosition_{},
writePosition_{},
dummyData_{},
started_{},
wordLength_{8}
{
}
/**
* \brief SpiMasterLowLevelInterruptBased's destructor
*
* Does nothing if driver is already stopped. If it's not, performs forced stop of operation.
*/
~SpiMasterLowLevelInterruptBased() override;
/**
* \brief Configures parameters of low-level SPI master driver.
*
* \param [in] mode is the desired SPI mode
* \param [in] clockFrequency is the desired clock frequency, Hz
* \param [in] wordLength selects word length, bits, [4; 16] or [minSpiWordLength; maxSpiWordLength]
* \param [in] lsbFirst selects whether MSB (false) or LSB (true) is transmitted first
* \param [in] dummyData is the dummy data that will be sent if write buffer of transfer is nullptr
*
* \return pair with return code (0 on success, error code otherwise) and real clock frequency; error codes:
* - EBADF - the driver is not started;
* - EBUSY - transfer is in progress;
* - error codes returned by configureSpi();
*/
std::pair<int, uint32_t> configure(devices::SpiMode mode, uint32_t clockFrequency, uint8_t wordLength,
bool lsbFirst, uint32_t dummyData) override;
/**
* \brief Interrupt handler
*
* \note this must not be called by user code
*/
void interruptHandler();
/**
* \brief Starts low-level SPI master driver.
*
* \return 0 on success, error code otherwise:
* - EBADF - the driver is not stopped;
*/
int start() override;
/**
* \brief Starts asynchronous transfer.
*
* This function returns immediately. When the transfer is physically finished (either expected number of bytes were
* written and read or an error was detected), SpiMasterBase::transferCompleteEvent() will be executed.
*
* \param [in] spiMasterBase is a reference to SpiMasterBase object that will be notified about completed transfer
* \param [in] writeBuffer is the buffer with data that will be written, nullptr to send dummy data
* \param [out] readBuffer is the buffer with data that will be read, nullptr to ignore received data
* \param [in] size is the size of transfer (size of \a writeBuffer and/or \a readBuffer), bytes, must be even if
* number of data bits is in range (8; 16], divisible by 3 if number of data bits is in range (16; 24] or divisible
* by 4 if number of data bits is in range (24; 32]
*
* \return 0 on success, error code otherwise:
* - EBADF - the driver is not started;
* - EBUSY - transfer is in progress;
* - EINVAL - \a size is invalid;
*/
int startTransfer(devices::SpiMasterBase& spiMasterBase, const void* writeBuffer, void* readBuffer,
size_t size) override;
/**
* \brief Stops low-level SPI master driver.
*
* \return 0 on success, error code otherwise:
* - EBADF - the driver is not started;
* - EBUSY - transfer is in progress;
*/
int stop() override;
private:
/**
* \return true if driver is started, false otherwise
*/
bool isStarted() const
{
return started_;
}
/**
* \return true if transfer is in progress, false otherwise
*/
bool isTransferInProgress() const
{
return size_ != 0;
}
/**
* \brief Writes next item to SPI peripheral.
*/
void writeNextItem();
/// reference to raw SPI peripheral
const SpiPeripheral& spiPeripheral_;
/// pointer to SpiMasterBase object associated with this one
devices::SpiMasterBase* volatile spiMasterBase_;
/// buffer to which the data is being written, nullptr to ignore received data
uint8_t* volatile readBuffer_;
/// buffer with data that is being transmitted, nullptr to send dummy data
const uint8_t* volatile writeBuffer_;
/// size of transfer (size of \a readBuffer_ and/or \a writeBuffer_), bytes
volatile size_t size_;
/// current position in \a readBuffer_
volatile size_t readPosition_;
/// current position in \a writeBuffer_
volatile size_t writePosition_;
/// dummy data that will be sent if write buffer of transfer is nullptr
uint16_t dummyData_;
/// true if driver is started, false otherwise
bool started_;
/// selected word length, bits, [4; 16] or [minSpiWordLength; maxSpiWordLength]
uint8_t wordLength_;
};
} // namespace chip
} // namespace distortos
#endif // SOURCE_CHIP_STM32_PERIPHERALS_SPIV2_INCLUDE_DISTORTOS_CHIP_SPIMASTERLOWLEVELINTERRUPTBASED_HPP_
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: generatedtypeset.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 02:06:16 $
*
* 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 INCLUDED_codemaker_generatedtypeset_hxx
#define INCLUDED_codemaker_generatedtypeset_hxx
#include "rtl/string.hxx"
#include <hash_set>
/// @HTML
namespace codemaker {
/**
A simple class to track which types have already been processed by a code
maker.
<p>This class is not multi-thread–safe.</p>
*/
class GeneratedTypeSet {
public:
GeneratedTypeSet() {}
~GeneratedTypeSet() {}
/**
Add a type to the set of generated types.
<p>If the type was already present, nothing happens.</p>
@param type a UNO type registry name
*/
void add(rtl::OString const & type) { m_set.insert(type); }
/**
Checks whether a given type has already been generated.
@param type a UNO type registry name
@return true iff the given type has already been generated
*/
bool contains(rtl::OString const & type) const
{ return m_set.find(type) != m_set.end(); }
private:
GeneratedTypeSet(GeneratedTypeSet &); // not implemented
void operator =(GeneratedTypeSet); // not implemented
std::hash_set< rtl::OString, rtl::OStringHash > m_set;
};
}
#endif
<commit_msg>INTEGRATION: CWS jsc3 (1.3.16); FILE MERGED 2006/01/20 13:00:05 jsc 1.3.16.1: #i56247# unify include guards<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: generatedtypeset.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2006-03-15 09:10:27 $
*
* 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 INCLUDED_CODEMAKER_GENERATEDTYPESET_HXX
#define INCLUDED_CODEMAKER_GENERATEDTYPESET_HXX
#ifndef _RTL_STRING_HXX_
#include "rtl/string.hxx"
#endif
#include <hash_set>
/// @HTML
namespace codemaker {
/**
A simple class to track which types have already been processed by a code
maker.
<p>This class is not multi-thread–safe.</p>
*/
class GeneratedTypeSet {
public:
GeneratedTypeSet() {}
~GeneratedTypeSet() {}
/**
Add a type to the set of generated types.
<p>If the type was already present, nothing happens.</p>
@param type a UNO type registry name
*/
void add(rtl::OString const & type) { m_set.insert(type); }
/**
Checks whether a given type has already been generated.
@param type a UNO type registry name
@return true iff the given type has already been generated
*/
bool contains(rtl::OString const & type) const
{ return m_set.find(type) != m_set.end(); }
private:
GeneratedTypeSet(GeneratedTypeSet &); // not implemented
void operator =(GeneratedTypeSet); // not implemented
std::hash_set< rtl::OString, rtl::OStringHash > m_set;
};
}
#endif // INCLUDED_CODEMAKER_GENERATEDTYPESET_HXX
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- interface include --------------------------------------------------------
#include "Resolver.h"
//--- standard modules used ----------------------------------------------------
#include "SysLog.h"
#include "Socket.h"
#include "Dbg.h"
//--- c-library modules used ---------------------------------------------------
#include <ctype.h> // for isdigit test..
#if !defined(WIN32)
#include <arpa/nameser.h> // for inet_ntop gethostbyname etc.
#include <arpa/inet.h> // for inet_ntop gethostbyname etc.
#include <resolv.h> // for inet_ntop gethostbyname etc.
#include <netdb.h> // for gethostbyname etc.
#include <sys/socket.h> // for gethostbyname etc.
#include <netinet/in.h> // for gethostbyname etc.
#else
#include <io.h>
#endif
#define INET_ADDRSTRLEN 16 // "ddd.ddd.ddd.ddd\0"
/* Define following even if IPv6 not supported, so we can always allocate
an adequately-sized buffer, without #ifdefs in the code. */
#ifndef INET6_ADDRSTRLEN
/* $$.Ic INET6_ADDRSTRLEN$$ */
#define INET6_ADDRSTRLEN 46 /* max size of IPv6 address string:
"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx" or
"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd\0"
1234567890123456789012345678901234567890123456 */
#endif
#if defined(__sun)
#define SystemSpecific(className) _NAME2_(Sun, className)
#elif defined(__linux__)
#define SystemSpecific(className) _NAME2_(Linux, className)
#elif defined(WIN32)
#define SystemSpecific(className) _NAME2_(Win32, className)
#else //we suggest Linux (for posix)
#define SystemSpecific(className) _NAME2_(Linux, className)
#endif
class EXPORTDECL_FOUNDATION SystemSpecific(Resolver): public Resolver
{
public:
SystemSpecific(Resolver)() {}
~SystemSpecific(Resolver)() {}
virtual bool DNS2IP(String &ipAddress, const String &dnsName);
virtual bool IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr);
};
//---- Resolver ----------------------------------------------------------------
String Resolver::DNS2IPAddress( const String &dnsName )
{
StartTrace(Resolver.DNS2IPAddress);
// no need to change Server IP address if localhost (?)
if ( (dnsName.Length() <= 0) || isdigit( dnsName.At(0) ) ) {
return dnsName;
} else {
String ipAddress;
SystemSpecific(Resolver) sysResolver;
if ( sysResolver.DNS2IP(ipAddress, dnsName) ) {
return ipAddress;
}
String logMsg("Resolving of DNS Name<");
logMsg << dnsName << "> failed";
SysLog::Error(logMsg);
}
return "127.0.0.1";
}
String Resolver::IPAddress2DNS( const String &ipAddress )
{
unsigned long addr = EndPoint::MakeInetAddr(ipAddress);
String dnsName("localhost");
SystemSpecific(Resolver) sysResolver;
if ( !sysResolver.IP2DNS(dnsName, ipAddress, addr) ) {
String logMsg("Resolving of IPAddress <");
logMsg << ipAddress << "> failed";
SysLog::Error(logMsg);
}
dnsName.ToLower();
return dnsName;
}
Resolver::Resolver() {}
Resolver::~Resolver() {}
//--- system dependent subclasses ----
#if defined(__sun)
extern "C" const char *inet_ntop __P((int af, const void *src, char *dst, size_t s));
bool SunResolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent he;
const int bufSz = 8192;
char buf[bufSz];
int err = 0;
if (gethostbyname_r(dnsName, &he, buf, bufSz, &err)) {
char **pptr;
char str[INET6_ADDRSTRLEN];
pptr = he.h_addr_list;
ipAddress = inet_ntop(he.h_addrtype, *pptr, str, sizeof(str));
return true;
}
return false;
}
bool SunResolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent he;
int err;
const int bufSz = 8192;
char buf[bufSz];
if (gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &he, buf, bufSz, &err)) {
dnsName = he.h_name;
return true;
}
return false;
}
#endif
#if defined(__linux__)
bool LinuxResolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent he;
struct hostent *res;
const int bufSz = 8192;
char buf[bufSz];
int err;
if (gethostbyname_r(dnsName, &he, buf, bufSz, &res, &err) == 0) {
char **pptr;
char str[INET6_ADDRSTRLEN];
pptr = he.h_addr_list;
ipAddress = inet_ntop(he.h_addrtype, *pptr, str, sizeof(str));
return true;
}
return false;
}
bool LinuxResolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent he;
struct hostent *res = 0;
int err = 0;
const int bufSz = 8192;
char buf[bufSz];
int result = gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &he, buf, bufSz, &res, &err);
if ( result == 0 && err == NETDB_SUCCESS) {
dnsName = res->h_name;
return true;
}
return false;
}
#endif
#if defined(WIN32)
bool Win32Resolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent *ptrHe;
if ( ptrHe = gethostbyname(dnsName)) { // in windows thread scope
struct in_addr *iaddr = (struct in_addr *) * ptrHe->h_addr_list;
ipAddress = inet_ntoa(*iaddr);
return true;
}
// for tracing possible errors
// long error= WSAGetLastError ();
return false;
}
bool Win32Resolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent *hePtr;
if (hePtr = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET)) {
dnsName = (hePtr->h_name);
return true;
}
return false;
}
#endif
<commit_msg>Resolver for Mac OS X<commit_after>/*
* Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
* All rights reserved.
*
* This library/application is free software; you can redistribute and/or modify it under the terms of
* the license that is included with this library/application in the file license.txt.
*/
//--- interface include --------------------------------------------------------
#include "Resolver.h"
//--- standard modules used ----------------------------------------------------
#include "SysLog.h"
#include "Socket.h"
#include "Dbg.h"
//--- c-library modules used ---------------------------------------------------
#include <ctype.h> // for isdigit test..
#if !defined(WIN32)
#include <arpa/nameser.h> // for inet_ntop gethostbyname etc.
#include <arpa/inet.h> // for inet_ntop gethostbyname etc.
#include <resolv.h> // for inet_ntop gethostbyname etc.
#include <netdb.h> // for gethostbyname etc.
#include <sys/socket.h> // for gethostbyname etc.
#include <netinet/in.h> // for gethostbyname etc.
#else
#include <io.h>
#endif
#define INET_ADDRSTRLEN 16 // "ddd.ddd.ddd.ddd\0"
/* Define following even if IPv6 not supported, so we can always allocate
an adequately-sized buffer, without #ifdefs in the code. */
#ifndef INET6_ADDRSTRLEN
/* $$.Ic INET6_ADDRSTRLEN$$ */
#define INET6_ADDRSTRLEN 46 /* max size of IPv6 address string:
"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx" or
"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:ddd.ddd.ddd.ddd\0"
1234567890123456789012345678901234567890123456 */
#endif
#if defined(__sun)
#define SystemSpecific(className) _NAME2_(Sun, className)
#elif defined(WIN32)
#define SystemSpecific(className) _NAME2_(Win32, className)
#elif defined(__APPLE__)
#define SystemSpecific(className) _NAME2_(Apple, className)
#else //we suggest Linux (for posix)
#define SystemSpecific(className) _NAME2_(Linux, className)
#endif
class EXPORTDECL_FOUNDATION SystemSpecific(Resolver): public Resolver
{
public:
SystemSpecific(Resolver)() {}
~SystemSpecific(Resolver)() {}
virtual bool DNS2IP(String &ipAddress, const String &dnsName);
virtual bool IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr);
};
//---- Resolver ----------------------------------------------------------------
String Resolver::DNS2IPAddress( const String &dnsName )
{
StartTrace(Resolver.DNS2IPAddress);
// no need to change Server IP address if localhost (?)
if ( (dnsName.Length() <= 0) || isdigit( dnsName.At(0) ) ) {
return dnsName;
} else {
String ipAddress;
SystemSpecific(Resolver) sysResolver;
if ( sysResolver.DNS2IP(ipAddress, dnsName) ) {
return ipAddress;
}
String logMsg("Resolving of DNS Name<");
logMsg << dnsName << "> failed";
SysLog::Error(logMsg);
}
return "127.0.0.1";
}
String Resolver::IPAddress2DNS( const String &ipAddress )
{
unsigned long addr = EndPoint::MakeInetAddr(ipAddress);
String dnsName("localhost");
SystemSpecific(Resolver) sysResolver;
if ( !sysResolver.IP2DNS(dnsName, ipAddress, addr) ) {
String logMsg("Resolving of IPAddress <");
logMsg << ipAddress << "> failed";
SysLog::Error(logMsg);
}
dnsName.ToLower();
return dnsName;
}
Resolver::Resolver() {}
Resolver::~Resolver() {}
//--- system dependent subclasses ----
#if defined(__sun)
extern "C" const char *inet_ntop __P((int af, const void *src, char *dst, size_t s));
bool SunResolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent he;
const int bufSz = 8192;
char buf[bufSz];
int err = 0;
if (gethostbyname_r(dnsName, &he, buf, bufSz, &err)) {
char **pptr;
char str[INET6_ADDRSTRLEN];
pptr = he.h_addr_list;
ipAddress = inet_ntop(he.h_addrtype, *pptr, str, sizeof(str));
return true;
}
return false;
}
bool SunResolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent he;
int err;
const int bufSz = 8192;
char buf[bufSz];
if (gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &he, buf, bufSz, &err)) {
dnsName = he.h_name;
return true;
}
return false;
}
#elif defined(WIN32)
bool Win32Resolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent *ptrHe;
if ( ptrHe = gethostbyname(dnsName)) { // in windows thread scope
struct in_addr *iaddr = (struct in_addr *) * ptrHe->h_addr_list;
ipAddress = inet_ntoa(*iaddr);
return true;
}
// for tracing possible errors
// long error= WSAGetLastError ();
return false;
}
bool Win32Resolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent *hePtr;
if (hePtr = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET)) {
dnsName = (hePtr->h_name);
return true;
}
return false;
}
#elif defined(__APPLE__)
bool AppleResolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent *ptrHe;
int error_num = 0;
if (ptrHe = getipnodebyname(dnsName, AF_INET, AI_DEFAULT, &error_num)) {
struct in_addr *iaddr = (struct in_addr *) * ptrHe->h_addr_list;
ipAddress = inet_ntoa(*iaddr);
freehostent(ptrHe);
return true;
}
return false;
}
bool AppleResolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent *ptrHe;
int error_num = 0;
if (ptrHe = getipnodebyaddr((char *)&addr, sizeof(addr), AF_INET, &error_num)) {
dnsName = (ptrHe->h_name);
freehostent(ptrHe);
return true;
}
return false;
}
#else
bool LinuxResolver::DNS2IP(String &ipAddress, const String &dnsName)
{
struct hostent he;
struct hostent *res;
const int bufSz = 8192;
char buf[bufSz];
int err;
if (gethostbyname_r(dnsName, &he, buf, bufSz, &res, &err) == 0) {
char **pptr;
char str[INET6_ADDRSTRLEN];
pptr = he.h_addr_list;
ipAddress = inet_ntop(he.h_addrtype, *pptr, str, sizeof(str));
return true;
}
return false;
}
bool LinuxResolver::IP2DNS(String &dnsName, const String &ipAddress, unsigned long addr)
{
struct hostent he;
struct hostent *res = 0;
int err = 0;
const int bufSz = 8192;
char buf[bufSz];
int result = gethostbyaddr_r((char *)&addr, sizeof(addr), AF_INET, &he, buf, bufSz, &res, &err);
if ( result == 0 && err == NETDB_SUCCESS) {
dnsName = res->h_name;
return true;
}
return false;
}
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <cassert>
#include <vector>
#include <random>
#include <memory>
#include <string>
#include <cmath>
#include <macros.hh>
#include <vec.hh>
#include <pretty_printers.hh>
#include <loss_functions.hh>
#include <dataset.hh>
#include <timer.hh>
#include <model.hh>
#include <classifier.hh>
#include <lvec.hh>
#include <task_executor.hh>
namespace opt {
template <typename Model, typename Generator>
class parsgd : public classifier::base_iterative_clf<Model, Generator> {
public:
typedef Model model_type;
typedef Generator generator_type;
parsgd(const Model &model,
size_t nrounds,
const std::shared_ptr<Generator> &prng,
size_t nworkers,
bool do_locking,
size_t t_offset = 0,
double c0 = 1.0,
bool verbose = false)
: classifier::base_iterative_clf<Model, Generator>(model, nrounds, prng, verbose),
t_offset_(t_offset),
c0_(c0),
nworkers_(nworkers),
do_locking_(do_locking)
{
ALWAYS_ASSERT(c0_ > 0.0);
ALWAYS_ASSERT(nworkers_ > 0);
}
void
fit(const dataset& d, bool keep_histories=false)
{
dataset transformed(this->model_.transform(d));
if (this->verbose_)
std::cerr << "[INFO] fitting x_shape: "
<< transformed.get_x_shape() << std::endl;
timer tt;
transformed.materialize();
if (this->verbose_) {
std::cerr << "[INFO] materializing took " << tt.lap_ms() << " ms" << std::endl;
std::cerr << "[INFO] max transformed norm is " << transformed.max_x_norm() << std::endl;
}
const auto shape = transformed.get_x_shape();
this->training_sz_ = shape.first;
const auto feature_counts = transformed.feature_counts();
//if (this->verbose_) {
// for (size_t i = 0; i < feature_counts.size(); i++)
// if (!feature_counts[i])
// std::cerr << "[WARN] feature idx " << i << " is never used!" << std::endl;
//}
this->state_.reset(new standard_lvec<double>(shape.second));
this->w_history_.clear();
if (keep_histories)
this->w_history_.reserve(this->nrounds_);
// setup executors
std::vector< std::unique_ptr<task_executor_thread<bool>> > workers;
const size_t actual_nworkers =
(this->training_sz_ < nworkers_) ? 1 : nworkers_;
if (this->verbose_) {
std::cerr << "[INFO] keep_histories: " << keep_histories << std::endl;
std::cerr << "[INFO] actual_nworkers: " << actual_nworkers << std::endl;
std::cerr << "[INFO] starting eta_t: "
<< c0_ / (this->model_.get_lambda() * (1 + this->t_offset_))
<< std::endl;
}
for (size_t i = 0; i < actual_nworkers; i++)
workers.emplace_back(new task_executor_thread<bool>);
const size_t nelems_per_worker =
this->training_sz_ / actual_nworkers;
tt.lap();
std::vector<std::future<bool>> futures;
timer tt1;
for (size_t round = 0; round < this->nrounds_; round++) {
const auto permutation = transformed.permute(*this->prng_);
const auto it_end = permutation.end();
const auto it_beg = permutation.begin();
// Uncomment (and comment out above) to remove randomness each round
// (testing purposes)
/**
const auto it_end = transformed.end();
const auto it_beg = transformed.begin();
*/
tt1.lap();
for (size_t i = 0; i < actual_nworkers; i++)
futures.emplace_back(
workers[i]->enq(
std::bind(
do_locking_ ? &parsgd::work<true> : &parsgd::work<false>,
this,
i,
round+1,
this->training_sz_,
std::ref(feature_counts),
it_beg + i*nelems_per_worker,
((i+1)==actual_nworkers) ?
it_end : (it_beg + (i+1)*nelems_per_worker))));
for (auto &f : futures)
f.wait();
futures.clear();
if (keep_histories) {
state_->unsafesnapshot(this->model_.weightvec());
this->w_history_.emplace_back(
round + 1, tt.elapsed_usec(), this->model_.weightvec());
}
if (this->verbose_) {
std::cerr << "[INFO] finished round " << (round+1) << " in "
<< tt1.lap_ms() << " ms" << std::endl;
state_->unsafesnapshot(this->model_.weightvec());
std::cerr << "[INFO] current risk: "
<< this->model_.empirical_risk(transformed) << std::endl;
}
}
state_->unsafesnapshot(this->model_.weightvec());
for (auto &w : workers)
w->shutdown();
ALWAYS_ASSERT( this->model_.weightvec().size() == shape.second );
}
inline size_t get_t_offset() const { return t_offset_; }
inline double get_c0() const { return c0_; }
inline size_t get_nworkers() const { return nworkers_; }
inline bool get_do_locking() const { return do_locking_; }
std::string name() const OVERRIDE { return "parsgd"; }
std::map<std::string, std::string>
mapconfig() const OVERRIDE
{
std::map<std::string, std::string> m =
classifier::base_iterative_clf<Model, Generator>::mapconfig();
m["clf_name"] = name();
m["clf_t_offset"] = std::to_string(t_offset_);
m["clf_c0"] = std::to_string(c0_);
m["clf_nworkers"] = std::to_string(nworkers_);
m["clf_do_locking"] = std::to_string(do_locking_);
return m;
}
private:
template <bool DoLocking>
static inline double
dot(const vec_t &x, standard_lvec<double> &b)
{
double s = 0.0;
const auto inner_it_end = x.end();
for (auto inner_it = x.begin();
inner_it != inner_it_end; ++inner_it) {
const size_t feature_idx = inner_it.tell();
if (DoLocking)
s += (*inner_it) * b.lockandread(feature_idx);
else
s += (*inner_it) * b.unsaferead(feature_idx);
}
return s;
}
template <bool DoLocking>
bool
work(size_t workerid,
size_t round,
size_t dataset_size,
const std::vector<size_t> &feature_counts,
dataset::const_iterator begin,
dataset::const_iterator end)
{
const double dataset_sizef = double(dataset_size);
size_t i = 1;
for (auto it = begin; it != end; ++it, ++i) {
const size_t t_eff = (round-1)*dataset_size + i + t_offset_;
const double eta_t = c0_ / (this->model_.get_lambda() * t_eff);
const auto &x = *it.first();
const double dloss = this->model_.get_lossfn().dloss(
*it.second(), dot<DoLocking>(x, *state_.get()));
const auto inner_it_end = x.end();
for (auto inner_it = x.begin();
inner_it != inner_it_end; ++inner_it) {
const size_t feature_idx = inner_it.tell();
const double w_old = state_->unsaferead(feature_idx);
assert(feature_counts[feature_idx]);
const double w_new =
(1.0 - eta_t * this->model_.get_lambda() * dataset_sizef /
double(feature_counts[feature_idx])) * w_old
- eta_t * dloss * (*inner_it);
if (DoLocking)
state_->writeandunlock(feature_idx, w_new);
else
state_->unsafewrite(feature_idx, w_new);
}
//std::cerr << "[worker " << workerid << ", round " << round << ", item " << i << "]" << std::endl;
}
return false;
}
size_t t_offset_;
double c0_;
size_t nworkers_;
bool do_locking_;
std::unique_ptr<standard_lvec<double>> state_;
};
} // namespace opt
<commit_msg>don't spawn off workers for single threaded<commit_after>#pragma once
#include <cassert>
#include <vector>
#include <random>
#include <memory>
#include <string>
#include <cmath>
#include <macros.hh>
#include <vec.hh>
#include <pretty_printers.hh>
#include <loss_functions.hh>
#include <dataset.hh>
#include <timer.hh>
#include <model.hh>
#include <classifier.hh>
#include <lvec.hh>
#include <task_executor.hh>
namespace opt {
template <typename Model, typename Generator>
class parsgd : public classifier::base_iterative_clf<Model, Generator> {
public:
typedef Model model_type;
typedef Generator generator_type;
parsgd(const Model &model,
size_t nrounds,
const std::shared_ptr<Generator> &prng,
size_t nworkers,
bool do_locking,
size_t t_offset = 0,
double c0 = 1.0,
bool verbose = false)
: classifier::base_iterative_clf<Model, Generator>(model, nrounds, prng, verbose),
t_offset_(t_offset),
c0_(c0),
nworkers_(nworkers),
do_locking_(do_locking)
{
ALWAYS_ASSERT(c0_ > 0.0);
ALWAYS_ASSERT(nworkers_ > 0);
}
void
fit(const dataset& d, bool keep_histories=false)
{
dataset transformed(this->model_.transform(d));
if (this->verbose_)
std::cerr << "[INFO] fitting x_shape: "
<< transformed.get_x_shape() << std::endl;
timer tt;
transformed.materialize();
if (this->verbose_) {
std::cerr << "[INFO] materializing took " << tt.lap_ms() << " ms" << std::endl;
std::cerr << "[INFO] max transformed norm is " << transformed.max_x_norm() << std::endl;
}
const auto shape = transformed.get_x_shape();
this->training_sz_ = shape.first;
const auto feature_counts = transformed.feature_counts();
//if (this->verbose_) {
// for (size_t i = 0; i < feature_counts.size(); i++)
// if (!feature_counts[i])
// std::cerr << "[WARN] feature idx " << i << " is never used!" << std::endl;
//}
this->state_.reset(new standard_lvec<double>(shape.second));
this->w_history_.clear();
if (keep_histories)
this->w_history_.reserve(this->nrounds_);
// setup executors
std::vector< std::unique_ptr<task_executor_thread<bool>> > workers;
const size_t actual_nworkers =
(this->training_sz_ < nworkers_) ? 1 : nworkers_;
if (this->verbose_) {
std::cerr << "[INFO] keep_histories: " << keep_histories << std::endl;
std::cerr << "[INFO] actual_nworkers: " << actual_nworkers << std::endl;
std::cerr << "[INFO] starting eta_t: "
<< c0_ / (this->model_.get_lambda() * (1 + this->t_offset_))
<< std::endl;
}
if (actual_nworkers > 1)
for (size_t i = 0; i < actual_nworkers; i++)
workers.emplace_back(new task_executor_thread<bool>);
const size_t nelems_per_worker =
this->training_sz_ / actual_nworkers;
tt.lap();
std::vector<std::future<bool>> futures;
timer tt1;
for (size_t round = 0; round < this->nrounds_; round++) {
const auto permutation = transformed.permute(*this->prng_);
const auto it_end = permutation.end();
const auto it_beg = permutation.begin();
// Uncomment (and comment out above) to remove randomness each round
// (testing purposes)
/**
const auto it_end = transformed.end();
const auto it_beg = transformed.begin();
*/
tt1.lap();
if (actual_nworkers > 1) {
for (size_t i = 0; i < actual_nworkers; i++)
futures.emplace_back(
workers[i]->enq(
std::bind(
do_locking_ ? &parsgd::work<true> : &parsgd::work<false>,
this,
i,
round+1,
this->training_sz_,
std::ref(feature_counts),
it_beg + i*nelems_per_worker,
((i+1)==actual_nworkers) ?
it_end : (it_beg + (i+1)*nelems_per_worker))));
for (auto &f : futures)
f.wait();
futures.clear();
} else {
if (do_locking_)
work<true>(0, round+1, this->training_sz_, feature_counts, it_beg, it_end);
else
work<false>(0, round+1, this->training_sz_, feature_counts, it_beg, it_end);
}
if (keep_histories) {
state_->unsafesnapshot(this->model_.weightvec());
this->w_history_.emplace_back(
round + 1, tt.elapsed_usec(), this->model_.weightvec());
}
if (this->verbose_) {
std::cerr << "[INFO] finished round " << (round+1) << " in "
<< tt1.lap_ms() << " ms" << std::endl;
state_->unsafesnapshot(this->model_.weightvec());
std::cerr << "[INFO] current risk: "
<< this->model_.empirical_risk(transformed) << std::endl;
}
}
state_->unsafesnapshot(this->model_.weightvec());
for (auto &w : workers)
w->shutdown();
ALWAYS_ASSERT( this->model_.weightvec().size() == shape.second );
}
inline size_t get_t_offset() const { return t_offset_; }
inline double get_c0() const { return c0_; }
inline size_t get_nworkers() const { return nworkers_; }
inline bool get_do_locking() const { return do_locking_; }
std::string name() const OVERRIDE { return "parsgd"; }
std::map<std::string, std::string>
mapconfig() const OVERRIDE
{
std::map<std::string, std::string> m =
classifier::base_iterative_clf<Model, Generator>::mapconfig();
m["clf_name"] = name();
m["clf_t_offset"] = std::to_string(t_offset_);
m["clf_c0"] = std::to_string(c0_);
m["clf_nworkers"] = std::to_string(nworkers_);
m["clf_do_locking"] = std::to_string(do_locking_);
return m;
}
private:
template <bool DoLocking>
static inline double
dot(const vec_t &x, standard_lvec<double> &b)
{
double s = 0.0;
const auto inner_it_end = x.end();
for (auto inner_it = x.begin();
inner_it != inner_it_end; ++inner_it) {
const size_t feature_idx = inner_it.tell();
if (DoLocking)
s += (*inner_it) * b.lockandread(feature_idx);
else
s += (*inner_it) * b.unsaferead(feature_idx);
}
return s;
}
template <bool DoLocking>
bool
work(size_t workerid,
size_t round,
size_t dataset_size,
const std::vector<size_t> &feature_counts,
dataset::const_iterator begin,
dataset::const_iterator end)
{
const double dataset_sizef = double(dataset_size);
size_t i = 1;
//std::cerr << "[worker " << workerid << ", round " << round << ", elems" << size_t(end-begin) << "]" << std::endl;
for (auto it = begin; it != end; ++it, ++i) {
const size_t t_eff = (round-1)*dataset_size + i + t_offset_;
const double eta_t = c0_ / (this->model_.get_lambda() * t_eff);
const auto &x = *it.first();
const double dloss = this->model_.get_lossfn().dloss(
*it.second(), dot<DoLocking>(x, *state_.get()));
const auto inner_it_end = x.end();
for (auto inner_it = x.begin();
inner_it != inner_it_end; ++inner_it) {
const size_t feature_idx = inner_it.tell();
const double w_old = state_->unsaferead(feature_idx);
assert(feature_counts[feature_idx]);
const double w_new =
(1.0 - eta_t * this->model_.get_lambda() * dataset_sizef /
double(feature_counts[feature_idx])) * w_old
- eta_t * dloss * (*inner_it);
if (DoLocking)
state_->writeandunlock(feature_idx, w_new);
else
state_->unsafewrite(feature_idx, w_new);
}
//std::cerr << "[worker " << workerid << ", round " << round << ", item " << i << "]" << std::endl;
}
return false;
}
size_t t_offset_;
double c0_;
size_t nworkers_;
bool do_locking_;
std::unique_ptr<standard_lvec<double>> state_;
};
} // namespace opt
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ODriver.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: kz $ $Date: 2006-12-13 16:22:01 $
*
* 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_connectivity.hxx"
#ifndef _CONNECTIVITY_ODBC_ODRIVER_HXX_
#include "odbc/ODriver.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OCONNECTION_HXX_
#include "odbc/OConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OFUNCTIONS_HXX_
#include "odbc/OFunctions.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "odbc/OTools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace connectivity::odbc;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
ODBCDriver::ODBCDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
:ODriver_BASE(m_aMutex)
,m_xORB(_rxFactory)
,m_pDriverHandle(SQL_NULL_HANDLE)
{
}
// --------------------------------------------------------------------------------
void ODBCDriver::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_xConnections.clear();
ODriver_BASE::disposing();
}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString ODBCDriver::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii("com.sun.star.comp.sdbc.ODBCDriver");
// this name is referenced in the configuration and in the odbc.xml
// Please take care when changing it.
}
typedef Sequence< ::rtl::OUString > SS;
//------------------------------------------------------------------------------
SS ODBCDriver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
SS aSNS( 1 );
aSNS[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.Driver");
return aSNS;
}
//------------------------------------------------------------------
::rtl::OUString SAL_CALL ODBCDriver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
SS aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
//------------------------------------------------------------------
SS SAL_CALL ODBCDriver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL ODBCDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( ! acceptsURL(url) )
return NULL;
if(!m_pDriverHandle)
{
::rtl::OUString aPath;
if(!EnvironmentHandle(aPath))
throw SQLException(aPath,*this,::rtl::OUString(),1000,Any());
}
OConnection* pCon = new OConnection(m_pDriverHandle,this);
Reference< XConnection > xCon = pCon;
pCon->Construct(url,info);
m_xConnections.push_back(WeakReferenceHelper(*pCon));
return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::acceptsURL( const ::rtl::OUString& url )
throw(SQLException, RuntimeException)
{
return (!url.compareTo(::rtl::OUString::createFromAscii("sdbc:odbc:"),10));
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException)
{
if ( acceptsURL(url) )
{
::std::vector< DriverPropertyInfo > aDriverInfo;
Sequence< ::rtl::OUString > aBooleanValues(2);
aBooleanValues[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) );
aBooleanValues[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "true" ) );
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet of the database."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCatalog"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Use catalog for file-based databases."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SystemDriverSettings"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Driver settings."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ParameterNameSubstitution"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Change named parameters with '?'."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IgnoreDriverPrivileges"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Ignore the privileges from the database driver."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsAutoRetrievingEnabled"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Retrieve generated values."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoRetrievingStatement"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Auto-increment statement."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GenerateASBeforeCorrelationName"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Generate AS before table correlation names."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "true" ) )
,aBooleanValues)
);
return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
}
::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) throw(RuntimeException)
{
return 1;
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) throw(RuntimeException)
{
return 0;
}
// --------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba24e_SRC680 (1.16.136); FILE MERGED 2007/12/03 11:09:55 lla 1.16.136.1: #i78988# add EscapeDateTime property<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ODriver.cxx,v $
*
* $Revision: 1.17 $
*
* last change: $Author: vg $ $Date: 2008-01-29 08:38:30 $
*
* 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_connectivity.hxx"
#ifndef _CONNECTIVITY_ODBC_ODRIVER_HXX_
#include "odbc/ODriver.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OCONNECTION_HXX_
#include "odbc/OConnection.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_OFUNCTIONS_HXX_
#include "odbc/OFunctions.hxx"
#endif
#ifndef _CONNECTIVITY_OTOOLS_HXX_
#include "odbc/OTools.hxx"
#endif
#ifndef _DBHELPER_DBEXCEPTION_HXX_
#include "connectivity/dbexception.hxx"
#endif
using namespace connectivity::odbc;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;
using namespace com::sun::star::sdbc;
// --------------------------------------------------------------------------------
ODBCDriver::ODBCDriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory)
:ODriver_BASE(m_aMutex)
,m_xORB(_rxFactory)
,m_pDriverHandle(SQL_NULL_HANDLE)
{
}
// --------------------------------------------------------------------------------
void ODBCDriver::disposing()
{
::osl::MutexGuard aGuard(m_aMutex);
for (OWeakRefArray::iterator i = m_xConnections.begin(); m_xConnections.end() != i; ++i)
{
Reference< XComponent > xComp(i->get(), UNO_QUERY);
if (xComp.is())
xComp->dispose();
}
m_xConnections.clear();
ODriver_BASE::disposing();
}
// static ServiceInfo
//------------------------------------------------------------------------------
rtl::OUString ODBCDriver::getImplementationName_Static( ) throw(RuntimeException)
{
return rtl::OUString::createFromAscii("com.sun.star.comp.sdbc.ODBCDriver");
// this name is referenced in the configuration and in the odbc.xml
// Please take care when changing it.
}
typedef Sequence< ::rtl::OUString > SS;
//------------------------------------------------------------------------------
SS ODBCDriver::getSupportedServiceNames_Static( ) throw (RuntimeException)
{
SS aSNS( 1 );
aSNS[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbc.Driver");
return aSNS;
}
//------------------------------------------------------------------
::rtl::OUString SAL_CALL ODBCDriver::getImplementationName( ) throw(RuntimeException)
{
return getImplementationName_Static();
}
//------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::supportsService( const ::rtl::OUString& _rServiceName ) throw(RuntimeException)
{
SS aSupported(getSupportedServiceNames());
const ::rtl::OUString* pSupported = aSupported.getConstArray();
const ::rtl::OUString* pEnd = pSupported + aSupported.getLength();
for (;pSupported != pEnd && !pSupported->equals(_rServiceName); ++pSupported)
;
return pSupported != pEnd;
}
//------------------------------------------------------------------
SS SAL_CALL ODBCDriver::getSupportedServiceNames( ) throw(RuntimeException)
{
return getSupportedServiceNames_Static();
}
// --------------------------------------------------------------------------------
Reference< XConnection > SAL_CALL ODBCDriver::connect( const ::rtl::OUString& url, const Sequence< PropertyValue >& info ) throw(SQLException, RuntimeException)
{
if ( ! acceptsURL(url) )
return NULL;
if(!m_pDriverHandle)
{
::rtl::OUString aPath;
if(!EnvironmentHandle(aPath))
throw SQLException(aPath,*this,::rtl::OUString(),1000,Any());
}
OConnection* pCon = new OConnection(m_pDriverHandle,this);
Reference< XConnection > xCon = pCon;
pCon->Construct(url,info);
m_xConnections.push_back(WeakReferenceHelper(*pCon));
return xCon;
}
// --------------------------------------------------------------------------------
sal_Bool SAL_CALL ODBCDriver::acceptsURL( const ::rtl::OUString& url )
throw(SQLException, RuntimeException)
{
return (!url.compareTo(::rtl::OUString::createFromAscii("sdbc:odbc:"),10));
}
// --------------------------------------------------------------------------------
Sequence< DriverPropertyInfo > SAL_CALL ODBCDriver::getPropertyInfo( const ::rtl::OUString& url, const Sequence< PropertyValue >& /*info*/ ) throw(SQLException, RuntimeException)
{
if ( acceptsURL(url) )
{
::std::vector< DriverPropertyInfo > aDriverInfo;
Sequence< ::rtl::OUString > aBooleanValues(2);
aBooleanValues[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) );
aBooleanValues[1] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "true" ) );
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("CharSet of the database."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("UseCatalog"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Use catalog for file-based databases."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("SystemDriverSettings"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Driver settings."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("ParameterNameSubstitution"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Change named parameters with '?'."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IgnoreDriverPrivileges"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Ignore the privileges from the database driver."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("IsAutoRetrievingEnabled"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Retrieve generated values."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "false" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("AutoRetrievingStatement"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Auto-increment statement."))
,sal_False
,::rtl::OUString()
,Sequence< ::rtl::OUString >())
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("GenerateASBeforeCorrelationName"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Generate AS before table correlation names."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "true" ) )
,aBooleanValues)
);
aDriverInfo.push_back(DriverPropertyInfo(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("EscapeDateTime"))
,::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Escape date time format."))
,sal_False
,::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "true" ) )
,aBooleanValues)
);
return Sequence< DriverPropertyInfo >(&aDriverInfo[0],aDriverInfo.size());
}
::dbtools::throwGenericSQLException(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Invalid URL!")) ,*this);
return Sequence< DriverPropertyInfo >();
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMajorVersion( ) throw(RuntimeException)
{
return 1;
}
// --------------------------------------------------------------------------------
sal_Int32 SAL_CALL ODBCDriver::getMinorVersion( ) throw(RuntimeException)
{
return 0;
}
// --------------------------------------------------------------------------------
//-----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autocomplete/history_quick_provider.h"
#include <vector>
#include "base/basictypes.h"
#include "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/history/in_memory_url_index.h"
#include "chrome/browser/history/in_memory_url_index_types.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "googleurl/src/url_parse.h"
#include "googleurl/src/url_util.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
using history::InMemoryURLIndex;
using history::ScoredHistoryMatch;
using history::ScoredHistoryMatches;
bool HistoryQuickProvider::disabled_ = false;
HistoryQuickProvider::HistoryQuickProvider(ACProviderListener* listener,
Profile* profile)
: HistoryProvider(listener, profile, "HistoryQuickProvider"),
languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)) {}
HistoryQuickProvider::~HistoryQuickProvider() {}
void HistoryQuickProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
matches_.clear();
if (disabled_)
return;
// Don't bother with INVALID and FORCED_QUERY. Also pass when looking for
// BEST_MATCH and there is no inline autocompletion because none of the HQP
// matches can score highly enough to qualify.
if ((input.type() == AutocompleteInput::INVALID) ||
(input.type() == AutocompleteInput::FORCED_QUERY) ||
(input.matches_requested() == AutocompleteInput::BEST_MATCH &&
input.prevent_inline_autocomplete()))
return;
autocomplete_input_ = input;
// TODO(pkasting): We should just block here until this loads. Any time
// someone unloads the history backend, we'll get inconsistent inline
// autocomplete behavior here.
if (GetIndex()) {
base::TimeTicks start_time = base::TimeTicks::Now();
DoAutocomplete();
if (input.text().length() < 6) {
base::TimeTicks end_time = base::TimeTicks::Now();
std::string name = "HistoryQuickProvider.QueryIndexTime." +
base::IntToString(input.text().length());
base::Histogram* counter = base::Histogram::FactoryGet(
name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
}
UpdateStarredStateOfMatches();
}
}
// TODO(mrossetti): Implement this function. (Will happen in next CL.)
void HistoryQuickProvider::DeleteMatch(const AutocompleteMatch& match) {}
void HistoryQuickProvider::DoAutocomplete() {
// Get the matching URLs from the DB.
string16 term_string = autocomplete_input_.text();
ScoredHistoryMatches matches = GetIndex()->HistoryItemsForTerms(term_string);
if (matches.empty())
return;
// Artificially reduce the score of high-scoring matches which should not be
// inline autocompletd. Each such result gets the next available
// |max_match_score|. Upon use of |max_match_score| it is decremented.
// All subsequent matches must be clamped to retain match results ordering.
int max_match_score = autocomplete_input_.prevent_inline_autocomplete() ?
(AutocompleteResult::kLowestDefaultScore - 1) : -1;
for (ScoredHistoryMatches::const_iterator match_iter = matches.begin();
match_iter != matches.end(); ++match_iter) {
const ScoredHistoryMatch& history_match(*match_iter);
if (history_match.raw_score > 0) {
AutocompleteMatch ac_match = QuickMatchToACMatch(
history_match,
PreventInlineAutocomplete(autocomplete_input_),
&max_match_score);
matches_.push_back(ac_match);
}
}
}
AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
const ScoredHistoryMatch& history_match,
bool prevent_inline_autocomplete,
int* max_match_score) {
DCHECK(max_match_score);
const history::URLRow& info = history_match.url_info;
int score = CalculateRelevance(history_match, max_match_score);
AutocompleteMatch match(this, score, !!info.visit_count(),
history_match.url_matches.empty() ?
AutocompleteMatch::HISTORY_URL : AutocompleteMatch::HISTORY_TITLE);
match.destination_url = info.url();
DCHECK(match.destination_url.is_valid());
// Format the URL autocomplete presentation.
std::vector<size_t> offsets =
OffsetsFromTermMatches(history_match.url_matches);
const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP);
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
net::FormatUrlWithOffsets(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, &offsets));
match.contents = net::FormatUrl(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, NULL);
history::TermMatches new_matches =
ReplaceOffsetsInTermMatches(history_match.url_matches, offsets);
match.contents_class =
SpansFromTermMatch(new_matches, match.contents.length(), true);
if (prevent_inline_autocomplete || !history_match.can_inline) {
match.inline_autocomplete_offset = string16::npos;
} else {
DCHECK(!new_matches.empty());
match.inline_autocomplete_offset = new_matches[0].offset +
new_matches[0].length;
DCHECK_LE(match.inline_autocomplete_offset, match.fill_into_edit.length());
}
// Format the description autocomplete presentation.
match.description = info.title();
match.description_class = SpansFromTermMatch(
history_match.title_matches, match.description.length(), false);
return match;
}
history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() {
if (index_for_testing_.get())
return index_for_testing_.get();
HistoryService* const history_service =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (!history_service)
return NULL;
return history_service->InMemoryIndex();
}
// static
int HistoryQuickProvider::CalculateRelevance(
const ScoredHistoryMatch& history_match,
int* max_match_score) {
DCHECK(max_match_score);
// Note that |can_inline| will only be true if what the user typed starts
// at the beginning of the result's URL and there is exactly one substring
// match in the URL.
int score = (history_match.can_inline) ? history_match.raw_score :
std::min(AutocompleteResult::kLowestDefaultScore - 1,
history_match.raw_score);
*max_match_score = ((*max_match_score < 0) ?
score : std::min(score, *max_match_score)) - 1;
return *max_match_score + 1;
}
// static
ACMatchClassifications HistoryQuickProvider::SpansFromTermMatch(
const history::TermMatches& matches,
size_t text_length,
bool is_url) {
ACMatchClassification::Style url_style =
is_url ? ACMatchClassification::URL : ACMatchClassification::NONE;
ACMatchClassifications spans;
if (matches.empty()) {
if (text_length)
spans.push_back(ACMatchClassification(0, url_style));
return spans;
}
if (matches[0].offset)
spans.push_back(ACMatchClassification(0, url_style));
size_t match_count = matches.size();
for (size_t i = 0; i < match_count;) {
size_t offset = matches[i].offset;
spans.push_back(ACMatchClassification(offset,
ACMatchClassification::MATCH | url_style));
// Skip all adjacent matches.
do {
offset += matches[i].length;
++i;
} while ((i < match_count) && (offset == matches[i].offset));
if (offset < text_length)
spans.push_back(ACMatchClassification(offset, url_style));
}
return spans;
}
<commit_msg>Fix DCHECK with Trailing Slash.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autocomplete/history_quick_provider.h"
#include <vector>
#include "base/basictypes.h"
#include "base/i18n/break_iterator.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/history/in_memory_url_index.h"
#include "chrome/browser/history/in_memory_url_index_types.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/notification_types.h"
#include "googleurl/src/url_parse.h"
#include "googleurl/src/url_util.h"
#include "net/base/escape.h"
#include "net/base/net_util.h"
using history::InMemoryURLIndex;
using history::ScoredHistoryMatch;
using history::ScoredHistoryMatches;
bool HistoryQuickProvider::disabled_ = false;
HistoryQuickProvider::HistoryQuickProvider(ACProviderListener* listener,
Profile* profile)
: HistoryProvider(listener, profile, "HistoryQuickProvider"),
languages_(profile_->GetPrefs()->GetString(prefs::kAcceptLanguages)) {}
HistoryQuickProvider::~HistoryQuickProvider() {}
void HistoryQuickProvider::Start(const AutocompleteInput& input,
bool minimal_changes) {
matches_.clear();
if (disabled_)
return;
// Don't bother with INVALID and FORCED_QUERY. Also pass when looking for
// BEST_MATCH and there is no inline autocompletion because none of the HQP
// matches can score highly enough to qualify.
if ((input.type() == AutocompleteInput::INVALID) ||
(input.type() == AutocompleteInput::FORCED_QUERY) ||
(input.matches_requested() == AutocompleteInput::BEST_MATCH &&
input.prevent_inline_autocomplete()))
return;
autocomplete_input_ = input;
// TODO(pkasting): We should just block here until this loads. Any time
// someone unloads the history backend, we'll get inconsistent inline
// autocomplete behavior here.
if (GetIndex()) {
base::TimeTicks start_time = base::TimeTicks::Now();
DoAutocomplete();
if (input.text().length() < 6) {
base::TimeTicks end_time = base::TimeTicks::Now();
std::string name = "HistoryQuickProvider.QueryIndexTime." +
base::IntToString(input.text().length());
base::Histogram* counter = base::Histogram::FactoryGet(
name, 1, 1000, 50, base::Histogram::kUmaTargetedHistogramFlag);
counter->Add(static_cast<int>((end_time - start_time).InMilliseconds()));
}
UpdateStarredStateOfMatches();
}
}
// TODO(mrossetti): Implement this function. (Will happen in next CL.)
void HistoryQuickProvider::DeleteMatch(const AutocompleteMatch& match) {}
void HistoryQuickProvider::DoAutocomplete() {
// Get the matching URLs from the DB.
string16 term_string = autocomplete_input_.text();
ScoredHistoryMatches matches = GetIndex()->HistoryItemsForTerms(term_string);
if (matches.empty())
return;
// Artificially reduce the score of high-scoring matches which should not be
// inline autocompletd. Each such result gets the next available
// |max_match_score|. Upon use of |max_match_score| it is decremented.
// All subsequent matches must be clamped to retain match results ordering.
int max_match_score = autocomplete_input_.prevent_inline_autocomplete() ?
(AutocompleteResult::kLowestDefaultScore - 1) : -1;
for (ScoredHistoryMatches::const_iterator match_iter = matches.begin();
match_iter != matches.end(); ++match_iter) {
const ScoredHistoryMatch& history_match(*match_iter);
if (history_match.raw_score > 0) {
AutocompleteMatch ac_match = QuickMatchToACMatch(
history_match,
PreventInlineAutocomplete(autocomplete_input_),
&max_match_score);
matches_.push_back(ac_match);
}
}
}
AutocompleteMatch HistoryQuickProvider::QuickMatchToACMatch(
const ScoredHistoryMatch& history_match,
bool prevent_inline_autocomplete,
int* max_match_score) {
DCHECK(max_match_score);
const history::URLRow& info = history_match.url_info;
int score = CalculateRelevance(history_match, max_match_score);
AutocompleteMatch match(this, score, !!info.visit_count(),
history_match.url_matches.empty() ?
AutocompleteMatch::HISTORY_URL : AutocompleteMatch::HISTORY_TITLE);
match.destination_url = info.url();
DCHECK(match.destination_url.is_valid());
// Format the URL autocomplete presentation.
std::vector<size_t> offsets =
OffsetsFromTermMatches(history_match.url_matches);
const net::FormatUrlTypes format_types = net::kFormatUrlOmitAll &
~(!history_match.match_in_scheme ? 0 : net::kFormatUrlOmitHTTP);
match.fill_into_edit =
AutocompleteInput::FormattedStringWithEquivalentMeaning(info.url(),
net::FormatUrlWithOffsets(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, &offsets));
history::TermMatches new_matches =
ReplaceOffsetsInTermMatches(history_match.url_matches, offsets);
match.contents = net::FormatUrl(info.url(), languages_, format_types,
net::UnescapeRule::SPACES, NULL, NULL, NULL);
match.contents_class =
SpansFromTermMatch(new_matches, match.contents.length(), true);
if (prevent_inline_autocomplete || !history_match.can_inline) {
match.inline_autocomplete_offset = string16::npos;
} else {
DCHECK(!new_matches.empty());
match.inline_autocomplete_offset = new_matches[0].offset +
new_matches[0].length;
// The following will happen if the user has typed an URL with a scheme
// and the last character typed is a slash because that slash is removed
// by the FormatURLWithOffsets call above.
if (match.inline_autocomplete_offset > match.fill_into_edit.length())
match.inline_autocomplete_offset = match.fill_into_edit.length();
}
// Format the description autocomplete presentation.
match.description = info.title();
match.description_class = SpansFromTermMatch(
history_match.title_matches, match.description.length(), false);
return match;
}
history::InMemoryURLIndex* HistoryQuickProvider::GetIndex() {
if (index_for_testing_.get())
return index_for_testing_.get();
HistoryService* const history_service =
profile_->GetHistoryService(Profile::EXPLICIT_ACCESS);
if (!history_service)
return NULL;
return history_service->InMemoryIndex();
}
// static
int HistoryQuickProvider::CalculateRelevance(
const ScoredHistoryMatch& history_match,
int* max_match_score) {
DCHECK(max_match_score);
// Note that |can_inline| will only be true if what the user typed starts
// at the beginning of the result's URL and there is exactly one substring
// match in the URL.
int score = (history_match.can_inline) ? history_match.raw_score :
std::min(AutocompleteResult::kLowestDefaultScore - 1,
history_match.raw_score);
*max_match_score = ((*max_match_score < 0) ?
score : std::min(score, *max_match_score)) - 1;
return *max_match_score + 1;
}
// static
ACMatchClassifications HistoryQuickProvider::SpansFromTermMatch(
const history::TermMatches& matches,
size_t text_length,
bool is_url) {
ACMatchClassification::Style url_style =
is_url ? ACMatchClassification::URL : ACMatchClassification::NONE;
ACMatchClassifications spans;
if (matches.empty()) {
if (text_length)
spans.push_back(ACMatchClassification(0, url_style));
return spans;
}
if (matches[0].offset)
spans.push_back(ACMatchClassification(0, url_style));
size_t match_count = matches.size();
for (size_t i = 0; i < match_count;) {
size_t offset = matches[i].offset;
spans.push_back(ACMatchClassification(offset,
ACMatchClassification::MATCH | url_style));
// Skip all adjacent matches.
do {
offset += matches[i].length;
++i;
} while ((i < match_count) && (offset == matches[i].offset));
if (offset < text_length)
spans.push_back(ACMatchClassification(offset, url_style));
}
return spans;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: aststructinstance.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2004-08-20 09:20:12 $
*
* 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 "idlc/aststructinstance.hxx"
#include "idlc/asttype.hxx"
#include "idlc/idlctypes.hxx"
#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"
namespace {
rtl::OString createName(
AstType const * typeTemplate, DeclList const * typeArguments)
{
rtl::OStringBuffer buf(typeTemplate->getScopedName());
if (typeArguments != 0) {
buf.append('<');
for (DeclList::const_iterator i(typeArguments->begin());
i != typeArguments->end(); ++i)
{
if (i != typeArguments->begin()) {
buf.append(',');
}
if (*i != 0) {
buf.append((*i)->getScopedName());
}
}
buf.append('>');
}
return buf.makeStringAndClear();
}
}
AstStructInstance::AstStructInstance(
AstType const * typeTemplate, DeclList const * typeArguments,
AstScope * scope):
AstType(
NT_instantiated_struct, createName(typeTemplate, typeArguments), scope),
m_typeTemplate(typeTemplate), m_typeArguments(*typeArguments)
{}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.20); FILE MERGED 2005/09/05 17:39:39 rt 1.3.20.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: aststructinstance.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: rt $ $Date: 2005-09-07 18:09:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "idlc/aststructinstance.hxx"
#include "idlc/asttype.hxx"
#include "idlc/idlctypes.hxx"
#include "rtl/strbuf.hxx"
#include "rtl/string.hxx"
namespace {
rtl::OString createName(
AstType const * typeTemplate, DeclList const * typeArguments)
{
rtl::OStringBuffer buf(typeTemplate->getScopedName());
if (typeArguments != 0) {
buf.append('<');
for (DeclList::const_iterator i(typeArguments->begin());
i != typeArguments->end(); ++i)
{
if (i != typeArguments->begin()) {
buf.append(',');
}
if (*i != 0) {
buf.append((*i)->getScopedName());
}
}
buf.append('>');
}
return buf.makeStringAndClear();
}
}
AstStructInstance::AstStructInstance(
AstType const * typeTemplate, DeclList const * typeArguments,
AstScope * scope):
AstType(
NT_instantiated_struct, createName(typeTemplate, typeArguments), scope),
m_typeTemplate(typeTemplate), m_typeArguments(*typeArguments)
{}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_profile_lock.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "base/file_util.h"
// This class is based on Firefox code in:
// profile/dirserviceprovider/src/nsProfileLock.cpp
// The license block is:
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Conrad Carlen <ccarlen@netscape.com>
* Brendan Eich <brendan@mozilla.org>
* Colin Blake <colin@theblakes.com>
* Javier Pedemonte <pedemont@us.ibm.com>
* Mats Palmgren <mats.palmgren@bredband.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
void FirefoxProfileLock::Init() {
lock_fd_ = -1;
}
void FirefoxProfileLock::Lock() {
if (HasAcquired())
return;
bool fcntl_lock = LockWithFcntl();
if (!fcntl_lock) {
return;
} else if (!HasAcquired()) {
old_lock_file_ = lock_file_.DirName().Append(kOldLockFileName);
lock_fd_ = open(old_lock_file_.value().c_str(), O_CREAT | O_EXCL, 0644);
}
}
void FirefoxProfileLock::Unlock() {
if (!HasAcquired())
return;
close(lock_fd_);
lock_fd_ = -1;
file_util::Delete(old_lock_file_, false);
}
bool FirefoxProfileLock::HasAcquired() {
return (lock_fd_ >= 0);
}
// This function tries to lock Firefox profile using fcntl(). The return
// value of this function together with HasAcquired() tells the current status
// of lock.
// if return == false: Another process has lock to the profile.
// if return == true && HasAcquired() == true: successfully acquired the lock.
// if return == false && HasAcquired() == false: Failed to acquire lock due
// to some error (so that we can try alternate method of profile lock).
bool FirefoxProfileLock::LockWithFcntl() {
lock_fd_ = open(lock_file_.value().c_str(), O_WRONLY | O_CREAT | O_TRUNC,
0666);
if (lock_fd_ == -1)
return true;
struct flock lock;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
struct flock testlock = lock;
if (fcntl(lock_fd_, F_GETLK, &testlock) == -1) {
close(lock_fd_);
lock_fd_ = -1;
return true;
} else if (fcntl(lock_fd_, F_SETLK, &lock) == -1) {
close(lock_fd_);
lock_fd_ = -1;
if (errno == EAGAIN || errno == EACCES)
return false;
else
return true;
} else {
// We have the lock.
return true;
}
}
<commit_msg>Coverity: Ensure |lock| is fully initialized.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/firefox_profile_lock.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "base/file_util.h"
// This class is based on Firefox code in:
// profile/dirserviceprovider/src/nsProfileLock.cpp
// The license block is:
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Conrad Carlen <ccarlen@netscape.com>
* Brendan Eich <brendan@mozilla.org>
* Colin Blake <colin@theblakes.com>
* Javier Pedemonte <pedemont@us.ibm.com>
* Mats Palmgren <mats.palmgren@bredband.net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
void FirefoxProfileLock::Init() {
lock_fd_ = -1;
}
void FirefoxProfileLock::Lock() {
if (HasAcquired())
return;
bool fcntl_lock = LockWithFcntl();
if (!fcntl_lock) {
return;
} else if (!HasAcquired()) {
old_lock_file_ = lock_file_.DirName().Append(kOldLockFileName);
lock_fd_ = open(old_lock_file_.value().c_str(), O_CREAT | O_EXCL, 0644);
}
}
void FirefoxProfileLock::Unlock() {
if (!HasAcquired())
return;
close(lock_fd_);
lock_fd_ = -1;
file_util::Delete(old_lock_file_, false);
}
bool FirefoxProfileLock::HasAcquired() {
return (lock_fd_ >= 0);
}
// This function tries to lock Firefox profile using fcntl(). The return
// value of this function together with HasAcquired() tells the current status
// of lock.
// if return == false: Another process has lock to the profile.
// if return == true && HasAcquired() == true: successfully acquired the lock.
// if return == false && HasAcquired() == false: Failed to acquire lock due
// to some error (so that we can try alternate method of profile lock).
bool FirefoxProfileLock::LockWithFcntl() {
lock_fd_ = open(lock_file_.value().c_str(), O_WRONLY | O_CREAT | O_TRUNC,
0666);
if (lock_fd_ == -1)
return true;
struct flock lock;
lock.l_start = 0;
lock.l_len = 0;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_pid = 0;
struct flock testlock = lock;
if (fcntl(lock_fd_, F_GETLK, &testlock) == -1) {
close(lock_fd_);
lock_fd_ = -1;
return true;
} else if (fcntl(lock_fd_, F_SETLK, &lock) == -1) {
close(lock_fd_);
lock_fd_ = -1;
if (errno == EAGAIN || errno == EACCES)
return false;
else
return true;
} else {
// We have the lock.
return true;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include "DataArrayHDF5.hpp"
#include "h5x/H5DataSet.hpp"
#include "DimensionHDF5.hpp"
using namespace std;
using namespace nix::base;
namespace nix {
namespace hdf5 {
DataArrayHDF5::DataArrayHDF5(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const H5Group &group)
: EntityWithSourcesHDF5(file, block, group) {
dimension_group = this->group().openOptGroup("dimensions");
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group,
const string &id, const string &type, const string &name)
: DataArrayHDF5(file, block, group, id, type, name, util::getTime()) {
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group,
const string &id, const string &type, const string &name, time_t time)
: EntityWithSourcesHDF5(file, block, group, id, type, name, time) {
dimension_group = this->group().openOptGroup("dimensions");
}
//--------------------------------------------------
// Element getters and setters
//--------------------------------------------------
boost::optional<std::string> DataArrayHDF5::label() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("label", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::label(const string &label) {
group().setAttr("label", label);
forceUpdatedAt();
}
void DataArrayHDF5::label(const none_t t) {
if (group().hasAttr("label")) {
group().removeAttr("label");
}
forceUpdatedAt();
}
boost::optional<std::string> DataArrayHDF5::unit() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("unit", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::unit(const string &unit) {
group().setAttr("unit", unit);
forceUpdatedAt();
}
void DataArrayHDF5::unit(const none_t t) {
if (group().hasAttr("unit")) {
group().removeAttr("unit");
}
forceUpdatedAt();
}
// TODO use defaults
boost::optional<double> DataArrayHDF5::expansionOrigin() const {
boost::optional<double> ret;
double expansion_origin;
bool have_attr = group().getAttr("expansion_origin", expansion_origin);
if (have_attr) {
ret = expansion_origin;
}
return ret;
}
void DataArrayHDF5::expansionOrigin(double expansion_origin) {
group().setAttr("expansion_origin", expansion_origin);
forceUpdatedAt();
}
void DataArrayHDF5::expansionOrigin(const none_t t) {
if (group().hasAttr("expansion_origin")) {
group().removeAttr("expansion_origin");
}
forceUpdatedAt();
}
// TODO use defaults
vector<double> DataArrayHDF5::polynomCoefficients() const {
vector<double> polynom_coefficients;
if (group().hasData("polynom_coefficients")) {
DataSet ds = group().openData("polynom_coefficients");
ds.read(polynom_coefficients, true);
}
return polynom_coefficients;
}
void DataArrayHDF5::polynomCoefficients(const vector<double> &coefficients) {
DataSet ds;
if (group().hasData("polynom_coefficients")) {
ds = group().openData("polynom_coefficients");
ds.setExtent({coefficients.size()});
} else {
ds = group().createData("polynom_coefficients", DataType::Double, {coefficients.size()});
}
ds.write(coefficients);
forceUpdatedAt();
}
void DataArrayHDF5::polynomCoefficients(const none_t t) {
if (group().hasData("polynom_coefficients")) {
group().removeData("polynom_coefficients");
}
forceUpdatedAt();
}
//--------------------------------------------------
// Methods concerning dimensions
//--------------------------------------------------
ndsize_t DataArrayHDF5::dimensionCount() const {
boost::optional<H5Group> g = dimension_group();
ndsize_t count = 0;
if (g) {
count = g->objectCount();
}
return count;
}
shared_ptr<IDimension> DataArrayHDF5::getDimension(ndsize_t index) const {
shared_ptr<IDimension> dim;
boost::optional<H5Group> g = dimension_group();
if (g) {
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
H5Group group = g->openGroup(str_id, false);
dim = openDimensionHDF5(group, index);
}
}
return dim;
}
std::shared_ptr<base::ISetDimension> DataArrayHDF5::createSetDimension(ndsize_t index) {
H5Group g = createDimensionGroup(index);
return make_shared<SetDimensionHDF5>(g, index);
}
std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createRangeDimension(ndsize_t index, const std::vector<double> &ticks) {
H5Group g = createDimensionGroup(index);
return make_shared<RangeDimensionHDF5>(g, index, ticks);
}
std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createAliasRangeDimension() {
H5Group g = createDimensionGroup(1);
return make_shared<RangeDimensionHDF5>(g, 1, *this);
}
std::shared_ptr<base::ISampledDimension> DataArrayHDF5::createSampledDimension(ndsize_t index, double sampling_interval) {
H5Group g = createDimensionGroup(index);
return make_shared<SampledDimensionHDF5>(g, index, sampling_interval);
}
H5Group DataArrayHDF5::createDimensionGroup(ndsize_t index) {
boost::optional<H5Group> g = dimension_group(true);
ndsize_t dim_max = dimensionCount() + 1;
if (index > dim_max || index <= 0)
throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max));
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
}
return g->openGroup(str_id, true);
}
bool DataArrayHDF5::deleteDimension(ndsize_t index) {
bool deleted = false;
ndsize_t dim_count = dimensionCount();
string str_id = util::numToStr(index);
boost::optional<H5Group> g = dimension_group();
if (g) {
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
deleted = true;
}
if (deleted && index < dim_count) {
for (ndsize_t old_id = index + 1; old_id <= dim_count; old_id++) {
string str_old_id = util::numToStr(old_id);
string str_new_id = util::numToStr(old_id - 1);
g->renameGroup(str_old_id, str_new_id);
}
}
}
return deleted;
}
//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------
DataArrayHDF5::~DataArrayHDF5() {
}
void DataArrayHDF5::createData(DataType dtype, const NDSize &size) {
if (group().hasData("data")) {
throw ConsistencyError("DataArray's hdf5 data group already exists!");
}
group().createData("data", dtype, size); //FIXME: check if this 2-step creation is needed
DataSet ds = group().openData("data");
}
bool DataArrayHDF5::hasData() const {
return group().hasData("data");
}
void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) {
if (!group().hasData("data")) {
throw ConsistencyError("DataArray with missing h5df DataSet");
}
DataSet ds = group().openData("data");
if (offset.size()) {
Selection fileSel = ds.createSelection();
fileSel.select(count, offset);
Selection memSel(DataSpace::create(count, false));
ds.write(dtype, data, fileSel, memSel);
} else {
ds.write(dtype, count, data);
}
}
void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const {
if (!group().hasData("data")) {
return;
}
DataSet ds = group().openData("data");
if (offset.size()) {
Selection fileSel = ds.createSelection();
// if count.size() == 0, i.e. we want to read a scalar,
// we have to supply something that fileSel can make sense of
fileSel.select(count ? count : NDSize(offset.size(), 1), offset);
Selection memSel(DataSpace::create(count, false));
ds.read(dtype, data, fileSel, memSel);
} else {
ds.read(dtype, count, data);
}
}
NDSize DataArrayHDF5::dataExtent(void) const {
if (!group().hasData("data")) {
return NDSize{};
}
DataSet ds = group().openData("data");
return ds.size();
}
void DataArrayHDF5::dataExtent(const NDSize &extent) {
if (!group().hasData("data")) {
throw runtime_error("Data field not found in DataArray!");
}
DataSet ds = group().openData("data");
ds.setExtent(extent);
}
DataType DataArrayHDF5::dataType(void) const {
if (!group().hasData("data")) {
return DataType::Nothing;
}
DataSet ds = group().openData("data");
const h5x::DataType dtype = ds.dataType();
return data_type_from_h5(dtype);
}
} // ns nix::hdf5
} // ns nix
<commit_msg>[hdf5] DataArray::createData, nix extra openData()<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/util/util.hpp>
#include "DataArrayHDF5.hpp"
#include "h5x/H5DataSet.hpp"
#include "DimensionHDF5.hpp"
using namespace std;
using namespace nix::base;
namespace nix {
namespace hdf5 {
DataArrayHDF5::DataArrayHDF5(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const H5Group &group)
: EntityWithSourcesHDF5(file, block, group) {
dimension_group = this->group().openOptGroup("dimensions");
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group,
const string &id, const string &type, const string &name)
: DataArrayHDF5(file, block, group, id, type, name, util::getTime()) {
}
DataArrayHDF5::DataArrayHDF5(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const H5Group &group,
const string &id, const string &type, const string &name, time_t time)
: EntityWithSourcesHDF5(file, block, group, id, type, name, time) {
dimension_group = this->group().openOptGroup("dimensions");
}
//--------------------------------------------------
// Element getters and setters
//--------------------------------------------------
boost::optional<std::string> DataArrayHDF5::label() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("label", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::label(const string &label) {
group().setAttr("label", label);
forceUpdatedAt();
}
void DataArrayHDF5::label(const none_t t) {
if (group().hasAttr("label")) {
group().removeAttr("label");
}
forceUpdatedAt();
}
boost::optional<std::string> DataArrayHDF5::unit() const {
boost::optional<std::string> ret;
string value;
bool have_attr = group().getAttr("unit", value);
if (have_attr) {
ret = value;
}
return ret;
}
void DataArrayHDF5::unit(const string &unit) {
group().setAttr("unit", unit);
forceUpdatedAt();
}
void DataArrayHDF5::unit(const none_t t) {
if (group().hasAttr("unit")) {
group().removeAttr("unit");
}
forceUpdatedAt();
}
// TODO use defaults
boost::optional<double> DataArrayHDF5::expansionOrigin() const {
boost::optional<double> ret;
double expansion_origin;
bool have_attr = group().getAttr("expansion_origin", expansion_origin);
if (have_attr) {
ret = expansion_origin;
}
return ret;
}
void DataArrayHDF5::expansionOrigin(double expansion_origin) {
group().setAttr("expansion_origin", expansion_origin);
forceUpdatedAt();
}
void DataArrayHDF5::expansionOrigin(const none_t t) {
if (group().hasAttr("expansion_origin")) {
group().removeAttr("expansion_origin");
}
forceUpdatedAt();
}
// TODO use defaults
vector<double> DataArrayHDF5::polynomCoefficients() const {
vector<double> polynom_coefficients;
if (group().hasData("polynom_coefficients")) {
DataSet ds = group().openData("polynom_coefficients");
ds.read(polynom_coefficients, true);
}
return polynom_coefficients;
}
void DataArrayHDF5::polynomCoefficients(const vector<double> &coefficients) {
DataSet ds;
if (group().hasData("polynom_coefficients")) {
ds = group().openData("polynom_coefficients");
ds.setExtent({coefficients.size()});
} else {
ds = group().createData("polynom_coefficients", DataType::Double, {coefficients.size()});
}
ds.write(coefficients);
forceUpdatedAt();
}
void DataArrayHDF5::polynomCoefficients(const none_t t) {
if (group().hasData("polynom_coefficients")) {
group().removeData("polynom_coefficients");
}
forceUpdatedAt();
}
//--------------------------------------------------
// Methods concerning dimensions
//--------------------------------------------------
ndsize_t DataArrayHDF5::dimensionCount() const {
boost::optional<H5Group> g = dimension_group();
ndsize_t count = 0;
if (g) {
count = g->objectCount();
}
return count;
}
shared_ptr<IDimension> DataArrayHDF5::getDimension(ndsize_t index) const {
shared_ptr<IDimension> dim;
boost::optional<H5Group> g = dimension_group();
if (g) {
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
H5Group group = g->openGroup(str_id, false);
dim = openDimensionHDF5(group, index);
}
}
return dim;
}
std::shared_ptr<base::ISetDimension> DataArrayHDF5::createSetDimension(ndsize_t index) {
H5Group g = createDimensionGroup(index);
return make_shared<SetDimensionHDF5>(g, index);
}
std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createRangeDimension(ndsize_t index, const std::vector<double> &ticks) {
H5Group g = createDimensionGroup(index);
return make_shared<RangeDimensionHDF5>(g, index, ticks);
}
std::shared_ptr<base::IRangeDimension> DataArrayHDF5::createAliasRangeDimension() {
H5Group g = createDimensionGroup(1);
return make_shared<RangeDimensionHDF5>(g, 1, *this);
}
std::shared_ptr<base::ISampledDimension> DataArrayHDF5::createSampledDimension(ndsize_t index, double sampling_interval) {
H5Group g = createDimensionGroup(index);
return make_shared<SampledDimensionHDF5>(g, index, sampling_interval);
}
H5Group DataArrayHDF5::createDimensionGroup(ndsize_t index) {
boost::optional<H5Group> g = dimension_group(true);
ndsize_t dim_max = dimensionCount() + 1;
if (index > dim_max || index <= 0)
throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max));
string str_id = util::numToStr(index);
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
}
return g->openGroup(str_id, true);
}
bool DataArrayHDF5::deleteDimension(ndsize_t index) {
bool deleted = false;
ndsize_t dim_count = dimensionCount();
string str_id = util::numToStr(index);
boost::optional<H5Group> g = dimension_group();
if (g) {
if (g->hasGroup(str_id)) {
g->removeGroup(str_id);
deleted = true;
}
if (deleted && index < dim_count) {
for (ndsize_t old_id = index + 1; old_id <= dim_count; old_id++) {
string str_old_id = util::numToStr(old_id);
string str_new_id = util::numToStr(old_id - 1);
g->renameGroup(str_old_id, str_new_id);
}
}
}
return deleted;
}
//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------
DataArrayHDF5::~DataArrayHDF5() {
}
void DataArrayHDF5::createData(DataType dtype, const NDSize &size) {
if (group().hasData("data")) {
throw ConsistencyError("DataArray's hdf5 data group already exists!");
}
group().createData("data", dtype, size);
}
bool DataArrayHDF5::hasData() const {
return group().hasData("data");
}
void DataArrayHDF5::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) {
if (!group().hasData("data")) {
throw ConsistencyError("DataArray with missing h5df DataSet");
}
DataSet ds = group().openData("data");
if (offset.size()) {
Selection fileSel = ds.createSelection();
fileSel.select(count, offset);
Selection memSel(DataSpace::create(count, false));
ds.write(dtype, data, fileSel, memSel);
} else {
ds.write(dtype, count, data);
}
}
void DataArrayHDF5::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const {
if (!group().hasData("data")) {
return;
}
DataSet ds = group().openData("data");
if (offset.size()) {
Selection fileSel = ds.createSelection();
// if count.size() == 0, i.e. we want to read a scalar,
// we have to supply something that fileSel can make sense of
fileSel.select(count ? count : NDSize(offset.size(), 1), offset);
Selection memSel(DataSpace::create(count, false));
ds.read(dtype, data, fileSel, memSel);
} else {
ds.read(dtype, count, data);
}
}
NDSize DataArrayHDF5::dataExtent(void) const {
if (!group().hasData("data")) {
return NDSize{};
}
DataSet ds = group().openData("data");
return ds.size();
}
void DataArrayHDF5::dataExtent(const NDSize &extent) {
if (!group().hasData("data")) {
throw runtime_error("Data field not found in DataArray!");
}
DataSet ds = group().openData("data");
ds.setExtent(extent);
}
DataType DataArrayHDF5::dataType(void) const {
if (!group().hasData("data")) {
return DataType::Nothing;
}
DataSet ds = group().openData("data");
const h5x::DataType dtype = ds.dataType();
return data_type_from_h5(dtype);
}
} // ns nix::hdf5
} // ns nix
<|endoftext|>
|
<commit_before><commit_msg>Fix for x64 handler registration<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include <algorithm>
namespace crest {
namespace algo {
template <typename Container, typename Element>
bool contains(const Container & c, const Element & element)
{
return std::find(c.begin(), c.end(), element) != c.end();
};
template <typename Container>
Container sorted_unique(Container c)
{
std::sort(c.begin(), c.end());
c.erase(std::unique(c.begin(), c.end()), c.end());
return c;
}
template <typename Integer, typename ForwardIt>
void fill_strided_integers(ForwardIt begin, ForwardIt end, Integer start = 0, Integer stride = 1)
{
Integer current_value = start;
std::generate(begin, end, [&] {
const auto val = current_value;
current_value += stride;
return val;
});
};
template <typename OutputIt, typename Integer>
void fill_strided_integers_n(OutputIt first, Integer count, Integer start = 0, Integer stride = 1)
{
Integer current_value = start;
std::generate_n(first, count, [&] {
const auto val = current_value;
current_value += stride;
return val;
});
};
}
}
<commit_msg>Implement indexOf<commit_after>#pragma once
#include <algorithm>
namespace crest {
namespace algo {
template <typename Container, typename Element>
bool contains(const Container & c, const Element & element)
{
return std::find(c.begin(), c.end(), element) != c.end();
};
// Returns the index of the first occurrence of element in the contiguous random-access container c.
// If the element does not exist, returns ~0u (the maximum unsigned value).
template <typename Container, typename Element>
size_t index_of(const Container & c, const Element & element)
{
const auto it = std::find(c.begin(), c.end(), element);
return it != c.end()
? it - c.begin()
: ~0u;
};
template <typename Container>
Container sorted_unique(Container c)
{
std::sort(c.begin(), c.end());
c.erase(std::unique(c.begin(), c.end()), c.end());
return c;
}
template <typename Integer, typename ForwardIt>
void fill_strided_integers(ForwardIt begin, ForwardIt end, Integer start = 0, Integer stride = 1)
{
Integer current_value = start;
std::generate(begin, end, [&] {
const auto val = current_value;
current_value += stride;
return val;
});
};
template <typename OutputIt, typename Integer>
void fill_strided_integers_n(OutputIt first, Integer count, Integer start = 0, Integer stride = 1)
{
Integer current_value = start;
std::generate_n(first, count, [&] {
const auto val = current_value;
current_value += stride;
return val;
});
};
}
}
<|endoftext|>
|
<commit_before>/*
* main.cpp
*
* Created on: 2011-11-15
* Author: matlab
*/
#include <stdio.h>
// Qt stuff
#include <QtCore/QTime>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QGraphicsRectItem>
#include <QtGui/QPen>
#include <QtGui/QColor>
// OpenCV stuff
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/calib3d/calib3d.hpp> // for homography
// From this project (see src folder)
#include "ObjWidget.h"
void showUsage()
{
printf("\n");
printf("Usage :\n");
printf(" ./example object.png scene.png\n");
exit(1);
}
int main(int argc, char * argv[])
{
if(argc<3)
{
showUsage();
}
QTime time;
time.start();
// GUI stuff
QApplication app(argc, argv);
ObjWidget objWidget;
ObjWidget sceneWidget;
//Load as grayscale
IplImage * objectImg = cvLoadImage(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
IplImage * sceneImg = cvLoadImage(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
if(objectImg && sceneImg)
{
std::vector<cv::KeyPoint> objectKeypoints;
std::vector<cv::KeyPoint> sceneKeypoints;
cv::Mat objectDescriptors;
cv::Mat sceneDescriptors;
////////////////////////////
// EXTRACT KEYPOINTS
////////////////////////////
// The detector can be any of (see OpenCV features2d.hpp):
// cv::FeatureDetector * detector = new cv::FastFeatureDetector();
// cv::FeatureDetector * detector = new cv::SiftFeatureDetector();
// cv::FeatureDetector * detector = new cv::SurfFeatureDetector();
// cv::FeatureDetector * detector = new cv::StarFeatureDetector();
cv::FeatureDetector * detector = new cv::SurfFeatureDetector();
detector->detect(objectImg, objectKeypoints);
printf("Object: %d keypoints detected in %d ms\n", (int)objectKeypoints.size(), time.restart());
detector->detect(sceneImg, sceneKeypoints);
printf("Scene: %d keypoints detected in %d ms\n", (int)sceneKeypoints.size(), time.restart());
////////////////////////////
// EXTRACT DESCRIPTORS
////////////////////////////
// The extractor can be any of (see OpenCV features2d.hpp):
// cv::DescriptorExtractor * detector = new cv::BriefDescriptorExtractor();
// cv::DescriptorExtractor * detector = new cv::SiftFeatureDetector();
// cv::DescriptorExtractor * detector = new cv::SurfFeatureDetector();
cv::DescriptorExtractor * extractor = new cv::SurfDescriptorExtractor();
extractor->compute(objectImg, objectKeypoints, objectDescriptors);
printf("Object: %d descriptors extracted in %d ms\n", objectDescriptors.rows, time.restart());
extractor->compute(sceneImg, sceneKeypoints, sceneDescriptors);
printf("Scene: %d descriptors extracted in %d ms\n", sceneDescriptors.rows, time.restart());
////////////////////////////
// NEAREST NEIGHBOR MATCHING USING FLANN LIBRARY (included in OpenCV)
////////////////////////////
// Format descriptors for Flann
cv::Mat objectData;
cv::Mat sceneData;
if(objectDescriptors.type()!=CV_32F) {
objectDescriptors.convertTo(objectData, CV_32F); // make sure it's CV_32F
}
else {
objectData = objectDescriptors;
}
if(sceneDescriptors.type()!=CV_32F) {
sceneDescriptors.convertTo(sceneData, CV_32F); // make sure it's CV_32F
}
else {
sceneData = sceneDescriptors;
}
// Create Flann index
cv::flann::Index treeFlannIndex(sceneData, cv::flann::KDTreeIndexParams());
printf("Time creating FLANN index = %d ms\n", time.restart());
// search (nearest neighbor)
int k=2; // find the 2 nearest neighbors
cv::Mat results(objectData.rows, k, CV_32SC1); // Results index
cv::Mat dists(objectData.rows, k, CV_32FC1); // Distance results are CV_32FC1
treeFlannIndex.knnSearch(objectData, results, dists, k, cv::flann::SearchParams() ); // maximum number of leafs checked
printf("Time nearest neighbor search = %d ms\n", time.restart());
////////////////////////////
// PROCESS NEAREST NEIGHBOR RESULTS
////////////////////////////
// Set gui data
objWidget.setData(objectKeypoints, objectDescriptors, objectImg);
sceneWidget.setData(sceneKeypoints, sceneDescriptors, sceneImg);
// Find correspondences by NNDR (Nearest Neighbor Distance Ratio)
float nndrRatio = 0.6;
std::vector<cv::Point2f> mpts_1, mpts_2; // Used for homography
std::vector<int> indexes_1, indexes_2; // Used for homography
std::vector<uchar> outlier_mask; // Used for homography
for(unsigned int i=0; i<objectData.rows; ++i)
{
// Check if this descriptor matches with those of the objects
// Apply NNDR
if(dists.at<float>(i,0) <= nndrRatio * dists.at<float>(i,1))
{
mpts_1.push_back(objectKeypoints.at(i).pt);
indexes_1.push_back(i);
mpts_2.push_back(sceneKeypoints.at(results.at<int>(i,0)).pt);
indexes_2.push_back(results.at<int>(i,0));
}
}
// FIND HOMOGRAPHY
int minInliers = 8;
if(mpts_1.size() >= minInliers)
{
time.start();
cv::Mat H = findHomography(mpts_1,
mpts_2,
cv::RANSAC,
1.0,
outlier_mask);
printf("Time finding homography = %d ms\n", time.restart());
int inliers=0, outliers=0;
for(int k=0; k<mpts_1.size();++k)
{
if(outlier_mask.at(k))
{
++inliers;
}
else
{
++outliers;
}
}
QTransform hTransform(
H.at<double>(0,0), H.at<double>(1,0), H.at<double>(2,0),
H.at<double>(0,1), H.at<double>(1,1), H.at<double>(2,1),
H.at<double>(0,2), H.at<double>(1,2), H.at<double>(2,2));
// GUI : Change color and add homography rectangle
QColor color(Qt::red);
int alpha = 130;
color.setAlpha(alpha);
for(int k=0; k<mpts_1.size();++k)
{
if(outlier_mask.at(k))
{
objWidget.setKptColor(indexes_1.at(k), color);
sceneWidget.setKptColor(indexes_2.at(k), color);
}
else
{
objWidget.setKptColor(indexes_1.at(k), QColor(0,0,0,alpha));
}
}
QPen rectPen(color);
rectPen.setWidth(4);
QGraphicsRectItem * rectItem = new QGraphicsRectItem(objWidget.image().rect());
rectItem->setPen(rectPen);
rectItem->setTransform(hTransform);
sceneWidget.addRect(rectItem);
printf("Inliers=%d Outliers=%d\n", inliers, outliers);
}
else
{
printf("Not enough matches (%d) for homography...\n", (int)mpts_1.size());
}
// Wait for gui
objWidget.setGraphicsViewMode(false);
objWidget.setWindowTitle("Object");
objWidget.show();
sceneWidget.setGraphicsViewMode(false);
sceneWidget.setWindowTitle("Scene");
sceneWidget.show();
int r = app.exec();
printf("Closing...\n");
////////////////////////////
//Cleanup
////////////////////////////
delete detector;
delete extractor;
if(objectImg) {
cvReleaseImage(&objectImg);
}
if(sceneImg) {
cvReleaseImage(&sceneImg);
}
return r;
}
else
{
if(objectImg) {
cvReleaseImage(&objectImg);
}
if(sceneImg) {
cvReleaseImage(&sceneImg);
}
printf("Images are not valid!\n");
showUsage();
}
return 1;
}
<commit_msg>Fixed a comment typo<commit_after>/*
* main.cpp
*
* Created on: 2011-11-15
* Author: matlab
*/
#include <stdio.h>
// Qt stuff
#include <QtCore/QTime>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QGraphicsRectItem>
#include <QtGui/QPen>
#include <QtGui/QColor>
// OpenCV stuff
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/calib3d/calib3d.hpp> // for homography
// From this project (see src folder)
#include "ObjWidget.h"
void showUsage()
{
printf("\n");
printf("Usage :\n");
printf(" ./example object.png scene.png\n");
exit(1);
}
int main(int argc, char * argv[])
{
if(argc<3)
{
showUsage();
}
QTime time;
time.start();
// GUI stuff
QApplication app(argc, argv);
ObjWidget objWidget;
ObjWidget sceneWidget;
//Load as grayscale
IplImage * objectImg = cvLoadImage(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
IplImage * sceneImg = cvLoadImage(argv[2], CV_LOAD_IMAGE_GRAYSCALE);
if(objectImg && sceneImg)
{
std::vector<cv::KeyPoint> objectKeypoints;
std::vector<cv::KeyPoint> sceneKeypoints;
cv::Mat objectDescriptors;
cv::Mat sceneDescriptors;
////////////////////////////
// EXTRACT KEYPOINTS
////////////////////////////
// The detector can be any of (see OpenCV features2d.hpp):
// cv::FeatureDetector * detector = new cv::FastFeatureDetector();
// cv::FeatureDetector * detector = new cv::SiftFeatureDetector();
// cv::FeatureDetector * detector = new cv::SurfFeatureDetector();
// cv::FeatureDetector * detector = new cv::StarFeatureDetector();
cv::FeatureDetector * detector = new cv::SurfFeatureDetector();
detector->detect(objectImg, objectKeypoints);
printf("Object: %d keypoints detected in %d ms\n", (int)objectKeypoints.size(), time.restart());
detector->detect(sceneImg, sceneKeypoints);
printf("Scene: %d keypoints detected in %d ms\n", (int)sceneKeypoints.size(), time.restart());
////////////////////////////
// EXTRACT DESCRIPTORS
////////////////////////////
// The extractor can be any of (see OpenCV features2d.hpp):
// cv::DescriptorExtractor * detector = new cv::BriefDescriptorExtractor();
// cv::DescriptorExtractor * detector = new cv::SiftDescriptorExtractor();
// cv::DescriptorExtractor * detector = new cv::SurfDescriptorExtractor();
cv::DescriptorExtractor * extractor = new cv::SurfDescriptorExtractor();
extractor->compute(objectImg, objectKeypoints, objectDescriptors);
printf("Object: %d descriptors extracted in %d ms\n", objectDescriptors.rows, time.restart());
extractor->compute(sceneImg, sceneKeypoints, sceneDescriptors);
printf("Scene: %d descriptors extracted in %d ms\n", sceneDescriptors.rows, time.restart());
////////////////////////////
// NEAREST NEIGHBOR MATCHING USING FLANN LIBRARY (included in OpenCV)
////////////////////////////
// Format descriptors for Flann
cv::Mat objectData;
cv::Mat sceneData;
if(objectDescriptors.type()!=CV_32F) {
objectDescriptors.convertTo(objectData, CV_32F); // make sure it's CV_32F
}
else {
objectData = objectDescriptors;
}
if(sceneDescriptors.type()!=CV_32F) {
sceneDescriptors.convertTo(sceneData, CV_32F); // make sure it's CV_32F
}
else {
sceneData = sceneDescriptors;
}
// Create Flann index
cv::flann::Index treeFlannIndex(sceneData, cv::flann::KDTreeIndexParams());
printf("Time creating FLANN index = %d ms\n", time.restart());
// search (nearest neighbor)
int k=2; // find the 2 nearest neighbors
cv::Mat results(objectData.rows, k, CV_32SC1); // Results index
cv::Mat dists(objectData.rows, k, CV_32FC1); // Distance results are CV_32FC1
treeFlannIndex.knnSearch(objectData, results, dists, k, cv::flann::SearchParams() ); // maximum number of leafs checked
printf("Time nearest neighbor search = %d ms\n", time.restart());
////////////////////////////
// PROCESS NEAREST NEIGHBOR RESULTS
////////////////////////////
// Set gui data
objWidget.setData(objectKeypoints, objectDescriptors, objectImg);
sceneWidget.setData(sceneKeypoints, sceneDescriptors, sceneImg);
// Find correspondences by NNDR (Nearest Neighbor Distance Ratio)
float nndrRatio = 0.6;
std::vector<cv::Point2f> mpts_1, mpts_2; // Used for homography
std::vector<int> indexes_1, indexes_2; // Used for homography
std::vector<uchar> outlier_mask; // Used for homography
for(unsigned int i=0; i<objectData.rows; ++i)
{
// Check if this descriptor matches with those of the objects
// Apply NNDR
if(dists.at<float>(i,0) <= nndrRatio * dists.at<float>(i,1))
{
mpts_1.push_back(objectKeypoints.at(i).pt);
indexes_1.push_back(i);
mpts_2.push_back(sceneKeypoints.at(results.at<int>(i,0)).pt);
indexes_2.push_back(results.at<int>(i,0));
}
}
// FIND HOMOGRAPHY
int minInliers = 8;
if(mpts_1.size() >= minInliers)
{
time.start();
cv::Mat H = findHomography(mpts_1,
mpts_2,
cv::RANSAC,
1.0,
outlier_mask);
printf("Time finding homography = %d ms\n", time.restart());
int inliers=0, outliers=0;
for(int k=0; k<mpts_1.size();++k)
{
if(outlier_mask.at(k))
{
++inliers;
}
else
{
++outliers;
}
}
QTransform hTransform(
H.at<double>(0,0), H.at<double>(1,0), H.at<double>(2,0),
H.at<double>(0,1), H.at<double>(1,1), H.at<double>(2,1),
H.at<double>(0,2), H.at<double>(1,2), H.at<double>(2,2));
// GUI : Change color and add homography rectangle
QColor color(Qt::red);
int alpha = 130;
color.setAlpha(alpha);
for(int k=0; k<mpts_1.size();++k)
{
if(outlier_mask.at(k))
{
objWidget.setKptColor(indexes_1.at(k), color);
sceneWidget.setKptColor(indexes_2.at(k), color);
}
else
{
objWidget.setKptColor(indexes_1.at(k), QColor(0,0,0,alpha));
}
}
QPen rectPen(color);
rectPen.setWidth(4);
QGraphicsRectItem * rectItem = new QGraphicsRectItem(objWidget.image().rect());
rectItem->setPen(rectPen);
rectItem->setTransform(hTransform);
sceneWidget.addRect(rectItem);
printf("Inliers=%d Outliers=%d\n", inliers, outliers);
}
else
{
printf("Not enough matches (%d) for homography...\n", (int)mpts_1.size());
}
// Wait for gui
objWidget.setGraphicsViewMode(false);
objWidget.setWindowTitle("Object");
objWidget.show();
sceneWidget.setGraphicsViewMode(false);
sceneWidget.setWindowTitle("Scene");
sceneWidget.show();
int r = app.exec();
printf("Closing...\n");
////////////////////////////
//Cleanup
////////////////////////////
delete detector;
delete extractor;
if(objectImg) {
cvReleaseImage(&objectImg);
}
if(sceneImg) {
cvReleaseImage(&sceneImg);
}
return r;
}
else
{
if(objectImg) {
cvReleaseImage(&objectImg);
}
if(sceneImg) {
cvReleaseImage(&sceneImg);
}
printf("Images are not valid!\n");
showUsage();
}
return 1;
}
<|endoftext|>
|
<commit_before>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "common/util/file_util.h"
#include <algorithm>
#include <filesystem>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::HasSubstr;
#undef EXPECT_OK
#define EXPECT_OK(value) \
{ \
auto s = (value); \
EXPECT_TRUE(s.ok()) << s; \
}
#undef ASSERT_OK
#define ASSERT_OK(value) \
{ \
auto s = (value); \
ASSERT_TRUE(s.ok()) << s; \
}
namespace verible {
namespace util {
namespace {
using file::testing::ScopedTestFile;
TEST(FileUtil, Basename) {
EXPECT_EQ(file::Basename("/foo/bar/baz"), "baz");
EXPECT_EQ(file::Basename("foo/bar/baz"), "baz");
EXPECT_EQ(file::Basename("/foo/bar/"), "");
EXPECT_EQ(file::Basename("/"), "");
EXPECT_EQ(file::Basename(""), "");
}
TEST(FileUtil, Dirname) {
EXPECT_EQ(file::Dirname("/foo/bar/baz"), "/foo/bar");
EXPECT_EQ(file::Dirname("/foo/bar/baz.txt"), "/foo/bar");
EXPECT_EQ(file::Dirname("foo/bar/baz"), "foo/bar");
EXPECT_EQ(file::Dirname("/foo/bar/"), "/foo/bar");
EXPECT_EQ(file::Dirname("/"), "");
EXPECT_EQ(file::Dirname(""), "");
EXPECT_EQ(file::Dirname("."), ".");
EXPECT_EQ(file::Dirname("./"), ".");
}
TEST(FileUtil, Stem) {
EXPECT_EQ(file::Stem(""), "");
EXPECT_EQ(file::Stem("/foo/bar.baz"), "/foo/bar");
EXPECT_EQ(file::Stem("foo/bar.baz"), "foo/bar");
EXPECT_EQ(file::Stem("/foo/bar."), "/foo/bar");
EXPECT_EQ(file::Stem("/foo/bar"), "/foo/bar");
}
// Returns the forward-slashed path in platform-specific notation.
static std::string PlatformPath(const std::string& path) {
return std::filesystem::path(path).lexically_normal().string();
}
TEST(FileUtil, JoinPath) {
EXPECT_EQ(file::JoinPath("foo", ""), PlatformPath("foo/"));
EXPECT_EQ(file::JoinPath("", "bar"), "bar");
EXPECT_EQ(file::JoinPath("foo", "bar"), PlatformPath("foo/bar"));
// Assemble an absolute path
EXPECT_EQ(file::JoinPath("", "bar"), "bar");
EXPECT_EQ(file::JoinPath("/", "bar"), PlatformPath("/bar"));
// Lightly canonicalize multiple consecutive slashes
EXPECT_EQ(file::JoinPath("foo/", "bar"), PlatformPath("foo/bar"));
EXPECT_EQ(file::JoinPath("foo///", "bar"), PlatformPath("foo/bar"));
EXPECT_EQ(file::JoinPath("foo/", "/bar"), PlatformPath("foo/bar"));
EXPECT_EQ(file::JoinPath("foo/", "///bar"), PlatformPath("foo/bar"));
#ifdef _WIN32
EXPECT_EQ(file::JoinPath("C:\\foo", "bar"), "C:\\foo\\bar");
#endif
}
TEST(FileUtil, CreateDir) {
const std::string test_dir = file::JoinPath(testing::TempDir(), "test_dir");
const std::string test_file = file::JoinPath(test_dir, "foo");
const absl::string_view test_content = "directory create test";
EXPECT_OK(file::CreateDir(test_dir));
EXPECT_OK(file::CreateDir(test_dir)); // Creating twice should succeed
EXPECT_OK(file::SetContents(test_file, test_content));
std::string read_back_content;
EXPECT_OK(file::GetContents(test_file, &read_back_content));
EXPECT_EQ(test_content, read_back_content);
}
TEST(FileUtil, StatusErrorReporting) {
std::string content;
absl::Status status = file::GetContents("does-not-exist", &content);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kNotFound) << status;
const std::string test_file = file::JoinPath(testing::TempDir(), "test-err");
unlink(test_file.c_str()); // Remove file if left from previous test.
EXPECT_OK(file::SetContents(test_file, "foo"));
EXPECT_OK(file::GetContents(test_file, &content));
EXPECT_EQ(content, "foo");
chmod(test_file.c_str(), 0); // Enforce a permission denied situation
status = file::GetContents(test_file, &content);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kPermissionDenied) << status;
}
TEST(FileUtil, ScopedTestFile) {
const absl::string_view test_content = "Hello World!";
ScopedTestFile test_file(testing::TempDir(), test_content);
std::string read_back_content;
EXPECT_OK(file::GetContents(test_file.filename(), &read_back_content));
EXPECT_EQ(test_content, read_back_content);
}
static ScopedTestFile TestFileGenerator(absl::string_view content) {
return ScopedTestFile(testing::TempDir(), content);
}
static void TestFileConsumer(ScopedTestFile&& f) {
ScopedTestFile temp(std::move(f));
}
TEST(FileUtil, ScopedTestFileMove) {
ScopedTestFile f(TestFileGenerator("barfoo"));
std::string tmpname(f.filename());
EXPECT_TRUE(file::FileExists(tmpname).ok());
TestFileConsumer(std::move(f));
EXPECT_FALSE(file::FileExists(tmpname).ok());
}
TEST(FileUtil, ScopedTestFileEmplace) {
std::vector<std::string> names;
{
std::vector<ScopedTestFile> files;
for (size_t i = 0; i < 10; ++i) {
files.emplace_back(::testing::TempDir(), "zzz");
names.push_back(std::string(files.back().filename()));
}
for (const auto& name : names) {
EXPECT_TRUE(file::FileExists(name).ok());
}
}
for (const auto& name : names) {
EXPECT_FALSE(file::FileExists(name).ok());
}
}
TEST(FileUtil, FileExistsDirectoryErrorMessage) {
absl::Status s;
s = file::FileExists(testing::TempDir());
EXPECT_FALSE(s.ok());
EXPECT_THAT(s.message(), HasSubstr("is a directory"));
}
static bool CreateFsStructure(absl::string_view base_dir,
const std::vector<absl::string_view>& tree) {
for (absl::string_view path : tree) {
const std::string full_path = file::JoinPath(base_dir, path);
if (absl::EndsWith(path, "/")) {
if (!file::CreateDir(full_path).ok()) return false;
} else {
if (!file::SetContents(full_path, "(content)").ok()) return false;
}
}
return true;
}
TEST(FileUtil, UpwardFileSearchTest) {
const std::string root_dir = file::JoinPath(testing::TempDir(), "up-search");
ASSERT_OK(file::CreateDir(root_dir));
ASSERT_TRUE(CreateFsStructure(root_dir, {
"toplevel-file",
"foo/",
"foo/foo-file",
"foo/bar/",
"foo/bar/baz/",
"foo/bar/baz/baz-file",
}));
std::string result;
// Same directory
EXPECT_OK(file::UpwardFileSearch(file::JoinPath(root_dir, "foo"), "foo-file",
&result));
// We don't compare the full path, as the UpwardFileSearch() makes it an
// realpath which might not entirely match our root_dir prefix anymore; but
// we do know that the suffix should be the same.
EXPECT_TRUE(absl::EndsWith(result, PlatformPath("up-search/foo/foo-file")));
// Somewhere below
EXPECT_OK(file::UpwardFileSearch(file::JoinPath(root_dir, "foo/bar/baz"),
"foo-file", &result));
EXPECT_TRUE(absl::EndsWith(result, PlatformPath("up-search/foo/foo-file")));
// Find toplevel file
EXPECT_OK(file::UpwardFileSearch(file::JoinPath(root_dir, "foo/bar/baz"),
"toplevel-file", &result));
EXPECT_TRUE(absl::EndsWith(result, PlatformPath("up-search/toplevel-file")));
// Negative test.
auto status = file::UpwardFileSearch(file::JoinPath(root_dir, "foo/bar/baz"),
"unknownfile", &result);
EXPECT_FALSE(status.ok());
}
TEST(FileUtil, ReadEmptyDirectory) {
const std::string test_dir = file::JoinPath(testing::TempDir(), "empty_dir");
ASSERT_TRUE(file::CreateDir(test_dir).ok());
auto dir_or = file::ListDir(test_dir);
ASSERT_TRUE(dir_or.ok());
const auto& dir = *dir_or;
EXPECT_EQ(dir.path, test_dir);
EXPECT_TRUE(dir.directories.empty());
EXPECT_TRUE(dir.files.empty());
}
TEST(FileUtil, ReadNonexistentDirectory) {
const std::string test_dir =
file::JoinPath(testing::TempDir(), "dir_not_there");
auto dir_or = file::ListDir(test_dir);
EXPECT_FALSE(dir_or.ok());
EXPECT_EQ(dir_or.status().code(), absl::StatusCode::kNotFound);
}
TEST(FileUtil, ListNotADirectory) {
ScopedTestFile tempfile(testing::TempDir(), "O HAI, WRLD");
auto dir_or = file::ListDir(tempfile.filename());
EXPECT_FALSE(dir_or.ok());
EXPECT_EQ(dir_or.status().code(), absl::StatusCode::kInvalidArgument);
}
TEST(FileUtil, ReadDirectory) {
const std::string test_dir = file::JoinPath(testing::TempDir(), "mixed_dir");
const std::string test_subdir1 = file::JoinPath(test_dir, "subdir1");
const std::string test_subdir2 = file::JoinPath(test_dir, "subdir2");
std::vector<std::string> test_directories{test_subdir1, test_subdir2};
ASSERT_TRUE(file::CreateDir(test_dir).ok());
ASSERT_TRUE(file::CreateDir(test_subdir1).ok());
ASSERT_TRUE(file::CreateDir(test_subdir2).ok());
const absl::string_view test_content = "Hello World!";
file::testing::ScopedTestFile test_file1(test_dir, test_content);
file::testing::ScopedTestFile test_file2(test_dir, test_content);
file::testing::ScopedTestFile test_file3(test_dir, test_content);
std::vector<std::string> test_files;
test_files.emplace_back(test_file1.filename());
test_files.emplace_back(test_file2.filename());
test_files.emplace_back(test_file3.filename());
std::sort(test_files.begin(), test_files.end());
auto dir_or = file::ListDir(test_dir);
ASSERT_TRUE(dir_or.ok()) << dir_or.status().message();
const auto& dir = *dir_or;
EXPECT_EQ(dir.path, test_dir);
EXPECT_EQ(dir.directories.size(), test_directories.size());
EXPECT_EQ(dir.directories, test_directories);
EXPECT_EQ(dir.files.size(), test_files.size());
EXPECT_EQ(dir.files, test_files);
}
} // namespace
} // namespace util
} // namespace verible
<commit_msg>chmod() does not work on Win32<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "common/util/file_util.h"
#include <algorithm>
#include <filesystem>
#include <string>
#include <vector>
#include "absl/status/status.h"
#include "absl/strings/match.h"
#include "absl/strings/string_view.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::HasSubstr;
#undef EXPECT_OK
#define EXPECT_OK(value) \
{ \
auto s = (value); \
EXPECT_TRUE(s.ok()) << s; \
}
#undef ASSERT_OK
#define ASSERT_OK(value) \
{ \
auto s = (value); \
ASSERT_TRUE(s.ok()) << s; \
}
namespace verible {
namespace util {
namespace {
using file::testing::ScopedTestFile;
TEST(FileUtil, Basename) {
EXPECT_EQ(file::Basename("/foo/bar/baz"), "baz");
EXPECT_EQ(file::Basename("foo/bar/baz"), "baz");
EXPECT_EQ(file::Basename("/foo/bar/"), "");
EXPECT_EQ(file::Basename("/"), "");
EXPECT_EQ(file::Basename(""), "");
}
TEST(FileUtil, Dirname) {
EXPECT_EQ(file::Dirname("/foo/bar/baz"), "/foo/bar");
EXPECT_EQ(file::Dirname("/foo/bar/baz.txt"), "/foo/bar");
EXPECT_EQ(file::Dirname("foo/bar/baz"), "foo/bar");
EXPECT_EQ(file::Dirname("/foo/bar/"), "/foo/bar");
EXPECT_EQ(file::Dirname("/"), "");
EXPECT_EQ(file::Dirname(""), "");
EXPECT_EQ(file::Dirname("."), ".");
EXPECT_EQ(file::Dirname("./"), ".");
}
TEST(FileUtil, Stem) {
EXPECT_EQ(file::Stem(""), "");
EXPECT_EQ(file::Stem("/foo/bar.baz"), "/foo/bar");
EXPECT_EQ(file::Stem("foo/bar.baz"), "foo/bar");
EXPECT_EQ(file::Stem("/foo/bar."), "/foo/bar");
EXPECT_EQ(file::Stem("/foo/bar"), "/foo/bar");
}
// Returns the forward-slashed path in platform-specific notation.
static std::string PlatformPath(const std::string& path) {
return std::filesystem::path(path).lexically_normal().string();
}
TEST(FileUtil, JoinPath) {
EXPECT_EQ(file::JoinPath("foo", ""), PlatformPath("foo/"));
EXPECT_EQ(file::JoinPath("", "bar"), "bar");
EXPECT_EQ(file::JoinPath("foo", "bar"), PlatformPath("foo/bar"));
// Assemble an absolute path
EXPECT_EQ(file::JoinPath("", "bar"), "bar");
EXPECT_EQ(file::JoinPath("/", "bar"), PlatformPath("/bar"));
// Lightly canonicalize multiple consecutive slashes
EXPECT_EQ(file::JoinPath("foo/", "bar"), PlatformPath("foo/bar"));
EXPECT_EQ(file::JoinPath("foo///", "bar"), PlatformPath("foo/bar"));
EXPECT_EQ(file::JoinPath("foo/", "/bar"), PlatformPath("foo/bar"));
EXPECT_EQ(file::JoinPath("foo/", "///bar"), PlatformPath("foo/bar"));
#ifdef _WIN32
EXPECT_EQ(file::JoinPath("C:\\foo", "bar"), "C:\\foo\\bar");
#endif
}
TEST(FileUtil, CreateDir) {
const std::string test_dir = file::JoinPath(testing::TempDir(), "test_dir");
const std::string test_file = file::JoinPath(test_dir, "foo");
const absl::string_view test_content = "directory create test";
EXPECT_OK(file::CreateDir(test_dir));
EXPECT_OK(file::CreateDir(test_dir)); // Creating twice should succeed
EXPECT_OK(file::SetContents(test_file, test_content));
std::string read_back_content;
EXPECT_OK(file::GetContents(test_file, &read_back_content));
EXPECT_EQ(test_content, read_back_content);
}
TEST(FileUtil, StatusErrorReporting) {
std::string content;
absl::Status status = file::GetContents("does-not-exist", &content);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kNotFound) << status;
const std::string test_file = file::JoinPath(testing::TempDir(), "test-err");
unlink(test_file.c_str()); // Remove file if left from previous test.
EXPECT_OK(file::SetContents(test_file, "foo"));
EXPECT_OK(file::GetContents(test_file, &content));
EXPECT_EQ(content, "foo");
#ifndef _WIN32
// The following chmod() is not working on Win32. So let's not use
// this test here.
// TODO: Can we make permission-denied test that works on Windows ?
chmod(test_file.c_str(), 0); // Enforce a permission denied situation
status = file::GetContents(test_file, &content);
EXPECT_FALSE(status.ok());
EXPECT_EQ(status.code(), absl::StatusCode::kPermissionDenied) << status;
#endif
}
TEST(FileUtil, ScopedTestFile) {
const absl::string_view test_content = "Hello World!";
ScopedTestFile test_file(testing::TempDir(), test_content);
std::string read_back_content;
EXPECT_OK(file::GetContents(test_file.filename(), &read_back_content));
EXPECT_EQ(test_content, read_back_content);
}
static ScopedTestFile TestFileGenerator(absl::string_view content) {
return ScopedTestFile(testing::TempDir(), content);
}
static void TestFileConsumer(ScopedTestFile&& f) {
ScopedTestFile temp(std::move(f));
}
TEST(FileUtil, ScopedTestFileMove) {
ScopedTestFile f(TestFileGenerator("barfoo"));
std::string tmpname(f.filename());
EXPECT_TRUE(file::FileExists(tmpname).ok());
TestFileConsumer(std::move(f));
EXPECT_FALSE(file::FileExists(tmpname).ok());
}
TEST(FileUtil, ScopedTestFileEmplace) {
std::vector<std::string> names;
{
std::vector<ScopedTestFile> files;
for (size_t i = 0; i < 10; ++i) {
files.emplace_back(::testing::TempDir(), "zzz");
names.push_back(std::string(files.back().filename()));
}
for (const auto& name : names) {
EXPECT_TRUE(file::FileExists(name).ok());
}
}
for (const auto& name : names) {
EXPECT_FALSE(file::FileExists(name).ok());
}
}
TEST(FileUtil, FileExistsDirectoryErrorMessage) {
absl::Status s;
s = file::FileExists(testing::TempDir());
EXPECT_FALSE(s.ok());
EXPECT_THAT(s.message(), HasSubstr("is a directory"));
}
static bool CreateFsStructure(absl::string_view base_dir,
const std::vector<absl::string_view>& tree) {
for (absl::string_view path : tree) {
const std::string full_path = file::JoinPath(base_dir, path);
if (absl::EndsWith(path, "/")) {
if (!file::CreateDir(full_path).ok()) return false;
} else {
if (!file::SetContents(full_path, "(content)").ok()) return false;
}
}
return true;
}
TEST(FileUtil, UpwardFileSearchTest) {
const std::string root_dir = file::JoinPath(testing::TempDir(), "up-search");
ASSERT_OK(file::CreateDir(root_dir));
ASSERT_TRUE(CreateFsStructure(root_dir, {
"toplevel-file",
"foo/",
"foo/foo-file",
"foo/bar/",
"foo/bar/baz/",
"foo/bar/baz/baz-file",
}));
std::string result;
// Same directory
EXPECT_OK(file::UpwardFileSearch(file::JoinPath(root_dir, "foo"), "foo-file",
&result));
// We don't compare the full path, as the UpwardFileSearch() makes it an
// realpath which might not entirely match our root_dir prefix anymore; but
// we do know that the suffix should be the same.
EXPECT_TRUE(absl::EndsWith(result, PlatformPath("up-search/foo/foo-file")));
// Somewhere below
EXPECT_OK(file::UpwardFileSearch(file::JoinPath(root_dir, "foo/bar/baz"),
"foo-file", &result));
EXPECT_TRUE(absl::EndsWith(result, PlatformPath("up-search/foo/foo-file")));
// Find toplevel file
EXPECT_OK(file::UpwardFileSearch(file::JoinPath(root_dir, "foo/bar/baz"),
"toplevel-file", &result));
EXPECT_TRUE(absl::EndsWith(result, PlatformPath("up-search/toplevel-file")));
// Negative test.
auto status = file::UpwardFileSearch(file::JoinPath(root_dir, "foo/bar/baz"),
"unknownfile", &result);
EXPECT_FALSE(status.ok());
}
TEST(FileUtil, ReadEmptyDirectory) {
const std::string test_dir = file::JoinPath(testing::TempDir(), "empty_dir");
ASSERT_TRUE(file::CreateDir(test_dir).ok());
auto dir_or = file::ListDir(test_dir);
ASSERT_TRUE(dir_or.ok());
const auto& dir = *dir_or;
EXPECT_EQ(dir.path, test_dir);
EXPECT_TRUE(dir.directories.empty());
EXPECT_TRUE(dir.files.empty());
}
TEST(FileUtil, ReadNonexistentDirectory) {
const std::string test_dir =
file::JoinPath(testing::TempDir(), "dir_not_there");
auto dir_or = file::ListDir(test_dir);
EXPECT_FALSE(dir_or.ok());
EXPECT_EQ(dir_or.status().code(), absl::StatusCode::kNotFound);
}
TEST(FileUtil, ListNotADirectory) {
ScopedTestFile tempfile(testing::TempDir(), "O HAI, WRLD");
auto dir_or = file::ListDir(tempfile.filename());
EXPECT_FALSE(dir_or.ok());
EXPECT_EQ(dir_or.status().code(), absl::StatusCode::kInvalidArgument);
}
TEST(FileUtil, ReadDirectory) {
const std::string test_dir = file::JoinPath(testing::TempDir(), "mixed_dir");
const std::string test_subdir1 = file::JoinPath(test_dir, "subdir1");
const std::string test_subdir2 = file::JoinPath(test_dir, "subdir2");
std::vector<std::string> test_directories{test_subdir1, test_subdir2};
ASSERT_TRUE(file::CreateDir(test_dir).ok());
ASSERT_TRUE(file::CreateDir(test_subdir1).ok());
ASSERT_TRUE(file::CreateDir(test_subdir2).ok());
const absl::string_view test_content = "Hello World!";
file::testing::ScopedTestFile test_file1(test_dir, test_content);
file::testing::ScopedTestFile test_file2(test_dir, test_content);
file::testing::ScopedTestFile test_file3(test_dir, test_content);
std::vector<std::string> test_files;
test_files.emplace_back(test_file1.filename());
test_files.emplace_back(test_file2.filename());
test_files.emplace_back(test_file3.filename());
std::sort(test_files.begin(), test_files.end());
auto dir_or = file::ListDir(test_dir);
ASSERT_TRUE(dir_or.ok()) << dir_or.status().message();
const auto& dir = *dir_or;
EXPECT_EQ(dir.path, test_dir);
EXPECT_EQ(dir.directories.size(), test_directories.size());
EXPECT_EQ(dir.directories, test_directories);
EXPECT_EQ(dir.files.size(), test_files.size());
EXPECT_EQ(dir.files, test_files);
}
} // namespace
} // namespace util
} // namespace verible
<|endoftext|>
|
<commit_before>namespace mant {
template <typename T, typename U = double>
class LipschitzContinuityAnalysis : public PassivePropertyAnalysis<T, U> {
public:
using PassivePropertyAnalysis<T, U>::PassivePropertyAnalysis;
double getLipschitzConstant() const noexcept;
std::string toString() const noexcept override;
protected:
double lipschitzConstant_;
void analyseImplementation(
const std::unordered_map<arma::Col<T>, U, Hash<T>, IsEqual<T>>& parameterToObjectiveValueMappings) noexcept override;
};
//
// Implementation
//
template <typename T, typename U>
double LipschitzContinuityAnalysis<T, U>::getLipschitzConstant() const noexcept {
return lipschitzConstant_;
}
template <typename T, typename U>
void LipschitzContinuityAnalysis<T, U>::analyseImplementation(
const std::unordered_map<arma::Col<T>, U, Hash<T>, IsEqual<T>>& parameterToObjectiveValueMappings) noexcept {
for (auto n = parameterToObjectiveValueMappings.cbegin(); n != parameterToObjectiveValueMappings.cend();) {
const arma::Col<T>& parameter = n->first;
const double& objectiveValue = n->second;
for (auto k = ++n; k != parameterToObjectiveValueMappings.cend(); ++k) {
}
}
}
template <typename T, typename U>
std::string LipschitzContinuityAnalysis<T, U>::toString() const noexcept {
return "lipschitz_continuity_analysis";
}
}
<commit_msg>Removed superflous reference<commit_after>namespace mant {
template <typename T, typename U = double>
class LipschitzContinuityAnalysis : public PassivePropertyAnalysis<T, U> {
public:
using PassivePropertyAnalysis<T, U>::PassivePropertyAnalysis;
double getLipschitzConstant() const noexcept;
std::string toString() const noexcept override;
protected:
double lipschitzConstant_;
void analyseImplementation(
const std::unordered_map<arma::Col<T>, U, Hash<T>, IsEqual<T>>& parameterToObjectiveValueMappings) noexcept override;
};
//
// Implementation
//
template <typename T, typename U>
double LipschitzContinuityAnalysis<T, U>::getLipschitzConstant() const noexcept {
return lipschitzConstant_;
}
template <typename T, typename U>
void LipschitzContinuityAnalysis<T, U>::analyseImplementation(
const std::unordered_map<arma::Col<T>, U, Hash<T>, IsEqual<T>>& parameterToObjectiveValueMappings) noexcept {
for (auto n = parameterToObjectiveValueMappings.cbegin(); n != parameterToObjectiveValueMappings.cend();) {
const arma::Col<T>& parameter = n->first;
const U objectiveValue = n->second;
for (auto k = ++n; k != parameterToObjectiveValueMappings.cend(); ++k) {
}
}
}
template <typename T, typename U>
std::string LipschitzContinuityAnalysis<T, U>::toString() const noexcept {
return "lipschitz_continuity_analysis";
}
}
<|endoftext|>
|
<commit_before>/**
* @file tc.hxx
* @author Muhammad A. Awad (mawad@ucdavis.edu)
* @brief Triangle Counting algorithm.
* @version 0.1
* @date 2022-08-06
*
* @copyright Copyright (c) 2022
*
*/
#pragma once
#include <gunrock/algorithms/algorithms.hxx>
namespace gunrock {
namespace tc {
template <typename vertex_t>
struct param_t {
bool reduce_all_triangles;
param_t(bool _reduce_all_triangles)
: reduce_all_triangles(_reduce_all_triangles) {}
};
template <typename vertex_t>
struct result_t {
vertex_t* vertex_triangles_count;
std::size_t* total_triangles_count;
result_t(vertex_t* _vertex_triangles_count, uint64_t* _total_triangles_count)
: vertex_triangles_count(_vertex_triangles_count),
total_triangles_count(_total_triangles_count) {}
};
template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
param_type param;
result_type result;
problem_t(graph_t& G,
param_type& _param,
result_type& _result,
std::shared_ptr<gcuda::multi_context_t> _context)
: gunrock::problem_t<graph_t>(G, _context),
param(_param),
result(_result) {}
using vertex_t = typename graph_t::vertex_type;
using edge_t = typename graph_t::edge_type;
void init() override {}
void reset() override {}
};
template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
enactor_t(problem_t* _problem,
std::shared_ptr<gcuda::multi_context_t> _context)
: gunrock::enactor_t<problem_t>(_problem, _context) {}
using vertex_t = typename problem_t::vertex_t;
using edge_t = typename problem_t::edge_t;
using weight_t = typename problem_t::weight_t;
using frontier_t = typename enactor_t<problem_t>::frontier_t;
void prepare_frontier(frontier_t* f,
gcuda::multi_context_t& context) override {
auto P = this->get_problem();
auto n_vertices = P->get_graph().get_number_of_vertices();
f->sequence((vertex_t)0, n_vertices, context.get_context(0)->stream());
}
void loop(gcuda::multi_context_t& context) override {
// Data slice
auto E = this->get_enactor();
auto P = this->get_problem();
auto G = P->get_graph();
auto vertex_triangles_count = P->result.vertex_triangles_count;
auto iteration = this->iteration;
auto intersect = [G, vertex_triangles_count] __host__ __device__(
vertex_t const& source, // ... source
vertex_t const& neighbor, // neighbor
edge_t const& edge, // edge
weight_t const& weight // weight (tuple).
) -> bool {
if (neighbor > source) {
auto src_vertex_triangles_count = G.get_intersection_count(
source, neighbor,
[vertex_triangles_count](auto intersection_vertex) {
math::atomic::add(&(vertex_triangles_count[intersection_vertex]),
vertex_t{1});
});
}
return false;
};
// Execute advance operator on the provided lambda
operators::advance::execute<operators::load_balance_t::block_mapped>(
G, E, intersect, context);
}
}; // struct enactor_t
template <typename graph_t>
float run(graph_t& G,
bool reduce_all_triangles,
typename graph_t::vertex_type* vertex_triangles_count, // Output
std::size_t* total_triangles_count, // Output
std::shared_ptr<gcuda::multi_context_t> context =
std::shared_ptr<gcuda::multi_context_t>(
new gcuda::multi_context_t(0)) // Context
) {
// <user-defined>
using vertex_t = typename graph_t::vertex_type;
using weight_t = typename graph_t::weight_type;
using param_type = param_t<vertex_t>;
using result_type = result_t<vertex_t>;
param_type param(reduce_all_triangles);
result_type result(vertex_triangles_count, total_triangles_count);
// </user-defined>
using problem_type = problem_t<graph_t, param_type, result_type>;
using enactor_type = enactor_t<problem_type>;
problem_type problem(G, param, result, context);
problem.init();
problem.reset();
enactor_type enactor(&problem, context);
auto time = enactor.enact();
if (param.reduce_all_triangles) {
auto policy = context->get_context(0)->execution_policy();
*result.total_triangles_count = thrust::transform_reduce(
policy, result.vertex_triangles_count,
result.vertex_triangles_count + G.get_number_of_vertices(),
[] __device__(const vertex_t& vertex_triangles) {
return static_cast<std::size_t>(vertex_triangles);
},
std::size_t{0}, thrust::plus<std::size_t>());
}
// </boiler-plate>
return time;
}
} // namespace tc
} // namespace gunrock<commit_msg>Add post processing step<commit_after>/**
* @file tc.hxx
* @author Muhammad A. Awad (mawad@ucdavis.edu)
* @brief Triangle Counting algorithm.
* @version 0.1
* @date 2022-08-06
*
* @copyright Copyright (c) 2022
*
*/
#pragma once
#include <gunrock/algorithms/algorithms.hxx>
#include <gunrock/util/timer.hxx>
namespace gunrock {
namespace tc {
template <typename vertex_t>
struct param_t {
bool reduce_all_triangles;
param_t(bool _reduce_all_triangles)
: reduce_all_triangles(_reduce_all_triangles) {}
};
template <typename vertex_t>
struct result_t {
vertex_t* vertex_triangles_count;
std::size_t* total_triangles_count;
result_t(vertex_t* _vertex_triangles_count, uint64_t* _total_triangles_count)
: vertex_triangles_count(_vertex_triangles_count),
total_triangles_count(_total_triangles_count) {}
};
template <typename graph_t, typename param_type, typename result_type>
struct problem_t : gunrock::problem_t<graph_t> {
param_type param;
result_type result;
problem_t(graph_t& G,
param_type& _param,
result_type& _result,
std::shared_ptr<gcuda::multi_context_t> _context)
: gunrock::problem_t<graph_t>(G, _context),
param(_param),
result(_result) {}
using vertex_t = typename graph_t::vertex_type;
using edge_t = typename graph_t::edge_type;
void init() override {}
void reset() override {}
};
template <typename problem_t>
struct enactor_t : gunrock::enactor_t<problem_t> {
enactor_t(problem_t* _problem,
std::shared_ptr<gcuda::multi_context_t> _context)
: gunrock::enactor_t<problem_t>(_problem, _context) {}
using vertex_t = typename problem_t::vertex_t;
using edge_t = typename problem_t::edge_t;
using weight_t = typename problem_t::weight_t;
using frontier_t = typename enactor_t<problem_t>::frontier_t;
void prepare_frontier(frontier_t* f,
gcuda::multi_context_t& context) override {
auto P = this->get_problem();
auto n_vertices = P->get_graph().get_number_of_vertices();
f->sequence((vertex_t)0, n_vertices, context.get_context(0)->stream());
}
void loop(gcuda::multi_context_t& context) override {
// Data slice
auto E = this->get_enactor();
auto P = this->get_problem();
auto G = P->get_graph();
auto vertex_triangles_count = P->result.vertex_triangles_count;
auto iteration = this->iteration;
auto intersect = [G, vertex_triangles_count] __host__ __device__(
vertex_t const& source, // ... source
vertex_t const& neighbor, // neighbor
edge_t const& edge, // edge
weight_t const& weight // weight (tuple).
) -> bool {
if (neighbor > source) {
auto src_vertex_triangles_count = G.get_intersection_count(
source, neighbor,
[vertex_triangles_count](auto intersection_vertex) {
math::atomic::add(&(vertex_triangles_count[intersection_vertex]),
vertex_t{1});
});
}
return false;
};
// Execute advance operator on the provided lambda
operators::advance::execute<operators::load_balance_t::block_mapped>(
G, E, intersect, context);
}
float post_process() {
util::timer_t timer;
timer.begin();
auto P = this->get_problem();
auto G = P->get_graph();
if (P->param.reduce_all_triangles) {
auto policy = this->context->get_context(0)->execution_policy();
*P->result.total_triangles_count = thrust::transform_reduce(
policy, P->result.vertex_triangles_count,
P->result.vertex_triangles_count + G.get_number_of_vertices(),
[] __device__(const vertex_t& vertex_triangles) {
return static_cast<std::size_t>(vertex_triangles);
},
std::size_t{0}, thrust::plus<std::size_t>());
}
return timer.end();
}
}; // struct enactor_t
template <typename graph_t>
float run(graph_t& G,
bool reduce_all_triangles,
typename graph_t::vertex_type* vertex_triangles_count, // Output
std::size_t* total_triangles_count, // Output
std::shared_ptr<gcuda::multi_context_t> context =
std::shared_ptr<gcuda::multi_context_t>(
new gcuda::multi_context_t(0)) // Context
) {
// <user-defined>
using vertex_t = typename graph_t::vertex_type;
using weight_t = typename graph_t::weight_type;
using param_type = param_t<vertex_t>;
using result_type = result_t<vertex_t>;
param_type param(reduce_all_triangles);
result_type result(vertex_triangles_count, total_triangles_count);
// </user-defined>
using problem_type = problem_t<graph_t, param_type, result_type>;
using enactor_type = enactor_t<problem_type>;
problem_type problem(G, param, result, context);
problem.init();
problem.reset();
enactor_type enactor(&problem, context);
auto time = enactor.enact();
time += enactor.post_process();
// </boiler-plate>
return time;
}
} // namespace tc
} // namespace gunrock<|endoftext|>
|
<commit_before><commit_msg>no message<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: register.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2007-03-26 14:48:51 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#if defined(_MSC_VER) && (_MSC_VER > 1310)
#pragma warning(disable : 4917 4555)
#endif
#ifdef __MINGW32__
#define INITGUID
#endif
#include "servprov.hxx"
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#endif
#ifndef _RTL_USTRING_H_
#include <rtl/ustring.h>
#endif
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
using namespace ::com::sun::star;
uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(
const uno::Reference<lang::XMultiServiceFactory> & xSMgr)
throw (uno::Exception)
{
uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );
return xService;
}
::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") );
}
uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()
{
uno::Sequence< ::rtl::OUString > aServiceNames( 1 );
aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) );
return aServiceNames;
}
extern "C" {
void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
void * pRet = 0;
::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
uno::Reference< lang::XSingleServiceFactory > xFactory;
if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )
{
xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),
EmbedServer_getImplementationName(),
EmbedServer_createInstance,
EmbedServer_getSupportedServiceNames() );
}
if (xFactory.is())
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
if (pRegistryKey)
{
try
{
uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );
uno::Reference< registry::XRegistryKey > xNewKey;
xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
EmbedServer_getImplementationName() +
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) );
uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();
for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
xNewKey->createKey( rServices.getConstArray()[ind] );
return sal_True;
}
catch (registry::InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
}
return sal_False;
}
} // extern "C"
// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif<commit_msg>INTEGRATION: CWS changefileheader (1.6.22); FILE MERGED 2008/04/01 15:13:59 thb 1.6.22.3: #i85898# Stripping all external header guards 2008/04/01 12:29:02 thb 1.6.22.2: #i85898# Stripping all external header guards 2008/03/31 13:33:41 rt 1.6.22.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: register.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#if defined(_MSC_VER) && (_MSC_VER > 1310)
#pragma warning(disable : 4917 4555)
#endif
#ifdef __MINGW32__
#define INITGUID
#endif
#include "servprov.hxx"
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/registry/InvalidRegistryException.hpp>
#include <rtl/ustring.h>
#include <cppuhelper/factory.hxx>
using namespace ::com::sun::star;
uno::Reference<uno::XInterface> SAL_CALL EmbedServer_createInstance(
const uno::Reference<lang::XMultiServiceFactory> & xSMgr)
throw (uno::Exception)
{
uno::Reference<uno::XInterface > xService = *new EmbedServer_Impl( xSMgr );
return xService;
}
::rtl::OUString SAL_CALL EmbedServer_getImplementationName() throw()
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.comp.ole.EmbedServer") );
}
uno::Sequence< ::rtl::OUString > SAL_CALL EmbedServer_getSupportedServiceNames() throw()
{
uno::Sequence< ::rtl::OUString > aServiceNames( 1 );
aServiceNames[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.document.OleEmbeddedServerRegistration" ) );
return aServiceNames;
}
extern "C" {
void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
void * pRet = 0;
::rtl::OUString aImplName( ::rtl::OUString::createFromAscii( pImplName ) );
uno::Reference< lang::XSingleServiceFactory > xFactory;
if(pServiceManager && aImplName.equals( EmbedServer_getImplementationName() ) )
{
xFactory= ::cppu::createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory*>(pServiceManager),
EmbedServer_getImplementationName(),
EmbedServer_createInstance,
EmbedServer_getSupportedServiceNames() );
}
if (xFactory.is())
{
xFactory->acquire();
pRet = xFactory.get();
}
return pRet;
}
sal_Bool SAL_CALL component_writeInfo( void * /*pServiceManager*/, void * pRegistryKey )
{
if (pRegistryKey)
{
try
{
uno::Reference< registry::XRegistryKey > xKey( reinterpret_cast< registry::XRegistryKey* >( pRegistryKey ) );
uno::Reference< registry::XRegistryKey > xNewKey;
xNewKey = xKey->createKey( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) +
EmbedServer_getImplementationName() +
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) );
uno::Sequence< ::rtl::OUString > rServices = EmbedServer_getSupportedServiceNames();
for( sal_Int32 ind = 0; ind < rServices.getLength(); ind++ )
xNewKey->createKey( rServices.getConstArray()[ind] );
return sal_True;
}
catch (registry::InvalidRegistryException &)
{
OSL_ENSURE( sal_False, "### InvalidRegistryException!" );
}
}
return sal_False;
}
} // extern "C"
// Fix strange warnings about some
// ATL::CAxHostWindow::QueryInterface|AddRef|Releae functions.
// warning C4505: 'xxx' : unreferenced local function has been removed
#if defined(_MSC_VER)
#pragma warning(disable: 4505)
#endif<|endoftext|>
|
<commit_before>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory> // std::make_shared, std::shared_ptr
#include <string> // std::string
namespace yli
{
namespace callback_system
{
void CallbackParameter::bind_to_parent()
{
// requirements:
// `this->parent` must not be `nullptr`.
yli::callback_system::CallbackObject* const callback_object = this->parent;
if (callback_object == nullptr)
{
std::cerr << "ERROR: `CallbackParameter::bind_to_parent`: `callback_object` is `nullptr`!\n";
return;
}
// note: `CallbackObject::bind_callback_parameter` also stores named variables in its `anyvalue_hashmap`.
callback_object->bind_callback_parameter(this);
}
CallbackParameter::CallbackParameter(const std::string& name, std::shared_ptr<yli::datatypes::AnyValue> any_value, const bool is_reference, yli::callback_system::CallbackObject* const parent)
{
// constructor.
this->name = name;
this->any_value = any_value;
this->is_reference = is_reference;
this->parent = parent;
// get childID from the CallbackObject and set pointer to this CallbackParameter.
this->bind_to_parent();
}
CallbackParameter::~CallbackParameter()
{
// destructor.
std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n";
// set pointer to this object to nullptr.
this->parent->set_callback_parameter_pointer(this->childID, nullptr);
}
std::shared_ptr<yli::datatypes::AnyValue> CallbackParameter::get_any_value() const
{
return std::make_shared<yli::datatypes::AnyValue>(*this->any_value);
}
}
}
<commit_msg>`CallbackParameter::~CallbackParameter`: check `parent` for `nullptr`.<commit_after>#include "callback_parameter.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <memory> // std::make_shared, std::shared_ptr
#include <string> // std::string
namespace yli
{
namespace callback_system
{
void CallbackParameter::bind_to_parent()
{
// requirements:
// `this->parent` must not be `nullptr`.
yli::callback_system::CallbackObject* const callback_object = this->parent;
if (callback_object == nullptr)
{
std::cerr << "ERROR: `CallbackParameter::bind_to_parent`: `callback_object` is `nullptr`!\n";
return;
}
// note: `CallbackObject::bind_callback_parameter` also stores named variables in its `anyvalue_hashmap`.
callback_object->bind_callback_parameter(this);
}
CallbackParameter::CallbackParameter(const std::string& name, std::shared_ptr<yli::datatypes::AnyValue> any_value, const bool is_reference, yli::callback_system::CallbackObject* const parent)
{
// constructor.
this->name = name;
this->any_value = any_value;
this->is_reference = is_reference;
this->parent = parent;
// get childID from the CallbackObject and set pointer to this CallbackParameter.
this->bind_to_parent();
}
CallbackParameter::~CallbackParameter()
{
// destructor.
//
// requirements:
// `this->parent` must not be `nullptr`.
std::cout << "Callback parameter with childID " << this->childID << " will be destroyed.\n";
yli::callback_system::CallbackObject* const callback_object = this->parent;
if (callback_object == nullptr)
{
std::cerr << "ERROR: `CallbackParameter::~CallbackParameter`: `callback_object` is `nullptr`!\n";
return;
}
// set pointer to this `CallbackParameter` to `nullptr`.
callback_object->set_callback_parameter_pointer(this->childID, nullptr);
}
std::shared_ptr<yli::datatypes::AnyValue> CallbackParameter::get_any_value() const
{
return std::make_shared<yli::datatypes::AnyValue>(*this->any_value);
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: source.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:18:03 $
*
* 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 _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_
#include <com/sun/star/datatransfer/dnd/DNDConstants.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_
#include <com/sun/star/awt/MouseButton.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEEVENT_HPP_
#include <com/sun/star/awt/MouseEvent.hpp>
#endif
#ifndef _RTL_UNLOAD_H_
#include <rtl/unload.h>
#endif
#include <process.h>
#include <memory>
#include "source.hxx"
#include "globals.hxx"
#include "sourcecontext.hxx"
#include "../../inc/DtObjFactory.hxx"
#include <rtl/ustring.h>
#include <process.h>
#include <winuser.h>
#include <stdio.h>
using namespace rtl;
using namespace cppu;
using namespace osl;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::dnd;
using namespace com::sun::star::datatransfer::dnd::DNDConstants;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt::MouseButton;
using namespace com::sun::star::awt;
using namespace com::sun::star::lang;
extern rtl_StandardModuleCount g_moduleCount;
//--> TRA
extern Reference< XTransferable > g_XTransferable;
//<-- TRA
unsigned __stdcall DndOleSTAFunc(LPVOID pParams);
//----------------------------------------------------
/** Ctor
*/
DragSource::DragSource( const Reference<XMultiServiceFactory>& sf):
m_serviceFactory( sf),
WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo >(m_mutex),
// m_pcurrentContext_impl(0),
m_hAppWindow(0),
m_MouseButton(0),
m_RunningDndOperationCount(0)
{
g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}
//----------------------------------------------------
/** Dtor
*/
DragSource::~DragSource()
{
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
//----------------------------------------------------
/** First start a new drag and drop thread if
the last one has finished
????
Do we really need a separate thread for
every Dnd opeartion or only if the source
thread is an MTA thread
????
*/
void DragSource::StartDragImpl(
const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener )
{
// The actions supported by the drag source
m_sourceActions= sourceActions;
// We need to know which mouse button triggered the operation.
// If it was the left one, then the drop occurs when that button
// has been released and if it was the right one then the drop
// occurs when the right button has been released. If the event is not
// set then we assume that the left button is pressed.
MouseEvent evtMouse;
trigger.Event >>= evtMouse;
m_MouseButton= evtMouse.Buttons;
// The SourceContext class administers the XDragSourceListener s and
// fires events to them. An instance only exists in the scope of this
// functions. However, the drag and drop operation causes callbacks
// to the IDropSource interface implemented in this class (but only
// while this function executes). The source context is also used
// in DragSource::QueryContinueDrag.
m_currentContext= static_cast<XDragSourceContext*>( new SourceContext(
static_cast<DragSource*>(this), listener ) );
// Convert the XTransferable data object into an IDataObject object;
//--> TRA
g_XTransferable = trans;
//<-- TRA
m_spDataObject= m_aDataConverter.createDataObjFromTransferable(
m_serviceFactory, trans);
// Obtain the id of the thread that created the window
DWORD processId;
m_threadIdWindow= GetWindowThreadProcessId( m_hAppWindow, &processId);
// hold the instance for the DnD thread, it's to late
// to acquire at the start of the thread procedure
// the thread procedure is responsible for the release
acquire();
// The thread acccesses members of this instance but does not call acquire.
// Hopefully this instance is not destroyed before the thread has terminated.
unsigned threadId;
HANDLE hThread= reinterpret_cast<HANDLE>(_beginthreadex(
0, 0, DndOleSTAFunc, reinterpret_cast<void*>(this), 0, &threadId));
// detach from thread
CloseHandle(hThread);
}
// XInitialization
//----------------------------------------------------
/** aArguments contains a machine id
*/
void SAL_CALL DragSource::initialize( const Sequence< Any >& aArguments )
throw(Exception, RuntimeException)
{
if( aArguments.getLength() >=2)
m_hAppWindow= *(HWND*)aArguments[1].getValue();
OSL_ASSERT( IsWindow( m_hAppWindow) );
}
//----------------------------------------------------
/** XDragSource
*/
sal_Bool SAL_CALL DragSource::isDragImageSupported( )
throw(RuntimeException)
{
return 0;
}
//----------------------------------------------------
/**
*/
sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 dragAction )
throw( IllegalArgumentException, RuntimeException)
{
return 0;
}
//----------------------------------------------------
/** Notifies the XDragSourceListener by
calling dragDropEnd
*/
void SAL_CALL DragSource::startDrag(
const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener ) throw( RuntimeException)
{
// Allow only one running dnd operation at a time,
// see XDragSource documentation
long cnt = InterlockedIncrement(&m_RunningDndOperationCount);
if (1 == cnt)
{
StartDragImpl(trigger, sourceActions, cursor, image, trans, listener);
}
else
{
//OSL_ENSURE(false, "Overlapping Drag&Drop operation rejected!");
cnt = InterlockedDecrement(&m_RunningDndOperationCount);
DragSourceDropEvent dsde;
dsde.DropAction = ACTION_NONE;
dsde.DropSuccess = false;
try
{
listener->dragDropEnd(dsde);
}
catch(RuntimeException&)
{
OSL_ENSURE(false, "Runtime exception during event dispatching");
}
}
}
//----------------------------------------------------
/**
*/
#if OSL_DEBUG_LEVEL > 1
void SAL_CALL DragSource::release()
{
if( m_refCount == 1)
{
int a = m_refCount;
}
WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo>::release();
}
#endif
//----------------------------------------------------
/**IDropTarget
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryInterface( REFIID riid, void **ppvObject)
{
if( !ppvObject)
return E_POINTER;
*ppvObject= NULL;
if( riid == __uuidof( IUnknown) )
*ppvObject= static_cast<IUnknown*>( this);
else if ( riid == __uuidof( IDropSource) )
*ppvObject= static_cast<IDropSource*>( this);
if(*ppvObject)
{
AddRef();
return S_OK;
}
else
return E_NOINTERFACE;
}
//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::AddRef( void)
{
acquire();
return (ULONG) m_refCount;
}
//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::Release( void)
{
ULONG ref= m_refCount;
release();
return --ref;
}
//----------------------------------------------------
/** IDropSource
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryContinueDrag(
/* [in] */ BOOL fEscapePressed,
/* [in] */ DWORD grfKeyState)
{
#if DBG_CONSOLE_OUT
printf("\nDragSource::QueryContinueDrag");
#endif
HRESULT retVal= S_OK; // default continue DnD
if (fEscapePressed)
{
retVal= DRAGDROP_S_CANCEL;
}
else
{
if( ( m_MouseButton == MouseButton::RIGHT && !(grfKeyState & MK_RBUTTON) ) ||
( m_MouseButton == MouseButton::MIDDLE && !(grfKeyState & MK_MBUTTON) ) ||
( m_MouseButton == MouseButton::LEFT && !(grfKeyState & MK_LBUTTON) ) ||
( m_MouseButton == 0 && !(grfKeyState & MK_LBUTTON) ) )
{
retVal= DRAGDROP_S_DROP;
}
}
// fire dropActionChanged event.
// this is actually done by the context, which also detects whether the action
// changed at all
sal_Int8 dropAction= fEscapePressed ? ACTION_NONE :
dndOleKeysToAction( grfKeyState, m_sourceActions);
sal_Int8 userAction= fEscapePressed ? ACTION_NONE :
dndOleKeysToAction( grfKeyState, -1 );
static_cast<SourceContext*>(m_currentContext.get())->fire_dropActionChanged(
dropAction, userAction);
return retVal;
}
//----------------------------------------------------
/**
*/
HRESULT STDMETHODCALLTYPE DragSource::GiveFeedback(
/* [in] */ DWORD dwEffect)
{
#if DBG_CONSOLE_OUT
printf("\nDragSource::GiveFeedback %d", dwEffect);
#endif
return DRAGDROP_S_USEDEFAULTCURSORS;
}
// XServiceInfo
OUString SAL_CALL DragSource::getImplementationName( ) throw (RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_IMPL_NAME));;
}
// XServiceInfo
sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException)
{
if( ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME ))))
return sal_True;
return sal_False;
}
Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames( ) throw (RuntimeException)
{
OUString names[1]= {OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME))};
return Sequence<OUString>(names, 1);
}
//----------------------------------------------------
/**This function is called as extra thread from
DragSource::executeDrag. The function
carries out a drag and drop operation by calling
DoDragDrop. The thread also notifies all
XSourceListener.
*/
unsigned __stdcall DndOleSTAFunc(LPVOID pParams)
{
// The structure contains all arguments for DoDragDrop and other
DragSource *pSource= (DragSource*)pParams;
// Drag and drop only works in a thread in which OleInitialize is called.
HRESULT hr= OleInitialize( NULL);
if(SUCCEEDED(hr))
{
// We force the creation of a thread message queue. This is necessary
// for a later call to AttachThreadInput
MSG msgtemp;
PeekMessage( &msgtemp, NULL, WM_USER, WM_USER, PM_NOREMOVE);
DWORD threadId= GetCurrentThreadId();
// This thread is attached to the thread that created the window. Hence
// this thread also receives all mouse and keyboard messages which are
// needed by DoDragDrop
AttachThreadInput( threadId , pSource->m_threadIdWindow, TRUE );
DWORD dwEffect= 0;
hr= DoDragDrop(
pSource->m_spDataObject.get(),
static_cast<IDropSource*>(pSource),
dndActionsToDropEffects( pSource->m_sourceActions),
&dwEffect);
// #105428 detach my message queue from the other threads
// message queue before calling fire_dragDropEnd else
// the office may appear to hang sometimes
AttachThreadInput( threadId, pSource->m_threadIdWindow, FALSE);
//--> TRA
// clear the global transferable again
g_XTransferable = Reference< XTransferable >( );
//<-- TRA
OSL_ENSURE( hr != E_INVALIDARG, "IDataObject impl does not contain valid data");
//Fire event
sal_Int8 action= hr == DRAGDROP_S_DROP ? dndOleDropEffectsToActions( dwEffect) : ACTION_NONE;
static_cast<SourceContext*>(pSource->m_currentContext.get())->fire_dragDropEnd(
hr == DRAGDROP_S_DROP ? sal_True : sal_False, action);
// Destroy SourceContextslkfgj
pSource->m_currentContext= 0;
// Destroy the XTransferable wrapper
pSource->m_spDataObject=0;
OleUninitialize();
}
long cnt = InterlockedDecrement(&pSource->m_RunningDndOperationCount);
// the DragSource was manually acquired by
// thread starting method DelayedStartDrag
pSource->release();
return 0;
}
<commit_msg>INTEGRATION: CWS warnings01 (1.18.4); FILE MERGED 2006/03/09 20:31:48 pl 1.18.4.1: #i55991# removed warnings for windows platform<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: source.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: hr $ $Date: 2006-06-20 06:02:45 $
*
* 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 _COM_SUN_STAR_DATATRANSFER_DND_DNDCONSTANTS_HPP_
#include <com/sun/star/datatransfer/dnd/DNDConstants.hpp>
#endif
#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEBUTTON_HPP_
#include <com/sun/star/awt/MouseButton.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_MOUSEEVENT_HPP_
#include <com/sun/star/awt/MouseEvent.hpp>
#endif
#ifndef _RTL_UNLOAD_H_
#include <rtl/unload.h>
#endif
#include <process.h>
#include <memory>
#include "source.hxx"
#include "globals.hxx"
#include "sourcecontext.hxx"
#include "../../inc/DtObjFactory.hxx"
#include <rtl/ustring.h>
#include <process.h>
#include <winuser.h>
#include <stdio.h>
using namespace rtl;
using namespace cppu;
using namespace osl;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::dnd;
using namespace com::sun::star::datatransfer::dnd::DNDConstants;
using namespace com::sun::star::uno;
using namespace com::sun::star::awt::MouseButton;
using namespace com::sun::star::awt;
using namespace com::sun::star::lang;
extern rtl_StandardModuleCount g_moduleCount;
//--> TRA
extern Reference< XTransferable > g_XTransferable;
//<-- TRA
unsigned __stdcall DndOleSTAFunc(LPVOID pParams);
//----------------------------------------------------
/** Ctor
*/
DragSource::DragSource( const Reference<XMultiServiceFactory>& sf):
m_serviceFactory( sf),
WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo >(m_mutex),
// m_pcurrentContext_impl(0),
m_hAppWindow(0),
m_MouseButton(0),
m_RunningDndOperationCount(0)
{
g_moduleCount.modCnt.acquire( &g_moduleCount.modCnt );
}
//----------------------------------------------------
/** Dtor
*/
DragSource::~DragSource()
{
g_moduleCount.modCnt.release( &g_moduleCount.modCnt );
}
//----------------------------------------------------
/** First start a new drag and drop thread if
the last one has finished
????
Do we really need a separate thread for
every Dnd opeartion or only if the source
thread is an MTA thread
????
*/
void DragSource::StartDragImpl(
const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 /*cursor*/,
sal_Int32 /*image*/,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener )
{
// The actions supported by the drag source
m_sourceActions= sourceActions;
// We need to know which mouse button triggered the operation.
// If it was the left one, then the drop occurs when that button
// has been released and if it was the right one then the drop
// occurs when the right button has been released. If the event is not
// set then we assume that the left button is pressed.
MouseEvent evtMouse;
trigger.Event >>= evtMouse;
m_MouseButton= evtMouse.Buttons;
// The SourceContext class administers the XDragSourceListener s and
// fires events to them. An instance only exists in the scope of this
// functions. However, the drag and drop operation causes callbacks
// to the IDropSource interface implemented in this class (but only
// while this function executes). The source context is also used
// in DragSource::QueryContinueDrag.
m_currentContext= static_cast<XDragSourceContext*>( new SourceContext(
static_cast<DragSource*>(this), listener ) );
// Convert the XTransferable data object into an IDataObject object;
//--> TRA
g_XTransferable = trans;
//<-- TRA
m_spDataObject= m_aDataConverter.createDataObjFromTransferable(
m_serviceFactory, trans);
// Obtain the id of the thread that created the window
DWORD processId;
m_threadIdWindow= GetWindowThreadProcessId( m_hAppWindow, &processId);
// hold the instance for the DnD thread, it's to late
// to acquire at the start of the thread procedure
// the thread procedure is responsible for the release
acquire();
// The thread acccesses members of this instance but does not call acquire.
// Hopefully this instance is not destroyed before the thread has terminated.
unsigned threadId;
HANDLE hThread= reinterpret_cast<HANDLE>(_beginthreadex(
0, 0, DndOleSTAFunc, reinterpret_cast<void*>(this), 0, &threadId));
// detach from thread
CloseHandle(hThread);
}
// XInitialization
//----------------------------------------------------
/** aArguments contains a machine id
*/
void SAL_CALL DragSource::initialize( const Sequence< Any >& aArguments )
throw(Exception, RuntimeException)
{
if( aArguments.getLength() >=2)
m_hAppWindow= *(HWND*)aArguments[1].getValue();
OSL_ASSERT( IsWindow( m_hAppWindow) );
}
//----------------------------------------------------
/** XDragSource
*/
sal_Bool SAL_CALL DragSource::isDragImageSupported( )
throw(RuntimeException)
{
return 0;
}
//----------------------------------------------------
/**
*/
sal_Int32 SAL_CALL DragSource::getDefaultCursor( sal_Int8 /*dragAction*/ )
throw( IllegalArgumentException, RuntimeException)
{
return 0;
}
//----------------------------------------------------
/** Notifies the XDragSourceListener by
calling dragDropEnd
*/
void SAL_CALL DragSource::startDrag(
const DragGestureEvent& trigger,
sal_Int8 sourceActions,
sal_Int32 cursor,
sal_Int32 image,
const Reference<XTransferable >& trans,
const Reference<XDragSourceListener >& listener ) throw( RuntimeException)
{
// Allow only one running dnd operation at a time,
// see XDragSource documentation
long cnt = InterlockedIncrement(&m_RunningDndOperationCount);
if (1 == cnt)
{
StartDragImpl(trigger, sourceActions, cursor, image, trans, listener);
}
else
{
//OSL_ENSURE(false, "Overlapping Drag&Drop operation rejected!");
cnt = InterlockedDecrement(&m_RunningDndOperationCount);
DragSourceDropEvent dsde;
dsde.DropAction = ACTION_NONE;
dsde.DropSuccess = false;
try
{
listener->dragDropEnd(dsde);
}
catch(RuntimeException&)
{
OSL_ENSURE(false, "Runtime exception during event dispatching");
}
}
}
//----------------------------------------------------
/**
*/
#if OSL_DEBUG_LEVEL > 1
void SAL_CALL DragSource::release()
{
if( m_refCount == 1)
{
int a = m_refCount;
}
WeakComponentImplHelper3< XDragSource, XInitialization, XServiceInfo>::release();
}
#endif
//----------------------------------------------------
/**IDropTarget
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryInterface( REFIID riid, void **ppvObject)
{
if( !ppvObject)
return E_POINTER;
*ppvObject= NULL;
if( riid == __uuidof( IUnknown) )
*ppvObject= static_cast<IUnknown*>( this);
else if ( riid == __uuidof( IDropSource) )
*ppvObject= static_cast<IDropSource*>( this);
if(*ppvObject)
{
AddRef();
return S_OK;
}
else
return E_NOINTERFACE;
}
//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::AddRef( void)
{
acquire();
return (ULONG) m_refCount;
}
//----------------------------------------------------
/**
*/
ULONG STDMETHODCALLTYPE DragSource::Release( void)
{
ULONG ref= m_refCount;
release();
return --ref;
}
//----------------------------------------------------
/** IDropSource
*/
HRESULT STDMETHODCALLTYPE DragSource::QueryContinueDrag(
/* [in] */ BOOL fEscapePressed,
/* [in] */ DWORD grfKeyState)
{
#if defined DBG_CONSOLE_OUT
printf("\nDragSource::QueryContinueDrag");
#endif
HRESULT retVal= S_OK; // default continue DnD
if (fEscapePressed)
{
retVal= DRAGDROP_S_CANCEL;
}
else
{
if( ( m_MouseButton == MouseButton::RIGHT && !(grfKeyState & MK_RBUTTON) ) ||
( m_MouseButton == MouseButton::MIDDLE && !(grfKeyState & MK_MBUTTON) ) ||
( m_MouseButton == MouseButton::LEFT && !(grfKeyState & MK_LBUTTON) ) ||
( m_MouseButton == 0 && !(grfKeyState & MK_LBUTTON) ) )
{
retVal= DRAGDROP_S_DROP;
}
}
// fire dropActionChanged event.
// this is actually done by the context, which also detects whether the action
// changed at all
sal_Int8 dropAction= fEscapePressed ? ACTION_NONE :
dndOleKeysToAction( grfKeyState, m_sourceActions);
sal_Int8 userAction= fEscapePressed ? ACTION_NONE :
dndOleKeysToAction( grfKeyState, -1 );
static_cast<SourceContext*>(m_currentContext.get())->fire_dropActionChanged(
dropAction, userAction);
return retVal;
}
//----------------------------------------------------
/**
*/
HRESULT STDMETHODCALLTYPE DragSource::GiveFeedback(
/* [in] */ DWORD
#if defined DBG_CONSOLE_OUT
dwEffect
#endif
)
{
#if defined DBG_CONSOLE_OUT
printf("\nDragSource::GiveFeedback %d", dwEffect);
#endif
return DRAGDROP_S_USEDEFAULTCURSORS;
}
// XServiceInfo
OUString SAL_CALL DragSource::getImplementationName( ) throw (RuntimeException)
{
return OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_IMPL_NAME));;
}
// XServiceInfo
sal_Bool SAL_CALL DragSource::supportsService( const OUString& ServiceName ) throw (RuntimeException)
{
if( ServiceName.equals(OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME ))))
return sal_True;
return sal_False;
}
Sequence< OUString > SAL_CALL DragSource::getSupportedServiceNames( ) throw (RuntimeException)
{
OUString names[1]= {OUString(RTL_CONSTASCII_USTRINGPARAM(DNDSOURCE_SERVICE_NAME))};
return Sequence<OUString>(names, 1);
}
//----------------------------------------------------
/**This function is called as extra thread from
DragSource::executeDrag. The function
carries out a drag and drop operation by calling
DoDragDrop. The thread also notifies all
XSourceListener.
*/
unsigned __stdcall DndOleSTAFunc(LPVOID pParams)
{
// The structure contains all arguments for DoDragDrop and other
DragSource *pSource= (DragSource*)pParams;
// Drag and drop only works in a thread in which OleInitialize is called.
HRESULT hr= OleInitialize( NULL);
if(SUCCEEDED(hr))
{
// We force the creation of a thread message queue. This is necessary
// for a later call to AttachThreadInput
MSG msgtemp;
PeekMessage( &msgtemp, NULL, WM_USER, WM_USER, PM_NOREMOVE);
DWORD threadId= GetCurrentThreadId();
// This thread is attached to the thread that created the window. Hence
// this thread also receives all mouse and keyboard messages which are
// needed by DoDragDrop
AttachThreadInput( threadId , pSource->m_threadIdWindow, TRUE );
DWORD dwEffect= 0;
hr= DoDragDrop(
pSource->m_spDataObject.get(),
static_cast<IDropSource*>(pSource),
dndActionsToDropEffects( pSource->m_sourceActions),
&dwEffect);
// #105428 detach my message queue from the other threads
// message queue before calling fire_dragDropEnd else
// the office may appear to hang sometimes
AttachThreadInput( threadId, pSource->m_threadIdWindow, FALSE);
//--> TRA
// clear the global transferable again
g_XTransferable = Reference< XTransferable >( );
//<-- TRA
OSL_ENSURE( hr != E_INVALIDARG, "IDataObject impl does not contain valid data");
//Fire event
sal_Int8 action= hr == DRAGDROP_S_DROP ? dndOleDropEffectsToActions( dwEffect) : ACTION_NONE;
static_cast<SourceContext*>(pSource->m_currentContext.get())->fire_dragDropEnd(
hr == DRAGDROP_S_DROP ? sal_True : sal_False, action);
// Destroy SourceContextslkfgj
pSource->m_currentContext= 0;
// Destroy the XTransferable wrapper
pSource->m_spDataObject=0;
OleUninitialize();
}
InterlockedDecrement(&pSource->m_RunningDndOperationCount);
// the DragSource was manually acquired by
// thread starting method DelayedStartDrag
pSource->release();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* LayoutAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LAYOUTAPPENDER_HH
#define _LOG4CPP_LAYOUTAPPENDER_HH
#include <string>
#include "log4cpp/Export.hh"
#include "log4cpp/AppenderSkeleton.hh"
namespace log4cpp {
/**
* LayoutAppender is a common superclass for all Appenders that require
* a Layout.
**/
class LOG4CPP_EXPORT LayoutAppender : public AppenderSkeleton {
public:
LayoutAppender(const std::string& name);
virtual ~LayoutAppender();
/**
* Check if the appender requires a layout. All LayoutAppenders do,
* therefore this method returns true for all subclasses.
*
* @returns true.
**/
virtual bool requiresLayout() const;
virtual void setLayout(Layout* layout);
protected:
/**
* Return the layout of the appender.
* This method is the Layout accessor for subclasses of LayoutAppender.
* @returns the Layout.
**/
Layout& _getLayout();
private:
Layout* _layout;
};
}
#endif // _LOG4CPP_LAYOUTAPPENDER_HH
<commit_msg>typedef SimpleLayout as DefaultLayoutType.<commit_after>/*
* LayoutAppender.hh
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_LAYOUTAPPENDER_HH
#define _LOG4CPP_LAYOUTAPPENDER_HH
#include <string>
#include "log4cpp/Export.hh"
#include "log4cpp/AppenderSkeleton.hh"
#include "log4cpp/SimpleLayout.hh"
namespace log4cpp {
/**
* LayoutAppender is a common superclass for all Appenders that require
* a Layout.
**/
class LOG4CPP_EXPORT LayoutAppender : public AppenderSkeleton {
public:
typedef SimpleLayout DefaultLayoutType;
LayoutAppender(const std::string& name);
virtual ~LayoutAppender();
/**
* Check if the appender requires a layout. All LayoutAppenders do,
* therefore this method returns true for all subclasses.
*
* @returns true.
**/
virtual bool requiresLayout() const;
virtual void setLayout(Layout* layout = NULL);
protected:
/**
* Return the layout of the appender.
* This method is the Layout accessor for subclasses of LayoutAppender.
* @returns the Layout.
**/
Layout& _getLayout();
private:
Layout* _layout;
};
}
#endif // _LOG4CPP_LAYOUTAPPENDER_HH
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "config.h"
#if CROWN_PLATFORM_ANDROID
#include "apk_file.h"
#include "assert.h"
#include "macros.h"
#include <android/asset_manager.h>
namespace crown
{
ApkFile::ApkFile(AAssetManager* asset_manager, const char* path)
: File(FOM_READ)
, _asset(NULL)
{
_asset = AAssetManager_open(asset_manager, path, AASSET_MODE_RANDOM);
CE_ASSERT(_asset != NULL, "AAssetManager_open: failed to open %s", path);
}
ApkFile::~ApkFile()
{
if (_asset != NULL)
{
AAsset_close(_asset);
_asset = NULL;
}
}
void ApkFile::seek(size_t position)
{
off_t seek_result = AAsset_seek(_asset, (off_t)position, SEEK_SET);
CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
CE_UNUSED(seek_result);
}
void ApkFile::seek_to_end()
{
off_t seek_result = AAsset_seek(_asset, 0, SEEK_END);
CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
CE_UNUSED(seek_result);
}
void ApkFile::skip(size_t bytes)
{
off_t seek_result = AAsset_seek(_asset, (off_t) bytes, SEEK_CUR);
CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
CE_UNUSED(seek_result);
}
void ApkFile::read(void* buffer, size_t size)
{
CE_ASSERT_NOT_NULL(buffer);
size_t bytes_read = (size_t) AAsset_read(_asset, buffer, size);
CE_ASSERT(bytes_read == size, "AAsset_read: requested: %lu, read: %lu", size, bytes_read);
CE_UNUSED(bytes_read);
}
void ApkFile::write(const void* /*buffer*/, size_t /*size*/)
{
CE_ASSERT(false, "Apk files are read only!");
}
bool ApkFile::copy_to(File& /*file*/, size_t /*size = 0*/)
{
CE_ASSERT(false, "Not implemented");
return false;
}
void ApkFile::flush()
{
// Not needed
}
bool ApkFile::is_valid()
{
return _asset != NULL;
}
bool ApkFile::end_of_file()
{
return AAsset_getRemainingLength(_asset) == 0;
}
size_t ApkFile::size()
{
return AAsset_getLength(_asset);
}
size_t ApkFile::position()
{
return (size_t) (AAsset_getLength(_asset) - AAsset_getRemainingLength(_asset));
}
bool ApkFile::can_read() const
{
return true;
}
bool ApkFile::can_write() const
{
return false;
}
bool ApkFile::can_seek() const
{
return true;
}
} // namespace crown
#endif // CROWN_PLATFORM_ANDROID
<commit_msg>Fix android build<commit_after>/*
* Copyright (c) 2012-2015 Daniele Bartolini and individual contributors.
* License: https://github.com/taylor001/crown/blob/master/LICENSE
*/
#include "config.h"
#if CROWN_PLATFORM_ANDROID
#include "apk_file.h"
#include "assert.h"
#include "macros.h"
#include <stdio.h> // SEEK_SET, ...
#include <android/asset_manager.h>
namespace crown
{
ApkFile::ApkFile(AAssetManager* asset_manager, const char* path)
: File(FOM_READ)
, _asset(NULL)
{
_asset = AAssetManager_open(asset_manager, path, AASSET_MODE_RANDOM);
CE_ASSERT(_asset != NULL, "AAssetManager_open: failed to open %s", path);
}
ApkFile::~ApkFile()
{
if (_asset != NULL)
{
AAsset_close(_asset);
_asset = NULL;
}
}
void ApkFile::seek(size_t position)
{
off_t seek_result = AAsset_seek(_asset, (off_t)position, SEEK_SET);
CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
CE_UNUSED(seek_result);
}
void ApkFile::seek_to_end()
{
off_t seek_result = AAsset_seek(_asset, 0, SEEK_END);
CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
CE_UNUSED(seek_result);
}
void ApkFile::skip(size_t bytes)
{
off_t seek_result = AAsset_seek(_asset, (off_t) bytes, SEEK_CUR);
CE_ASSERT(seek_result != (off_t) -1, "AAsset_seek: error");
CE_UNUSED(seek_result);
}
void ApkFile::read(void* buffer, size_t size)
{
CE_ASSERT_NOT_NULL(buffer);
size_t bytes_read = (size_t) AAsset_read(_asset, buffer, size);
CE_ASSERT(bytes_read == size, "AAsset_read: requested: %lu, read: %lu", size, bytes_read);
CE_UNUSED(bytes_read);
}
void ApkFile::write(const void* /*buffer*/, size_t /*size*/)
{
CE_ASSERT(false, "Apk files are read only!");
}
bool ApkFile::copy_to(File& /*file*/, size_t /*size = 0*/)
{
CE_ASSERT(false, "Not implemented");
return false;
}
void ApkFile::flush()
{
// Not needed
}
bool ApkFile::is_valid()
{
return _asset != NULL;
}
bool ApkFile::end_of_file()
{
return AAsset_getRemainingLength(_asset) == 0;
}
size_t ApkFile::size()
{
return AAsset_getLength(_asset);
}
size_t ApkFile::position()
{
return (size_t) (AAsset_getLength(_asset) - AAsset_getRemainingLength(_asset));
}
bool ApkFile::can_read() const
{
return true;
}
bool ApkFile::can_write() const
{
return false;
}
bool ApkFile::can_seek() const
{
return true;
}
} // namespace crown
#endif // CROWN_PLATFORM_ANDROID
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#include <vector>
#include <type_traits>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/fv/interface.hh>
#include <dune/gdt/mapper/interface.hh>
namespace Dune {
namespace GDT {
template <class VectorImp>
class ConstLocalDoFVector
{
static_assert(
std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
typedef VectorImp VectorType;
typedef typename VectorType::ScalarType ScalarType;
template <class M, class EntityType>
ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
: vector_(vector)
, indices_(mapper.numDofs(entity))
{
mapper.globalIndices(entity, indices_);
}
~ConstLocalDoFVector()
{
}
size_t size() const
{
return indices_.size();
}
ScalarType get(const size_t ii) const
{
assert(ii < indices_.size());
return vector_.get_entry(indices_[ii]);
}
private:
const VectorType& vector_;
protected:
Dune::DynamicVector<size_t> indices_;
private:
template <class V>
friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector
template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
out << "[";
const size_t sz = vector.size();
if (sz > 0) {
out << vector.get(0);
for (size_t ii = 1; ii < sz; ++ii)
out << ", " << vector.get(ii);
} else
out << " ";
out << "]";
return out;
} // ... operator<<(...)
template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
typedef ConstLocalDoFVector<VectorImp> BaseType;
public:
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ScalarType ScalarType;
template <class M, class EntityType>
LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
: BaseType(mapper, entity, vector)
, vector_(vector)
{
}
~LocalDoFVector()
{
}
void set(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.set_entry(indices_[ii], val);
}
void add(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.add_to_entry(indices_[ii], val);
}
template <class OtherVectorImp>
void add(const OtherVectorImp& vector)
{
assert(vector.size() == indices_.size());
for (size_t ii = 0; ii < indices_.size(); ++ii)
add(ii, vector[ii]);
}
private:
using BaseType::indices_;
VectorType& vector_;
}; // class LocalDoFVector
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
: public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
SpaceImp::dimRangeCols>,
SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols> BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& space, const VectorType& globalVector, const EntityType& ent)
: BaseType(ent)
, space_(space)
, base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source) = default;
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~ConstLocalDiscreteFunction()
{
}
const SpaceType& space() const
{
return space_;
}
const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
{
return basis();
}
const BaseFunctionSetType& basis() const
{
return *base_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order() const override
{
return base_->order();
}
void evaluate(const DomainType& xx, RangeType& ret) const override final
{
assert(this->is_a_valid_point(xx));
if (!GDT::is_fv_space<SpaceType>::value) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
assert(localVector_->size() == tmpBaseValues.size());
base_->evaluate(xx, tmpBaseValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
}
} else {
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret[ii] = localVector_->get(ii);
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final
{
assert(this->is_a_valid_point(xx));
if (!GDT::is_fv_space<SpaceType>::value) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
assert(localVector_->size() == tmpBaseJacobianValues.size());
base_->jacobian(xx, tmpBaseJacobianValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
} else {
ret = JacobianRangeType(0);
}
} // ... jacobian(...)
using BaseType::evaluate;
using BaseType::jacobian;
protected:
const SpaceType& space_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
: BaseType(space, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
//! previous comment questioned validity, defaulting this doesn't touch that question
LocalDiscreteFunction(ThisType&& source) = default;
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~LocalDiscreteFunction()
{
}
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<commit_msg>[discretefunction.local] fix warning<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#define DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
#include <vector>
#include <type_traits>
#include <dune/common/deprecated.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/la/container/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>
#include <dune/gdt/spaces/fv/interface.hh>
#include <dune/gdt/mapper/interface.hh>
namespace Dune {
namespace GDT {
template <class VectorImp>
class ConstLocalDoFVector
{
static_assert(
std::is_base_of<Stuff::LA::VectorInterface<typename VectorImp::Traits, typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
public:
typedef VectorImp VectorType;
typedef typename VectorType::ScalarType ScalarType;
template <class M, class EntityType>
ConstLocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, const VectorType& vector)
: vector_(vector)
, indices_(mapper.numDofs(entity))
{
mapper.globalIndices(entity, indices_);
}
~ConstLocalDoFVector()
{
}
size_t size() const
{
return indices_.size();
}
ScalarType get(const size_t ii) const
{
assert(ii < indices_.size());
return vector_.get_entry(indices_[ii]);
}
private:
const VectorType& vector_;
protected:
Dune::DynamicVector<size_t> indices_;
private:
template <class V>
friend std::ostream& operator<<(std::ostream& /*out*/, const ConstLocalDoFVector<V>& /*vector*/);
}; // class ConstLocalDoFVector
template <class V>
std::ostream& operator<<(std::ostream& out, const ConstLocalDoFVector<V>& vector)
{
out << "[";
const size_t sz = vector.size();
if (sz > 0) {
out << vector.get(0);
for (size_t ii = 1; ii < sz; ++ii)
out << ", " << vector.get(ii);
} else
out << " ";
out << "]";
return out;
} // ... operator<<(...)
template <class VectorImp>
class LocalDoFVector : public ConstLocalDoFVector<VectorImp>
{
typedef ConstLocalDoFVector<VectorImp> BaseType;
public:
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::ScalarType ScalarType;
template <class M, class EntityType>
LocalDoFVector(const MapperInterface<M>& mapper, const EntityType& entity, VectorType& vector)
: BaseType(mapper, entity, vector)
, vector_(vector)
{
}
~LocalDoFVector()
{
}
void set(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.set_entry(indices_[ii], val);
}
void add(const size_t ii, const ScalarType& val)
{
assert(ii < indices_.size());
vector_.add_to_entry(indices_[ii], val);
}
template <class OtherVectorImp>
void add(const OtherVectorImp& vector)
{
assert(vector.size() == indices_.size());
for (size_t ii = 0; ii < indices_.size(); ++ii)
add(ii, vector[ii]);
}
private:
using BaseType::indices_;
VectorType& vector_;
}; // class LocalDoFVector
template <class SpaceImp, class VectorImp>
class ConstLocalDiscreteFunction
: public Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols>
{
static_assert(std::is_base_of<SpaceInterface<typename SpaceImp::Traits, SpaceImp::dimDomain, SpaceImp::dimRange,
SpaceImp::dimRangeCols>,
SpaceImp>::value,
"SpaceImp has to be derived from SpaceInterface!");
static_assert(std::is_base_of<Dune::Stuff::LA::VectorInterface<typename VectorImp::Traits,
typename VectorImp::Traits::ScalarType>,
VectorImp>::value,
"VectorImp has to be derived from Stuff::LA::VectorInterface!");
static_assert(std::is_same<typename SpaceImp::RangeFieldType, typename VectorImp::ScalarType>::value,
"Types do not match!");
typedef Stuff::LocalfunctionInterface<typename SpaceImp::EntityType, typename SpaceImp::DomainFieldType,
SpaceImp::dimDomain, typename SpaceImp::RangeFieldType, SpaceImp::dimRange,
SpaceImp::dimRangeCols> BaseType;
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef SpaceImp SpaceType;
typedef VectorImp VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef ConstLocalDoFVector<VectorType> ConstLocalDoFVectorType;
ConstLocalDiscreteFunction(const SpaceType& sp, const VectorType& globalVector, const EntityType& ent)
: BaseType(ent)
, space_(sp)
, base_(new BaseFunctionSetType(space_.base_function_set(this->entity())))
, localVector_(new ConstLocalDoFVectorType(space_.mapper(), this->entity(), globalVector))
{
assert(localVector_->size() == base_->size());
}
ConstLocalDiscreteFunction(ThisType&& source) = default;
ConstLocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~ConstLocalDiscreteFunction()
{
}
const SpaceType& space() const
{
return space_;
}
const DUNE_DEPRECATED_MSG("Use basis() instead (05.07.2015)!") BaseFunctionSetType& base() const
{
return basis();
}
const BaseFunctionSetType& basis() const
{
return *base_;
}
const ConstLocalDoFVectorType& vector() const
{
return *localVector_;
}
virtual size_t order() const override
{
return base_->order();
}
void evaluate(const DomainType& xx, RangeType& ret) const override final
{
assert(this->is_a_valid_point(xx));
if (!GDT::is_fv_space<SpaceType>::value) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<RangeType> tmpBaseValues(base_->size(), RangeType(0));
assert(localVector_->size() == tmpBaseValues.size());
base_->evaluate(xx, tmpBaseValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii) {
ret.axpy(localVector_->get(ii), tmpBaseValues[ii]);
}
} else {
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret[ii] = localVector_->get(ii);
}
} // ... evaluate(...)
virtual void jacobian(const DomainType& xx, JacobianRangeType& ret) const override final
{
assert(this->is_a_valid_point(xx));
if (!GDT::is_fv_space<SpaceType>::value) {
std::fill(ret.begin(), ret.end(), RangeFieldType(0));
std::vector<JacobianRangeType> tmpBaseJacobianValues(base_->size(), JacobianRangeType(0));
assert(localVector_->size() == tmpBaseJacobianValues.size());
base_->jacobian(xx, tmpBaseJacobianValues);
for (size_t ii = 0; ii < localVector_->size(); ++ii)
ret.axpy(localVector_->get(ii), tmpBaseJacobianValues[ii]);
} else {
ret = JacobianRangeType(0);
}
} // ... jacobian(...)
using BaseType::evaluate;
using BaseType::jacobian;
protected:
const SpaceType& space_;
std::unique_ptr<const BaseFunctionSetType> base_;
std::unique_ptr<const ConstLocalDoFVectorType> localVector_;
}; // class ConstLocalDiscreteFunction
template <class SpaceImp, class VectorImp>
class LocalDiscreteFunction : public ConstLocalDiscreteFunction<SpaceImp, VectorImp>
{
typedef ConstLocalDiscreteFunction<SpaceImp, VectorImp> BaseType;
typedef LocalDiscreteFunction<SpaceImp, VectorImp> ThisType;
public:
typedef typename BaseType::SpaceType SpaceType;
typedef typename BaseType::VectorType VectorType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::DomainFieldType DomainFieldType;
static const size_t dimDomain = BaseType::dimDomain;
typedef typename BaseType::DomainType DomainType;
typedef typename BaseType::RangeFieldType RangeFieldType;
static const size_t dimRangeRows = BaseType::dimRangeCols;
static const size_t dimRangeCols = BaseType::dimRangeCols;
typedef typename BaseType::RangeType RangeType;
typedef typename BaseType::JacobianRangeType JacobianRangeType;
private:
typedef typename SpaceType::BaseFunctionSetType BaseFunctionSetType;
public:
typedef LocalDoFVector<VectorType> LocalDoFVectorType;
LocalDiscreteFunction(const SpaceType& space, VectorType& globalVector, const EntityType& ent)
: BaseType(space, globalVector, ent)
, localVector_(new LocalDoFVectorType(space_.mapper(), entity_, globalVector))
{
assert(localVector_->size() == base_->size());
}
//! previous comment questioned validity, defaulting this doesn't touch that question
LocalDiscreteFunction(ThisType&& source) = default;
LocalDiscreteFunction(const ThisType& other) = delete;
ThisType& operator=(const ThisType& other) = delete;
virtual ~LocalDiscreteFunction()
{
}
LocalDoFVectorType& vector()
{
return *localVector_;
}
private:
using BaseType::space_;
using BaseType::entity_;
using BaseType::base_;
std::unique_ptr<LocalDoFVectorType> localVector_;
}; // class LocalDiscreteFunction
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_DISCRETEFUNCTION_LOCAL_HH
<|endoftext|>
|
<commit_before>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH
#define DUNE_PYMOR_OPERATORS_INTERFACES_HH
#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/la/container/interfaces.hh>
namespace Dune {
namespace Pymor {
class OperatorInterface
: public Parametric
{
public:
template< class... Args >
OperatorInterface(Args&& ...args)
: Parametric(std::forward< Args >(args)...)
{}
virtual ~OperatorInterface() {}
virtual bool linear() const = 0;
virtual unsigned int dim_source() const = 0;
virtual unsigned int dim_range() const = 0;
virtual std::string type_source() const = 0;
virtual std::string type_range() const = 0;
virtual void apply(const LA::VectorInterface* /*source*/,
LA::VectorInterface* /*range*/,
const Parameter /*mu*/ = Parameter()) const
throw (Exception::types_are_not_compatible,
Exception::you_have_to_implement_this,
Exception::sizes_do_not_match,
Exception::wrong_parameter_type) = 0;
virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const
throw (Exception::types_are_not_compatible,
Exception::you_have_to_implement_this,
Exception::sizes_do_not_match,
Exception::wrong_parameter_type)
{
DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
"U (" << U->type() << ") is not a compatible type_source (" << type_source() << ")!");
LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());
apply(U, ret, mu);
return ret;
}
virtual double apply2(const LA::VectorInterface* range,
const LA::VectorInterface* source,
const Parameter mu = Parameter()) const
throw (Exception::types_are_not_compatible,
Exception::sizes_do_not_match,
Exception::wrong_parameter_type)
{
std::stringstream msg;
size_t throw_up = 0;
if (source->type() != type_source()) {
msg << "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")";
++throw_up;
}
if (range->type() != type_range()) {
if (throw_up)
msg << " and ";
msg << "range (" << range->type() << ") is not a compatible type_range (" << type_range() << ")";
}
if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << "!");
LA::VectorInterface* tmp = apply(source, tmp, mu);
return range->dot(tmp);
}
virtual OperatorInterface* freeze_parameter(const Parameter /*mu*/ = Parameter()) const
throw (Exception::this_is_not_parametric) = 0;
}; // class OperatorInterface
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_OPERATORS_INTERFACES_HH
<commit_msg>[operators.interface] some fixes<commit_after>// This file is part of the dune-pymor project:
// https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_PYMOR_OPERATORS_INTERFACES_HH
#define DUNE_PYMOR_OPERATORS_INTERFACES_HH
#include <dune/pymor/common/exceptions.hh>
#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/la/container/interfaces.hh>
#include <dune/pymor/la/container.hh>
namespace Dune {
namespace Pymor {
class OperatorInterface
: public Parametric
{
public:
template< class... Args >
OperatorInterface(Args&& ...args)
: Parametric(std::forward< Args >(args)...)
{}
virtual ~OperatorInterface() {}
virtual bool linear() const = 0;
virtual unsigned int dim_source() const = 0;
virtual unsigned int dim_range() const = 0;
virtual std::string type_source() const = 0;
virtual std::string type_range() const = 0;
virtual void apply(const LA::VectorInterface* /*source*/,
LA::VectorInterface* /*range*/,
const Parameter /*mu*/ = Parameter()) const
throw (Exception::types_are_not_compatible,
Exception::you_have_to_implement_this,
Exception::sizes_do_not_match,
Exception::wrong_parameter_type) = 0;
virtual LA::VectorInterface* apply(const LA::VectorInterface* source, const Parameter mu = Parameter()) const
throw (Exception::types_are_not_compatible,
Exception::you_have_to_implement_this,
Exception::sizes_do_not_match,
Exception::wrong_parameter_type)
{
DUNE_PYMOR_THROW(Exception::types_are_not_compatible,
"source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")!");
LA::VectorInterface* ret = LA::createVector(type_range(), dim_range());
apply(source, ret, mu);
return ret;
}
virtual double apply2(const LA::VectorInterface* range,
const LA::VectorInterface* source,
const Parameter mu = Parameter()) const
throw (Exception::types_are_not_compatible,
Exception::sizes_do_not_match,
Exception::wrong_parameter_type)
{
std::stringstream msg;
size_t throw_up = 0;
if (source->type() != type_source()) {
msg << "source (" << source->type() << ") is not a compatible type_source (" << type_source() << ")";
++throw_up;
}
if (range->type() != type_range()) {
if (throw_up)
msg << " and ";
msg << "range (" << range->type() << ") is not a compatible type_range (" << type_range() << ")";
}
if (throw_up) DUNE_PYMOR_THROW(Exception::types_are_not_compatible, msg.str() << "!");
LA::VectorInterface* tmp = apply(source, mu);
return range->dot(tmp);
}
virtual OperatorInterface* freeze_parameter(const Parameter /*mu*/ = Parameter()) const
throw (Exception::this_is_not_parametric) = 0;
}; // class OperatorInterface
} // namespace Pymor
} // namespace Dune
#endif // DUNE_PYMOR_OPERATORS_INTERFACES_HH
<|endoftext|>
|
<commit_before>/*
* error.hpp
*
* Created on: Oct 6, 2015
* Author: zmij
*/
#ifndef TIP_HTTP_SERVER_ERROR_HPP_
#define TIP_HTTP_SERVER_ERROR_HPP_
#include <stdexcept>
#include <tip/log.hpp>
#include <tip/http/common/response_status.hpp>
namespace tip {
namespace http {
namespace server {
class error: public std::runtime_error {
public:
error(std::string const& cat, std::string const& w,
response_status s
= response_status::internal_server_error,
log::logger::event_severity sv = log::logger::ERROR) :
runtime_error(w), category_(cat), status_(s), severity_(sv) {};
virtual ~error() {}
virtual std::string const&
name() const;
virtual int
code() const
{ return !0; }
log::logger::event_severity
severity() const
{ return severity_; }
std::string const&
category() const
{ return category_; }
response_status
status() const
{ return status_; }
void
log_error(std::string const& message = "") const;
private:
std::string category_;
response_status status_;
log::logger::event_severity severity_;
};
class client_error : public error {
public:
client_error(std::string const& cat, std::string const& w,
response_status s
= response_status::bad_request,
log::logger::event_severity sv = log::logger::ERROR)
: error(cat, w, s, sv) {};
virtual ~client_error() {};
virtual std::string const&
name() const;
};
} /* namespace server */
} /* namespace http */
} /* namespace tip */
#endif /* TIP_HTTP_SERVER_ERROR_HPP_ */
<commit_msg>Special function for lobby_error log<commit_after>/*
* error.hpp
*
* Created on: Oct 6, 2015
* Author: zmij
*/
#ifndef TIP_HTTP_SERVER_ERROR_HPP_
#define TIP_HTTP_SERVER_ERROR_HPP_
#include <stdexcept>
#include <tip/log.hpp>
#include <tip/http/common/response_status.hpp>
namespace tip {
namespace http {
namespace server {
class error: public std::runtime_error {
public:
error(std::string const& cat, std::string const& w,
response_status s
= response_status::internal_server_error,
log::logger::event_severity sv = log::logger::ERROR) :
runtime_error(w), category_(cat), status_(s), severity_(sv) {};
virtual ~error() {}
virtual std::string const&
name() const;
virtual int
code() const
{ return !0; }
log::logger::event_severity
severity() const
{ return severity_; }
std::string const&
category() const
{ return category_; }
response_status
status() const
{ return status_; }
virtual void
log_error(std::string const& message = "") const;
private:
std::string category_;
response_status status_;
log::logger::event_severity severity_;
};
class client_error : public error {
public:
client_error(std::string const& cat, std::string const& w,
response_status s
= response_status::bad_request,
log::logger::event_severity sv = log::logger::ERROR)
: error(cat, w, s, sv) {};
virtual ~client_error() {};
virtual std::string const&
name() const;
};
} /* namespace server */
} /* namespace http */
} /* namespace tip */
#endif /* TIP_HTTP_SERVER_ERROR_HPP_ */
<|endoftext|>
|
<commit_before>// -----------------------------------------------------------------------------
//
// GAMCS -- Generalized Agent Model and Computer Simulation
//
// Copyright (C) 2013-2014, Andy Huang <andyspider@126.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// -----------------------------------------------------------------------------
#include <stdlib.h>
#include <sys/timeb.h>
#include "gamcs/Avatar.h"
#include "gamcs/debug.h"
#include "gamcs/platforms.h"
namespace gamcs
{
/**
* @brief The default constructor.
*
* @param id the avatar id
*/
Avatar::Avatar(int i) :
id(i), ava_loop_count(0), myagent(NULL)
{
}
/**
* @brief The default destructor.
*/
Avatar::~Avatar()
{
}
/**
* @brief Step avatar for one circle.
*
* Note: if there are no more actions for an avatar to perform, the step will return -1 which means the end is reached.
* @return 0 on success, -1 if reach the end
* @see loop()
*/
int Avatar::step()
{
++ava_loop_count; // increase count
/* Perceive state */
Agent::State cs = perceiveState(); // get current state
dbgmoreprt("Launch():", "Avatar %d, State: %" ST_FMT "\n", id, cs);
/* Process */
OSpace acts = availableActions(cs); // get all action candidates of a state
Agent::Action act = myagent->process(cs, acts); // choose an action from candidates
// check validation
if (act == Agent::INVALID_ACTION) // no valid actions available, reach a dead end, quit. !!!: be sure to check this before update stage
return -1;
/* update memory */
myagent->update(originalPayoff(cs)); // agent update inner states
/* Perform action */
performAction(act); // otherwise, perform the action
return 0;
}
/**
* @brief Step avatar in loops.
*
* @param [in] sps steps/loops per second, < 0 if not control
* @see step()
*/
void Avatar::loop(int sps)
{
// check if agent is connected
if (myagent == NULL)
ERROR("launch(): Avatar is not connected to any agent!\n");
unsigned long control_step_time = 0; /**< delta time in millisecond requested bewteen two steps */
if (sps > 0)
control_step_time = 1000 / sps; // (1 / sps) * 1000
unsigned long start_time = 0;
while (true)
{
dbgmoreprt("Enter Launch Loop ", "------------------------------ count == %ld\n", ava_loop_count);
if (sps > 0)
start_time = getCurrentTime();
int re = step();
if (re == -1) // break if no actions available
break;
// handle time related job
if (sps > 0) // no control when sps <= 0
{
unsigned long consumed_time = getCurrentTime() - start_time;
long time_remaining = control_step_time - consumed_time;
if (time_remaining > 0) // remaining time
{
dbgmoreprt("",
"You got %ld milliseconds remaining to do other things.\n",
time_remaining);
// do some useful things here if you don't want to sleep
pi_msleep(time_remaining);
}
else
{
WARNNING(
"time is not enough to run a step, %ldms in lack, try to decrease the sps!\n",
-time_remaining);
}
}
}
// quit
dbgmoreprt("Exit Launch Loop", "----------------------------------------------------------- %s Exit!\n", name.c_str());
return;
}
/**
* @brief Connect avatar to an agent.
*
* Every avatar should be connected to an agent before activated. Just like every man should have soul.
* @param [in] agt the agent to be connected
*/
void Avatar::connectAgent(Agent *agt)
{
myagent = agt;
}
/**
* @brief Get the original payoff of a state.
*
* There is where you can control your avatar, you can train it by telling what it likes and dislikes.
* Your avatar will chase after the states that it told to like, and escape from the states told to dislike.
*
* By default this function returns 1 for every state which means that as long as the avatar can survive in the next state, the avatar should like it.
* This is how the evolution works.
* @param [in] st the state
* @return original payoff of the state
*/
float Avatar::originalPayoff(Agent::State st)
{
UNUSED(st);
return 1; // original payoff of states is 1.0 by default
}
/**
* @brief Get current time in milliseconds.
*
* @return the current time as milliseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
*/
unsigned long Avatar::getCurrentTime()
{
struct timeb tb;
ftime(&tb);
return 1000 * tb.time + tb.millitm;
}
} // namespace gamcs
<commit_msg>fix originalPayoof return comments<commit_after>// -----------------------------------------------------------------------------
//
// GAMCS -- Generalized Agent Model and Computer Simulation
//
// Copyright (C) 2013-2014, Andy Huang <andyspider@126.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// -----------------------------------------------------------------------------
#include <stdlib.h>
#include <sys/timeb.h>
#include "gamcs/Avatar.h"
#include "gamcs/debug.h"
#include "gamcs/platforms.h"
namespace gamcs
{
/**
* @brief The default constructor.
*
* @param id the avatar id
*/
Avatar::Avatar(int i) :
id(i), ava_loop_count(0), myagent(NULL)
{
}
/**
* @brief The default destructor.
*/
Avatar::~Avatar()
{
}
/**
* @brief Step avatar for one circle.
*
* Note: if there are no more actions for an avatar to perform, the step will return -1 which means the end is reached.
* @return 0 on success, -1 if reach the end
* @see loop()
*/
int Avatar::step()
{
++ava_loop_count; // increase count
/* Perceive state */
Agent::State cs = perceiveState(); // get current state
dbgmoreprt("Launch():", "Avatar %d, State: %" ST_FMT "\n", id, cs);
/* Process */
OSpace acts = availableActions(cs); // get all action candidates of a state
Agent::Action act = myagent->process(cs, acts); // choose an action from candidates
// check validation
if (act == Agent::INVALID_ACTION) // no valid actions available, reach a dead end, quit. !!!: be sure to check this before update stage
return -1;
/* update memory */
myagent->update(originalPayoff(cs)); // agent update inner states
/* Perform action */
performAction(act); // otherwise, perform the action
return 0;
}
/**
* @brief Step avatar in loops.
*
* @param [in] sps steps/loops per second, < 0 if not control
* @see step()
*/
void Avatar::loop(int sps)
{
// check if agent is connected
if (myagent == NULL)
ERROR("launch(): Avatar is not connected to any agent!\n");
unsigned long control_step_time = 0; /**< delta time in millisecond requested bewteen two steps */
if (sps > 0)
control_step_time = 1000 / sps; // (1 / sps) * 1000
unsigned long start_time = 0;
while (true)
{
dbgmoreprt("Enter Launch Loop ", "------------------------------ count == %ld\n", ava_loop_count);
if (sps > 0)
start_time = getCurrentTime();
int re = step();
if (re == -1) // break if no actions available
break;
// handle time related job
if (sps > 0) // no control when sps <= 0
{
unsigned long consumed_time = getCurrentTime() - start_time;
long time_remaining = control_step_time - consumed_time;
if (time_remaining > 0) // remaining time
{
dbgmoreprt("",
"You got %ld milliseconds remaining to do other things.\n",
time_remaining);
// do some useful things here if you don't want to sleep
pi_msleep(time_remaining);
}
else
{
WARNNING(
"time is not enough to run a step, %ldms in lack, try to decrease the sps!\n",
-time_remaining);
}
}
}
// quit
dbgmoreprt("Exit Launch Loop", "----------------------------------------------------------- %s Exit!\n", name.c_str());
return;
}
/**
* @brief Connect avatar to an agent.
*
* Every avatar should be connected to an agent before activated. Just like every man should have soul.
* @param [in] agt the agent to be connected
*/
void Avatar::connectAgent(Agent *agt)
{
myagent = agt;
}
/**
* @brief Get the original payoff of a state.
*
* There is where you can control your avatar, you can train it by telling what it likes and dislikes.
* Your avatar will chase after the states that it told to like, and escape from the states told to dislike.
*
* By default this function returns 1 for every state which means that as long as the avatar can survive in the next state, the avatar should like it.
* This is how the evolution works.
* @param [in] st the state
* @return original payoff of the state, if you want avatar to use the original payoff of the state set last time, return INVALID_PAYOFF.
*/
float Avatar::originalPayoff(Agent::State st)
{
UNUSED(st);
return 1; // original payoff of states is 1.0 by default
}
/**
* @brief Get current time in milliseconds.
*
* @return the current time as milliseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC)
*/
unsigned long Avatar::getCurrentTime()
{
struct timeb tb;
ftime(&tb);
return 1000 * tb.time + tb.millitm;
}
} // namespace gamcs
<|endoftext|>
|
<commit_before>#include "Binary.hpp"
#include <stdexcept>
#include <algorithm>
#include "constants.hpp"
#include "Tree.hpp"
using namespace std;
int safe_fclose(FILE* fptr) { return fptr ? fclose(fptr) : 0; }
Binary::Binary(const string& binary_file_path) : bin_fptr_(nullptr, safe_fclose)
{
// open the binary file
pll_binary_header_t header;
bin_fptr_ = unique_fptr(pllmod_binary_open(binary_file_path.c_str(), &header), safe_fclose);
if (!bin_fptr_)
throw runtime_error{"Could not open binary file for reading."};
if (header.access_type != PLLMOD_BIN_ACCESS_RANDOM)
throw runtime_error{"Binary file must be random access enabled."};
if (header.n_blocks <= 0)
throw runtime_error{string("Binary file header must have nonzero positive number of blocks: ")
+ to_string(header.n_blocks)};
// proccess the random access map
unsigned int n_blocks;
pll_block_map_t* block_map;
block_map = pllmod_binary_get_map(bin_fptr_.get(), &n_blocks);
assert(block_map);
assert(n_blocks);
for (size_t i = 0; i < n_blocks; i++)
{
map_.push_back(block_map[i]);
}
free(block_map);
}
static long int get_offset(vector<pll_block_map_t>& map, const int block_id)
{
auto item = map.begin();
while (item != map.end())
{
if (item->block_id == block_id)
break;
item++;
}
if(item == map.end())
throw runtime_error{string("Map does not contain block_id: ") + to_string(block_id)};
return item->block_offset;
}
void Binary::load_clv(pll_partition_t * partition, const unsigned int clv_index)
{
assert(bin_fptr_);
assert(clv_index < partition->clv_buffers + partition->tips);
if (partition->attributes & PLL_ATTRIB_PATTERN_TIP)
assert(clv_index >= partition->tips);
if (!(partition->clv[clv_index]))
{
size_t clv_size = partition->sites * partition->states_padded *
partition->rate_cats*sizeof(double);
partition->clv[clv_index] = (double*) pll_aligned_alloc(clv_size, partition->alignment);
if (!partition->clv[i])
throw runtime_error{"Could not allocate CLV memory"};
}
unsigned int attributes;
auto err = pllmod_binary_clv_load(
bin_fptr_.get(),
0,
partition,
clv_index,
&attributes,
get_offset(map_, clv_index));
if (err != PLL_SUCCESS)
throw runtime_error{string("Loading CLV failed: ") + pll_errmsg};
}
void Binary::load_tipchars(pll_partition_t * partition, const unsigned int tipchars_index)
{
assert(bin_fptr_);
assert(tipchars_index < partition->tips);
assert(partition->attributes & PLL_ATTRIB_PATTERN_TIP);
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0, &size, &type, &attributes, get_offset(map_, tipchars_index));
if (!ptr)
throw runtime_error{string("Loading tipchar failed: ") + pll_errmsg};
partition->tipchars[tipchars_index] = (unsigned char*)ptr;
}
void Binary::load_scaler(pll_partition_t * partition, const unsigned int scaler_index)
{
assert(bin_fptr_);
assert(scaler_index < partition->scale_buffers);
auto block_offset = partition->clv_buffers + partition->tips;
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0,
&size, &type, &attributes, get_offset(map_, block_offset + scaler_index));
if (!ptr)
throw runtime_error{string("Loading scaler failed: ") + pll_errmsg};
partition->scale_buffer[scaler_index] = (unsigned int*)ptr;
}
static pll_partition_t* skeleton_partition()
{
auto attributes = PLL_ATTRIB_ARCH_SSE;
#ifdef __AVX
attributes = PLL_ATTRIB_ARCH_AVX;
#endif
attributes |= PLL_ATTRIB_PATTERN_TIP;
auto partition = pll_partition_create(
3, // number of tip nodes
1, // number of extra clv buffers
STATES,
1, // number of sites
1, // number of concurrent subs. models
1, // number of probabillity matrices
RATE_CATS,
1, // number of scale buffers
//pll_map_nt,
attributes);
if (!partition)
throw runtime_error{string("Creating skeleton partition: ") + pll_errmsg};
// ensure clv, tipchar and scaler fields are only shallowly allocated
// TODO
return partition;
}
static void dealloc_buffers(pll_partition_t* part)
{
// dealloc clvs and tipchars
if (part->tipchars)
for (size_t i = 0; i < part->tips; ++i)
{
pll_aligned_free(part->tipchars[i]);
part->tipchars[i] = nullptr;
}
if (part->clv)
{
size_t start = (part->attributes & PLL_ATTRIB_PATTERN_TIP) ? part->tips : 0;
for (size_t i = start; i < part->clv_buffers + part->tips; ++i)
{
pll_aligned_free(part->clv[i]);
part->clv[i] = nullptr;
}
}
if (part->scale_buffer)
{
for (size_t i = 0; i < part->scale_buffers; ++i)
{
free(part->scale_buffer[i]);
part->scale_buffer[i] = nullptr;
}
}
}
pll_partition_t* Binary::load_partition()
{
// make skeleton partition that only allocates the pointers to the clv/tipchar buffers
auto skelly = nullptr;// skeleton_partition();
unsigned int attributes = PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
auto partition = pllmod_binary_partition_load(bin_fptr_.get(), 0, skelly, &attributes,
get_offset(map_, -1));
if (!partition)
throw runtime_error{string("Error loading partition: ") + pll_errmsg};
// free up buffers for things we want to load on demand
// TODO never alloc in the first place
dealloc_buffers(partition);
return partition;
}
pll_utree_t* Binary::load_utree()
{
unsigned int attributes = 0;
auto tree = pllmod_binary_utree_load(bin_fptr_.get(), 0, &attributes, get_offset(map_, -2));
if (!tree)
throw runtime_error{string("Loading tree: ") + pll_errmsg};
return tree;
}
/**
Writes the structures and data encapsulated in Tree to the specified file in the binary format.
Writes them in such a way that the Binary class can read them.
*/
void dump_to_binary(Tree& tree, const string& file)
{
auto num_clvs = tree.partition()->clv_buffers;
auto num_tips = tree.partition()->tips;
auto num_scalers = tree.partition()->scale_buffers;
auto max_clv_index = num_clvs + num_tips;
pll_binary_header_t header;
auto fptr = pllmod_binary_create(
file.c_str(),
&header,
PLLMOD_BIN_ACCESS_RANDOM,
2 + num_clvs + num_tips + num_scalers);
if(!fptr)
throw runtime_error{string("Opening binary file for writing: ") + pll_errmsg};
unsigned int attributes = PLLMOD_BIN_ATTRIB_UPDATE_MAP | PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
int block_id = -2;
bool use_tipchars = tree.partition()->attributes & PLL_ATTRIB_PATTERN_TIP;
// dump the utree structure
if(!pllmod_binary_utree_dump(fptr, block_id++, tree.tree(), num_tips, attributes))
throw runtime_error{string("Dumping the utree to binary: ") + pll_errmsg};
// dump the partition
if(!pllmod_binary_partition_dump(fptr, block_id++, tree.partition(), attributes))
throw runtime_error{string("Dumping partition to binary: ") + pll_errmsg};
// dump the tipchars, but only if partition uses them
unsigned int tip_index = 0;
if (use_tipchars)
{
for (tip_index = 0; tip_index < num_tips; tip_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->tipchars[tip_index],
tree.partition()->sites * sizeof(char), attributes))
throw runtime_error{string("Dumping tipchars to binary: ") + pll_errmsg};
}
}
// dump the clvs
for (unsigned int clv_index = tip_index; clv_index < max_clv_index; clv_index++)
{
if(!pllmod_binary_clv_dump(fptr, block_id++, tree.partition(), clv_index, attributes))
throw runtime_error{string("Dumping clvs to binary: ") + pll_errmsg};
}
// dump the scalers
for (unsigned int scaler_index = 0; scaler_index < num_scalers; scaler_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->scale_buffer[scaler_index],
tree.partition()->sites * sizeof(unsigned int), attributes))
throw runtime_error{string("Dumping scalers to binary: ") + pll_errmsg};
}
fclose(fptr);
}
<commit_msg>fixed incorrect index<commit_after>#include "Binary.hpp"
#include <stdexcept>
#include <algorithm>
#include "constants.hpp"
#include "Tree.hpp"
using namespace std;
int safe_fclose(FILE* fptr) { return fptr ? fclose(fptr) : 0; }
Binary::Binary(const string& binary_file_path) : bin_fptr_(nullptr, safe_fclose)
{
// open the binary file
pll_binary_header_t header;
bin_fptr_ = unique_fptr(pllmod_binary_open(binary_file_path.c_str(), &header), safe_fclose);
if (!bin_fptr_)
throw runtime_error{"Could not open binary file for reading."};
if (header.access_type != PLLMOD_BIN_ACCESS_RANDOM)
throw runtime_error{"Binary file must be random access enabled."};
if (header.n_blocks <= 0)
throw runtime_error{string("Binary file header must have nonzero positive number of blocks: ")
+ to_string(header.n_blocks)};
// proccess the random access map
unsigned int n_blocks;
pll_block_map_t* block_map;
block_map = pllmod_binary_get_map(bin_fptr_.get(), &n_blocks);
assert(block_map);
assert(n_blocks);
for (size_t i = 0; i < n_blocks; i++)
{
map_.push_back(block_map[i]);
}
free(block_map);
}
static long int get_offset(vector<pll_block_map_t>& map, const int block_id)
{
auto item = map.begin();
while (item != map.end())
{
if (item->block_id == block_id)
break;
item++;
}
if(item == map.end())
throw runtime_error{string("Map does not contain block_id: ") + to_string(block_id)};
return item->block_offset;
}
void Binary::load_clv(pll_partition_t * partition, const unsigned int clv_index)
{
assert(bin_fptr_);
assert(clv_index < partition->clv_buffers + partition->tips);
if (partition->attributes & PLL_ATTRIB_PATTERN_TIP)
assert(clv_index >= partition->tips);
if (!(partition->clv[clv_index]))
{
size_t clv_size = partition->sites * partition->states_padded *
partition->rate_cats*sizeof(double);
partition->clv[clv_index] = (double*) pll_aligned_alloc(clv_size, partition->alignment);
if (!partition->clv[clv_index])
throw runtime_error{"Could not allocate CLV memory"};
}
unsigned int attributes;
auto err = pllmod_binary_clv_load(
bin_fptr_.get(),
0,
partition,
clv_index,
&attributes,
get_offset(map_, clv_index));
if (err != PLL_SUCCESS)
throw runtime_error{string("Loading CLV failed: ") + pll_errmsg};
}
void Binary::load_tipchars(pll_partition_t * partition, const unsigned int tipchars_index)
{
assert(bin_fptr_);
assert(tipchars_index < partition->tips);
assert(partition->attributes & PLL_ATTRIB_PATTERN_TIP);
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0, &size, &type, &attributes, get_offset(map_, tipchars_index));
if (!ptr)
throw runtime_error{string("Loading tipchar failed: ") + pll_errmsg};
partition->tipchars[tipchars_index] = (unsigned char*)ptr;
}
void Binary::load_scaler(pll_partition_t * partition, const unsigned int scaler_index)
{
assert(bin_fptr_);
assert(scaler_index < partition->scale_buffers);
auto block_offset = partition->clv_buffers + partition->tips;
unsigned int type, attributes;
size_t size;
auto ptr = pllmod_binary_custom_load(bin_fptr_.get(), 0,
&size, &type, &attributes, get_offset(map_, block_offset + scaler_index));
if (!ptr)
throw runtime_error{string("Loading scaler failed: ") + pll_errmsg};
partition->scale_buffer[scaler_index] = (unsigned int*)ptr;
}
static pll_partition_t* skeleton_partition()
{
auto attributes = PLL_ATTRIB_ARCH_SSE;
#ifdef __AVX
attributes = PLL_ATTRIB_ARCH_AVX;
#endif
attributes |= PLL_ATTRIB_PATTERN_TIP;
auto partition = pll_partition_create(
3, // number of tip nodes
1, // number of extra clv buffers
STATES,
1, // number of sites
1, // number of concurrent subs. models
1, // number of probabillity matrices
RATE_CATS,
1, // number of scale buffers
//pll_map_nt,
attributes);
if (!partition)
throw runtime_error{string("Creating skeleton partition: ") + pll_errmsg};
// ensure clv, tipchar and scaler fields are only shallowly allocated
// TODO
return partition;
}
static void dealloc_buffers(pll_partition_t* part)
{
// dealloc clvs and tipchars
if (part->tipchars)
for (size_t i = 0; i < part->tips; ++i)
{
pll_aligned_free(part->tipchars[i]);
part->tipchars[i] = nullptr;
}
if (part->clv)
{
size_t start = (part->attributes & PLL_ATTRIB_PATTERN_TIP) ? part->tips : 0;
for (size_t i = start; i < part->clv_buffers + part->tips; ++i)
{
pll_aligned_free(part->clv[i]);
part->clv[i] = nullptr;
}
}
if (part->scale_buffer)
{
for (size_t i = 0; i < part->scale_buffers; ++i)
{
free(part->scale_buffer[i]);
part->scale_buffer[i] = nullptr;
}
}
}
pll_partition_t* Binary::load_partition()
{
// make skeleton partition that only allocates the pointers to the clv/tipchar buffers
auto skelly = nullptr;// skeleton_partition();
unsigned int attributes = PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
auto partition = pllmod_binary_partition_load(bin_fptr_.get(), 0, skelly, &attributes,
get_offset(map_, -1));
if (!partition)
throw runtime_error{string("Error loading partition: ") + pll_errmsg};
// free up buffers for things we want to load on demand
// TODO never alloc in the first place
dealloc_buffers(partition);
return partition;
}
pll_utree_t* Binary::load_utree()
{
unsigned int attributes = 0;
auto tree = pllmod_binary_utree_load(bin_fptr_.get(), 0, &attributes, get_offset(map_, -2));
if (!tree)
throw runtime_error{string("Loading tree: ") + pll_errmsg};
return tree;
}
/**
Writes the structures and data encapsulated in Tree to the specified file in the binary format.
Writes them in such a way that the Binary class can read them.
*/
void dump_to_binary(Tree& tree, const string& file)
{
auto num_clvs = tree.partition()->clv_buffers;
auto num_tips = tree.partition()->tips;
auto num_scalers = tree.partition()->scale_buffers;
auto max_clv_index = num_clvs + num_tips;
pll_binary_header_t header;
auto fptr = pllmod_binary_create(
file.c_str(),
&header,
PLLMOD_BIN_ACCESS_RANDOM,
2 + num_clvs + num_tips + num_scalers);
if(!fptr)
throw runtime_error{string("Opening binary file for writing: ") + pll_errmsg};
unsigned int attributes = PLLMOD_BIN_ATTRIB_UPDATE_MAP | PLLMOD_BIN_ATTRIB_PARTITION_DUMP_WGT;
int block_id = -2;
bool use_tipchars = tree.partition()->attributes & PLL_ATTRIB_PATTERN_TIP;
// dump the utree structure
if(!pllmod_binary_utree_dump(fptr, block_id++, tree.tree(), num_tips, attributes))
throw runtime_error{string("Dumping the utree to binary: ") + pll_errmsg};
// dump the partition
if(!pllmod_binary_partition_dump(fptr, block_id++, tree.partition(), attributes))
throw runtime_error{string("Dumping partition to binary: ") + pll_errmsg};
// dump the tipchars, but only if partition uses them
unsigned int tip_index = 0;
if (use_tipchars)
{
for (tip_index = 0; tip_index < num_tips; tip_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->tipchars[tip_index],
tree.partition()->sites * sizeof(char), attributes))
throw runtime_error{string("Dumping tipchars to binary: ") + pll_errmsg};
}
}
// dump the clvs
for (unsigned int clv_index = tip_index; clv_index < max_clv_index; clv_index++)
{
if(!pllmod_binary_clv_dump(fptr, block_id++, tree.partition(), clv_index, attributes))
throw runtime_error{string("Dumping clvs to binary: ") + pll_errmsg};
}
// dump the scalers
for (unsigned int scaler_index = 0; scaler_index < num_scalers; scaler_index++)
{
if(!pllmod_binary_custom_dump(fptr, block_id++, tree.partition()->scale_buffer[scaler_index],
tree.partition()->sites * sizeof(unsigned int), attributes))
throw runtime_error{string("Dumping scalers to binary: ") + pll_errmsg};
}
fclose(fptr);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbLabelImageSmallRegionMergingFilter.h"
#include "itkChangeLabelImageFilter.h"
#include "otbStopwatch.h"
namespace otb
{
namespace Wrapper
{
class SmallRegionsMerging : public Application
{
public:
typedef SmallRegionsMerging Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef FloatVectorImageType ImageType;
typedef ImageType::InternalPixelType ImagePixelType;
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::InternalPixelType LabelImagePixelType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter
<ImageType, LabelImageType> StatisticsMapFromLabelImageFilterType;
typedef otb::LabelImageSmallRegionMergingFilter<LabelImageType>
LabelImageSmallRegionMergingFilterType;
typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType>
ChangeLabelImageFilterType;
itkNewMacro(Self);
itkTypeMacro(Merging, otb::Application);
private:
ChangeLabelImageFilterType::Pointer m_ChangeLabelFilter;
void DoInit() override
{
SetName("SmallRegionsMerging");
SetDescription("This application merges small regions of a segmentation "
"result to connected region.");
SetDocName("Small Region Merging");
SetDocLongDescription("Given a segmentation result and the original image,"
" it will merge segments whose size in pixels is"
" lower than minsize parameter with the adjacent"
" segments with the adjacent segment with closest"
" radiometry and acceptable size. \n\n"
"Small segments will be processed by increasing size:"
" first all segments for which area is equal to 1"
" pixel will be merged with adjacent segments, then"
" all segments of area equal to 2 pixels will be"
" processed, until segments of area minsize.");
SetDocLimitations( "None") ;
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Segmentation");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription( "in", "The input image, containing initial"
" spectral signatures corresponding to the segmented image (inseg)." );
AddParameter(ParameterType_InputImage, "inseg", "Segmented image");
SetParameterDescription( "inseg", "Segmented image where each pixel value"
" is the unique integer label of the segment it belongs to." );
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out", "The output image. The output image is the"
" segmented image where the minimal segments have been merged." );
SetDefaultOutputPixelType("out",ImagePixelType_uint32);
AddParameter(ParameterType_Int, "minsize", "Minimum Segment Size");
SetParameterDescription("minsize", "Minimum Segment Size. If, after the "
" segmentation, a segment is of size strictly lower than this criterion,"
" the segment is merged with the segment that has the closest sepctral"
" signature.");
SetDefaultParameterInt("minsize", 50);
SetMinimumParameterIntValue("minsize", 1);
MandatoryOff("minsize");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in","smooth.tif");
SetDocExampleParameterValue("inseg","segmentation.tif");
SetDocExampleParameterValue("out","merged.tif");
SetDocExampleParameterValue("minsize","50");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
}
void DoExecute() override
{
// Start Timer for the application
auto Timer = Stopwatch::StartNew();
unsigned int minSize = GetParameterInt("minsize");
//Acquisition of the input image dimensions
ImageType::Pointer imageIn = GetParameterImage("in");
LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg");
// Compute statistics for each segment
auto labelStatsFilter = StatisticsMapFromLabelImageFilterType::New();
labelStatsFilter->SetInput(imageIn);
labelStatsFilter->SetInputLabelImage(labelIn);
AddProcess(labelStatsFilter->GetStreamer() , "Computing stats on input"
" image ...");
labelStatsFilter->Update();
// Convert Map to Unordered map
auto labelPopulationMap = labelStatsFilter->GetLabelPopulationMap();
std::unordered_map< unsigned int,double> labelPopulation;
for (auto population : labelPopulationMap)
{
labelPopulation[population.first]=population.second;
}
auto meanValueMap = labelStatsFilter->GetMeanValueMap();
std::unordered_map< unsigned int, itk::VariableLengthVector<double> >
meanValues;
for (const auto & mean : meanValueMap)
{
meanValues[mean.first] = mean.second;
}
// Compute the LUT from the original label image to the merged output
// label image.
auto regionMergingFilter = LabelImageSmallRegionMergingFilterType::New();
regionMergingFilter->SetInputLabelImage( labelIn );
regionMergingFilter->SetLabelPopulation( labelPopulation );
regionMergingFilter->SetLabelStatistic( meanValues );
regionMergingFilter->SetMinSize( minSize);
AddProcess(regionMergingFilter, "Computing LUT ...");
regionMergingFilter->Update();
// Relabelling using the LUT
auto changeLabelFilter = ChangeLabelImageFilterType::New();
changeLabelFilter->SetInput(labelIn);
const auto & LUT = regionMergingFilter->GetLUT();
for (auto label : LUT)
{
if (label.first != label.second)
{
changeLabelFilter->SetChange(label.first, label.second);
}
}
SetParameterOutputImage("out", changeLabelFilter->GetOutput());
RegisterPipeline();
Timer.Stop();
otbAppLogINFO( "Total elapsed time: "<< float(Timer.GetElapsedMilliseconds())/1000 <<" seconds.");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SmallRegionsMerging)
<commit_msg>STYLE : 80 char rule for timer<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbStreamingStatisticsMapFromLabelImageFilter.h"
#include "otbLabelImageSmallRegionMergingFilter.h"
#include "itkChangeLabelImageFilter.h"
#include "otbStopwatch.h"
namespace otb
{
namespace Wrapper
{
class SmallRegionsMerging : public Application
{
public:
typedef SmallRegionsMerging Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
typedef FloatVectorImageType ImageType;
typedef ImageType::InternalPixelType ImagePixelType;
typedef UInt32ImageType LabelImageType;
typedef LabelImageType::InternalPixelType LabelImagePixelType;
typedef otb::StreamingStatisticsMapFromLabelImageFilter
<ImageType, LabelImageType> StatisticsMapFromLabelImageFilterType;
typedef otb::LabelImageSmallRegionMergingFilter<LabelImageType>
LabelImageSmallRegionMergingFilterType;
typedef itk::ChangeLabelImageFilter<LabelImageType,LabelImageType>
ChangeLabelImageFilterType;
itkNewMacro(Self);
itkTypeMacro(Merging, otb::Application);
private:
ChangeLabelImageFilterType::Pointer m_ChangeLabelFilter;
void DoInit() override
{
SetName("SmallRegionsMerging");
SetDescription("This application merges small regions of a segmentation "
"result to connected region.");
SetDocName("Small Region Merging");
SetDocLongDescription("Given a segmentation result and the original image,"
" it will merge segments whose size in pixels is"
" lower than minsize parameter with the adjacent"
" segments with the adjacent segment with closest"
" radiometry and acceptable size. \n\n"
"Small segments will be processed by increasing size:"
" first all segments for which area is equal to 1"
" pixel will be merged with adjacent segments, then"
" all segments of area equal to 2 pixels will be"
" processed, until segments of area minsize.");
SetDocLimitations( "None") ;
SetDocAuthors("OTB-Team");
SetDocSeeAlso("Segmentation");
AddDocTag(Tags::Segmentation);
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription( "in", "The input image, containing initial"
" spectral signatures corresponding to the segmented image (inseg)." );
AddParameter(ParameterType_InputImage, "inseg", "Segmented image");
SetParameterDescription( "inseg", "Segmented image where each pixel value"
" is the unique integer label of the segment it belongs to." );
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription( "out", "The output image. The output image is the"
" segmented image where the minimal segments have been merged." );
SetDefaultOutputPixelType("out",ImagePixelType_uint32);
AddParameter(ParameterType_Int, "minsize", "Minimum Segment Size");
SetParameterDescription("minsize", "Minimum Segment Size. If, after the "
" segmentation, a segment is of size strictly lower than this criterion,"
" the segment is merged with the segment that has the closest sepctral"
" signature.");
SetDefaultParameterInt("minsize", 50);
SetMinimumParameterIntValue("minsize", 1);
MandatoryOff("minsize");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in","smooth.tif");
SetDocExampleParameterValue("inseg","segmentation.tif");
SetDocExampleParameterValue("out","merged.tif");
SetDocExampleParameterValue("minsize","50");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
}
void DoExecute() override
{
// Start Timer for the application
auto Timer = Stopwatch::StartNew();
unsigned int minSize = GetParameterInt("minsize");
//Acquisition of the input image dimensions
ImageType::Pointer imageIn = GetParameterImage("in");
LabelImageType::Pointer labelIn = GetParameterUInt32Image("inseg");
// Compute statistics for each segment
auto labelStatsFilter = StatisticsMapFromLabelImageFilterType::New();
labelStatsFilter->SetInput(imageIn);
labelStatsFilter->SetInputLabelImage(labelIn);
AddProcess(labelStatsFilter->GetStreamer() , "Computing stats on input"
" image ...");
labelStatsFilter->Update();
// Convert Map to Unordered map
auto labelPopulationMap = labelStatsFilter->GetLabelPopulationMap();
std::unordered_map< unsigned int,double> labelPopulation;
for (auto population : labelPopulationMap)
{
labelPopulation[population.first]=population.second;
}
auto meanValueMap = labelStatsFilter->GetMeanValueMap();
std::unordered_map< unsigned int, itk::VariableLengthVector<double> >
meanValues;
for (const auto & mean : meanValueMap)
{
meanValues[mean.first] = mean.second;
}
// Compute the LUT from the original label image to the merged output
// label image.
auto regionMergingFilter = LabelImageSmallRegionMergingFilterType::New();
regionMergingFilter->SetInputLabelImage( labelIn );
regionMergingFilter->SetLabelPopulation( labelPopulation );
regionMergingFilter->SetLabelStatistic( meanValues );
regionMergingFilter->SetMinSize( minSize);
AddProcess(regionMergingFilter, "Computing LUT ...");
regionMergingFilter->Update();
// Relabelling using the LUT
auto changeLabelFilter = ChangeLabelImageFilterType::New();
changeLabelFilter->SetInput(labelIn);
const auto & LUT = regionMergingFilter->GetLUT();
for (auto label : LUT)
{
if (label.first != label.second)
{
changeLabelFilter->SetChange(label.first, label.second);
}
}
SetParameterOutputImage("out", changeLabelFilter->GetOutput());
RegisterPipeline();
Timer.Stop();
otbAppLogINFO( "Total elapsed time: "<<
float(Timer.GetElapsedMilliseconds())/1000 <<" seconds.");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::SmallRegionsMerging)
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkSigmoidImageFilter.h"
int itkSigmoidImageFilterTest(int, char* [] )
{
// Define the dimension of the images
const unsigned int ImageDimension = 3;
// Declare the types of the images
typedef float InputPixelType;
typedef float OutputPixelType;
typedef itk::Image<InputPixelType, ImageDimension> InputImageType;
typedef itk::Image<OutputPixelType, ImageDimension> OutputImageType;
// Declare Iterator types apropriated for each image
typedef itk::ImageRegionIteratorWithIndex<
InputImageType> InputIteratorType;
typedef itk::ImageRegionIteratorWithIndex<
OutputImageType> OutputIteratorType;
// Declare the type of the index to access images
typedef itk::Index<ImageDimension> IndexType;
// Declare the type of the size
typedef itk::Size<ImageDimension> SizeType;
// Declare the type of the Region
typedef itk::ImageRegion<ImageDimension> RegionType;
// Create two images
InputImageType::Pointer inputImage = InputImageType::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImage->SetLargestPossibleRegion( region );
inputImage->SetBufferedRegion( region );
inputImage->SetRequestedRegion( region );
inputImage->Allocate();
// Create one iterator for the Input Image (this is a light object)
InputIteratorType it( inputImage, inputImage->GetBufferedRegion() );
// Initialize the content of Image A
const double value = 30;
std::cout << "Content of the Input " << std::endl;
it.GoToBegin();
while( !it.IsAtEnd() )
{
it.Set( value );
std::cout << it.Get() << std::endl;
++it;
}
// Declare the type for the Sigmoid filter
typedef itk::SigmoidImageFilter< InputImageType,
OutputImageType > FilterType;
// Create a Filter
FilterType::Pointer filter = FilterType::New();
// Connect the input images
filter->SetInput( inputImage );
// Set alpha and beta parameters
const double alpha = 2.0;
const double beta = 3.0;
filter->SetAlpha( alpha );
filter->SetBeta( beta );
const OutputPixelType maximum = 1.0;
const OutputPixelType minimum = -1.0;
filter->SetOutputMinimum( minimum );
filter->SetOutputMaximum( maximum );
// Get the Smart Pointer to the Filter Output
OutputImageType::Pointer outputImage = filter->GetOutput();
// Execute the filter
filter->Update();
filter->SetFunctor(filter->GetFunctor());
// Create an iterator for going through the image output
OutputIteratorType ot(outputImage, outputImage->GetRequestedRegion());
// Check the content of the result image
std::cout << "Verification of the output " << std::endl;
const OutputImageType::PixelType epsilon = 1e-6;
ot.GoToBegin();
it.GoToBegin();
while( !ot.IsAtEnd() )
{
const InputImageType::PixelType input = it.Get();
const OutputImageType::PixelType output = ot.Get();
const double x1 = ( input - beta ) / alpha;
const double x2 = ( maximum - minimum )*( 1.0 / ( 1.0 + std::exp( -x1 ) ) ) + minimum;
const OutputImageType::PixelType sigmoid =
static_cast<OutputImageType::PixelType>( x2 );
if( std::fabs( sigmoid - output ) > epsilon )
{
std::cerr << "Error in itkSigmoidImageFilterTest " << std::endl;
std::cerr << " simoid( " << input << ") = " << sigmoid << std::endl;
std::cerr << " differs from " << output;
std::cerr << " by more than " << epsilon << std::endl;
return EXIT_FAILURE;
}
++ot;
++it;
}
return EXIT_SUCCESS;
}
<commit_msg>ENH: Improve itkSigmoidImageFilter coverage.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkMath.h"
#include "itkSigmoidImageFilter.h"
#include "itkTestingMacros.h"
int itkSigmoidImageFilterTest( int, char* [] )
{
// Define the dimension of the images
const unsigned int ImageDimension = 3;
// Declare the types of the images
typedef float InputPixelType;
typedef float OutputPixelType;
typedef itk::Image< InputPixelType, ImageDimension > InputImageType;
typedef itk::Image< OutputPixelType, ImageDimension > OutputImageType;
// Declare appropriate Iterator types for each image
typedef itk::ImageRegionIteratorWithIndex<
InputImageType> InputIteratorType;
typedef itk::ImageRegionIteratorWithIndex<
OutputImageType> OutputIteratorType;
// Declare the type of the index to access images
typedef itk::Index< ImageDimension > IndexType;
// Declare the type of the size
typedef itk::Size< ImageDimension > SizeType;
// Declare the type of the Region
typedef itk::ImageRegion< ImageDimension > RegionType;
// Create the input images
InputImageType::Pointer inputImage = InputImageType::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize the input image
inputImage->SetLargestPossibleRegion( region );
inputImage->SetBufferedRegion( region );
inputImage->SetRequestedRegion( region );
inputImage->Allocate();
// Create one iterator for the input image (this is a light object)
InputIteratorType it( inputImage, inputImage->GetBufferedRegion() );
// Initialize the content of the input image
const double value = 30;
it.GoToBegin();
while( !it.IsAtEnd() )
{
it.Set( value );
++it;
}
// Declare the type for the Sigmoid filter
typedef itk::SigmoidImageFilter< InputImageType,
OutputImageType > FilterType;
// Create the filter
FilterType::Pointer filter = FilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( filter, SigmoidImageFilter,
UnaryFunctorImageFilter );
// Set the input image
filter->SetInput( inputImage );
// Set the filter parameters
const double alpha = 2.0;
const double beta = 3.0;
filter->SetAlpha( alpha );
TEST_SET_GET_VALUE( alpha, filter->GetAlpha() );
filter->SetBeta( beta );
TEST_SET_GET_VALUE( beta, filter->GetBeta() );
const OutputPixelType maximum = 1.0;
const OutputPixelType minimum = -1.0;
filter->SetOutputMinimum( minimum );
TEST_SET_GET_VALUE( minimum, filter->GetOutputMinimum() );
filter->SetOutputMaximum( maximum );
TEST_SET_GET_VALUE( maximum, filter->GetOutputMaximum() );
filter->SetFunctor( filter->GetFunctor() );
// Execute the filter
filter->Update();
// Get the filter output
OutputImageType::Pointer outputImage = filter->GetOutput();
// Create an iterator for going through the image output
OutputIteratorType ot( outputImage, outputImage->GetRequestedRegion() );
// Check the content of the result image
const OutputImageType::PixelType epsilon = 1e-6;
ot.GoToBegin();
it.GoToBegin();
while( !ot.IsAtEnd() )
{
const InputImageType::PixelType input = it.Get();
const OutputImageType::PixelType output = ot.Get();
const double x1 = ( input - beta ) / alpha;
const double x2 = ( maximum - minimum )*( 1.0 / ( 1.0 + std::exp( -x1 ) ) ) + minimum;
const OutputImageType::PixelType sigmoid =
static_cast<OutputImageType::PixelType>( x2 );
if( !itk::Math::FloatAlmostEqual( sigmoid, output, 10, epsilon ) )
{
std::cerr.precision( static_cast< int >( itk::Math::abs( std::log10( epsilon ) ) ) );
std::cerr << "Error in itkSigmoidImageFilterTest " << std::endl;
std::cerr << " simoid( " << input << ") = " << sigmoid << std::endl;
std::cerr << " differs from " << output;
std::cerr << " by more than " << epsilon << std::endl;
return EXIT_FAILURE;
}
++ot;
++it;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkComputeContourSetNormalsFilter.h"
#include "mitkImagePixelReadAccessor.h"
#include "mitkIOUtil.h"
mitk::ComputeContourSetNormalsFilter::ComputeContourSetNormalsFilter()
: m_SegmentationBinaryImage(NULL)
, m_MaxSpacing(5)
, m_NegativeNormalCounter(0)
, m_PositiveNormalCounter(0)
, m_UseProgressBar(false)
, m_ProgressStepSize(1)
{
mitk::Surface::Pointer output = mitk::Surface::New();
this->SetNthOutput(0, output.GetPointer());
}
mitk::ComputeContourSetNormalsFilter::~ComputeContourSetNormalsFilter()
{
}
void mitk::ComputeContourSetNormalsFilter::GenerateData()
{
unsigned int numberOfInputs = this->GetNumberOfIndexedInputs();
//Iterating over each input
for(unsigned int i = 0; i < numberOfInputs; i++)
{
//Getting the inputs polydata and polygons
Surface* currentSurface = const_cast<Surface*>( this->GetInput(i) );
vtkPolyData* polyData = currentSurface->GetVtkPolyData();
vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys();
vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints();
existingPolys->InitTraversal();
vtkIdType* cell (NULL);
vtkIdType cellSize (0);
//The array that contains all the vertex normals of the current polygon
vtkSmartPointer<vtkDoubleArray> normals = vtkSmartPointer<vtkDoubleArray>::New();
normals->SetNumberOfComponents(3);
normals->SetNumberOfTuples(polyData->GetNumberOfPoints());
//If the current contour is an inner contour then the direction is -1
//A contour lies inside another one if the pixel values in the direction of the normal is 1
m_NegativeNormalCounter = 0;
m_PositiveNormalCounter = 0;
vtkIdType offSet (0);
//Iterating over each polygon
for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);)
{
if(cellSize < 3)continue;
//First we calculate the current polygon's normal
double polygonNormal[3] = {0.0};
double p1[3];
double p2[3];
double v1[3];
double v2[3];
existingPoints->GetPoint(cell[0], p1);
unsigned int index = cellSize*0.5;
existingPoints->GetPoint(cell[index], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
for (vtkIdType k = 2; k < cellSize; k++)
{
index = cellSize*0.25;
existingPoints->GetPoint(cell[index], p1);
index = cellSize*0.75;
existingPoints->GetPoint(cell[index], p2);
v2[0] = p2[0]-p1[0];
v2[1] = p2[1]-p1[1];
v2[2] = p2[2]-p1[2];
vtkMath::Cross(v1,v2,polygonNormal);
if (vtkMath::Norm(polygonNormal) != 0)
break;
}
vtkMath::Normalize(polygonNormal);
//Now we start computing the normal for each vertex
double vertexNormalTemp[3];
existingPoints->GetPoint(cell[0], p1);
existingPoints->GetPoint(cell[1], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
vtkMath::Cross(v1,polygonNormal,vertexNormalTemp);
vtkMath::Normalize(vertexNormalTemp);
double vertexNormal[3];
for (vtkIdType j = 0; j < cellSize-2; j++)
{
existingPoints->GetPoint(cell[j+1], p1);
existingPoints->GetPoint(cell[j+2], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
vtkMath::Cross(v1,polygonNormal,vertexNormal);
vtkMath::Normalize(vertexNormal);
double finalNormal[3];
finalNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5;
finalNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5;
finalNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5;
vtkMath::Normalize(finalNormal);
//Here we determine the direction of the normal
if (m_SegmentationBinaryImage)
{
Point3D worldCoord;
worldCoord[0] = p1[0]+finalNormal[0]*m_MaxSpacing;
worldCoord[1] = p1[1]+finalNormal[1]*m_MaxSpacing;
worldCoord[2] = p1[2]+finalNormal[2]*m_MaxSpacing;
double val = 0.0;
mitk::ImagePixelReadAccessor<unsigned char> readAccess(m_SegmentationBinaryImage);
itk::Index<3> idx;
m_SegmentationBinaryImage->GetGeometry()->WorldToIndex(worldCoord, idx);
try
{
val = readAccess.GetPixelByIndexSafe(idx);
}
catch (mitk::Exception e)
{
// If value is outside the image's region ignore it
}
if (val == 0.0)
{
//MITK_INFO << "val equals zero.";
++m_PositiveNormalCounter;
}
else
{
//MITK_INFO << "val does not equal zero.";
++m_NegativeNormalCounter;
}
}
vertexNormalTemp[0] = vertexNormal[0];
vertexNormalTemp[1] = vertexNormal[1];
vertexNormalTemp[2] = vertexNormal[2];
vtkIdType id = cell[j+1];
normals->SetTuple(id,finalNormal);
}
existingPoints->GetPoint(cell[0], p1);
existingPoints->GetPoint(cell[1], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
vtkMath::Cross(v1,polygonNormal,vertexNormal);
vtkMath::Normalize(vertexNormal);
vertexNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5;
vertexNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5;
vertexNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5;
vtkMath::Normalize(vertexNormal);
vtkIdType id = cell[0];
normals->SetTuple(id,vertexNormal);
id = cell[cellSize-1];
normals->SetTuple(id,vertexNormal);
if(m_NegativeNormalCounter > m_PositiveNormalCounter)
{
for(vtkIdType n = 0; n < cellSize; n++)
{
double normal[3];
normals->GetTuple(offSet+n, normal);
normal[0] = (-1)*normal[0];
normal[1] = (-1)*normal[1];
normal[2] = (-1)*normal[2];
normals->SetTuple(offSet+n, normal);
}
}
m_NegativeNormalCounter = 0;
m_PositiveNormalCounter = 0;
offSet += cellSize;
}//end for all cells
Surface::Pointer surface = this->GetOutput(i);
surface->GetVtkPolyData()->GetCellData()->SetNormals(normals);
}//end for all inputs
//Setting progressbar
if (this->m_UseProgressBar)
mitk::ProgressBar::GetInstance()->Progress(this->m_ProgressStepSize);
}
mitk::Surface::Pointer mitk::ComputeContourSetNormalsFilter::GetNormalsAsSurface()
{
//Just for debugging:
vtkSmartPointer<vtkPolyData> newPolyData = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> newLines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New();
unsigned int idCounter (0);
//Debug end
for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); i++)
{
Surface* currentSurface = const_cast<Surface*>( this->GetOutput(i) );
vtkPolyData* polyData = currentSurface->GetVtkPolyData();
vtkSmartPointer<vtkDoubleArray> currentCellNormals = vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetNormals());
vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys();
vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints();
existingPolys->InitTraversal();
vtkIdType* cell (NULL);
vtkIdType cellSize (0);
for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);)
{
for ( vtkIdType j = 0; j < cellSize; j++ )
{
double currentNormal[3];
currentCellNormals->GetTuple(cell[j], currentNormal);
vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
line->GetPointIds()->SetNumberOfIds(2);
double newPoint[3];
double p0[3];
existingPoints->GetPoint(cell[j], p0);
newPoint[0] = p0[0] + currentNormal[0];
newPoint[1] = p0[1] + currentNormal[1];
newPoint[2] = p0[2] + currentNormal[2];
line->GetPointIds()->SetId(0, idCounter);
newPoints->InsertPoint(idCounter, p0);
idCounter++;
line->GetPointIds()->SetId(1, idCounter);
newPoints->InsertPoint(idCounter, newPoint);
idCounter++;
newLines->InsertNextCell(line);
}//end for all points
}//end for all cells
}//end for all outputs
newPolyData->SetPoints(newPoints);
newPolyData->SetLines(newLines);
newPolyData->BuildCells();
mitk::Surface::Pointer surface = mitk::Surface::New();
surface->SetVtkPolyData(newPolyData);
return surface;
}
void mitk::ComputeContourSetNormalsFilter::SetMaxSpacing(double maxSpacing)
{
m_MaxSpacing = maxSpacing;
}
void mitk::ComputeContourSetNormalsFilter::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
}
void mitk::ComputeContourSetNormalsFilter::Reset()
{
for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++)
{
this->PopBackInput();
}
this->SetNumberOfIndexedInputs(0);
this->SetNumberOfIndexedOutputs(0);
mitk::Surface::Pointer output = mitk::Surface::New();
this->SetNthOutput(0, output.GetPointer());
}
void mitk::ComputeContourSetNormalsFilter::SetUseProgressBar(bool status)
{
this->m_UseProgressBar = status;
}
void mitk::ComputeContourSetNormalsFilter::SetProgressStepSize(unsigned int stepSize)
{
this->m_ProgressStepSize = stepSize;
}
<commit_msg>Fix 3D interpolation<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkComputeContourSetNormalsFilter.h"
#include "mitkImagePixelReadAccessor.h"
#include "mitkIOUtil.h"
mitk::ComputeContourSetNormalsFilter::ComputeContourSetNormalsFilter()
: m_SegmentationBinaryImage(NULL)
, m_MaxSpacing(5)
, m_NegativeNormalCounter(0)
, m_PositiveNormalCounter(0)
, m_UseProgressBar(false)
, m_ProgressStepSize(1)
{
mitk::Surface::Pointer output = mitk::Surface::New();
this->SetNthOutput(0, output.GetPointer());
}
mitk::ComputeContourSetNormalsFilter::~ComputeContourSetNormalsFilter()
{
}
void mitk::ComputeContourSetNormalsFilter::GenerateData()
{
unsigned int numberOfInputs = this->GetNumberOfIndexedInputs();
//Iterating over each input
for(unsigned int i = 0; i < numberOfInputs; i++)
{
//Getting the inputs polydata and polygons
Surface* currentSurface = const_cast<Surface*>( this->GetInput(i) );
vtkPolyData* polyData = currentSurface->GetVtkPolyData();
vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys();
vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints();
existingPolys->InitTraversal();
vtkIdType* cell (NULL);
vtkIdType cellSize (0);
//The array that contains all the vertex normals of the current polygon
vtkSmartPointer<vtkDoubleArray> normals = vtkSmartPointer<vtkDoubleArray>::New();
normals->SetNumberOfComponents(3);
normals->SetNumberOfTuples(polyData->GetNumberOfPoints());
//If the current contour is an inner contour then the direction is -1
//A contour lies inside another one if the pixel values in the direction of the normal is 1
m_NegativeNormalCounter = 0;
m_PositiveNormalCounter = 0;
vtkIdType offSet (0);
//Iterating over each polygon
for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);)
{
if(cellSize < 3)continue;
//First we calculate the current polygon's normal
double polygonNormal[3] = {0.0};
double p1[3];
double p2[3];
double v1[3];
double v2[3];
existingPoints->GetPoint(cell[0], p1);
unsigned int index = cellSize*0.5;
existingPoints->GetPoint(cell[index], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
for (vtkIdType k = 2; k < cellSize; k++)
{
index = cellSize*0.25;
existingPoints->GetPoint(cell[index], p1);
index = cellSize*0.75;
existingPoints->GetPoint(cell[index], p2);
v2[0] = p2[0]-p1[0];
v2[1] = p2[1]-p1[1];
v2[2] = p2[2]-p1[2];
vtkMath::Cross(v1,v2,polygonNormal);
if (vtkMath::Norm(polygonNormal) != 0)
break;
}
vtkMath::Normalize(polygonNormal);
//Now we start computing the normal for each vertex
double vertexNormalTemp[3];
existingPoints->GetPoint(cell[0], p1);
existingPoints->GetPoint(cell[1], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
vtkMath::Cross(v1,polygonNormal,vertexNormalTemp);
vtkMath::Normalize(vertexNormalTemp);
double vertexNormal[3];
for (vtkIdType j = 0; j < cellSize-2; j++)
{
existingPoints->GetPoint(cell[j+1], p1);
existingPoints->GetPoint(cell[j+2], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
vtkMath::Cross(v1,polygonNormal,vertexNormal);
vtkMath::Normalize(vertexNormal);
double finalNormal[3];
finalNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5;
finalNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5;
finalNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5;
vtkMath::Normalize(finalNormal);
//Here we determine the direction of the normal
if (m_SegmentationBinaryImage)
{
Point3D worldCoord;
worldCoord[0] = p1[0]+finalNormal[0]*m_MaxSpacing;
worldCoord[1] = p1[1]+finalNormal[1]*m_MaxSpacing;
worldCoord[2] = p1[2]+finalNormal[2]*m_MaxSpacing;
double val = 0.0;
itk::Index<3> idx;
m_SegmentationBinaryImage->GetGeometry()->WorldToIndex(worldCoord, idx);
try
{
if (m_SegmentationBinaryImage->GetPixelType().GetPixelType() == itk::ImageIOBase::UCHAR)
{
mitk::ImagePixelReadAccessor<unsigned char> readAccess(m_SegmentationBinaryImage);
val = readAccess.GetPixelByIndexSafe(idx);
}
else if (m_SegmentationBinaryImage->GetPixelType().GetPixelType() == itk::ImageIOBase::USHORT)
{
mitk::ImagePixelReadAccessor<unsigned short> readAccess(m_SegmentationBinaryImage);
val = readAccess.GetPixelByIndexSafe(idx);
}
}
catch (mitk::Exception e)
{
// If value is outside the image's region ignore it
MITK_WARN<<e.what();
}
if (val == 0.0)
{
//MITK_INFO << "val equals zero.";
++m_PositiveNormalCounter;
}
else
{
//MITK_INFO << "val does not equal zero.";
++m_NegativeNormalCounter;
}
}
vertexNormalTemp[0] = vertexNormal[0];
vertexNormalTemp[1] = vertexNormal[1];
vertexNormalTemp[2] = vertexNormal[2];
vtkIdType id = cell[j+1];
normals->SetTuple(id,finalNormal);
}
existingPoints->GetPoint(cell[0], p1);
existingPoints->GetPoint(cell[1], p2);
v1[0] = p2[0]-p1[0];
v1[1] = p2[1]-p1[1];
v1[2] = p2[2]-p1[2];
vtkMath::Cross(v1,polygonNormal,vertexNormal);
vtkMath::Normalize(vertexNormal);
vertexNormal[0] = (vertexNormal[0] + vertexNormalTemp[0])*0.5;
vertexNormal[1] = (vertexNormal[1] + vertexNormalTemp[1])*0.5;
vertexNormal[2] = (vertexNormal[2] + vertexNormalTemp[2])*0.5;
vtkMath::Normalize(vertexNormal);
vtkIdType id = cell[0];
normals->SetTuple(id,vertexNormal);
id = cell[cellSize-1];
normals->SetTuple(id,vertexNormal);
if(m_NegativeNormalCounter > m_PositiveNormalCounter)
{
for(vtkIdType n = 0; n < cellSize; n++)
{
double normal[3];
normals->GetTuple(offSet+n, normal);
normal[0] = (-1)*normal[0];
normal[1] = (-1)*normal[1];
normal[2] = (-1)*normal[2];
normals->SetTuple(offSet+n, normal);
}
}
m_NegativeNormalCounter = 0;
m_PositiveNormalCounter = 0;
offSet += cellSize;
}//end for all cells
Surface::Pointer surface = this->GetOutput(i);
surface->GetVtkPolyData()->GetCellData()->SetNormals(normals);
}//end for all inputs
//Setting progressbar
if (this->m_UseProgressBar)
mitk::ProgressBar::GetInstance()->Progress(this->m_ProgressStepSize);
}
mitk::Surface::Pointer mitk::ComputeContourSetNormalsFilter::GetNormalsAsSurface()
{
//Just for debugging:
vtkSmartPointer<vtkPolyData> newPolyData = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkCellArray> newLines = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> newPoints = vtkSmartPointer<vtkPoints>::New();
unsigned int idCounter (0);
//Debug end
for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); i++)
{
Surface* currentSurface = const_cast<Surface*>( this->GetOutput(i) );
vtkPolyData* polyData = currentSurface->GetVtkPolyData();
vtkSmartPointer<vtkDoubleArray> currentCellNormals = vtkDoubleArray::SafeDownCast(polyData->GetCellData()->GetNormals());
vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys();
vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints();
existingPolys->InitTraversal();
vtkIdType* cell (NULL);
vtkIdType cellSize (0);
for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);)
{
for ( vtkIdType j = 0; j < cellSize; j++ )
{
double currentNormal[3];
currentCellNormals->GetTuple(cell[j], currentNormal);
vtkSmartPointer<vtkLine> line = vtkSmartPointer<vtkLine>::New();
line->GetPointIds()->SetNumberOfIds(2);
double newPoint[3];
double p0[3];
existingPoints->GetPoint(cell[j], p0);
newPoint[0] = p0[0] + currentNormal[0];
newPoint[1] = p0[1] + currentNormal[1];
newPoint[2] = p0[2] + currentNormal[2];
line->GetPointIds()->SetId(0, idCounter);
newPoints->InsertPoint(idCounter, p0);
idCounter++;
line->GetPointIds()->SetId(1, idCounter);
newPoints->InsertPoint(idCounter, newPoint);
idCounter++;
newLines->InsertNextCell(line);
}//end for all points
}//end for all cells
}//end for all outputs
newPolyData->SetPoints(newPoints);
newPolyData->SetLines(newLines);
newPolyData->BuildCells();
mitk::Surface::Pointer surface = mitk::Surface::New();
surface->SetVtkPolyData(newPolyData);
return surface;
}
void mitk::ComputeContourSetNormalsFilter::SetMaxSpacing(double maxSpacing)
{
m_MaxSpacing = maxSpacing;
}
void mitk::ComputeContourSetNormalsFilter::GenerateOutputInformation()
{
Superclass::GenerateOutputInformation();
}
void mitk::ComputeContourSetNormalsFilter::Reset()
{
for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++)
{
this->PopBackInput();
}
this->SetNumberOfIndexedInputs(0);
this->SetNumberOfIndexedOutputs(0);
mitk::Surface::Pointer output = mitk::Surface::New();
this->SetNthOutput(0, output.GetPointer());
}
void mitk::ComputeContourSetNormalsFilter::SetUseProgressBar(bool status)
{
this->m_UseProgressBar = status;
}
void mitk::ComputeContourSetNormalsFilter::SetProgressStepSize(unsigned int stepSize)
{
this->m_ProgressStepSize = stepSize;
}
<|endoftext|>
|
<commit_before>/**
* @file lldrawpoolwlsky.cpp
* @brief LLDrawPoolWLSky class implementation
*
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "lldrawpoolwlsky.h"
#include "llerror.h"
#include "llgl.h"
#include "pipeline.h"
#include "llviewercamera.h"
#include "llimage.h"
#include "llwlparammanager.h"
#include "llviewershadermgr.h"
#include "llglslshader.h"
#include "llsky.h"
#include "llvowlsky.h"
#include "llviewerregion.h"
#include "llface.h"
#include "llrender.h"
LLPointer<LLViewerTexture> LLDrawPoolWLSky::sCloudNoiseTexture = NULL;
LLPointer<LLImageRaw> LLDrawPoolWLSky::sCloudNoiseRawImage = NULL;
static LLGLSLShader* cloud_shader = NULL;
static LLGLSLShader* sky_shader = NULL;
LLDrawPoolWLSky::LLDrawPoolWLSky(void) :
LLDrawPool(POOL_WL_SKY)
{
const std::string cloudNoiseFilename(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight", "clouds2.tga"));
llinfos << "loading WindLight cloud noise from " << cloudNoiseFilename << llendl;
LLPointer<LLImageFormatted> cloudNoiseFile(LLImageFormatted::createFromExtension(cloudNoiseFilename));
if(cloudNoiseFile.isNull()) {
llerrs << "Error: Failed to load cloud noise image " << cloudNoiseFilename << llendl;
}
if(cloudNoiseFile->load(cloudNoiseFilename))
{
sCloudNoiseRawImage = new LLImageRaw();
if(cloudNoiseFile->decode(sCloudNoiseRawImage, 0.0f))
{
//debug use
llinfos << "cloud noise raw image width: " << sCloudNoiseRawImage->getWidth() << " : height: " << sCloudNoiseRawImage->getHeight() << " : components: " <<
(S32)sCloudNoiseRawImage->getComponents() << " : data size: " << sCloudNoiseRawImage->getDataSize() << llendl ;
llassert_always(sCloudNoiseRawImage->getData()) ;
sCloudNoiseTexture = LLViewerTextureManager::getLocalTexture(sCloudNoiseRawImage.get(), TRUE);
}
else
{
sCloudNoiseRawImage = NULL ;
}
}
LLWLParamManager::getInstance()->propagateParameters();
}
LLDrawPoolWLSky::~LLDrawPoolWLSky()
{
//llinfos << "destructing wlsky draw pool." << llendl;
sCloudNoiseTexture = NULL;
sCloudNoiseRawImage = NULL;
}
LLViewerTexture *LLDrawPoolWLSky::getDebugTexture()
{
return NULL;
}
void LLDrawPoolWLSky::beginRenderPass( S32 pass )
{
sky_shader =
LLPipeline::sUnderWaterRender ?
&gObjectSimpleWaterProgram :
&gWLSkyProgram;
cloud_shader =
LLPipeline::sUnderWaterRender ?
&gObjectSimpleWaterProgram :
&gWLCloudProgram;
}
void LLDrawPoolWLSky::endRenderPass( S32 pass )
{
}
void LLDrawPoolWLSky::beginDeferredPass(S32 pass)
{
sky_shader = &gDeferredWLSkyProgram;
cloud_shader = &gDeferredWLCloudProgram;
}
void LLDrawPoolWLSky::endDeferredPass(S32 pass)
{
}
void LLDrawPoolWLSky::renderDome(F32 camHeightLocal, LLGLSLShader * shader) const
{
LLVector3 const & origin = LLViewerCamera::getInstance()->getOrigin();
llassert_always(NULL != shader);
glPushMatrix();
//chop off translation
if (LLPipeline::sReflectionRender && origin.mV[2] > 256.f)
{
glTranslatef(origin.mV[0], origin.mV[1], 256.f-origin.mV[2]*0.5f);
}
else
{
glTranslatef(origin.mV[0], origin.mV[1], origin.mV[2]);
}
// the windlight sky dome works most conveniently in a coordinate system
// where Y is up, so permute our basis vectors accordingly.
glRotatef(120.f, 1.f / F_SQRT3, 1.f / F_SQRT3, 1.f / F_SQRT3);
glScalef(0.333f, 0.333f, 0.333f);
glTranslatef(0.f,-camHeightLocal, 0.f);
// Draw WL Sky
shader->uniform3f("camPosLocal", 0.f, camHeightLocal, 0.f);
gSky.mVOWLSkyp->drawDome();
glPopMatrix();
}
void LLDrawPoolWLSky::renderSkyHaze(F32 camHeightLocal) const
{
if (gPipeline.canUseWindLightShaders() && gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SKY))
{
LLGLDisable blend(GL_BLEND);
sky_shader->bind();
/// Render the skydome
renderDome(camHeightLocal, sky_shader);
sky_shader->unbind();
}
}
void LLDrawPoolWLSky::renderStars(void) const
{
LLGLSPipelineSkyBox gls_sky;
LLGLEnable blend(GL_BLEND);
gGL.setSceneBlendType(LLRender::BT_ALPHA);
// *NOTE: have to have bound the cloud noise texture already since register
// combiners blending below requires something to be bound
// and we might as well only bind once.
gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE);
gPipeline.disableLights();
// *NOTE: we divide by two here and GL_ALPHA_SCALE by two below to avoid
// clamping and allow the star_alpha param to brighten the stars.
bool error;
LLColor4 star_alpha(LLColor4::black);
star_alpha.mV[3] = LLWLParamManager::getInstance()->mCurParams.getFloat("star_brightness", error) / 2.f;
llassert_always(!error);
gGL.getTexUnit(0)->bind(gSky.mVOSkyp->getBloomTex());
gGL.pushMatrix();
glRotatef(gFrameTimeSeconds*0.01f, 0.f, 0.f, 1.f);
// gl_FragColor.rgb = gl_Color.rgb;
// gl_FragColor.a = gl_Color.a * star_alpha.a;
if (LLGLSLShader::sNoFixedFunction)
{
gCustomAlphaProgram.bind();
gCustomAlphaProgram.uniform1f("custom_alpha", star_alpha.mV[3]);
}
else
{
gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR);
gGL.getTexUnit(0)->setTextureAlphaBlend(LLTexUnit::TBO_MULT_X2, LLTexUnit::TBS_CONST_ALPHA, LLTexUnit::TBS_TEX_ALPHA);
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, star_alpha.mV);
}
gSky.mVOWLSkyp->drawStars();
gGL.popMatrix();
if (LLGLSLShader::sNoFixedFunction)
{
gCustomAlphaProgram.unbind();
}
else
{
// and disable the combiner states
gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
}
}
void LLDrawPoolWLSky::renderSkyClouds(F32 camHeightLocal) const
{
if (gPipeline.canUseWindLightShaders() && gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_CLOUDS) && sCloudNoiseTexture.notNull())
{
LLGLEnable blend(GL_BLEND);
gGL.setSceneBlendType(LLRender::BT_ALPHA);
gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
gGL.getTexUnit(0)->bind(sCloudNoiseTexture);
cloud_shader->bind();
/// Render the skydome
renderDome(camHeightLocal, cloud_shader);
cloud_shader->unbind();
}
}
void LLDrawPoolWLSky::renderHeavenlyBodies()
{
LLGLSPipelineSkyBox gls_skybox;
LLGLEnable blend_on(GL_BLEND);
gPipeline.disableLights();
#if 0 // when we want to re-add a texture sun disc, here's where to do it.
LLFace * face = gSky.mVOSkyp->mFace[LLVOSky::FACE_SUN];
if (gSky.mVOSkyp->getSun().getDraw() && face->getGeomCount())
{
LLViewerTexture * tex = face->getTexture();
gGL.getTexUnit(0)->bind(tex);
LLColor4 color(gSky.mVOSkyp->getSun().getInterpColor());
LLFacePool::LLOverrideFaceColor color_override(this, color);
face->renderIndexed();
}
#endif
LLFace * face = gSky.mVOSkyp->mFace[LLVOSky::FACE_MOON];
if (gSky.mVOSkyp->getMoon().getDraw() && face->getGeomCount())
{
if (gPipeline.canUseVertexShaders())
{
gUIProgram.bind();
}
// *NOTE: even though we already bound this texture above for the
// stars register combiners, we bind again here for defensive reasons,
// since LLImageGL::bind detects that it's a noop, and optimizes it out.
gGL.getTexUnit(0)->bind(face->getTexture());
LLColor4 color(gSky.mVOSkyp->getMoon().getInterpColor());
F32 a = gSky.mVOSkyp->getMoon().getDirection().mV[2];
if (a > 0.f)
{
a = a*a*4.f;
}
color.mV[3] = llclamp(a, 0.f, 1.f);
LLFacePool::LLOverrideFaceColor color_override(this, color);
face->renderIndexed();
if (gPipeline.canUseVertexShaders())
{
gUIProgram.unbind();
}
}
}
void LLDrawPoolWLSky::renderDeferred(S32 pass)
{
if (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SKY))
{
return;
}
LLFastTimer ftm(FTM_RENDER_WL_SKY);
const F32 camHeightLocal = LLWLParamManager::getInstance()->getDomeOffset() * LLWLParamManager::getInstance()->getDomeRadius();
LLGLSNoFog disableFog;
LLGLDepthTest depth(GL_TRUE, GL_FALSE);
LLGLDisable clip(GL_CLIP_PLANE0);
gGL.setColorMask(true, false);
LLGLSquashToFarClip far_clip(glh_get_current_projection());
renderSkyHaze(camHeightLocal);
LLVector3 const & origin = LLViewerCamera::getInstance()->getOrigin();
glPushMatrix();
glTranslatef(origin.mV[0], origin.mV[1], origin.mV[2]);
gDeferredStarProgram.bind();
// *NOTE: have to bind a texture here since register combiners blending in
// renderStars() requires something to be bound and we might as well only
// bind the moon's texture once.
gGL.getTexUnit(0)->bind(gSky.mVOSkyp->mFace[LLVOSky::FACE_MOON]->getTexture());
renderHeavenlyBodies();
renderStars();
gDeferredStarProgram.unbind();
glPopMatrix();
renderSkyClouds(camHeightLocal);
gGL.setColorMask(true, true);
//gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
void LLDrawPoolWLSky::render(S32 pass)
{
if (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SKY))
{
return;
}
LLFastTimer ftm(FTM_RENDER_WL_SKY);
const F32 camHeightLocal = LLWLParamManager::getInstance()->getDomeOffset() * LLWLParamManager::getInstance()->getDomeRadius();
LLGLSNoFog disableFog;
LLGLDepthTest depth(GL_TRUE, GL_FALSE);
LLGLDisable clip(GL_CLIP_PLANE0);
LLGLSquashToFarClip far_clip(glh_get_current_projection());
renderSkyHaze(camHeightLocal);
LLVector3 const & origin = LLViewerCamera::getInstance()->getOrigin();
glPushMatrix();
glTranslatef(origin.mV[0], origin.mV[1], origin.mV[2]);
// *NOTE: have to bind a texture here since register combiners blending in
// renderStars() requires something to be bound and we might as well only
// bind the moon's texture once.
gGL.getTexUnit(0)->bind(gSky.mVOSkyp->mFace[LLVOSky::FACE_MOON]->getTexture());
renderHeavenlyBodies();
renderStars();
glPopMatrix();
renderSkyClouds(camHeightLocal);
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
void LLDrawPoolWLSky::prerender()
{
//llinfos << "wlsky prerendering pass." << llendl;
}
LLDrawPoolWLSky *LLDrawPoolWLSky::instancePool()
{
return new LLDrawPoolWLSky();
}
LLViewerTexture* LLDrawPoolWLSky::getTexture()
{
return NULL;
}
void LLDrawPoolWLSky::resetDrawOrders()
{
}
//static
void LLDrawPoolWLSky::cleanupGL()
{
sCloudNoiseTexture = NULL;
}
//static
void LLDrawPoolWLSky::restoreGL()
{
if(sCloudNoiseRawImage.notNull())
{
sCloudNoiseTexture = LLViewerTextureManager::getLocalTexture(sCloudNoiseRawImage.get(), TRUE);
}
}
<commit_msg>a trivial change: use lldebugs to replace llinfos for STORM-1417.<commit_after>/**
* @file lldrawpoolwlsky.cpp
* @brief LLDrawPoolWLSky class implementation
*
* $LicenseInfo:firstyear=2007&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "lldrawpoolwlsky.h"
#include "llerror.h"
#include "llgl.h"
#include "pipeline.h"
#include "llviewercamera.h"
#include "llimage.h"
#include "llwlparammanager.h"
#include "llviewershadermgr.h"
#include "llglslshader.h"
#include "llsky.h"
#include "llvowlsky.h"
#include "llviewerregion.h"
#include "llface.h"
#include "llrender.h"
LLPointer<LLViewerTexture> LLDrawPoolWLSky::sCloudNoiseTexture = NULL;
LLPointer<LLImageRaw> LLDrawPoolWLSky::sCloudNoiseRawImage = NULL;
static LLGLSLShader* cloud_shader = NULL;
static LLGLSLShader* sky_shader = NULL;
LLDrawPoolWLSky::LLDrawPoolWLSky(void) :
LLDrawPool(POOL_WL_SKY)
{
const std::string cloudNoiseFilename(gDirUtilp->getExpandedFilename(LL_PATH_APP_SETTINGS, "windlight", "clouds2.tga"));
llinfos << "loading WindLight cloud noise from " << cloudNoiseFilename << llendl;
LLPointer<LLImageFormatted> cloudNoiseFile(LLImageFormatted::createFromExtension(cloudNoiseFilename));
if(cloudNoiseFile.isNull()) {
llerrs << "Error: Failed to load cloud noise image " << cloudNoiseFilename << llendl;
}
if(cloudNoiseFile->load(cloudNoiseFilename))
{
sCloudNoiseRawImage = new LLImageRaw();
if(cloudNoiseFile->decode(sCloudNoiseRawImage, 0.0f))
{
//debug use
lldebugs << "cloud noise raw image width: " << sCloudNoiseRawImage->getWidth() << " : height: " << sCloudNoiseRawImage->getHeight() << " : components: " <<
(S32)sCloudNoiseRawImage->getComponents() << " : data size: " << sCloudNoiseRawImage->getDataSize() << llendl ;
llassert_always(sCloudNoiseRawImage->getData()) ;
sCloudNoiseTexture = LLViewerTextureManager::getLocalTexture(sCloudNoiseRawImage.get(), TRUE);
}
else
{
sCloudNoiseRawImage = NULL ;
}
}
LLWLParamManager::getInstance()->propagateParameters();
}
LLDrawPoolWLSky::~LLDrawPoolWLSky()
{
//llinfos << "destructing wlsky draw pool." << llendl;
sCloudNoiseTexture = NULL;
sCloudNoiseRawImage = NULL;
}
LLViewerTexture *LLDrawPoolWLSky::getDebugTexture()
{
return NULL;
}
void LLDrawPoolWLSky::beginRenderPass( S32 pass )
{
sky_shader =
LLPipeline::sUnderWaterRender ?
&gObjectSimpleWaterProgram :
&gWLSkyProgram;
cloud_shader =
LLPipeline::sUnderWaterRender ?
&gObjectSimpleWaterProgram :
&gWLCloudProgram;
}
void LLDrawPoolWLSky::endRenderPass( S32 pass )
{
}
void LLDrawPoolWLSky::beginDeferredPass(S32 pass)
{
sky_shader = &gDeferredWLSkyProgram;
cloud_shader = &gDeferredWLCloudProgram;
}
void LLDrawPoolWLSky::endDeferredPass(S32 pass)
{
}
void LLDrawPoolWLSky::renderDome(F32 camHeightLocal, LLGLSLShader * shader) const
{
LLVector3 const & origin = LLViewerCamera::getInstance()->getOrigin();
llassert_always(NULL != shader);
glPushMatrix();
//chop off translation
if (LLPipeline::sReflectionRender && origin.mV[2] > 256.f)
{
glTranslatef(origin.mV[0], origin.mV[1], 256.f-origin.mV[2]*0.5f);
}
else
{
glTranslatef(origin.mV[0], origin.mV[1], origin.mV[2]);
}
// the windlight sky dome works most conveniently in a coordinate system
// where Y is up, so permute our basis vectors accordingly.
glRotatef(120.f, 1.f / F_SQRT3, 1.f / F_SQRT3, 1.f / F_SQRT3);
glScalef(0.333f, 0.333f, 0.333f);
glTranslatef(0.f,-camHeightLocal, 0.f);
// Draw WL Sky
shader->uniform3f("camPosLocal", 0.f, camHeightLocal, 0.f);
gSky.mVOWLSkyp->drawDome();
glPopMatrix();
}
void LLDrawPoolWLSky::renderSkyHaze(F32 camHeightLocal) const
{
if (gPipeline.canUseWindLightShaders() && gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SKY))
{
LLGLDisable blend(GL_BLEND);
sky_shader->bind();
/// Render the skydome
renderDome(camHeightLocal, sky_shader);
sky_shader->unbind();
}
}
void LLDrawPoolWLSky::renderStars(void) const
{
LLGLSPipelineSkyBox gls_sky;
LLGLEnable blend(GL_BLEND);
gGL.setSceneBlendType(LLRender::BT_ALPHA);
// *NOTE: have to have bound the cloud noise texture already since register
// combiners blending below requires something to be bound
// and we might as well only bind once.
gGL.getTexUnit(0)->enable(LLTexUnit::TT_TEXTURE);
gPipeline.disableLights();
// *NOTE: we divide by two here and GL_ALPHA_SCALE by two below to avoid
// clamping and allow the star_alpha param to brighten the stars.
bool error;
LLColor4 star_alpha(LLColor4::black);
star_alpha.mV[3] = LLWLParamManager::getInstance()->mCurParams.getFloat("star_brightness", error) / 2.f;
llassert_always(!error);
gGL.getTexUnit(0)->bind(gSky.mVOSkyp->getBloomTex());
gGL.pushMatrix();
glRotatef(gFrameTimeSeconds*0.01f, 0.f, 0.f, 1.f);
// gl_FragColor.rgb = gl_Color.rgb;
// gl_FragColor.a = gl_Color.a * star_alpha.a;
if (LLGLSLShader::sNoFixedFunction)
{
gCustomAlphaProgram.bind();
gCustomAlphaProgram.uniform1f("custom_alpha", star_alpha.mV[3]);
}
else
{
gGL.getTexUnit(0)->setTextureColorBlend(LLTexUnit::TBO_MULT, LLTexUnit::TBS_TEX_COLOR, LLTexUnit::TBS_VERT_COLOR);
gGL.getTexUnit(0)->setTextureAlphaBlend(LLTexUnit::TBO_MULT_X2, LLTexUnit::TBS_CONST_ALPHA, LLTexUnit::TBS_TEX_ALPHA);
glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, star_alpha.mV);
}
gSky.mVOWLSkyp->drawStars();
gGL.popMatrix();
if (LLGLSLShader::sNoFixedFunction)
{
gCustomAlphaProgram.unbind();
}
else
{
// and disable the combiner states
gGL.getTexUnit(0)->setTextureBlendType(LLTexUnit::TB_MULT);
}
}
void LLDrawPoolWLSky::renderSkyClouds(F32 camHeightLocal) const
{
if (gPipeline.canUseWindLightShaders() && gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_CLOUDS) && sCloudNoiseTexture.notNull())
{
LLGLEnable blend(GL_BLEND);
gGL.setSceneBlendType(LLRender::BT_ALPHA);
gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
gGL.getTexUnit(0)->bind(sCloudNoiseTexture);
cloud_shader->bind();
/// Render the skydome
renderDome(camHeightLocal, cloud_shader);
cloud_shader->unbind();
}
}
void LLDrawPoolWLSky::renderHeavenlyBodies()
{
LLGLSPipelineSkyBox gls_skybox;
LLGLEnable blend_on(GL_BLEND);
gPipeline.disableLights();
#if 0 // when we want to re-add a texture sun disc, here's where to do it.
LLFace * face = gSky.mVOSkyp->mFace[LLVOSky::FACE_SUN];
if (gSky.mVOSkyp->getSun().getDraw() && face->getGeomCount())
{
LLViewerTexture * tex = face->getTexture();
gGL.getTexUnit(0)->bind(tex);
LLColor4 color(gSky.mVOSkyp->getSun().getInterpColor());
LLFacePool::LLOverrideFaceColor color_override(this, color);
face->renderIndexed();
}
#endif
LLFace * face = gSky.mVOSkyp->mFace[LLVOSky::FACE_MOON];
if (gSky.mVOSkyp->getMoon().getDraw() && face->getGeomCount())
{
if (gPipeline.canUseVertexShaders())
{
gUIProgram.bind();
}
// *NOTE: even though we already bound this texture above for the
// stars register combiners, we bind again here for defensive reasons,
// since LLImageGL::bind detects that it's a noop, and optimizes it out.
gGL.getTexUnit(0)->bind(face->getTexture());
LLColor4 color(gSky.mVOSkyp->getMoon().getInterpColor());
F32 a = gSky.mVOSkyp->getMoon().getDirection().mV[2];
if (a > 0.f)
{
a = a*a*4.f;
}
color.mV[3] = llclamp(a, 0.f, 1.f);
LLFacePool::LLOverrideFaceColor color_override(this, color);
face->renderIndexed();
if (gPipeline.canUseVertexShaders())
{
gUIProgram.unbind();
}
}
}
void LLDrawPoolWLSky::renderDeferred(S32 pass)
{
if (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SKY))
{
return;
}
LLFastTimer ftm(FTM_RENDER_WL_SKY);
const F32 camHeightLocal = LLWLParamManager::getInstance()->getDomeOffset() * LLWLParamManager::getInstance()->getDomeRadius();
LLGLSNoFog disableFog;
LLGLDepthTest depth(GL_TRUE, GL_FALSE);
LLGLDisable clip(GL_CLIP_PLANE0);
gGL.setColorMask(true, false);
LLGLSquashToFarClip far_clip(glh_get_current_projection());
renderSkyHaze(camHeightLocal);
LLVector3 const & origin = LLViewerCamera::getInstance()->getOrigin();
glPushMatrix();
glTranslatef(origin.mV[0], origin.mV[1], origin.mV[2]);
gDeferredStarProgram.bind();
// *NOTE: have to bind a texture here since register combiners blending in
// renderStars() requires something to be bound and we might as well only
// bind the moon's texture once.
gGL.getTexUnit(0)->bind(gSky.mVOSkyp->mFace[LLVOSky::FACE_MOON]->getTexture());
renderHeavenlyBodies();
renderStars();
gDeferredStarProgram.unbind();
glPopMatrix();
renderSkyClouds(camHeightLocal);
gGL.setColorMask(true, true);
//gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
void LLDrawPoolWLSky::render(S32 pass)
{
if (!gPipeline.hasRenderType(LLPipeline::RENDER_TYPE_SKY))
{
return;
}
LLFastTimer ftm(FTM_RENDER_WL_SKY);
const F32 camHeightLocal = LLWLParamManager::getInstance()->getDomeOffset() * LLWLParamManager::getInstance()->getDomeRadius();
LLGLSNoFog disableFog;
LLGLDepthTest depth(GL_TRUE, GL_FALSE);
LLGLDisable clip(GL_CLIP_PLANE0);
LLGLSquashToFarClip far_clip(glh_get_current_projection());
renderSkyHaze(camHeightLocal);
LLVector3 const & origin = LLViewerCamera::getInstance()->getOrigin();
glPushMatrix();
glTranslatef(origin.mV[0], origin.mV[1], origin.mV[2]);
// *NOTE: have to bind a texture here since register combiners blending in
// renderStars() requires something to be bound and we might as well only
// bind the moon's texture once.
gGL.getTexUnit(0)->bind(gSky.mVOSkyp->mFace[LLVOSky::FACE_MOON]->getTexture());
renderHeavenlyBodies();
renderStars();
glPopMatrix();
renderSkyClouds(camHeightLocal);
gGL.getTexUnit(0)->unbind(LLTexUnit::TT_TEXTURE);
}
void LLDrawPoolWLSky::prerender()
{
//llinfos << "wlsky prerendering pass." << llendl;
}
LLDrawPoolWLSky *LLDrawPoolWLSky::instancePool()
{
return new LLDrawPoolWLSky();
}
LLViewerTexture* LLDrawPoolWLSky::getTexture()
{
return NULL;
}
void LLDrawPoolWLSky::resetDrawOrders()
{
}
//static
void LLDrawPoolWLSky::cleanupGL()
{
sCloudNoiseTexture = NULL;
}
//static
void LLDrawPoolWLSky::restoreGL()
{
if(sCloudNoiseRawImage.notNull())
{
sCloudNoiseTexture = LLViewerTextureManager::getLocalTexture(sCloudNoiseRawImage.get(), TRUE);
}
}
<|endoftext|>
|
<commit_before>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2017 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "AFCRecordMgr.h"
#include "AFRecord.h"
AFCRecordMgr::AFCRecordMgr(const AFGUID& guid)
: self(guid)
{
}
AFCRecordMgr::~AFCRecordMgr()
{
ReleaseAll();
}
const AFGUID& AFCRecordMgr::Self()
{
return self;
}
void AFCRecordMgr::ReleaseAll()
{
for(size_t i = 0; i < GetCount(); ++i)
{
delete mxRecords[i];
mxRecords[i] = NULL;
}
mxRecords.clear();
mxRecordCallbacks.clear();
}
bool AFCRecordMgr::Exist(const char* name) const
{
return mxIndices.exists(name);
}
bool AFCRecordMgr::Exist(const char* name, size_t& index) const
{
return mxIndices.GetData(name, index);
}
bool AFCRecordMgr::GetRecordData(const char* name, const int row, const int col, AFIData& value)
{
AFRecord* pRecord = GetRecord(name);
if (NULL == pRecord)
{
return NULL;
}
return pRecord->GetValue(row, col, value);
}
void AFCRecordMgr::OnEventHandler(const AFGUID& self, const RECORD_EVENT_DATA& xEventData, const AFCData& oldData, const AFCData& newData)
{
for (auto& iter : mxRecordCallbacks)
{
//TODO:check name from xEventData
(*iter)(self, xEventData, oldData, newData);
}
}
bool AFCRecordMgr::AddRecordInternal(AFRecord* record)
{
assert(record != NULL);
mxIndices.Add(record->GetName(), mxRecords.size());
mxRecords.push_back(record);
return true;
}
bool AFCRecordMgr::AddRecord(const AFGUID& self_id, const char* record_name, const AFIDataList& col_type_list, const int8_t feature)
{
ARK_ASSERT(record_name != NULL && sizeof(record_name) > 0, "record name is invalid", __FILE__, __FUNCTION__);
self = self_id;
AFRecord* pRecord = ARK_NEW AFRecord();
pRecord->SetName(record_name);
pRecord->SetColCount(col_type_list.GetCount());
for(int i = 0; i < col_type_list.GetCount(); ++i)
{
pRecord->SetColType(i, col_type_list.GetType(i));
}
pRecord->SetFeature(feature);
return AddRecordInternal(pRecord);
}
bool AFCRecordMgr::AddRecordCallback(const char* record_name, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
//TODO:
mxRecordCallbacks.push_back(cb);
return true;
}
void AFCRecordMgr::Clear()
{
ReleaseAll();
mxIndices.Clear();
}
AFRecord* AFCRecordMgr::GetRecord(const char* name)
{
size_t index;
if(!mxIndices.GetData(name, index))
{
return NULL;
}
return mxRecords[index];
}
size_t AFCRecordMgr::GetCount() const
{
return mxRecords.size();
}
AFRecord* AFCRecordMgr::GetRecordByIndex(size_t index) const
{
assert(index < GetCount());
return mxRecords[index];
}
bool AFCRecordMgr::SetRecordBool(const char* name, const int row, const int col, const bool value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetBool() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetBool(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetBool(row, col, value);
}
bool AFCRecordMgr::SetRecordInt(const char* name, const int row, const int col, const int32_t value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->SetInt(row, col, value);
}
bool AFCRecordMgr::SetRecordInt64(const char* name, const int row, const int col, const int64_t value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->SetInt64(row, col, value);
}
bool AFCRecordMgr::SetRecordFloat(const char* name, const int row, const int col, const float value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->SetFloat(row, col, value);
}
bool AFCRecordMgr::SetRecordDouble(const char* name, const int row, const int col, const double value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->SetDouble(row, col, value);
}
bool AFCRecordMgr::SetRecordString(const char* name, const int row, const int col, const char* value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->SetString(row, col, value);
}
bool AFCRecordMgr::SetRecordObject(const char* name, const int row, const int col, const AFGUID& value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->SetObject(row, col, value);
}
bool AFCRecordMgr::GetRecordBool(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->GetBool(row, col);
}
int32_t AFCRecordMgr::GetRecordInt(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_INT;
}
return record->GetInt(row, col);
}
int64_t AFCRecordMgr::GetRecordInt64(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_INT64;
}
return record->GetInt64(row, col);
}
float AFCRecordMgr::GetRecordFloat(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_FLOAT;
}
return record->GetFloat(row, col);
}
double AFCRecordMgr::GetRecordDouble(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_DOUBLE;
}
return record->GetDouble(row, col);
}
const char* AFCRecordMgr::GetRecordString(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_STR.c_str();
}
return record->GetString(row, col);
}
const AFGUID& AFCRecordMgr::GetRecordObject(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_GUID;
}
return record->GetObject(row, col);
}<commit_msg>Add record callback for other basic data type<commit_after>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2017 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "AFCRecordMgr.h"
#include "AFRecord.h"
AFCRecordMgr::AFCRecordMgr(const AFGUID& guid)
: self(guid)
{
}
AFCRecordMgr::~AFCRecordMgr()
{
ReleaseAll();
}
const AFGUID& AFCRecordMgr::Self()
{
return self;
}
void AFCRecordMgr::ReleaseAll()
{
for(size_t i = 0; i < GetCount(); ++i)
{
delete mxRecords[i];
mxRecords[i] = NULL;
}
mxRecords.clear();
mxRecordCallbacks.clear();
}
bool AFCRecordMgr::Exist(const char* name) const
{
return mxIndices.exists(name);
}
bool AFCRecordMgr::Exist(const char* name, size_t& index) const
{
return mxIndices.GetData(name, index);
}
bool AFCRecordMgr::GetRecordData(const char* name, const int row, const int col, AFIData& value)
{
AFRecord* pRecord = GetRecord(name);
if (NULL == pRecord)
{
return NULL;
}
return pRecord->GetValue(row, col, value);
}
void AFCRecordMgr::OnEventHandler(const AFGUID& self, const RECORD_EVENT_DATA& xEventData, const AFCData& oldData, const AFCData& newData)
{
for (auto& iter : mxRecordCallbacks)
{
//TODO:check name from xEventData
(*iter)(self, xEventData, oldData, newData);
}
}
bool AFCRecordMgr::AddRecordInternal(AFRecord* record)
{
assert(record != NULL);
mxIndices.Add(record->GetName(), mxRecords.size());
mxRecords.push_back(record);
return true;
}
bool AFCRecordMgr::AddRecord(const AFGUID& self_id, const char* record_name, const AFIDataList& col_type_list, const int8_t feature)
{
ARK_ASSERT(record_name != NULL && sizeof(record_name) > 0, "record name is invalid", __FILE__, __FUNCTION__);
self = self_id;
AFRecord* pRecord = ARK_NEW AFRecord();
pRecord->SetName(record_name);
pRecord->SetColCount(col_type_list.GetCount());
for(int i = 0; i < col_type_list.GetCount(); ++i)
{
pRecord->SetColType(i, col_type_list.GetType(i));
}
pRecord->SetFeature(feature);
return AddRecordInternal(pRecord);
}
bool AFCRecordMgr::AddRecordCallback(const char* record_name, const RECORD_EVENT_FUNCTOR_PTR& cb)
{
//TODO:
//record_name
mxRecordCallbacks.push_back(cb);
return true;
}
void AFCRecordMgr::Clear()
{
ReleaseAll();
mxIndices.Clear();
}
AFRecord* AFCRecordMgr::GetRecord(const char* name)
{
size_t index;
if(!mxIndices.GetData(name, index))
{
return NULL;
}
return mxRecords[index];
}
size_t AFCRecordMgr::GetCount() const
{
return mxRecords.size();
}
AFRecord* AFCRecordMgr::GetRecordByIndex(size_t index) const
{
assert(index < GetCount());
return mxRecords[index];
}
bool AFCRecordMgr::SetRecordBool(const char* name, const int row, const int col, const bool value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetBool() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetBool(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetBool(row, col, value);
}
bool AFCRecordMgr::SetRecordInt(const char* name, const int row, const int col, const int32_t value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetInt() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetInt(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetInt(row, col, value);
}
bool AFCRecordMgr::SetRecordInt64(const char* name, const int row, const int col, const int64_t value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetInt64() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetInt64(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetInt64(row, col, value);
}
bool AFCRecordMgr::SetRecordFloat(const char* name, const int row, const int col, const float value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetFloat() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetFloat(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetFloat(row, col, value);
}
bool AFCRecordMgr::SetRecordDouble(const char* name, const int row, const int col, const double value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetDouble() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetDouble(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetDouble(row, col, value);
}
bool AFCRecordMgr::SetRecordString(const char* name, const int row, const int col, const char* value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (ARK_STRICMP(oldData.GetString(), value) == 0)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetString(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetString(row, col, value);
}
bool AFCRecordMgr::SetRecordObject(const char* name, const int row, const int col, const AFGUID& value)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
//callback
do
{
AFCData oldData;
if (!GetRecordData(name, row, col, oldData))
{
ARK_ASSERT_RET_VAL(0, false);
}
if (oldData.GetObject() == value)
{
return false;
}
if (!mxRecordCallbacks.empty())
{
AFCData newData;
newData.SetObject(value);
RECORD_EVENT_DATA xRecordEventData;
xRecordEventData.nOpType = AFRecord::Update;
xRecordEventData.nRow = row;
xRecordEventData.nCol = col;
xRecordEventData.strRecordName = name;
OnEventHandler(self, xRecordEventData, oldData, newData);
}
} while (0);
return record->SetObject(row, col, value);
}
bool AFCRecordMgr::GetRecordBool(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return false;
}
return record->GetBool(row, col);
}
int32_t AFCRecordMgr::GetRecordInt(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_INT;
}
return record->GetInt(row, col);
}
int64_t AFCRecordMgr::GetRecordInt64(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_INT64;
}
return record->GetInt64(row, col);
}
float AFCRecordMgr::GetRecordFloat(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_FLOAT;
}
return record->GetFloat(row, col);
}
double AFCRecordMgr::GetRecordDouble(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_DOUBLE;
}
return record->GetDouble(row, col);
}
const char* AFCRecordMgr::GetRecordString(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_STR.c_str();
}
return record->GetString(row, col);
}
const AFGUID& AFCRecordMgr::GetRecordObject(const char* name, const int row, const int col)
{
AFRecord* record = GetRecord(name);
if(NULL == record)
{
return NULL_GUID;
}
return record->GetObject(row, col);
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSelectionSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSelectionSource.h"
#include "vtkCommand.h"
#include "vtkIdTypeArray.h"
#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTrivialProducer.h"
#include "vtkstd/vector"
#include "vtkstd/set"
vtkCxxRevisionMacro(vtkSelectionSource, "1.12");
vtkStandardNewMacro(vtkSelectionSource);
class vtkSelectionSourceInternals
{
public:
vtkSelectionSourceInternals()
{
this->Values = NULL;
}
~vtkSelectionSourceInternals()
{
if (this->Values)
{
this->Values->Delete();
}
}
typedef vtkstd::set<vtkIdType> IDSetType;
typedef vtkstd::vector<IDSetType> IDsType;
IDsType IDs;
vtkAbstractArray *Values;
};
//----------------------------------------------------------------------------
vtkSelectionSource::vtkSelectionSource()
{
this->SetNumberOfInputPorts(0);
this->Internal = new vtkSelectionSourceInternals;
this->ContentType = vtkSelection::INDICES;
this->FieldType = vtkSelection::CELL;
this->ContainingCells = 1;
this->PreserveTopology = 0;
this->Inverse = 0;
this->ExactTest = 1;
this->ShowBounds = 0;
this->ArrayName = NULL;
}
//----------------------------------------------------------------------------
vtkSelectionSource::~vtkSelectionSource()
{
delete this->Internal;
if (this->ArrayName)
{
delete[] this->ArrayName;
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllIDs()
{
this->Internal->IDs.clear();
this->Modified();
}
//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllValues()
{
if (this->Internal->Values)
{
this->Internal->Values->Reset();
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id)
{
if (this->ContentType != vtkSelection::GLOBALIDS &&
this->ContentType != vtkSelection::INDICES)
{
return;
}
// proc == -1 means all processes. All other are stored at index proc+1
proc++;
if (proc >= (vtkIdType)this->Internal->IDs.size())
{
this->Internal->IDs.resize(proc+1);
}
vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc];
idSet.insert(id);
this->Modified();
}
//----------------------------------------------------------------------------
void vtkSelectionSource::AddLocation(double x, double y, double z)
{
if (this->ContentType != vtkSelection::LOCATIONS)
{
return;
}
vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
if (da)
{
da->InsertNextTuple3(x,y,z);
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::AddThreshold(double min, double max)
{
if (this->ContentType != vtkSelection::THRESHOLDS)
{
return;
}
vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
if (da)
{
da->InsertNextValue(min);
da->InsertNextValue(max);
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::SetFrustum(double *vertices)
{
if (this->ContentType != vtkSelection::FRUSTUM)
{
return;
}
vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
if (da)
{
double *data = da->GetPointer(0);
memcpy(data, vertices, 32*sizeof(double));
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ContentType: " ;
switch (this->ContentType)
{
case vtkSelection::SELECTIONS:
os << "SELECTIONS";
break;
case vtkSelection::COMPOSITE_SELECTIONS:
os << "COMPOSITE_SELECTIONS";
break;
case vtkSelection::GLOBALIDS:
os << "GLOBALIDS";
break;
case vtkSelection::VALUES:
os << "VALUES";
break;
case vtkSelection::INDICES:
os << "INDICES";
break;
case vtkSelection::FRUSTUM:
os << "FRUSTUM";
break;
case vtkSelection::LOCATIONS:
os << "LOCATIONS";
break;
case vtkSelection::THRESHOLDS:
os << "THRESHOLDS";
break;
default:
os << "UNKNOWN";
}
os << endl;
os << indent << "FieldType: " ;
switch (this->FieldType)
{
case vtkSelection::CELL:
os << "CELL";
break;
case vtkSelection::POINT:
os << "POINT";
break;
default:
os << "UNKNOWN";
}
os << endl;
os << indent << "ContainingCells: ";
os << (this->ContainingCells?"CELLS":"POINTS") << endl;
os << indent << "PreserveTopology: " << this->PreserveTopology << endl;
os << indent << "Inverse: " << this->Inverse << endl;
os << indent << "ExactTest: " << this->ExactTest << endl;
os << indent << "ShowBounds: " << this->ShowBounds << endl;
os << indent << "ArrayName: " << (this->ArrayName?this->ArrayName:"NULL") << endl;
}
//----------------------------------------------------------------------------
int vtkSelectionSource::RequestInformation(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector)
{
// We can handle multiple piece request.
vtkInformation* info = outputVector->GetInformationObject(0);
info->Set(
vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1);
return 1;
}
//----------------------------------------------------------------------------
int vtkSelectionSource::RequestData(
vtkInformation* vtkNotUsed( request ),
vtkInformationVector** vtkNotUsed( inputVector ),
vtkInformationVector* outputVector )
{
vtkSelection* output = vtkSelection::GetData(outputVector);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
int piece = 0;
if (outInfo->Has(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))
{
piece = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
}
if (
(this->ContentType == vtkSelection::GLOBALIDS) ||
(this->ContentType == vtkSelection::INDICES))
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Number of selected items common to all pieces
vtkIdType numCommonElems = 0;
if (!this->Internal->IDs.empty())
{
numCommonElems = this->Internal->IDs[0].size();
}
if (piece+1 >= (int)this->Internal->IDs.size() &&
numCommonElems == 0)
{
vtkDebugMacro("No selection for piece: " << piece);
return 1;
}
// idx == 0 is the list for all pieces
// idx == piece+1 is the list for the current piece
size_t pids[2] = {0, piece+1};
for(int i=0; i<2; i++)
{
size_t idx = pids[i];
if (idx >= this->Internal->IDs.size())
{
continue;
}
vtkSelectionSourceInternals::IDSetType& selSet =
this->Internal->IDs[idx];
if (selSet.size() > 0)
{
// Create the selection list
vtkIdTypeArray* selectionList = vtkIdTypeArray::New();
selectionList->SetNumberOfTuples(selSet.size());
// iterate over ids and insert to the selection list
vtkSelectionSourceInternals::IDSetType::iterator iter =
selSet.begin();
for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++)
{
selectionList->SetValue(idx2, *iter);
}
output->SetSelectionList(selectionList);
selectionList->Delete();
}
}
}
if (
(this->ContentType == vtkSelection::LOCATIONS)
&&
(this->Internal->Values != 0)
)
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Create the selection list
vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
selectionList->DeepCopy(this->Internal->Values);
output->SetSelectionList(selectionList);
selectionList->Delete();
}
if (
(this->ContentType == vtkSelection::THRESHOLDS)
&&
(this->Internal->Values != 0)
)
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Create the selection list
vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
selectionList->DeepCopy(this->Internal->Values);
output->SetSelectionList(selectionList);
selectionList->Delete();
}
if (
(this->ContentType == vtkSelection::FRUSTUM)
&&
(this->Internal->Values != 0)
)
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Create the selection list
vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
selectionList->DeepCopy(this->Internal->Values);
output->SetSelectionList(selectionList);
selectionList->Delete();
}
output->GetProperties()->Set(vtkSelection::CONTAINING_CELLS(),
this->ContainingCells);
output->GetProperties()->Set(vtkSelection::PRESERVE_TOPOLOGY(),
this->PreserveTopology);
output->GetProperties()->Set(vtkSelection::INVERSE(),
this->Inverse);
output->GetProperties()->Set(vtkSelection::ARRAY_NAME(),
this->ArrayName);
output->GetProperties()->Set(vtkSelection::EXACT_TEST(),
this->ExactTest);
output->GetProperties()->Set(vtkSelection::SHOW_BOUNDS(),
this->ShowBounds);
return 1;
}
//------------------------------------------------------------------------------
void vtkSelectionSource::SetContentType(int value)
{
vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ContentType to " << value);
if (this->ContentType != value)
{
this->ContentType = value;
this->RemoveAllIDs();
this->RemoveAllValues();
if (this->Internal->Values)
{
this->Internal->Values->Delete();
}
switch (value)
{
case vtkSelection::LOCATIONS:
{
vtkDoubleArray *da = vtkDoubleArray::New();
da->SetNumberOfComponents(3);
da->SetNumberOfTuples(0);
this->Internal->Values = da;
break;
}
case vtkSelection::THRESHOLDS:
{
vtkDoubleArray *da = vtkDoubleArray::New();
da->SetNumberOfComponents(1);
da->SetNumberOfTuples(0);
this->Internal->Values = da;
break;
}
case vtkSelection::FRUSTUM:
{
vtkDoubleArray *da = vtkDoubleArray::New();
da->SetNumberOfComponents(4);
da->SetNumberOfTuples(8);
this->Internal->Values = da;
break;
}
default:
break;
}
this->Modified();
}
}
<commit_msg>BUG: Dangling pointer.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSelectionSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkSelectionSource.h"
#include "vtkCommand.h"
#include "vtkIdTypeArray.h"
#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTrivialProducer.h"
#include "vtkstd/vector"
#include "vtkstd/set"
vtkCxxRevisionMacro(vtkSelectionSource, "1.13");
vtkStandardNewMacro(vtkSelectionSource);
class vtkSelectionSourceInternals
{
public:
vtkSelectionSourceInternals()
{
this->Values = NULL;
}
~vtkSelectionSourceInternals()
{
if (this->Values)
{
this->Values->Delete();
}
}
typedef vtkstd::set<vtkIdType> IDSetType;
typedef vtkstd::vector<IDSetType> IDsType;
IDsType IDs;
vtkAbstractArray *Values;
};
//----------------------------------------------------------------------------
vtkSelectionSource::vtkSelectionSource()
{
this->SetNumberOfInputPorts(0);
this->Internal = new vtkSelectionSourceInternals;
this->ContentType = vtkSelection::INDICES;
this->FieldType = vtkSelection::CELL;
this->ContainingCells = 1;
this->PreserveTopology = 0;
this->Inverse = 0;
this->ExactTest = 1;
this->ShowBounds = 0;
this->ArrayName = NULL;
}
//----------------------------------------------------------------------------
vtkSelectionSource::~vtkSelectionSource()
{
delete this->Internal;
if (this->ArrayName)
{
delete[] this->ArrayName;
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllIDs()
{
this->Internal->IDs.clear();
this->Modified();
}
//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllValues()
{
if (this->Internal->Values)
{
this->Internal->Values->Reset();
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id)
{
if (this->ContentType != vtkSelection::GLOBALIDS &&
this->ContentType != vtkSelection::INDICES)
{
return;
}
// proc == -1 means all processes. All other are stored at index proc+1
proc++;
if (proc >= (vtkIdType)this->Internal->IDs.size())
{
this->Internal->IDs.resize(proc+1);
}
vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc];
idSet.insert(id);
this->Modified();
}
//----------------------------------------------------------------------------
void vtkSelectionSource::AddLocation(double x, double y, double z)
{
if (this->ContentType != vtkSelection::LOCATIONS)
{
return;
}
vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
if (da)
{
da->InsertNextTuple3(x,y,z);
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::AddThreshold(double min, double max)
{
if (this->ContentType != vtkSelection::THRESHOLDS)
{
return;
}
vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
if (da)
{
da->InsertNextValue(min);
da->InsertNextValue(max);
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::SetFrustum(double *vertices)
{
if (this->ContentType != vtkSelection::FRUSTUM)
{
return;
}
vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
if (da)
{
double *data = da->GetPointer(0);
memcpy(data, vertices, 32*sizeof(double));
this->Modified();
}
}
//----------------------------------------------------------------------------
void vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "ContentType: " ;
switch (this->ContentType)
{
case vtkSelection::SELECTIONS:
os << "SELECTIONS";
break;
case vtkSelection::COMPOSITE_SELECTIONS:
os << "COMPOSITE_SELECTIONS";
break;
case vtkSelection::GLOBALIDS:
os << "GLOBALIDS";
break;
case vtkSelection::VALUES:
os << "VALUES";
break;
case vtkSelection::INDICES:
os << "INDICES";
break;
case vtkSelection::FRUSTUM:
os << "FRUSTUM";
break;
case vtkSelection::LOCATIONS:
os << "LOCATIONS";
break;
case vtkSelection::THRESHOLDS:
os << "THRESHOLDS";
break;
default:
os << "UNKNOWN";
}
os << endl;
os << indent << "FieldType: " ;
switch (this->FieldType)
{
case vtkSelection::CELL:
os << "CELL";
break;
case vtkSelection::POINT:
os << "POINT";
break;
default:
os << "UNKNOWN";
}
os << endl;
os << indent << "ContainingCells: ";
os << (this->ContainingCells?"CELLS":"POINTS") << endl;
os << indent << "PreserveTopology: " << this->PreserveTopology << endl;
os << indent << "Inverse: " << this->Inverse << endl;
os << indent << "ExactTest: " << this->ExactTest << endl;
os << indent << "ShowBounds: " << this->ShowBounds << endl;
os << indent << "ArrayName: " << (this->ArrayName?this->ArrayName:"NULL") << endl;
}
//----------------------------------------------------------------------------
int vtkSelectionSource::RequestInformation(
vtkInformation* vtkNotUsed(request),
vtkInformationVector** vtkNotUsed(inputVector),
vtkInformationVector* outputVector)
{
// We can handle multiple piece request.
vtkInformation* info = outputVector->GetInformationObject(0);
info->Set(
vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1);
return 1;
}
//----------------------------------------------------------------------------
int vtkSelectionSource::RequestData(
vtkInformation* vtkNotUsed( request ),
vtkInformationVector** vtkNotUsed( inputVector ),
vtkInformationVector* outputVector )
{
vtkSelection* output = vtkSelection::GetData(outputVector);
vtkInformation* outInfo = outputVector->GetInformationObject(0);
int piece = 0;
if (outInfo->Has(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))
{
piece = outInfo->Get(
vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
}
if (
(this->ContentType == vtkSelection::GLOBALIDS) ||
(this->ContentType == vtkSelection::INDICES))
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Number of selected items common to all pieces
vtkIdType numCommonElems = 0;
if (!this->Internal->IDs.empty())
{
numCommonElems = this->Internal->IDs[0].size();
}
if (piece+1 >= (int)this->Internal->IDs.size() &&
numCommonElems == 0)
{
vtkDebugMacro("No selection for piece: " << piece);
return 1;
}
// idx == 0 is the list for all pieces
// idx == piece+1 is the list for the current piece
size_t pids[2] = {0, piece+1};
for(int i=0; i<2; i++)
{
size_t idx = pids[i];
if (idx >= this->Internal->IDs.size())
{
continue;
}
vtkSelectionSourceInternals::IDSetType& selSet =
this->Internal->IDs[idx];
if (selSet.size() > 0)
{
// Create the selection list
vtkIdTypeArray* selectionList = vtkIdTypeArray::New();
selectionList->SetNumberOfTuples(selSet.size());
// iterate over ids and insert to the selection list
vtkSelectionSourceInternals::IDSetType::iterator iter =
selSet.begin();
for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++)
{
selectionList->SetValue(idx2, *iter);
}
output->SetSelectionList(selectionList);
selectionList->Delete();
}
}
}
if (
(this->ContentType == vtkSelection::LOCATIONS)
&&
(this->Internal->Values != 0)
)
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Create the selection list
vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
selectionList->DeepCopy(this->Internal->Values);
output->SetSelectionList(selectionList);
selectionList->Delete();
}
if (
(this->ContentType == vtkSelection::THRESHOLDS)
&&
(this->Internal->Values != 0)
)
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Create the selection list
vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
selectionList->DeepCopy(this->Internal->Values);
output->SetSelectionList(selectionList);
selectionList->Delete();
}
if (
(this->ContentType == vtkSelection::FRUSTUM)
&&
(this->Internal->Values != 0)
)
{
output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
this->ContentType);
output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
this->FieldType);
// Create the selection list
vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
selectionList->DeepCopy(this->Internal->Values);
output->SetSelectionList(selectionList);
selectionList->Delete();
}
output->GetProperties()->Set(vtkSelection::CONTAINING_CELLS(),
this->ContainingCells);
output->GetProperties()->Set(vtkSelection::PRESERVE_TOPOLOGY(),
this->PreserveTopology);
output->GetProperties()->Set(vtkSelection::INVERSE(),
this->Inverse);
output->GetProperties()->Set(vtkSelection::ARRAY_NAME(),
this->ArrayName);
output->GetProperties()->Set(vtkSelection::EXACT_TEST(),
this->ExactTest);
output->GetProperties()->Set(vtkSelection::SHOW_BOUNDS(),
this->ShowBounds);
return 1;
}
//------------------------------------------------------------------------------
void vtkSelectionSource::SetContentType(int value)
{
vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ContentType to " << value);
if (this->ContentType != value)
{
this->ContentType = value;
this->RemoveAllIDs();
this->RemoveAllValues();
if (this->Internal->Values)
{
this->Internal->Values->Delete();
this->Internal->Values=0;
}
switch (value)
{
case vtkSelection::LOCATIONS:
{
vtkDoubleArray *da = vtkDoubleArray::New();
da->SetNumberOfComponents(3);
da->SetNumberOfTuples(0);
this->Internal->Values = da;
break;
}
case vtkSelection::THRESHOLDS:
{
vtkDoubleArray *da = vtkDoubleArray::New();
da->SetNumberOfComponents(1);
da->SetNumberOfTuples(0);
this->Internal->Values = da;
break;
}
case vtkSelection::FRUSTUM:
{
vtkDoubleArray *da = vtkDoubleArray::New();
da->SetNumberOfComponents(4);
da->SetNumberOfTuples(8);
this->Internal->Values = da;
break;
}
default:
break;
}
this->Modified();
}
}
<|endoftext|>
|
<commit_before>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TEST_FILENAME "Testfile2"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
using namespace std;
bool gremlin(Packet * pack, int corruptProb, int lossProb);
bool init(int argc, char** argv);
bool loadFile();
bool sendFile();
bool getFile();
char * recvPkt();
bool isvpack(unsigned char * p);
Packet createPacket(int index);
bool sendPacket();
bool isAck();
void handleAck();
void handleNak(int& x);
int seqNum;
int s;
int probCorrupt;
int probLoss;
string hs;
short int port;
char * file;
unsigned char* window[16]; //packet window
int windowBase; //used to determine position in window of arriving packets
int length;
struct sockaddr_in a;
struct sockaddr_in sa;
socklen_t salen;
string fstr;
bool dropPck;
Packet p;
int delayT;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
getFile();
return 0;
}
bool init(int argc, char** argv) {
windowBase = 0; //initialize windowBase
s = 0;
hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */
port = 10038; /* Can be any port within 10038-10041, inclusive. */
char* delayTStr = argv[2];
delayT = boost::lexical_cast<int>(delayTStr);
/*if(!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0?
a.sin_port = htons(0);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){
cout << "Socket binding failed. (socket s, address a)" << endl;
return false;
}
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr));
cout << endl;
cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl;
cout << "Port: " << ntohs(sa.sin_port) << endl;
cout << endl << endl;
/*fstr = string(file);
cout << "File: " << endl << fstr << endl << endl;*/
seqNum = 0;
dropPck = false;
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= length / BUFSIZE; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(index * BUFSIZE + BUFSIZE > length) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss;
if((dropPck = gremlin(&p, pc, pl)) == false){
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
} else return false;
}
bool isAck() {
recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen);
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool gremlin(Packet * pack, int corruptProb, int lossProb){
bool dropPacket = false;
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
if(r <= (lossProb)){
dropPacket = true;
cout << "Dropped!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return dropPacket;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[6];
memcpy(css, &p[1], 6);
css[5] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[7], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == seqNum) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
int rlen;
int ack;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen);
/* Begin Window Loading */
int tempSeqNum = boost::lexical_cast<int>(packet[0]);
int properIndex = tempSeqNum - windowBase;
window[properIndex] = packet;
cout << "Packet loaded into window" << endl;
char* tempTest = new char[6];
memcpy(tempTest, &window[1], 0);
tempTest[5] = '\0';
cout << "The Checksum pulled from client window: " << tempTest[0] << endl;
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * sns = new char[3];
memcpy(sns, &packet[0], 3);
sns[2] = '\0';
char * css = new char[6];
memcpy(css, &packet[2], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << packet[0] << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
if(isvpack(packet)) {
if(boost::lexical_cast<int>(sns) == windowBase) windowBase++; //increment base of window //FIXME
file << dataPull;
file.flush();
}
cout << "Sent response: ";
cout << "ACK " << windowBase << endl;
if(packet[6] == '1') usleep(delayT*1000);
string wbs = to_string((long long)windowBase);
const char * ackval = wbs.c_str();
if(sendto(s, ackval, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
<commit_msg>Fix testing statement<commit_after>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include "packet.h"
#define BUFSIZE 121
#define FILENAME "Testfile"
#define TEST_FILENAME "Testfile2"
#define PORT 10038
#define PAKSIZE 128
#define ACK 0
#define NAK 1
using namespace std;
bool gremlin(Packet * pack, int corruptProb, int lossProb);
bool init(int argc, char** argv);
bool loadFile();
bool sendFile();
bool getFile();
char * recvPkt();
bool isvpack(unsigned char * p);
Packet createPacket(int index);
bool sendPacket();
bool isAck();
void handleAck();
void handleNak(int& x);
int seqNum;
int s;
int probCorrupt;
int probLoss;
string hs;
short int port;
char * file;
unsigned char* window[16]; //packet window
int windowBase; //used to determine position in window of arriving packets
int length;
struct sockaddr_in a;
struct sockaddr_in sa;
socklen_t salen;
string fstr;
bool dropPck;
Packet p;
int delayT;
unsigned char b[BUFSIZE];
int main(int argc, char** argv) {
if(!init(argc, argv)) return -1;
if(sendto(s, "GET Testfile", BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
getFile();
return 0;
}
bool init(int argc, char** argv) {
windowBase = 0; //initialize windowBase
s = 0;
hs = string("131.204.14.") + argv[1]; /* Needs to be updated? Might be a string like "tux175.engr.auburn.edu." */
port = 10038; /* Can be any port within 10038-10041, inclusive. */
char* delayTStr = argv[2];
delayT = boost::lexical_cast<int>(delayTStr);
/*if(!loadFile()) {
cout << "Loading file failed. (filename FILENAME)" << endl;
return false;
}*/
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
cout << "Socket creation failed. (socket s)" << endl;
return false;
}
memset((char *)&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = htonl(INADDR_ANY); //why does this always give us 0?
a.sin_port = htons(0);
if (bind(s, (struct sockaddr *)&a, sizeof(a)) < 0){
cout << "Socket binding failed. (socket s, address a)" << endl;
return false;
}
memset((char *)&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
inet_pton(AF_INET, hs.c_str(), &(sa.sin_addr));
cout << endl;
cout << "Server address (inet mode): " << inet_ntoa(sa.sin_addr) << endl;
cout << "Port: " << ntohs(sa.sin_port) << endl;
cout << endl << endl;
/*fstr = string(file);
cout << "File: " << endl << fstr << endl << endl;*/
seqNum = 0;
dropPck = false;
return true;
}
bool loadFile() {
ifstream is (FILENAME, ifstream::binary);
if(is) {
is.seekg(0, is.end);
length = is.tellg();
is.seekg(0, is.beg);
file = new char[length];
cout << "Reading " << length << " characters..." << endl;
is.read(file, length);
if(!is) { cout << "File reading failed. (filename " << FILENAME << "). Only " << is.gcount() << " could be read."; return false; }
is.close();
}
return true;
}
bool sendFile() {
for(int x = 0; x <= length / BUFSIZE; x++) {
p = createPacket(x);
if(!sendPacket()) continue;
if(isAck()) {
handleAck();
} else {
handleNak(x);
}
memset(b, 0, BUFSIZE);
}
return true;
}
Packet createPacket(int index){
cout << endl;
cout << "=== TRANSMISSION START" << endl;
string mstr = fstr.substr(index * BUFSIZE, BUFSIZE);
if(index * BUFSIZE + BUFSIZE > length) {
mstr[length - (index * BUFSIZE)] = '\0';
}
return Packet (seqNum, mstr.c_str());
}
bool sendPacket(){
int pc = probCorrupt; int pl = probLoss;
if((dropPck = gremlin(&p, pc, pl)) == false){
if(sendto(s, p.str(), BUFSIZE + 7, 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
cout << "Package sending failed. (socket s, server address sa, message m)" << endl;
return false;
}
return true;
} else return false;
}
bool isAck() {
recvfrom(s, b, BUFSIZE + 7, 0, (struct sockaddr *)&sa, &salen);
cout << endl << "=== SERVER RESPONSE TEST" << endl;
cout << "Data: " << b << endl;
if(b[6] == '0') return true;
else return false;
}
void handleAck() {
}
void handleNak(int& x) {
char * sns = new char[2];
memcpy(sns, &b[0], 1);
sns[1] = '\0';
char * css = new char[5];
memcpy(css, &b[1], 5);
char * db = new char[BUFSIZE + 1];
memcpy(db, &b[2], BUFSIZE);
db[BUFSIZE] = '\0';
cout << "Sequence number: " << sns << endl;
cout << "Checksum: " << css << endl;
Packet pk (0, db);
pk.setSequenceNum(boost::lexical_cast<int>(sns));
pk.setCheckSum(boost::lexical_cast<int>(css));
if(!pk.chksm()) x--;
else x = (x - 2 > 0) ? x - 2 : 0;
}
bool gremlin(Packet * pack, int corruptProb, int lossProb){
bool dropPacket = false;
int r = rand() % 100;
cout << "Corruption probability: " << corruptProb << endl;
cout << "Random number: " << r << endl;
if(r <= (lossProb)){
dropPacket = true;
cout << "Dropped!" << endl;
}
else if(r <= (corruptProb)){
cout << "Corrupted!" << endl;
pack->loadDataBuffer((char*)"GREMLIN LOL");
}
else seqNum = (seqNum) ? false : true;
cout << "Seq. num: " << pack->getSequenceNum() << endl;
cout << "Checksum: " << pack->getCheckSum() << endl;
cout << "Message: " << pack->getDataBuffer() << endl;
return dropPacket;
}
bool isvpack(unsigned char * p) {
cout << endl << "=== IS VALID PACKET TESTING" << endl;
char * sns = new char[2];
memcpy(sns, &p[0], 1);
sns[1] = '\0';
char * css = new char[6];
memcpy(css, &p[1], 6);
css[5] = '\0';
char * db = new char[121 + 1];
memcpy(db, &p[7], 121);
db[121] = '\0';
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Message: " << db << endl;
int sn = boost::lexical_cast<int>(sns);
int cs = boost::lexical_cast<int>(css);
Packet pk (0, db);
pk.setSequenceNum(sn);
// change to validate based on checksum and sequence number
if(sn == seqNum) return false;
if(cs != pk.generateCheckSum()) return false;
return true;
}
bool getFile(){
/* Loop forever, waiting for messages from a client. */
cout << "Waiting on port " << PORT << "..." << endl;
ofstream file("Dumpfile");
int rlen;
int ack;
for (;;) {
unsigned char packet[PAKSIZE + 1];
unsigned char dataPull[PAKSIZE - 7 + 1];
rlen = recvfrom(s, packet, PAKSIZE, 0, (struct sockaddr *)&sa, &salen);
/* Begin Window Loading */
int tempSeqNum = boost::lexical_cast<int>(packet[0]);
int properIndex = tempSeqNum - windowBase;
window[properIndex] = packet;
cout << "Packet loaded into window" << endl;
char* tempTest = new char[6];
memcpy(tempTest, &window[1], 0);
tempTest[5] = '\0';
cout << "The Checksum pulled from client window: " << tempTest[0] << endl;
for(int x = 0; x < PAKSIZE - 7; x++) {
dataPull[x] = packet[x + 7];
}
dataPull[PAKSIZE - 7] = '\0';
packet[PAKSIZE] = '\0';
if (rlen > 0) {
char * sns = new char[3];
memcpy(sns, &packet[0], 3);
sns[2] = '\0';
char * css = new char[6];
memcpy(css, &packet[2], 5);
css[5] = '\0';
cout << endl << endl << "=== RECEIPT" << endl;
cout << "Seq. num: " << sns << endl;
cout << "Checksum: " << css << endl;
cout << "Received message: " << dataPull << endl;
if(isvpack(packet)) {
if(boost::lexical_cast<int>(sns) == windowBase) windowBase++; //increment base of window //FIXME
file << dataPull;
file.flush();
}
cout << "Sent response: ";
cout << "ACK " << windowBase << endl;
if(packet[6] == '1') usleep(delayT*1000);
string wbs = to_string((long long)windowBase);
const char * ackval = wbs.c_str();
if(sendto(s, ackval, PAKSIZE, 0, (struct sockaddr *)&sa, salen) < 0) {
cout << "Acknowledgement failed. (socket s, acknowledgement message ack, client address ca, client address length calen)" << endl;
return 0;
}
delete css;
}
}
file.close();
return true;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageWeightedSum.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageWeightedSum.h"
#include "vtkObjectFactory.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkImageIterator.h"
#include "vtkImageProgressIterator.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkImageWeightedSum, "1.3");
vtkStandardNewMacro(vtkImageWeightedSum);
vtkCxxSetObjectMacro(vtkImageWeightedSum,Weights,vtkDoubleArray);
//----------------------------------------------------------------------------
// Description:
// Constructor sets default values
vtkImageWeightedSum::vtkImageWeightedSum()
{
this->SetNumberOfInputPorts(1);
// array of weights: need as many weights as inputs
this->Weights = vtkDoubleArray::New();
// By default normalize
this->NormalizeByWeight = 1;
}
//----------------------------------------------------------------------------
vtkImageWeightedSum::~vtkImageWeightedSum()
{
this->Weights->Delete();
}
//----------------------------------------------------------------------------
void vtkImageWeightedSum::SetWeight(vtkIdType id, double weight)
{
// Reallocate if needed:
this->Weights->SetNumberOfTuples(id+1);
// Pass the new weight
this->Weights->SetValue(id, weight);
}
//----------------------------------------------------------------------------
double vtkImageWeightedSum::CalculateTotalWeight()
{
double totalWeight = 0.0;
for(int i = 0; i < this->Weights->GetNumberOfTuples(); ++i)
{
totalWeight += this->Weights->GetValue(i);
}
return totalWeight;
}
//----------------------------------------------------------------------------
// Description:
// This templated function executes the filter for any type of data.
template <class T>
void vtkImageWeightedSumExecute(vtkImageWeightedSum *self,
vtkImageData **inDatas, int numInputs, vtkImageData *outData,
int outExt[6], int id, T*)
{
const int fastpath = 256;
vtkImageIterator<T> inItsFast[fastpath];
T* inSIFast[fastpath];
vtkImageProgressIterator<T> outIt(outData, outExt, self, id);
double *weights = ((vtkDoubleArray *)self->GetWeights())->GetPointer(0);
double totalWeight = self->CalculateTotalWeight();
int normalize = self->GetNormalizeByWeight();
vtkImageIterator<T> *inIts;
T* *inSI;
if( numInputs < fastpath )
{
inIts = inItsFast;
inSI = inSIFast;
}
else
{
inIts = new vtkImageIterator<T>[numInputs];
inSI = new T*[numInputs];
}
// Loop through all input ImageData to initialize iterators
for(int i=0; i < numInputs; ++i)
{
inIts[i].Initialize(inDatas[i], outExt);
}
// Loop through ouput pixels
while (!outIt.IsAtEnd())
{
for(int j=0; j < numInputs; ++j)
{
inSI[j] = inIts[j].BeginSpan();
}
T* outSI = outIt.BeginSpan();
T* outSIEnd = outIt.EndSpan();
// Pixel operation
while (outSI != outSIEnd)
{
double sum = 0.;
for(int k=0; k < numInputs; ++k)
{
sum += weights[k] * *inSI[k];
}
// Divide only if needed and different from 0
if (normalize && totalWeight != 0.0)
{
sum /= totalWeight;
}
*outSI = static_cast<T>(sum); // do the cast only at the end
outSI++;
for(int l=0; l < numInputs; ++l)
{
inSI[l]++;
}
}
for(int j=0; j < numInputs; ++j)
{
inIts[j].NextSpan();
}
outIt.NextSpan();
}
if( numInputs >= fastpath )
{
delete[] inIts;
delete[] inSI;
}
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the datas data types.
void vtkImageWeightedSum::ThreadedRequestData (
vtkInformation * vtkNotUsed( request ),
vtkInformationVector** vtkNotUsed( inputVector ),
vtkInformationVector * vtkNotUsed( outputVector ),
vtkImageData ***inData,
vtkImageData **outData,
int outExt[6], int id)
{
if (inData[0][0] == NULL)
{
vtkErrorMacro(<< "Input " << 0 << " must be specified.");
return;
}
// this filter expects that input is the same type as output.
if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, "
<< inData[0][0]->GetScalarType()
<< ", must match out ScalarType "
<< outData[0]->GetScalarType());
return;
}
int numInputs = this->GetNumberOfInputConnections(0);
int numWeights = this->Weights->GetNumberOfTuples();
if( numWeights != numInputs )
{
vtkErrorMacro( << "Execute: There are " << numInputs << " vtkImageData provided"
<< " but only " << numWeights << " number of weights provided" );
return;
}
switch (inData[0][0]->GetScalarType())
{
vtkTemplateMacro(
vtkImageWeightedSumExecute(this , inData[0], numInputs,
outData[0], outExt, id, static_cast<VTK_TT *>(0))
);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
//----------------------------------------------------------------------------
int vtkImageWeightedSum::FillInputPortInformation(int i, vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
return this->Superclass::FillInputPortInformation(i,info);
}
//----------------------------------------------------------------------------
void vtkImageWeightedSum::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
// objects
os << indent << "NormalizeByWeight: " <<
(this->NormalizeByWeight ? "On" : "Off" ) << "\n";
os << indent << "Weights: " << this->Weights << "\n";
this->Weights->PrintSelf(os,indent.GetNextIndent());
}
<commit_msg>BUG: Need to properly reallocate the double array<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageWeightedSum.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkImageWeightedSum.h"
#include "vtkObjectFactory.h"
#include "vtkDoubleArray.h"
#include "vtkImageData.h"
#include "vtkImageIterator.h"
#include "vtkImageProgressIterator.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkStreamingDemandDrivenPipeline.h"
vtkCxxRevisionMacro(vtkImageWeightedSum, "1.4");
vtkStandardNewMacro(vtkImageWeightedSum);
vtkCxxSetObjectMacro(vtkImageWeightedSum,Weights,vtkDoubleArray);
//----------------------------------------------------------------------------
// Description:
// Constructor sets default values
vtkImageWeightedSum::vtkImageWeightedSum()
{
this->SetNumberOfInputPorts(1);
// array of weights: need as many weights as inputs
this->Weights = vtkDoubleArray::New();
// By default normalize
this->NormalizeByWeight = 1;
}
//----------------------------------------------------------------------------
vtkImageWeightedSum::~vtkImageWeightedSum()
{
this->Weights->Delete();
}
//----------------------------------------------------------------------------
void vtkImageWeightedSum::SetWeight(vtkIdType id, double weight)
{
// Reallocate if needed and pass the new weight
this->Weights->InsertValue(id, weight);
}
//----------------------------------------------------------------------------
double vtkImageWeightedSum::CalculateTotalWeight()
{
double totalWeight = 0.0;
for(int i = 0; i < this->Weights->GetNumberOfTuples(); ++i)
{
totalWeight += this->Weights->GetValue(i);
}
return totalWeight;
}
//----------------------------------------------------------------------------
// Description:
// This templated function executes the filter for any type of data.
template <class T>
void vtkImageWeightedSumExecute(vtkImageWeightedSum *self,
vtkImageData **inDatas, int numInputs, vtkImageData *outData,
int outExt[6], int id, T*)
{
const int fastpath = 256;
vtkImageIterator<T> inItsFast[fastpath];
T* inSIFast[fastpath];
vtkImageProgressIterator<T> outIt(outData, outExt, self, id);
double *weights = ((vtkDoubleArray *)self->GetWeights())->GetPointer(0);
double totalWeight = self->CalculateTotalWeight();
int normalize = self->GetNormalizeByWeight();
vtkImageIterator<T> *inIts;
T* *inSI;
if( numInputs < fastpath )
{
inIts = inItsFast;
inSI = inSIFast;
}
else
{
inIts = new vtkImageIterator<T>[numInputs];
inSI = new T*[numInputs];
}
// Loop through all input ImageData to initialize iterators
for(int i=0; i < numInputs; ++i)
{
inIts[i].Initialize(inDatas[i], outExt);
}
// Loop through ouput pixels
while (!outIt.IsAtEnd())
{
for(int j=0; j < numInputs; ++j)
{
inSI[j] = inIts[j].BeginSpan();
}
T* outSI = outIt.BeginSpan();
T* outSIEnd = outIt.EndSpan();
// Pixel operation
while (outSI != outSIEnd)
{
double sum = 0.;
for(int k=0; k < numInputs; ++k)
{
sum += weights[k] * *inSI[k];
}
// Divide only if needed and different from 0
if (normalize && totalWeight != 0.0)
{
sum /= totalWeight;
}
*outSI = static_cast<T>(sum); // do the cast only at the end
outSI++;
for(int l=0; l < numInputs; ++l)
{
inSI[l]++;
}
}
for(int j=0; j < numInputs; ++j)
{
inIts[j].NextSpan();
}
outIt.NextSpan();
}
if( numInputs >= fastpath )
{
delete[] inIts;
delete[] inSI;
}
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the datas data types.
void vtkImageWeightedSum::ThreadedRequestData (
vtkInformation * vtkNotUsed( request ),
vtkInformationVector** vtkNotUsed( inputVector ),
vtkInformationVector * vtkNotUsed( outputVector ),
vtkImageData ***inData,
vtkImageData **outData,
int outExt[6], int id)
{
if (inData[0][0] == NULL)
{
vtkErrorMacro(<< "Input " << 0 << " must be specified.");
return;
}
// this filter expects that input is the same type as output.
if (inData[0][0]->GetScalarType() != outData[0]->GetScalarType())
{
vtkErrorMacro(<< "Execute: input ScalarType, "
<< inData[0][0]->GetScalarType()
<< ", must match out ScalarType "
<< outData[0]->GetScalarType());
return;
}
int numInputs = this->GetNumberOfInputConnections(0);
int numWeights = this->Weights->GetNumberOfTuples();
if( numWeights != numInputs )
{
vtkErrorMacro( << "Execute: There are " << numInputs << " vtkImageData provided"
<< " but only " << numWeights << " number of weights provided" );
return;
}
switch (inData[0][0]->GetScalarType())
{
vtkTemplateMacro(
vtkImageWeightedSumExecute(this , inData[0], numInputs,
outData[0], outExt, id, static_cast<VTK_TT *>(0))
);
default:
vtkErrorMacro(<< "Execute: Unknown ScalarType");
return;
}
}
//----------------------------------------------------------------------------
int vtkImageWeightedSum::FillInputPortInformation(int i, vtkInformation* info)
{
info->Set(vtkAlgorithm::INPUT_IS_REPEATABLE(), 1);
return this->Superclass::FillInputPortInformation(i,info);
}
//----------------------------------------------------------------------------
void vtkImageWeightedSum::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
// objects
os << indent << "NormalizeByWeight: " <<
(this->NormalizeByWeight ? "On" : "Off" ) << "\n";
os << indent << "Weights: " << this->Weights << "\n";
this->Weights->PrintSelf(os,indent.GetNextIndent());
}
<|endoftext|>
|
<commit_before>#include "Effect.h"
#include "main.h"
#include <QFile>
Effect::Effect(RenderContext *context)
: VideoNode(context),
m_fboIndex(0),
m_intensity(0),
m_previous(0),
m_blankPreviewFbo(0) {
}
void Effect::initialize() {
QSize size = uiSettings->previewSize();
delete m_displayPreviewFbo;
m_displayPreviewFbo = new QOpenGLFramebufferObject(size);
delete m_renderPreviewFbo;
m_renderPreviewFbo = new QOpenGLFramebufferObject(size);
delete m_blankPreviewFbo;
m_blankPreviewFbo = new QOpenGLFramebufferObject(size);
}
void Effect::paint() {
QSize size = uiSettings->previewSize();
glClearColor(0, 0, 0, 0);
glViewport(0, 0, size.width(), size.height());
glDisable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_BLEND);
QOpenGLFramebufferObject *previousPreviewFbo;
VideoNode *prev = previous();
if(prev == 0) {
resizeFbo(&m_blankPreviewFbo, size);
m_blankPreviewFbo->bind();
glClear(GL_COLOR_BUFFER_BIT);
previousPreviewFbo = m_blankPreviewFbo;
} else {
previousPreviewFbo = prev->m_previewFbo;
}
m_programLock.lock();
if(m_programs.count() > 0) {
float values[] = {
-1, -1,
1, -1,
-1, 1,
1, 1
};
if(m_regeneratePreviewFbos) {
foreach(QOpenGLFramebufferObject *f, m_previewFbos)
delete f;
m_previewFbos.clear();
for(int i = 0; i < m_programs.count() + 1; i++) {
m_previewFbos.append(new QOpenGLFramebufferObject(size));
m_fboIndex = 0;
}
m_regeneratePreviewFbos = false;
}
for(int i = m_programs.count() - 1; i >= 0; i--) {
resizeFbo(&m_previewFbos[(m_fboIndex + 1) % m_previewFbos.count()], size);
auto target = m_previewFbos.at((m_fboIndex + 1) % m_previewFbos.count());
auto p = m_programs.at(i);
p->bind();
target->bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, previousPreviewFbo->texture());
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_previewFbos.at(m_fboIndex)->texture());
p->setAttributeArray(0, GL_FLOAT, values, 2);
float intense = intensity();
p->setUniformValue("iIntensity", intense);
p->setUniformValue("iFrame", 0);
p->setUniformValue("iChannelP", 1);
p->enableAttributeArray(0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
p->disableAttributeArray(0);
p->release();
}
m_fboIndex = (m_fboIndex + 1) % m_previewFbos.count();
QOpenGLFramebufferObject::bindDefault();
m_previewFbo = m_previewFbos.at(m_fboIndex);
} else {
m_previewFbo = previousPreviewFbo;
}
m_programLock.unlock();
blitToRenderFbo();
}
Effect::~Effect() {
beforeDestruction();
foreach(QOpenGLShaderProgram *p, m_programs) delete p;
foreach(QOpenGLFramebufferObject *fbo, m_previewFbos) delete fbo;
m_programs.clear();
m_previewFbos.clear();
m_previewFbo = 0; // This points to one of m_previewFbos
}
QSet<VideoNode*> Effect::dependencies()
{
QSet<VideoNode*> d;
if(auto p = previous())
d.insert(p);
return d;
}
// Call this to load shader code into this Effect.
// This function is thread-safe, avoid calling this in the render thread.
// A current OpenGL context is required.
// Returns true if the program was loaded successfully
bool Effect::loadProgram(QString name) {
QString filename = QString("../resources/effects/%1.glsl").arg(name);
QFile file(filename);
if(!file.open(QIODevice::ReadOnly)) {
qDebug() << QString("Could not open \"%1\"").arg(filename);
return false;
}
QTextStream s1(&file);
QString s = s1.readAll();
auto program = new QOpenGLShaderProgram();
program->addShaderFromSourceCode(QOpenGLShader::Vertex,
"attribute highp vec4 vertices;"
"varying highp vec2 coords;"
"void main() {"
" gl_Position = vertices;"
" coords = vertices.xy;"
"}");
program->addShaderFromSourceCode(QOpenGLShader::Fragment, s);
program->bindAttributeLocation("vertices", 0);
program->link();
m_programLock.lock();
foreach(QOpenGLShaderProgram *p, m_programs) delete p;
m_programs.clear();
m_programs.append(program);
m_regeneratePreviewFbos = true;
m_programLock.unlock();
return true;
}
qreal Effect::intensity() {
QMutexLocker locker(&m_intensityLock);
return m_intensity;
}
VideoNode *Effect::previous() {
QMutexLocker locker(&m_previousLock);
return m_previous;
}
void Effect::setIntensity(qreal value) {
{
if(value > 1) value = 1;
if(value < 0) value = 0;
QMutexLocker locker(&m_intensityLock);
if(m_intensity == value)
return;
m_intensity = value;
}
emit intensityChanged(value);
}
void Effect::setPrevious(VideoNode *value) {
// TODO take context lock??
{
QMutexLocker locker(&m_context->m_contextLock);
QMutexLocker locker(&m_previousLock);
m_previous = value;
}
}
<commit_msg>i'm dumb sometimes. v_v ( dedupe local variables. )<commit_after>#include "Effect.h"
#include "main.h"
#include <QFile>
Effect::Effect(RenderContext *context)
: VideoNode(context),
m_fboIndex(0),
m_intensity(0),
m_previous(0),
m_blankPreviewFbo(0) {
}
void Effect::initialize() {
QSize size = uiSettings->previewSize();
delete m_displayPreviewFbo;
m_displayPreviewFbo = new QOpenGLFramebufferObject(size);
delete m_renderPreviewFbo;
m_renderPreviewFbo = new QOpenGLFramebufferObject(size);
delete m_blankPreviewFbo;
m_blankPreviewFbo = new QOpenGLFramebufferObject(size);
}
void Effect::paint() {
QSize size = uiSettings->previewSize();
glClearColor(0, 0, 0, 0);
glViewport(0, 0, size.width(), size.height());
glDisable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_BLEND);
QOpenGLFramebufferObject *previousPreviewFbo;
VideoNode *prev = previous();
if(prev == 0) {
resizeFbo(&m_blankPreviewFbo, size);
m_blankPreviewFbo->bind();
glClear(GL_COLOR_BUFFER_BIT);
previousPreviewFbo = m_blankPreviewFbo;
} else {
previousPreviewFbo = prev->m_previewFbo;
}
m_programLock.lock();
if(m_programs.count() > 0) {
float values[] = {
-1, -1,
1, -1,
-1, 1,
1, 1
};
if(m_regeneratePreviewFbos) {
foreach(QOpenGLFramebufferObject *f, m_previewFbos)
delete f;
m_previewFbos.clear();
for(int i = 0; i < m_programs.count() + 1; i++) {
m_previewFbos.append(new QOpenGLFramebufferObject(size));
m_fboIndex = 0;
}
m_regeneratePreviewFbos = false;
}
for(int i = m_programs.count() - 1; i >= 0; i--) {
resizeFbo(&m_previewFbos[(m_fboIndex + 1) % m_previewFbos.count()], size);
auto target = m_previewFbos.at((m_fboIndex + 1) % m_previewFbos.count());
auto p = m_programs.at(i);
p->bind();
target->bind();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, previousPreviewFbo->texture());
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, m_previewFbos.at(m_fboIndex)->texture());
p->setAttributeArray(0, GL_FLOAT, values, 2);
float intense = intensity();
p->setUniformValue("iIntensity", intense);
p->setUniformValue("iFrame", 0);
p->setUniformValue("iChannelP", 1);
p->enableAttributeArray(0);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
p->disableAttributeArray(0);
p->release();
}
m_fboIndex = (m_fboIndex + 1) % m_previewFbos.count();
QOpenGLFramebufferObject::bindDefault();
m_previewFbo = m_previewFbos.at(m_fboIndex);
} else {
m_previewFbo = previousPreviewFbo;
}
m_programLock.unlock();
blitToRenderFbo();
}
Effect::~Effect() {
beforeDestruction();
foreach(QOpenGLShaderProgram *p, m_programs) delete p;
foreach(QOpenGLFramebufferObject *fbo, m_previewFbos) delete fbo;
m_programs.clear();
m_previewFbos.clear();
m_previewFbo = 0; // This points to one of m_previewFbos
}
QSet<VideoNode*> Effect::dependencies()
{
QSet<VideoNode*> d;
if(auto p = previous())
d.insert(p);
return d;
}
// Call this to load shader code into this Effect.
// This function is thread-safe, avoid calling this in the render thread.
// A current OpenGL context is required.
// Returns true if the program was loaded successfully
bool Effect::loadProgram(QString name) {
QString filename = QString("../resources/effects/%1.glsl").arg(name);
QFile file(filename);
if(!file.open(QIODevice::ReadOnly)) {
qDebug() << QString("Could not open \"%1\"").arg(filename);
return false;
}
QTextStream s1(&file);
QString s = s1.readAll();
auto program = new QOpenGLShaderProgram();
program->addShaderFromSourceCode(QOpenGLShader::Vertex,
"attribute highp vec4 vertices;"
"varying highp vec2 coords;"
"void main() {"
" gl_Position = vertices;"
" coords = vertices.xy;"
"}");
program->addShaderFromSourceCode(QOpenGLShader::Fragment, s);
program->bindAttributeLocation("vertices", 0);
program->link();
m_programLock.lock();
foreach(QOpenGLShaderProgram *p, m_programs) delete p;
m_programs.clear();
m_programs.append(program);
m_regeneratePreviewFbos = true;
m_programLock.unlock();
return true;
}
qreal Effect::intensity() {
QMutexLocker locker(&m_intensityLock);
return m_intensity;
}
VideoNode *Effect::previous() {
QMutexLocker locker(&m_previousLock);
return m_previous;
}
void Effect::setIntensity(qreal value) {
{
if(value > 1) value = 1;
if(value < 0) value = 0;
QMutexLocker locker(&m_intensityLock);
if(m_intensity == value)
return;
m_intensity = value;
}
emit intensityChanged(value);
}
void Effect::setPrevious(VideoNode *value) {
// TODO take context lock??
{
QMutexLocker clocker(&m_context->m_contextLock);
QMutexLocker plocker(&m_previousLock);
m_previous = value;
}
}
<|endoftext|>
|
<commit_before>/*
ofxTableGestures (formerly OF-TangibleFramework)
Developed for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2011 Daniel Gallardo Grassot <daniel.gallardo@upf.edu>
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 "Figure.h"
#include "CollisionHelper.h"
namespace Figures
{
Figure::Figure():has_texture(false)
{
bbox.Reset();
matrix.SetIdentity();
}
Figure::~Figure()
{
//dtor
}
void Figure::SetTexture(const std::string & path)
{
if (path.compare("") == 0)
{
has_texture = false;
return;
}
if(!texture.loadImage(path))
{
has_texture = false;
return;
}
has_texture = true;
}
void Figure::SetTexture(ofImage& image)
{
if(image.getHeight() == 0)
{
has_texture = false;
return;
}
texture = image;
has_texture = true;
}
void Figure::Draw()
{
glGetDoublev(GL_MODELVIEW_MATRIX,matrix.data);
if(CollisionHelper::debug_graphics)
{
bbox.Draw();
ofNoFill();
ofSetLineWidth(1.0f);
}
Design();
if(CollisionHelper::debug_graphics)
ofFill();
}
void Figure::DrawStroke()
{
glGetDoublev(GL_MODELVIEW_MATRIX,matrix.data);
DesignStroke();
if(CollisionHelper::debug_graphics)
bbox.Draw();
}
bool Figure::Collide(ofPoint const & point)
{
ofPoint target = (CollisionHelper::ignore_transformation_matrix*matrix).TransformInverse(point);
//std::cout << (CollisionHelper::ignore_transformation_matrix*matrix).ToString() << std::endl;
//if(bbox.Collide(target.x,target.y) && CheckCollision(target))return true;
//std::cout << target.x << " " << target.y << " -- " << point.x << " " << point.y << std::endl;
if(bbox.Collide(target.x,target.y))
if(CheckCollision(target))
return true;
return false;
}
ofPoint Figure::GetCentre()
{
ofPoint center;
/*center.x = 0;
center.y = 0;
center.z = 0;*/
GetCentre(center.x,center.y);
return matrix.Transform(center);
}
void Figure::GetCentre(float & x, float & y)
{
ofPoint center;
center.x = 0;
center.y = 0;
center.z = 0;
matrix.Transform(center);
x = center.x;
y = center.y;
}
Matrix & Figure::getMatrix()
{
return matrix;
}
}
<commit_msg>inverted textures for of 0.8.0<commit_after>/*
ofxTableGestures (formerly OF-TangibleFramework)
Developed for Taller de Sistemes Interactius I
Universitat Pompeu Fabra
Copyright (c) 2011 Daniel Gallardo Grassot <daniel.gallardo@upf.edu>
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 "Figure.h"
#include "CollisionHelper.h"
namespace Figures
{
Figure::Figure():has_texture(false)
{
bbox.Reset();
matrix.SetIdentity();
}
Figure::~Figure()
{
//dtor
}
void Figure::SetTexture(const std::string & path)
{
if (path.compare("") == 0)
{
has_texture = false;
return;
}
if(!texture.loadImage(path))
{
has_texture = false;
return;
}
texture.rotate90(2);
has_texture = true;
}
void Figure::SetTexture(ofImage& image)
{
if(image.getHeight() == 0)
{
has_texture = false;
return;
}
texture = image;
has_texture = true;
}
void Figure::Draw()
{
glGetDoublev(GL_MODELVIEW_MATRIX,matrix.data);
if(CollisionHelper::debug_graphics)
{
bbox.Draw();
ofNoFill();
ofSetLineWidth(1.0f);
}
Design();
if(CollisionHelper::debug_graphics)
ofFill();
}
void Figure::DrawStroke()
{
glGetDoublev(GL_MODELVIEW_MATRIX,matrix.data);
DesignStroke();
if(CollisionHelper::debug_graphics)
bbox.Draw();
}
bool Figure::Collide(ofPoint const & point)
{
ofPoint target = (CollisionHelper::ignore_transformation_matrix*matrix).TransformInverse(point);
//std::cout << (CollisionHelper::ignore_transformation_matrix*matrix).ToString() << std::endl;
//if(bbox.Collide(target.x,target.y) && CheckCollision(target))return true;
//std::cout << target.x << " " << target.y << " -- " << point.x << " " << point.y << std::endl;
if(bbox.Collide(target.x,target.y))
if(CheckCollision(target))
return true;
return false;
}
ofPoint Figure::GetCentre()
{
ofPoint center;
/*center.x = 0;
center.y = 0;
center.z = 0;*/
GetCentre(center.x,center.y);
return matrix.Transform(center);
}
void Figure::GetCentre(float & x, float & y)
{
ofPoint center;
center.x = 0;
center.y = 0;
center.z = 0;
matrix.Transform(center);
x = center.x;
y = center.y;
}
Matrix & Figure::getMatrix()
{
return matrix;
}
}
<|endoftext|>
|
<commit_before>#include "Folder.h"
#include "File.h"
#include "database/SqliteTools.h"
#include "filesystem/IDirectory.h"
namespace policy
{
const std::string FolderTable::Name = "Folder";
const std::string FolderTable::CacheColumn = "path";
unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id;
const FolderCache::KeyType&FolderCache::key(const std::shared_ptr<Folder>& self)
{
return self->path();
}
FolderCache::KeyType FolderCache::key( sqlite3_stmt* stmt )
{
return sqlite::Traits<FolderCache::KeyType>::Load( stmt, 1 );
}
}
Folder::Folder( DBConnection dbConnection, sqlite3_stmt* stmt )
: m_dbConection( dbConnection )
{
m_id = sqlite::Traits<unsigned int>::Load( stmt, 0 );
m_path = sqlite::Traits<std::string>::Load( stmt, 1 );
m_parent = sqlite::Traits<unsigned int>::Load( stmt, 2 );
m_lastModificationDate = sqlite::Traits<unsigned int>::Load( stmt, 3 );
m_isRemovable = sqlite::Traits<bool>::Load( stmt, 4 );
}
Folder::Folder( const std::string& path, time_t lastModificationDate, bool isRemovable, unsigned int parent )
: m_path( path )
, m_parent( parent )
, m_lastModificationDate( lastModificationDate )
, m_isRemovable( isRemovable )
{
}
bool Folder::createTable(DBConnection connection)
{
std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name +
"("
"id_folder INTEGER PRIMARY KEY AUTOINCREMENT,"
"path TEXT UNIQUE ON CONFLICT FAIL,"
"id_parent UNSIGNED INTEGER,"
"last_modification_date UNSIGNED INTEGER,"
"is_removable INTEGER,"
"FOREIGN KEY (id_parent) REFERENCES " + policy::FolderTable::Name +
"(id_folder) ON DELETE CASCADE"
")";
return sqlite::Tools::executeRequest( connection, req );
}
FolderPtr Folder::create( DBConnection connection, const std::string& path, time_t lastModificationDate, bool isRemovable, unsigned int parentId )
{
auto self = std::make_shared<Folder>( path, lastModificationDate, isRemovable, parentId );
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, id_parent, last_modification_date, is_removable) VALUES(?, ?, ?, ?)";
if ( _Cache::insert( connection, self, req, path, sqlite::ForeignKey( parentId ),
lastModificationDate, isRemovable ) == false )
return nullptr;
self->m_dbConection = connection;
return self;
}
unsigned int Folder::id() const
{
return m_id;
}
const std::string& Folder::path()
{
return m_path;
}
std::vector<FilePtr> Folder::files()
{
static const std::string req = "SELECT * FROM " + policy::FileTable::Name +
" WHERE folder_id = ?";
return sqlite::Tools::fetchAll<File, IFile>( m_dbConection, req, m_id );
}
std::vector<FolderPtr> Folder::folders()
{
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name +
" WHERE id_parent = ?";
return sqlite::Tools::fetchAll<Folder, IFolder>( m_dbConection, req, m_id );
}
FolderPtr Folder::parent()
{
//FIXME: use path to be able to fetch from cache?
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name +
" WHERE id_folder = ?";
return sqlite::Tools::fetchOne<Folder>( m_dbConection, req, m_parent );
}
unsigned int Folder::lastModificationDate()
{
return m_lastModificationDate;
}
bool Folder::setLastModificationDate( unsigned int lastModificationDate )
{
static const std::string req = "UPDATE " + policy::FolderTable::Name +
" SET last_modification_date = ? WHERE id_folder = ?";
if ( sqlite::Tools::executeUpdate( m_dbConection, req, lastModificationDate, m_id ) == false )
return false;
m_lastModificationDate = lastModificationDate;
return true;
}
bool Folder::isRemovable()
{
return m_isRemovable;
}
<commit_msg>Folder: Add missing initialization<commit_after>#include "Folder.h"
#include "File.h"
#include "database/SqliteTools.h"
#include "filesystem/IDirectory.h"
namespace policy
{
const std::string FolderTable::Name = "Folder";
const std::string FolderTable::CacheColumn = "path";
unsigned int Folder::* const FolderTable::PrimaryKey = &Folder::m_id;
const FolderCache::KeyType&FolderCache::key(const std::shared_ptr<Folder>& self)
{
return self->path();
}
FolderCache::KeyType FolderCache::key( sqlite3_stmt* stmt )
{
return sqlite::Traits<FolderCache::KeyType>::Load( stmt, 1 );
}
}
Folder::Folder( DBConnection dbConnection, sqlite3_stmt* stmt )
: m_dbConection( dbConnection )
{
m_id = sqlite::Traits<unsigned int>::Load( stmt, 0 );
m_path = sqlite::Traits<std::string>::Load( stmt, 1 );
m_parent = sqlite::Traits<unsigned int>::Load( stmt, 2 );
m_lastModificationDate = sqlite::Traits<unsigned int>::Load( stmt, 3 );
m_isRemovable = sqlite::Traits<bool>::Load( stmt, 4 );
}
Folder::Folder( const std::string& path, time_t lastModificationDate, bool isRemovable, unsigned int parent )
: m_id( 0 )
, m_path( path )
, m_parent( parent )
, m_lastModificationDate( lastModificationDate )
, m_isRemovable( isRemovable )
{
}
bool Folder::createTable(DBConnection connection)
{
std::string req = "CREATE TABLE IF NOT EXISTS " + policy::FolderTable::Name +
"("
"id_folder INTEGER PRIMARY KEY AUTOINCREMENT,"
"path TEXT UNIQUE ON CONFLICT FAIL,"
"id_parent UNSIGNED INTEGER,"
"last_modification_date UNSIGNED INTEGER,"
"is_removable INTEGER,"
"FOREIGN KEY (id_parent) REFERENCES " + policy::FolderTable::Name +
"(id_folder) ON DELETE CASCADE"
")";
return sqlite::Tools::executeRequest( connection, req );
}
FolderPtr Folder::create( DBConnection connection, const std::string& path, time_t lastModificationDate, bool isRemovable, unsigned int parentId )
{
auto self = std::make_shared<Folder>( path, lastModificationDate, isRemovable, parentId );
static const std::string req = "INSERT INTO " + policy::FolderTable::Name +
"(path, id_parent, last_modification_date, is_removable) VALUES(?, ?, ?, ?)";
if ( _Cache::insert( connection, self, req, path, sqlite::ForeignKey( parentId ),
lastModificationDate, isRemovable ) == false )
return nullptr;
self->m_dbConection = connection;
return self;
}
unsigned int Folder::id() const
{
return m_id;
}
const std::string& Folder::path()
{
return m_path;
}
std::vector<FilePtr> Folder::files()
{
static const std::string req = "SELECT * FROM " + policy::FileTable::Name +
" WHERE folder_id = ?";
return sqlite::Tools::fetchAll<File, IFile>( m_dbConection, req, m_id );
}
std::vector<FolderPtr> Folder::folders()
{
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name +
" WHERE id_parent = ?";
return sqlite::Tools::fetchAll<Folder, IFolder>( m_dbConection, req, m_id );
}
FolderPtr Folder::parent()
{
//FIXME: use path to be able to fetch from cache?
static const std::string req = "SELECT * FROM " + policy::FolderTable::Name +
" WHERE id_folder = ?";
return sqlite::Tools::fetchOne<Folder>( m_dbConection, req, m_parent );
}
unsigned int Folder::lastModificationDate()
{
return m_lastModificationDate;
}
bool Folder::setLastModificationDate( unsigned int lastModificationDate )
{
static const std::string req = "UPDATE " + policy::FolderTable::Name +
" SET last_modification_date = ? WHERE id_folder = ?";
if ( sqlite::Tools::executeUpdate( m_dbConection, req, lastModificationDate, m_id ) == false )
return false;
m_lastModificationDate = lastModificationDate;
return true;
}
bool Folder::isRemovable()
{
return m_isRemovable;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $
Version: $Revision: 21975 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "QmitkFiberBundleDeveloperView.h"
#include <QmitkStdMultiWidget.h>
// Qt
// VTK
#include <vtkPointSource.h>
#include <vtkPolyLine.h>
#include <vtkCellArray.h>
const std::string QmitkFiberBundleDeveloperView::VIEW_ID = "org.mitk.views.fiberbundledeveloper";
const std::string id_DataManager = "org.mitk.views.datamanager";
using namespace berry;
QmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView()
: QmitkFunctionality()
, m_Controls( 0 )
, m_MultiWidget( NULL )
{
}
// Destructor
QmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView()
{
}
void QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent )
{
// build up qt view, unless already done in QtDesigner, etc.
if ( !m_Controls )
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls;
m_Controls->setupUi( parent );
connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) );
connect( m_Controls->radioButton_directionRandom, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
connect( m_Controls->radioButton_directionX, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
connect( m_Controls->radioButton_directionY, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
connect( m_Controls->radioButton_directionZ, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
}
// Checkpoint for fiber ORIENTATION
if ( m_DirectionRadios.empty() )
{
m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom);
m_DirectionRadios.insert(1, m_Controls->radioButton_directionX);
m_DirectionRadios.insert(2, m_Controls->radioButton_directionY);
m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ);
}
}
void QmitkFiberBundleDeveloperView::DoUpdateGenerateFibersWidget()
{
MITK_INFO << "DO_UPDATE_GENERATE_FIBERS_WIDGET :-) ";
//get selected radioButton
QString fibDirection; //stores the object_name of selected radiobutton
QVector<QRadioButton*>::const_iterator i;
for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i)
{
QRadioButton* rdbtn = *i;
if (rdbtn->isChecked())
fibDirection = rdbtn->objectName();
}
if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) {
// disable radiobuttons
if (m_Controls->boxFiberMinLength->isEnabled())
m_Controls->boxFiberMinLength->setEnabled(false);
if (m_Controls->labelFiberMinLength->isEnabled())
m_Controls->labelFiberMinLength->setEnabled(false);
if (m_Controls->boxFiberMaxLength->isEnabled())
m_Controls->boxFiberMaxLength->setEnabled(false);
if (m_Controls->labelFiberMaxLength->isEnabled())
m_Controls->labelFiberMaxLength->setEnabled(false);
//enable radiobuttons
if (!m_Controls->labelFibersTotal->isEnabled())
m_Controls->labelFibersTotal->setEnabled(true);
if (!m_Controls->boxFiberNumbers->isEnabled())
m_Controls->boxFiberNumbers->setEnabled(true);
if (!m_Controls->labelDistrRadius->isEnabled())
m_Controls->labelDistrRadius->setEnabled(true);
if (!m_Controls->boxDistributionRadius->isEnabled())
m_Controls->boxDistributionRadius->setEnabled(true);
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_X ) {
// disable radiobuttons
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Y ) {
// disable radiobuttons
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Z ) {
// disable radiobuttons
}
}
void QmitkFiberBundleDeveloperView::DoGenerateFibers()
{
// GET SELECTED FIBER DIRECTION
QString fibDirection; //stores the object_name of selected radiobutton
QVector<QRadioButton*>::const_iterator i;
for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i)
{
QRadioButton* rdbtn = *i;
if (rdbtn->isChecked())
fibDirection = rdbtn->objectName();
}
vtkSmartPointer<vtkPolyData> output; // FiberPD stores the generated PolyData
if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) {
// build polydata with random lines and fibers
output = GenerateVtkFibersRandom();
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_X ) {
// build polydata with XDirection fibers
output = GenerateVtkFibersDirectionX();
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Y ) {
// build polydata with YDirection fibers
output = GenerateVtkFibersDirectionY();
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Z ) {
// build polydata with ZDirection fibers
output = GenerateVtkFibersDirectionZ();
}
//mitkFiberBundleX::New()
//write to dataStorage
}
/*
* Generate polydata of random fibers
*/
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersRandom()
{
int numOfFibers = m_Controls->boxFiberNumbers->value();
int distrRadius = m_Controls->boxDistributionRadius->value();
int numOfPoints = numOfFibers * distrRadius;
std::vector< std::vector<int> > fiberStorage;
for (int i=0; i<numOfFibers; ++i) {
std::vector<int> a;
fiberStorage.push_back( a );
}
//get number of items in fiberStorage
MITK_INFO << "Fibers in fiberstorage: " << fiberStorage.size();
for (unsigned long i=0; i<fiberStorage.size(); ++i)
{
//add dummy points to storageentries
fiberStorage.at(i).push_back(222);
fiberStorage.at(i).push_back((int)i);
}
for (unsigned long i=0; i<fiberStorage.size(); ++i)
{
std::vector<int> singleFiber = fiberStorage.at(i);
MITK_INFO << "====FIBER_" << i << "_=====";
for (unsigned long si=0; si<singleFiber.size(); ++si) {
MITK_INFO << singleFiber.at(si);
}
}
vtkSmartPointer<vtkPointSource> randomPoints = vtkSmartPointer<vtkPointSource>::New();
randomPoints->SetCenter(0.0, 0.0, 0.0);
randomPoints->SetNumberOfPoints(numOfPoints);
randomPoints->SetRadius(distrRadius);
randomPoints->Update();
vtkPolyData* pntHost = randomPoints->GetOutput();
vtkPoints* pnts = pntHost->GetPoints();
//===================================
//checkpoint if requested amount of points equals generated amount
if (numOfPoints != pnts->GetNumberOfPoints()) {
MITK_INFO << "VTK POINT ERROR, WRONG AMOUNT OF GENRERATED POINTS";
return 0;
}// =================================
// Set Fibers
vtkSmartPointer<vtkCellArray> linesCell = vtkSmartPointer<vtkCellArray>::New();
// iterate through points
vtkSmartPointer<vtkPolyData> PDRandom = vtkSmartPointer<vtkPolyData>::New();
PDRandom->SetPoints(pnts);
PDRandom->SetLines(linesCell);
return PDRandom;
}
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionX()
{
int numOfFibers = m_Controls->boxFiberNumbers->value();
vtkSmartPointer<vtkCellArray> linesCell = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
//insert Origin point, this point has index 0 in point array
double originX = 0.0;
double originY = 0.0;
double originZ = 0.0;
//after each iteration the origin of the new fiber increases
//here you set which direction is affected.
double increaseX = 0.0;
double increaseY = 1.0;
double increaseZ = 0.0;
//walk along X axis
//length of fibers increases in each iteration
for (int i=0; i<numOfFibers; ++i) {
vtkSmartPointer<vtkPolyLine> newFiber = vtkSmartPointer<vtkPolyLine>::New();
newFiber->GetPointIds()->SetNumberOfIds(i+2);
//create starting point and add it to pointset
points->InsertNextPoint(originX + (double)i * increaseX , originY + (double)i * increaseY, originZ + (double)i * increaseZ);
//add starting point to fiber
newFiber->GetPointIds()->SetId(0,points->GetNumberOfPoints()-1);
//insert remaining points for fiber
for (int pj=0; pj<=i ; ++pj)
{ //generate next point on X axis
points->InsertNextPoint( originX + (double)pj+1 , originY + (double)i * increaseY, originZ + (double)i * increaseZ );
newFiber->GetPointIds()->SetId(pj+1,points->GetNumberOfPoints()-1);
}
linesCell->InsertNextCell(newFiber);
}
vtkSmartPointer<vtkPolyData> PDX = vtkSmartPointer<vtkPolyData>::New();
PDX->SetPoints(points);
PDX->SetLines(linesCell);
return PDX;
}
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionY()
{
vtkSmartPointer<vtkPolyData> PDY = vtkSmartPointer<vtkPolyData>::New();
//todo
return PDY;
}
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionZ()
{
vtkSmartPointer<vtkPolyData> PDZ = vtkSmartPointer<vtkPolyData>::New();
//todo
return PDZ;
}
void QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
m_MultiWidget = &stdMultiWidget;
}
void QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable()
{
m_MultiWidget = NULL;
}
/* OnSelectionChanged is registered to SelectionService, therefore no need to
implement SelectionService Listener explicitly */
void QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes )
{
}
void QmitkFiberBundleDeveloperView::Activated()
{
MITK_INFO << "FB OPerations ACTIVATED()";
}
<commit_msg>gui element logic [cOK]<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $
Version: $Revision: 21975 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>
// Qmitk
#include "QmitkFiberBundleDeveloperView.h"
#include <QmitkStdMultiWidget.h>
// Qt
// VTK
#include <vtkPointSource.h>
#include <vtkPolyLine.h>
#include <vtkCellArray.h>
const std::string QmitkFiberBundleDeveloperView::VIEW_ID = "org.mitk.views.fiberbundledeveloper";
const std::string id_DataManager = "org.mitk.views.datamanager";
using namespace berry;
QmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView()
: QmitkFunctionality()
, m_Controls( 0 )
, m_MultiWidget( NULL )
{
}
// Destructor
QmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView()
{
}
void QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent )
{
// build up qt view, unless already done in QtDesigner, etc.
if ( !m_Controls )
{
// create GUI widgets from the Qt Designer's .ui file
m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls;
m_Controls->setupUi( parent );
connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) );
connect( m_Controls->radioButton_directionRandom, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
connect( m_Controls->radioButton_directionX, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
connect( m_Controls->radioButton_directionY, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
connect( m_Controls->radioButton_directionZ, SIGNAL(clicked()), this, SLOT(DoUpdateGenerateFibersWidget()) );
}
// Checkpoint for fiber ORIENTATION
if ( m_DirectionRadios.empty() )
{
m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom);
m_DirectionRadios.insert(1, m_Controls->radioButton_directionX);
m_DirectionRadios.insert(2, m_Controls->radioButton_directionY);
m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ);
}
// set GUI elements of FiberGenerator to according configuration
DoUpdateGenerateFibersWidget();
}
void QmitkFiberBundleDeveloperView::DoUpdateGenerateFibersWidget()
{
//get selected radioButton
QString fibDirection; //stores the object_name of selected radiobutton
QVector<QRadioButton*>::const_iterator i;
for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i)
{
QRadioButton* rdbtn = *i;
if (rdbtn->isChecked())
fibDirection = rdbtn->objectName();
}
if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) {
// disable radiobuttons
if (m_Controls->boxFiberMinLength->isEnabled())
m_Controls->boxFiberMinLength->setEnabled(false);
if (m_Controls->labelFiberMinLength->isEnabled())
m_Controls->labelFiberMinLength->setEnabled(false);
if (m_Controls->boxFiberMaxLength->isEnabled())
m_Controls->boxFiberMaxLength->setEnabled(false);
if (m_Controls->labelFiberMaxLength->isEnabled())
m_Controls->labelFiberMaxLength->setEnabled(false);
//enable radiobuttons
if (!m_Controls->labelFibersTotal->isEnabled())
m_Controls->labelFibersTotal->setEnabled(true);
if (!m_Controls->boxFiberNumbers->isEnabled())
m_Controls->boxFiberNumbers->setEnabled(true);
if (!m_Controls->labelDistrRadius->isEnabled())
m_Controls->labelDistrRadius->setEnabled(true);
if (!m_Controls->boxDistributionRadius->isEnabled())
m_Controls->boxDistributionRadius->setEnabled(true);
} else {
// disable radiobuttons
if (m_Controls->labelDistrRadius->isEnabled())
m_Controls->labelDistrRadius->setEnabled(false);
if (m_Controls->boxDistributionRadius->isEnabled())
m_Controls->boxDistributionRadius->setEnabled(false);
//enable radiobuttons
if (!m_Controls->labelFibersTotal->isEnabled())
m_Controls->labelFibersTotal->setEnabled(true);
if (!m_Controls->boxFiberNumbers->isEnabled())
m_Controls->boxFiberNumbers->setEnabled(true);
if (!m_Controls->boxFiberMinLength->isEnabled())
m_Controls->boxFiberMinLength->setEnabled(true);
if (!m_Controls->labelFiberMinLength->isEnabled())
m_Controls->labelFiberMinLength->setEnabled(true);
if (!m_Controls->boxFiberMaxLength->isEnabled())
m_Controls->boxFiberMaxLength->setEnabled(true);
if (!m_Controls->labelFiberMaxLength->isEnabled())
m_Controls->labelFiberMaxLength->setEnabled(true);
}
}
void QmitkFiberBundleDeveloperView::DoGenerateFibers()
{
// GET SELECTED FIBER DIRECTION
QString fibDirection; //stores the object_name of selected radiobutton
QVector<QRadioButton*>::const_iterator i;
for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i)
{
QRadioButton* rdbtn = *i;
if (rdbtn->isChecked())
fibDirection = rdbtn->objectName();
}
vtkSmartPointer<vtkPolyData> output; // FiberPD stores the generated PolyData
if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_RANDOM ) {
// build polydata with random lines and fibers
output = GenerateVtkFibersRandom();
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_X ) {
// build polydata with XDirection fibers
output = GenerateVtkFibersDirectionX();
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Y ) {
// build polydata with YDirection fibers
output = GenerateVtkFibersDirectionY();
} else if ( fibDirection == FIB_RADIOBUTTON_DIRECTION_Z ) {
// build polydata with ZDirection fibers
output = GenerateVtkFibersDirectionZ();
}
//mitkFiberBundleX::New()
//write to dataStorage
}
/*
* Generate polydata of random fibers
*/
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersRandom()
{
int numOfFibers = m_Controls->boxFiberNumbers->value();
int distrRadius = m_Controls->boxDistributionRadius->value();
int numOfPoints = numOfFibers * distrRadius;
std::vector< std::vector<int> > fiberStorage;
for (int i=0; i<numOfFibers; ++i) {
std::vector<int> a;
fiberStorage.push_back( a );
}
//get number of items in fiberStorage
MITK_INFO << "Fibers in fiberstorage: " << fiberStorage.size();
for (unsigned long i=0; i<fiberStorage.size(); ++i)
{
//add dummy points to storageentries
fiberStorage.at(i).push_back(222);
fiberStorage.at(i).push_back((int)i);
}
for (unsigned long i=0; i<fiberStorage.size(); ++i)
{
std::vector<int> singleFiber = fiberStorage.at(i);
MITK_INFO << "====FIBER_" << i << "_=====";
for (unsigned long si=0; si<singleFiber.size(); ++si) {
MITK_INFO << singleFiber.at(si);
}
}
/* Generate Point Cloud */
vtkSmartPointer<vtkPointSource> randomPoints = vtkSmartPointer<vtkPointSource>::New();
randomPoints->SetCenter(0.0, 0.0, 0.0);
randomPoints->SetNumberOfPoints(numOfPoints);
randomPoints->SetRadius(distrRadius);
randomPoints->Update();
vtkPolyData* pntHost = randomPoints->GetOutput();
vtkPoints* pnts = pntHost->GetPoints();
//===================================
//checkpoint if requested amount of points equals generated amount
if (numOfPoints != pnts->GetNumberOfPoints()) {
MITK_INFO << "VTK POINT ERROR, WRONG AMOUNT OF GENRERATED POINTS";
return 0;
}// =================================
// Set Fibers
vtkSmartPointer<vtkCellArray> linesCell = vtkSmartPointer<vtkCellArray>::New();
// iterate through points
vtkSmartPointer<vtkPolyData> PDRandom = vtkSmartPointer<vtkPolyData>::New();
PDRandom->SetPoints(pnts);
PDRandom->SetLines(linesCell);
return PDRandom;
}
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionX()
{
int numOfFibers = m_Controls->boxFiberNumbers->value();
vtkSmartPointer<vtkCellArray> linesCell = vtkSmartPointer<vtkCellArray>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
//insert Origin point, this point has index 0 in point array
double originX = 0.0;
double originY = 0.0;
double originZ = 0.0;
//after each iteration the origin of the new fiber increases
//here you set which direction is affected.
double increaseX = 0.0;
double increaseY = 1.0;
double increaseZ = 0.0;
//walk along X axis
//length of fibers increases in each iteration
for (int i=0; i<numOfFibers; ++i) {
vtkSmartPointer<vtkPolyLine> newFiber = vtkSmartPointer<vtkPolyLine>::New();
newFiber->GetPointIds()->SetNumberOfIds(i+2);
//create starting point and add it to pointset
points->InsertNextPoint(originX + (double)i * increaseX , originY + (double)i * increaseY, originZ + (double)i * increaseZ);
//add starting point to fiber
newFiber->GetPointIds()->SetId(0,points->GetNumberOfPoints()-1);
//insert remaining points for fiber
for (int pj=0; pj<=i ; ++pj)
{ //generate next point on X axis
points->InsertNextPoint( originX + (double)pj+1 , originY + (double)i * increaseY, originZ + (double)i * increaseZ );
newFiber->GetPointIds()->SetId(pj+1,points->GetNumberOfPoints()-1);
}
linesCell->InsertNextCell(newFiber);
}
vtkSmartPointer<vtkPolyData> PDX = vtkSmartPointer<vtkPolyData>::New();
PDX->SetPoints(points);
PDX->SetLines(linesCell);
return PDX;
}
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionY()
{
vtkSmartPointer<vtkPolyData> PDY = vtkSmartPointer<vtkPolyData>::New();
//todo
return PDY;
}
vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionZ()
{
vtkSmartPointer<vtkPolyData> PDZ = vtkSmartPointer<vtkPolyData>::New();
//todo
return PDZ;
}
void QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
m_MultiWidget = &stdMultiWidget;
}
void QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable()
{
m_MultiWidget = NULL;
}
/* OnSelectionChanged is registered to SelectionService, therefore no need to
implement SelectionService Listener explicitly */
void QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes )
{
}
void QmitkFiberBundleDeveloperView::Activated()
{
MITK_INFO << "FB OPerations ACTIVATED()";
}
<|endoftext|>
|
<commit_before>/*
* kernel.cpp
*
* Created on: Feb 20, 2017
* Author: garrett
*/
#include "Kernel.h"
#include "drivers/ProgrammableInterruptController.h"
#include "memory/alloc/PageFrameAllocator.h"
#include "drivers/Keyboard.h"
#include "interrupts/InterruptDescriptorTable.h"
#include "drivers/TTY/Console.h"
//#include "memory/alloc/malloc.h"
#include "memory/structures/GlobalDescriptorTable.h"
#include "memory/structures/PageTable.h"
#include "drivers/PCI/PCI.h"
#include "drivers/PCI/PCIDeviceList.h"
#include "multiboot_spec/Multiboot.h"
#include "memory/Mem.h"
#include "utils/printf/Printf.h"
InterruptDescriptorTable idt;
GlobalDescriptorTable gdt;
PageTable pageTable;
Keyboard KB;
PageFrameAllocator frameAlloc;
#if defined(__cplusplus)
extern "C" {/* Use C linkage for kernel_main. */
#endif
void kernelMain(multiboot_info_t* mbd) {
//turn off interrupts before configed
asm("cli");
//clear screen, set the pointer to the start of the VGA buffer.
terminalInit((uint16_t*) 0xC00B8000);
// Green on black!
terminalSetColor(vgaEntryColor(VGA_COLOR_GREEN, VGA_COLOR_BLACK));
terminalWriteLine("Terminal active, Welcome to ExOS!");
terminalWriteLine("Preparing your system:");
terminalWriteString(" Preparing GDT...");
//build and replce grub's GDT with a custom writable one.
gdt.build( );
gdt.load( );
terminalWriteLine(" Done!");
terminalWriteString(" Preparing the page table...");
//rebuild page table. replaces the one built in boot.s
pageTable.build( );
terminalWriteLine(" Done!");
terminalWriteString(" Setting up interrupts...");
//sets up interrups and enables them
interruptSetUp( );
terminalWriteLine(" Done!");
terminalWriteString(" Preparing the memory allocator...");
//get the memory map from grub
getMemMap(mbd);
//build the page frame allocator (allocate physical memory)
frameAlloc.build( );
//set malloc's support vars
mallocInit( );
terminalWriteLine(" Done!");
terminalWriteString(" Finding PCI buses...");
//find the valid PCI buses
PCIInit();
terminalWriteLine(" Done!");
terminalWriteString(" Finding USB host controllers...");
//find the (3 or less) USB host controllers. all have the same class/subclass code.
PCIDeviceList usbHostControllers(0x0C, 0x03, false);
terminalWriteLine(" Done!");
terminalWriteLine("!!!!ExOS fully booted!!!!");
printf("Test printf %d %c\n", 42, 'B');
printf("Newline is 0x%x%c", '\n', '\n');
for (int cx = 0; cx < 10; cx++) {
printf("%d", cx);
}
//dont return.
while (true) {
asm("hlt");
}
}
#if defined(__cplusplus)
}
#endif
void interruptSetUp( ) {
//build the IDT.
idt.build( );
//set the interrupt lines for the PIC
PICRemap(0x20, 0x28);
//mask the timer line
IRQSetMask(0);
//load it to the CPU
idt.load( );
//enable interupts
asm("sti");
}
<commit_msg>test code<commit_after>/*
* kernel.cpp
*
* Created on: Feb 20, 2017
* Author: garrett
*/
#include "Kernel.h"
#include "drivers/ProgrammableInterruptController.h"
#include "memory/alloc/PageFrameAllocator.h"
#include "drivers/Keyboard.h"
#include "interrupts/InterruptDescriptorTable.h"
#include "drivers/TTY/Console.h"
//#include "memory/alloc/malloc.h"
#include "memory/structures/GlobalDescriptorTable.h"
#include "memory/structures/PageTable.h"
#include "drivers/PCI/PCI.h"
#include "drivers/PCI/PCIDeviceList.h"
#include "multiboot_spec/Multiboot.h"
#include "memory/Mem.h"
#include "utils/printf/Printf.h"
InterruptDescriptorTable idt;
GlobalDescriptorTable gdt;
PageTable pageTable;
Keyboard KB;
PageFrameAllocator frameAlloc;
#if defined(__cplusplus)
extern "C" {/* Use C linkage for kernel_main. */
#endif
void kernelMain(multiboot_info_t *mbd)
{
//turn off interrupts before configed
asm("cli");
//clear screen, set the pointer to the start of the VGA buffer.
terminalInit((uint16_t *) 0xC00B8000);
// Green on black!
terminalSetColor(vgaEntryColor(VGA_COLOR_GREEN, VGA_COLOR_BLACK));
terminalWriteLine("Terminal active, Welcome to ExOS!");
terminalWriteLine("Preparing your system:");
terminalWriteString(" Preparing GDT...");
//build and replce grub's GDT with a custom writable one.
gdt.build();
gdt.load();
terminalWriteLine(" Done!");
terminalWriteString(" Preparing the page table...");
//rebuild page table. replaces the one built in boot.s
pageTable.build();
terminalWriteLine(" Done!");
terminalWriteString(" Setting up interrupts...");
//sets up interrups and enables them
interruptSetUp();
terminalWriteLine(" Done!");
terminalWriteString(" Preparing the memory allocator...");
//get the memory map from grub
getMemMap(mbd);
//build the page frame allocator (allocate physical memory)
frameAlloc.build();
//set malloc's support vars
mallocInit();
terminalWriteLine(" Done!");
terminalWriteString(" Finding PCI buses...");
//find the valid PCI buses
PCIInit();
terminalWriteLine(" Done!");
terminalWriteString(" Finding USB host controllers...");
//find the (3 or less) USB host controllers. all have the same class/subclass code.
PCIDeviceList usbHostControllers(0x0C, 0x03, false);
terminalWriteLine(" Done!");
terminalWriteLine("!!!!ExOS fully booted!!!!");
printf("Test printf %d %c\n", 42, 'B');
printf("Newline is 0x%x%c", '\n', '\n');
uint32_t i = (uint32_t) malloc(10);
printf("malloc returned 0x%x\n", i);
i = (uint32_t)malloc(100);
printf("malloc returned 0x%x\n", i);
i =(uint32_t) malloc(50);
printf("malloc returned 0x%x\n", i);
i = (uint32_t)malloc(1);
printf("malloc returned 0x%x\n", i);
printf("freeing 1 byte");
free((void*)i);
i = (uint32_t)malloc(1);
printf("malloc returned 0x%x\n", i);
/*
for (int cx = 0; cx < 10; cx++) {
printf("%d", cx);
}*/
//dont return.
while (true) {
asm("hlt");
}
}
#if defined(__cplusplus)
}
#endif
void interruptSetUp()
{
//build the IDT.
idt.build();
//set the interrupt lines for the PIC
PICRemap(0x20, 0x28);
//mask the timer line
IRQSetMask(0);
//load it to the CPU
idt.load();
//enable interupts
asm("sti");
}
<|endoftext|>
|
<commit_before>// SciTE - Scintilla based Text Editor
// LexCPP.cxx - lexer for C++, C, Java, and Javascript
// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
char s[100];
for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
s[i] = styler[start + i];
s[i + 1] = '\0';
}
bool wordIsUUID = false;
char chAttr = SCE_C_IDENTIFIER;
if (isdigit(s[0]) || (s[0] == '.'))
chAttr = SCE_C_NUMBER;
else {
if (keywords.InList(s)) {
chAttr = SCE_C_WORD;
wordIsUUID = strcmp(s, "uuid") == 0;
}
}
styler.ColourTo(end, chAttr);
return wordIsUUID;
}
static bool isOKBeforeRE(char ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold");
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int state = initStyle;
if (state == SCE_C_STRINGEOL) // Does not leak onto next line
state = SCE_C_DEFAULT;
char chPrev = ' ';
char chNext = styler[startPos];
char chPrevNonWhite = ' ';
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
styler.StartSegment(startPos);
bool lastWordWasUUID = false;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
// Avoid triggering two times on Dos/Win
// End of line
if (state == SCE_C_STRINGEOL) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
if (fold) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
levelPrev = levelCurrent;
}
visibleChars = 0;
}
if (!isspace(ch))
visibleChars++;
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_C_DEFAULT) {
if (ch == '@' && chNext == '\"') {
styler.ColourTo(i-1, state);
state = SCE_C_VERBATIM;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else if (iswordstart(ch) || (ch == '@')) {
styler.ColourTo(i-1, state);
if (lastWordWasUUID) {
state = SCE_C_UUID;
lastWordWasUUID = false;
} else {
state = SCE_C_IDENTIFIER;
}
} else if (ch == '/' && chNext == '*') {
styler.ColourTo(i-1, state);
if (styler.SafeGetCharAt(i + 2) == '*')
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
styler.ColourTo(i-1, state);
state = SCE_C_COMMENTLINE;
} else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) {
styler.ColourTo(i-1, state);
state = SCE_C_REGEX;
} else if (ch == '\"') {
styler.ColourTo(i-1, state);
state = SCE_C_STRING;
} else if (ch == '\'') {
styler.ColourTo(i-1, state);
state = SCE_C_CHARACTER;
} else if (ch == '#' && visibleChars == 1) {
// Preprocessor commands are alone on their line
styler.ColourTo(i-1, state);
state = SCE_C_PREPROCESSOR;
// Skip whitespace between # and preprocessor word
do {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} while (isspace(ch) && (i < lengthDoc));
} else if (isoperator(ch)) {
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_C_OPERATOR);
if ((ch == '{') || (ch == '}')) {
levelCurrent += (ch == '{') ? 1 : -1;
}
}
} else if (state == SCE_C_IDENTIFIER) {
if (!iswordchar(ch)) {
lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_C_DEFAULT;
if (ch == '/' && chNext == '*') {
if (styler.SafeGetCharAt(i + 2) == '*')
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
state = SCE_C_STRING;
} else if (ch == '\'') {
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i, SCE_C_OPERATOR);
if ((ch == '{') || (ch == '}')) {
levelCurrent += (ch == '{') ? 1 : -1;
}
}
}
} else {
if (state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (isspace(ch)) {
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
} else {
if ((ch == '\r' || ch == '\n') && !(chPrev == '\\' || chPrev == '\r')) {
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENT) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(initStyle == SCE_C_COMMENT) &&
(styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENTDOC) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(initStyle == SCE_C_COMMENTDOC) &&
(styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENTLINE) {
if (ch == '\r' || ch == '\n') {
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) {
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
}
} else if (state == SCE_C_CHARACTER) {
if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
} else if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\'') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_REGEX) {
if (ch == '\r' || ch == '\n' || ch == '/') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if (ch == '\\') {
// Gobble up the quoted character
if (chNext == '\\' || chNext == '/') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
} else if (state == SCE_C_VERBATIM) {
if (ch == '\"') {
if (chNext == '\"') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_UUID) {
if (ch == '\r' || ch == '\n' || ch == ')') {
styler.ColourTo(i-1, state);
if (ch == ')')
styler.ColourTo(i, SCE_C_OPERATOR);
state = SCE_C_DEFAULT;
}
}
}
chPrev = ch;
if (ch != ' ' && ch != '\t')
chPrevNonWhite = ch;
}
styler.ColourTo(lengthDoc - 1, state);
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
if (fold) {
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc);
<commit_msg>Addition of SCE_C_COMMENTLINEDOC by Philippe.<commit_after>// SciTE - Scintilla based Text Editor
// LexCPP.cxx - lexer for C++, C, Java, and Javascript
// Copyright 1998-2000 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool classifyWordCpp(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {
char s[100];
for (unsigned int i = 0; i < end - start + 1 && i < 30; i++) {
s[i] = styler[start + i];
s[i + 1] = '\0';
}
bool wordIsUUID = false;
char chAttr = SCE_C_IDENTIFIER;
if (isdigit(s[0]) || (s[0] == '.'))
chAttr = SCE_C_NUMBER;
else {
if (keywords.InList(s)) {
chAttr = SCE_C_WORD;
wordIsUUID = strcmp(s, "uuid") == 0;
}
}
styler.ColourTo(end, chAttr);
return wordIsUUID;
}
static bool isOKBeforeRE(char ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold");
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor");
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
int state = initStyle;
if (state == SCE_C_STRINGEOL) // Does not leak onto next line
state = SCE_C_DEFAULT;
char chPrev = ' ';
char chNext = styler[startPos];
char chPrevNonWhite = ' ';
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
styler.StartSegment(startPos);
bool lastWordWasUUID = false;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
// Trigger on CR only (Mac style) or either on LF from CR+LF (Dos/Win) or on LF alone (Unix)
// Avoid triggering two times on Dos/Win
// End of line
if (state == SCE_C_STRINGEOL) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
if (fold) {
int lev = levelPrev;
if (visibleChars == 0)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
styler.SetLevel(lineCurrent, lev);
lineCurrent++;
levelPrev = levelCurrent;
}
visibleChars = 0;
}
if (!isspace(ch))
visibleChars++;
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
if (state == SCE_C_DEFAULT) {
if (ch == '@' && chNext == '\"') {
styler.ColourTo(i-1, state);
state = SCE_C_VERBATIM;
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else if (iswordstart(ch) || (ch == '@')) {
styler.ColourTo(i-1, state);
if (lastWordWasUUID) {
state = SCE_C_UUID;
lastWordWasUUID = false;
} else {
state = SCE_C_IDENTIFIER;
}
} else if (ch == '/' && chNext == '*') {
styler.ColourTo(i-1, state);
if (styler.SafeGetCharAt(i + 2) == '*' ||
styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
styler.ColourTo(i-1, state);
if (styler.SafeGetCharAt(i + 2) == '/' ||
styler.SafeGetCharAt(i + 2) == '!') // Support of Qt/Doxygen doc. style
state = SCE_C_COMMENTLINEDOC;
else
state = SCE_C_COMMENTLINE;
} else if (ch == '/' && isOKBeforeRE(chPrevNonWhite)) {
styler.ColourTo(i-1, state);
state = SCE_C_REGEX;
} else if (ch == '\"') {
styler.ColourTo(i-1, state);
state = SCE_C_STRING;
} else if (ch == '\'') {
styler.ColourTo(i-1, state);
state = SCE_C_CHARACTER;
} else if (ch == '#' && visibleChars == 1) {
// Preprocessor commands are alone on their line
styler.ColourTo(i-1, state);
state = SCE_C_PREPROCESSOR;
// Skip whitespace between # and preprocessor word
do {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} while (isspace(ch) && (i < lengthDoc));
} else if (isoperator(ch)) {
styler.ColourTo(i-1, state);
styler.ColourTo(i, SCE_C_OPERATOR);
if ((ch == '{') || (ch == '}')) {
levelCurrent += (ch == '{') ? 1 : -1;
}
}
} else if (state == SCE_C_IDENTIFIER) {
if (!iswordchar(ch)) {
lastWordWasUUID = classifyWordCpp(styler.GetStartSegment(), i - 1, keywords, styler);
state = SCE_C_DEFAULT;
if (ch == '/' && chNext == '*') {
if (styler.SafeGetCharAt(i + 2) == '*')
state = SCE_C_COMMENTDOC;
else
state = SCE_C_COMMENT;
} else if (ch == '/' && chNext == '/') {
state = SCE_C_COMMENTLINE;
} else if (ch == '\"') {
state = SCE_C_STRING;
} else if (ch == '\'') {
state = SCE_C_CHARACTER;
} else if (isoperator(ch)) {
styler.ColourTo(i, SCE_C_OPERATOR);
if ((ch == '{') || (ch == '}')) {
levelCurrent += (ch == '{') ? 1 : -1;
}
}
}
} else {
if (state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (isspace(ch)) {
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
} else {
if ((ch == '\r' || ch == '\n') && !(chPrev == '\\' || chPrev == '\r')) {
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENT) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(initStyle == SCE_C_COMMENT) &&
(styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENTDOC) {
if (ch == '/' && chPrev == '*') {
if (((i > styler.GetStartSegment() + 2) || (
(initStyle == SCE_C_COMMENTDOC) &&
(styler.GetStartSegment() == static_cast<unsigned int>(startPos))))) {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_COMMENTLINE || state == SCE_C_COMMENTLINEDOC) {
if (ch == '\r' || ch == '\n') {
styler.ColourTo(i-1, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_STRING) {
if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\"') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if ((chNext == '\r' || chNext == '\n') && (chPrev != '\\')) {
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
}
} else if (state == SCE_C_CHARACTER) {
if ((ch == '\r' || ch == '\n') && (chPrev != '\\')) {
styler.ColourTo(i-1, SCE_C_STRINGEOL);
state = SCE_C_STRINGEOL;
} else if (ch == '\\') {
if (chNext == '\"' || chNext == '\'' || chNext == '\\') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
} else if (ch == '\'') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
} else if (state == SCE_C_REGEX) {
if (ch == '\r' || ch == '\n' || ch == '/') {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
} else if (ch == '\\') {
// Gobble up the quoted character
if (chNext == '\\' || chNext == '/') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
}
}
} else if (state == SCE_C_VERBATIM) {
if (ch == '\"') {
if (chNext == '\"') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
state = SCE_C_DEFAULT;
}
}
} else if (state == SCE_C_UUID) {
if (ch == '\r' || ch == '\n' || ch == ')') {
styler.ColourTo(i-1, state);
if (ch == ')')
styler.ColourTo(i, SCE_C_OPERATOR);
state = SCE_C_DEFAULT;
}
}
}
chPrev = ch;
if (ch != ' ' && ch != '\t')
chPrevNonWhite = ch;
}
styler.ColourTo(lengthDoc - 1, state);
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
if (fold) {
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
//styler.SetLevel(lineCurrent, levelCurrent | flagsNext);
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
}
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc);
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<commit_msg>Patch from Kein-Hong Man properly handles + or - as operators in numbers like 1+2.<commit_after>// Scintilla source code edit control
/** @file LexLua.cxx
** Lexer for Lua language.
**
** Written by Paul Winwood.
** Folder by Alexey Yutkin.
** Modified by Marcos E. Wurzius & Philippe Lhoste
**/
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
// Extended to accept accented characters
static inline bool IsAWordChar(int ch) {
return ch >= 0x80 ||
(isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(int ch) {
return ch >= 0x80 ||
(isalpha(ch) || ch == '_');
}
static inline bool IsANumberChar(int ch) {
// Not exactly following number definition (several dots are seen as OK, etc.)
// but probably enough in most cases.
return (ch < 0x80) &&
(isdigit(ch) || toupper(ch) == 'E' ||
ch == '.' || ch == '-' || ch == '+' ||
(ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'));
}
static inline bool IsLuaOperator(int ch) {
if (ch >= 0x80 || isalnum(ch)) {
return false;
}
// '.' left out as it is used to make up numbers
if (ch == '*' || ch == '/' || ch == '-' || ch == '+' ||
ch == '(' || ch == ')' || ch == '=' ||
ch == '{' || ch == '}' || ch == '~' ||
ch == '[' || ch == ']' || ch == ';' ||
ch == '<' || ch == '>' || ch == ',' ||
ch == '.' || ch == '^' || ch == '%' || ch == ':' ||
ch == '#') {
return true;
}
return false;
}
// Test for [=[ ... ]=] delimiters, returns 0 if it's only a [ or ],
// return 1 for [[ or ]], returns >=2 for [=[ or ]=] and so on.
// The maximum number of '=' characters allowed is 254.
static int LongDelimCheck(StyleContext &sc) {
int sep = 1;
while (sc.GetRelative(sep) == '=' && sep < 0xFF)
sep++;
if (sc.GetRelative(sep) == sc.ch)
return sep;
return 0;
}
static void ColouriseLuaDoc(
unsigned int startPos,
int length,
int initStyle,
WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
WordList &keywords4 = *keywordlists[3];
WordList &keywords5 = *keywordlists[4];
WordList &keywords6 = *keywordlists[5];
WordList &keywords7 = *keywordlists[6];
WordList &keywords8 = *keywordlists[7];
int currentLine = styler.GetLine(startPos);
// Initialize long string [[ ... ]] or block comment --[[ ... ]] nesting level,
// if we are inside such a string. Block comment was introduced in Lua 5.0,
// blocks with separators [=[ ... ]=] in Lua 5.1.
int nestLevel = 0;
int sepCount = 0;
if (initStyle == SCE_LUA_LITERALSTRING || initStyle == SCE_LUA_COMMENT) {
int lineState = styler.GetLineState(currentLine - 1);
nestLevel = lineState >> 8;
sepCount = lineState & 0xFF;
}
// Do not leak onto next line
if (initStyle == SCE_LUA_STRINGEOL || initStyle == SCE_LUA_COMMENTLINE || initStyle == SCE_LUA_PREPROCESSOR) {
initStyle = SCE_LUA_DEFAULT;
}
StyleContext sc(startPos, length, initStyle, styler);
if (startPos == 0 && sc.ch == '#') {
// shbang line: # is a comment only if first char of the script
sc.SetState(SCE_LUA_COMMENTLINE);
}
for (; sc.More(); sc.Forward()) {
if (sc.atLineEnd) {
// Update the line state, so it can be seen by next line
currentLine = styler.GetLine(sc.currentPos);
switch (sc.state) {
case SCE_LUA_LITERALSTRING:
case SCE_LUA_COMMENT:
// Inside a literal string or block comment, we set the line state
styler.SetLineState(currentLine, (nestLevel << 8) | sepCount);
break;
default:
// Reset the line state
styler.SetLineState(currentLine, 0);
break;
}
}
if (sc.atLineStart && (sc.state == SCE_LUA_STRING)) {
// Prevent SCE_LUA_STRINGEOL from leaking back to previous line
sc.SetState(SCE_LUA_STRING);
}
// Handle string line continuation
if ((sc.state == SCE_LUA_STRING || sc.state == SCE_LUA_CHARACTER) &&
sc.ch == '\\') {
if (sc.chNext == '\n' || sc.chNext == '\r') {
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
sc.Forward();
}
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_LUA_OPERATOR) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.state == SCE_LUA_NUMBER) {
// We stop the number definition on non-numerical non-dot non-eE non-sign non-hexdigit char
if (!IsANumberChar(sc.ch)) {
sc.SetState(SCE_LUA_DEFAULT);
} else if (sc.ch == '-' || sc.ch == '+') {
if (sc.chPrev != 'E' && sc.chPrev != 'e')
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || sc.Match('.', '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
sc.ChangeState(SCE_LUA_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_LUA_WORD2);
} else if (keywords3.InList(s)) {
sc.ChangeState(SCE_LUA_WORD3);
} else if (keywords4.InList(s)) {
sc.ChangeState(SCE_LUA_WORD4);
} else if (keywords5.InList(s)) {
sc.ChangeState(SCE_LUA_WORD5);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords6.InList(s)) {
sc.ChangeState(SCE_LUA_WORD6);
} else if (keywords7.InList(s)) {
sc.ChangeState(SCE_LUA_WORD7);
} else if (keywords8.InList(s)) {
sc.ChangeState(SCE_LUA_WORD8);
}
sc.SetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_COMMENTLINE || sc.state == SCE_LUA_PREPROCESSOR) {
if (sc.atLineEnd) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_LUA_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_LUA_STRINGEOL);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sc.state == SCE_LUA_LITERALSTRING || sc.state == SCE_LUA_COMMENT) {
if (sc.ch == '[') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // [[-only allowed to nest
nestLevel++;
sc.Forward();
}
} else if (sc.ch == ']') {
int sep = LongDelimCheck(sc);
if (sep == 1 && sepCount == 1) { // un-nest with ]]-only
nestLevel--;
sc.Forward();
if (nestLevel == 0) {
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
} else if (sep > 1 && sep == sepCount) { // ]=]-style delim
sc.Forward(sep);
sc.ForwardSetState(SCE_LUA_DEFAULT);
}
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_LUA_DEFAULT) {
if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
sc.SetState(SCE_LUA_NUMBER);
if (sc.ch == '0' && toupper(sc.chNext) == 'X') {
sc.Forward(1);
}
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_LUA_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_LUA_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_LUA_CHARACTER);
} else if (sc.ch == '[') {
sepCount = LongDelimCheck(sc);
if (sepCount == 0) {
sc.SetState(SCE_LUA_OPERATOR);
} else {
nestLevel = 1;
sc.SetState(SCE_LUA_LITERALSTRING);
sc.Forward(sepCount);
}
} else if (sc.Match('-', '-')) {
sc.SetState(SCE_LUA_COMMENTLINE);
if (sc.Match("--[")) {
sc.Forward(2);
sepCount = LongDelimCheck(sc);
if (sepCount > 0) {
nestLevel = 1;
sc.ChangeState(SCE_LUA_COMMENT);
sc.Forward(sepCount);
}
} else {
sc.Forward();
}
} else if (sc.atLineStart && sc.Match('$')) {
sc.SetState(SCE_LUA_PREPROCESSOR); // Obsolete since Lua 4.0, but still in old code
} else if (IsLuaOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_LUA_OPERATOR);
}
}
}
sc.Complete();
}
static void FoldLuaDoc(unsigned int startPos, int length, int /* initStyle */, WordList *[],
Accessor &styler) {
unsigned int lengthDoc = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
int styleNext = styler.StyleAt(startPos);
char s[10];
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (style == SCE_LUA_WORD) {
if (ch == 'i' || ch == 'd' || ch == 'f' || ch == 'e' || ch == 'r' || ch == 'u') {
for (unsigned int j = 0; j < 8; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if ((strcmp(s, "if") == 0) || (strcmp(s, "do") == 0) || (strcmp(s, "function") == 0) || (strcmp(s, "repeat") == 0)) {
levelCurrent++;
}
if ((strcmp(s, "end") == 0) || (strcmp(s, "elseif") == 0) || (strcmp(s, "until") == 0)) {
levelCurrent--;
}
}
} else if (style == SCE_LUA_OPERATOR) {
if (ch == '{' || ch == '(') {
levelCurrent++;
} else if (ch == '}' || ch == ')') {
levelCurrent--;
}
} else if (style == SCE_LUA_LITERALSTRING || style == SCE_LUA_COMMENT) {
if (ch == '[') {
levelCurrent++;
} else if (ch == ']') {
levelCurrent--;
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact) {
lev |= SC_FOLDLEVELWHITEFLAG;
}
if ((levelCurrent > levelPrev) && (visibleChars > 0)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch)) {
visibleChars++;
}
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const luaWordListDesc[] = {
"Keywords",
"Basic functions",
"String, (table) & math functions",
"(coroutines), I/O & system facilities",
"user1",
"user2",
"user3",
"user4",
0
};
LexerModule lmLua(SCLEX_LUA, ColouriseLuaDoc, "lua", FoldLuaDoc, luaWordListDesc);
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <stddef.h>
#include <linux/inotify.h>
using namespace std;
#include "debug.h"
#include "config.h"
Config::Config(int count, char** values) :
m_all(false),
m_verbose(2),
m_pidfile_path("/var/run"),
m_logfile_path(""),
m_no_demon(false),
m_path_to_scripts("/etc/rnotifyd"),
m_exclude(),
m_heartbeat(250),
m_skip_zero_file(false),
m_enable_supressor(false),
m_mask(0),
m_catch_rename(false),
m_need_help(false),
m_my_name(values[0])
{
readOpts(count, values);
readMask();
}
Config::~Config()
{
vector <char*> :: iterator itr;
for (itr = m_watch.begin(); itr != m_watch.end(); ++itr)
{
delete *itr;
}
}
bool Config::getAll()
{
return m_all;
}
string Config::getMyName()
{
return m_my_name;
}
bool Config::getNeedHelp()
{
return m_need_help;
}
bool Config::getCatchRename()
{
return m_catch_rename;
}
bool Config::getEnableSuppressor()
{
return m_enable_supressor;
}
bool Config::getSkipZeroFile()
{
return m_skip_zero_file;
}
bool Config::getNoDemon()
{
return m_no_demon;
}
string Config::getExclude()
{
return m_exclude;
}
string Config::getPathToScripts()
{
return m_path_to_scripts;
}
string Config::getPidfile()
{
return m_pidfile_path + "/" + m_my_name + ".pid";
}
string Config::getLogfilePath()
{
return m_logfile_path;
}
uint32_t Config::getMask()
{
return m_mask;
}
int Config::getHearbeat()
{
return m_heartbeat;
}
int Config::getVerbose()
{
return m_verbose;
}
char** Config::getWatch()
{
return &m_watch[0];
}
void Config::readMask()
{
if (m_all)
{
m_mask = IN_ALL_EVENTS;
return;
}
if (m_path_to_scripts.empty())
{
m_mask = 0;
return;
}
DIR* dp = opendir(m_path_to_scripts.c_str());
if (dp == NULL)
{
fatal << " Nothing to do in " << m_path_to_scripts.c_str() << "/. Please follow instructions for -s argument." << std::endl;
m_need_help = true;
return;
}
size_t dirent_sz = offsetof(struct dirent, d_name) + pathconf(m_path_to_scripts.c_str(), _PC_NAME_MAX);
struct dirent* entry = new struct dirent[dirent_sz + 1];
if (entry == NULL)
{
fatal << " Can't get entry from " << m_path_to_scripts.c_str() << "." << std::endl;
m_need_help = true;
closedir(dp);
return;
}
char** lst = NULL;
for (;;)
{
struct dirent* result = NULL;
if (0 != readdir_r(dp, entry, &result)
|| result == NULL)
{
break;
}
if (!strcmp(entry->d_name, ".")
|| !strcmp(entry->d_name, ".."))
{
continue;
}
string script = m_path_to_scripts + "/" + result->d_name;
debug << "<<<<<<<< ++" << script << std::endl;
if (!strcmp(result->d_name, "IN_ACCESS") && !access(script.c_str(), X_OK))
{
m_mask |= IN_ACCESS;
}
if (!strcmp(result->d_name, "IN_ATTRIB") && !access(script.c_str(), X_OK))
{
m_mask |= IN_ATTRIB;
}
if (!strcmp(result->d_name, "IN_CLOSE_WRITE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_CLOSE_WRITE;
}
if (!strcmp(result->d_name, "IN_CLOSE_NOWRITE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_CLOSE_NOWRITE;
}
if (!strcmp(result->d_name, "IN_CREATE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_CREATE;
}
if (!strcmp(result->d_name, "IN_DELETE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_DELETE;
}
if (!strcmp(result->d_name, "IN_DELETE_SELF") && !access(script.c_str(), X_OK))
{
m_mask |= IN_DELETE_SELF;
}
if (!strcmp(result->d_name, "IN_MODIFY") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MODIFY;
}
if (!strcmp(result->d_name, "IN_MOVE_SELF") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MOVE_SELF;
}
if (!strcmp(result->d_name, "IN_MOVED_FROM") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MOVED_FROM;
}
if (!strcmp(result->d_name, "IN_MOVED_TO") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MOVED_TO;
}
if (!strcmp(result->d_name, "IN_OPEN") && !access(script.c_str(), X_OK))
{
m_mask |= IN_OPEN;
}
if (!strcmp(result->d_name, "IN_RENAME") && !access(script.c_str(), X_OK))
{
m_catch_rename = true;
}
}
if (!m_mask && !m_catch_rename)
{
m_need_help = true;
}
delete entry;
closedir(dp);
}
void Config::readOpts(int count, char** values)
{
const char* opts = "av:p:l:dhw:s:e:t:zu";
char opt = 0;
while (-1 != (opt = getopt(count, values, opts)))
{
switch (opt)
{
case 'a':
m_all = true;
m_no_demon = true;
break;
case 'v':
m_verbose = atoi(optarg);
break;
case 'p':
m_pidfile_path = optarg;
break;
case 'l':
m_logfile_path = optarg;
break;
case 'd':
m_no_demon = true;
break;
case 's':
m_path_to_scripts = optarg;
break;
case 'e':
m_exclude = optarg;
break;
case 't':
m_heartbeat = atoi(optarg);
break;
case 'z':
m_skip_zero_file = true;
break;
case 'u':
m_enable_supressor = true;
break;
case 'w':
m_watch.push_back(strdup(optarg));
break;
case 'h':
m_need_help = true;
break;
default:
break;
}
}
m_watch.push_back(NULL);
Debug::Init(m_verbose, m_no_demon, m_logfile_path);
char** watch = getWatch();
if (watch[0] == NULL)
{
fatal << " At least one watched directory should be present. Look at -w argument please." << std::endl;
m_need_help = true;
}
}
<commit_msg>clear code<commit_after>#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <stddef.h>
#include <linux/inotify.h>
using namespace std;
#include "debug.h"
#include "config.h"
Config::Config(int count, char** values) :
m_all(false),
m_verbose(2),
m_pidfile_path("/var/run"),
m_logfile_path(""),
m_no_demon(false),
m_path_to_scripts("/etc/rnotifyd"),
m_exclude(),
m_heartbeat(250),
m_skip_zero_file(false),
m_enable_supressor(false),
m_mask(0),
m_catch_rename(false),
m_need_help(false),
m_my_name(values[0])
{
readOpts(count, values);
readMask();
}
Config::~Config()
{
vector <char*> :: iterator itr;
for (itr = m_watch.begin(); itr != m_watch.end(); ++itr)
{
delete *itr;
}
}
bool Config::getAll()
{
return m_all;
}
string Config::getMyName()
{
return m_my_name;
}
bool Config::getNeedHelp()
{
return m_need_help;
}
bool Config::getCatchRename()
{
return m_catch_rename;
}
bool Config::getEnableSuppressor()
{
return m_enable_supressor;
}
bool Config::getSkipZeroFile()
{
return m_skip_zero_file;
}
bool Config::getNoDemon()
{
return m_no_demon;
}
string Config::getExclude()
{
return m_exclude;
}
string Config::getPathToScripts()
{
return m_path_to_scripts;
}
string Config::getPidfile()
{
return m_pidfile_path + "/" + m_my_name + ".pid";
}
string Config::getLogfilePath()
{
return m_logfile_path;
}
uint32_t Config::getMask()
{
return m_mask;
}
int Config::getHearbeat()
{
return m_heartbeat;
}
int Config::getVerbose()
{
return m_verbose;
}
char** Config::getWatch()
{
return &m_watch[0];
}
void Config::readMask()
{
if (m_all)
{
m_mask = IN_ALL_EVENTS;
return;
}
if (m_path_to_scripts.empty())
{
m_mask = 0;
return;
}
DIR* dp = opendir(m_path_to_scripts.c_str());
if (dp == NULL)
{
fatal << " Nothing to do in " << m_path_to_scripts.c_str() << "/. Please follow instructions for -s argument." << std::endl;
m_need_help = true;
return;
}
size_t dirent_sz = offsetof(struct dirent, d_name) + pathconf(m_path_to_scripts.c_str(), _PC_NAME_MAX);
struct dirent* entry = new struct dirent[dirent_sz + 1];
if (entry == NULL)
{
fatal << " Can't get entry from " << m_path_to_scripts.c_str() << "." << std::endl;
m_need_help = true;
closedir(dp);
return;
}
char** lst = NULL;
for (;;)
{
struct dirent* result = NULL;
if (0 != readdir_r(dp, entry, &result)
|| result == NULL)
{
break;
}
if (!strcmp(entry->d_name, ".")
|| !strcmp(entry->d_name, ".."))
{
continue;
}
string script = m_path_to_scripts + "/" + result->d_name;
if (!strcmp(result->d_name, "IN_ACCESS") && !access(script.c_str(), X_OK))
{
m_mask |= IN_ACCESS;
}
if (!strcmp(result->d_name, "IN_ATTRIB") && !access(script.c_str(), X_OK))
{
m_mask |= IN_ATTRIB;
}
if (!strcmp(result->d_name, "IN_CLOSE_WRITE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_CLOSE_WRITE;
}
if (!strcmp(result->d_name, "IN_CLOSE_NOWRITE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_CLOSE_NOWRITE;
}
if (!strcmp(result->d_name, "IN_CREATE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_CREATE;
}
if (!strcmp(result->d_name, "IN_DELETE") && !access(script.c_str(), X_OK))
{
m_mask |= IN_DELETE;
}
if (!strcmp(result->d_name, "IN_DELETE_SELF") && !access(script.c_str(), X_OK))
{
m_mask |= IN_DELETE_SELF;
}
if (!strcmp(result->d_name, "IN_MODIFY") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MODIFY;
}
if (!strcmp(result->d_name, "IN_MOVE_SELF") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MOVE_SELF;
}
if (!strcmp(result->d_name, "IN_MOVED_FROM") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MOVED_FROM;
}
if (!strcmp(result->d_name, "IN_MOVED_TO") && !access(script.c_str(), X_OK))
{
m_mask |= IN_MOVED_TO;
}
if (!strcmp(result->d_name, "IN_OPEN") && !access(script.c_str(), X_OK))
{
m_mask |= IN_OPEN;
}
if (!strcmp(result->d_name, "IN_RENAME") && !access(script.c_str(), X_OK))
{
m_catch_rename = true;
}
}
if (!m_mask && !m_catch_rename)
{
m_need_help = true;
}
delete entry;
closedir(dp);
}
void Config::readOpts(int count, char** values)
{
const char* opts = "av:p:l:dhw:s:e:t:zu";
char opt = 0;
while (-1 != (opt = getopt(count, values, opts)))
{
switch (opt)
{
case 'a':
m_all = true;
m_no_demon = true;
break;
case 'v':
m_verbose = atoi(optarg);
break;
case 'p':
m_pidfile_path = optarg;
break;
case 'l':
m_logfile_path = optarg;
break;
case 'd':
m_no_demon = true;
break;
case 's':
m_path_to_scripts = optarg;
break;
case 'e':
m_exclude = optarg;
break;
case 't':
m_heartbeat = atoi(optarg);
break;
case 'z':
m_skip_zero_file = true;
break;
case 'u':
m_enable_supressor = true;
break;
case 'w':
m_watch.push_back(strdup(optarg));
break;
case 'h':
m_need_help = true;
break;
default:
break;
}
}
m_watch.push_back(NULL);
Debug::Init(m_verbose, m_no_demon, m_logfile_path);
char** watch = getWatch();
if (watch[0] == NULL)
{
fatal << " At least one watched directory should be present. Look at -w argument please." << std::endl;
m_need_help = true;
}
}
<|endoftext|>
|
<commit_before>#include "pending_irob.h"
#include "debug.h"
#include "timeops.h"
#include <functional>
#include <vector>
using std::vector; using std::max;
using std::mem_fun_ref;
using std::bind1st;
#include "pthread_util.h"
static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
ssize_t PendingIROB::obj_count = 0;
PendingIROB::PendingIROB(irob_id_t id_)
: id(id_),
anonymous(false),
complete(false),
placeholder(true)
{
/* this placeholder PendingIROB will be replaced by
the real one, when it arrives. */
}
PendingIROB::PendingIROB(irob_id_t id_, int numdeps, const irob_id_t *deps_array,
size_t datalen, char *data, u_long send_labels_)
: id(id_),
send_labels(send_labels_),
anonymous(false),
complete(false),
placeholder(false)
{
if (numdeps > 0) {
assert(deps_array);
}
for (int i = 0; i < numdeps; i++) {
deps.insert(deps_array[i]);
}
if (datalen > 0) {
anonymous = true;
assert(data);
struct irob_chunk_data chunk;
chunk.id = id;
chunk.seqno = INVALID_IROB_SEQNO;
chunk.datalen = datalen;
chunk.data = data;
(void)add_chunk(chunk);
(void)finish();
}
PthreadScopedLock lock(&count_mutex);
++obj_count;
}
PendingIROB::~PendingIROB()
{
while (!chunks.empty()) {
struct irob_chunk_data chunk = chunks.front();
chunks.pop_front();
delete [] chunk.data;
}
PthreadScopedLock lock(&count_mutex);
--obj_count;
}
ssize_t
PendingIROB::objs()
{
PthreadScopedLock lock(&count_mutex);
return obj_count;
}
bool
PendingIROB::add_chunk(struct irob_chunk_data& irob_chunk)
{
if (is_complete()) {
return false;
}
chunks.push_back(irob_chunk);
return true;
}
bool
PendingIROB::finish(void)
{
if (is_complete()) {
return false;
}
complete = true;
return true;
}
void
PendingIROB::add_dep(irob_id_t id)
{
deps.insert(id);
}
void
PendingIROB::dep_satisfied(irob_id_t id)
{
deps.erase(id);
}
void
PendingIROB::add_dependent(irob_id_t id)
{
dependents.insert(id);
}
bool
PendingIROB::is_complete(void) const
{
return complete;
}
bool
PendingIROB::is_anonymous(void) const
{
return anonymous;
}
bool
PendingIROB::depends_on(irob_id_t that)
{
return (deps.count(that) == 1);
}
PendingIROBLattice::PendingIROBLattice()
: offset(0), last_anon_irob_id(-1), count(0)
{
pthread_mutex_init(&membership_lock, NULL);
}
PendingIROBLattice::~PendingIROBLattice()
{
{
PthreadScopedLock lock(&membership_lock);
for (size_t i = 0; i < pending_irobs.size(); i++) {
delete pending_irobs[i];
}
pending_irobs.clear();
offset = 0;
}
pthread_mutex_destroy(&membership_lock);
}
bool
PendingIROBLattice::insert(PendingIROB *pirob, bool infer_deps)
{
PthreadScopedLock lock(&membership_lock);
return insert_locked(pirob, infer_deps);
}
bool
PendingIROBLattice::insert_locked(PendingIROB *pirob, bool infer_deps)
{
assert(pirob);
if (past_irobs.contains(pirob->id)) {
dbgprintf("Inserting IROB %d failed; it's in past_irobs\n", pirob->id);
return false;
}
if (pending_irobs.empty()) {
offset = pirob->id;
}
int index = pirob->id - offset;
if (index >= 0 && index < (int)pending_irobs.size() &&
(pending_irobs[index] != NULL &&
!pending_irobs[index]->placeholder)) {
dbgprintf("Inserting IROB %d failed; I have it already??\n", pirob->id);
return false;
}
while (index < 0) {
pending_irobs.push_front(NULL);
--offset;
index = pirob->id - offset;
}
if ((int)pending_irobs.size() <= index) {
pending_irobs.resize(index+1, NULL);
}
if (pending_irobs[index]) {
// grab the placeholder's dependents and replace it
// with the real PendingIROB
assert(!pirob->placeholder);
assert(pending_irobs[index]->placeholder);
assert(pending_irobs[index]->id == pirob->id);
pirob->dependents.insert(pending_irobs[index]->dependents.begin(),
pending_irobs[index]->dependents.end());
delete pending_irobs[index];
pending_irobs[index] = pirob;
} else {
pending_irobs[index] = pirob;
}
if (pirob->placeholder) {
// pirob only exists to hold dependents until
// its replacement arrives.
return true;
}
correct_deps(pirob, infer_deps);
dbgprintf("Adding IROB %d as dependent of: [ ", pirob->id);
for (irob_id_set::iterator it = pirob->deps.begin();
it != pirob->deps.end(); it++) {
PendingIROB *dep = find_locked(*it);
if (dep) {
dbgprintf_plain("%ld ", dep->id);
dep->add_dependent(pirob->id);
} else {
dbgprintf_plain("(%ld) ", *it);
dep = new PendingIROB(*it);
insert_locked(dep);
dep->add_dependent(pirob->id);
}
}
dbgprintf_plain("]\n");
++count;
return true;
}
void
PendingIROBLattice::clear()
{
PthreadScopedLock lock(&membership_lock);
pending_irobs.clear();
min_dominator_set.clear();
last_anon_irob_id = -1;
count = 0;
}
void
PendingIROBLattice::correct_deps(PendingIROB *pirob, bool infer_deps)
{
/* 1) If pirob is anonymous, add deps on all pending IROBs. */
/* 2) Otherwise, add deps on all pending anonymous IROBs. */
/* we keep around a min-dominator set of IROBs; that is,
* the minimal set of IROBs that the next anonymous IROB
* must depend on. */
if (!infer_deps) {
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
if (infer_deps) {
// skip this at the receiver. The sender infers and
// communicates deps; the receiver enforces them.
if (pirob->is_anonymous()) {
if (last_anon_irob_id >= 0 && min_dominator_set.empty()) {
pirob->add_dep(last_anon_irob_id);
} else {
pirob->deps.insert(min_dominator_set.begin(),
min_dominator_set.end());
min_dominator_set.clear();
}
last_anon_irob_id = pirob->id;
} else {
// this IROB dominates its deps, so remove them from
// the min_dominator_set before inserting it
vector<irob_id_t> isect(max(pirob->deps.size(),
min_dominator_set.size()));
vector<irob_id_t>::iterator the_end =
set_intersection(pirob->deps.begin(), pirob->deps.end(),
min_dominator_set.begin(),
min_dominator_set.end(),
isect.begin());
if (last_anon_irob_id >= 0 && isect.begin() == the_end) {
pirob->add_dep(last_anon_irob_id);
} // otherwise, it already depends on something
// that depends on the last_anon_irob
for (vector<irob_id_t>::iterator it = isect.begin();
it != the_end; ++it) {
min_dominator_set.erase(*it);
}
min_dominator_set.insert(pirob->id);
}
}
if (!infer_deps) {
/* 3) Remove already-satisfied deps. */
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
}
PendingIROB *
PendingIROBLattice::find(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return find_locked(id);
}
PendingIROB *
PendingIROBLattice::find_locked(irob_id_t id)
{
//TimeFunctionBody timer("pending_irobs.find(accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size()) {
return NULL;
}
return pending_irobs[index];
}
bool
PendingIROBLattice::erase(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
//TimeFunctionBody timer("pending_irobs.erase(const_accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size() ||
pending_irobs[index] == NULL) {
dbgprintf("WARNING: failed to remove IROB %d from lattice!\n", id);
return false;
}
past_irobs.insert(id);
min_dominator_set.erase(id);
PendingIROB *victim = pending_irobs[index];
pending_irobs[index] = NULL; // caller must free it
while (!pending_irobs.empty() && pending_irobs[0] == NULL) {
pending_irobs.pop_front();
offset++;
}
dbgprintf("Notifying dependents of IROB %d's release: [ ", id);
for (irob_id_set::iterator it = victim->dependents.begin();
it != victim->dependents.end(); it++) {
PendingIROB *dependent = this->find_locked(*it);
if (dependent == NULL) {
dbgprintf_plain("(%ld) ", *it);
continue;
}
dbgprintf_plain("%ld ", dependent->id);
dependent->dep_satisfied(id);
}
dbgprintf_plain("]\n");
--count;
return true;
}
bool
PendingIROBLattice::past_irob_exists(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return past_irobs.contains(id);
}
bool
PendingIROBLattice::empty()
{
PthreadScopedLock lock(&membership_lock);
return pending_irobs.empty();
}
size_t
PendingIROBLattice::size()
{
PthreadScopedLock lock(&membership_lock);
return count;
}
IROBSchedulingData::IROBSchedulingData(irob_id_t id_, u_long seqno_)
: id(id_), seqno(seqno_)
{
/* empty */
}
bool
IROBSchedulingData::operator<(const IROBSchedulingData& other) const
{
// can implement priority here, based on
// any added scheduling hints
return (id < other.id) || (seqno < other.seqno);
}
<commit_msg>Don't insert placeholders for IROBs that are in past_irobs.<commit_after>#include "pending_irob.h"
#include "debug.h"
#include "timeops.h"
#include <functional>
#include <vector>
using std::vector; using std::max;
using std::mem_fun_ref;
using std::bind1st;
#include "pthread_util.h"
static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
ssize_t PendingIROB::obj_count = 0;
PendingIROB::PendingIROB(irob_id_t id_)
: id(id_),
anonymous(false),
complete(false),
placeholder(true)
{
/* this placeholder PendingIROB will be replaced by
the real one, when it arrives. */
}
PendingIROB::PendingIROB(irob_id_t id_, int numdeps, const irob_id_t *deps_array,
size_t datalen, char *data, u_long send_labels_)
: id(id_),
send_labels(send_labels_),
anonymous(false),
complete(false),
placeholder(false)
{
if (numdeps > 0) {
assert(deps_array);
}
for (int i = 0; i < numdeps; i++) {
deps.insert(deps_array[i]);
}
if (datalen > 0) {
anonymous = true;
assert(data);
struct irob_chunk_data chunk;
chunk.id = id;
chunk.seqno = INVALID_IROB_SEQNO;
chunk.datalen = datalen;
chunk.data = data;
(void)add_chunk(chunk);
(void)finish();
}
PthreadScopedLock lock(&count_mutex);
++obj_count;
}
PendingIROB::~PendingIROB()
{
while (!chunks.empty()) {
struct irob_chunk_data chunk = chunks.front();
chunks.pop_front();
delete [] chunk.data;
}
PthreadScopedLock lock(&count_mutex);
--obj_count;
}
ssize_t
PendingIROB::objs()
{
PthreadScopedLock lock(&count_mutex);
return obj_count;
}
bool
PendingIROB::add_chunk(struct irob_chunk_data& irob_chunk)
{
if (is_complete()) {
return false;
}
chunks.push_back(irob_chunk);
return true;
}
bool
PendingIROB::finish(void)
{
if (is_complete()) {
return false;
}
complete = true;
return true;
}
void
PendingIROB::add_dep(irob_id_t id)
{
deps.insert(id);
}
void
PendingIROB::dep_satisfied(irob_id_t id)
{
deps.erase(id);
}
void
PendingIROB::add_dependent(irob_id_t id)
{
dependents.insert(id);
}
bool
PendingIROB::is_complete(void) const
{
return complete;
}
bool
PendingIROB::is_anonymous(void) const
{
return anonymous;
}
bool
PendingIROB::depends_on(irob_id_t that)
{
return (deps.count(that) == 1);
}
PendingIROBLattice::PendingIROBLattice()
: offset(0), last_anon_irob_id(-1), count(0)
{
pthread_mutex_init(&membership_lock, NULL);
}
PendingIROBLattice::~PendingIROBLattice()
{
{
PthreadScopedLock lock(&membership_lock);
for (size_t i = 0; i < pending_irobs.size(); i++) {
delete pending_irobs[i];
}
pending_irobs.clear();
offset = 0;
}
pthread_mutex_destroy(&membership_lock);
}
bool
PendingIROBLattice::insert(PendingIROB *pirob, bool infer_deps)
{
PthreadScopedLock lock(&membership_lock);
return insert_locked(pirob, infer_deps);
}
bool
PendingIROBLattice::insert_locked(PendingIROB *pirob, bool infer_deps)
{
assert(pirob);
if (past_irobs.contains(pirob->id)) {
dbgprintf("Inserting IROB %d failed; it's in past_irobs\n", pirob->id);
return false;
}
if (pending_irobs.empty()) {
offset = pirob->id;
}
int index = pirob->id - offset;
if (index >= 0 && index < (int)pending_irobs.size() &&
(pending_irobs[index] != NULL &&
!pending_irobs[index]->placeholder)) {
dbgprintf("Inserting IROB %d failed; I have it already??\n", pirob->id);
return false;
}
while (index < 0) {
pending_irobs.push_front(NULL);
--offset;
index = pirob->id - offset;
}
if ((int)pending_irobs.size() <= index) {
pending_irobs.resize(index+1, NULL);
}
if (pending_irobs[index]) {
// grab the placeholder's dependents and replace it
// with the real PendingIROB
assert(!pirob->placeholder);
assert(pending_irobs[index]->placeholder);
assert(pending_irobs[index]->id == pirob->id);
pirob->dependents.insert(pending_irobs[index]->dependents.begin(),
pending_irobs[index]->dependents.end());
delete pending_irobs[index];
pending_irobs[index] = pirob;
} else {
pending_irobs[index] = pirob;
}
if (pirob->placeholder) {
// pirob only exists to hold dependents until
// its replacement arrives.
return true;
}
correct_deps(pirob, infer_deps);
dbgprintf("Adding IROB %d as dependent of: [ ", pirob->id);
for (irob_id_set::iterator it = pirob->deps.begin();
it != pirob->deps.end(); it++) {
if (past_irobs.contains(*it)) {
dbgprintf_plain("(%ld) ", *it);
continue;
}
PendingIROB *dep = find_locked(*it);
if (dep) {
dbgprintf_plain("%ld ", dep->id);
dep->add_dependent(pirob->id);
} else {
dbgprintf_plain("P%ld ", *it);
dep = new PendingIROB(*it);
bool ret = insert_locked(dep);
assert(ret);
dep->add_dependent(pirob->id);
}
}
dbgprintf_plain("]\n");
++count;
return true;
}
void
PendingIROBLattice::clear()
{
PthreadScopedLock lock(&membership_lock);
pending_irobs.clear();
min_dominator_set.clear();
last_anon_irob_id = -1;
count = 0;
}
void
PendingIROBLattice::correct_deps(PendingIROB *pirob, bool infer_deps)
{
/* 1) If pirob is anonymous, add deps on all pending IROBs. */
/* 2) Otherwise, add deps on all pending anonymous IROBs. */
/* we keep around a min-dominator set of IROBs; that is,
* the minimal set of IROBs that the next anonymous IROB
* must depend on. */
if (!infer_deps) {
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
if (infer_deps) {
// skip this at the receiver. The sender infers and
// communicates deps; the receiver enforces them.
if (pirob->is_anonymous()) {
if (last_anon_irob_id >= 0 && min_dominator_set.empty()) {
pirob->add_dep(last_anon_irob_id);
} else {
pirob->deps.insert(min_dominator_set.begin(),
min_dominator_set.end());
min_dominator_set.clear();
}
last_anon_irob_id = pirob->id;
} else {
// this IROB dominates its deps, so remove them from
// the min_dominator_set before inserting it
vector<irob_id_t> isect(max(pirob->deps.size(),
min_dominator_set.size()));
vector<irob_id_t>::iterator the_end =
set_intersection(pirob->deps.begin(), pirob->deps.end(),
min_dominator_set.begin(),
min_dominator_set.end(),
isect.begin());
if (last_anon_irob_id >= 0 && isect.begin() == the_end) {
pirob->add_dep(last_anon_irob_id);
} // otherwise, it already depends on something
// that depends on the last_anon_irob
for (vector<irob_id_t>::iterator it = isect.begin();
it != the_end; ++it) {
min_dominator_set.erase(*it);
}
min_dominator_set.insert(pirob->id);
}
}
if (!infer_deps) {
/* 3) Remove already-satisfied deps. */
pirob->remove_deps_if(bind1st(mem_fun_ref(&IntSet::contains),
past_irobs));
}
}
PendingIROB *
PendingIROBLattice::find(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return find_locked(id);
}
PendingIROB *
PendingIROBLattice::find_locked(irob_id_t id)
{
//TimeFunctionBody timer("pending_irobs.find(accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size()) {
return NULL;
}
return pending_irobs[index];
}
bool
PendingIROBLattice::erase(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
//TimeFunctionBody timer("pending_irobs.erase(const_accessor)");
int index = id - offset;
if (index < 0 || index >= (int)pending_irobs.size() ||
pending_irobs[index] == NULL) {
dbgprintf("WARNING: failed to remove IROB %d from lattice!\n", id);
return false;
}
past_irobs.insert(id);
min_dominator_set.erase(id);
PendingIROB *victim = pending_irobs[index];
pending_irobs[index] = NULL; // caller must free it
while (!pending_irobs.empty() && pending_irobs[0] == NULL) {
pending_irobs.pop_front();
offset++;
}
dbgprintf("Notifying dependents of IROB %d's release: [ ", id);
for (irob_id_set::iterator it = victim->dependents.begin();
it != victim->dependents.end(); it++) {
PendingIROB *dependent = this->find_locked(*it);
if (dependent == NULL) {
dbgprintf_plain("(%ld) ", *it);
continue;
}
dbgprintf_plain("%ld ", dependent->id);
dependent->dep_satisfied(id);
}
dbgprintf_plain("]\n");
--count;
return true;
}
bool
PendingIROBLattice::past_irob_exists(irob_id_t id)
{
PthreadScopedLock lock(&membership_lock);
return past_irobs.contains(id);
}
bool
PendingIROBLattice::empty()
{
PthreadScopedLock lock(&membership_lock);
return pending_irobs.empty();
}
size_t
PendingIROBLattice::size()
{
PthreadScopedLock lock(&membership_lock);
return count;
}
IROBSchedulingData::IROBSchedulingData(irob_id_t id_, u_long seqno_)
: id(id_), seqno(seqno_)
{
/* empty */
}
bool
IROBSchedulingData::operator<(const IROBSchedulingData& other) const
{
// can implement priority here, based on
// any added scheduling hints
return (id < other.id) || (seqno < other.seqno);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include <Result.h>
#include <Format.h>
#include <Report.h>
using namespace std;
using namespace oout;
Result::Result(
const string &tag,
const map<string, string> &attributes,
const list<shared_ptr<const Result>> &nodes
)
: tag(tag), attributes(attributes), nodes(nodes)
{
}
string Result::print(const Format &format) const
{
// @todo #??:15min Use polymorphism instead if
if (tag == "testcase") {
return format.test(
attributes.at("name"),
attributes.at("failures") != "0",
0
);
}
if (tag == "testsuite") {
return format.suite(
attributes.at("name"),
0,
nodes
);
}
throw runtime_error("Wrong node type");
}
size_t Result::failures() const
{
return stoi(attributes.at("failures"));
}
<commit_msg>#68: fix todo<commit_after>// Copyright (c) 2017 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include <Result.h>
#include <Format.h>
#include <Report.h>
using namespace std;
using namespace oout;
Result::Result(
const string &tag,
const map<string, string> &attributes,
const list<shared_ptr<const Result>> &nodes
)
: tag(tag), attributes(attributes), nodes(nodes)
{
}
string Result::print(const Format &format) const
{
// @todo #68:15min Use polymorphism instead if
if (tag == "testcase") {
return format.test(
attributes.at("name"),
attributes.at("failures") != "0",
0
);
}
if (tag == "testsuite") {
return format.suite(
attributes.at("name"),
0,
nodes
);
}
throw runtime_error("Wrong node type");
}
size_t Result::failures() const
{
return stoi(attributes.at("failures"));
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Library
Module: STLRead.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <ctype.h>
#include "STLRead.hh"
#include "ByteSwap.hh"
#define ASCII 0
#define BINARY 1
void vlSTLReader::Execute()
{
FILE *fp;
vlFloatPoints *newPts;
vlCellArray *newPolys;
//
// Initialize
//
this->Initialize();
if ((fp = fopen(this->Filename, "r")) == NULL)
{
vlErrorMacro(<< "File " << this->Filename << " not found");
return;
}
newPts = new vlFloatPoints(5000,10000);
newPolys = new vlCellArray(10000,20000);
//
// Depending upon file type, read differently
//
if ( this->GetSTLFileType(fp) == ASCII )
{
if ( this->ReadASCIISTL(fp,newPts,newPolys) ) return;
}
else
{
if ( this->ReadBinarySTL(fp,newPts,newPolys) ) return;
}
vlDebugMacro(<< "Read " << newPts->GetNumberOfPoints() << " points");
vlDebugMacro(<< "Read " << newPolys->GetNumberOfCells() << " triangles");
//
// Since we sized the dynamic arrays arbitrarily to begin with
// need to resize them to fit data
//
newPts->Squeeze();
newPolys->Squeeze();
//
// Update ourselves
//
this->SetPoints(newPts);
this->SetPolys(newPolys);
}
int vlSTLReader::ReadBinarySTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
int i, numTris, pts[3];
unsigned long ulint;
unsigned short ibuff2;
char header[81];
vlByteSwap swap;
typedef struct {float n[3], v1[3], v2[3], v3[3];} facet_t;
facet_t facet;
vlDebugMacro(<< " Reading BINARY STL file");
//
// File is read to obtain raw information as well as bounding box
//
fread (header, 1, 80, fp);
fread (&ulint, 1, 4, fp);
swap.Swap4 (&ulint);
//
// Many .stl files contain bogus count. Hence we will ignore and read
// until end of file.
//
if ( (numTris = (int) ulint) <= 0 )
{
vlDebugMacro(<< "Bad binary count (" << numTris << ")");
}
for ( i=0; fread(&facet,48,1,fp) > 0; i++ )
{
fread(&ibuff2,2,1,fp); /* read extra junk */
swap.Swap4 (facet.n);
swap.Swap4 (facet.n+1);
swap.Swap4 (facet.n+2);
swap.Swap4 (facet.v1);
swap.Swap4 (facet.v1+1);
swap.Swap4 (facet.v1+2);
pts[0] = newPts->InsertNextPoint(facet.v1);
swap.Swap4 (facet.v2);
swap.Swap4 (facet.v2+1);
swap.Swap4 (facet.v2+2);
pts[1] = newPts->InsertNextPoint(facet.v2);
swap.Swap4 (facet.v3);
swap.Swap4 (facet.v3+1);
swap.Swap4 (facet.v3+2);
pts[2] = newPts->InsertNextPoint(facet.v3);
newPolys->InsertNextCell(3,pts);
if ( (i % 5000) == 0 && i != 0 )
vlDebugMacro(<< "triangle# " << i);
}
return 0;
}
int vlSTLReader::ReadASCIISTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
char line[256];
float x[3];
int pts[3];
vlDebugMacro(<< " Reading ASCII STL file");
//
// Ingest header and junk to get to first vertex
//
fgets (line, 255, fp);
/*
* Go into loop, reading facet normal and vertices
*/
while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF)
{
fgets (line, 255, fp);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[0] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[1] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[2] = newPts->InsertNextPoint(x);
fgets (line, 255, fp); /* end loop */
fgets (line, 255, fp); /* end facet */
newPolys->InsertNextCell(3,pts);
if ( (newPolys->GetNumberOfCells() % 5000) == 0 )
vlDebugMacro(<< "triangle# " << newPolys->GetNumberOfCells());
}
return 0;
}
int vlSTLReader::GetSTLFileType(FILE *fp)
{
char header[256];
int type, i;
//
// Read a little from the file to figure what type it is.
//
fgets (header, 255, fp); /* first line is always ascii */
fgets (header, 18, fp);
for (i=0, type=ASCII; i<17 && type == ASCII; i++) // don't test \0
if ( ! isprint(header[i]) )
type = BINARY;
//
// Reset file for reading
//
rewind (fp);
return type;
}
void vlSTLReader::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlSTLReader::GetClassName()))
{
vlPolySource::PrintSelf(os,indent);
os << indent << "Filename: " << this->Filename << "\n";
}
}
<commit_msg>now closes the file<commit_after>/*=========================================================================
Program: Visualization Library
Module: STLRead.cc
Language: C++
Date: $Date$
Version: $Revision$
This file is part of the Visualization Library. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994
=========================================================================*/
#include <ctype.h>
#include "STLRead.hh"
#include "ByteSwap.hh"
#define ASCII 0
#define BINARY 1
void vlSTLReader::Execute()
{
FILE *fp;
vlFloatPoints *newPts;
vlCellArray *newPolys;
//
// Initialize
//
this->Initialize();
if ((fp = fopen(this->Filename, "r")) == NULL)
{
vlErrorMacro(<< "File " << this->Filename << " not found");
return;
}
newPts = new vlFloatPoints(5000,10000);
newPolys = new vlCellArray(10000,20000);
//
// Depending upon file type, read differently
//
if ( this->GetSTLFileType(fp) == ASCII )
{
if ( this->ReadASCIISTL(fp,newPts,newPolys) ) return;
}
else
{
if ( this->ReadBinarySTL(fp,newPts,newPolys) ) return;
}
vlDebugMacro(<< "Read " << newPts->GetNumberOfPoints() << " points");
vlDebugMacro(<< "Read " << newPolys->GetNumberOfCells() << " triangles");
fclose(fp);
//
// Since we sized the dynamic arrays arbitrarily to begin with
// need to resize them to fit data
//
newPts->Squeeze();
newPolys->Squeeze();
//
// Update ourselves
//
this->SetPoints(newPts);
this->SetPolys(newPolys);
}
int vlSTLReader::ReadBinarySTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
int i, numTris, pts[3];
unsigned long ulint;
unsigned short ibuff2;
char header[81];
vlByteSwap swap;
typedef struct {float n[3], v1[3], v2[3], v3[3];} facet_t;
facet_t facet;
vlDebugMacro(<< " Reading BINARY STL file");
//
// File is read to obtain raw information as well as bounding box
//
fread (header, 1, 80, fp);
fread (&ulint, 1, 4, fp);
swap.Swap4 (&ulint);
//
// Many .stl files contain bogus count. Hence we will ignore and read
// until end of file.
//
if ( (numTris = (int) ulint) <= 0 )
{
vlDebugMacro(<< "Bad binary count (" << numTris << ")");
}
for ( i=0; fread(&facet,48,1,fp) > 0; i++ )
{
fread(&ibuff2,2,1,fp); /* read extra junk */
swap.Swap4 (facet.n);
swap.Swap4 (facet.n+1);
swap.Swap4 (facet.n+2);
swap.Swap4 (facet.v1);
swap.Swap4 (facet.v1+1);
swap.Swap4 (facet.v1+2);
pts[0] = newPts->InsertNextPoint(facet.v1);
swap.Swap4 (facet.v2);
swap.Swap4 (facet.v2+1);
swap.Swap4 (facet.v2+2);
pts[1] = newPts->InsertNextPoint(facet.v2);
swap.Swap4 (facet.v3);
swap.Swap4 (facet.v3+1);
swap.Swap4 (facet.v3+2);
pts[2] = newPts->InsertNextPoint(facet.v3);
newPolys->InsertNextCell(3,pts);
if ( (i % 5000) == 0 && i != 0 )
vlDebugMacro(<< "triangle# " << i);
}
return 0;
}
int vlSTLReader::ReadASCIISTL(FILE *fp, vlFloatPoints *newPts, vlCellArray *newPolys)
{
char line[256];
float x[3];
int pts[3];
vlDebugMacro(<< " Reading ASCII STL file");
//
// Ingest header and junk to get to first vertex
//
fgets (line, 255, fp);
/*
* Go into loop, reading facet normal and vertices
*/
while (fscanf(fp,"%*s %*s %f %f %f\n", x, x+1, x+2)!=EOF)
{
fgets (line, 255, fp);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[0] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[1] = newPts->InsertNextPoint(x);
fscanf (fp, "%*s %f %f %f\n", x,x+1,x+2);
pts[2] = newPts->InsertNextPoint(x);
fgets (line, 255, fp); /* end loop */
fgets (line, 255, fp); /* end facet */
newPolys->InsertNextCell(3,pts);
if ( (newPolys->GetNumberOfCells() % 5000) == 0 )
vlDebugMacro(<< "triangle# " << newPolys->GetNumberOfCells());
}
return 0;
}
int vlSTLReader::GetSTLFileType(FILE *fp)
{
char header[256];
int type, i;
//
// Read a little from the file to figure what type it is.
//
fgets (header, 255, fp); /* first line is always ascii */
fgets (header, 18, fp);
for (i=0, type=ASCII; i<17 && type == ASCII; i++) // don't test \0
if ( ! isprint(header[i]) )
type = BINARY;
//
// Reset file for reading
//
rewind (fp);
return type;
}
void vlSTLReader::PrintSelf(ostream& os, vlIndent indent)
{
if (this->ShouldIPrint(vlSTLReader::GetClassName()))
{
vlPolySource::PrintSelf(os,indent);
os << indent << "Filename: " << this->Filename << "\n";
}
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.31
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "EnsemblePreprocessor.h"
#include "System.h"
#include "CalculateEnergy.h"
#include "EwaldCached.h"
#include "Ewald.h"
#include "NoEwald.h"
#include "EnergyTypes.h"
#include "Setup.h" //For source of setup data.
#include "ConfigSetup.h" //For types directly read from config. file
#include "StaticVals.h"
#include "Molecules.h" //For indexing molecules.
#include "MoveConst.h" //For array of move objects.
#include "MoveBase.h" //For move bases....
#include "MoleculeTransfer.h"
#include "IntraSwap.h"
#include "MultiParticle.h"
#include "Regrowth.h"
System::System(StaticVals& statics) :
statV(statics),
#ifdef VARIABLE_VOLUME
boxDimRef(*BoxDim(statics.isOrthogonal)),
#else
boxDimRef(*statics.GetBoxDim()),
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
molLookupRef(molLookup),
#else
molLookupRef(statics.molLookup),
#endif
prng(molLookupRef),
coordinates(boxDimRef, com, molLookupRef, prng, statics.mol),
com(boxDimRef, coordinates, molLookupRef, statics.mol),
moveSettings(boxDimRef), cellList(statics.mol, boxDimRef),
calcEnergy(statics, *this)
{
calcEwald = NULL;
}
System::~System()
{
#ifdef VARIABLE_VOLUME
if (boxDimensions != NULL)
delete boxDimensions;
#endif
if (calcEwald != NULL)
delete calcEwald;
delete moves[mv::DISPLACE];
delete moves[mv::ROTATE];
delete moves[mv::INTRA_SWAP];
delete moves[mv::REGROWTH];
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
delete moves[mv::VOL_TRANSFER];
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
delete moves[mv::MOL_TRANSFER];
#endif
}
void System::Init(Setup const& set)
{
prng.Init(set.prng.prngMaker.prng);
#ifdef VARIABLE_VOLUME
boxDimensions->Init(set.config.in.restart,
set.config.sys.volume, set.pdb.cryst,
statV.forcefield.rCut,
statV.forcefield.rCutSq);
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
molLookup.Init(statV.mol, set.pdb.atoms);
#endif
moveSettings.Init(statV, set.pdb.remarks);
//Note... the following calls use box iterators, so must come after
//the molecule lookup initialization, in case we're in a constant
//particle/molecule ensemble, e.g. NVT
coordinates.InitFromPDB(set.pdb.atoms);
com.CalcCOM();
// Allocate space for atom forces
atomForceRef.Init(set.pdb.atoms.beta.size());
molForceRef.Init(com.Count());
// Allocate space for reciprocate force
atomForceRecRef.Init(set.pdb.atoms.beta.size());
molForceRecRef.Init(com.Count());
cellList.SetCutoff(statV.forcefield.rCut);
cellList.GridAll(boxDimRef, coordinates, molLookupRef);
//check if we have to use cached version of ewlad or not.
bool ewald = set.config.sys.elect.ewald;
bool cached = set.config.sys.elect.cache;
#ifdef GOMC_CUDA
if(ewald)
calcEwald = new Ewald(statV, *this);
else
calcEwald = new NoEwald(statV, *this);
#else
if (ewald && cached)
calcEwald = new EwaldCached(statV, *this);
else if (ewald && !cached)
calcEwald = new Ewald(statV, *this);
else
calcEwald = new NoEwald(statV, *this);
#endif
calcEnergy.Init(*this);
calcEwald->Init();
potential = calcEnergy.SystemTotal();
InitMoves();
for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++)
moveTime[m] = 0.0;
}
void System::InitMoves()
{
moves[mv::DISPLACE] = new Translate(*this, statV);
moves[mv::MULTIPARTICLE] = new MultiParticle(*this, statV);
moves[mv::ROTATE] = new Rotate(*this, statV);
moves[mv::INTRA_SWAP] = new IntraSwap(*this, statV);
moves[mv::REGROWTH] = new Regrowth(*this, statV);
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
moves[mv::VOL_TRANSFER] = new VolumeTransfer(*this, statV);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
moves[mv::MOL_TRANSFER] = new MoleculeTransfer(*this, statV);
#endif
}
void System::RecalculateTrajectory(Setup &set, uint frameNum)
{
set.pdb.Init(set.config.in.restart, set.config.in.files.pdb.name, frameNum);
statV.InitOver(set, *this);
#ifdef VARIABLE_PARTICLE_NUMBER
molLookup.Init(statV.mol, set.pdb.atoms);
#endif
coordinates.InitFromPDB(set.pdb.atoms);
com.CalcCOM();
cellList.GridAll(boxDimRef, coordinates, molLookupRef);
calcEnergy.Init(*this);
calcEwald->Init();
potential = calcEnergy.SystemTotal();
}
void System::ChooseAndRunMove(const uint step)
{
double draw = 0;
uint majKind = 0;
PickMove(majKind, draw);
time.SetStart();
RunMove(majKind, draw, step);
time.SetStop();
moveTime[majKind] += time.GetTimDiff();
}
void System::PickMove(uint & kind, double & draw)
{
prng.PickArbDist(kind, draw, statV.movePerc, statV.totalPerc,
mv::MOVE_KINDS_TOTAL);
}
void System::RunMove(uint majKind, double draw, const uint step)
{
//return now if move targets molecule and there's none in that box.
uint rejectState = SetParams(majKind, draw);
//If single atom, redo move as displacement
if (rejectState == mv::fail_state::ROTATE_ON_SINGLE_ATOM) {
majKind = mv::DISPLACE;
Translate * disp = static_cast<Translate *>(moves[mv::DISPLACE]);
Rotate * rot = static_cast<Rotate *>(moves[mv::ROTATE]);
rejectState = disp->ReplaceRot(*rot);
}
if (rejectState == mv::fail_state::NO_FAIL)
rejectState = Transform(majKind);
if (rejectState == mv::fail_state::NO_FAIL)
CalcEn(majKind);
Accept(majKind, rejectState, step);
}
uint System::SetParams(const uint kind, const double draw)
{
return moves[kind]->Prep(draw, statV.movePerc[kind]);
}
uint System::Transform(const uint kind)
{
return moves[kind]->Transform();
}
void System::CalcEn(const uint kind)
{
moves[kind]->CalcEn();
}
void System::Accept(const uint kind, const uint rejectState, const uint step)
{
moves[kind]->Accept(rejectState, step);
}
void System::PrintTime()
{
//std::cout << "MC moves Execution time:\n";
printf("%-30s %10.4f sec.\n", "Displacement:", moveTime[mv::DISPLACE]);
printf("%-30s %10.4f sec.\n", "Rotation:", moveTime[mv::ROTATE]);
printf("%-30s %10.4f sec.\n", "Intra-Swap:", moveTime[mv::INTRA_SWAP]);
printf("%-30s %10.4f sec.\n", "Regrowth:", moveTime[mv::REGROWTH]);
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
printf("%-30s %10.4f sec.\n", "Molecule-Transfer:",
moveTime[mv::MOL_TRANSFER]);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
printf("%-30s %10.4f sec.\n", "Volume-Transfer:", moveTime[mv::VOL_TRANSFER]);
#endif
}
<commit_msg>Added MultiParticle time print at the end of the simulation<commit_after>/*******************************************************************************
GPU OPTIMIZED MONTE CARLO (GOMC) 2.31
Copyright (C) 2018 GOMC Group
A copy of the GNU General Public License can be found in the COPYRIGHT.txt
along with this program, also can be found at <http://www.gnu.org/licenses/>.
********************************************************************************/
#include "EnsemblePreprocessor.h"
#include "System.h"
#include "CalculateEnergy.h"
#include "EwaldCached.h"
#include "Ewald.h"
#include "NoEwald.h"
#include "EnergyTypes.h"
#include "Setup.h" //For source of setup data.
#include "ConfigSetup.h" //For types directly read from config. file
#include "StaticVals.h"
#include "Molecules.h" //For indexing molecules.
#include "MoveConst.h" //For array of move objects.
#include "MoveBase.h" //For move bases....
#include "MoleculeTransfer.h"
#include "IntraSwap.h"
#include "MultiParticle.h"
#include "Regrowth.h"
System::System(StaticVals& statics) :
statV(statics),
#ifdef VARIABLE_VOLUME
boxDimRef(*BoxDim(statics.isOrthogonal)),
#else
boxDimRef(*statics.GetBoxDim()),
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
molLookupRef(molLookup),
#else
molLookupRef(statics.molLookup),
#endif
prng(molLookupRef),
coordinates(boxDimRef, com, molLookupRef, prng, statics.mol),
com(boxDimRef, coordinates, molLookupRef, statics.mol),
moveSettings(boxDimRef), cellList(statics.mol, boxDimRef),
calcEnergy(statics, *this)
{
calcEwald = NULL;
}
System::~System()
{
#ifdef VARIABLE_VOLUME
if (boxDimensions != NULL)
delete boxDimensions;
#endif
if (calcEwald != NULL)
delete calcEwald;
delete moves[mv::DISPLACE];
delete moves[mv::ROTATE];
delete moves[mv::INTRA_SWAP];
delete moves[mv::REGROWTH];
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
delete moves[mv::VOL_TRANSFER];
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
delete moves[mv::MOL_TRANSFER];
#endif
}
void System::Init(Setup const& set)
{
prng.Init(set.prng.prngMaker.prng);
#ifdef VARIABLE_VOLUME
boxDimensions->Init(set.config.in.restart,
set.config.sys.volume, set.pdb.cryst,
statV.forcefield.rCut,
statV.forcefield.rCutSq);
#endif
#ifdef VARIABLE_PARTICLE_NUMBER
molLookup.Init(statV.mol, set.pdb.atoms);
#endif
moveSettings.Init(statV, set.pdb.remarks);
//Note... the following calls use box iterators, so must come after
//the molecule lookup initialization, in case we're in a constant
//particle/molecule ensemble, e.g. NVT
coordinates.InitFromPDB(set.pdb.atoms);
com.CalcCOM();
// Allocate space for atom forces
atomForceRef.Init(set.pdb.atoms.beta.size());
molForceRef.Init(com.Count());
// Allocate space for reciprocate force
atomForceRecRef.Init(set.pdb.atoms.beta.size());
molForceRecRef.Init(com.Count());
cellList.SetCutoff(statV.forcefield.rCut);
cellList.GridAll(boxDimRef, coordinates, molLookupRef);
//check if we have to use cached version of ewlad or not.
bool ewald = set.config.sys.elect.ewald;
bool cached = set.config.sys.elect.cache;
#ifdef GOMC_CUDA
if(ewald)
calcEwald = new Ewald(statV, *this);
else
calcEwald = new NoEwald(statV, *this);
#else
if (ewald && cached)
calcEwald = new EwaldCached(statV, *this);
else if (ewald && !cached)
calcEwald = new Ewald(statV, *this);
else
calcEwald = new NoEwald(statV, *this);
#endif
calcEnergy.Init(*this);
calcEwald->Init();
potential = calcEnergy.SystemTotal();
InitMoves();
for(uint m = 0; m < mv::MOVE_KINDS_TOTAL; m++)
moveTime[m] = 0.0;
}
void System::InitMoves()
{
moves[mv::DISPLACE] = new Translate(*this, statV);
moves[mv::MULTIPARTICLE] = new MultiParticle(*this, statV);
moves[mv::ROTATE] = new Rotate(*this, statV);
moves[mv::INTRA_SWAP] = new IntraSwap(*this, statV);
moves[mv::REGROWTH] = new Regrowth(*this, statV);
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
moves[mv::VOL_TRANSFER] = new VolumeTransfer(*this, statV);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
moves[mv::MOL_TRANSFER] = new MoleculeTransfer(*this, statV);
#endif
}
void System::RecalculateTrajectory(Setup &set, uint frameNum)
{
set.pdb.Init(set.config.in.restart, set.config.in.files.pdb.name, frameNum);
statV.InitOver(set, *this);
#ifdef VARIABLE_PARTICLE_NUMBER
molLookup.Init(statV.mol, set.pdb.atoms);
#endif
coordinates.InitFromPDB(set.pdb.atoms);
com.CalcCOM();
cellList.GridAll(boxDimRef, coordinates, molLookupRef);
calcEnergy.Init(*this);
calcEwald->Init();
potential = calcEnergy.SystemTotal();
}
void System::ChooseAndRunMove(const uint step)
{
double draw = 0;
uint majKind = 0;
PickMove(majKind, draw);
time.SetStart();
RunMove(majKind, draw, step);
time.SetStop();
moveTime[majKind] += time.GetTimDiff();
}
void System::PickMove(uint & kind, double & draw)
{
prng.PickArbDist(kind, draw, statV.movePerc, statV.totalPerc,
mv::MOVE_KINDS_TOTAL);
}
void System::RunMove(uint majKind, double draw, const uint step)
{
//return now if move targets molecule and there's none in that box.
uint rejectState = SetParams(majKind, draw);
//If single atom, redo move as displacement
if (rejectState == mv::fail_state::ROTATE_ON_SINGLE_ATOM) {
majKind = mv::DISPLACE;
Translate * disp = static_cast<Translate *>(moves[mv::DISPLACE]);
Rotate * rot = static_cast<Rotate *>(moves[mv::ROTATE]);
rejectState = disp->ReplaceRot(*rot);
}
if (rejectState == mv::fail_state::NO_FAIL)
rejectState = Transform(majKind);
if (rejectState == mv::fail_state::NO_FAIL)
CalcEn(majKind);
Accept(majKind, rejectState, step);
}
uint System::SetParams(const uint kind, const double draw)
{
return moves[kind]->Prep(draw, statV.movePerc[kind]);
}
uint System::Transform(const uint kind)
{
return moves[kind]->Transform();
}
void System::CalcEn(const uint kind)
{
moves[kind]->CalcEn();
}
void System::Accept(const uint kind, const uint rejectState, const uint step)
{
moves[kind]->Accept(rejectState, step);
}
void System::PrintTime()
{
//std::cout << "MC moves Execution time:\n";
printf("%-30s %10.4f sec.\n", "Displacement:", moveTime[mv::DISPLACE]);
printf("%-30s %10.4f sec.\n", "Rotation:", moveTime[mv::ROTATE]);
printf("%-30s %10.4f sec.\n", "Intra-Swap:", moveTime[mv::INTRA_SWAP]);
printf("%-30s %10.4f sec.\n", "Regrowth:", moveTime[mv::REGROWTH]);
printf("%-30s %10.4f sec.\n", "MultiParticle:", moveTime[mv::MULTIPARTICLE]);
#if ENSEMBLE == GEMC || ENSEMBLE == GCMC
printf("%-30s %10.4f sec.\n", "Molecule-Transfer:",
moveTime[mv::MOL_TRANSFER]);
#endif
#if ENSEMBLE == GEMC || ENSEMBLE == NPT
printf("%-30s %10.4f sec.\n", "Volume-Transfer:", moveTime[mv::VOL_TRANSFER]);
#endif
}
<|endoftext|>
|
<commit_before>#include "config.h"
#include "Window.h"
#include "Global.h"
#include "Input.h"
#include "Egl.h"
#include <GL/gl.h>
Window::Window(int width, int height)
: Rectangle(0, 0, width, height)
, running(true)
, fullscreen(false) {
display = new Display;
global = new Global(display->get_registry());
display->roundtrip();
input = new Input(this, global->seat);
surface = global->compositor->create_surface();
shellsurface = global->shell->get_shell_surface(surface);
static const struct wl_shell_surface_listener shell_surface_listener = {
Window::HandlePing,
Window::HandleConfigure,
Window::HandlePopupDone
};
shellsurface->add_listener((const struct wl_listener *)&shell_surface_listener, this);
shellsurface->set_title("cairo-wayland-cpp");
shellsurface->set_toplevel();
egl = new Egl(display->cobj);
eglwindow = egl->CreateWindow(surface->cobj, width, height);
// Create a pixmap font from a TrueType file.
font = new FTGLTextureFont("/usr/share/fonts/TTF/DejaVuSans.ttf");
// If something went wrong, bail out.
if(font->Error())
throw "Could no load font";
// Set the font size and render a small text.
font->FaceSize(14);
}
Window::~Window() {
delete eglwindow;
delete egl;
delete shellsurface;
delete surface;
delete input;
delete global;
delete display;
}
void Window::HandlePing(void *data,
struct wl_shell_surface *shell_surface,
uint32_t serial){
Window *window = static_cast<Window *>(data);
window->shellsurface->pong(serial);
}
void Window::HandleConfigure(void *data,
struct wl_shell_surface *shell_surface,
uint32_t edges,
int32_t width,
int32_t height){
Window *window = static_cast<Window *>(data);
window->Resize(width, height);
}
void Window::HandlePopupDone(void *data,
struct wl_shell_surface *shell_surface){
//Window *window = static_cast<Window *>(data);
}
void Window::Fullscreen(bool value){
if(fullscreen == value)
return;
fullscreen = value;
if (value){
shellsurface->set_fullscreen(ShellSurface::FULLSCREEN_METHOD_DEFAULT,0,NULL);
display->dispatch(); /* get configure event and update window size */
} else {
shellsurface->set_toplevel();
Resize(oldwidth, oldheight);
}
}
void Window::Resize(int w, int h){
if(SetSize(w, h)){
eglwindow->Resize(w, h);
glViewport(0, 0, w, h);
}
}
void Window::run(){
float ratio;
int width, height;
char str[10];
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
while(running) {
display->dispatch();
GetSize(&width, &height); /* after configure event */
ratio = width / (float) height;
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width,
0.0f, height,
-10000.0f, 10000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, (height - font->Ascender()) * 1.0f, 0.0f);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
sprintf(str,"%.1f fps", eglwindow->fps);
font->Render(str);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef((input->pointer_x / width) * 360.0f, 0.f, 1.f, 0.f);
glRotatef((input->pointer_y / height) * 360.0f, 1.f, 0.f, 0.f);
//Multi-colored side - FRONT
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 ); glVertex3f( 0.5, -0.5, -0.5 ); // P1 is red
glColor3f( 0.0, 1.0, 0.0 ); glVertex3f( 0.5, 0.5, -0.5 ); // P2 is green
glColor3f( 0.0, 0.0, 1.0 ); glVertex3f( -0.5, 0.5, -0.5 ); // P3 is blue
glColor3f( 1.0, 0.0, 1.0 ); glVertex3f( -0.5, -0.5, -0.5 ); // P4 is purple
glEnd();
// White side - BACK
glBegin(GL_POLYGON);
glColor3f( 1.0, 1.0, 1.0 );
glVertex3f( 0.5, -0.5, 0.5 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glVertex3f( -0.5, -0.5, 0.5 );
glEnd();
// Purple side - RIGHT
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 1.0 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( 0.5, -0.5, 0.5 );
glEnd();
// Green side - LEFT
glBegin(GL_POLYGON);
glColor3f( 0.0, 1.0, 0.0 );
glVertex3f( -0.5, -0.5, 0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glVertex3f( -0.5, -0.5, -0.5 );
glEnd();
// Blue side - TOP
glBegin(GL_POLYGON);
glColor3f( 0.0, 0.0, 1.0 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glEnd();
// Red side - BOTTOM
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, -0.5, 0.5 );
glVertex3f( -0.5, -0.5, 0.5 );
glVertex3f( -0.5, -0.5, -0.5 );
glEnd();
eglwindow->SwapBuffers();
}
}
<commit_msg>cleanup memory for font object<commit_after>#include "config.h"
#include "Window.h"
#include "Global.h"
#include "Input.h"
#include "Egl.h"
#include <GL/gl.h>
Window::Window(int width, int height)
: Rectangle(0, 0, width, height)
, running(true)
, fullscreen(false) {
display = new Display;
global = new Global(display->get_registry());
display->roundtrip();
input = new Input(this, global->seat);
surface = global->compositor->create_surface();
shellsurface = global->shell->get_shell_surface(surface);
static const struct wl_shell_surface_listener shell_surface_listener = {
Window::HandlePing,
Window::HandleConfigure,
Window::HandlePopupDone
};
shellsurface->add_listener((const struct wl_listener *)&shell_surface_listener, this);
shellsurface->set_title("cairo-wayland-cpp");
shellsurface->set_toplevel();
egl = new Egl(display->cobj);
eglwindow = egl->CreateWindow(surface->cobj, width, height);
font = new FTGLTextureFont("/usr/share/fonts/TTF/DejaVuSans.ttf");
if(font->Error())
throw "Could no load font";
font->FaceSize(14);
}
Window::~Window() {
delete font;
delete eglwindow;
delete egl;
delete shellsurface;
delete surface;
delete input;
delete global;
delete display;
}
void Window::HandlePing(void *data,
struct wl_shell_surface *shell_surface,
uint32_t serial){
Window *window = static_cast<Window *>(data);
window->shellsurface->pong(serial);
}
void Window::HandleConfigure(void *data,
struct wl_shell_surface *shell_surface,
uint32_t edges,
int32_t width,
int32_t height){
Window *window = static_cast<Window *>(data);
window->Resize(width, height);
}
void Window::HandlePopupDone(void *data,
struct wl_shell_surface *shell_surface){
//Window *window = static_cast<Window *>(data);
}
void Window::Fullscreen(bool value){
if(fullscreen == value)
return;
fullscreen = value;
if (value){
shellsurface->set_fullscreen(ShellSurface::FULLSCREEN_METHOD_DEFAULT,0,NULL);
display->dispatch(); /* get configure event and update window size */
} else {
shellsurface->set_toplevel();
Resize(oldwidth, oldheight);
}
}
void Window::Resize(int w, int h){
if(SetSize(w, h)){
eglwindow->Resize(w, h);
glViewport(0, 0, w, h);
}
}
void Window::run(){
float ratio;
int width, height;
char str[10];
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
while(running) {
display->dispatch();
GetSize(&width, &height); /* after configure event */
ratio = width / (float) height;
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, width,
0.0f, height,
-10000.0f, 10000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, (height - font->Ascender()) * 1.0f, 0.0f);
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
sprintf(str,"%.1f fps", eglwindow->fps);
font->Render(str);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef((input->pointer_x / width) * 360.0f, 0.f, 1.f, 0.f);
glRotatef((input->pointer_y / height) * 360.0f, 1.f, 0.f, 0.f);
//Multi-colored side - FRONT
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 ); glVertex3f( 0.5, -0.5, -0.5 ); // P1 is red
glColor3f( 0.0, 1.0, 0.0 ); glVertex3f( 0.5, 0.5, -0.5 ); // P2 is green
glColor3f( 0.0, 0.0, 1.0 ); glVertex3f( -0.5, 0.5, -0.5 ); // P3 is blue
glColor3f( 1.0, 0.0, 1.0 ); glVertex3f( -0.5, -0.5, -0.5 ); // P4 is purple
glEnd();
// White side - BACK
glBegin(GL_POLYGON);
glColor3f( 1.0, 1.0, 1.0 );
glVertex3f( 0.5, -0.5, 0.5 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glVertex3f( -0.5, -0.5, 0.5 );
glEnd();
// Purple side - RIGHT
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 1.0 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( 0.5, -0.5, 0.5 );
glEnd();
// Green side - LEFT
glBegin(GL_POLYGON);
glColor3f( 0.0, 1.0, 0.0 );
glVertex3f( -0.5, -0.5, 0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glVertex3f( -0.5, -0.5, -0.5 );
glEnd();
// Blue side - TOP
glBegin(GL_POLYGON);
glColor3f( 0.0, 0.0, 1.0 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glEnd();
// Red side - BOTTOM
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, -0.5, 0.5 );
glVertex3f( -0.5, -0.5, 0.5 );
glVertex3f( -0.5, -0.5, -0.5 );
glEnd();
eglwindow->SwapBuffers();
}
}
<|endoftext|>
|
<commit_before>#include <stdexcept>
#include "ClassFile.h"
#include "OutputStream.h"
namespace
{
void writeUnsigned(OutputStream* fp, int n, uint32_t val)
{
uint8_t buf[16];
for(int i = n; i >= 0; --i)
buf[i] = (val >> (8 * (n - i - 1))) & 0xff;
fp->write(buf, n);
}
void writeWord(OutputStream* fp, uint16_t val)
{
writeUnsigned(fp, 2, val);
}
struct Writer
{
Writer(ClassFile const& c) : m_class(c)
{
}
ClassFile const& m_class;
void write(OutputStream* fp)
{
writeHeader(fp);
writeConstPool(fp);
writeFlagAndClass(fp);
writeInterface(fp);
writeField(fp);
writeMethod(fp);
writeAttr(fp);
}
void writeHeader(OutputStream* fp)
{
writeUnsigned(fp, 4, 0xCAFEBABE);
writeWord(fp, m_class.minor_version);
writeWord(fp, m_class.major_version);
}
void writeConstPool(OutputStream* fp)
{
writeWord(fp, m_class.const_pool_count);
for(size_t i = 1; i < m_class.const_pool_count; ++i) // no use index 0
{
writeUnsigned(fp, 1, (int)m_class.const_pool[i].tag);
writeConstPoolContents(m_class.const_pool[i], fp);
// those are take two entries
if(m_class.const_pool[i].tag == CONSTANT::Long
|| m_class.const_pool[i].tag == CONSTANT::Double)
++i;
}
}
void writeConstPoolContents(const ConstPoolInfo& info, OutputStream* fp)
{
switch(info.tag)
{
case CONSTANT::Fieldref:
case CONSTANT::Methodref:
case CONSTANT::InterfaceMethodref:
writeWord(fp, info.class_index);
writeWord(fp, info.name_and_type_index);
break;
case CONSTANT::InvokeDynamic:
fp->write(info.info, 2);
fp->write(&info.info[2], 2);
break;
case CONSTANT::NameAndType:
writeWord(fp, info.name_index);
writeWord(fp, info.descriptor_index);
break;
case CONSTANT::Class:
writeWord(fp, info.name_index);
break;
case CONSTANT::String:
case CONSTANT::MethodType:
fp->write(info.info, 2);
break;
case CONSTANT::Integer:
case CONSTANT::Float:
fp->write(info.info, 4);
break;
case CONSTANT::Long:
case CONSTANT::Double:
fp->write(info.info, 4);
fp->write(&info.info[4], 4);
break;
case CONSTANT::Utf8:
{
auto const len = info.utf8.size();
writeWord(fp, len);
fp->write((uint8_t*)info.utf8.data(), len);
}
break;
case CONSTANT::MethodHandle:
fp->write(info.info, 1);
fp->write(&info.info[1], 2);
break;
default:
throw runtime_error("unsupported constant pool tag");
}
}
void writeFlagAndClass(OutputStream* fp)
{
writeWord(fp, m_class.access_flags);
writeWord(fp, m_class.this_class);
writeWord(fp, m_class.super_class);
}
void writeInterface(OutputStream* fp)
{
writeWord(fp, m_class.interfaces.size());
for(auto& itf : m_class.interfaces)
writeWord(fp, itf);
}
void writeField(OutputStream* fp)
{
writeWord(fp, m_class.fields.size());
for(auto& field : m_class.fields)
{
writeWord(fp, field.access_flags);
writeWord(fp, field.name_index);
writeWord(fp, field.descriptor_index);
writeWord(fp, field.attrs_count);
writeAttrInner(field.attrs, field.attrs_count, fp);
}
}
void writeMethod(OutputStream* fp)
{
writeWord(fp, m_class.methods.size());
for(auto& method : m_class.methods)
{
writeWord(fp, method.access_flags);
writeWord(fp, method.name_index);
writeWord(fp, method.descriptor_index);
writeWord(fp, method.attrs_count);
writeAttrInner(method.attrs, method.attrs_count, fp);
}
}
void writeAttr(OutputStream* fp)
{
writeWord(fp, m_class.attrs_count);
writeAttrInner(m_class.attrs, m_class.attrs_count, fp);
}
void writeAttrInner(const vector<AttrInfo>& attributes, size_t num, OutputStream* fp)
{
for(auto& attr : attributes)
{
writeWord(fp, attr.attr_name_index);
writeUnsigned(fp, 4, attr.attr_len);
for(auto& inf : attr.info)
fp->write(&inf, 1);
}
}
};
}
// module entry point
void writeClass(OutputStream* fp, ClassFile const& class_)
{
Writer p(class_);
p.write(fp);
}
<commit_msg>Dead code elimination<commit_after>#include <stdexcept>
#include "ClassFile.h"
#include "OutputStream.h"
namespace
{
void writeUnsigned(OutputStream* fp, int n, uint32_t val)
{
uint8_t buf[16];
for(int i = n; i >= 0; --i)
buf[i] = (val >> (8 * (n - i - 1))) & 0xff;
fp->write(buf, n);
}
void writeWord(OutputStream* fp, uint16_t val)
{
writeUnsigned(fp, 2, val);
}
struct Writer
{
Writer(ClassFile const& c) : m_class(c)
{
}
ClassFile const& m_class;
void write(OutputStream* fp)
{
writeHeader(fp);
writeConstPool(fp);
writeFlagAndClass(fp);
writeInterface(fp);
writeField(fp);
writeMethod(fp);
writeAttr(fp);
}
void writeHeader(OutputStream* fp)
{
writeUnsigned(fp, 4, 0xCAFEBABE);
writeWord(fp, m_class.minor_version);
writeWord(fp, m_class.major_version);
}
void writeConstPool(OutputStream* fp)
{
writeWord(fp, m_class.const_pool_count);
for(size_t i = 1; i < m_class.const_pool_count; ++i) // no use index 0
{
writeUnsigned(fp, 1, (int)m_class.const_pool[i].tag);
writeConstPoolContents(m_class.const_pool[i], fp);
// those are take two entries
if(m_class.const_pool[i].tag == CONSTANT::Long
|| m_class.const_pool[i].tag == CONSTANT::Double)
++i;
}
}
void writeConstPoolContents(const ConstPoolInfo& info, OutputStream* fp)
{
switch(info.tag)
{
case CONSTANT::Fieldref:
case CONSTANT::Methodref:
case CONSTANT::InterfaceMethodref:
writeWord(fp, info.class_index);
writeWord(fp, info.name_and_type_index);
break;
case CONSTANT::InvokeDynamic:
fp->write(info.info, 2);
fp->write(&info.info[2], 2);
break;
case CONSTANT::NameAndType:
writeWord(fp, info.name_index);
writeWord(fp, info.descriptor_index);
break;
case CONSTANT::Class:
writeWord(fp, info.name_index);
break;
case CONSTANT::String:
case CONSTANT::MethodType:
fp->write(info.info, 2);
break;
case CONSTANT::Integer:
case CONSTANT::Float:
fp->write(info.info, 4);
break;
case CONSTANT::Long:
case CONSTANT::Double:
fp->write(info.info, 4);
fp->write(&info.info[4], 4);
break;
case CONSTANT::Utf8:
{
auto const len = info.utf8.size();
writeWord(fp, len);
fp->write((uint8_t*)info.utf8.data(), len);
}
break;
case CONSTANT::MethodHandle:
fp->write(info.info, 1);
fp->write(&info.info[1], 2);
break;
default:
throw runtime_error("unsupported constant pool tag");
}
}
void writeFlagAndClass(OutputStream* fp)
{
writeWord(fp, m_class.access_flags);
writeWord(fp, m_class.this_class);
writeWord(fp, m_class.super_class);
}
void writeInterface(OutputStream* fp)
{
writeWord(fp, m_class.interfaces.size());
for(auto& itf : m_class.interfaces)
writeWord(fp, itf);
}
void writeField(OutputStream* fp)
{
writeWord(fp, m_class.fields.size());
for(auto& field : m_class.fields)
{
writeWord(fp, field.access_flags);
writeWord(fp, field.name_index);
writeWord(fp, field.descriptor_index);
writeWord(fp, field.attrs_count);
writeAttrInner(field.attrs, fp);
}
}
void writeMethod(OutputStream* fp)
{
writeWord(fp, m_class.methods.size());
for(auto& method : m_class.methods)
{
writeWord(fp, method.access_flags);
writeWord(fp, method.name_index);
writeWord(fp, method.descriptor_index);
writeWord(fp, method.attrs_count);
writeAttrInner(method.attrs, fp);
}
}
void writeAttr(OutputStream* fp)
{
writeWord(fp, m_class.attrs_count);
writeAttrInner(m_class.attrs, fp);
}
void writeAttrInner(const vector<AttrInfo>& attributes, OutputStream* fp)
{
for(auto& attr : attributes)
{
writeWord(fp, attr.attr_name_index);
writeUnsigned(fp, 4, attr.attr_len);
for(auto& inf : attr.info)
fp->write(&inf, 1);
}
}
};
}
// module entry point
void writeClass(OutputStream* fp, ClassFile const& class_)
{
Writer p(class_);
p.write(fp);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-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 <addrdb.h>
#include <addrman.h>
#include <chainparams.h>
#include <clientversion.h>
#include <cstdint>
#include <hash.h>
#include <logging/timer.h>
#include <random.h>
#include <streams.h>
#include <tinyformat.h>
#include <util/system.h>
namespace {
template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
// Write and commit header, data
try {
CHashWriter hasher(SER_DISK, CLIENT_VERSION);
stream << Params().MessageStart() << data;
hasher << Params().MessageStart() << data;
stream << hasher.GetHash();
} catch (const std::exception& e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
return true;
}
template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data)
{
// Generate random temporary filename
uint16_t randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
// open temp output file, and associate with CAutoFile
fs::path pathTmp = gArgs.GetDataDirNet() / tmpfn;
FILE *file = fsbridge::fopen(pathTmp, "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull()) {
fileout.fclose();
remove(pathTmp);
return error("%s: Failed to open file %s", __func__, pathTmp.string());
}
// Serialize
if (!SerializeDB(fileout, data)) {
fileout.fclose();
remove(pathTmp);
return false;
}
if (!FileCommit(fileout.Get())) {
fileout.fclose();
remove(pathTmp);
return error("%s: Failed to flush file %s", __func__, pathTmp.string());
}
fileout.fclose();
// replace existing file, if any, with new file
if (!RenameOver(pathTmp, path)) {
remove(pathTmp);
return error("%s: Rename-into-place failed", __func__);
}
return true;
}
template <typename Stream, typename Data>
bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
{
try {
CHashVerifier<Stream> verifier(&stream);
// de-serialize file header (network specific magic number) and ..
unsigned char pchMsgTmp[4];
verifier >> pchMsgTmp;
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
// de-serialize data
verifier >> data;
// verify checksum
if (fCheckSum) {
uint256 hashTmp;
stream >> hashTmp;
if (hashTmp != verifier.GetHash()) {
return error("%s: Checksum mismatch, data corrupted", __func__);
}
}
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
template <typename Data>
bool DeserializeFileDB(const fs::path& path, Data& data)
{
// open input file, and associate with CAutoFile
FILE* file = fsbridge::fopen(path, "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull()) {
LogPrintf("Missing or invalid file %s\n", path.string());
return false;
}
return DeserializeDB(filein, data);
}
} // namespace
CBanDB::CBanDB(fs::path ban_list_path) : m_ban_list_path(std::move(ban_list_path))
{
}
bool CBanDB::Write(const banmap_t& banSet)
{
return SerializeFileDB("banlist", m_ban_list_path, banSet);
}
bool CBanDB::Read(banmap_t& banSet)
{
return DeserializeFileDB(m_ban_list_path, banSet);
}
CAddrDB::CAddrDB()
{
pathAddr = gArgs.GetDataDirNet() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
return SerializeFileDB("peers", pathAddr, addr);
}
bool CAddrDB::Read(CAddrMan& addr)
{
return DeserializeFileDB(pathAddr, addr);
}
bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
{
bool ret = DeserializeDB(ssPeers, addr, false);
if (!ret) {
// Ensure addrman is left in a clean state
addr.Clear();
}
return ret;
}
void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)
{
LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size()));
SerializeFileDB("anchors", anchors_db_path, anchors);
}
std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path)
{
std::vector<CAddress> anchors;
if (DeserializeFileDB(anchors_db_path, anchors)) {
LogPrintf("Loaded %i addresses from %s\n", anchors.size(), anchors_db_path.filename());
} else {
anchors.clear();
}
fs::remove(anchors_db_path);
return anchors;
}
<commit_msg>Use addrv2 serialization in anchors.dat<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-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 <addrdb.h>
#include <addrman.h>
#include <chainparams.h>
#include <clientversion.h>
#include <cstdint>
#include <hash.h>
#include <logging/timer.h>
#include <random.h>
#include <streams.h>
#include <tinyformat.h>
#include <util/system.h>
namespace {
template <typename Stream, typename Data>
bool SerializeDB(Stream& stream, const Data& data)
{
// Write and commit header, data
try {
CHashWriter hasher(stream.GetType(), stream.GetVersion());
stream << Params().MessageStart() << data;
hasher << Params().MessageStart() << data;
stream << hasher.GetHash();
} catch (const std::exception& e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
return true;
}
template <typename Data>
bool SerializeFileDB(const std::string& prefix, const fs::path& path, const Data& data, int version)
{
// Generate random temporary filename
uint16_t randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("%s.%04x", prefix, randv);
// open temp output file, and associate with CAutoFile
fs::path pathTmp = gArgs.GetDataDirNet() / tmpfn;
FILE *file = fsbridge::fopen(pathTmp, "wb");
CAutoFile fileout(file, SER_DISK, version);
if (fileout.IsNull()) {
fileout.fclose();
remove(pathTmp);
return error("%s: Failed to open file %s", __func__, pathTmp.string());
}
// Serialize
if (!SerializeDB(fileout, data)) {
fileout.fclose();
remove(pathTmp);
return false;
}
if (!FileCommit(fileout.Get())) {
fileout.fclose();
remove(pathTmp);
return error("%s: Failed to flush file %s", __func__, pathTmp.string());
}
fileout.fclose();
// replace existing file, if any, with new file
if (!RenameOver(pathTmp, path)) {
remove(pathTmp);
return error("%s: Rename-into-place failed", __func__);
}
return true;
}
template <typename Stream, typename Data>
bool DeserializeDB(Stream& stream, Data& data, bool fCheckSum = true)
{
try {
CHashVerifier<Stream> verifier(&stream);
// de-serialize file header (network specific magic number) and ..
unsigned char pchMsgTmp[4];
verifier >> pchMsgTmp;
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
// de-serialize data
verifier >> data;
// verify checksum
if (fCheckSum) {
uint256 hashTmp;
stream >> hashTmp;
if (hashTmp != verifier.GetHash()) {
return error("%s: Checksum mismatch, data corrupted", __func__);
}
}
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
template <typename Data>
bool DeserializeFileDB(const fs::path& path, Data& data, int version)
{
// open input file, and associate with CAutoFile
FILE* file = fsbridge::fopen(path, "rb");
CAutoFile filein(file, SER_DISK, version);
if (filein.IsNull()) {
LogPrintf("Missing or invalid file %s\n", path.string());
return false;
}
return DeserializeDB(filein, data);
}
} // namespace
CBanDB::CBanDB(fs::path ban_list_path) : m_ban_list_path(std::move(ban_list_path))
{
}
bool CBanDB::Write(const banmap_t& banSet)
{
return SerializeFileDB("banlist", m_ban_list_path, banSet, CLIENT_VERSION);
}
bool CBanDB::Read(banmap_t& banSet)
{
return DeserializeFileDB(m_ban_list_path, banSet, CLIENT_VERSION);
}
CAddrDB::CAddrDB()
{
pathAddr = gArgs.GetDataDirNet() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
return SerializeFileDB("peers", pathAddr, addr, CLIENT_VERSION);
}
bool CAddrDB::Read(CAddrMan& addr)
{
return DeserializeFileDB(pathAddr, addr, CLIENT_VERSION);
}
bool CAddrDB::Read(CAddrMan& addr, CDataStream& ssPeers)
{
bool ret = DeserializeDB(ssPeers, addr, false);
if (!ret) {
// Ensure addrman is left in a clean state
addr.Clear();
}
return ret;
}
void DumpAnchors(const fs::path& anchors_db_path, const std::vector<CAddress>& anchors)
{
LOG_TIME_SECONDS(strprintf("Flush %d outbound block-relay-only peer addresses to anchors.dat", anchors.size()));
SerializeFileDB("anchors", anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT);
}
std::vector<CAddress> ReadAnchors(const fs::path& anchors_db_path)
{
std::vector<CAddress> anchors;
if (DeserializeFileDB(anchors_db_path, anchors, CLIENT_VERSION | ADDRV2_FORMAT)) {
LogPrintf("Loaded %i addresses from %s\n", anchors.size(), anchors_db_path.filename());
} else {
anchors.clear();
}
fs::remove(anchors_db_path);
return anchors;
}
<|endoftext|>
|
<commit_before>/*
* beagle.cpp
* BEAGLE
*
* @author Andrew Rambaut
* @author Marc Suchard
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <list>
#include <vector>
#include "beagle.h"
#include "BeagleImpl.h"
#ifdef CUDA
#include "CUDA/BeagleCUDAImpl.h"
#endif
#include "CPU/BeagleCPUImpl.h"
BeagleImpl **instances = NULL;
int instanceCount = 0;
std::list<BeagleImplFactory*> implFactory;
ResourceList* getResourceList() {
return null;
}
int createInstance(
int bufferCount,
int tipCount,
int stateCount,
int patternCount,
int eigenDecompositionCount,
int matrixCount,
int* resourceList,
int resourceCount,
int preferenceFlags,
int requirementFlags )
{
// Set-up a list of implementation factories in trial-order
if (implFactory.size() == 0) {
#ifdef CUDA
implFactory.push_back(new BeagleCUDAImplFactory());
#endif
implFactory.push_back(new BeagleCPUImplFactory());
}
// Try each implementation
for(std::list<BeagleImplFactory*>::iterator factory = implFactory.begin();
factory != implFactory.end(); factory++) {
fprintf(stderr,"BEAGLE bootstrap: %s - ",(*factory)->getName());
BeagleImpl* beagle = (*factory)->createImpl(
bufferCount,
tipCount,
stateCount,
patternCount,
eigenDecompositionCount,
matrixCount);
if (beagle != NULL) {
fprintf(stderr,"Success\n");
int instance = instanceCount;
instanceCount++;
instances = (BeagleImpl **)realloc(instances, sizeof(BeagleImpl *) * instanceCount);
instances[instance] = beagle;
return instance;
}
fprintf(stderr,"Failed\n");
}
// No implementations found or appropriate
return ERROR;
}
void initializeInstance(
int *instance,
int instanceCount,
InstanceDetails* returnInfo)
{
// TODO: Actual creation of instances should wait until here
}
void finalize(int *instance, int instanceCount)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->finalize();
}
int setPartials(
int* instance,
int instanceCount,
int bufferIndex,
const double* inPartials)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setTipPartials(bufferIndex, inPartials);
return 0;
}
int getPartials(int* instance, int bufferIndex, double *outPartials)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->getPartials(bufferIndex, outPartials);
return 0;
}
int setTipStates(
int* instance,
int instanceCount,
int tipIndex,
const int* inStates)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setTipStates(tipIndex, inStates);
return 0;
}
int setStateFrequencies(int* instance,
int instanceCount,
const double* inStateFrequencies)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setStateFrequencies(inStateFrequencies);
return 0;
}
int setEigenDecomposition(
int* instance,
int instanceCount,
int eigenIndex,
const double** inEigenVectors,
const double** inInverseEigenVectors,
const double* inEigenValues)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues);
return 0;
}
int setTransitionMatrix( int* instance,
int matrixIndex,
const double* inMatrix)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setTransitionMatrix(matrixIndex, inMatrix);
return 0;
}
int updateTransitionMatrices(
int* instance,
int instanceCount,
int eigenIndex,
const int* probabilityIndices,
const int* firstDerivativeIndices,
const int* secondDervativeIndices,
const double* edgeLengths,
int count)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->updateTransitionMatrices(eigenIndex, probabilityIndices, firstDerivativeIndices, secondDervativeIndices, edgeLengths, count);
return 0;
}
int updatePartials(
int* instance,
int instanceCount,
int* operations,
int operationCount,
int rescale)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->calculatePartials(operations, operationCount, rescale);
return 0;
}
int calculateRootLogLikelihoods(
int* instance,
int instanceCount,
const int* bufferIndices,
int count,
const double* weights,
const double** stateFrequencies,
double* outLogLikelihoods)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->calculateLogLikelihoods(bufferIndices, count, weights, stateFrequencies, outLogLikelihoods);
return 0;
}
int calculateEdgeLogLikelihoods(
int* instance,
int instanceCount,
const int* parentBufferIndices,
const int* childBufferIndices,
const int* probabilityIndices,
const int* firstDerivativeIndices,
const int* secondDerivativeIndices,
int count,
const double* weights,
const double** stateFrequencies,
double* outLogLikelihoods,
double* outFirstDerivatives,
double* outSecondDerivatives)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->calculateEdgeLogLikelihoods(
parentBufferIndices,
childBufferIndices,
probabilityIndices,
firstDerivativeIndices,
secondDerivativeIndices,
count,
weights,
stateFrequencies,
outLogLikelihoods,
outFirstDerivatives,
outSecondDerivatives);
return 0;
}
<commit_msg>finalize updated<commit_after>/*
* beagle.cpp
* BEAGLE
*
* @author Andrew Rambaut
* @author Marc Suchard
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <list>
#include <vector>
#include "beagle.h"
#include "BeagleImpl.h"
#ifdef CUDA
#include "CUDA/BeagleCUDAImpl.h"
#endif
#include "CPU/BeagleCPUImpl.h"
BeagleImpl **instances = NULL;
int instanceCount = 0;
std::list<BeagleImplFactory*> implFactory;
ResourceList* getResourceList() {
return null;
}
int createInstance(
int bufferCount,
int tipCount,
int stateCount,
int patternCount,
int eigenDecompositionCount,
int matrixCount,
int* resourceList,
int resourceCount,
int preferenceFlags,
int requirementFlags )
{
// Set-up a list of implementation factories in trial-order
if (implFactory.size() == 0) {
#ifdef CUDA
implFactory.push_back(new BeagleCUDAImplFactory());
#endif
implFactory.push_back(new BeagleCPUImplFactory());
}
// Try each implementation
for(std::list<BeagleImplFactory*>::iterator factory = implFactory.begin();
factory != implFactory.end(); factory++) {
fprintf(stderr,"BEAGLE bootstrap: %s - ",(*factory)->getName());
BeagleImpl* beagle = (*factory)->createImpl(
bufferCount,
tipCount,
stateCount,
patternCount,
eigenDecompositionCount,
matrixCount);
if (beagle != NULL) {
fprintf(stderr,"Success\n");
int instance = instanceCount;
instanceCount++;
instances = (BeagleImpl **)realloc(instances, sizeof(BeagleImpl *) * instanceCount);
instances[instance] = beagle;
return instance;
}
fprintf(stderr,"Failed\n");
}
// No implementations found or appropriate
return ERROR;
}
void initializeInstance(
int *instance,
int instanceCount,
InstanceDetails* returnInfo)
{
}
void finalize(int *instance, int instanceCount)
{
for (int i = 0; i < instanceCount; i++) {
delete instances[instance];
instances[instance] = 0L;
}
}
int setPartials(
int* instance,
int instanceCount,
int bufferIndex,
const double* inPartials)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setTipPartials(bufferIndex, inPartials);
return 0;
}
int getPartials(int* instance, int bufferIndex, double *outPartials)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->getPartials(bufferIndex, outPartials);
return 0;
}
int setTipStates(
int* instance,
int instanceCount,
int tipIndex,
const int* inStates)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setTipStates(tipIndex, inStates);
return 0;
}
int setStateFrequencies(int* instance,
int instanceCount,
const double* inStateFrequencies)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setStateFrequencies(inStateFrequencies);
return 0;
}
int setEigenDecomposition(
int* instance,
int instanceCount,
int eigenIndex,
const double** inEigenVectors,
const double** inInverseEigenVectors,
const double* inEigenValues)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setEigenDecomposition(eigenIndex, inEigenVectors, inInverseEigenVectors, inEigenValues);
return 0;
}
int setTransitionMatrix( int* instance,
int matrixIndex,
const double* inMatrix)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->setTransitionMatrix(matrixIndex, inMatrix);
return 0;
}
int updateTransitionMatrices(
int* instance,
int instanceCount,
int eigenIndex,
const int* probabilityIndices,
const int* firstDerivativeIndices,
const int* secondDervativeIndices,
const double* edgeLengths,
int count)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->updateTransitionMatrices(eigenIndex, probabilityIndices, firstDerivativeIndices, secondDervativeIndices, edgeLengths, count);
return 0;
}
int updatePartials(
int* instance,
int instanceCount,
int* operations,
int operationCount,
int rescale)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->calculatePartials(operations, operationCount, rescale);
return 0;
}
int calculateRootLogLikelihoods(
int* instance,
int instanceCount,
const int* bufferIndices,
int count,
const double* weights,
const double** stateFrequencies,
double* outLogLikelihoods)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->calculateLogLikelihoods(bufferIndices, count, weights, stateFrequencies, outLogLikelihoods);
return 0;
}
int calculateEdgeLogLikelihoods(
int* instance,
int instanceCount,
const int* parentBufferIndices,
const int* childBufferIndices,
const int* probabilityIndices,
const int* firstDerivativeIndices,
const int* secondDerivativeIndices,
int count,
const double* weights,
const double** stateFrequencies,
double* outLogLikelihoods,
double* outFirstDerivatives,
double* outSecondDerivatives)
{
for (int i = 0; i < instanceCount; i++)
instances[instance]->calculateEdgeLogLikelihoods(
parentBufferIndices,
childBufferIndices,
probabilityIndices,
firstDerivativeIndices,
secondDerivativeIndices,
count,
weights,
stateFrequencies,
outLogLikelihoods,
outFirstDerivatives,
outSecondDerivatives);
return 0;
}
<|endoftext|>
|
<commit_before>#include "broker.hpp"
#include "message.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <unordered_map>
namespace {
bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse
if(str1.length() != str2.length()) return false;
for(int i = str1.length() - 1; i >= 0; --i)
if(str1[i] != str2[i]) return false;
return true;
}
bool equalOrPlus(const std::string& pat, const std::string& top) {
return pat == "+" || revStrEquals(pat, top);
}
} //anonymous namespace
class Subscription {
public:
Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic,
std::vector<std::string> topicParts):
_subscriber(subscriber),
_part(std::move(topicParts[topicParts.size() - 1])),
_topic(std::move(topic.topic)),
_qos(topic.qos) {
}
void newMessage(std::string topic, std::vector<ubyte> payload) {
_subscriber.newMessage(topic, payload);
}
bool isSubscriber(const MqttSubscriber& subscriber) const {
return &_subscriber == &subscriber;
}
bool isSubscription(const MqttSubscriber& subscriber,
std::vector<std::string> topics) const {
return isSubscriber(subscriber) && isTopic(topics);
}
bool isTopic(std::vector<std::string> topics) const {
return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend();
}
private:
MqttSubscriber& _subscriber;
std::string _part;
std::string _topic;
ubyte _qos;
};
struct SubscriptionTree {
public:
// void addSubscription(Subscription* s, std::vector<std::string> parts) {
// assert(parts.size());
// if(_useCache) _cache.clear(); //invalidate cache
// addSubscriptionImpl(s, parts, null, _nodes);
// }
// void addSubscriptionImpl(Subscription s, const(string)[] parts,
// Node* parent, ref Node*[string] nodes) {
// auto part = parts[0];
// parts = parts[1 .. $];
// auto node = addOrFindNode(part, parent, nodes);
// if(parts.empty) {
// node.leaves ~= s;
// } else {
// addSubscriptionImpl(s, parts, node, node.branches);
// }
// }
// void removeSubscription(MqttSubscriber subscriber, ref Node*[string] nodes) {
// if(_useCache) _cache = _cache.init; //invalidate cache
// auto newnodes = nodes.dup;
// foreach(n; newnodes) {
// if(n.leaves) {
// n.leaves = std.algorithm.remove!(l => l.isSubscriber(subscriber))(n.leaves);
// if(n.leaves.empty && !n.branches.length) {
// removeNode(n.parent, n);
// }
// } else {
// removeSubscription(subscriber, n.branches);
// }
// }
// }
// void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) {
// if(_useCache) _cache = _cache.init; //invalidate cache
// auto newnodes = nodes.dup;
// foreach(n; newnodes) {
// if(n.leaves) {
// n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves);
// if(n.leaves.empty && !n.branches.length) {
// removeNode(n.parent, n);
// }
// } else {
// removeSubscription(subscriber, topic, n.branches);
// }
// }
// }
// void removeNode(Node* parent, Node* child) {
// if(parent) {
// parent.branches.remove(child.part);
// } else {
// _nodes.remove(child.part);
// }
// if(parent && !parent.branches.length && parent.leaves.empty)
// removeNode(parent.parent, parent);
// }
// void publish(in string topic, string[] topParts, in const(ubyte)[] payload) {
// publish(topic, topParts, payload, _nodes);
// }
// void publish(in string topic, string[] topParts, in const(ubyte)[] payload,
// Node*[string] nodes) {
// //check the cache first
// if(_useCache && topic in _cache) {
// foreach(s; _cache[topic]) s.newMessage(topic, payload);
// return;
// }
// //not in the cache or not using the cache, do it the hard way
// foreach(part; [topParts[0], "#", "+"]) {
// if(part in nodes) {
// if(topParts.length == 1 && "#" in nodes[part].branches) {
// //So that "finance/#" matches finance
// publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves);
// }
// publishLeaves(topic, payload, topParts, nodes[part].leaves);
// if(topParts.length > 1) {
// publish(topic, topParts[1..$], payload, nodes[part].branches);
// }
// }
// }
// }
// void publishLeaves(in string topic, in const(ubyte)[] payload,
// in string[] topParts,
// Subscription[] subscriptions) {
// foreach(sub; subscriptions) {
// if(topParts.length == 1 &&
// equalOrPlus(sub._part, topParts[0])) {
// publishLeaf(sub, topic, payload);
// }
// else if(sub._part == "#") {
// publishLeaf(sub, topic, payload);
// }
// }
// }
// void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) {
// sub.newMessage(topic, payload);
// if(_useCache) _cache[topic] ~= sub;
// }
void useCache(bool u) { _useCache = u; }
private:
struct Node {
Node(std::string pt, Node* pr):part(pt), parent(pr) {}
std::string part;
Node* parent;
std::unordered_map<std::string, Node*> branches;
std::vector<Subscription> leaves;
};
bool _useCache;
std::unordered_map<std::string, Subscription*> _cache;
std::unordered_map<std::string, Node*> _nodes;
Node* addOrFindNode(std::string part, Node* parent,
std::unordered_map<std::string, Node*> nodes) {
if(nodes.count(part) && part == nodes[part]->part) {
return nodes[part];
}
auto node = new Node(part, parent);
nodes[part] = node;
return node;
}
};
class MqttBroker {
public:
void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
std::vector<MqttSubscribe::Topic> newTopics;
std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics),
[](std::string t) { return MqttSubscribe::Topic(t, 0); });
subscribe(subscriber, newTopics);
}
void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) {
(void)subscriber;
for(const auto& t: topics) {
std::vector<std::string> parts;
boost::split(parts, t.topic, boost::is_any_of("/"));
//_subscriptions.addSubscription(Subscription(subscriber, t, parts), parts);
}
}
// void unsubscribe(MqttSubscriber& subscriber) {
// _subscriptions.removeSubscription(subscriber, _subscriptions._nodes);
// }
// void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
// _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes);
// }
// void publish(std::string topic, std::vector<ubyte> payload) {
// auto topParts = array(splitter(topic, "/"));
// publish(topic, topParts, payload);
// }
void useCache(bool u) { _subscriptions.useCache(u); }
private:
SubscriptionTree _subscriptions;
// void publish(std::string topic, std::vector<std::string> topParts,
// std::vector<ubyte> payload) {
// _subscriptions.publish(topic, topParts, payload);
// }
};
<commit_msg>Uncommented addSubscriptionImpl<commit_after>#include "broker.hpp"
#include "message.hpp"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <unordered_map>
namespace {
bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse
if(str1.length() != str2.length()) return false;
for(int i = str1.length() - 1; i >= 0; --i)
if(str1[i] != str2[i]) return false;
return true;
}
bool equalOrPlus(const std::string& pat, const std::string& top) {
return pat == "+" || revStrEquals(pat, top);
}
} //anonymous namespace
class Subscription {
public:
Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic,
std::vector<std::string> topicParts):
_subscriber(subscriber),
_part(std::move(topicParts[topicParts.size() - 1])),
_topic(std::move(topic.topic)),
_qos(topic.qos) {
}
void newMessage(std::string topic, std::vector<ubyte> payload) {
_subscriber.newMessage(topic, payload);
}
bool isSubscriber(const MqttSubscriber& subscriber) const {
return &_subscriber == &subscriber;
}
bool isSubscription(const MqttSubscriber& subscriber,
std::vector<std::string> topics) const {
return isSubscriber(subscriber) && isTopic(topics);
}
bool isTopic(std::vector<std::string> topics) const {
return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend();
}
private:
MqttSubscriber& _subscriber;
std::string _part;
std::string _topic;
ubyte _qos;
};
struct SubscriptionTree {
public:
// void addSubscription(Subscription* s, std::vector<std::string> parts) {
// assert(parts.size());
// if(_useCache) _cache.clear(); //invalidate cache
// addSubscriptionImpl(s, parts, null, _nodes);
// }
// void removeSubscription(MqttSubscriber subscriber, ref Node*[string] nodes) {
// if(_useCache) _cache = _cache.init; //invalidate cache
// auto newnodes = nodes.dup;
// foreach(n; newnodes) {
// if(n.leaves) {
// n.leaves = std.algorithm.remove!(l => l.isSubscriber(subscriber))(n.leaves);
// if(n.leaves.empty && !n.branches.length) {
// removeNode(n.parent, n);
// }
// } else {
// removeSubscription(subscriber, n.branches);
// }
// }
// }
// void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) {
// if(_useCache) _cache = _cache.init; //invalidate cache
// auto newnodes = nodes.dup;
// foreach(n; newnodes) {
// if(n.leaves) {
// n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves);
// if(n.leaves.empty && !n.branches.length) {
// removeNode(n.parent, n);
// }
// } else {
// removeSubscription(subscriber, topic, n.branches);
// }
// }
// }
// void removeNode(Node* parent, Node* child) {
// if(parent) {
// parent.branches.remove(child.part);
// } else {
// _nodes.remove(child.part);
// }
// if(parent && !parent.branches.length && parent.leaves.empty)
// removeNode(parent.parent, parent);
// }
// void publish(in string topic, string[] topParts, in const(ubyte)[] payload) {
// publish(topic, topParts, payload, _nodes);
// }
// void publish(in string topic, string[] topParts, in const(ubyte)[] payload,
// Node*[string] nodes) {
// //check the cache first
// if(_useCache && topic in _cache) {
// foreach(s; _cache[topic]) s.newMessage(topic, payload);
// return;
// }
// //not in the cache or not using the cache, do it the hard way
// foreach(part; [topParts[0], "#", "+"]) {
// if(part in nodes) {
// if(topParts.length == 1 && "#" in nodes[part].branches) {
// //So that "finance/#" matches finance
// publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves);
// }
// publishLeaves(topic, payload, topParts, nodes[part].leaves);
// if(topParts.length > 1) {
// publish(topic, topParts[1..$], payload, nodes[part].branches);
// }
// }
// }
// }
// void publishLeaves(in string topic, in const(ubyte)[] payload,
// in string[] topParts,
// Subscription[] subscriptions) {
// foreach(sub; subscriptions) {
// if(topParts.length == 1 &&
// equalOrPlus(sub._part, topParts[0])) {
// publishLeaf(sub, topic, payload);
// }
// else if(sub._part == "#") {
// publishLeaf(sub, topic, payload);
// }
// }
// }
// void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) {
// sub.newMessage(topic, payload);
// if(_useCache) _cache[topic] ~= sub;
// }
void useCache(bool u) { _useCache = u; }
private:
struct Node {
Node(std::string pt, Node* pr):part(pt), parent(pr) {}
std::string part;
Node* parent;
std::unordered_map<std::string, Node*> branches;
std::vector<Subscription*> leaves;
};
bool _useCache;
std::unordered_map<std::string, Subscription*> _cache;
std::unordered_map<std::string, Node*> _nodes;
void addSubscriptionImpl(Subscription* s,
std::deque<std::string> parts,
Node* parent,
std::unordered_map<std::string, Node*> nodes) {
auto part = parts.front();
parts.pop_front();
auto node = addOrFindNode(part, parent, nodes);
if(!parts.size()) {
node->leaves.emplace_back(s);
} else {
addSubscriptionImpl(s, parts, node, node->branches);
}
}
Node* addOrFindNode(std::string part, Node* parent,
std::unordered_map<std::string, Node*> nodes) {
if(nodes.count(part) && part == nodes[part]->part) {
return nodes[part];
}
auto node = new Node(part, parent);
nodes[part] = node;
return node;
}
};
class MqttBroker {
public:
void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
std::vector<MqttSubscribe::Topic> newTopics;
std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics),
[](std::string t) { return MqttSubscribe::Topic(t, 0); });
subscribe(subscriber, newTopics);
}
void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) {
(void)subscriber;
for(const auto& t: topics) {
std::vector<std::string> parts;
boost::split(parts, t.topic, boost::is_any_of("/"));
//_subscriptions.addSubscription(Subscription(subscriber, t, parts), parts);
}
}
// void unsubscribe(MqttSubscriber& subscriber) {
// _subscriptions.removeSubscription(subscriber, _subscriptions._nodes);
// }
// void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) {
// _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes);
// }
// void publish(std::string topic, std::vector<ubyte> payload) {
// auto topParts = array(splitter(topic, "/"));
// publish(topic, topParts, payload);
// }
void useCache(bool u) { _subscriptions.useCache(u); }
private:
SubscriptionTree _subscriptions;
// void publish(std::string topic, std::vector<std::string> topParts,
// std::vector<ubyte> payload) {
// _subscriptions.publish(topic, topParts, payload);
// }
};
<|endoftext|>
|
<commit_before>// $Id$
/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior 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 the Stanford University 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 _BUFFER_HPP_
#define _BUFFER_HPP_
#include <vector>
#include "vc.hpp"
#include "flit.hpp"
#include "outputset.hpp"
#include "routefunc.hpp"
#include "config_utils.hpp"
class Buffer : public Module {
int _vc_size;
int _shared_count;
int _shared_size;
bool _dynamic_sharing;
vector<VC*> _vc;
public:
Buffer( const Configuration& config, int outputs,
Module *parent, const string& name );
~Buffer();
bool AddFlit( int vc, Flit *f );
Flit *RemoveFlit( int vc );
inline Flit *FrontFlit( int vc ) const
{
return _vc[vc]->FrontFlit( );
}
inline bool Empty( int vc ) const
{
return _vc[vc]->Empty( );
}
bool Full( int vc ) const;
inline VC::eVCState GetState( int vc ) const
{
return _vc[vc]->GetState( );
}
inline int GetStateTime( int vc ) const
{
return _vc[vc]->GetStateTime( );
}
inline void SetState( int vc, VC::eVCState s )
{
_vc[vc]->SetState(s);
}
inline const OutputSet *GetRouteSet( int vc ) const
{
return _vc[vc]->GetRouteSet( );
}
inline void SetOutput( int vc, int out_port, int out_vc )
{
_vc[vc]->SetOutput(out_port, out_vc);
}
inline int GetOutputPort( int vc ) const
{
return _vc[vc]->GetOutputPort( );
}
inline int GetOutputVC( int vc ) const
{
return _vc[vc]->GetOutputVC( );
}
inline int GetPriority( int vc ) const
{
return _vc[vc]->GetPriority( );
}
inline void Route( int vc, tRoutingFunction rf, const Router* router, const Flit* f, int in_channel )
{
_vc[vc]->Route(rf, router, f, in_channel);
}
inline void AdvanceTime( )
{
for(vector<VC*>::iterator i = _vc.begin(); i != _vc.end(); ++i) {
(*i)->AdvanceTime();
}
}
// ==== Debug functions ====
inline void SetWatch( int vc, bool watch = true )
{
_vc[vc]->SetWatch(watch);
}
inline bool IsWatched( int vc ) const
{
return _vc[vc]->IsWatched( );
}
inline int GetSize( int vc ) const
{
return _vc[vc]->GetSize( );
}
void Display( ) const;
};
#endif
<commit_msg>remove unused member variable<commit_after>// $Id$
/*
Copyright (c) 2007-2010, Trustees of The Leland Stanford Junior 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 the Stanford University 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 _BUFFER_HPP_
#define _BUFFER_HPP_
#include <vector>
#include "vc.hpp"
#include "flit.hpp"
#include "outputset.hpp"
#include "routefunc.hpp"
#include "config_utils.hpp"
class Buffer : public Module {
int _vc_size;
int _shared_count;
int _shared_size;
vector<VC*> _vc;
public:
Buffer( const Configuration& config, int outputs,
Module *parent, const string& name );
~Buffer();
bool AddFlit( int vc, Flit *f );
Flit *RemoveFlit( int vc );
inline Flit *FrontFlit( int vc ) const
{
return _vc[vc]->FrontFlit( );
}
inline bool Empty( int vc ) const
{
return _vc[vc]->Empty( );
}
bool Full( int vc ) const;
inline VC::eVCState GetState( int vc ) const
{
return _vc[vc]->GetState( );
}
inline int GetStateTime( int vc ) const
{
return _vc[vc]->GetStateTime( );
}
inline void SetState( int vc, VC::eVCState s )
{
_vc[vc]->SetState(s);
}
inline const OutputSet *GetRouteSet( int vc ) const
{
return _vc[vc]->GetRouteSet( );
}
inline void SetOutput( int vc, int out_port, int out_vc )
{
_vc[vc]->SetOutput(out_port, out_vc);
}
inline int GetOutputPort( int vc ) const
{
return _vc[vc]->GetOutputPort( );
}
inline int GetOutputVC( int vc ) const
{
return _vc[vc]->GetOutputVC( );
}
inline int GetPriority( int vc ) const
{
return _vc[vc]->GetPriority( );
}
inline void Route( int vc, tRoutingFunction rf, const Router* router, const Flit* f, int in_channel )
{
_vc[vc]->Route(rf, router, f, in_channel);
}
inline void AdvanceTime( )
{
for(vector<VC*>::iterator i = _vc.begin(); i != _vc.end(); ++i) {
(*i)->AdvanceTime();
}
}
// ==== Debug functions ====
inline void SetWatch( int vc, bool watch = true )
{
_vc[vc]->SetWatch(watch);
}
inline bool IsWatched( int vc ) const
{
return _vc[vc]->IsWatched( );
}
inline int GetSize( int vc ) const
{
return _vc[vc]->GetSize( );
}
void Display( ) const;
};
#endif
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <unistd.h> //for getuid
#include <sys/types.h> //for getuid
#include <sys/stat.h> //For mkdir
#ifdef _WIN32
#include <shlobj.h>
#else
#include <pwd.h> //For getpwuid
#endif
#include "config.hpp"
#include "utils.hpp"
#include "server.hpp"
#include "assets.hpp"
#include "fortune.hpp"
using namespace budget;
typedef std::unordered_map<std::string, std::string> config_type;
namespace {
bool load_configuration(const std::string& path, config_type& configuration){
if (file_exists(path)) {
std::ifstream file(path);
if (file.is_open() && file.good()) {
std::string line;
while (file.good() && getline(file, line)) {
// Ignore empty lines
if (line.empty()) {
continue;
}
// Ignore comments
if(line[0] == '#'){
continue;
}
auto first = line.find('=');
if (first == std::string::npos || line.rfind('=') != first) {
std::cout << "The configuration file " << path << " is invalid only supports entries in form of key=value" << std::endl;
return false;
}
auto key = line.substr(0, first);
auto value = line.substr(first + 1, line.size());
configuration[key] = value;
}
} else {
std::cerr << "ERROR: Unable to open config file " << path << std::endl;
}
}
return true;
}
void save_configuration(const std::string& path, const config_type& configuration){
std::ofstream file(path);
for(auto& entry : configuration){
file << entry.first << "=" << entry.second << std::endl;
}
}
bool verify_folder(){
auto folder_path = budget_folder();
if(!folder_exists(folder_path)){
std::cout << "The folder " << folder_path << " does not exist. Would like to create it [yes/no] ? ";
std::string answer;
std::cin >> answer;
if(answer == "yes" || answer == "y"){
#ifdef _WIN32
if(mkdir(folder_path.c_str()) == 0){
#else
if(mkdir(folder_path.c_str(), ACCESSPERMS) == 0){
#endif
std::cout << "The folder " << folder_path << " was created. " << std::endl;
return true;
} else {
std::cout << "Impossible to create the folder " << folder_path << std::endl;
return false;
}
} else {
return false;
}
}
return true;
}
} //end of anonymous namespace
static config_type configuration;
static config_type internal;
static config_type internal_bak;
bool budget::load_config(){
if(!load_configuration(path_to_home_file(".budgetrc"), configuration)){
return false;
}
if(!verify_folder()){
return false;
}
if(!load_configuration(path_to_budget_file("config"), internal)){
return false;
}
internal_bak = internal;
//At the first start, the version is not set
if(internal.find("data_version") == internal.end()){
internal["data_version"] = budget::to_string(budget::DATA_VERSION);
}
return true;
}
void budget::save_config(){
if(internal != internal_bak){
save_configuration(path_to_budget_file("config"), internal);
}
}
std::string budget::home_folder(){
#ifdef _WIN32
TCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, path))) {
std::wstring wpath(path);
return std::string(wpath.begin(), wpath.end());
}
return "c:\\";
#else
struct passwd *pw = getpwuid(getuid());
const char* homedir = pw->pw_dir;
return std::string(homedir);
#endif
}
std::string budget::path_to_home_file(const std::string& file){
return home_folder() + "/" + file;
}
std::string budget::budget_folder(){
if(config_contains("directory")){
return config_value("directory");
}
return path_to_home_file(".budget");
}
std::string budget::path_to_budget_file(const std::string& file){
return budget_folder() + "/" + file;
}
bool budget::config_contains(const std::string& key){
return configuration.find(key) != configuration.end();
}
std::string budget::config_value(const std::string& key){
return configuration[key];
}
std::string budget::config_value(const std::string& key, const std::string& def){
if (config_contains(key)) {
return config_value(key);
}
return def;
}
bool budget::config_contains_and_true(const std::string& key) {
if (config_contains(key)) {
return config_value(key) == "true";
}
return false;
}
bool budget::internal_config_contains(const std::string& key){
return internal.find(key) != internal.end();
}
std::string& budget::internal_config_value(const std::string& key){
return internal[key];
}
void budget::internal_config_remove(const std::string& key){
internal.erase(key);
}
std::string budget::get_web_user(){
if (config_contains("web_user")) {
return config_value("web_user");
}
return "admin";
}
std::string budget::get_web_password(){
if (config_contains("web_password")) {
return config_value("web_password");
}
return "1234";
}
std::string budget::get_server_listen(){
if (config_contains("server_listen")) {
return config_value("server_listen");
}
return "localhost";
}
size_t budget::get_server_port(){
if (config_contains("server_port")) {
return to_number<size_t>(config_value("server_port"));
}
return 8080;
}
bool budget::is_server_mode(){
// The server cannot run in server mode
if (is_server_running()) {
return false;
}
if (config_contains("server_mode")) {
return config_value("server_mode") == "true";
}
return false;
}
bool budget::is_secure(){
if (config_contains("server_secure")) {
return config_value("server_secure") != "false";
}
return true;
}
bool budget::is_server_ssl(){
if (config_contains("server_ssl")) {
return config_value("server_ssl") == "true";
}
return false;
}
bool budget::is_fortune_disabled(){
return config_contains("disable_fortune") && config_value("disable_fortune") == "true";
}
bool budget::is_debts_disabled(){
return config_contains("disable_debts") && config_value("disable_debts") == "true";
}
bool budget::net_worth_over_fortune(){
// If the fortune module is disabled, use net worth
if (config_contains("disable_fortune")) {
if(config_value("disable_fortune") == "true"){
return true;
}
}
// By default, fortune is the thing being taken into account
// Unless it's not used and net worth is used
return all_asset_values().size() && !all_fortunes().size();
}
<commit_msg>Refactorings<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <unistd.h> //for getuid
#include <sys/types.h> //for getuid
#include <sys/stat.h> //For mkdir
#ifdef _WIN32
#include <shlobj.h>
#else
#include <pwd.h> //For getpwuid
#endif
#include "config.hpp"
#include "utils.hpp"
#include "server.hpp"
#include "assets.hpp"
#include "fortune.hpp"
using namespace budget;
typedef std::unordered_map<std::string, std::string> config_type;
namespace {
bool load_configuration(const std::string& path, config_type& configuration){
if (file_exists(path)) {
std::ifstream file(path);
if (file.is_open() && file.good()) {
std::string line;
while (file.good() && getline(file, line)) {
// Ignore empty lines
if (line.empty()) {
continue;
}
// Ignore comments
if(line[0] == '#'){
continue;
}
auto first = line.find('=');
if (first == std::string::npos || line.rfind('=') != first) {
std::cout << "The configuration file " << path << " is invalid only supports entries in form of key=value" << std::endl;
return false;
}
auto key = line.substr(0, first);
auto value = line.substr(first + 1, line.size());
configuration[key] = value;
}
} else {
std::cerr << "ERROR: Unable to open config file " << path << std::endl;
}
}
return true;
}
void save_configuration(const std::string& path, const config_type& configuration){
std::ofstream file(path);
for(auto& entry : configuration){
file << entry.first << "=" << entry.second << std::endl;
}
}
bool verify_folder(){
auto folder_path = budget_folder();
if(!folder_exists(folder_path)){
std::cout << "The folder " << folder_path << " does not exist. Would like to create it [yes/no] ? ";
std::string answer;
std::cin >> answer;
if(answer == "yes" || answer == "y"){
#ifdef _WIN32
if(mkdir(folder_path.c_str()) == 0){
#else
if(mkdir(folder_path.c_str(), ACCESSPERMS) == 0){
#endif
std::cout << "The folder " << folder_path << " was created. " << std::endl;
return true;
} else {
std::cout << "Impossible to create the folder " << folder_path << std::endl;
return false;
}
} else {
return false;
}
}
return true;
}
} //end of anonymous namespace
static config_type configuration;
static config_type internal;
static config_type internal_bak;
bool budget::load_config(){
if(!load_configuration(path_to_home_file(".budgetrc"), configuration)){
return false;
}
if(!verify_folder()){
return false;
}
if(!load_configuration(path_to_budget_file("config"), internal)){
return false;
}
internal_bak = internal;
//At the first start, the version is not set
if(internal.find("data_version") == internal.end()){
internal["data_version"] = budget::to_string(budget::DATA_VERSION);
}
return true;
}
void budget::save_config(){
if(internal != internal_bak){
save_configuration(path_to_budget_file("config"), internal);
}
}
std::string budget::home_folder(){
#ifdef _WIN32
TCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, 0, path))) {
std::wstring wpath(path);
return std::string(wpath.begin(), wpath.end());
}
return "c:\\";
#else
struct passwd *pw = getpwuid(getuid());
const char* homedir = pw->pw_dir;
return std::string(homedir);
#endif
}
std::string budget::path_to_home_file(const std::string& file){
return home_folder() + "/" + file;
}
std::string budget::budget_folder(){
if(config_contains("directory")){
return config_value("directory");
}
return path_to_home_file(".budget");
}
std::string budget::path_to_budget_file(const std::string& file){
return budget_folder() + "/" + file;
}
bool budget::config_contains(const std::string& key){
return configuration.find(key) != configuration.end();
}
std::string budget::config_value(const std::string& key){
return configuration[key];
}
std::string budget::config_value(const std::string& key, const std::string& def){
if (config_contains(key)) {
return config_value(key);
}
return def;
}
bool budget::config_contains_and_true(const std::string& key) {
if (config_contains(key)) {
return config_value(key) == "true";
}
return false;
}
bool budget::internal_config_contains(const std::string& key){
return internal.find(key) != internal.end();
}
std::string& budget::internal_config_value(const std::string& key){
return internal[key];
}
void budget::internal_config_remove(const std::string& key){
internal.erase(key);
}
std::string budget::get_web_user(){
if (config_contains("web_user")) {
return config_value("web_user");
}
return "admin";
}
std::string budget::get_web_password(){
if (config_contains("web_password")) {
return config_value("web_password");
}
return "1234";
}
std::string budget::get_server_listen(){
if (config_contains("server_listen")) {
return config_value("server_listen");
}
return "localhost";
}
size_t budget::get_server_port(){
if (config_contains("server_port")) {
return to_number<size_t>(config_value("server_port"));
}
return 8080;
}
bool budget::is_server_mode(){
// The server cannot run in server mode
if (is_server_running()) {
return false;
}
return config_contains_and_true("server_mode");
}
bool budget::is_secure(){
if (config_contains("server_secure")) {
return config_value("server_secure") != "false";
}
return true;
}
bool budget::is_server_ssl(){
if (config_contains("server_ssl")) {
return config_value("server_ssl") == "true";
}
return config_contains_and_true("server_ssl");
}
bool budget::is_fortune_disabled(){
return config_contains_and_true("disable_fortune");
}
bool budget::is_debts_disabled(){
return config_contains_and_true("disable_debts");
}
bool budget::net_worth_over_fortune(){
// If the fortune module is disabled, use net worth
if (config_contains_and_true("disable_fortune")) {
return true;
}
// By default, fortune is the thing being taken into account
// Unless it's not used and net worth is used
return all_asset_values().size() && !all_fortunes().size();
}
<|endoftext|>
|
<commit_before>#include "Tetris/Game/Tetris.hpp"
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdexcept>
#include <algorithm>
namespace tetris {
namespace game {
void Tetris::setScore(const int score) {
score_ = score;
fireScoreUpdated();
}
void Tetris::addScore(const int value) {
setScore(score_ + value);
}
void Tetris::setHighScore(const int highScore) {
highScore_ = highScore;
fireHighScoreUpdated();
}
void Tetris::create() {
create(time(0));
}
void Tetris::create(int seed) {
rng_.seed(seed);
loadHighScore();
setupBlockDataArray();
resetCurrentTetromino(newTetromino());
checkGameOver();
fireGameStarted();
}
void Tetris::destroy() {
saveHighScore();
blockDataArray_ = {};
worldBlockArray_ = {};
currentTetromino_ = {};
currentTetrominoCopy_ = {};
inputMovement_ = InputDirection::NONE;
inputRotation_ = InputDirection::NONE;
fastFall_ = false;
timer_ = 0.0f;
delay_ = DEFAULT_DELAY;
gameOver_ = false;
}
void Tetris::update(const float deltaTime) {
if (gameOver_) {
return;
}
timer_ += deltaTime;
delay_ = fastFall_ ? FAST_FALL_DELAY : DEFAULT_DELAY;
saveCurrentTetromino();
moveTetromino();
rotateTetromino();
moveDownTetromino();
inputMovement_ = inputRotation_ = InputDirection::NONE;
delay_ = DEFAULT_DELAY;
if (gameOver_) {
fireGameOver();
}
}
void Tetris::loadHighScore() {
std::ifstream scoreboard;
int highScore;
scoreboard.open(SCOREBOARD_FILE);
scoreboard >> highScore;;
scoreboard.close();
setHighScore(highScore);
}
void Tetris::saveHighScore() {
std::ofstream scoreboard;
scoreboard.open(SCOREBOARD_FILE);
if (scoreboard.is_open()) {
scoreboard << getHighScore();
scoreboard.close();
} else {
std::cout << "Unable to save scoreboard" << std::endl;
}
}
Tetromino Tetris::newTetromino() {
std::uniform_int_distribution<> uniform_dist(0,
static_cast<int>(Tetromino::Type::SIZE) - 1);
int index = uniform_dist(rng_);
Tetromino tetromino;
tetromino.setType(static_cast<Tetromino::Type>(index));
tetromino.loadRotationsFromIntArray(blockDataArray_[index]);
return tetromino;
}
void Tetris::resetCurrentTetromino(const Tetromino& tetromino) {
currentTetromino_ = tetromino;
currentTetromino_.move({4, 1});
nextTetromino_ = newTetromino();
}
void Tetris::checkGameOver() {
if (hasCollisions()) {
gameOver_ = true;
}
}
void Tetris::moveTetromino() {
int movement = static_cast<int>(inputMovement_);
currentTetromino_.move({movement, 0});
if (hasCollisions()) {
restoreCurrentTetromino();
}
}
void Tetris::rotateTetromino() {
if (inputRotation_ == InputDirection::LEFT) {
currentTetromino_.rotateLeft();
} else if (inputRotation_ == InputDirection::RIGHT) {
currentTetromino_.rotateRight();
}
if (hasCollisions()) {
restoreCurrentTetromino();
}
}
void Tetris::moveDownTetromino() {
if (timer_ >= delay_) {
saveCurrentTetromino();
Tetromino::Position fallMovement{0, 1};
currentTetromino_.move(fallMovement);
addScore(SCORE_POINT);
if (hasCollisions()) {
for (auto block : currentTetrominoCopy_.getBlocks()) {
int type = static_cast<int>(currentTetromino_.getType()) + 1;
worldBlockArray_[block.y][block.x] = type;
}
resetCurrentTetromino(nextTetromino_);
checkGameOver();
eraseLines();
fireWorldUpdated();
fireNextTetrominoUpdated();
}
timer_ = 0.0f;
}
fireTetrominoUpdated();
}
void Tetris::eraseLines() {
int k = WORLD_HEIGHT - 1;
int linesErased = 0;
for (int i = WORLD_HEIGHT - 1; i > 0; --i) {
int count = 0;
for (int j = 0; j < WORLD_WIDTH; ++j) {
if (worldBlockArray_[i][j] > 0) {
count++;
}
worldBlockArray_[k][j] = worldBlockArray_[i][j];
}
if (count < WORLD_WIDTH) {
k--;
} else {
linesErased++;
}
}
if (linesErased > 0) {
addScore(SCORE_BASE_POINTS * linesErased + (SCORE_BASE_POINTS * (linesErased - 1) / 3));
fireScoreUpdated();
}
}
void Tetris::restoreCurrentTetromino() {
currentTetromino_ = currentTetrominoCopy_;
}
void Tetris::saveCurrentTetromino() {
currentTetrominoCopy_ = currentTetromino_;
}
bool Tetris::hasCollisions() {
for (auto block : currentTetromino_.getBlocks()) {
if (block.x < 0 || block.x >= WORLD_WIDTH) {
return true;
}
if (block.y < 0 || block.y >= WORLD_HEIGHT) {
return true;
}
if (worldBlockArray_[block.y][block.x] > 0) {
return true;
}
}
return false;
}
void Tetris::setupBlockDataArray() {
blockDataArray_ = {{
{{
4,5,6,7,
2,6,10,14,
8,9,10,11,
1,5,9,13
}},
{{
4,8,9,10,
5,6,9,13,
8,9,10,14,
5,9,12,13
}},
{{
6,8,9,10,
5,9,13,14,
8,9,10,12,
4,5,9,13
}},
{{
5,6,9,10,
5,6,9,10,
5,6,9,10,
5,6,9,10
}},
{{
5,6,8,9,
5,9,10,14,
9,10,12,13,
4,8,9,13
}},
{{
5,8,9,10,
5,9,10,13,
8,9,10,13,
5,8,9,13
}},
{{
8,9,13,14,
6,9,10,13,
8,9,13,14,
5,8,9,12
}}
}};
}
void Tetris::fireGameStarted() {
if (gameStartedCallback) {
gameStartedCallback(*this);
}
fireScoreUpdated();
fireTetrominoUpdated();
fireNextTetrominoUpdated();
fireWorldUpdated();
}
void Tetris::fireGameOver() {
if (gameOverCallback) {
gameOverCallback(*this);
}
}
void Tetris::fireScoreUpdated() {
if (scoreUpdatedCallback) {
scoreUpdatedCallback(score_);
}
if (score_ >= highScore_) {
setHighScore(score_);
}
}
void Tetris::fireHighScoreUpdated() {
if (highScoreUpdatedCallback) {
highScoreUpdatedCallback(highScore_);
}
}
void Tetris::fireTetrominoUpdated() {
if (tetrominoUpdatedCallback) {
tetrominoUpdatedCallback(currentTetromino_);
}
}
void Tetris::fireNextTetrominoUpdated() {
if (nextTetrominoCallback) {
nextTetrominoCallback(nextTetromino_);
}
}
void Tetris::fireWorldUpdated() {
if (worldUpdatedCallback) {
worldUpdatedCallback(worldBlockArray_);
}
}
} /* namespace game */
} /* namespace tetris */
<commit_msg>Check if file is open<commit_after>#include "Tetris/Game/Tetris.hpp"
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdexcept>
#include <algorithm>
namespace tetris {
namespace game {
void Tetris::setScore(const int score) {
score_ = score;
fireScoreUpdated();
}
void Tetris::addScore(const int value) {
setScore(score_ + value);
}
void Tetris::setHighScore(const int highScore) {
highScore_ = highScore;
fireHighScoreUpdated();
}
void Tetris::create() {
create(time(0));
}
void Tetris::create(int seed) {
rng_.seed(seed);
loadHighScore();
setupBlockDataArray();
resetCurrentTetromino(newTetromino());
checkGameOver();
fireGameStarted();
}
void Tetris::destroy() {
saveHighScore();
blockDataArray_ = {};
worldBlockArray_ = {};
currentTetromino_ = {};
currentTetrominoCopy_ = {};
inputMovement_ = InputDirection::NONE;
inputRotation_ = InputDirection::NONE;
fastFall_ = false;
timer_ = 0.0f;
delay_ = DEFAULT_DELAY;
gameOver_ = false;
}
void Tetris::update(const float deltaTime) {
if (gameOver_) {
return;
}
timer_ += deltaTime;
delay_ = fastFall_ ? FAST_FALL_DELAY : DEFAULT_DELAY;
saveCurrentTetromino();
moveTetromino();
rotateTetromino();
moveDownTetromino();
inputMovement_ = inputRotation_ = InputDirection::NONE;
delay_ = DEFAULT_DELAY;
if (gameOver_) {
fireGameOver();
}
}
void Tetris::loadHighScore() {
std::ifstream scoreboard;
int highScore;
scoreboard.open(SCOREBOARD_FILE);
if (scoreboard.is_open()) {
scoreboard >> highScore;
scoreboard.close();
setHighScore(highScore);
}
}
void Tetris::saveHighScore() {
std::ofstream scoreboard;
scoreboard.open(SCOREBOARD_FILE);
if (scoreboard.is_open()) {
scoreboard << getHighScore();
scoreboard.close();
} else {
std::cout << "Unable to save scoreboard" << std::endl;
}
}
Tetromino Tetris::newTetromino() {
std::uniform_int_distribution<> uniform_dist(0,
static_cast<int>(Tetromino::Type::SIZE) - 1);
int index = uniform_dist(rng_);
Tetromino tetromino;
tetromino.setType(static_cast<Tetromino::Type>(index));
tetromino.loadRotationsFromIntArray(blockDataArray_[index]);
return tetromino;
}
void Tetris::resetCurrentTetromino(const Tetromino& tetromino) {
currentTetromino_ = tetromino;
currentTetromino_.move({4, 1});
nextTetromino_ = newTetromino();
}
void Tetris::checkGameOver() {
if (hasCollisions()) {
gameOver_ = true;
}
}
void Tetris::moveTetromino() {
int movement = static_cast<int>(inputMovement_);
currentTetromino_.move({movement, 0});
if (hasCollisions()) {
restoreCurrentTetromino();
}
}
void Tetris::rotateTetromino() {
if (inputRotation_ == InputDirection::LEFT) {
currentTetromino_.rotateLeft();
} else if (inputRotation_ == InputDirection::RIGHT) {
currentTetromino_.rotateRight();
}
if (hasCollisions()) {
restoreCurrentTetromino();
}
}
void Tetris::moveDownTetromino() {
if (timer_ >= delay_) {
saveCurrentTetromino();
Tetromino::Position fallMovement{0, 1};
currentTetromino_.move(fallMovement);
addScore(SCORE_POINT);
if (hasCollisions()) {
for (auto block : currentTetrominoCopy_.getBlocks()) {
int type = static_cast<int>(currentTetromino_.getType()) + 1;
worldBlockArray_[block.y][block.x] = type;
}
resetCurrentTetromino(nextTetromino_);
checkGameOver();
eraseLines();
fireWorldUpdated();
fireNextTetrominoUpdated();
}
timer_ = 0.0f;
}
fireTetrominoUpdated();
}
void Tetris::eraseLines() {
int k = WORLD_HEIGHT - 1;
int linesErased = 0;
for (int i = WORLD_HEIGHT - 1; i > 0; --i) {
int count = 0;
for (int j = 0; j < WORLD_WIDTH; ++j) {
if (worldBlockArray_[i][j] > 0) {
count++;
}
worldBlockArray_[k][j] = worldBlockArray_[i][j];
}
if (count < WORLD_WIDTH) {
k--;
} else {
linesErased++;
}
}
if (linesErased > 0) {
addScore(SCORE_BASE_POINTS * linesErased + (SCORE_BASE_POINTS * (linesErased - 1) / 3));
fireScoreUpdated();
}
}
void Tetris::restoreCurrentTetromino() {
currentTetromino_ = currentTetrominoCopy_;
}
void Tetris::saveCurrentTetromino() {
currentTetrominoCopy_ = currentTetromino_;
}
bool Tetris::hasCollisions() {
for (auto block : currentTetromino_.getBlocks()) {
if (block.x < 0 || block.x >= WORLD_WIDTH) {
return true;
}
if (block.y < 0 || block.y >= WORLD_HEIGHT) {
return true;
}
if (worldBlockArray_[block.y][block.x] > 0) {
return true;
}
}
return false;
}
void Tetris::setupBlockDataArray() {
blockDataArray_ = {{
{{
4,5,6,7,
2,6,10,14,
8,9,10,11,
1,5,9,13
}},
{{
4,8,9,10,
5,6,9,13,
8,9,10,14,
5,9,12,13
}},
{{
6,8,9,10,
5,9,13,14,
8,9,10,12,
4,5,9,13
}},
{{
5,6,9,10,
5,6,9,10,
5,6,9,10,
5,6,9,10
}},
{{
5,6,8,9,
5,9,10,14,
9,10,12,13,
4,8,9,13
}},
{{
5,8,9,10,
5,9,10,13,
8,9,10,13,
5,8,9,13
}},
{{
8,9,13,14,
6,9,10,13,
8,9,13,14,
5,8,9,12
}}
}};
}
void Tetris::fireGameStarted() {
if (gameStartedCallback) {
gameStartedCallback(*this);
}
fireScoreUpdated();
fireTetrominoUpdated();
fireNextTetrominoUpdated();
fireWorldUpdated();
}
void Tetris::fireGameOver() {
if (gameOverCallback) {
gameOverCallback(*this);
}
}
void Tetris::fireScoreUpdated() {
if (scoreUpdatedCallback) {
scoreUpdatedCallback(score_);
}
if (score_ >= highScore_) {
setHighScore(score_);
}
}
void Tetris::fireHighScoreUpdated() {
if (highScoreUpdatedCallback) {
highScoreUpdatedCallback(highScore_);
}
}
void Tetris::fireTetrominoUpdated() {
if (tetrominoUpdatedCallback) {
tetrominoUpdatedCallback(currentTetromino_);
}
}
void Tetris::fireNextTetrominoUpdated() {
if (nextTetrominoCallback) {
nextTetrominoCallback(nextTetromino_);
}
}
void Tetris::fireWorldUpdated() {
if (worldUpdatedCallback) {
worldUpdatedCallback(worldBlockArray_);
}
}
} /* namespace game */
} /* namespace tetris */
<|endoftext|>
|
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_SkyBox.h"
#include "Renderer.h"
#include "SceneManager.h"
#include "OgreMaterialUtils.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_SkyBox")
#include <Ogre.h>
#include "MemoryLeakCheck.h"
const unsigned int cSkyBoxTextureCount = 6; ///< Sky box has 6 textures.
namespace Environment
{
/// \todo Use Asset API for fetching sky resources.
EC_SkyBox::EC_SkyBox(IModule *module) :
IComponent(module->GetFramework()),
materialRef(this, "Material", AssetReference("RexSkyBox")), ///< \todo Add "orge://" when AssetAPI can handle it.
textureRefs(this, "Texture"),
orientation(this, "Orientation", Quaternion(f32(M_PI/2.0), Vector3df(1.0,0.0,0.0))),
distance(this, "Distance",50.0),
drawFirst(this, "Draw first", true)
{
connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(OnAttributeUpdated(IAttribute*)));
static AttributeMetadata materialRefMetadata;
AttributeMetadata::ButtonInfoList materialRefButtons;
materialRefButtons.push_back(AttributeMetadata::ButtonInfo(materialRef.GetName(), "V", "View"));
materialRefMetadata.buttons = materialRefButtons;
materialRef.SetMetadata(&materialRefMetadata);
// Find out default textures.
renderer_ = module->GetFramework()->GetServiceManager()->GetService<OgreRenderer::Renderer>();
StringVector names;
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(materialRef.Get().ref.toStdString().c_str());
if ( materialPtr.get() != 0)
{
OgreRenderer::GetTextureNamesFromMaterial(materialPtr, names);
AssetReferenceList lst;
if (names.size() == cSkyBoxTextureCount)
{
// This code block is not currently working, but if for some reason GetTextureNamesFromMaterialn understands cubic_textures this codeblock is runned
for(int i = 0; i < cSkyBoxTextureCount; ++i)
lst.Append(AssetReference(names[i].c_str()));
}
else
{
// Add default values, hardcoded
/// HACK use hardcoded-values because ogre textureunit state class cannot find out texture names for cubic_texture type.
lst.Append(AssetReference(names[0].c_str()));
lst.Append(AssetReference("rex_sky_back.dds"));
lst.Append(AssetReference("rex_sky_left.dds"));
lst.Append(AssetReference("rex_sky_right.dds"));
lst.Append(AssetReference("rex_sky_top.dds"));
lst.Append(AssetReference("rex_sky_bot.dds"));
}
textureRefs.Set(lst, AttributeChange::LocalOnly);
}
// Disable old sky.
// DisableSky();
CreateSky();
lastMaterial_ = materialRef.Get().ref;
lastOrientation_ = orientation.Get();
lastDistance_ = distance.Get();
lastDrawFirst_ = drawFirst.Get();
lastTextures_ = textureRefs.Get();
}
EC_SkyBox::~EC_SkyBox()
{
DisableSky();
renderer_.reset();
}
void EC_SkyBox::CreateSky()
{
if (!ViewEnabled())
return;
if (renderer_.expired())
return;
QString currentMaterial = materialRef.Get().ref;
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(currentMaterial.toStdString().c_str());
if (materialPtr.isNull())
{
LogError("Could not get SkyBox material : " + currentMaterial.toStdString());
return;
}
materialPtr->setReceiveShadows(false);
try
{
//RexTypes::Vector3 v = angleAxisAttr.Get();
//Ogre::Quaternion rotation(Ogre::Degree(90.0), Ogre::Vector3(1, 0, 0));
Quaternion o = orientation.Get();
renderer_.lock()->GetSceneManager()->setSkyBox(true, currentMaterial.toStdString().c_str(), distance.Get(),
drawFirst.Get(), Ogre::Quaternion(o.w, o.x, o.y, o.z));
}
catch(Ogre::Exception& e)
{
LogError("Could not set SkyBox: " + std::string(e.what()));
}
}
void EC_SkyBox::View(const QString &attributeName)
{
/// @todo implement this.
}
void EC_SkyBox::OnAttributeUpdated(IAttribute* attribute)
{
if (!ViewEnabled())
return;
std::string name = attribute->GetNameString();
if ((name == materialRef.GetNameString() && materialRef.Get().ref != lastMaterial_ ) ||
(name == distance.GetNameString() && distance.Get() != lastDistance_ ) ||
(name == drawFirst.GetNameString() && drawFirst.Get() != lastDrawFirst_ ))
{
DisableSky();
CreateSky();
lastMaterial_ = materialRef.Get().ref;
lastDistance_ = distance.Get();
lastDrawFirst_ = drawFirst.Get();
}
else if (name == textureRefs.GetNameString() )
{
// What texture has changed?
SetTextures();
}
}
void EC_SkyBox::SetTextures()
{
if (!ViewEnabled())
return;
AssetReferenceList lst = textureRefs.Get();
std::vector<std::string> texture_names;
texture_names.reserve(6);
for(int i = 0; i < lst.Size() && i <= 6; ++i)
texture_names.push_back(lst[i].ref.toStdString());
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(materialRef.Get().ref.toStdString().c_str());
if (!materialPtr.isNull() && texture_names.size() == 6)
materialPtr->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setCubicTextureName(&texture_names[0], false);
//skyMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureScale(1, -1);
else if(!materialPtr.isNull() )
for(int i = 0; i < texture_names.size(); ++i)
materialPtr->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setFrameTextureName(Ogre::String(texture_names[i].c_str()), i);
DisableSky();
CreateSky();
}
void EC_SkyBox::DisableSky()
{
if (!ViewEnabled())
return;
if (renderer_.expired())
renderer_.lock()->GetSceneManager()->setSkyBox(false, "");
}
}
<commit_msg>Fix bug: "if (renderer_.expired())" -> "if (!renderer_.expired())"<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_SkyBox.h"
#include "Renderer.h"
#include "SceneManager.h"
#include "OgreMaterialUtils.h"
#include "LoggingFunctions.h"
DEFINE_POCO_LOGGING_FUNCTIONS("EC_SkyBox")
#include <Ogre.h>
#include "MemoryLeakCheck.h"
const unsigned int cSkyBoxTextureCount = 6; ///< Sky box has 6 textures.
namespace Environment
{
/// \todo Use Asset API for fetching sky resources.
EC_SkyBox::EC_SkyBox(IModule *module) :
IComponent(module->GetFramework()),
materialRef(this, "Material", AssetReference("RexSkyBox")), ///< \todo Add "orge://" when AssetAPI can handle it.
textureRefs(this, "Texture"),
orientation(this, "Orientation", Quaternion(f32(M_PI/2.0), Vector3df(1.0,0.0,0.0))),
distance(this, "Distance",50.0),
drawFirst(this, "Draw first", true)
{
connect(this, SIGNAL(AttributeChanged(IAttribute*, AttributeChange::Type)), SLOT(OnAttributeUpdated(IAttribute*)));
static AttributeMetadata materialRefMetadata;
AttributeMetadata::ButtonInfoList materialRefButtons;
materialRefButtons.push_back(AttributeMetadata::ButtonInfo(materialRef.GetName(), "V", "View"));
materialRefMetadata.buttons = materialRefButtons;
materialRef.SetMetadata(&materialRefMetadata);
// Find out default textures.
renderer_ = module->GetFramework()->GetServiceManager()->GetService<OgreRenderer::Renderer>();
StringVector names;
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(materialRef.Get().ref.toStdString().c_str());
if ( materialPtr.get() != 0)
{
OgreRenderer::GetTextureNamesFromMaterial(materialPtr, names);
AssetReferenceList lst;
if (names.size() == cSkyBoxTextureCount)
{
// This code block is not currently working, but if for some reason GetTextureNamesFromMaterialn understands cubic_textures this codeblock is runned
for(int i = 0; i < cSkyBoxTextureCount; ++i)
lst.Append(AssetReference(names[i].c_str()));
}
else
{
// Add default values, hardcoded
/// HACK use hardcoded-values because ogre textureunit state class cannot find out texture names for cubic_texture type.
lst.Append(AssetReference(names[0].c_str()));
lst.Append(AssetReference("rex_sky_back.dds"));
lst.Append(AssetReference("rex_sky_left.dds"));
lst.Append(AssetReference("rex_sky_right.dds"));
lst.Append(AssetReference("rex_sky_top.dds"));
lst.Append(AssetReference("rex_sky_bot.dds"));
}
textureRefs.Set(lst, AttributeChange::LocalOnly);
}
// Disable old sky.
// DisableSky();
CreateSky();
lastMaterial_ = materialRef.Get().ref;
lastOrientation_ = orientation.Get();
lastDistance_ = distance.Get();
lastDrawFirst_ = drawFirst.Get();
lastTextures_ = textureRefs.Get();
}
EC_SkyBox::~EC_SkyBox()
{
DisableSky();
renderer_.reset();
}
void EC_SkyBox::CreateSky()
{
if (!ViewEnabled())
return;
if (renderer_.expired())
return;
QString currentMaterial = materialRef.Get().ref;
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(currentMaterial.toStdString().c_str());
if (materialPtr.isNull())
{
LogError("Could not get SkyBox material : " + currentMaterial.toStdString());
return;
}
materialPtr->setReceiveShadows(false);
try
{
//RexTypes::Vector3 v = angleAxisAttr.Get();
//Ogre::Quaternion rotation(Ogre::Degree(90.0), Ogre::Vector3(1, 0, 0));
Quaternion o = orientation.Get();
renderer_.lock()->GetSceneManager()->setSkyBox(true, currentMaterial.toStdString().c_str(), distance.Get(),
drawFirst.Get(), Ogre::Quaternion(o.w, o.x, o.y, o.z));
}
catch(Ogre::Exception& e)
{
LogError("Could not set SkyBox: " + std::string(e.what()));
}
}
void EC_SkyBox::View(const QString &attributeName)
{
/// @todo implement this.
}
void EC_SkyBox::OnAttributeUpdated(IAttribute* attribute)
{
if (!ViewEnabled())
return;
std::string name = attribute->GetNameString();
if ((name == materialRef.GetNameString() && materialRef.Get().ref != lastMaterial_ ) ||
(name == distance.GetNameString() && distance.Get() != lastDistance_ ) ||
(name == drawFirst.GetNameString() && drawFirst.Get() != lastDrawFirst_ ))
{
DisableSky();
CreateSky();
lastMaterial_ = materialRef.Get().ref;
lastDistance_ = distance.Get();
lastDrawFirst_ = drawFirst.Get();
}
else if (name == textureRefs.GetNameString() )
{
// What texture has changed?
SetTextures();
}
}
void EC_SkyBox::SetTextures()
{
if (!ViewEnabled())
return;
AssetReferenceList lst = textureRefs.Get();
std::vector<std::string> texture_names;
texture_names.reserve(6);
for(int i = 0; i < lst.Size() && i <= 6; ++i)
texture_names.push_back(lst[i].ref.toStdString());
Ogre::MaterialPtr materialPtr = Ogre::MaterialManager::getSingleton().getByName(materialRef.Get().ref.toStdString().c_str());
if (!materialPtr.isNull() && texture_names.size() == 6)
materialPtr->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setCubicTextureName(&texture_names[0], false);
//skyMaterial->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setTextureScale(1, -1);
else if(!materialPtr.isNull() )
for(int i = 0; i < texture_names.size(); ++i)
materialPtr->getTechnique(0)->getPass(0)->getTextureUnitState(0)->setFrameTextureName(Ogre::String(texture_names[i].c_str()), i);
DisableSky();
CreateSky();
}
void EC_SkyBox::DisableSky()
{
if (!ViewEnabled())
return;
if (!renderer_.expired())
renderer_.lock()->GetSceneManager()->setSkyBox(false, "");
}
}
<|endoftext|>
|
<commit_before>/** @file
@brief Display struct and related types.
@date 2016
@author
Sensics, Inc.
<http://sensics.com>
*/
// Copyright 2016 Sensics, 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.
// Internal Includes
#include <osvr/Display/Display.h>
// Library/third-party includes
// - none
// Standard includes
#include <cctype> // for toupper
#include <cmath>
#include <cstdint>
#include <string>
namespace osvr {
namespace display {
bool DisplaySize::operator==(const DisplaySize& other) const
{
if (width != other.width) return false;
if (height != other.height) return false;
return true;
}
bool DisplaySize::operator!=(const DisplaySize& other) const
{
return !(*this == other);
}
bool DisplayPosition::operator==(const DisplayPosition& other) const
{
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
bool DisplayPosition::operator!=(const DisplayPosition& other) const
{
return !(*this == other);
}
bool DisplayAdapter::operator==(const DisplayAdapter& other) const
{
if (description != other.description) return false;
return true;
}
bool DisplayAdapter::operator!=(const DisplayAdapter& other) const
{
return !(*this == other);
}
Rotation operator-(const DesktopOrientation lhs, const DesktopOrientation rhs)
{
const auto difference = (4 + static_cast<int>(lhs) - static_cast<int>(rhs)) % 4;
switch (difference) {
case 0:
return Rotation::Zero;
case 1:
return Rotation::Ninety;
case 2:
return Rotation::OneEighty;
case 3:
return Rotation::TwoSeventy;
default:
// ERROR! Shouldn't get here. Check to see if the Rotation or
// DesktopOrientation enums have changed.
return Rotation::Zero;
}
}
DesktopOrientation operator+(DesktopOrientation orientation, Rotation rotation)
{
return static_cast<DesktopOrientation>((static_cast<int>(orientation) + static_cast<int>(rotation)) % 4);
}
DesktopOrientation operator+(Rotation rotation, DesktopOrientation orientation)
{
return orientation + rotation;
}
DesktopOrientation operator-(DesktopOrientation orientation, Rotation rotation)
{
return static_cast<DesktopOrientation>((static_cast<int>(orientation) - static_cast<int>(rotation) + 4) % 4);
}
DesktopOrientation operator+(ScanOutOrigin origin, Rotation rotation)
{
int shift = 0;
if (ScanOutOrigin::UpperLeft == origin) {
shift = 0;
} else if (ScanOutOrigin::LowerLeft == origin) {
shift = 1;
} else if (ScanOutOrigin::LowerRight == origin) {
shift = 2;
} else if (ScanOutOrigin::UpperRight == origin) {
shift = 3;
}
if (Rotation::Zero == rotation) {
shift += 0;
} else if (Rotation::Ninety == rotation) {
shift += 1;
} else if (Rotation::OneEighty == rotation) {
shift += 2;
} else if (Rotation::TwoSeventy == rotation) {
shift += 3;
}
const auto orientation = static_cast<DesktopOrientation>((static_cast<int>(DesktopOrientation::Landscape) + shift) % 4);
return orientation;
}
DesktopOrientation operator+(Rotation rotation, ScanOutOrigin origin)
{
return origin + rotation;
}
DesktopOrientation operator-(ScanOutOrigin origin, Rotation rotation)
{
// FIXME
int shift = 0;
if (ScanOutOrigin::UpperLeft == origin) {
shift = 0;
} else if (ScanOutOrigin::LowerLeft == origin) {
shift = 1;
} else if (ScanOutOrigin::LowerRight == origin) {
shift = 2;
} else if (ScanOutOrigin::UpperRight == origin) {
shift = 3;
}
if (Rotation::Zero == rotation) {
shift += 0;
} else if (Rotation::Ninety == rotation) {
shift += 1;
} else if (Rotation::OneEighty == rotation) {
shift += 2;
} else if (Rotation::TwoSeventy == rotation) {
shift += 3;
}
const auto orientation = static_cast<DesktopOrientation>((static_cast<int>(DesktopOrientation::Landscape) + shift) % 4);
return orientation;
}
Rotation operator-(const Rotation rotation)
{
return static_cast<Rotation>((4 - static_cast<int>(rotation)) % 4);
}
ScanOutOrigin to_ScanOutOrigin(const DesktopOrientation& orientation)
{
switch (orientation) {
case DesktopOrientation::Landscape:
return ScanOutOrigin::UpperLeft;
case DesktopOrientation::Portrait:
return ScanOutOrigin::LowerLeft;
case DesktopOrientation::LandscapeFlipped:
return ScanOutOrigin::LowerRight;
case DesktopOrientation::PortraitFlipped:
return ScanOutOrigin::UpperRight;
default:
throw std::invalid_argument("Invalid orientation.");
}
}
Rotation to_Rotation(int r)
{
switch (r) {
case 0:
return Rotation::Zero;
case 90:
case -270:
return Rotation::Ninety;
case 180:
case -180:
return Rotation::OneEighty;
case 270:
case -90:
return Rotation::TwoSeventy;
default:
throw std::invalid_argument("Invalid rotation value. Only support 0, 90, 180, 270, and their negatives.");
}
}
bool Display::operator==(const Display& other) const
{
if (adapter != other.adapter) return false;
if (name != other.name) return false;
if (size != other.size) return false;
if (position != other.position) return false;
if (rotation != other.rotation) return false;
if (verticalRefreshRate != other.verticalRefreshRate) return false;
if (attachedToDesktop != other.attachedToDesktop) return false;
if (edidProductId != other.edidProductId) return false;
if (edidVendorId != other.edidVendorId) return false;
return true;
}
bool Display::operator!=(const Display& other) const
{
return !(*this == other);
}
OSVR_DISPLAY_EXPORT std::string to_string(const Rotation rotation)
{
switch (rotation) {
case osvr::display::Rotation::Zero:
return "0 degrees counter-clockwise";
case osvr::display::Rotation::Ninety:
return "90 degrees counter-clockwise";
case osvr::display::Rotation::OneEighty:
return "180 degrees counter-clockwise";
case osvr::display::Rotation::TwoSeventy:
return "270 degrees counter-clockwise";
default:
return "Unknown rotation: " + std::to_string(static_cast<int>(rotation));
}
}
OSVR_DISPLAY_EXPORT std::string to_string(const DesktopOrientation orientation)
{
switch (orientation) {
case osvr::display::DesktopOrientation::Landscape:
return "Landscape";
case osvr::display::DesktopOrientation::Portrait:
return "Portrait";
case osvr::display::DesktopOrientation::LandscapeFlipped:
return "Landscape (flipped)";
case osvr::display::DesktopOrientation::PortraitFlipped:
return "Portrait (flipped)";
default:
return "Unknown orientation: " + std::to_string(static_cast<int>(orientation));
}
}
OSVR_DISPLAY_EXPORT std::string to_string(const ScanOutOrigin origin)
{
switch (origin) {
case ScanOutOrigin::UpperLeft:
return "Upper-left";
case ScanOutOrigin::UpperRight:
return "Upper-right";
case ScanOutOrigin::LowerRight:
return "Lower-right";
case ScanOutOrigin::LowerLeft:
return "Lower-left";
default:
return "Unknown scan-out origin: " + std::to_string(static_cast<int>(origin));
}
}
OSVR_DISPLAY_EXPORT std::string decodeEdidVendorId(uint32_t vid)
{
// The vid is two bytes wide. The most-significant bit is always 0. The
// remaining 15 bits are split into five-bit segments. Each segment
// represents a letter (0b00001 = A, 0b00010 = B, etc.).
//
// We'll just mask out each letter's bits and convert it to a character.
// Then append each character to a string to get the three-letter vendor ID.
// But first, we need to swap the bytes.
vid = ((vid & 0xff00) >> 8) | ((vid & 0x00ff) << 8);
std::string str = " ";
str[2] = 'A' + ((vid >> 0) & 0x1f) - 1;
str[1] = 'A' + ((vid >> 5) & 0x1f) - 1;
str[0] = 'A' + ((vid >> 10) & 0x1f) - 1;
return str;
}
OSVR_DISPLAY_EXPORT uint32_t encodeEdidVendorId(const std::string& vid)
{
// The vid is two bytes wide. The most-significant bit is always 0. The
// remaining 15 bits are split into five-bit segments. Each segment
// represents a letter (0b00001 = A, 0b00010 = B, etc.).
if (3 != vid.length()) {
throw std::invalid_argument("The EDID vendor ID may only consist of three characters.");
}
uint32_t val = 0x0000;
for (auto c : vid) {
c = static_cast<char>(std::toupper(c));
if (c < 'A' || c > 'Z') {
throw std::invalid_argument("Each letter of the EDID vendor ID must be an uppercase letter A..Z.");
}
val = val << 5;
val += static_cast<uint32_t>(c) - 'A' + 1;
}
// Swap the bytes
val = ((val & 0xff00) >> 8) | ((val & 0x00ff) << 8);
return val;
}
} // end namespace display
} // end namespace osvr
<commit_msg>Added missing #include.<commit_after>/** @file
@brief Display struct and related types.
@date 2016
@author
Sensics, Inc.
<http://sensics.com>
*/
// Copyright 2016 Sensics, 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.
// Internal Includes
#include <osvr/Display/Display.h>
// Library/third-party includes
// - none
// Standard includes
#include <cctype> // for toupper
#include <cmath>
#include <cstdint>
#include <stdexcept>
#include <string>
namespace osvr {
namespace display {
bool DisplaySize::operator==(const DisplaySize& other) const
{
if (width != other.width) return false;
if (height != other.height) return false;
return true;
}
bool DisplaySize::operator!=(const DisplaySize& other) const
{
return !(*this == other);
}
bool DisplayPosition::operator==(const DisplayPosition& other) const
{
if (x != other.x) return false;
if (y != other.y) return false;
return true;
}
bool DisplayPosition::operator!=(const DisplayPosition& other) const
{
return !(*this == other);
}
bool DisplayAdapter::operator==(const DisplayAdapter& other) const
{
if (description != other.description) return false;
return true;
}
bool DisplayAdapter::operator!=(const DisplayAdapter& other) const
{
return !(*this == other);
}
Rotation operator-(const DesktopOrientation lhs, const DesktopOrientation rhs)
{
const auto difference = (4 + static_cast<int>(lhs) - static_cast<int>(rhs)) % 4;
switch (difference) {
case 0:
return Rotation::Zero;
case 1:
return Rotation::Ninety;
case 2:
return Rotation::OneEighty;
case 3:
return Rotation::TwoSeventy;
default:
// ERROR! Shouldn't get here. Check to see if the Rotation or
// DesktopOrientation enums have changed.
return Rotation::Zero;
}
}
DesktopOrientation operator+(DesktopOrientation orientation, Rotation rotation)
{
return static_cast<DesktopOrientation>((static_cast<int>(orientation) + static_cast<int>(rotation)) % 4);
}
DesktopOrientation operator+(Rotation rotation, DesktopOrientation orientation)
{
return orientation + rotation;
}
DesktopOrientation operator-(DesktopOrientation orientation, Rotation rotation)
{
return static_cast<DesktopOrientation>((static_cast<int>(orientation) - static_cast<int>(rotation) + 4) % 4);
}
DesktopOrientation operator+(ScanOutOrigin origin, Rotation rotation)
{
int shift = 0;
if (ScanOutOrigin::UpperLeft == origin) {
shift = 0;
} else if (ScanOutOrigin::LowerLeft == origin) {
shift = 1;
} else if (ScanOutOrigin::LowerRight == origin) {
shift = 2;
} else if (ScanOutOrigin::UpperRight == origin) {
shift = 3;
}
if (Rotation::Zero == rotation) {
shift += 0;
} else if (Rotation::Ninety == rotation) {
shift += 1;
} else if (Rotation::OneEighty == rotation) {
shift += 2;
} else if (Rotation::TwoSeventy == rotation) {
shift += 3;
}
const auto orientation = static_cast<DesktopOrientation>((static_cast<int>(DesktopOrientation::Landscape) + shift) % 4);
return orientation;
}
DesktopOrientation operator+(Rotation rotation, ScanOutOrigin origin)
{
return origin + rotation;
}
DesktopOrientation operator-(ScanOutOrigin origin, Rotation rotation)
{
// FIXME
int shift = 0;
if (ScanOutOrigin::UpperLeft == origin) {
shift = 0;
} else if (ScanOutOrigin::LowerLeft == origin) {
shift = 1;
} else if (ScanOutOrigin::LowerRight == origin) {
shift = 2;
} else if (ScanOutOrigin::UpperRight == origin) {
shift = 3;
}
if (Rotation::Zero == rotation) {
shift += 0;
} else if (Rotation::Ninety == rotation) {
shift += 1;
} else if (Rotation::OneEighty == rotation) {
shift += 2;
} else if (Rotation::TwoSeventy == rotation) {
shift += 3;
}
const auto orientation = static_cast<DesktopOrientation>((static_cast<int>(DesktopOrientation::Landscape) + shift) % 4);
return orientation;
}
Rotation operator-(const Rotation rotation)
{
return static_cast<Rotation>((4 - static_cast<int>(rotation)) % 4);
}
ScanOutOrigin to_ScanOutOrigin(const DesktopOrientation& orientation)
{
switch (orientation) {
case DesktopOrientation::Landscape:
return ScanOutOrigin::UpperLeft;
case DesktopOrientation::Portrait:
return ScanOutOrigin::LowerLeft;
case DesktopOrientation::LandscapeFlipped:
return ScanOutOrigin::LowerRight;
case DesktopOrientation::PortraitFlipped:
return ScanOutOrigin::UpperRight;
default:
throw std::invalid_argument("Invalid orientation.");
}
}
Rotation to_Rotation(int r)
{
switch (r) {
case 0:
return Rotation::Zero;
case 90:
case -270:
return Rotation::Ninety;
case 180:
case -180:
return Rotation::OneEighty;
case 270:
case -90:
return Rotation::TwoSeventy;
default:
throw std::invalid_argument("Invalid rotation value. Only support 0, 90, 180, 270, and their negatives.");
}
}
bool Display::operator==(const Display& other) const
{
if (adapter != other.adapter) return false;
if (name != other.name) return false;
if (size != other.size) return false;
if (position != other.position) return false;
if (rotation != other.rotation) return false;
if (verticalRefreshRate != other.verticalRefreshRate) return false;
if (attachedToDesktop != other.attachedToDesktop) return false;
if (edidProductId != other.edidProductId) return false;
if (edidVendorId != other.edidVendorId) return false;
return true;
}
bool Display::operator!=(const Display& other) const
{
return !(*this == other);
}
OSVR_DISPLAY_EXPORT std::string to_string(const Rotation rotation)
{
switch (rotation) {
case osvr::display::Rotation::Zero:
return "0 degrees counter-clockwise";
case osvr::display::Rotation::Ninety:
return "90 degrees counter-clockwise";
case osvr::display::Rotation::OneEighty:
return "180 degrees counter-clockwise";
case osvr::display::Rotation::TwoSeventy:
return "270 degrees counter-clockwise";
default:
return "Unknown rotation: " + std::to_string(static_cast<int>(rotation));
}
}
OSVR_DISPLAY_EXPORT std::string to_string(const DesktopOrientation orientation)
{
switch (orientation) {
case osvr::display::DesktopOrientation::Landscape:
return "Landscape";
case osvr::display::DesktopOrientation::Portrait:
return "Portrait";
case osvr::display::DesktopOrientation::LandscapeFlipped:
return "Landscape (flipped)";
case osvr::display::DesktopOrientation::PortraitFlipped:
return "Portrait (flipped)";
default:
return "Unknown orientation: " + std::to_string(static_cast<int>(orientation));
}
}
OSVR_DISPLAY_EXPORT std::string to_string(const ScanOutOrigin origin)
{
switch (origin) {
case ScanOutOrigin::UpperLeft:
return "Upper-left";
case ScanOutOrigin::UpperRight:
return "Upper-right";
case ScanOutOrigin::LowerRight:
return "Lower-right";
case ScanOutOrigin::LowerLeft:
return "Lower-left";
default:
return "Unknown scan-out origin: " + std::to_string(static_cast<int>(origin));
}
}
OSVR_DISPLAY_EXPORT std::string decodeEdidVendorId(uint32_t vid)
{
// The vid is two bytes wide. The most-significant bit is always 0. The
// remaining 15 bits are split into five-bit segments. Each segment
// represents a letter (0b00001 = A, 0b00010 = B, etc.).
//
// We'll just mask out each letter's bits and convert it to a character.
// Then append each character to a string to get the three-letter vendor ID.
// But first, we need to swap the bytes.
vid = ((vid & 0xff00) >> 8) | ((vid & 0x00ff) << 8);
std::string str = " ";
str[2] = 'A' + ((vid >> 0) & 0x1f) - 1;
str[1] = 'A' + ((vid >> 5) & 0x1f) - 1;
str[0] = 'A' + ((vid >> 10) & 0x1f) - 1;
return str;
}
OSVR_DISPLAY_EXPORT uint32_t encodeEdidVendorId(const std::string& vid)
{
// The vid is two bytes wide. The most-significant bit is always 0. The
// remaining 15 bits are split into five-bit segments. Each segment
// represents a letter (0b00001 = A, 0b00010 = B, etc.).
if (3 != vid.length()) {
throw std::invalid_argument("The EDID vendor ID may only consist of three characters.");
}
uint32_t val = 0x0000;
for (auto c : vid) {
c = static_cast<char>(std::toupper(c));
if (c < 'A' || c > 'Z') {
throw std::invalid_argument("Each letter of the EDID vendor ID must be an uppercase letter A..Z.");
}
val = val << 5;
val += static_cast<uint32_t>(c) - 'A' + 1;
}
// Swap the bytes
val = ((val & 0xff00) >> 8) | ((val & 0x00ff) << 8);
return val;
}
} // end namespace display
} // end namespace osvr
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonSession.hxx,v $
*
* $Revision: 1.29 $
*
* last change: $Author: rt $ $Date: 2007-11-07 10:03:57 $
*
* 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 _NEONSESSION_HXX_
#define _NEONSESSION_HXX_
#include <vector>
#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _DAVSESSION_HXX_
#include "DAVSession.hxx"
#endif
#ifndef _NEONTYPES_HXX_
#include "NeonTypes.hxx"
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
using namespace com::sun::star;
namespace ucbhelper { class ProxyDecider; }
namespace webdav_ucp
{
// -------------------------------------------------------------------
// NeonSession
// A DAVSession implementation using the neon/expat library
// -------------------------------------------------------------------
class NeonSession : public DAVSession
{
private:
osl::Mutex m_aMutex;
rtl::OUString m_aScheme;
rtl::OUString m_aHostName;
rtl::OUString m_aProxyName;
sal_Int32 m_nPort;
sal_Int32 m_nProxyPort;
HttpSession * m_pHttpSession;
void * m_pRequestData;
const ucbhelper::InternetProxyDecider & m_rProxyDecider;
// @@@ This should really be per-request data. But Neon currently
// (0.23.5) has no interface for passing per-request user data.
// Theoretically, a NeonSession instance could handle multiple requests
// at a time --currently it doesn't. Thus this is not an issue at the
// moment.
DAVRequestEnvironment m_aEnv;
// Note: Uncomment the following if locking support is required
// NeonLockSession * mNeonLockSession;
static bool m_bGlobalsInited;
protected:
virtual ~NeonSession();
public:
NeonSession( const rtl::Reference< DAVSessionFactory > & rSessionFactory,
const rtl::OUString& inUri,
const ucbhelper::InternetProxyDecider & rProxyDecider )
throw ( DAVException );
// DAVSession methods
virtual sal_Bool CanUse( const ::rtl::OUString & inUri );
virtual sal_Bool UsesProxy();
const DAVRequestEnvironment & getRequestEnvironment() const
{ return m_aEnv; }
virtual void
OPTIONS( const ::rtl::OUString & inPath,
DAVCapabilities & outCapabilities,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
// allprop & named
virtual void
PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
const std::vector< ::rtl::OUString > & inPropNames,
std::vector< DAVResource > & ioResources,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
// propnames
virtual void
PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
std::vector< DAVResourceInfo >& ioResInfo,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
PROPPATCH( const ::rtl::OUString & inPath,
const std::vector< ProppatchValue > & inValues,
const DAVRequestEnvironment & rEnv )
throw( DAVException );
virtual void
HEAD( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException );
virtual com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & ioOutputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & ioOutputStream,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
PUT( const ::rtl::OUString & inPath,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >
POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & oOutputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
MKCOL( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
COPY( const ::rtl::OUString & inSourceURL,
const ::rtl::OUString & inDestinationURL,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverWrite )
throw ( DAVException );
virtual void
MOVE( const ::rtl::OUString & inSourceURL,
const ::rtl::OUString & inDestinationURL,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverWrite )
throw ( DAVException );
virtual void DESTROY( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
// Note: Uncomment the following if locking support is required
/*
virtual void LOCK (const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void UNLOCK (const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
*/
// helpers
const rtl::OUString & getHostName() const { return m_aHostName; }
const ::uno::Reference< ::lang::XMultiServiceFactory > getMSF() { return m_xFactory->getServiceFactory(); }
static bool isCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name );
static void rememberCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name );
const void * getRequestData() const { return m_pRequestData; }
sal_Bool isDomainMatch( rtl::OUString certHostName );
private:
// Initialise "Neon sockets"
void Init( void )
throw ( DAVException );
void HandleError( int nError )
throw ( DAVException );
const ucbhelper::InternetProxyServer & getProxySettings() const;
// Note: Uncomment the following if locking support is required
// void Lockit( const Lock & inLock, bool inLockit )
// throw ( DAVException );
// low level GET implementation, used by public GET implementations
static int GET( ne_session * sess,
const char * uri,
ne_block_reader reader,
bool getheaders,
void * userdata );
// Buffer-based PUT implementation. Neon only has file descriptor-
// based API.
static int PUT( ne_session * sess,
const char * uri,
const char * buffer,
size_t size );
// Buffer-based POST implementation. Neon only has file descriptor-
// based API.
int POST( ne_session * sess,
const char * uri,
const char * buffer,
ne_block_reader reader,
void * userdata,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer );
// Helper: XInputStream -> Sequence< sal_Int8 >
static bool getDataFromInputStream(
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & xStream,
com::sun::star::uno::Sequence< sal_Int8 > & rData,
bool bAppendTrailingZeroByte );
typedef std::map< ::rtl::OUString, ::rtl::OUString > Map;
static Map certMap;
};
} // namespace_ucp
#endif // _NEONSESSION_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.29.42); FILE MERGED 2008/04/01 16:02:27 thb 1.29.42.3: #i85898# Stripping all external header guards 2008/04/01 12:58:27 thb 1.29.42.2: #i85898# Stripping all external header guards 2008/03/31 15:30:31 rt 1.29.42.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonSession.hxx,v $
* $Revision: 1.30 $
*
* 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 _NEONSESSION_HXX_
#define _NEONSESSION_HXX_
#include <vector>
#include <osl/mutex.hxx>
#include "DAVSession.hxx"
#include "NeonTypes.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
using namespace com::sun::star;
namespace ucbhelper { class ProxyDecider; }
namespace webdav_ucp
{
// -------------------------------------------------------------------
// NeonSession
// A DAVSession implementation using the neon/expat library
// -------------------------------------------------------------------
class NeonSession : public DAVSession
{
private:
osl::Mutex m_aMutex;
rtl::OUString m_aScheme;
rtl::OUString m_aHostName;
rtl::OUString m_aProxyName;
sal_Int32 m_nPort;
sal_Int32 m_nProxyPort;
HttpSession * m_pHttpSession;
void * m_pRequestData;
const ucbhelper::InternetProxyDecider & m_rProxyDecider;
// @@@ This should really be per-request data. But Neon currently
// (0.23.5) has no interface for passing per-request user data.
// Theoretically, a NeonSession instance could handle multiple requests
// at a time --currently it doesn't. Thus this is not an issue at the
// moment.
DAVRequestEnvironment m_aEnv;
// Note: Uncomment the following if locking support is required
// NeonLockSession * mNeonLockSession;
static bool m_bGlobalsInited;
protected:
virtual ~NeonSession();
public:
NeonSession( const rtl::Reference< DAVSessionFactory > & rSessionFactory,
const rtl::OUString& inUri,
const ucbhelper::InternetProxyDecider & rProxyDecider )
throw ( DAVException );
// DAVSession methods
virtual sal_Bool CanUse( const ::rtl::OUString & inUri );
virtual sal_Bool UsesProxy();
const DAVRequestEnvironment & getRequestEnvironment() const
{ return m_aEnv; }
virtual void
OPTIONS( const ::rtl::OUString & inPath,
DAVCapabilities & outCapabilities,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
// allprop & named
virtual void
PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
const std::vector< ::rtl::OUString > & inPropNames,
std::vector< DAVResource > & ioResources,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
// propnames
virtual void
PROPFIND( const ::rtl::OUString & inPath,
const Depth inDepth,
std::vector< DAVResourceInfo >& ioResInfo,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
PROPPATCH( const ::rtl::OUString & inPath,
const std::vector< ProppatchValue > & inValues,
const DAVRequestEnvironment & rEnv )
throw( DAVException );
virtual void
HEAD( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw( DAVException );
virtual com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & ioOutputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >
GET( const ::rtl::OUString & inPath,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
GET( const ::rtl::OUString & inPath,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & ioOutputStream,
const std::vector< ::rtl::OUString > & inHeaderNames,
DAVResource & ioResource,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
PUT( const ::rtl::OUString & inPath,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual com::sun::star::uno::Reference<
com::sun::star::io::XInputStream >
POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
POST( const rtl::OUString & inPath,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer,
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & inInputStream,
com::sun::star::uno::Reference<
com::sun::star::io::XOutputStream > & oOutputStream,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
MKCOL( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void
COPY( const ::rtl::OUString & inSourceURL,
const ::rtl::OUString & inDestinationURL,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverWrite )
throw ( DAVException );
virtual void
MOVE( const ::rtl::OUString & inSourceURL,
const ::rtl::OUString & inDestinationURL,
const DAVRequestEnvironment & rEnv,
sal_Bool inOverWrite )
throw ( DAVException );
virtual void DESTROY( const ::rtl::OUString & inPath,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
// Note: Uncomment the following if locking support is required
/*
virtual void LOCK (const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
virtual void UNLOCK (const Lock & inLock,
const DAVRequestEnvironment & rEnv )
throw ( DAVException );
*/
// helpers
const rtl::OUString & getHostName() const { return m_aHostName; }
const ::uno::Reference< ::lang::XMultiServiceFactory > getMSF() { return m_xFactory->getServiceFactory(); }
static bool isCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name );
static void rememberCertificate( const ::rtl::OUString & url, const ::rtl::OUString & certificate_name );
const void * getRequestData() const { return m_pRequestData; }
sal_Bool isDomainMatch( rtl::OUString certHostName );
private:
// Initialise "Neon sockets"
void Init( void )
throw ( DAVException );
void HandleError( int nError )
throw ( DAVException );
const ucbhelper::InternetProxyServer & getProxySettings() const;
// Note: Uncomment the following if locking support is required
// void Lockit( const Lock & inLock, bool inLockit )
// throw ( DAVException );
// low level GET implementation, used by public GET implementations
static int GET( ne_session * sess,
const char * uri,
ne_block_reader reader,
bool getheaders,
void * userdata );
// Buffer-based PUT implementation. Neon only has file descriptor-
// based API.
static int PUT( ne_session * sess,
const char * uri,
const char * buffer,
size_t size );
// Buffer-based POST implementation. Neon only has file descriptor-
// based API.
int POST( ne_session * sess,
const char * uri,
const char * buffer,
ne_block_reader reader,
void * userdata,
const rtl::OUString & rContentType,
const rtl::OUString & rReferer );
// Helper: XInputStream -> Sequence< sal_Int8 >
static bool getDataFromInputStream(
const com::sun::star::uno::Reference<
com::sun::star::io::XInputStream > & xStream,
com::sun::star::uno::Sequence< sal_Int8 > & rData,
bool bAppendTrailingZeroByte );
typedef std::map< ::rtl::OUString, ::rtl::OUString > Map;
static Map certMap;
};
} // namespace_ucp
#endif // _NEONSESSION_HXX_
<|endoftext|>
|
<commit_before>// This file is part of the AliceVision project.
// Copyright (c) 2018 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
#include <aliceVision/feature/svgVisualization.hpp>
#include "GeometricFilterMatrix_HGrowing.hpp"
namespace aliceVision {
namespace matchingImageCollection {
bool GeometricFilterMatrix_HGrowing::getMatches(const feature::EImageDescriberType &descType,
const IndexT homographyId, matching::IndMatches &matches) const
{
matches.clear();
if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
return false;
if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
return false;
matches = _HsAndMatchesPerDesc.at(descType).at(homographyId).second;
return !matches.empty();
}
std::size_t GeometricFilterMatrix_HGrowing::getNbHomographies(const feature::EImageDescriberType &descType) const
{
if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
return 0;
return _HsAndMatchesPerDesc.at(descType).size();
}
std::size_t GeometricFilterMatrix_HGrowing::getNbVerifiedMatches(const feature::EImageDescriberType &descType,
const IndexT homographyId) const
{
if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
return 0;
if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
return 0;
return _HsAndMatchesPerDesc.at(descType).at(homographyId).second.size();
}
std::size_t GeometricFilterMatrix_HGrowing::getNbAllVerifiedMatches() const
{
std::size_t counter = 0;
for (const auto & HnMs : _HsAndMatchesPerDesc)
{
for (const std::pair<Mat3, matching::IndMatches> & HnM : HnMs.second)
{
counter += HnM.second.size();
}
}
return counter;
}
bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI,
const std::vector<feature::SIOPointFeature> &featuresJ,
const matching::IndMatches &matches,
const IndexT &seedMatchId,
std::set<IndexT> &planarMatchesIndices, Mat3 &transformation,
const GrowParameters& param)
{
assert(seedMatchId <= matches.size());
planarMatchesIndices.clear();
transformation = Mat3::Identity();
const matching::IndMatch & seedMatch = matches.at(seedMatchId);
const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i);
const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j);
double currTolerance;
for (IndexT iRefineStep = 0; iRefineStep < param._nbRefiningIterations; ++iRefineStep)
{
if (iRefineStep == 0)
{
computeSimilarity(seedFeatureI, seedFeatureJ, transformation);
currTolerance = param._similarityTolerance;
}
else if (iRefineStep <= 4)
{
estimateAffinity(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
currTolerance = param._affinityTolerance;
}
else
{
estimateHomography(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
currTolerance = param._homographyTolerance;
}
findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices);
if (planarMatchesIndices.size() < param._minInliersToRefine)
return false;
// Note: the following statement is present in the MATLAB code but not implemented in YASM
// if (planarMatchesIndices.size() >= param._maxFractionPlanarMatches * matches.size())
// break;
}
return !transformation.isIdentity();
}
void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I,
const std::vector<feature::SIOPointFeature>& siofeatures_J,
const matching::IndMatches& putativeMatches,
std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
matching::IndMatches& outGeometricInliers,
const HGrowingFilteringParam& param)
{
using namespace aliceVision::feature;
using namespace aliceVision::matching;
IndMatches remainingMatches = putativeMatches;
GeometricFilterMatrix_HGrowing dummy;
for(IndexT iH = 0; iH < param._maxNbHomographies; ++iH)
{
std::set<IndexT> usedMatchesId, bestMatchesId;
Mat3 bestHomography;
// -- Estimate H using homography-growing approach
#pragma omp parallel for // (huge optimization but modify results a little)
for(int iMatch = 0; iMatch < remainingMatches.size(); ++iMatch)
{
// Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20)
// each match is used once only per homography estimation (increases computation time) [1st improvement ([F.Srajer, 2016] p. 20) ]
if (usedMatchesId.find(iMatch) != usedMatchesId.end())
continue;
std::set<IndexT> planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
Mat3 homography;
if (!growHomography(siofeatures_I,
siofeatures_J,
remainingMatches,
iMatch,
planarMatchesId,
homography,
param._growParam))
{
continue;
}
#pragma omp critical
usedMatchesId.insert(planarMatchesId.begin(), planarMatchesId.end());
if (planarMatchesId.size() > bestMatchesId.size())
{
#pragma omp critical
{
if(iH == 3) std::cout << "best iMatch" << iMatch << std::endl;
bestMatchesId = planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
bestHomography = homography;
}
}
} // 'iMatch'
// -- Refine H using Ceres minimizer
refineHomography(siofeatures_I, siofeatures_J, remainingMatches, bestHomography, bestMatchesId, param._growParam._homographyTolerance);
// stop when the models get too small
if (bestMatchesId.size() < param._minNbMatchesPerH)
break;
// Store validated results:
{
IndMatches matches;
Mat3 H = bestHomography;
for (IndexT id : bestMatchesId)
{
matches.push_back(remainingMatches.at(id));
}
homographiesAndMatches.emplace_back(H, matches);
}
// -- Update not used matches & Save geometrically verified matches
for (IndexT id : bestMatchesId)
{
outGeometricInliers.push_back(remainingMatches.at(id));
}
// update remaining matches (/!\ Keep ordering)
std::size_t cpt = 0;
for (IndexT id : bestMatchesId)
{
remainingMatches.erase(remainingMatches.begin() + id - cpt);
++cpt;
}
// stop when the number of remaining matches is too small
if (remainingMatches.size() < param._minNbMatchesPerH)
break;
} // 'iH'
}
void drawHomographyMatches(const sfmData::View &viewI,
const sfmData::View &viewJ,
const std::vector<feature::SIOPointFeature> &siofeatures_I,
const std::vector<feature::SIOPointFeature> &siofeatures_J,
const std::vector<std::pair<Mat3, matching::IndMatches>> &homographiesAndMatches,
const matching::IndMatches &putativeMatches,
const std::string &outFilename)
{
const std::string& imagePathLeft = viewI.getImagePath();
const std::string& imagePathRight = viewJ.getImagePath();
const auto imageSizeLeft = std::make_pair(viewI.getWidth(), viewI.getHeight());
const auto imageSizeRight = std::make_pair(viewJ.getWidth(), viewJ.getHeight());
drawHomographyMatches(imagePathLeft,
imageSizeLeft,
siofeatures_I,
imagePathRight,
imageSizeRight,
siofeatures_J,
homographiesAndMatches,
putativeMatches,
outFilename);
}
}
}<commit_msg>[matching] HGrowing: remove trailing cout<commit_after>// This file is part of the AliceVision project.
// Copyright (c) 2018 AliceVision contributors.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
#include <aliceVision/feature/svgVisualization.hpp>
#include "GeometricFilterMatrix_HGrowing.hpp"
namespace aliceVision {
namespace matchingImageCollection {
bool GeometricFilterMatrix_HGrowing::getMatches(const feature::EImageDescriberType &descType,
const IndexT homographyId, matching::IndMatches &matches) const
{
matches.clear();
if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
return false;
if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
return false;
matches = _HsAndMatchesPerDesc.at(descType).at(homographyId).second;
return !matches.empty();
}
std::size_t GeometricFilterMatrix_HGrowing::getNbHomographies(const feature::EImageDescriberType &descType) const
{
if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
return 0;
return _HsAndMatchesPerDesc.at(descType).size();
}
std::size_t GeometricFilterMatrix_HGrowing::getNbVerifiedMatches(const feature::EImageDescriberType &descType,
const IndexT homographyId) const
{
if (_HsAndMatchesPerDesc.find(descType) == _HsAndMatchesPerDesc.end())
return 0;
if (homographyId > _HsAndMatchesPerDesc.at(descType).size() - 1)
return 0;
return _HsAndMatchesPerDesc.at(descType).at(homographyId).second.size();
}
std::size_t GeometricFilterMatrix_HGrowing::getNbAllVerifiedMatches() const
{
std::size_t counter = 0;
for (const auto & HnMs : _HsAndMatchesPerDesc)
{
for (const std::pair<Mat3, matching::IndMatches> & HnM : HnMs.second)
{
counter += HnM.second.size();
}
}
return counter;
}
bool growHomography(const std::vector<feature::SIOPointFeature> &featuresI,
const std::vector<feature::SIOPointFeature> &featuresJ,
const matching::IndMatches &matches,
const IndexT &seedMatchId,
std::set<IndexT> &planarMatchesIndices, Mat3 &transformation,
const GrowParameters& param)
{
assert(seedMatchId <= matches.size());
planarMatchesIndices.clear();
transformation = Mat3::Identity();
const matching::IndMatch & seedMatch = matches.at(seedMatchId);
const feature::SIOPointFeature & seedFeatureI = featuresI.at(seedMatch._i);
const feature::SIOPointFeature & seedFeatureJ = featuresJ.at(seedMatch._j);
double currTolerance;
for (IndexT iRefineStep = 0; iRefineStep < param._nbRefiningIterations; ++iRefineStep)
{
if (iRefineStep == 0)
{
computeSimilarity(seedFeatureI, seedFeatureJ, transformation);
currTolerance = param._similarityTolerance;
}
else if (iRefineStep <= 4)
{
estimateAffinity(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
currTolerance = param._affinityTolerance;
}
else
{
estimateHomography(featuresI, featuresJ, matches, transformation, planarMatchesIndices);
currTolerance = param._homographyTolerance;
}
findTransformationInliers(featuresI, featuresJ, matches, transformation, currTolerance, planarMatchesIndices);
if (planarMatchesIndices.size() < param._minInliersToRefine)
return false;
// Note: the following statement is present in the MATLAB code but not implemented in YASM
// if (planarMatchesIndices.size() >= param._maxFractionPlanarMatches * matches.size())
// break;
}
return !transformation.isIdentity();
}
void filterMatchesByHGrowing(const std::vector<feature::SIOPointFeature>& siofeatures_I,
const std::vector<feature::SIOPointFeature>& siofeatures_J,
const matching::IndMatches& putativeMatches,
std::vector<std::pair<Mat3, matching::IndMatches>>& homographiesAndMatches,
matching::IndMatches& outGeometricInliers,
const HGrowingFilteringParam& param)
{
using namespace aliceVision::feature;
using namespace aliceVision::matching;
IndMatches remainingMatches = putativeMatches;
GeometricFilterMatrix_HGrowing dummy;
for(IndexT iH = 0; iH < param._maxNbHomographies; ++iH)
{
std::set<IndexT> usedMatchesId, bestMatchesId;
Mat3 bestHomography;
// -- Estimate H using homography-growing approach
#pragma omp parallel for // (huge optimization but modify results a little)
for(int iMatch = 0; iMatch < remainingMatches.size(); ++iMatch)
{
// Growing a homography from one match ([F.Srajer, 2016] algo. 1, p. 20)
// each match is used once only per homography estimation (increases computation time) [1st improvement ([F.Srajer, 2016] p. 20) ]
if (usedMatchesId.find(iMatch) != usedMatchesId.end())
continue;
std::set<IndexT> planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
Mat3 homography;
if (!growHomography(siofeatures_I,
siofeatures_J,
remainingMatches,
iMatch,
planarMatchesId,
homography,
param._growParam))
{
continue;
}
#pragma omp critical
usedMatchesId.insert(planarMatchesId.begin(), planarMatchesId.end());
if (planarMatchesId.size() > bestMatchesId.size())
{
#pragma omp critical
{
// if(iH == 3) { std::cout << "best iMatch" << iMatch << std::endl; }
bestMatchesId = planarMatchesId; // be careful: it contains the id. in the 'remainingMatches' vector not 'putativeMatches' vector.
bestHomography = homography;
}
}
} // 'iMatch'
// -- Refine H using Ceres minimizer
refineHomography(siofeatures_I, siofeatures_J, remainingMatches, bestHomography, bestMatchesId, param._growParam._homographyTolerance);
// stop when the models get too small
if (bestMatchesId.size() < param._minNbMatchesPerH)
break;
// Store validated results:
{
IndMatches matches;
Mat3 H = bestHomography;
for (IndexT id : bestMatchesId)
{
matches.push_back(remainingMatches.at(id));
}
homographiesAndMatches.emplace_back(H, matches);
}
// -- Update not used matches & Save geometrically verified matches
for (IndexT id : bestMatchesId)
{
outGeometricInliers.push_back(remainingMatches.at(id));
}
// update remaining matches (/!\ Keep ordering)
std::size_t cpt = 0;
for (IndexT id : bestMatchesId)
{
remainingMatches.erase(remainingMatches.begin() + id - cpt);
++cpt;
}
// stop when the number of remaining matches is too small
if (remainingMatches.size() < param._minNbMatchesPerH)
break;
} // 'iH'
}
void drawHomographyMatches(const sfmData::View &viewI,
const sfmData::View &viewJ,
const std::vector<feature::SIOPointFeature> &siofeatures_I,
const std::vector<feature::SIOPointFeature> &siofeatures_J,
const std::vector<std::pair<Mat3, matching::IndMatches>> &homographiesAndMatches,
const matching::IndMatches &putativeMatches,
const std::string &outFilename)
{
const std::string& imagePathLeft = viewI.getImagePath();
const std::string& imagePathRight = viewJ.getImagePath();
const auto imageSizeLeft = std::make_pair(viewI.getWidth(), viewI.getHeight());
const auto imageSizeRight = std::make_pair(viewJ.getWidth(), viewJ.getHeight());
drawHomographyMatches(imagePathLeft,
imageSizeLeft,
siofeatures_I,
imagePathRight,
imageSizeRight,
siofeatures_J,
homographiesAndMatches,
putativeMatches,
outFilename);
}
}
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnetworksession_p.h"
#include "qnetworksession.h"
#include "qnetworksessionengine_win_p.h"
#include "qnlaengine_win_p.h"
#ifndef Q_OS_WINCE
#include "qnativewifiengine_win_p.h"
#include "qioctlwifiengine_win_p.h"
#endif
#include <QtCore/qstringlist.h>
#include <QtCore/qdebug.h>
#include <QtCore/qmutex.h>
#include <QtNetwork/qnetworkinterface.h>
QT_BEGIN_NAMESPACE
static QNetworkSessionEngine *getEngineFromId(const QString &id)
{
QNlaEngine *nla = QNlaEngine::instance();
if (nla && nla->hasIdentifier(id))
return nla;
#ifndef Q_OS_WINCE
QNativeWifiEngine *nativeWifi = QNativeWifiEngine::instance();
if (nativeWifi && nativeWifi->hasIdentifier(id))
return nativeWifi;
QIoctlWifiEngine *ioctlWifi = QIoctlWifiEngine::instance();
if (ioctlWifi && ioctlWifi->hasIdentifier(id))
return ioctlWifi;
#endif
return 0;
}
class QNetworkSessionManagerPrivate : public QObject
{
Q_OBJECT
public:
QNetworkSessionManagerPrivate(QObject *parent = 0);
~QNetworkSessionManagerPrivate();
void forceSessionClose(const QNetworkConfiguration &config);
Q_SIGNALS:
void forcedSessionClose(const QNetworkConfiguration &config);
};
#include "qnetworksession_win.moc"
Q_GLOBAL_STATIC(QNetworkSessionManagerPrivate, sessionManager);
QNetworkSessionManagerPrivate::QNetworkSessionManagerPrivate(QObject *parent)
: QObject(parent)
{
}
QNetworkSessionManagerPrivate::~QNetworkSessionManagerPrivate()
{
}
void QNetworkSessionManagerPrivate::forceSessionClose(const QNetworkConfiguration &config)
{
emit forcedSessionClose(config);
}
void QNetworkSessionPrivate::syncStateWithInterface()
{
connect(&manager, SIGNAL(updateCompleted()), this, SLOT(networkConfigurationsChanged()));
connect(&manager, SIGNAL(configurationChanged(QNetworkConfiguration)),
this, SLOT(configurationChanged(QNetworkConfiguration)));
connect(sessionManager(), SIGNAL(forcedSessionClose(QNetworkConfiguration)),
this, SLOT(forcedSessionClose(QNetworkConfiguration)));
opened = false;
state = QNetworkSession::Invalid;
lastError = QNetworkSession::UnknownSessionError;
qRegisterMetaType<QNetworkSessionEngine::ConnectionError>
("QNetworkSessionEngine::ConnectionError");
switch (publicConfig.type()) {
case QNetworkConfiguration::InternetAccessPoint:
activeConfig = publicConfig;
engine = getEngineFromId(activeConfig.identifier());
connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
Qt::QueuedConnection);
break;
case QNetworkConfiguration::ServiceNetwork:
serviceConfig = publicConfig;
// Defer setting engine and signals until open().
// fall through
case QNetworkConfiguration::UserChoice:
// Defer setting serviceConfig and activeConfig until open().
// fall through
default:
engine = 0;
}
networkConfigurationsChanged();
}
void QNetworkSessionPrivate::open()
{
if (serviceConfig.isValid()) {
lastError = QNetworkSession::OperationNotSupportedError;
emit q->error(lastError);
} else if (!isActive) {
if ((activeConfig.state() & QNetworkConfiguration::Discovered) !=
QNetworkConfiguration::Discovered) {
lastError =QNetworkSession::InvalidConfigurationError;
emit q->error(lastError);
return;
}
opened = true;
if ((activeConfig.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active &&
(activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) {
state = QNetworkSession::Connecting;
emit q->stateChanged(state);
engine->connectToId(activeConfig.identifier());
}
isActive = (activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active;
if (isActive)
emit quitPendingWaitsForOpened();
}
}
void QNetworkSessionPrivate::close()
{
if (serviceConfig.isValid()) {
lastError = QNetworkSession::OperationNotSupportedError;
emit q->error(lastError);
} else if (isActive) {
opened = false;
isActive = false;
emit q->sessionClosed();
}
}
void QNetworkSessionPrivate::stop()
{
if (serviceConfig.isValid()) {
lastError = QNetworkSession::OperationNotSupportedError;
emit q->error(lastError);
} else {
if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
state = QNetworkSession::Closing;
emit q->stateChanged(state);
engine->disconnectFromId(activeConfig.identifier());
sessionManager()->forceSessionClose(activeConfig);
}
opened = false;
isActive = false;
emit q->sessionClosed();
}
}
void QNetworkSessionPrivate::migrate()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
void QNetworkSessionPrivate::accept()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
void QNetworkSessionPrivate::ignore()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
void QNetworkSessionPrivate::reject()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
QNetworkInterface QNetworkSessionPrivate::currentInterface() const
{
if (!publicConfig.isValid() || !engine || state != QNetworkSession::Connected)
return QNetworkInterface();
QString interface = engine->getInterfaceFromId(activeConfig.identifier());
if (interface.isEmpty())
return QNetworkInterface();
return QNetworkInterface::interfaceFromName(interface);
}
QVariant QNetworkSessionPrivate::property(const QString&)
{
return QVariant();
}
QString QNetworkSessionPrivate::bearerName() const
{
if (!publicConfig.isValid() || !engine)
return QString();
return engine->bearerName(activeConfig.identifier());
}
QString QNetworkSessionPrivate::errorString() const
{
switch (lastError) {
case QNetworkSession::UnknownSessionError:
return tr("Unknown session error.");
case QNetworkSession::SessionAbortedError:
return tr("The session was aborted by the user or system.");
case QNetworkSession::OperationNotSupportedError:
return tr("The requested operation is not supported by the system.");
case QNetworkSession::InvalidConfigurationError:
return tr("The specified configuration cannot be used.");
}
return QString();
}
QNetworkSession::SessionError QNetworkSessionPrivate::error() const
{
return lastError;
}
quint64 QNetworkSessionPrivate::sentData() const
{
return tx_data;
}
quint64 QNetworkSessionPrivate::receivedData() const
{
return rx_data;
}
quint64 QNetworkSessionPrivate::activeTime() const
{
return m_activeTime;
}
void QNetworkSessionPrivate::updateStateFromServiceNetwork()
{
QNetworkSession::State oldState = state;
foreach (const QNetworkConfiguration &config, serviceConfig.children()) {
if ((config.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active)
continue;
if (activeConfig != config) {
if (engine) {
disconnect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)));
}
activeConfig = config;
engine = getEngineFromId(activeConfig.identifier());
connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
Qt::QueuedConnection);
emit q->newConfigurationActivated();
}
state = QNetworkSession::Connected;
if (state != oldState)
emit q->stateChanged(state);
return;
}
// No active configurations found, must be disconnected.
state = QNetworkSession::Disconnected;
if (state != oldState)
emit q->stateChanged(state);
}
void QNetworkSessionPrivate::updateStateFromActiveConfig()
{
QNetworkSession::State oldState = state;
bool newActive = false;
if (!activeConfig.isValid()) {
state = QNetworkSession::Invalid;
} else if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
state = QNetworkSession::Connected;
newActive = opened;
} else if ((activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) {
state = QNetworkSession::Disconnected;
} else if ((activeConfig.state() & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
state = QNetworkSession::NotAvailable;
} else if ((activeConfig.state() & QNetworkConfiguration::Undefined) == QNetworkConfiguration::Undefined) {
state = QNetworkSession::NotAvailable;
}
bool oldActive = isActive;
isActive = newActive;
if (!oldActive && isActive)
emit quitPendingWaitsForOpened();
if (oldActive && !isActive)
emit q->sessionClosed();
if (oldState != state)
emit q->stateChanged(state);
}
void QNetworkSessionPrivate::networkConfigurationsChanged()
{
if (serviceConfig.isValid())
updateStateFromServiceNetwork();
else
updateStateFromActiveConfig();
}
void QNetworkSessionPrivate::configurationChanged(const QNetworkConfiguration &config)
{
if (serviceConfig.isValid() && (config == serviceConfig || config == activeConfig))
updateStateFromServiceNetwork();
else if (config == activeConfig)
updateStateFromActiveConfig();
}
void QNetworkSessionPrivate::forcedSessionClose(const QNetworkConfiguration &config)
{
if (activeConfig == config) {
opened = false;
isActive = false;
emit q->sessionClosed();
lastError = QNetworkSession::SessionAbortedError;
emit q->error(lastError);
}
}
void QNetworkSessionPrivate::connectionError(const QString &id, QNetworkSessionEngine::ConnectionError error)
{
if (activeConfig.identifier() == id) {
switch (error) {
case QNetworkSessionEngine::OperationNotSupported:
lastError = QNetworkSession::OperationNotSupportedError;
opened = false;
break;
case QNetworkSessionEngine::InterfaceLookupError:
case QNetworkSessionEngine::ConnectError:
case QNetworkSessionEngine::DisconnectionError:
default:
lastError = QNetworkSession::UnknownSessionError;
}
emit q->error(lastError);
}
}
QT_END_NAMESPACE
<commit_msg>Fix incorrect session state.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, 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.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnetworksession_p.h"
#include "qnetworksession.h"
#include "qnetworksessionengine_win_p.h"
#include "qnlaengine_win_p.h"
#ifndef Q_OS_WINCE
#include "qnativewifiengine_win_p.h"
#include "qioctlwifiengine_win_p.h"
#endif
#include <QtCore/qstringlist.h>
#include <QtCore/qdebug.h>
#include <QtCore/qmutex.h>
#include <QtNetwork/qnetworkinterface.h>
QT_BEGIN_NAMESPACE
static QNetworkSessionEngine *getEngineFromId(const QString &id)
{
QNlaEngine *nla = QNlaEngine::instance();
if (nla && nla->hasIdentifier(id))
return nla;
#ifndef Q_OS_WINCE
QNativeWifiEngine *nativeWifi = QNativeWifiEngine::instance();
if (nativeWifi && nativeWifi->hasIdentifier(id))
return nativeWifi;
QIoctlWifiEngine *ioctlWifi = QIoctlWifiEngine::instance();
if (ioctlWifi && ioctlWifi->hasIdentifier(id))
return ioctlWifi;
#endif
return 0;
}
class QNetworkSessionManagerPrivate : public QObject
{
Q_OBJECT
public:
QNetworkSessionManagerPrivate(QObject *parent = 0);
~QNetworkSessionManagerPrivate();
void forceSessionClose(const QNetworkConfiguration &config);
Q_SIGNALS:
void forcedSessionClose(const QNetworkConfiguration &config);
};
#include "qnetworksession_win.moc"
Q_GLOBAL_STATIC(QNetworkSessionManagerPrivate, sessionManager);
QNetworkSessionManagerPrivate::QNetworkSessionManagerPrivate(QObject *parent)
: QObject(parent)
{
}
QNetworkSessionManagerPrivate::~QNetworkSessionManagerPrivate()
{
}
void QNetworkSessionManagerPrivate::forceSessionClose(const QNetworkConfiguration &config)
{
emit forcedSessionClose(config);
}
void QNetworkSessionPrivate::syncStateWithInterface()
{
connect(&manager, SIGNAL(updateCompleted()), this, SLOT(networkConfigurationsChanged()));
connect(&manager, SIGNAL(configurationChanged(QNetworkConfiguration)),
this, SLOT(configurationChanged(QNetworkConfiguration)));
connect(sessionManager(), SIGNAL(forcedSessionClose(QNetworkConfiguration)),
this, SLOT(forcedSessionClose(QNetworkConfiguration)));
opened = false;
state = QNetworkSession::Invalid;
lastError = QNetworkSession::UnknownSessionError;
qRegisterMetaType<QNetworkSessionEngine::ConnectionError>
("QNetworkSessionEngine::ConnectionError");
switch (publicConfig.type()) {
case QNetworkConfiguration::InternetAccessPoint:
activeConfig = publicConfig;
engine = getEngineFromId(activeConfig.identifier());
connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
Qt::QueuedConnection);
break;
case QNetworkConfiguration::ServiceNetwork:
serviceConfig = publicConfig;
// Defer setting engine and signals until open().
// fall through
case QNetworkConfiguration::UserChoice:
// Defer setting serviceConfig and activeConfig until open().
// fall through
default:
engine = 0;
}
networkConfigurationsChanged();
}
void QNetworkSessionPrivate::open()
{
if (serviceConfig.isValid()) {
lastError = QNetworkSession::OperationNotSupportedError;
emit q->error(lastError);
} else if (!isActive) {
if ((activeConfig.state() & QNetworkConfiguration::Discovered) !=
QNetworkConfiguration::Discovered) {
lastError =QNetworkSession::InvalidConfigurationError;
emit q->error(lastError);
return;
}
opened = true;
if ((activeConfig.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active &&
(activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) {
state = QNetworkSession::Connecting;
emit q->stateChanged(state);
engine->connectToId(activeConfig.identifier());
}
isActive = (activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active;
if (isActive)
emit quitPendingWaitsForOpened();
}
}
void QNetworkSessionPrivate::close()
{
if (serviceConfig.isValid()) {
lastError = QNetworkSession::OperationNotSupportedError;
emit q->error(lastError);
} else if (isActive) {
opened = false;
isActive = false;
emit q->sessionClosed();
}
}
void QNetworkSessionPrivate::stop()
{
if (serviceConfig.isValid()) {
lastError = QNetworkSession::OperationNotSupportedError;
emit q->error(lastError);
} else {
if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
state = QNetworkSession::Closing;
emit q->stateChanged(state);
engine->disconnectFromId(activeConfig.identifier());
sessionManager()->forceSessionClose(activeConfig);
}
opened = false;
isActive = false;
emit q->sessionClosed();
}
}
void QNetworkSessionPrivate::migrate()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
void QNetworkSessionPrivate::accept()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
void QNetworkSessionPrivate::ignore()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
void QNetworkSessionPrivate::reject()
{
qFatal("Function not implemented at %s.", __FUNCTION__);
}
QNetworkInterface QNetworkSessionPrivate::currentInterface() const
{
if (!publicConfig.isValid() || !engine || state != QNetworkSession::Connected)
return QNetworkInterface();
QString interface = engine->getInterfaceFromId(activeConfig.identifier());
if (interface.isEmpty())
return QNetworkInterface();
return QNetworkInterface::interfaceFromName(interface);
}
QVariant QNetworkSessionPrivate::property(const QString&)
{
return QVariant();
}
QString QNetworkSessionPrivate::bearerName() const
{
if (!publicConfig.isValid() || !engine)
return QString();
return engine->bearerName(activeConfig.identifier());
}
QString QNetworkSessionPrivate::errorString() const
{
switch (lastError) {
case QNetworkSession::UnknownSessionError:
return tr("Unknown session error.");
case QNetworkSession::SessionAbortedError:
return tr("The session was aborted by the user or system.");
case QNetworkSession::OperationNotSupportedError:
return tr("The requested operation is not supported by the system.");
case QNetworkSession::InvalidConfigurationError:
return tr("The specified configuration cannot be used.");
}
return QString();
}
QNetworkSession::SessionError QNetworkSessionPrivate::error() const
{
return lastError;
}
quint64 QNetworkSessionPrivate::sentData() const
{
return tx_data;
}
quint64 QNetworkSessionPrivate::receivedData() const
{
return rx_data;
}
quint64 QNetworkSessionPrivate::activeTime() const
{
return m_activeTime;
}
void QNetworkSessionPrivate::updateStateFromServiceNetwork()
{
QNetworkSession::State oldState = state;
foreach (const QNetworkConfiguration &config, serviceConfig.children()) {
if ((config.state() & QNetworkConfiguration::Active) != QNetworkConfiguration::Active)
continue;
if (activeConfig != config) {
if (engine) {
disconnect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)));
}
activeConfig = config;
engine = getEngineFromId(activeConfig.identifier());
connect(engine, SIGNAL(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
this, SLOT(connectionError(QString,QNetworkSessionEngine::ConnectionError)),
Qt::QueuedConnection);
emit q->newConfigurationActivated();
}
state = QNetworkSession::Connected;
if (state != oldState)
emit q->stateChanged(state);
return;
}
if (serviceConfig.children().isEmpty())
state = QNetworkSession::NotAvailable;
else
state = QNetworkSession::Disconnected;
if (state != oldState)
emit q->stateChanged(state);
}
void QNetworkSessionPrivate::updateStateFromActiveConfig()
{
QNetworkSession::State oldState = state;
bool newActive = false;
if (!activeConfig.isValid()) {
state = QNetworkSession::Invalid;
} else if ((activeConfig.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) {
state = QNetworkSession::Connected;
newActive = opened;
} else if ((activeConfig.state() & QNetworkConfiguration::Discovered) == QNetworkConfiguration::Discovered) {
state = QNetworkSession::Disconnected;
} else if ((activeConfig.state() & QNetworkConfiguration::Defined) == QNetworkConfiguration::Defined) {
state = QNetworkSession::NotAvailable;
} else if ((activeConfig.state() & QNetworkConfiguration::Undefined) == QNetworkConfiguration::Undefined) {
state = QNetworkSession::NotAvailable;
}
bool oldActive = isActive;
isActive = newActive;
if (!oldActive && isActive)
emit quitPendingWaitsForOpened();
if (oldActive && !isActive)
emit q->sessionClosed();
if (oldState != state)
emit q->stateChanged(state);
}
void QNetworkSessionPrivate::networkConfigurationsChanged()
{
if (serviceConfig.isValid())
updateStateFromServiceNetwork();
else
updateStateFromActiveConfig();
}
void QNetworkSessionPrivate::configurationChanged(const QNetworkConfiguration &config)
{
if (serviceConfig.isValid() && (config == serviceConfig || config == activeConfig))
updateStateFromServiceNetwork();
else if (config == activeConfig)
updateStateFromActiveConfig();
}
void QNetworkSessionPrivate::forcedSessionClose(const QNetworkConfiguration &config)
{
if (activeConfig == config) {
opened = false;
isActive = false;
emit q->sessionClosed();
lastError = QNetworkSession::SessionAbortedError;
emit q->error(lastError);
}
}
void QNetworkSessionPrivate::connectionError(const QString &id, QNetworkSessionEngine::ConnectionError error)
{
if (activeConfig.identifier() == id) {
switch (error) {
case QNetworkSessionEngine::OperationNotSupported:
lastError = QNetworkSession::OperationNotSupportedError;
opened = false;
break;
case QNetworkSessionEngine::InterfaceLookupError:
case QNetworkSessionEngine::ConnectError:
case QNetworkSessionEngine::DisconnectionError:
default:
lastError = QNetworkSession::UnknownSessionError;
}
emit q->error(lastError);
}
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>/**
*
* main
* ledger-core
*
* Created by Pierre Pollastri on 15/09/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 <algorithm>
#include <gtest/gtest.h>
#include <iostream>
#include <memory>
#include <vector>
#include <api/OperationType.hpp>
#include <api/TimePeriod.hpp>
#include <utils/DateUtils.hpp>
#include <utils/Option.hpp>
#include <wallet/common/BalanceHistory.hpp>
using namespace ledger::core;
using namespace std;
using namespace std::chrono;
struct DummyOperation {
int32_t amount;
api::OperationType ty;
system_clock::time_point date;
DummyOperation(int32_t amount_, api::OperationType ty_, system_clock::time_point date_)
: amount(amount_), ty(ty_), date(date_) {
}
~DummyOperation() = default;
};
TEST(BalanceHistory, ZeroesOutOfRange) {
// a basic collections of “operations” with nothing
std::vector<DummyOperation> operations;
auto start = DateUtils::fromJSON("2019-01-01T00:00:00Z");
auto end = DateUtils::fromJSON("2019-02-01T00:00:00Z");
auto balances = agnostic::getBalanceHistoryFor<int32_t, int32_t, int32_t>(
start,
end,
api::TimePeriod::DAY,
operations.cbegin(),
operations.cend(),
[](DummyOperation& op) { return op.date; },
[](DummyOperation& op) { return op.ty; },
[](DummyOperation& op) { return op.amount; },
[](DummyOperation&) { return Option<int32_t>(); },
0
);
auto size = balances.size();
EXPECT_EQ(size, 31);
auto all_zero = all_of(balances.cbegin(), balances.cend(), [](shared_ptr<int32_t> const& balance) {
return *balance == 0;
});
EXPECT_TRUE(all_zero);
}
<commit_msg>Add more getBalanceHistoryFor unit tests.<commit_after>/**
*
* main
* ledger-core
*
* Created by Pierre Pollastri on 15/09/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 <algorithm>
#include <gtest/gtest.h>
#include <iostream>
#include <memory>
#include <vector>
#include <api/OperationType.hpp>
#include <api/TimePeriod.hpp>
#include <utils/DateUtils.hpp>
#include <utils/Option.hpp>
#include <wallet/common/BalanceHistory.hpp>
using namespace ledger::core;
using namespace std;
using namespace std::chrono;
struct DummyOperation {
int32_t amount;
api::OperationType ty;
system_clock::time_point date;
DummyOperation(int32_t amount_, api::OperationType ty_, system_clock::time_point date_)
: amount(amount_), ty(ty_), date(date_) {
}
~DummyOperation() = default;
};
TEST(BalanceHistory, ZeroesOutOfRange) {
// a basic collections of “operations” with nothing
std::vector<DummyOperation> operations;
auto start = DateUtils::fromJSON("2019-01-01T00:00:00Z");
auto end = DateUtils::fromJSON("2019-02-01T00:00:00Z");
auto balances = agnostic::getBalanceHistoryFor<int32_t, int32_t, int32_t>(
start,
end,
api::TimePeriod::DAY,
operations.cbegin(),
operations.cend(),
[](DummyOperation& op) { return op.date; },
[](DummyOperation& op) { return op.ty; },
[](DummyOperation& op) { return op.amount; },
[](DummyOperation&) { return Option<int32_t>(); },
0
);
auto size = balances.size();
EXPECT_EQ(size, 31);
auto all_zero = all_of(balances.cbegin(), balances.cend(), [](shared_ptr<int32_t> const& balance) {
return *balance == 0;
});
EXPECT_TRUE(all_zero);
}
TEST(BalanceHistory, CorrectBalances) {
// a basic collections of “operations” with nothing
std::vector<DummyOperation> operations = {
DummyOperation(10, api::OperationType::RECEIVE, DateUtils::fromJSON("2019-01-01T00:00:00Z")),
DummyOperation(12, api::OperationType::RECEIVE, DateUtils::fromJSON("2019-01-01T00:01:00Z")),
DummyOperation(5, api::OperationType::SEND, DateUtils::fromJSON("2019-01-02T04:00:00Z")),
DummyOperation(3, api::OperationType::SEND, DateUtils::fromJSON("2019-01-02T04:30:00Z"))
};
auto start = DateUtils::fromJSON("2019-01-01T00:00:00Z");
auto end = DateUtils::fromJSON("2019-02-01T00:00:00Z");
auto balances = agnostic::getBalanceHistoryFor<int32_t, int32_t, int32_t>(
start,
end,
api::TimePeriod::DAY,
operations.cbegin(),
operations.cend(),
[](DummyOperation& op) { return op.date; },
[](DummyOperation& op) { return op.ty; },
[](DummyOperation& op) { return op.amount; },
[](DummyOperation&) { return Option<int32_t>(); },
0
);
auto size = balances.size();
EXPECT_EQ(size, 31);
EXPECT_EQ(*balances[0], 22);
EXPECT_EQ(*balances[1], 14);
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>
using namespace std;
namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
enum {
ret = (Size == Dynamic) ? Dynamic : Size+1
};
};
}
}
template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
typedef typename POLYNOMIAL::Index Index;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename SOLVER::RootsType RootsType;
typedef Matrix<Scalar,Deg,1> EvalRootsType;
const Index deg = pols.size()-1;
psolve.compute( pols );
const RootsType& roots( psolve.roots() );
EvalRootsType evr( deg );
for( int i=0; i<roots.size(); ++i ){
evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }
bool evalToZero = evr.isZero( test_precision<Scalar>() );
if( !evalToZero )
{
cerr << "WRONG root: " << endl;
cerr << "Polynomial: " << pols.transpose() << endl;
cerr << "Roots found: " << roots.transpose() << endl;
cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
cerr << endl;
}
std::vector<Scalar> rootModuli( roots.size() );
Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
aux = roots.array().abs();
std::sort( rootModuli.begin(), rootModuli.end() );
bool distinctModuli=true;
for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
{
if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
distinctModuli = false; }
}
VERIFY( evalToZero || !distinctModuli );
return distinctModuli;
}
template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}
template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
using std::sqrt;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
{
//It is supposed that
// 1) the roots found are correct
// 2) the roots have distinct moduli
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename REAL_ROOTS::Scalar Real;
//Test realRoots
std::vector< Real > calc_realRoots;
psolve.realRoots( calc_realRoots );
VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );
const Scalar psPrec = sqrt( test_precision<Scalar>() );
for( size_t i=0; i<calc_realRoots.size(); ++i )
{
bool found = false;
for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
{
if( internal::isApprox( calc_realRoots[i], real_roots[j], psPrec ) ){
found = true; }
}
VERIFY( found );
}
//Test greatestRoot
VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
abs( psolve.greatestRoot() ), psPrec ) );
//Test smallestRoot
VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
abs( psolve.smallestRoot() ), psPrec ) );
bool hasRealRoot;
//Test absGreatestRealRoot
Real r = psolve.absGreatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) ); }
//Test absSmallestRealRoot
r = psolve.absSmallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }
//Test greatestRealRoot
r = psolve.greatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }
//Test smallestRealRoot
r = psolve.smallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
}
}
template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
typedef internal::increment_if_fixed_size<_Deg> Dim;
typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;
typedef Matrix<_Scalar,_Deg,1> EvalRootsType;
cout << "Standard cases" << endl;
PolynomialType pols = PolynomialType::Random(deg+1);
evalSolver<_Deg,PolynomialType>( pols );
cout << "Hard cases" << endl;
_Scalar multipleRoot = internal::random<_Scalar>();
EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
roots_to_monicPolynomial( allRoots, pols );
evalSolver<_Deg,PolynomialType>( pols );
cout << "Test sugar" << endl;
EvalRootsType realRoots = EvalRootsType::Random(deg);
roots_to_monicPolynomial( realRoots, pols );
evalSolverSugarFunction<_Deg>(
pols,
realRoots.template cast <
std::complex<
typename NumTraits<_Scalar>::Real
>
>(),
realRoots );
}
void test_polynomialsolver()
{
for(int i = 0; i < g_repeat; i++)
{
CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );
CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
internal::random<int>(9,13)
)) );
CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
internal::random<int>(9,13)
)) );
}
}
<commit_msg>PolynomialSolver: add a test to reveal a bug.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <unsupported/Eigen/Polynomials>
#include <iostream>
#include <algorithm>
using namespace std;
namespace Eigen {
namespace internal {
template<int Size>
struct increment_if_fixed_size
{
enum {
ret = (Size == Dynamic) ? Dynamic : Size+1
};
};
}
}
template<int Deg, typename POLYNOMIAL, typename SOLVER>
bool aux_evalSolver( const POLYNOMIAL& pols, SOLVER& psolve )
{
typedef typename POLYNOMIAL::Index Index;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename SOLVER::RootsType RootsType;
typedef Matrix<Scalar,Deg,1> EvalRootsType;
const Index deg = pols.size()-1;
psolve.compute( pols );
const RootsType& roots( psolve.roots() );
EvalRootsType evr( deg );
for( int i=0; i<roots.size(); ++i ){
evr[i] = std::abs( poly_eval( pols, roots[i] ) ); }
bool evalToZero = evr.isZero( test_precision<Scalar>() );
if( !evalToZero )
{
cerr << "WRONG root: " << endl;
cerr << "Polynomial: " << pols.transpose() << endl;
cerr << "Roots found: " << roots.transpose() << endl;
cerr << "Abs value of the polynomial at the roots: " << evr.transpose() << endl;
cerr << endl;
}
std::vector<Scalar> rootModuli( roots.size() );
Map< EvalRootsType > aux( &rootModuli[0], roots.size() );
aux = roots.array().abs();
std::sort( rootModuli.begin(), rootModuli.end() );
bool distinctModuli=true;
for( size_t i=1; i<rootModuli.size() && distinctModuli; ++i )
{
if( internal::isApprox( rootModuli[i], rootModuli[i-1] ) ){
distinctModuli = false; }
}
VERIFY( evalToZero || !distinctModuli );
return distinctModuli;
}
template<int Deg, typename POLYNOMIAL>
void evalSolver( const POLYNOMIAL& pols )
{
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve );
}
template< int Deg, typename POLYNOMIAL, typename ROOTS, typename REAL_ROOTS >
void evalSolverSugarFunction( const POLYNOMIAL& pols, const ROOTS& roots, const REAL_ROOTS& real_roots )
{
using std::sqrt;
typedef typename POLYNOMIAL::Scalar Scalar;
typedef PolynomialSolver<Scalar, Deg > PolynomialSolverType;
PolynomialSolverType psolve;
if( aux_evalSolver<Deg, POLYNOMIAL, PolynomialSolverType>( pols, psolve ) )
{
//It is supposed that
// 1) the roots found are correct
// 2) the roots have distinct moduli
typedef typename POLYNOMIAL::Scalar Scalar;
typedef typename REAL_ROOTS::Scalar Real;
//Test realRoots
std::vector< Real > calc_realRoots;
psolve.realRoots( calc_realRoots );
VERIFY( calc_realRoots.size() == (size_t)real_roots.size() );
const Scalar psPrec = sqrt( test_precision<Scalar>() );
for( size_t i=0; i<calc_realRoots.size(); ++i )
{
bool found = false;
for( size_t j=0; j<calc_realRoots.size()&& !found; ++j )
{
if( internal::isApprox( calc_realRoots[i], real_roots[j], psPrec ) ){
found = true; }
}
VERIFY( found );
}
//Test greatestRoot
VERIFY( internal::isApprox( roots.array().abs().maxCoeff(),
abs( psolve.greatestRoot() ), psPrec ) );
//Test smallestRoot
VERIFY( internal::isApprox( roots.array().abs().minCoeff(),
abs( psolve.smallestRoot() ), psPrec ) );
bool hasRealRoot;
//Test absGreatestRealRoot
Real r = psolve.absGreatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().maxCoeff(), abs(r), psPrec ) ); }
//Test absSmallestRealRoot
r = psolve.absSmallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().abs().minCoeff(), abs( r ), psPrec ) ); }
//Test greatestRealRoot
r = psolve.greatestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().maxCoeff(), r, psPrec ) ); }
//Test smallestRealRoot
r = psolve.smallestRealRoot( hasRealRoot );
VERIFY( hasRealRoot == (real_roots.size() > 0 ) );
if( hasRealRoot ){
VERIFY( internal::isApprox( real_roots.array().minCoeff(), r, psPrec ) ); }
}
}
template<typename _Scalar, int _Deg>
void polynomialsolver(int deg)
{
typedef internal::increment_if_fixed_size<_Deg> Dim;
typedef Matrix<_Scalar,Dim::ret,1> PolynomialType;
typedef Matrix<_Scalar,_Deg,1> EvalRootsType;
cout << "Standard cases" << endl;
PolynomialType pols = PolynomialType::Random(deg+1);
evalSolver<_Deg,PolynomialType>( pols );
cout << "Hard cases" << endl;
_Scalar multipleRoot = internal::random<_Scalar>();
EvalRootsType allRoots = EvalRootsType::Constant(deg,multipleRoot);
roots_to_monicPolynomial( allRoots, pols );
evalSolver<_Deg,PolynomialType>( pols );
cout << "Test sugar" << endl;
EvalRootsType realRoots = EvalRootsType::Random(deg);
roots_to_monicPolynomial( realRoots, pols );
evalSolverSugarFunction<_Deg>(
pols,
realRoots.template cast <
std::complex<
typename NumTraits<_Scalar>::Real
>
>(),
realRoots );
}
void test_polynomialsolver()
{
for(int i = 0; i < g_repeat; i++)
{
CALL_SUBTEST_1( (polynomialsolver<float,1>(1)) );
CALL_SUBTEST_2( (polynomialsolver<double,2>(2)) );
CALL_SUBTEST_3( (polynomialsolver<double,3>(3)) );
CALL_SUBTEST_4( (polynomialsolver<float,4>(4)) );
CALL_SUBTEST_5( (polynomialsolver<double,5>(5)) );
CALL_SUBTEST_6( (polynomialsolver<float,6>(6)) );
CALL_SUBTEST_7( (polynomialsolver<float,7>(7)) );
CALL_SUBTEST_8( (polynomialsolver<double,8>(8)) );
CALL_SUBTEST_9( (polynomialsolver<float,Dynamic>(
internal::random<int>(9,13)
)) );
CALL_SUBTEST_10((polynomialsolver<double,Dynamic>(
internal::random<int>(9,13)
)) );
CALL_SUBTEST_11((polynomialsolver<float,Dynamic>(1)) );
}
}
<|endoftext|>
|
<commit_before>#include "qgeomapreplygooglemaps.h"
#include <QNetworkAccessManager>
#include <QNetworkCacheMetaData>
#include <QDateTime>
QT_BEGIN_NAMESPACE
QGeoMapReplyGooglemaps::QGeoMapReplyGooglemaps(QNetworkReply *reply, const QGeoTileSpec &spec, QObject *parent)
: QGeoTiledMapReply(spec, parent),
m_reply(reply)
{
connect(m_reply,
SIGNAL(finished()),
this,
SLOT(networkFinished()));
connect(m_reply,
SIGNAL(error(QNetworkReply::NetworkError)),
this,
SLOT(networkError(QNetworkReply::NetworkError)));
}
QGeoMapReplyGooglemaps::~QGeoMapReplyGooglemaps()
{
}
QNetworkReply *QGeoMapReplyGooglemaps::networkReply() const
{
return m_reply;
}
void QGeoMapReplyGooglemaps::abort()
{
if (!m_reply)
return;
m_reply->abort();
}
void QGeoMapReplyGooglemaps::networkFinished()
{
if (!m_reply)
return;
if (m_reply->error() != QNetworkReply::NoError)
return;
setMapImageData(m_reply->readAll());
setMapImageFormat("png");
setFinished(true);
m_reply->deleteLater();
m_reply = 0;
}
void QGeoMapReplyGooglemaps::networkError(QNetworkReply::NetworkError error)
{
if (!m_reply)
return;
if (error != QNetworkReply::OperationCanceledError)
setError(QGeoTiledMapReply::CommunicationError, m_reply->errorString());
setFinished(true);
m_reply->deleteLater();
m_reply = 0;
}
QT_END_NAMESPACE
<commit_msg>Set correct file extentions<commit_after>#include "qgeomapreplygooglemaps.h"
#include <QNetworkAccessManager>
#include <QNetworkCacheMetaData>
#include <QDateTime>
QT_BEGIN_NAMESPACE
QGeoMapReplyGooglemaps::QGeoMapReplyGooglemaps(QNetworkReply *reply, const QGeoTileSpec &spec, QObject *parent)
: QGeoTiledMapReply(spec, parent),
m_reply(reply)
{
connect(m_reply,
SIGNAL(finished()),
this,
SLOT(networkFinished()));
connect(m_reply,
SIGNAL(error(QNetworkReply::NetworkError)),
this,
SLOT(networkError(QNetworkReply::NetworkError)));
}
QGeoMapReplyGooglemaps::~QGeoMapReplyGooglemaps()
{
}
QNetworkReply *QGeoMapReplyGooglemaps::networkReply() const
{
return m_reply;
}
void QGeoMapReplyGooglemaps::abort()
{
if (!m_reply)
return;
m_reply->abort();
}
void QGeoMapReplyGooglemaps::networkFinished()
{
if (!m_reply)
return;
if (m_reply->error() != QNetworkReply::NoError)
return;
setMapImageData(m_reply->readAll());
const int _mid = tileSpec().mapId();
if (_mid == 2)
setMapImageFormat("jpeg");
else
setMapImageFormat("png");
setFinished(true);
m_reply->deleteLater();
m_reply = 0;
}
void QGeoMapReplyGooglemaps::networkError(QNetworkReply::NetworkError error)
{
if (!m_reply)
return;
if (error != QNetworkReply::OperationCanceledError)
setError(QGeoTiledMapReply::CommunicationError, m_reply->errorString());
setFinished(true);
m_reply->deleteLater();
m_reply = 0;
}
QT_END_NAMESPACE
<|endoftext|>
|
<commit_before>AliAnalysisTaskNuclei* AddHighMultNucleiTask(TString name = "name", ULong64_t triggerMask = AliVEvent::kHighMultV0)
{
// get the manager via the static access member. since it's static, you don't need
// to create an instance of the class here to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":AntiHe3HM"; // create a subfolder in the file
// now we create an instance of your task
AliAnalysisTaskNuclei* task = new AliAnalysisTaskNuclei(name.Data());
if(!task) return 0x0;
//Add task settings here
task->SelectCollisionCandidates(AliVEvent::kHighMultV0);
task->SetFilterBit(16);
task->SetLowPCut(0.1);
task->SetHighPCut(1e30);
task->SetEtaCut(0.8);
task->SetMinNITSCl(1);
task->SetMaxDCAxyPreCut(1.5);
task->SetMaxDCAxyFinal(1.5);
task->SetMaxDCAz(1.5);
//set PID cuts #### Legacy code not used in analysis anymore ###
task->SetMaxTPCnSigma(3.0);
task->SetUseTOFPidCut(kFALSE);//kTRUE or kFALSE for use of TOF
task->SetMaxTOFnSigma(3.0);
// momentum p from which a hit/cut in TOF is required
task->SetMomForTOFanaProt(0.7);
task->SetMomForTOFanaDeut(1.4);
task->SetAnalyseAllParticles(kTRUE);
AliESDtrackCuts* trackCuts = new AliESDtrackCuts();
trackCuts->SetPtRange(0.15, 1e30);
trackCuts->SetEtaRange(-0.8, 0.8);
/*
//TPC
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMinNCrossedRowsTPC(110);
trackCuts->SetMaxChi2PerClusterTPC(3.0);
trackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);
trackCuts->SetMaxFractionSharedTPCClusters(0.1);
trackCuts->SetMaxChi2TPCConstrainedGlobal(25.);
//ITS
trackCuts->SetRequireITSRefit(kTRUE);
trackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kFirst);
trackCuts->SetMinNClustersITS(3);//This seems very high?
//primary selection
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetDCAToVertex2D(kFALSE);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetMaxDCAToVertexZ(10.0);
trackCuts->SetMaxDCAToVertexXY(10.0);
*/
task->SetTrackCuts(trackCuts);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer("MyOutputContainerHighMult", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<commit_msg>Add suffix argument to AddTask<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <Rtypes.h>
#include <TString.h>
#include "AliAnalysisTaskNuclei.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "AliPID.h"
#include "AliVEvent.h"
#include "AliESDtrackCuts.h"
#endif
AliAnalysisTaskNuclei* AddHighMultNucleiTask(TString tskname = "name", ULong64_t triggerMask = AliVEvent::kHighMultV0, TString suffix = "")
{
// get the manager via the static access member. since it's static, you don't need
// to create an instance of the class here to call the function
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
return 0x0;
}
// get the input event handler, again via a static method.
// this handler is part of the managing system and feeds events
// to your task
if (!mgr->GetInputEventHandler()) {
return 0x0;
}
// by default, a file is open for writing. here, we get the filename
TString fileName = AliAnalysisManager::GetCommonFileName();
fileName += ":AntiHe3HM"; // create a subfolder in the file
// now we create an instance of your task
tskname.Append(Form("%s",suffix.Data()));
AliAnalysisTaskNuclei* task = new AliAnalysisTaskNuclei(tskname.Data());
if(!task) return 0x0;
//Add task settings here
task->SelectCollisionCandidates(AliVEvent::kHighMultV0);
task->SetFilterBit(16);
task->SetLowPCut(0.1);
task->SetHighPCut(1e30);
task->SetEtaCut(0.8);
task->SetMinNITSCl(1);
task->SetMaxDCAxyPreCut(1.5);
task->SetMaxDCAxyFinal(1.5);
task->SetMaxDCAz(1.5);
//set PID cuts #### Legacy code not used in analysis anymore ###
task->SetMaxTPCnSigma(3.0);
task->SetUseTOFPidCut(kFALSE);//kTRUE or kFALSE for use of TOF
task->SetMaxTOFnSigma(3.0);
// momentum p from which a hit/cut in TOF is required
task->SetMomForTOFanaProt(0.7);
task->SetMomForTOFanaDeut(1.4);
task->SetAnalyseAllParticles(kTRUE);
AliESDtrackCuts* trackCuts = new AliESDtrackCuts();
trackCuts->SetPtRange(0.15, 1e30);
trackCuts->SetEtaRange(-0.8, 0.8);
/*
//TPC
trackCuts->SetRequireTPCRefit(kTRUE);
trackCuts->SetMinNCrossedRowsTPC(110);
trackCuts->SetMaxChi2PerClusterTPC(3.0);
trackCuts->SetMinRatioCrossedRowsOverFindableClustersTPC(0.9);
trackCuts->SetMaxFractionSharedTPCClusters(0.1);
trackCuts->SetMaxChi2TPCConstrainedGlobal(25.);
//ITS
trackCuts->SetRequireITSRefit(kTRUE);
trackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD, AliESDtrackCuts::kFirst);
trackCuts->SetMinNClustersITS(3);//This seems very high?
//primary selection
trackCuts->SetAcceptKinkDaughters(kFALSE);
trackCuts->SetDCAToVertex2D(kFALSE);
trackCuts->SetRequireSigmaToVertex(kFALSE);
trackCuts->SetMaxDCAToVertexZ(10.0);
trackCuts->SetMaxDCAToVertexXY(10.0);
*/
task->SetTrackCuts(trackCuts);
// add your task to the manager
mgr->AddTask(task);
// your task needs input: here we connect the manager to your task
mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());
// same for the output
mgr->ConnectOutput(task,1,mgr->CreateContainer(Form("AbsorptionRatio_%s",tskname.Data()), TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data()));
// in the end, this macro returns a pointer to your task. this will be convenient later on
// when you will run your analysis in an analysis train on grid
return task;
}
<|endoftext|>
|
<commit_before>#include "../data_structures/dynamic_graph.hpp"
#include "../data_structures/import_edge.hpp"
#include "../data_structures/query_node.hpp"
#include "../data_structures/restriction.hpp"
#include "../data_structures/static_graph.hpp"
#include "../util/fingerprint.hpp"
#include "../util/graph_loader.hpp"
#include "../util/integer_range.hpp"
#include "../util/make_unique.hpp"
#include "../util/osrm_exception.hpp"
#include "../util/simple_logger.hpp"
#include "../typedefs.h"
#include <algorithm>
#include <fstream>
struct TarjanEdgeData
{
TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}
TarjanEdgeData(unsigned distance, unsigned name_id) : distance(distance), name_id(name_id) {}
unsigned distance;
unsigned name_id;
};
using StaticTestGraph = StaticGraph<TarjanEdgeData>;
using DynamicTestGraph = StaticGraph<TarjanEdgeData>;
using StaticEdge = StaticTestGraph::InputEdge;
using DynamicEdge = DynamicTestGraph::InputEdge;
int main(int argc, char *argv[])
{
std::vector<QueryNode> coordinate_list;
std::vector<TurnRestriction> restriction_list;
std::vector<NodeID> bollard_node_list;
std::vector<NodeID> traffic_lights_list;
LogPolicy::GetInstance().Unmute();
try
{
// enable logging
if (argc < 3)
{
SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0]
<< " <osrm> <osrm.restrictions>";
return -1;
}
SimpleLogger().Write() << "Using restrictions from file: " << argv[2];
std::ifstream restriction_ifstream(argv[2], std::ios::binary);
const FingerPrint fingerprint_orig;
FingerPrint fingerprint_loaded;
restriction_ifstream.read(reinterpret_cast<char *>(&fingerprint_loaded),
sizeof(FingerPrint));
// check fingerprint and warn if necessary
if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
{
SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. "
"Reprocess to get rid of this warning.";
}
if (!restriction_ifstream.good())
{
throw osrm::exception("Could not access <osrm-restrictions> files");
}
uint32_t usable_restrictions = 0;
restriction_ifstream.read(reinterpret_cast<char *>(&usable_restrictions), sizeof(uint32_t));
restriction_list.resize(usable_restrictions);
// load restrictions
if (usable_restrictions > 0)
{
restriction_ifstream.read(reinterpret_cast<char *>(&restriction_list[0]),
usable_restrictions * sizeof(TurnRestriction));
}
restriction_ifstream.close();
std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary);
if (!input_stream.is_open())
{
throw osrm::exception("Cannot open osrm file");
}
// load graph data
std::vector<ImportEdge> edge_list;
const NodeID number_of_nodes =
readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list,
traffic_lights_list, &coordinate_list, restriction_list);
input_stream.close();
BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions,
"size of restriction_list changed");
SimpleLogger().Write() << restriction_list.size() << " restrictions, "
<< bollard_node_list.size() << " bollard nodes, "
<< traffic_lights_list.size() << " traffic lights";
traffic_lights_list.clear();
traffic_lights_list.shrink_to_fit();
// Building an node-based graph
std::vector<StaticEdge> static_graph_edge_list;
std::vector<DynamicEdge> dynamic_graph_edge_list;
for (const auto &input_edge : edge_list)
{
if (input_edge.source == input_edge.target)
{
continue;
}
if (input_edge.forward)
{
static_graph_edge_list.emplace_back(input_edge.source, input_edge.target,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
dynamic_graph_edge_list.emplace_back(input_edge.source, input_edge.target,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
}
if (input_edge.backward)
{
dynamic_graph_edge_list.emplace_back(input_edge.target, input_edge.source,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
static_graph_edge_list.emplace_back(input_edge.target, input_edge.source,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
}
}
edge_list.clear();
edge_list.shrink_to_fit();
BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(),
"input edge vector not properly deallocated");
tbb::parallel_sort(static_graph_edge_list.begin(), static_graph_edge_list.end());
tbb::parallel_sort(dynamic_graph_edge_list.begin(), dynamic_graph_edge_list.end());
auto static_graph =
osrm::make_unique<StaticTestGraph>(number_of_nodes, static_graph_edge_list);
auto dynamic_graph =
osrm::make_unique<DynamicTestGraph>(number_of_nodes, dynamic_graph_edge_list);
SimpleLogger().Write() << "Starting static/dynamic graph comparison";
BOOST_ASSERT(static_graph->GetNumberOfNodes() == dynamic_graph->GetNumberOfNodes());
BOOST_ASSERT(static_graph->GetNumberOfEdges() == dynamic_graph->GetNumberOfEdges());
for (const auto node : osrm::irange(0u, static_graph->GetNumberOfNodes()))
{
const auto static_range = static_graph->GetAdjacentEdgeRange(node);
const auto dynamic_range = dynamic_graph->GetAdjacentEdgeRange(node);
SimpleLogger().Write() << "checking node " << node << "/"
<< static_graph->GetNumberOfNodes();
BOOST_ASSERT(static_range.size() == dynamic_range.size());
const auto static_begin = static_graph->BeginEdges(node);
const auto dynamic_begin = dynamic_graph->BeginEdges(node);
// check raw interface
for (int i = 0; i < static_range.size(); ++i)
{
const auto static_target = static_graph->GetTarget(static_begin + i);
const auto dynamic_target = dynamic_graph->GetTarget(dynamic_begin + i);
BOOST_ASSERT(static_target == dynamic_target);
const auto static_data = static_graph->GetEdgeData(static_begin + i);
const auto dynamic_data = dynamic_graph->GetEdgeData(dynamic_begin + i);
BOOST_ASSERT(static_data.distance == dynamic_data.distance);
BOOST_ASSERT(static_data.name_id == dynamic_data.name_id);
}
// check range interface
std::vector<EdgeID> static_target_ids, dynamic_target_ids;
std::vector<TarjanEdgeData> static_edge_data, dynamic_edge_data;
for (const auto static_id : static_range)
{
static_target_ids.push_back(static_graph->GetTarget(static_id));
static_edge_data.push_back(static_graph->GetEdgeData(static_id));
}
for (const auto dynamic_id : dynamic_range)
{
dynamic_target_ids.push_back(dynamic_graph->GetTarget(dynamic_id));
dynamic_edge_data.push_back(dynamic_graph->GetEdgeData(dynamic_id));
}
BOOST_ASSERT(static_target_ids.size() == dynamic_target_ids.size());
BOOST_ASSERT(std::equal(std::begin(static_target_ids), std::end(static_target_ids),
std::begin(dynamic_target_ids)));
}
SimpleLogger().Write() << "Graph comparison finished successfully";
}
catch (const std::exception &e)
{
SimpleLogger().Write(logWARNING) << "[exception] " << e.what();
}
return 0;
}
<commit_msg>fix unintended signed/unsigned comparison<commit_after>#include "../data_structures/dynamic_graph.hpp"
#include "../data_structures/import_edge.hpp"
#include "../data_structures/query_node.hpp"
#include "../data_structures/restriction.hpp"
#include "../data_structures/static_graph.hpp"
#include "../util/fingerprint.hpp"
#include "../util/graph_loader.hpp"
#include "../util/integer_range.hpp"
#include "../util/make_unique.hpp"
#include "../util/osrm_exception.hpp"
#include "../util/simple_logger.hpp"
#include "../typedefs.h"
#include <algorithm>
#include <fstream>
struct TarjanEdgeData
{
TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}
TarjanEdgeData(unsigned distance, unsigned name_id) : distance(distance), name_id(name_id) {}
unsigned distance;
unsigned name_id;
};
using StaticTestGraph = StaticGraph<TarjanEdgeData>;
using DynamicTestGraph = StaticGraph<TarjanEdgeData>;
using StaticEdge = StaticTestGraph::InputEdge;
using DynamicEdge = DynamicTestGraph::InputEdge;
int main(int argc, char *argv[])
{
std::vector<QueryNode> coordinate_list;
std::vector<TurnRestriction> restriction_list;
std::vector<NodeID> bollard_node_list;
std::vector<NodeID> traffic_lights_list;
LogPolicy::GetInstance().Unmute();
try
{
// enable logging
if (argc < 3)
{
SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0]
<< " <osrm> <osrm.restrictions>";
return -1;
}
SimpleLogger().Write() << "Using restrictions from file: " << argv[2];
std::ifstream restriction_ifstream(argv[2], std::ios::binary);
const FingerPrint fingerprint_orig;
FingerPrint fingerprint_loaded;
restriction_ifstream.read(reinterpret_cast<char *>(&fingerprint_loaded),
sizeof(FingerPrint));
// check fingerprint and warn if necessary
if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
{
SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. "
"Reprocess to get rid of this warning.";
}
if (!restriction_ifstream.good())
{
throw osrm::exception("Could not access <osrm-restrictions> files");
}
uint32_t usable_restrictions = 0;
restriction_ifstream.read(reinterpret_cast<char *>(&usable_restrictions), sizeof(uint32_t));
restriction_list.resize(usable_restrictions);
// load restrictions
if (usable_restrictions > 0)
{
restriction_ifstream.read(reinterpret_cast<char *>(&restriction_list[0]),
usable_restrictions * sizeof(TurnRestriction));
}
restriction_ifstream.close();
std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary);
if (!input_stream.is_open())
{
throw osrm::exception("Cannot open osrm file");
}
// load graph data
std::vector<ImportEdge> edge_list;
const NodeID number_of_nodes =
readBinaryOSRMGraphFromStream(input_stream, edge_list, bollard_node_list,
traffic_lights_list, &coordinate_list, restriction_list);
input_stream.close();
BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions,
"size of restriction_list changed");
SimpleLogger().Write() << restriction_list.size() << " restrictions, "
<< bollard_node_list.size() << " bollard nodes, "
<< traffic_lights_list.size() << " traffic lights";
traffic_lights_list.clear();
traffic_lights_list.shrink_to_fit();
// Building an node-based graph
std::vector<StaticEdge> static_graph_edge_list;
std::vector<DynamicEdge> dynamic_graph_edge_list;
for (const auto &input_edge : edge_list)
{
if (input_edge.source == input_edge.target)
{
continue;
}
if (input_edge.forward)
{
static_graph_edge_list.emplace_back(input_edge.source, input_edge.target,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
dynamic_graph_edge_list.emplace_back(input_edge.source, input_edge.target,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
}
if (input_edge.backward)
{
dynamic_graph_edge_list.emplace_back(input_edge.target, input_edge.source,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
static_graph_edge_list.emplace_back(input_edge.target, input_edge.source,
(std::max)(input_edge.weight, 1),
input_edge.name_id);
}
}
edge_list.clear();
edge_list.shrink_to_fit();
BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(),
"input edge vector not properly deallocated");
tbb::parallel_sort(static_graph_edge_list.begin(), static_graph_edge_list.end());
tbb::parallel_sort(dynamic_graph_edge_list.begin(), dynamic_graph_edge_list.end());
auto static_graph =
osrm::make_unique<StaticTestGraph>(number_of_nodes, static_graph_edge_list);
auto dynamic_graph =
osrm::make_unique<DynamicTestGraph>(number_of_nodes, dynamic_graph_edge_list);
SimpleLogger().Write() << "Starting static/dynamic graph comparison";
BOOST_ASSERT(static_graph->GetNumberOfNodes() == dynamic_graph->GetNumberOfNodes());
BOOST_ASSERT(static_graph->GetNumberOfEdges() == dynamic_graph->GetNumberOfEdges());
for (const auto node : osrm::irange(0u, static_graph->GetNumberOfNodes()))
{
const auto static_range = static_graph->GetAdjacentEdgeRange(node);
const auto dynamic_range = dynamic_graph->GetAdjacentEdgeRange(node);
SimpleLogger().Write() << "checking node " << node << "/"
<< static_graph->GetNumberOfNodes();
BOOST_ASSERT(static_range.size() == dynamic_range.size());
const auto static_begin = static_graph->BeginEdges(node);
const auto dynamic_begin = dynamic_graph->BeginEdges(node);
// check raw interface
for (const auto i : osrm::irange(0u, static_range.size()))
{
const auto static_target = static_graph->GetTarget(static_begin + i);
const auto dynamic_target = dynamic_graph->GetTarget(dynamic_begin + i);
BOOST_ASSERT(static_target == dynamic_target);
const auto static_data = static_graph->GetEdgeData(static_begin + i);
const auto dynamic_data = dynamic_graph->GetEdgeData(dynamic_begin + i);
BOOST_ASSERT(static_data.distance == dynamic_data.distance);
BOOST_ASSERT(static_data.name_id == dynamic_data.name_id);
}
// check range interface
std::vector<EdgeID> static_target_ids, dynamic_target_ids;
std::vector<TarjanEdgeData> static_edge_data, dynamic_edge_data;
for (const auto static_id : static_range)
{
static_target_ids.push_back(static_graph->GetTarget(static_id));
static_edge_data.push_back(static_graph->GetEdgeData(static_id));
}
for (const auto dynamic_id : dynamic_range)
{
dynamic_target_ids.push_back(dynamic_graph->GetTarget(dynamic_id));
dynamic_edge_data.push_back(dynamic_graph->GetEdgeData(dynamic_id));
}
BOOST_ASSERT(static_target_ids.size() == dynamic_target_ids.size());
BOOST_ASSERT(std::equal(std::begin(static_target_ids), std::end(static_target_ids),
std::begin(dynamic_target_ids)));
}
SimpleLogger().Write() << "Graph comparison finished successfully";
}
catch (const std::exception &e)
{
SimpleLogger().Write(logWARNING) << "[exception] " << e.what();
}
return 0;
}
<|endoftext|>
|
<commit_before>#include "QDataAnalysisView.h"
#include "QAction"
#include "QHeaderView"
#include <algorithm>
#include "simvis/color.h"
#include "xo/system/log.h"
#include "xo/utility/types.h"
#include "qtfx.h"
#include <array>
#include "xo/system/log.h"
#include "xo/container/sorted_vector.h"
#include "xo/numerical/constants.h"
#include "qt_convert.h"
QDataAnalysisView::QDataAnalysisView( QDataAnalysisModel* m, QWidget* parent ) :
QWidget( parent ),
model( m ),
currentUpdateIdx( 0 )
{
selectBox = new QCheckBox( this );
connect( selectBox, &QCheckBox::stateChanged, this, &QDataAnalysisView::select );
filter = new QLineEdit( this );
connect( filter, &QLineEdit::textChanged, this, &QDataAnalysisView::filterChanged );
auto* header = new QHGroup( this, 0, 4 );
*header << new QLabel( "Filter", this ) << filter << selectBox;
itemList = new QTreeWidget( this );
itemList->setRootIsDecorated( false );
itemList->setColumnCount( 2 );
itemList->header()->close();
itemList->resize( 100, 100 );
QStringList headerLabels;
headerLabels << "Variable" << "Value";
itemList->setHeaderLabels( headerLabels );
//itemList->setFrameStyle( QFrame::NoFrame );
itemGroup = new QVGroup( this, 0, 4 );
itemGroup->setContentsMargins( 0, 0, 0, 0 );
*itemGroup << header << itemList;
connect( itemList, &QTreeWidget::itemChanged, this, &QDataAnalysisView::itemChanged );
splitter = new QSplitter( this );
splitter->setContentsMargins( 0, 0, 0, 0 );
splitter->setFrameShape( QFrame::NoFrame );
splitter->setObjectName( "Analysis.Splitter" );
splitter->addWidget( itemGroup );
QVBoxLayout* layout = new QVBoxLayout( this );
setLayout( layout );
layout->setContentsMargins( 0, 0, 0, 0 );
layout->setSpacing( 4 );
layout->addWidget( splitter );
for ( int i = 0; i < maxSeriesCount; ++i )
freeColors.insert( i );
#if !defined QTFX_NO_QCUSTOMPLOT
customPlot = new QCustomPlot();
customPlot->setInteraction( QCP::iRangeZoom, true );
customPlot->setInteraction( QCP::iRangeDrag, true );
customPlot->axisRect()->setRangeDrag( Qt::Horizontal );
customPlot->axisRect()->setRangeZoom( Qt::Horizontal );
customPlot->legend->setVisible( true );
customPlot->legend->setFont( itemList->font() );
customPlot->legend->setRowSpacing( -6 );
customPlotLine = new QCPItemLine( customPlot );
customPlotLine->setHead( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) );
customPlotLine->setTail( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) );
customPlot->addItem( customPlotLine );
splitter->addWidget( customPlot );
connect( customPlot, &QCustomPlot::mousePress, this, &QDataAnalysisView::mouseEvent );
connect( customPlot, &QCustomPlot::mouseMove, this, &QDataAnalysisView::mouseEvent );
connect( customPlot->xAxis, SIGNAL( rangeChanged( const QCPRange&, const QCPRange& ) ), this, SLOT( rangeChanged( const QCPRange&, const QCPRange& ) ) );
#else
chart = new QtCharts::QChart();
chart->setBackgroundRoundness( 0 );
chart->setMargins( QMargins( 4, 4, 4, 4 ) );
chart->layout()->setContentsMargins( 0, 0, 0, 0 );
chart->legend()->setAlignment( Qt::AlignRight );
chart->createDefaultAxes();
chartView = new QtCharts::QChartView( chart, this );
chartView->setContentsMargins( 0, 0, 0, 0 );
chartView->setRenderHint( QPainter::Antialiasing );
chartView->setRubberBand( QtCharts::QChartView::RectangleRubberBand );
chartView->setBackgroundBrush( QBrush( Qt::red ) );
chartView->resize( 300, 100 );
splitter->addWidget( chartView );
#endif
splitter->setSizes( QList< int >{ 100, 300 } );
reset();
}
int QDataAnalysisView::decimalPoints( double v )
{
if ( v != 0 && xo::less_or_equal( abs( v ), 0.05 ) )
return 6;
else return 3;
}
void QDataAnalysisView::refresh( double time, bool refreshAll )
{
if ( itemList->topLevelItemCount() != model->seriesCount() )
return reset();
if ( model->seriesCount() == 0 )
return;
// update state
currentTime = time;
// draw stuff if visible
if ( isVisible() )
{
int itemCount = refreshAll ? model->seriesCount() : std::min<int>( smallRefreshItemCount, model->seriesCount() );
itemList->setUpdatesEnabled( false );
for ( size_t i = 0; i < itemCount; ++i )
{
auto y = model->value( currentUpdateIdx, time );
itemList->topLevelItem( currentUpdateIdx )->setText( 1, QString().sprintf( "%.*f", decimalPoints( y ), y ) );
++currentUpdateIdx %= model->seriesCount();
}
itemList->setUpdatesEnabled( true );
// update graph
updateIndicator();
#ifdef QTFX_USE_QCUSTOMPLOT
customPlot->replot( QCustomPlot::rpQueued );
#endif
}
}
void QDataAnalysisView::itemChanged( QTreeWidgetItem* item, int column )
{
if ( column == 0 )
updateSeries( itemList->indexOfTopLevelItem( item ) );
}
void QDataAnalysisView::clearSeries()
{
while ( !series.empty() )
removeSeries( series.rbegin()->channel );
}
void QDataAnalysisView::mouseEvent( QMouseEvent* event )
{
#if !defined QTFX_NO_QCUSTOMPLOT
if ( event->buttons() & Qt::LeftButton )
{
double x = customPlot->xAxis->pixelToCoord( event->pos().x() );
double t = model->timeValue( model->timeIndex( x ) );
emit timeChanged( t );
}
#endif
}
void QDataAnalysisView::rangeChanged( const QCPRange &newRange, const QCPRange &oldRange )
{
QCPRange fixedRange = QCPRange( xo::max( newRange.lower, model->timeStart() ), xo::min( newRange.upper, model->timeFinish() ) );
if ( fixedRange != newRange )
{
customPlot->xAxis->blockSignals( true );
customPlot->xAxis->setRange( fixedRange );
customPlot->xAxis->blockSignals( false );
}
updateSeriesStyle();
}
void QDataAnalysisView::filterChanged( const QString& filter )
{
updateFilter();
}
void QDataAnalysisView::setSelectionState( int state )
{
if ( state != Qt::PartiallyChecked )
{
for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i )
{
auto* item = itemList->topLevelItem( i );
if ( !item->isHidden() && item->checkState( 0 ) != state )
item->setCheckState( 0, Qt::CheckState( state ) );
}
}
}
QColor QDataAnalysisView::getStandardColor( int idx )
{
return to_qt( vis::make_unique_color( size_t( idx ) ) );
}
void QDataAnalysisView::reset()
{
itemList->clear();
clearSeries();
for ( size_t i = 0; i < model->seriesCount(); ++i )
{
auto* wdg = new QTreeWidgetItem( itemList, QStringList( model->label( i ) ) );
wdg->setTextAlignment( 1, Qt::AlignRight );
wdg->setFlags( wdg->flags() | Qt::ItemIsUserCheckable );
wdg->setCheckState( 0, persistentSerieNames.find( model->label( i ) ) != persistentSerieNames.end() ? Qt::Checked : Qt::Unchecked );
}
itemList->resizeColumnToContents( 0 );
currentUpdateIdx = 0;
currentTime = 0.0;
updateIndicator();
updateFilter();
}
void QDataAnalysisView::updateIndicator()
{
#if !defined QTFX_NO_QCUSTOMPLOT
customPlotLine->start->setCoords( currentTime, customPlot->yAxis->range().lower );
customPlotLine->end->setCoords( currentTime, customPlot->yAxis->range().upper );
customPlot->replot();
#else
auto pos = chart->mapToPosition( QPointF( currentTime, 0 ) );
#endif
}
void QDataAnalysisView::updateFilter()
{
//selectAllButton->setDisabled( filter->text().isEmpty() );
for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i )
{
auto* item = itemList->topLevelItem( i );
item->setHidden( !item->text( 0 ).contains( filter->text() ) );
}
updateSelectBox();
}
void QDataAnalysisView::updateSelectBox()
{
size_t checked_count = 0;
size_t shown_count = 0;
for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i )
{
auto* item = itemList->topLevelItem( i );
if ( !item->isHidden() )
{
shown_count++;
checked_count += item->checkState( 0 ) == Qt::Checked;
}
}
selectBox->blockSignals( true );
selectBox->setCheckState( checked_count > 0 ? ( shown_count == checked_count ? Qt::Checked : Qt::Checked ) : Qt::Unchecked );
selectBox->blockSignals( false );
}
void QDataAnalysisView::updateSeriesStyle()
{
auto zoom = currentSeriesInterval * customPlot->xAxis->axisRect()->width() / customPlot->xAxis->range().size();
SeriesStyle newstyle = zoom > 8 ? discStyle : lineStyle;
if ( newstyle != seriesStyle )
{
seriesStyle = newstyle;
QCPScatterStyle ss = QCPScatterStyle( seriesStyle == discStyle ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 );
for ( auto& s : series )
{
s.graph->setScatterStyle( ss );
s.graph->setLineStyle( QCPGraph::lsLine );
}
}
}
void QDataAnalysisView::updateSeries( int idx )
{
auto item = itemList->topLevelItem( idx );
auto series_it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } );
if ( item->checkState( 0 ) == Qt::Checked && series_it == series.end() )
{
if ( series.size() < maxSeriesCount )
{
addSeries( idx );
persistentSerieNames.insert( model->label( idx ) );
}
else item->setCheckState( 0, Qt::Unchecked );
}
else if ( series_it != series.end() && item->checkState( 0 ) == Qt::Unchecked )
{
removeSeries( idx );
persistentSerieNames.remove( model->label( idx ) );
}
updateSelectBox();
}
void QDataAnalysisView::addSeries( int idx )
{
#if !defined QTFX_NO_QCUSTOMPLOT
QCPGraph* graph = customPlot->addGraph();
QString name = model->label( idx );
graph->setName( name );
xo_assert( !freeColors.empty() );
graph->setScatterStyle( QCPScatterStyle( seriesStyle == discStyle ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 ) );
graph->setPen( QPen( getStandardColor( freeColors.front() ), lineWidth ) );
auto data = model->getSeries( idx, minSeriesInterval );
for ( auto& e : data )
graph->addData( e.first, e.second );
series.emplace_back( Series{ idx, freeColors.front(), graph } );
freeColors.erase( freeColors.begin() );
currentSeriesInterval = ( data.back().first - data.front().first ) / data.size();
updateSeriesStyle();
auto range = customPlot->xAxis->range();
customPlot->rescaleAxes();
customPlot->xAxis->setRange( range );
updateIndicator();
customPlot->replot();
#else
QtCharts::QLineSeries* ls = new QtCharts::QLineSeries;
ls->setName( model->label( idx ) );
auto data = model->getSeries( idx, minSeriesInterval );
for ( auto& e : data )
ls->append( e.first, e.second );
chart->addSeries( ls );
chart->createDefaultAxes();
chart->zoomReset();
series[ idx ] = ls;
#endif
}
void QDataAnalysisView::removeSeries( int idx )
{
#if !defined QTFX_NO_QCUSTOMPLOT
auto range = customPlot->xAxis->range();
auto it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } );
auto name = it->graph->name();
freeColors.insert( it->color );
customPlot->removeGraph( it->graph );
series.erase( it );
customPlot->rescaleAxes();
customPlot->xAxis->setRange( range );
updateIndicator();
customPlot->replot();
#else
auto it = series.find( idx );
chart->removeSeries( it->second );
chart->zoomReset();
chart->createDefaultAxes();
series.erase( it );
#endif
}
<commit_msg>U: const -> numconst<commit_after>#include "QDataAnalysisView.h"
#include "QAction"
#include "QHeaderView"
#include <algorithm>
#include "simvis/color.h"
#include "xo/system/log.h"
#include "xo/utility/types.h"
#include "qtfx.h"
#include <array>
#include "xo/system/log.h"
#include "xo/container/sorted_vector.h"
#include "xo/numerical/numconst.h"
#include "qt_convert.h"
QDataAnalysisView::QDataAnalysisView( QDataAnalysisModel* m, QWidget* parent ) :
QWidget( parent ),
model( m ),
currentUpdateIdx( 0 )
{
selectBox = new QCheckBox( this );
connect( selectBox, &QCheckBox::stateChanged, this, &QDataAnalysisView::select );
filter = new QLineEdit( this );
connect( filter, &QLineEdit::textChanged, this, &QDataAnalysisView::filterChanged );
auto* header = new QHGroup( this, 0, 4 );
*header << new QLabel( "Filter", this ) << filter << selectBox;
itemList = new QTreeWidget( this );
itemList->setRootIsDecorated( false );
itemList->setColumnCount( 2 );
itemList->header()->close();
itemList->resize( 100, 100 );
QStringList headerLabels;
headerLabels << "Variable" << "Value";
itemList->setHeaderLabels( headerLabels );
//itemList->setFrameStyle( QFrame::NoFrame );
itemGroup = new QVGroup( this, 0, 4 );
itemGroup->setContentsMargins( 0, 0, 0, 0 );
*itemGroup << header << itemList;
connect( itemList, &QTreeWidget::itemChanged, this, &QDataAnalysisView::itemChanged );
splitter = new QSplitter( this );
splitter->setContentsMargins( 0, 0, 0, 0 );
splitter->setFrameShape( QFrame::NoFrame );
splitter->setObjectName( "Analysis.Splitter" );
splitter->addWidget( itemGroup );
QVBoxLayout* layout = new QVBoxLayout( this );
setLayout( layout );
layout->setContentsMargins( 0, 0, 0, 0 );
layout->setSpacing( 4 );
layout->addWidget( splitter );
for ( int i = 0; i < maxSeriesCount; ++i )
freeColors.insert( i );
#if !defined QTFX_NO_QCUSTOMPLOT
customPlot = new QCustomPlot();
customPlot->setInteraction( QCP::iRangeZoom, true );
customPlot->setInteraction( QCP::iRangeDrag, true );
customPlot->axisRect()->setRangeDrag( Qt::Horizontal );
customPlot->axisRect()->setRangeZoom( Qt::Horizontal );
customPlot->legend->setVisible( true );
customPlot->legend->setFont( itemList->font() );
customPlot->legend->setRowSpacing( -6 );
customPlotLine = new QCPItemLine( customPlot );
customPlotLine->setHead( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) );
customPlotLine->setTail( QCPLineEnding( QCPLineEnding::esDiamond, 9, 9, true ) );
customPlot->addItem( customPlotLine );
splitter->addWidget( customPlot );
connect( customPlot, &QCustomPlot::mousePress, this, &QDataAnalysisView::mouseEvent );
connect( customPlot, &QCustomPlot::mouseMove, this, &QDataAnalysisView::mouseEvent );
connect( customPlot->xAxis, SIGNAL( rangeChanged( const QCPRange&, const QCPRange& ) ), this, SLOT( rangeChanged( const QCPRange&, const QCPRange& ) ) );
#else
chart = new QtCharts::QChart();
chart->setBackgroundRoundness( 0 );
chart->setMargins( QMargins( 4, 4, 4, 4 ) );
chart->layout()->setContentsMargins( 0, 0, 0, 0 );
chart->legend()->setAlignment( Qt::AlignRight );
chart->createDefaultAxes();
chartView = new QtCharts::QChartView( chart, this );
chartView->setContentsMargins( 0, 0, 0, 0 );
chartView->setRenderHint( QPainter::Antialiasing );
chartView->setRubberBand( QtCharts::QChartView::RectangleRubberBand );
chartView->setBackgroundBrush( QBrush( Qt::red ) );
chartView->resize( 300, 100 );
splitter->addWidget( chartView );
#endif
splitter->setSizes( QList< int >{ 100, 300 } );
reset();
}
int QDataAnalysisView::decimalPoints( double v )
{
if ( v != 0 && xo::less_or_equal( abs( v ), 0.05 ) )
return 6;
else return 3;
}
void QDataAnalysisView::refresh( double time, bool refreshAll )
{
if ( itemList->topLevelItemCount() != model->seriesCount() )
return reset();
if ( model->seriesCount() == 0 )
return;
// update state
currentTime = time;
// draw stuff if visible
if ( isVisible() )
{
int itemCount = refreshAll ? model->seriesCount() : std::min<int>( smallRefreshItemCount, model->seriesCount() );
itemList->setUpdatesEnabled( false );
for ( size_t i = 0; i < itemCount; ++i )
{
auto y = model->value( currentUpdateIdx, time );
itemList->topLevelItem( currentUpdateIdx )->setText( 1, QString().sprintf( "%.*f", decimalPoints( y ), y ) );
++currentUpdateIdx %= model->seriesCount();
}
itemList->setUpdatesEnabled( true );
// update graph
updateIndicator();
#ifdef QTFX_USE_QCUSTOMPLOT
customPlot->replot( QCustomPlot::rpQueued );
#endif
}
}
void QDataAnalysisView::itemChanged( QTreeWidgetItem* item, int column )
{
if ( column == 0 )
updateSeries( itemList->indexOfTopLevelItem( item ) );
}
void QDataAnalysisView::clearSeries()
{
while ( !series.empty() )
removeSeries( series.rbegin()->channel );
}
void QDataAnalysisView::mouseEvent( QMouseEvent* event )
{
#if !defined QTFX_NO_QCUSTOMPLOT
if ( event->buttons() & Qt::LeftButton )
{
double x = customPlot->xAxis->pixelToCoord( event->pos().x() );
double t = model->timeValue( model->timeIndex( x ) );
emit timeChanged( t );
}
#endif
}
void QDataAnalysisView::rangeChanged( const QCPRange &newRange, const QCPRange &oldRange )
{
QCPRange fixedRange = QCPRange( xo::max( newRange.lower, model->timeStart() ), xo::min( newRange.upper, model->timeFinish() ) );
if ( fixedRange != newRange )
{
customPlot->xAxis->blockSignals( true );
customPlot->xAxis->setRange( fixedRange );
customPlot->xAxis->blockSignals( false );
}
updateSeriesStyle();
}
void QDataAnalysisView::filterChanged( const QString& filter )
{
updateFilter();
}
void QDataAnalysisView::setSelectionState( int state )
{
if ( state != Qt::PartiallyChecked )
{
for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i )
{
auto* item = itemList->topLevelItem( i );
if ( !item->isHidden() && item->checkState( 0 ) != state )
item->setCheckState( 0, Qt::CheckState( state ) );
}
}
}
QColor QDataAnalysisView::getStandardColor( int idx )
{
return to_qt( vis::make_unique_color( size_t( idx ) ) );
}
void QDataAnalysisView::reset()
{
itemList->clear();
clearSeries();
for ( size_t i = 0; i < model->seriesCount(); ++i )
{
auto* wdg = new QTreeWidgetItem( itemList, QStringList( model->label( i ) ) );
wdg->setTextAlignment( 1, Qt::AlignRight );
wdg->setFlags( wdg->flags() | Qt::ItemIsUserCheckable );
wdg->setCheckState( 0, persistentSerieNames.find( model->label( i ) ) != persistentSerieNames.end() ? Qt::Checked : Qt::Unchecked );
}
itemList->resizeColumnToContents( 0 );
currentUpdateIdx = 0;
currentTime = 0.0;
updateIndicator();
updateFilter();
}
void QDataAnalysisView::updateIndicator()
{
#if !defined QTFX_NO_QCUSTOMPLOT
customPlotLine->start->setCoords( currentTime, customPlot->yAxis->range().lower );
customPlotLine->end->setCoords( currentTime, customPlot->yAxis->range().upper );
customPlot->replot();
#else
auto pos = chart->mapToPosition( QPointF( currentTime, 0 ) );
#endif
}
void QDataAnalysisView::updateFilter()
{
//selectAllButton->setDisabled( filter->text().isEmpty() );
for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i )
{
auto* item = itemList->topLevelItem( i );
item->setHidden( !item->text( 0 ).contains( filter->text() ) );
}
updateSelectBox();
}
void QDataAnalysisView::updateSelectBox()
{
size_t checked_count = 0;
size_t shown_count = 0;
for ( size_t i = 0; i < itemList->topLevelItemCount(); ++i )
{
auto* item = itemList->topLevelItem( i );
if ( !item->isHidden() )
{
shown_count++;
checked_count += item->checkState( 0 ) == Qt::Checked;
}
}
selectBox->blockSignals( true );
selectBox->setCheckState( checked_count > 0 ? ( shown_count == checked_count ? Qt::Checked : Qt::Checked ) : Qt::Unchecked );
selectBox->blockSignals( false );
}
void QDataAnalysisView::updateSeriesStyle()
{
auto zoom = currentSeriesInterval * customPlot->xAxis->axisRect()->width() / customPlot->xAxis->range().size();
SeriesStyle newstyle = zoom > 8 ? discStyle : lineStyle;
if ( newstyle != seriesStyle )
{
seriesStyle = newstyle;
QCPScatterStyle ss = QCPScatterStyle( seriesStyle == discStyle ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 );
for ( auto& s : series )
{
s.graph->setScatterStyle( ss );
s.graph->setLineStyle( QCPGraph::lsLine );
}
}
}
void QDataAnalysisView::updateSeries( int idx )
{
auto item = itemList->topLevelItem( idx );
auto series_it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } );
if ( item->checkState( 0 ) == Qt::Checked && series_it == series.end() )
{
if ( series.size() < maxSeriesCount )
{
addSeries( idx );
persistentSerieNames.insert( model->label( idx ) );
}
else item->setCheckState( 0, Qt::Unchecked );
}
else if ( series_it != series.end() && item->checkState( 0 ) == Qt::Unchecked )
{
removeSeries( idx );
persistentSerieNames.remove( model->label( idx ) );
}
updateSelectBox();
}
void QDataAnalysisView::addSeries( int idx )
{
#if !defined QTFX_NO_QCUSTOMPLOT
QCPGraph* graph = customPlot->addGraph();
QString name = model->label( idx );
graph->setName( name );
xo_assert( !freeColors.empty() );
graph->setScatterStyle( QCPScatterStyle( seriesStyle == discStyle ? QCPScatterStyle::ssDisc : QCPScatterStyle::ssNone, 4 ) );
graph->setPen( QPen( getStandardColor( freeColors.front() ), lineWidth ) );
auto data = model->getSeries( idx, minSeriesInterval );
for ( auto& e : data )
graph->addData( e.first, e.second );
series.emplace_back( Series{ idx, freeColors.front(), graph } );
freeColors.erase( freeColors.begin() );
currentSeriesInterval = ( data.back().first - data.front().first ) / data.size();
updateSeriesStyle();
auto range = customPlot->xAxis->range();
customPlot->rescaleAxes();
customPlot->xAxis->setRange( range );
updateIndicator();
customPlot->replot();
#else
QtCharts::QLineSeries* ls = new QtCharts::QLineSeries;
ls->setName( model->label( idx ) );
auto data = model->getSeries( idx, minSeriesInterval );
for ( auto& e : data )
ls->append( e.first, e.second );
chart->addSeries( ls );
chart->createDefaultAxes();
chart->zoomReset();
series[ idx ] = ls;
#endif
}
void QDataAnalysisView::removeSeries( int idx )
{
#if !defined QTFX_NO_QCUSTOMPLOT
auto range = customPlot->xAxis->range();
auto it = xo::find_if( series, [&]( auto& p ) { return idx == p.channel; } );
auto name = it->graph->name();
freeColors.insert( it->color );
customPlot->removeGraph( it->graph );
series.erase( it );
customPlot->rescaleAxes();
customPlot->xAxis->setRange( range );
updateIndicator();
customPlot->replot();
#else
auto it = series.find( idx );
chart->removeSeries( it->second );
chart->zoomReset();
chart->createDefaultAxes();
series.erase( it );
#endif
}
<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <chrono>
#include <functional>
#include <map>
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "joynr/LocalDiscoveryAggregator.h"
#include "joynr/Future.h"
#include "joynr/Semaphore.h"
#include "joynr/types/DiscoveryEntryWithMetaInfo.h"
#include "joynr/types/DiscoveryQos.h"
#include "tests/mock/MockDiscovery.h"
using namespace ::testing;
using namespace joynr;
class LocalDiscoveryAggregatorTest : public ::testing::Test
{
public:
LocalDiscoveryAggregatorTest()
: provisionedDiscoveryEntries(),
localDiscoveryAggregator(provisionedDiscoveryEntries),
discoveryMock(std::make_shared<MockDiscovery>())
{
}
~LocalDiscoveryAggregatorTest() override
{
}
protected:
std::map<std::string, types::DiscoveryEntryWithMetaInfo> provisionedDiscoveryEntries;
LocalDiscoveryAggregator localDiscoveryAggregator;
std::shared_ptr<MockDiscovery> discoveryMock;
private:
DISALLOW_COPY_AND_ASSIGN(LocalDiscoveryAggregatorTest);
};
TEST_F(LocalDiscoveryAggregatorTest, addAsync_proxyNotSet_doesNotThrow)
{
const types::DiscoveryEntryWithMetaInfo discoveryEntry;
EXPECT_DEATH(localDiscoveryAggregator.addAsync(discoveryEntry, false, nullptr, nullptr),
"Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncDomainInterface_proxyNotSet_doesNotThrow)
{
const std::vector<std::string> domains;
const std::string interfaceName;
const types::DiscoveryQos discoveryQos;
EXPECT_DEATH(localDiscoveryAggregator.lookupAsync(
domains, interfaceName, discoveryQos),
"Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncParticipantId_proxyNotSet_doesNotThrow)
{
const std::string participantId;
EXPECT_DEATH(
localDiscoveryAggregator.lookupAsync(participantId), "Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, removeAsync_proxyNotSet_doesNotThrow)
{
const std::string participantId;
EXPECT_DEATH(
localDiscoveryAggregator.removeAsync(participantId), "Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, addAsync_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
types::DiscoveryEntryWithMetaInfo discoveryEntry;
discoveryEntry.setParticipantId("testParticipantId");
EXPECT_CALL(*discoveryMock, addAsyncMock(Eq(discoveryEntry), _, Eq(nullptr), Eq(nullptr), _));
localDiscoveryAggregator.addAsync(discoveryEntry, false, nullptr, nullptr);
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncDomainInterface_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
const std::vector<std::string> domains{"domain1", "domain2"};
const std::string interfaceName("testInterfaceName");
types::DiscoveryQos discoveryQos;
discoveryQos.setDiscoveryTimeout(42421);
EXPECT_CALL(
*discoveryMock,
lookupAsyncMock(
Eq(domains), Eq(interfaceName), Eq(discoveryQos),Matcher<std::function<void(const std::vector<joynr::types::DiscoveryEntryWithMetaInfo>& result)>>(_),_,_));
localDiscoveryAggregator.lookupAsync(domains, interfaceName, discoveryQos);
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncParticipantId_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
const std::string participantId("testParticipantId");
EXPECT_CALL(*discoveryMock, lookupAsyncMock(Eq(participantId), Eq(nullptr), Eq(nullptr), _));
localDiscoveryAggregator.lookupAsync(participantId);
}
TEST_F(LocalDiscoveryAggregatorTest, removeAsync_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
const std::string participantId("testParticipantId");
EXPECT_CALL(*discoveryMock, removeAsyncMock(Eq(participantId), Eq(nullptr), Eq(nullptr), _));
localDiscoveryAggregator.removeAsync(participantId, nullptr, nullptr);
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncParticipantId_provisionedEntry_doesNotCallProxy)
{
Semaphore semaphore(0);
const std::string participantId("testProvisionedParticipantId");
types::DiscoveryEntryWithMetaInfo provisionedDiscoveryEntry;
provisionedDiscoveryEntry.setParticipantId("testProvisionedParticipantId");
provisionedDiscoveryEntries.insert(std::make_pair(participantId, provisionedDiscoveryEntry));
LocalDiscoveryAggregator localDiscoveryAggregator(provisionedDiscoveryEntries);
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
EXPECT_CALL(*discoveryMock, lookupAsyncMock(_, _, _, _)).Times(0);
auto onSuccess = [&semaphore, &provisionedDiscoveryEntry](
const types::DiscoveryEntryWithMetaInfo& entry) {
EXPECT_EQ(entry, provisionedDiscoveryEntry);
semaphore.notify();
};
auto future = localDiscoveryAggregator.lookupAsync(participantId, onSuccess, nullptr);
types::DiscoveryEntryWithMetaInfo result;
future->get(100, result);
EXPECT_EQ(result, provisionedDiscoveryEntry);
EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(100)));
}
<commit_msg>[C++] Added addAsync test with gbids to LocalDiscoveryAggregatorTest<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <chrono>
#include <functional>
#include <map>
#include <memory>
#include <vector>
#include <gtest/gtest.h>
#include "joynr/LocalDiscoveryAggregator.h"
#include "joynr/Future.h"
#include "joynr/Semaphore.h"
#include "joynr/types/DiscoveryEntryWithMetaInfo.h"
#include "joynr/types/DiscoveryError.h"
#include "joynr/types/DiscoveryQos.h"
#include "tests/mock/MockDiscovery.h"
using ::testing::DoAll;
using namespace ::testing;
using namespace joynr;
class LocalDiscoveryAggregatorTest : public ::testing::Test
{
public:
LocalDiscoveryAggregatorTest()
: provisionedDiscoveryEntries(),
localDiscoveryAggregator(provisionedDiscoveryEntries),
discoveryMock(std::make_shared<MockDiscovery>())
{
}
~LocalDiscoveryAggregatorTest() override
{
}
protected:
std::map<std::string, types::DiscoveryEntryWithMetaInfo> provisionedDiscoveryEntries;
LocalDiscoveryAggregator localDiscoveryAggregator;
std::shared_ptr<MockDiscovery> discoveryMock;
private:
DISALLOW_COPY_AND_ASSIGN(LocalDiscoveryAggregatorTest);
};
TEST_F(LocalDiscoveryAggregatorTest, addAsync_proxyNotSet_doesNotThrow)
{
const types::DiscoveryEntryWithMetaInfo discoveryEntry;
EXPECT_DEATH(localDiscoveryAggregator.addAsync(discoveryEntry, false, nullptr, nullptr),
"Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncDomainInterface_proxyNotSet_doesNotThrow)
{
const std::vector<std::string> domains;
const std::string interfaceName;
const types::DiscoveryQos discoveryQos;
EXPECT_DEATH(localDiscoveryAggregator.lookupAsync(
domains, interfaceName, discoveryQos),
"Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncParticipantId_proxyNotSet_doesNotThrow)
{
const std::string participantId;
EXPECT_DEATH(
localDiscoveryAggregator.lookupAsync(participantId), "Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, removeAsync_proxyNotSet_doesNotThrow)
{
const std::string participantId;
EXPECT_DEATH(
localDiscoveryAggregator.removeAsync(participantId), "Assertion.*");
}
TEST_F(LocalDiscoveryAggregatorTest, addAsync_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
types::DiscoveryEntryWithMetaInfo discoveryEntry;
discoveryEntry.setParticipantId("testParticipantId");
EXPECT_CALL(*discoveryMock, addAsyncMock(Eq(discoveryEntry), _, Eq(nullptr), Eq(nullptr), _));
localDiscoveryAggregator.addAsync(discoveryEntry, false, nullptr, nullptr);
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncDomainInterface_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
const std::vector<std::string> domains{"domain1", "domain2"};
const std::string interfaceName("testInterfaceName");
types::DiscoveryQos discoveryQos;
discoveryQos.setDiscoveryTimeout(42421);
EXPECT_CALL(
*discoveryMock,
lookupAsyncMock(
Eq(domains), Eq(interfaceName), Eq(discoveryQos),Matcher<std::function<void(const std::vector<joynr::types::DiscoveryEntryWithMetaInfo>& result)>>(_),_,_));
localDiscoveryAggregator.lookupAsync(domains, interfaceName, discoveryQos);
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncParticipantId_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
const std::string participantId("testParticipantId");
EXPECT_CALL(*discoveryMock, lookupAsyncMock(Eq(participantId), Eq(nullptr), Eq(nullptr), _));
localDiscoveryAggregator.lookupAsync(participantId);
}
TEST_F(LocalDiscoveryAggregatorTest, removeAsync_callsProxy)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
const std::string participantId("testParticipantId");
EXPECT_CALL(*discoveryMock, removeAsyncMock(Eq(participantId), Eq(nullptr), Eq(nullptr), _));
localDiscoveryAggregator.removeAsync(participantId, nullptr, nullptr);
}
TEST_F(LocalDiscoveryAggregatorTest, lookupAsyncParticipantId_provisionedEntry_doesNotCallProxy)
{
Semaphore semaphore(0);
const std::string participantId("testProvisionedParticipantId");
types::DiscoveryEntryWithMetaInfo provisionedDiscoveryEntry;
provisionedDiscoveryEntry.setParticipantId("testProvisionedParticipantId");
provisionedDiscoveryEntries.insert(std::make_pair(participantId, provisionedDiscoveryEntry));
LocalDiscoveryAggregator localDiscoveryAggregator(provisionedDiscoveryEntries);
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
EXPECT_CALL(*discoveryMock, lookupAsyncMock(_, _, _, _)).Times(0);
auto onSuccess = [&semaphore, &provisionedDiscoveryEntry](
const types::DiscoveryEntryWithMetaInfo& entry) {
EXPECT_EQ(entry, provisionedDiscoveryEntry);
semaphore.notify();
};
auto future = localDiscoveryAggregator.lookupAsync(participantId, onSuccess, nullptr);
types::DiscoveryEntryWithMetaInfo result;
future->get(100, result);
EXPECT_EQ(result, provisionedDiscoveryEntry);
EXPECT_TRUE(semaphore.waitFor(std::chrono::milliseconds(100)));
}
TEST_F(LocalDiscoveryAggregatorTest, addAsync_callsProxyWithGbids)
{
localDiscoveryAggregator.setDiscoveryProxy(discoveryMock);
types::DiscoveryEntryWithMetaInfo discoveryEntry;
discoveryEntry.setParticipantId("testParticipantId");
std::vector<std::string> gbids = { "joynrdefaultgbid", "othergbid" };
std::vector<std::string> capturedGbids;
Future<void> future;
auto onSuccess = [&future]() { future.onSuccess(); };
auto onError = [&future](const exceptions::JoynrRuntimeException& exception) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(exception));
};
auto onApplicationError = [&future](const joynr::types::DiscoveryError::Enum& errorEnum) {
future.onError(std::make_shared<exceptions::JoynrRuntimeException>(joynr::types::DiscoveryError::getLiteral(errorEnum)));
};
auto mockFuture = std::make_shared<joynr::Future<void>>();
mockFuture->onSuccess();
EXPECT_CALL(*discoveryMock, addAsyncMock(Eq(discoveryEntry), Eq(false), _, _, _, _, _)).WillOnce(
DoAll(::testing::SaveArg<2>(&capturedGbids), InvokeArgument<3>(), Return(mockFuture)));
localDiscoveryAggregator.addAsync(discoveryEntry, false, gbids, onSuccess, onApplicationError, onError);
future.get();
EXPECT_EQ(gbids, capturedGbids);
}
<|endoftext|>
|
<commit_before>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <algorithm>
# include <string>
# include <vector>
# include <gio/gio.h>
# include <Siv3D/PowerStatus.hpp>
# include <Siv3D/EngineLog.hpp>
namespace s3d
{
namespace detail
{
const char* NAME_UPower = "org.freedesktop.UPower";
const char* OBJECT_UPower = "/org/freedesktop/UPower";
const char* INTERFACE_UPower = "org.freedesktop.UPower";
const char* INTERFACE_UPower_Device = "org.freedesktop.UPower.Device";
bool get_property(GDBusProxy *_proxy, const gchar *_property_name, const gchar *_format, void *_dest)
{
GVariant *variant = g_dbus_proxy_get_cached_property(_proxy, _property_name);
if (variant != nullptr)
{
g_variant_get(variant, _format, _dest);
g_variant_unref(variant);
return true;
}
else
return false;
}
bool get_property_and_output_log(GDBusProxy *_proxy, const gchar *_property_name, const gchar *_format, void *_dest)
{
bool ret = get_property(_proxy, _property_name, _format, _dest);
if (ret == false)
{
LOG_FAIL(U"❌ PowerStatus: Failed to get UPower device property ({})."_fmt(Unicode::Widen(_property_name)));
}
return ret;
}
void GetPowerStatus_Linux(PowerStatus& result)
{
std::vector<std::string> devicePaths;
GDBusProxy *proxy;
GDBusConnection *conn;
GError *error = nullptr;
char *s;
guint32 u;
guint64 x;
gboolean b;
gdouble d;
GVariant *variant;
GVariantIter *iter;
conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
if (conn == nullptr)
{
LOG_FAIL(U"❌ PowerStatus: Failed to get d-bus connection.");
return;
}
proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE, nullptr,
NAME_UPower, OBJECT_UPower, INTERFACE_UPower, nullptr, &error);
if (proxy == nullptr)
{
LOG_FAIL(U"❌ PowerStatus: Failed to get d-bus proxy.");
return;
}
variant = g_dbus_proxy_get_cached_property(proxy, "DaemonVersion");
if (variant == nullptr)
{
LOG_FAIL(U"❌ PowerStatus: Failed to get UPower properties.");
return;
}
g_variant_get(variant, "s", &s);
g_variant_unref(variant);
LOG_INFO(U"ℹ️ PowerStatus: UPower daemon version {}"_fmt(Unicode::Widen(s)));
variant = g_dbus_proxy_call_sync(proxy, "EnumerateDevices", nullptr,
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
if (variant == nullptr)
{
LOG_FAIL(U"❌ PowerStatus: Failed to enumerate power supply devices.");
return;
}
g_variant_get(variant, "(ao)", &iter);
while (g_variant_iter_loop(iter, "o", &s))
{
devicePaths.push_back(s);
}
g_variant_iter_free(iter);
g_variant_unref(variant);
g_object_unref(proxy);
result.battery = BatteryStatus::NoBattery;
for (const auto &dev : devicePaths)
{
proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE, nullptr,
NAME_UPower, dev.c_str(), INTERFACE_UPower_Device, nullptr, &error);
if (!get_property_and_output_log(proxy, "Type", "u", &u))
continue;
if (u == 1)
{
//line power
if (get_property_and_output_log(proxy, "Online", "b", &b))
{
result.ac = b ? ACLineStatus::Online : ACLineStatus::Offline;
}
}
else if (u == 2)
{
//battery
if (get_property_and_output_log(proxy, "Percentage", "d", &d))
{
result.batteryLifePercent = static_cast<int32>(d);
result.battery = d <= 5 ? BatteryStatus::Critical
: d <= 33 ? BatteryStatus::Low
: d <= 66 ? BatteryStatus::Middle
: BatteryStatus::High;
}
if (get_property_and_output_log(proxy, "State", "u", &u))
{
if (u == 1)
{
//charging
result.charging = true;
if (get_property_and_output_log(proxy, "TimeToFull", "x", &x))
{
if (x != 0)
result.batteryTimeToFullChargeSec = static_cast<int32>(x);
}
}
else if (u == 2)
{
//discharging
if (get_property_and_output_log(proxy, "TimeToEmpty", "x", &x))
{
if (x != 0)
result.batteryLifeTimeSec = static_cast<int32>(x);
}
}
}
}
}
g_object_unref(conn);
}
}
namespace System
{
PowerStatus GetPowerStatus()
{
PowerStatus status;
detail::GetPowerStatus_Linux(status);
return status;
}
}
}
<commit_msg>[Linux] workaround #577<commit_after>//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2021 Ryo Suzuki
// Copyright (c) 2016-2021 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <algorithm>
# include <string>
# include <vector>
# include <fstream>
//# include <gio/gio.h>
# include <Siv3D/PowerStatus.hpp>
# include <Siv3D/EngineLog.hpp>
namespace s3d
{
/*
// [Siv3D ToDo]
// ・時間がかかりすぎる(> 20ms)
// ・ACLineStatus が不正確
namespace detail
{
const char* NAME_UPower = "org.freedesktop.UPower";
const char* OBJECT_UPower = "/org/freedesktop/UPower";
const char* INTERFACE_UPower = "org.freedesktop.UPower";
const char* INTERFACE_UPower_Device = "org.freedesktop.UPower.Device";
bool get_property(GDBusProxy *_proxy, const gchar *_property_name, const gchar *_format, void *_dest)
{
GVariant *variant = g_dbus_proxy_get_cached_property(_proxy, _property_name);
if (variant != nullptr)
{
g_variant_get(variant, _format, _dest);
g_variant_unref(variant);
return true;
}
else
return false;
}
bool get_property_and_output_log(GDBusProxy *_proxy, const gchar *_property_name, const gchar *_format, void *_dest)
{
bool ret = get_property(_proxy, _property_name, _format, _dest);
if (ret == false)
{
//LOG_FAIL(U"❌ PowerStatus: Failed to get UPower device property ({})."_fmt(Unicode::Widen(_property_name)));
}
return ret;
}
void GetPowerStatus_Linux(PowerStatus& result)
{
std::vector<std::string> devicePaths;
GDBusProxy *proxy;
GDBusConnection *conn;
GError *error = nullptr;
char *s;
guint32 u;
guint64 x;
gboolean b;
gdouble d;
GVariant *variant;
GVariantIter *iter;
conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, nullptr, &error);
if (conn == nullptr)
{
//LOG_FAIL(U"❌ PowerStatus: Failed to get d-bus connection.");
return;
}
proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE, nullptr,
NAME_UPower, OBJECT_UPower, INTERFACE_UPower, nullptr, &error);
if (proxy == nullptr)
{
//LOG_FAIL(U"❌ PowerStatus: Failed to get d-bus proxy.");
return;
}
variant = g_dbus_proxy_get_cached_property(proxy, "DaemonVersion");
if (variant == nullptr)
{
//LOG_FAIL(U"❌ PowerStatus: Failed to get UPower properties.");
return;
}
g_variant_get(variant, "s", &s);
g_variant_unref(variant);
//LOG_INFO(U"ℹ️ PowerStatus: UPower daemon version {}"_fmt(Unicode::Widen(s)));
variant = g_dbus_proxy_call_sync(proxy, "EnumerateDevices", nullptr,
G_DBUS_CALL_FLAGS_NONE, -1, nullptr, &error);
if (variant == nullptr)
{
//LOG_FAIL(U"❌ PowerStatus: Failed to enumerate power supply devices.");
return;
}
g_variant_get(variant, "(ao)", &iter);
while (g_variant_iter_loop(iter, "o", &s))
{
devicePaths.push_back(s);
}
g_variant_iter_free(iter);
g_variant_unref(variant);
g_object_unref(proxy);
result.battery = BatteryStatus::NoBattery;
for (const auto &dev : devicePaths)
{
proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE, nullptr,
NAME_UPower, dev.c_str(), INTERFACE_UPower_Device, nullptr, &error);
if (!get_property_and_output_log(proxy, "Type", "u", &u))
continue;
if (u == 1)
{
//line power
if (get_property_and_output_log(proxy, "Online", "b", &b))
{
result.ac = b ? ACLineStatus::Online : ACLineStatus::Offline;
}
}
else if (u == 2)
{
//battery
if (get_property_and_output_log(proxy, "Percentage", "d", &d))
{
result.batteryLifePercent = static_cast<int32>(d);
result.battery = d <= 5 ? BatteryStatus::Critical
: d <= 33 ? BatteryStatus::Low
: d <= 66 ? BatteryStatus::Middle
: BatteryStatus::High;
}
if (get_property_and_output_log(proxy, "State", "u", &u))
{
if (u == 1)
{
//charging
result.charging = true;
if (get_property_and_output_log(proxy, "TimeToFull", "x", &x))
{
if (x != 0)
result.batteryTimeToFullChargeSec = static_cast<int32>(x);
}
}
else if (u == 2)
{
//discharging
if (get_property_and_output_log(proxy, "TimeToEmpty", "x", &x))
{
if (x != 0)
result.batteryLifeTimeSec = static_cast<int32>(x);
}
}
}
}
}
g_object_unref(conn);
}
}
namespace System
{
PowerStatus GetPowerStatus()
{
PowerStatus status;
detail::GetPowerStatus_Linux(status);
return status;
}
}
*/
namespace detail
{
[[nodiscard]]
static Optional<int32> ReadInt(const char* path)
{
std::ifstream ifs{ path };
if (not ifs)
{
return none;
}
int32 value;
if (ifs >> value)
{
return value;
}
else
{
return none;
}
}
[[nodiscard]]
static Optional<std::string> ReadString(const char* path)
{
std::ifstream ifs{ path };
if (not ifs)
{
return none;
}
std::string value;
if (ifs >> value)
{
return value;
}
else
{
return none;
}
}
}
namespace System
{
PowerStatus GetPowerStatus()
{
PowerStatus status;
status.battery = BatteryStatus::NoBattery;
bool hasBattery = false;
if (auto value = detail::ReadInt("/sys/class/power_supply/AC/online"))
{
status.ac = (*value == 1) ? ACLineStatus::Online : ACLineStatus::Offline;
}
else if (auto value = detail::ReadInt("/sys/class/power_supply/ac/online"))
{
status.ac = (*value == 1) ? ACLineStatus::Online : ACLineStatus::Offline;
}
if (auto value = detail::ReadString("/sys/class/power_supply/battery/status"))
{
hasBattery = true;
status.charging = (*value == "Charging");
if (auto capacity = detail::ReadInt("/sys/class/power_supply/battery/capacity"))
{
status.batteryLifePercent = capacity;
}
}
else if (auto value = detail::ReadString("/sys/class/power_supply/BAT0/status"))
{
hasBattery = true;
status.charging = (*value == "Charging");
if (auto capacity = detail::ReadInt("/sys/class/power_supply/BAT0/capacity"))
{
status.batteryLifePercent = capacity;
}
}
if (hasBattery)
{
if (status.batteryLifePercent)
{
const int32 percent = *status.batteryLifePercent;
status.battery = percent <+ 5 ? BatteryStatus::Critical
: percent <= 33 ? BatteryStatus::Low
: percent <= 66 ? BatteryStatus::Middle
: BatteryStatus::High;
}
else
{
status.battery = BatteryStatus::Unknown;
}
}
return status;
}
}
}
<|endoftext|>
|
<commit_before>/** \brief Utility for generating ISSN mapping tables from Zeder.
* \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de)
*
* \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iostream>
#include <unordered_set>
#include <cstdio>
#include <cstdlib>
#include "BSZTransform.h"
#include "ExecUtil.h"
#include "File.h"
#include "FileUtil.h"
#include "MiscUtil.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"
namespace {
[[noreturn]] void Usage() {
::Usage("[--find-duplicate-issns] [--push-to-github] issn_map_directory <map-type=filename> <map-type=filename>...\n\n"
"Valid map type(s): ssg");
}
enum MapType { SSG };
struct MapParams {
std::string type_string_;
std::string zeder_column_;
std::function<std::string(const std::string &, const unsigned)> convert_zeder_value_to_map_value_;
};
std::string ZederToMapValueSSGN(const std::string &zeder_value, const unsigned zeder_id) {
switch (BSZTransform::GetSSGNTypeFromString(zeder_value)) {
case BSZTransform::SSGNType::FG_0:
return "0";
case BSZTransform::SSGNType::FG_1:
return "1";
case BSZTransform::SSGNType::FG_01:
return "0/1";
case BSZTransform::SSGNType::INVALID:
LOG_ERROR("invalid Zeder value for SSGN '" + zeder_value + "' (Zeder ID: " + std::to_string(zeder_id) + ")");
}
}
const std::map<MapType, MapParams> MAP_TYPE_TO_PARAMS {
{ MapType::SSG, { "ssg", "ber", ZederToMapValueSSGN } }
};
const std::map<std::string, MapType> STRING_TO_MAP_TYPE {
{ "ssg", MapType::SSG }
};
void ParseMapPairs(int argc, char * argv[], std::map<MapType, std::string> * const map_type_to_filename) {
std::vector<std::string> splits;
for (int i(1); i < argc; ++i) {
StringUtil::Split(std::string(argv[i]), std::string("="), &splits);
if (splits.size() != 2)
Usage();
const auto match(STRING_TO_MAP_TYPE.find(splits[0]));
if (match == STRING_TO_MAP_TYPE.end())
Usage();
map_type_to_filename->insert(std::make_pair(match->second, splits[1]));
}
}
void DownloadFullDumpFromZeder(Zeder::Flavour flavour, Zeder::EntryCollection * const entries) {
std::unordered_set<std::string> columns_to_download;
std::unordered_set<unsigned> entries_to_download;
std::unordered_map<std::string, std::string> filter_regexps;
std::unique_ptr<Zeder::FullDumpDownloader::Params> params(
new Zeder::FullDumpDownloader::Params(Zeder::GetFullDumpEndpointPath(flavour),
entries_to_download, columns_to_download, filter_regexps));
Zeder::EndpointDownloader::Factory(Zeder::EndpointDownloader::FULL_DUMP, std::move(params))->download(entries);
}
struct MapValue {
std::string issn_; // print or online
std::string journal_title_;
unsigned zeder_id_;
std::string value_;
MapValue(const std::string issn, const std::string journal_title, const unsigned zeder_id, const std::string &value)
: issn_(issn), journal_title_(journal_title), zeder_id_(zeder_id), value_(value) {}
};
void GenerateISSNMap(Zeder::EntryCollection &entries, const MapParams ¶ms,
std::vector<MapValue> * const map_values)
{
static const std::string ZEDER_TITLE_COLUMN("tit");
static const std::string ZEDER_ISSN_COLUMN("issn");
static const std::string ZEDER_ESSN_COLUMN("essn");
map_values->clear();
for (const auto &entry : entries) {
const auto zeder_value(entry.getAttribute(params.zeder_column_, ""));
if (zeder_value.empty()) {
LOG_DEBUG("Skipping zeder entry " + std::to_string(entry.getId()) + " with no value for '" + params.zeder_column_ + "'");
continue;
}
std::set<std::string> issns, scratch;
StringUtil::Split(entry.getAttribute(ZEDER_ISSN_COLUMN, ""), std::set<char>{ ' ', ','}, &scratch,
/* suppress_empty_tokens = */ true);
for (const auto &split : scratch) {
if (MiscUtil::IsPossibleISSN(split))
issns.insert(split);
}
StringUtil::Split(entry.getAttribute(ZEDER_ESSN_COLUMN, ""), std::set<char>{ ' ', ','}, &scratch,
/* suppress_empty_tokens = */ true);
for (const auto &split : scratch) {
if (MiscUtil::IsPossibleISSN(split))
issns.insert(split);
}
for (const auto &issn : issns) {
const auto converted_value(params.convert_zeder_value_to_map_value_(zeder_value, entry.getId()));
map_values->emplace_back(issn, entry.getAttribute(ZEDER_TITLE_COLUMN),
entry.getId(), converted_value);
}
}
}
void FindDuplicateISSNs(const std::vector<MapValue> &map_values) {
std::unordered_set<std::string> processed_issns;
std::unordered_multimap<std::string, unsigned> processed_values;
for (const auto &value : map_values) {
processed_values.insert(std::make_pair(value.issn_, value.zeder_id_));
processed_issns.insert(value.issn_);
}
for (const auto &issn : processed_issns) {
if (processed_values.count(issn) > 1) {
const auto range(processed_values.equal_range(issn));
std::string warning_message("ISSN '" + issn + "' found in multiple Zeder entries: ");
for (auto itr(range.first); itr != range.second; ++itr)
warning_message += std::to_string(itr->second) + " ";
LOG_WARNING(warning_message);
}
}
}
void WriteMapValuesToFile(const std::vector<MapValue> &map_values, const MapParams &map_params, const std::string &file_path) {
File output(file_path, "w");
for (const auto &value : map_values) {
output.writeln(value.issn_ + "=" + value.value_ + " # (" + std::to_string(value.zeder_id_) + ") "
+ value.journal_title_);
}
LOG_INFO("Wrote " + std::to_string(map_values.size()) + " entries to " + map_params.type_string_ + " map '"
+ file_path + "'");
}
/*
void PushToGitHub(const std::string &issn_directory, const std::vector<std::string> &files_to_push) {
}
*/
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 3)
Usage();
bool find_duplicate_issns(false);
const std::string FIND_DUPLICATE_ISSNS_FLAG("--find-duplicate-issns");
if (StringUtil::StartsWith(argv[1], FIND_DUPLICATE_ISSNS_FLAG)) {
find_duplicate_issns = true;
--argc, ++argv;
}
bool push_to_github(false);
const std::string COMMIT_AND_PUSH_FLAG("--push-to-github");
if (StringUtil::StartsWith(argv[1], COMMIT_AND_PUSH_FLAG)) {
push_to_github = true;
--argc, ++argv;
}
if (argc < 3)
Usage();
const std::string issn_directory(argv[1]);
--argc, ++argv;
std::map<MapType, std::string> map_filename_pairs;
ParseMapPairs(argc, argv, &map_filename_pairs);
Zeder::EntryCollection entries;
DownloadFullDumpFromZeder(Zeder::Flavour::IXTHEO, &entries);
std::vector<MapValue> map_values;
std::vector<std::string> files_to_push;
for (const auto &map_filename_pair : map_filename_pairs) {
const auto &map_params(MAP_TYPE_TO_PARAMS.at(map_filename_pair.first));
const std::string output_file(issn_directory + "/" + map_filename_pair.second);
GenerateISSNMap(entries, map_params, &map_values);
if (find_duplicate_issns)
FindDuplicateISSNs(map_values);
WriteMapValuesToFile(map_values, map_params, output_file);
if (push_to_github)
files_to_push.emplace_back(output_file);
}
// if (push_to_github)
// PushToGitHub(issn_directory, files_to_push);
return EXIT_SUCCESS;
}
<commit_msg>Code style<commit_after>/** \brief Utility for generating ISSN mapping tables from Zeder.
* \author Madeeswaran Kannan (madeeswaran.kannan@uni-tuebingen.de)
*
* \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iostream>
#include <unordered_set>
#include <cstdio>
#include <cstdlib>
#include "BSZTransform.h"
#include "ExecUtil.h"
#include "File.h"
#include "FileUtil.h"
#include "MiscUtil.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"
namespace {
const std::string FIND_DUPLICATE_ISSNS_FLAG("--find-duplicate-issns");
const std::string COMMIT_AND_PUSH_FLAG("--push-to-github");
[[noreturn]] void Usage() {
::Usage("[" + FIND_DUPLICATE_ISSNS_FLAG + "] [" + COMMIT_AND_PUSH_FLAG + "] issn_map_directory <map-type=filename>"
"<map-type=filename>...\n\nValid map type(s): ssg");
}
enum MapType { SSG };
struct MapParams {
std::string type_string_;
std::string zeder_column_;
std::function<std::string(const std::string &, const unsigned)> convert_zeder_value_to_map_value_;
};
std::string ZederToMapValueSSGN(const std::string &zeder_value, const unsigned zeder_id) {
switch (BSZTransform::GetSSGNTypeFromString(zeder_value)) {
case BSZTransform::SSGNType::FG_0:
return "0";
case BSZTransform::SSGNType::FG_1:
return "1";
case BSZTransform::SSGNType::FG_01:
return "0/1";
case BSZTransform::SSGNType::INVALID:
LOG_ERROR("invalid Zeder value for SSGN '" + zeder_value + "' (Zeder ID: " + std::to_string(zeder_id) + ")");
}
}
const std::map<MapType, MapParams> MAP_TYPE_TO_PARAMS {
{ MapType::SSG, { "ssg", "ber", ZederToMapValueSSGN } }
};
const std::map<std::string, MapType> STRING_TO_MAP_TYPE {
{ "ssg", MapType::SSG }
};
void ParseMapPairs(int argc, char * argv[], std::map<MapType, std::string> * const map_type_to_filename) {
std::vector<std::string> splits;
for (int i(1); i < argc; ++i) {
StringUtil::Split(std::string(argv[i]), std::string("="), &splits);
if (splits.size() != 2)
Usage();
const auto match(STRING_TO_MAP_TYPE.find(splits[0]));
if (match == STRING_TO_MAP_TYPE.end())
Usage();
map_type_to_filename->insert(std::make_pair(match->second, splits[1]));
}
}
void DownloadFullDumpFromZeder(Zeder::Flavour flavour, Zeder::EntryCollection * const entries) {
std::unordered_set<std::string> columns_to_download;
std::unordered_set<unsigned> entries_to_download;
std::unordered_map<std::string, std::string> filter_regexps;
std::unique_ptr<Zeder::FullDumpDownloader::Params> params(
new Zeder::FullDumpDownloader::Params(Zeder::GetFullDumpEndpointPath(flavour),
entries_to_download, columns_to_download, filter_regexps));
Zeder::EndpointDownloader::Factory(Zeder::EndpointDownloader::FULL_DUMP, std::move(params))->download(entries);
}
struct MapValue {
std::string issn_; // print or online
std::string journal_title_;
unsigned zeder_id_;
std::string value_;
MapValue(const std::string issn, const std::string journal_title, const unsigned zeder_id, const std::string &value)
: issn_(issn), journal_title_(journal_title), zeder_id_(zeder_id), value_(value) {}
};
void GenerateISSNMap(Zeder::EntryCollection &entries, const MapParams ¶ms,
std::vector<MapValue> * const map_values)
{
static const std::string ZEDER_TITLE_COLUMN("tit");
static const std::string ZEDER_ISSN_COLUMN("issn");
static const std::string ZEDER_ESSN_COLUMN("essn");
map_values->clear();
for (const auto &entry : entries) {
const auto zeder_value(entry.getAttribute(params.zeder_column_, ""));
if (zeder_value.empty()) {
LOG_DEBUG("Skipping zeder entry " + std::to_string(entry.getId()) + " with no value for '" + params.zeder_column_ + "'");
continue;
}
std::set<std::string> issns, scratch;
StringUtil::Split(entry.getAttribute(ZEDER_ISSN_COLUMN, ""), std::set<char>{ ' ', ','}, &scratch,
/* suppress_empty_tokens = */ true);
for (const auto &split : scratch) {
if (MiscUtil::IsPossibleISSN(split))
issns.insert(split);
}
StringUtil::Split(entry.getAttribute(ZEDER_ESSN_COLUMN, ""), std::set<char>{ ' ', ','}, &scratch,
/* suppress_empty_tokens = */ true);
for (const auto &split : scratch) {
if (MiscUtil::IsPossibleISSN(split))
issns.insert(split);
}
for (const auto &issn : issns) {
const auto converted_value(params.convert_zeder_value_to_map_value_(zeder_value, entry.getId()));
map_values->emplace_back(issn, entry.getAttribute(ZEDER_TITLE_COLUMN),
entry.getId(), converted_value);
}
}
}
void FindDuplicateISSNs(const std::vector<MapValue> &map_values) {
std::unordered_set<std::string> processed_issns;
std::unordered_multimap<std::string, unsigned> processed_values;
for (const auto &value : map_values) {
processed_values.insert(std::make_pair(value.issn_, value.zeder_id_));
processed_issns.insert(value.issn_);
}
for (const auto &issn : processed_issns) {
if (processed_values.count(issn) > 1) {
const auto range(processed_values.equal_range(issn));
std::string warning_message("ISSN '" + issn + "' found in multiple Zeder entries: ");
for (auto itr(range.first); itr != range.second; ++itr)
warning_message += std::to_string(itr->second) + " ";
LOG_WARNING(warning_message);
}
}
}
void WriteMapValuesToFile(const std::vector<MapValue> &map_values, const MapParams &map_params, const std::string &file_path) {
File output(file_path, "w");
for (const auto &value : map_values) {
output.writeln(value.issn_ + "=" + value.value_ + " # (" + std::to_string(value.zeder_id_) + ") "
+ value.journal_title_);
}
LOG_INFO("Wrote " + std::to_string(map_values.size()) + " entries to " + map_params.type_string_ + " map '"
+ file_path + "'");
}
/*
void PushToGitHub(const std::string &issn_directory, const std::vector<std::string> &files_to_push) {
}
*/
} // unnamed namespace
int Main(int argc, char *argv[]) {
if (argc < 3)
Usage();
bool find_duplicate_issns(false);
if (StringUtil::StartsWith(argv[1], FIND_DUPLICATE_ISSNS_FLAG)) {
find_duplicate_issns = true;
--argc, ++argv;
}
bool push_to_github(false);
if (StringUtil::StartsWith(argv[1], COMMIT_AND_PUSH_FLAG)) {
push_to_github = true;
--argc, ++argv;
}
if (argc < 3)
Usage();
const std::string issn_directory(argv[1]);
--argc, ++argv;
std::map<MapType, std::string> map_filename_pairs;
ParseMapPairs(argc, argv, &map_filename_pairs);
Zeder::EntryCollection entries;
DownloadFullDumpFromZeder(Zeder::Flavour::IXTHEO, &entries);
std::vector<MapValue> map_values;
std::vector<std::string> files_to_push;
for (const auto &map_filename_pair : map_filename_pairs) {
const auto &map_params(MAP_TYPE_TO_PARAMS.at(map_filename_pair.first));
const std::string output_file(issn_directory + "/" + map_filename_pair.second);
GenerateISSNMap(entries, map_params, &map_values);
if (find_duplicate_issns)
FindDuplicateISSNs(map_values);
WriteMapValuesToFile(map_values, map_params, output_file);
if (push_to_github)
files_to_push.emplace_back(output_file);
}
// if (push_to_github)
// PushToGitHub(issn_directory, files_to_push);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/version.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop
#include <string>
int main (int argc,char** argv)
{
namespace po = boost::program_options;
bool verbose = false;
bool auto_open = true;
int return_value = 0;
std::string xml_file;
std::string img_file;
double scale_factor = 1;
bool params_as_variables = false;
mapnik::logger logger;
logger.set_severity(mapnik::logger::error);
try
{
po::options_description desc("nik2img utility");
desc.add_options()
("help,h", "produce usage message")
("version,V","print version string")
("verbose,v","verbose output")
("open","automatically open the file after rendering (os x only)")
("xml",po::value<std::string>(),"xml map to read")
("img",po::value<std::string>(),"image to render")
("scale-factor",po::value<double>(),"scale factor for rendering")
("variables","make map parameters available as render-time variables")
;
po::positional_options_description p;
p.add("xml",1);
p.add("img",1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("version"))
{
std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl;
return 1;
}
if (vm.count("help"))
{
std::clog << desc << std::endl;
return 1;
}
if (vm.count("verbose"))
{
verbose = true;
}
if (vm.count("open"))
{
auto_open = true;
}
if (vm.count("xml"))
{
xml_file=vm["xml"].as<std::string>();
}
else
{
std::clog << "please provide an xml map as first argument!" << std::endl;
return -1;
}
if (vm.count("img"))
{
img_file=vm["img"].as<std::string>();
}
else
{
std::clog << "please provide an img as second argument!" << std::endl;
return -1;
}
if (vm.count("scale-factor"))
{
scale_factor=vm["scale-factor"].as<double>();
}
if (vm.count("variables"))
{
params_as_variables = true;
}
mapnik::datasource_cache::instance().register_datasources("./plugins/input/");
mapnik::freetype_engine::register_fonts("./fonts",true);
mapnik::Map map(600,400);
mapnik::load_map(map,xml_file,true);
map.zoom_all();
mapnik::image_rgba8 im(map.width(),map.height());
mapnik::request req(map.width(),map.height(),map.get_current_extent());
req.set_buffer_size(map.buffer_size());
mapnik::attributes vars;
if (params_as_variables)
{
mapnik::transcoder tr("utf-8");
for (auto const& param : map.get_extra_parameters())
{
std::string const& name = param.first.substr(1);
if (!name.empty())
{
if (param.second.is<mapnik::value_integer>())
{
vars[name] = param.second.get<mapnik::value_integer>();
}
else if (param.second.is<mapnik::value_double>())
{
vars[name] = param.second.get<mapnik::value_double>();
}
else if (param.second.is<std::string>())
{
vars[name] = tr.transcode(param.second.get<std::string>().c_str());
}
}
}
}
mapnik::agg_renderer<mapnik::image_rgba8> ren(map,req,vars,im,scale_factor,0,0);
ren.apply();
mapnik::save_to_file(im,img_file);
if (auto_open)
{
std::ostringstream s;
#ifdef __APPLE__
s << "open ";
#elif _WIN32
s << "start ";
#else
s << "xdg-open ";
#endif
s << img_file;
int ret = system(s.str().c_str());
if (ret != 0)
return_value = ret;
}
else
{
std::clog << "rendered to: " << img_file << "\n";
}
}
catch (std::exception const& ex)
{
std::clog << "Error " << ex.what() << std::endl;
return -1;
}
return return_value;
}
<commit_msg>Fix name reported by mapnik-render<commit_after>#include <mapnik/map.hpp>
#include <mapnik/load_map.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/version.hpp>
#include <mapnik/debug.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/unicode.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#pragma GCC diagnostic push
#include <mapnik/warning_ignore.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#pragma GCC diagnostic pop
#include <string>
int main (int argc,char** argv)
{
namespace po = boost::program_options;
bool verbose = false;
bool auto_open = true;
int return_value = 0;
std::string xml_file;
std::string img_file;
double scale_factor = 1;
bool params_as_variables = false;
mapnik::logger logger;
logger.set_severity(mapnik::logger::error);
try
{
po::options_description desc("mapnik-render utility");
desc.add_options()
("help,h", "produce usage message")
("version,V","print version string")
("verbose,v","verbose output")
("open","automatically open the file after rendering (os x only)")
("xml",po::value<std::string>(),"xml map to read")
("img",po::value<std::string>(),"image to render")
("scale-factor",po::value<double>(),"scale factor for rendering")
("variables","make map parameters available as render-time variables")
;
po::positional_options_description p;
p.add("xml",1);
p.add("img",1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("version"))
{
std::clog <<"version " << MAPNIK_VERSION_STRING << std::endl;
return 1;
}
if (vm.count("help"))
{
std::clog << desc << std::endl;
return 1;
}
if (vm.count("verbose"))
{
verbose = true;
}
if (vm.count("open"))
{
auto_open = true;
}
if (vm.count("xml"))
{
xml_file=vm["xml"].as<std::string>();
}
else
{
std::clog << "please provide an xml map as first argument!" << std::endl;
return -1;
}
if (vm.count("img"))
{
img_file=vm["img"].as<std::string>();
}
else
{
std::clog << "please provide an img as second argument!" << std::endl;
return -1;
}
if (vm.count("scale-factor"))
{
scale_factor=vm["scale-factor"].as<double>();
}
if (vm.count("variables"))
{
params_as_variables = true;
}
mapnik::datasource_cache::instance().register_datasources("./plugins/input/");
mapnik::freetype_engine::register_fonts("./fonts",true);
mapnik::Map map(600,400);
mapnik::load_map(map,xml_file,true);
map.zoom_all();
mapnik::image_rgba8 im(map.width(),map.height());
mapnik::request req(map.width(),map.height(),map.get_current_extent());
req.set_buffer_size(map.buffer_size());
mapnik::attributes vars;
if (params_as_variables)
{
mapnik::transcoder tr("utf-8");
for (auto const& param : map.get_extra_parameters())
{
std::string const& name = param.first.substr(1);
if (!name.empty())
{
if (param.second.is<mapnik::value_integer>())
{
vars[name] = param.second.get<mapnik::value_integer>();
}
else if (param.second.is<mapnik::value_double>())
{
vars[name] = param.second.get<mapnik::value_double>();
}
else if (param.second.is<std::string>())
{
vars[name] = tr.transcode(param.second.get<std::string>().c_str());
}
}
}
}
mapnik::agg_renderer<mapnik::image_rgba8> ren(map,req,vars,im,scale_factor,0,0);
ren.apply();
mapnik::save_to_file(im,img_file);
if (auto_open)
{
std::ostringstream s;
#ifdef __APPLE__
s << "open ";
#elif _WIN32
s << "start ";
#else
s << "xdg-open ";
#endif
s << img_file;
int ret = system(s.str().c_str());
if (ret != 0)
return_value = ret;
}
else
{
std::clog << "rendered to: " << img_file << "\n";
}
}
catch (std::exception const& ex)
{
std::clog << "Error " << ex.what() << std::endl;
return -1;
}
return return_value;
}
<|endoftext|>
|
<commit_before>/* Copyright 2016 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This example demonstrates way in which virtual mapping can be useful -
// generating variable-sized output from a task
#include <legion.h>
#include <realm/cmdline.h>
#include <mappers/default_mapper.h>
using namespace Legion;
using namespace Legion::Mapping;
using namespace LegionRuntime::Accessor;
enum TaskID
{
TOP_LEVEL_TASK_ID,
MAKE_DATA_TASK_ID,
USE_DATA_TASK_ID,
};
enum {
FID_DATA = 55,
};
enum {
PID_ALLOCED_DATA = 4,
};
enum {
PFID_USE_DATA_TASK = 77,
};
LegionRuntime::Logger::Category log_app("app");
struct MakeDataTaskArgs {
int random_seed;
size_t average_output_size;
};
void top_level_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
size_t num_subregions = 4;
size_t average_output_size = 100;
size_t total_region_size = 1 << 30;
int random_seed = 12345;
bool use_projection_functor = false;
const InputArgs &command_args = HighLevelRuntime::get_input_args();
bool ok = Realm::CommandLineParser()
.add_option_int("-n", num_subregions)
.add_option_int("-s", average_output_size)
.add_option_int("-l", total_region_size)
.add_option_int("-seed", random_seed)
.add_option_bool("-proj", use_projection_functor)
.parse_command_line(command_args.argc, (const char **)command_args.argv);
if(!ok) {
log_app.fatal() << "error parsing command line arguments";
exit(1);
}
// create a top-level region that is (easily) large enough to hold all of our
// data - we need not worry about a tight bound, because we will never create
// any instances of this size
Rect<1> bounds(0, total_region_size - 1);
IndexSpace is = runtime->create_index_space(ctx, Domain::from_rect<1>(bounds));
runtime->attach_name(is, "is");
// our field space will just have a single field
FieldSpace fs = runtime->create_field_space(ctx);
runtime->attach_name(fs, "fs");
{
FieldAllocator fsa = runtime->create_field_allocator(ctx, fs);
fsa.allocate_field(sizeof(int), FID_DATA);
runtime->attach_name(fs, FID_DATA, "data");
}
LogicalRegion lr = runtime->create_logical_region(ctx, is, fs);
runtime->attach_name(lr, "lr");
// partition it into equal pieces - again, these are expected to be much
// larger than the actual output of the generator tasks
Rect<1> subregion_idxs(0, num_subregions - 1);
size_t elements_per_subregion = total_region_size / num_subregions;
assert(elements_per_subregion >= (2 * average_output_size));
Blockify<1> blockify(elements_per_subregion);
IndexPartition ip = runtime->create_index_partition(ctx, is, blockify);
LogicalPartition lp = runtime->get_logical_partition(ctx, lr, ip);
// perform an index launch to have each subregion filled in with a variable
// amount of data
{
MakeDataTaskArgs args;
args.random_seed = random_seed;
args.average_output_size = average_output_size;
IndexLauncher launcher(MAKE_DATA_TASK_ID, Domain::from_rect<1>(subregion_idxs),
TaskArgument(&args, sizeof(args)),
ArgumentMap());
launcher.add_region_requirement(RegionRequirement(lp,
0, // identity projection
READ_WRITE,
EXCLUSIVE,
lr,
DefaultMapper::VIRTUAL_MAP)
.add_field(FID_DATA));
FutureMap fm = runtime->execute_index_space(ctx, launcher);
fm.wait_all_results();
}
// now perform a second index launch to use the variable-sized chunks of
// data
{
IndexLauncher launcher(USE_DATA_TASK_ID, Domain::from_rect<1>(subregion_idxs),
TaskArgument(0, 0),
ArgumentMap());
if(use_projection_functor) {
// use a projection functor to tell the runtime precisely which sub-subregion
// each point task will use so that it can be mapped before the task executes -
// make sure the default mapper doesn't try to map the parent region though
launcher.add_region_requirement(RegionRequirement(lp,
PFID_USE_DATA_TASK,
READ_ONLY,
EXCLUSIVE,
lr,
DefaultMapper::EXACT_REGION)
.add_field(FID_DATA));
} else {
// OR, use another virtual mapping and let the use_data_task walk the region
// tree itself and do an inline mapping within the task
launcher.add_region_requirement(RegionRequirement(lp,
0, // identity projection
READ_ONLY,
EXCLUSIVE,
lr,
DefaultMapper::VIRTUAL_MAP)
.add_field(FID_DATA));
}
FutureMap fm = runtime->execute_index_space(ctx, launcher);
fm.wait_all_results();
}
}
void make_data_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
const MakeDataTaskArgs& args = *static_cast<const MakeDataTaskArgs *>(task->args);
int subregion_index = task->index_point.get_point<1>();
// we should _NOT_ have a mapping of our region
assert(!regions[0].is_mapped());
// first, decide how much data we're going to produce
unsigned short xsubi[3];
xsubi[0] = args.random_seed >> 16;
xsubi[1] = args.random_seed;
xsubi[2] = subregion_index;
coord_t output_size = nrand48(xsubi) % (2 * args.average_output_size + 1);
log_app.print() << "make data: subregion " << subregion_index << ", output size = " << output_size;
// now we can define a (sub-)subregion of our subregion that is the right size
// to hold the output
LogicalRegion my_lr = regions[0].get_logical_region();
IndexSpace my_is = my_lr.get_index_space();
Rect<1> my_bounds = runtime->get_index_space_domain(my_is).get_rect<1>();
coord_t bounds_lo = my_bounds.lo[0];
// remember rectangle bounds are inclusive on both sides
Rect<1> alloc_bounds(my_bounds.lo, bounds_lo + output_size - 1);
// create a new partition with a known part_color so that other tasks can find
// the color space will consist of the single color '0'
DomainColoring dc;
Domain color_space = Domain::from_rect<1>(Rect<1>(0, 0));
dc[0] = Domain::from_rect<1>(alloc_bounds);
IndexPartition alloc_ip = runtime->create_index_partition(ctx,
my_is,
color_space,
dc,
DISJOINT_KIND, // trivial
PID_ALLOCED_DATA);
// now we get the name of the logical subregion we just created and inline map
// it to generate our output
LogicalPartition alloc_lp = runtime->get_logical_partition(my_lr, alloc_ip);
IndexSpace alloc_is = runtime->get_index_subspace(alloc_ip, DomainPoint::from_point<1>(0));
LogicalRegion alloc_lr = runtime->get_logical_subregion(alloc_lp, alloc_is);
log_app.debug() << "created subregion " << alloc_lr;
// tell the default mapper that we want exactly this region to be mapped
// otherwise, its heuristics may cause it to try to map the (huge) parent
InlineLauncher launcher(RegionRequirement(alloc_lr,
READ_WRITE,
EXCLUSIVE,
my_lr,
DefaultMapper::EXACT_REGION)
.add_field(FID_DATA));
PhysicalRegion pr = runtime->map_region(ctx, launcher);
// this would be done as part of asking for an accessor, but do it explicitly for
// didactic purposes - while inline mappings can often be expensive due to stalls or
// data movement, this should be fast because we are just allocating new space
pr.wait_until_valid();
{
RegionAccessor<AccessorType::Generic, int> ra = pr.get_field_accessor(FID_DATA).typeify<int>();
for(coord_t i = 0; i < output_size; i++)
ra.write(DomainPoint::from_point<1>(bounds_lo + i),
(subregion_index * 10000) + i);
}
// release our inline mapping
runtime->unmap_region(ctx, pr);
// no need to explicitly return the name of the subregion we created - it can be foud
// by walking the region tree using known colors
}
void use_data_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
int subregion_index = task->index_point.get_point<1>();
PhysicalRegion pr = regions[0];
Rect<1> my_bounds;
bool was_virtual_mapped = !regions[0].is_mapped();
if(was_virtual_mapped) {
// find the actual subregion containing our input data by walking the
// region tree
LogicalRegion my_lr = regions[0].get_logical_region();
IndexSpace my_is = my_lr.get_index_space();
IndexPartition alloc_ip = runtime->get_index_partition(my_is, PID_ALLOCED_DATA);
// getting from the index partition to the logical subregion is identical to
// what was done in make_data_task()
LogicalPartition alloc_lp = runtime->get_logical_partition(my_lr, alloc_ip);
IndexSpace alloc_is = runtime->get_index_subspace(alloc_ip, DomainPoint::from_point<1>(0));
LogicalRegion alloc_lr = runtime->get_logical_subregion(alloc_lp, alloc_is);
log_app.debug() << "looked up subregion " << alloc_lr;
// learn the input size from the bounds of the allocated subspace
my_bounds = runtime->get_index_space_domain(alloc_is).get_rect<1>();
// again, tell the default mapper that we want exactly this region to be mapped
// this is important if the mapper sends us to a different place than where the
// data was produced and a copy is needed
InlineLauncher launcher(RegionRequirement(alloc_lr,
READ_ONLY,
EXCLUSIVE,
my_lr,
DefaultMapper::EXACT_REGION)
.add_field(FID_DATA));
pr = runtime->map_region(ctx, launcher);
} else {
// we've got the exact region mapped for us, so ask for its size
LogicalRegion my_lr = regions[0].get_logical_region();
IndexSpace my_is = my_lr.get_index_space();
my_bounds = runtime->get_index_space_domain(my_is).get_rect<1>();
}
coord_t bounds_lo = my_bounds.lo[0];
coord_t input_size = my_bounds.volume();
log_app.print() << "use data: subregion " << subregion_index << ", input size = " << input_size
<< (was_virtual_mapped ? " (virtual mapped)" : " (NOT virtual mapped)");
// check that the data is what we expect
int errors = 0;
{
RegionAccessor<AccessorType::Generic, int> ra = pr.get_field_accessor(FID_DATA).typeify<int>();
for(coord_t i = 0; i < input_size; i++) {
int exp = (subregion_index * 10000) + i;
int act = ra.read(DomainPoint::from_point<1>(bounds_lo + i));
if(exp != act) {
// don't print more than 10 errors
if(errors < 10)
log_app.error() << "mismatch in subregion " << subregion_index << ": ["
<< (bounds_lo + i) << "] = " << act << " (expected " << exp << ")";
errors++;
}
}
}
// unmap any inline mapping we did
if(was_virtual_mapped)
runtime->unmap_region(ctx, pr);
//return errors;
}
class UseDataProjectionFunctor : public ProjectionFunctor {
public:
UseDataProjectionFunctor(void);
virtual LogicalRegion project(Context ctx, Task *task,
unsigned index,
LogicalRegion upper_bound,
const DomainPoint &point);
virtual LogicalRegion project(Context ctx, Task *task,
unsigned index,
LogicalPartition upper_bound,
const DomainPoint &point);
};
UseDataProjectionFunctor::UseDataProjectionFunctor(void) {}
// region -> region: UNUSED
LogicalRegion UseDataProjectionFunctor::project(Context ctx, Task *task,
unsigned index,
LogicalRegion upper_bound,
const DomainPoint &point)
{
assert(0);
return LogicalRegion::NO_REGION;
}
// partition -> region path: [index].PID_ALLOCED_DATA.0
LogicalRegion UseDataProjectionFunctor::project(Context ctx, Task *task,
unsigned index,
LogicalPartition upper_bound,
const DomainPoint &point)
{
// if our application did more than one index launch using this projection functor,
// we could consider memoizing the result of this lookup to reduce overhead on subsequent
// launches
LogicalRegion lr1 = runtime->get_logical_subregion_by_color(ctx, upper_bound, point);
LogicalPartition lp1 = runtime->get_logical_partition_by_color(ctx, lr1, PID_ALLOCED_DATA);
LogicalRegion lr2 = runtime->get_logical_subregion_by_color(ctx, lp1, 0);
return lr2;
}
int main(int argc, char **argv)
{
// Register our task variants
{
TaskVariantRegistrar top_level_registrar(TOP_LEVEL_TASK_ID);
top_level_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<top_level_task>(top_level_registrar,
"Top Level Task");
Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
}
{
TaskVariantRegistrar make_data_registrar(MAKE_DATA_TASK_ID);
make_data_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<make_data_task>(make_data_registrar,
"Make Data Task");
}
{
TaskVariantRegistrar use_data_registrar(USE_DATA_TASK_ID);
use_data_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<use_data_task>(use_data_registrar,
"Use Data Task");
}
Runtime::preregister_projection_functor(PFID_USE_DATA_TASK,
new UseDataProjectionFunctor);
// Fire up the runtime
return Runtime::start(argc, argv);
}
<commit_msg>virtual_map: add now-necessary get_depth method to projection functor<commit_after>/* Copyright 2016 Stanford University, NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This example demonstrates way in which virtual mapping can be useful -
// generating variable-sized output from a task
#include <legion.h>
#include <realm/cmdline.h>
#include <mappers/default_mapper.h>
using namespace Legion;
using namespace Legion::Mapping;
using namespace LegionRuntime::Accessor;
enum TaskID
{
TOP_LEVEL_TASK_ID,
MAKE_DATA_TASK_ID,
USE_DATA_TASK_ID,
};
enum {
FID_DATA = 55,
};
enum {
PID_ALLOCED_DATA = 4,
};
enum {
PFID_USE_DATA_TASK = 77,
};
LegionRuntime::Logger::Category log_app("app");
struct MakeDataTaskArgs {
int random_seed;
size_t average_output_size;
};
void top_level_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
size_t num_subregions = 4;
size_t average_output_size = 100;
size_t total_region_size = 1 << 30;
int random_seed = 12345;
bool use_projection_functor = false;
const InputArgs &command_args = HighLevelRuntime::get_input_args();
bool ok = Realm::CommandLineParser()
.add_option_int("-n", num_subregions)
.add_option_int("-s", average_output_size)
.add_option_int("-l", total_region_size)
.add_option_int("-seed", random_seed)
.add_option_bool("-proj", use_projection_functor)
.parse_command_line(command_args.argc, (const char **)command_args.argv);
if(!ok) {
log_app.fatal() << "error parsing command line arguments";
exit(1);
}
// create a top-level region that is (easily) large enough to hold all of our
// data - we need not worry about a tight bound, because we will never create
// any instances of this size
Rect<1> bounds(0, total_region_size - 1);
IndexSpace is = runtime->create_index_space(ctx, Domain::from_rect<1>(bounds));
runtime->attach_name(is, "is");
// our field space will just have a single field
FieldSpace fs = runtime->create_field_space(ctx);
runtime->attach_name(fs, "fs");
{
FieldAllocator fsa = runtime->create_field_allocator(ctx, fs);
fsa.allocate_field(sizeof(int), FID_DATA);
runtime->attach_name(fs, FID_DATA, "data");
}
LogicalRegion lr = runtime->create_logical_region(ctx, is, fs);
runtime->attach_name(lr, "lr");
// partition it into equal pieces - again, these are expected to be much
// larger than the actual output of the generator tasks
Rect<1> subregion_idxs(0, num_subregions - 1);
size_t elements_per_subregion = total_region_size / num_subregions;
assert(elements_per_subregion >= (2 * average_output_size));
Blockify<1> blockify(elements_per_subregion);
IndexPartition ip = runtime->create_index_partition(ctx, is, blockify);
LogicalPartition lp = runtime->get_logical_partition(ctx, lr, ip);
// perform an index launch to have each subregion filled in with a variable
// amount of data
{
MakeDataTaskArgs args;
args.random_seed = random_seed;
args.average_output_size = average_output_size;
IndexLauncher launcher(MAKE_DATA_TASK_ID, Domain::from_rect<1>(subregion_idxs),
TaskArgument(&args, sizeof(args)),
ArgumentMap());
launcher.add_region_requirement(RegionRequirement(lp,
0, // identity projection
READ_WRITE,
EXCLUSIVE,
lr,
DefaultMapper::VIRTUAL_MAP)
.add_field(FID_DATA));
FutureMap fm = runtime->execute_index_space(ctx, launcher);
fm.wait_all_results();
}
// now perform a second index launch to use the variable-sized chunks of
// data
{
IndexLauncher launcher(USE_DATA_TASK_ID, Domain::from_rect<1>(subregion_idxs),
TaskArgument(0, 0),
ArgumentMap());
if(use_projection_functor) {
// use a projection functor to tell the runtime precisely which sub-subregion
// each point task will use so that it can be mapped before the task executes -
// make sure the default mapper doesn't try to map the parent region though
launcher.add_region_requirement(RegionRequirement(lp,
PFID_USE_DATA_TASK,
READ_ONLY,
EXCLUSIVE,
lr,
DefaultMapper::EXACT_REGION)
.add_field(FID_DATA));
} else {
// OR, use another virtual mapping and let the use_data_task walk the region
// tree itself and do an inline mapping within the task
launcher.add_region_requirement(RegionRequirement(lp,
0, // identity projection
READ_ONLY,
EXCLUSIVE,
lr,
DefaultMapper::VIRTUAL_MAP)
.add_field(FID_DATA));
}
FutureMap fm = runtime->execute_index_space(ctx, launcher);
fm.wait_all_results();
}
}
void make_data_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
const MakeDataTaskArgs& args = *static_cast<const MakeDataTaskArgs *>(task->args);
int subregion_index = task->index_point.get_point<1>();
// we should _NOT_ have a mapping of our region
assert(!regions[0].is_mapped());
// first, decide how much data we're going to produce
unsigned short xsubi[3];
xsubi[0] = args.random_seed >> 16;
xsubi[1] = args.random_seed;
xsubi[2] = subregion_index;
coord_t output_size = nrand48(xsubi) % (2 * args.average_output_size + 1);
log_app.print() << "make data: subregion " << subregion_index << ", output size = " << output_size;
// now we can define a (sub-)subregion of our subregion that is the right size
// to hold the output
LogicalRegion my_lr = regions[0].get_logical_region();
IndexSpace my_is = my_lr.get_index_space();
Rect<1> my_bounds = runtime->get_index_space_domain(my_is).get_rect<1>();
coord_t bounds_lo = my_bounds.lo[0];
// remember rectangle bounds are inclusive on both sides
Rect<1> alloc_bounds(my_bounds.lo, bounds_lo + output_size - 1);
// create a new partition with a known part_color so that other tasks can find
// the color space will consist of the single color '0'
DomainColoring dc;
Domain color_space = Domain::from_rect<1>(Rect<1>(0, 0));
dc[0] = Domain::from_rect<1>(alloc_bounds);
IndexPartition alloc_ip = runtime->create_index_partition(ctx,
my_is,
color_space,
dc,
DISJOINT_KIND, // trivial
PID_ALLOCED_DATA);
// now we get the name of the logical subregion we just created and inline map
// it to generate our output
LogicalPartition alloc_lp = runtime->get_logical_partition(my_lr, alloc_ip);
IndexSpace alloc_is = runtime->get_index_subspace(alloc_ip, DomainPoint::from_point<1>(0));
LogicalRegion alloc_lr = runtime->get_logical_subregion(alloc_lp, alloc_is);
log_app.debug() << "created subregion " << alloc_lr;
// tell the default mapper that we want exactly this region to be mapped
// otherwise, its heuristics may cause it to try to map the (huge) parent
InlineLauncher launcher(RegionRequirement(alloc_lr,
READ_WRITE,
EXCLUSIVE,
my_lr,
DefaultMapper::EXACT_REGION)
.add_field(FID_DATA));
PhysicalRegion pr = runtime->map_region(ctx, launcher);
// this would be done as part of asking for an accessor, but do it explicitly for
// didactic purposes - while inline mappings can often be expensive due to stalls or
// data movement, this should be fast because we are just allocating new space
pr.wait_until_valid();
{
RegionAccessor<AccessorType::Generic, int> ra = pr.get_field_accessor(FID_DATA).typeify<int>();
for(coord_t i = 0; i < output_size; i++)
ra.write(DomainPoint::from_point<1>(bounds_lo + i),
(subregion_index * 10000) + i);
}
// release our inline mapping
runtime->unmap_region(ctx, pr);
// no need to explicitly return the name of the subregion we created - it can be foud
// by walking the region tree using known colors
}
void use_data_task(const Task *task,
const std::vector<PhysicalRegion> ®ions,
Context ctx, Runtime *runtime)
{
int subregion_index = task->index_point.get_point<1>();
PhysicalRegion pr = regions[0];
Rect<1> my_bounds;
bool was_virtual_mapped = !regions[0].is_mapped();
if(was_virtual_mapped) {
// find the actual subregion containing our input data by walking the
// region tree
LogicalRegion my_lr = regions[0].get_logical_region();
IndexSpace my_is = my_lr.get_index_space();
IndexPartition alloc_ip = runtime->get_index_partition(my_is, PID_ALLOCED_DATA);
// getting from the index partition to the logical subregion is identical to
// what was done in make_data_task()
LogicalPartition alloc_lp = runtime->get_logical_partition(my_lr, alloc_ip);
IndexSpace alloc_is = runtime->get_index_subspace(alloc_ip, DomainPoint::from_point<1>(0));
LogicalRegion alloc_lr = runtime->get_logical_subregion(alloc_lp, alloc_is);
log_app.debug() << "looked up subregion " << alloc_lr;
// learn the input size from the bounds of the allocated subspace
my_bounds = runtime->get_index_space_domain(alloc_is).get_rect<1>();
// again, tell the default mapper that we want exactly this region to be mapped
// this is important if the mapper sends us to a different place than where the
// data was produced and a copy is needed
InlineLauncher launcher(RegionRequirement(alloc_lr,
READ_ONLY,
EXCLUSIVE,
my_lr,
DefaultMapper::EXACT_REGION)
.add_field(FID_DATA));
pr = runtime->map_region(ctx, launcher);
} else {
// we've got the exact region mapped for us, so ask for its size
LogicalRegion my_lr = regions[0].get_logical_region();
IndexSpace my_is = my_lr.get_index_space();
my_bounds = runtime->get_index_space_domain(my_is).get_rect<1>();
}
coord_t bounds_lo = my_bounds.lo[0];
coord_t input_size = my_bounds.volume();
log_app.print() << "use data: subregion " << subregion_index << ", input size = " << input_size
<< (was_virtual_mapped ? " (virtual mapped)" : " (NOT virtual mapped)");
// check that the data is what we expect
int errors = 0;
{
RegionAccessor<AccessorType::Generic, int> ra = pr.get_field_accessor(FID_DATA).typeify<int>();
for(coord_t i = 0; i < input_size; i++) {
int exp = (subregion_index * 10000) + i;
int act = ra.read(DomainPoint::from_point<1>(bounds_lo + i));
if(exp != act) {
// don't print more than 10 errors
if(errors < 10)
log_app.error() << "mismatch in subregion " << subregion_index << ": ["
<< (bounds_lo + i) << "] = " << act << " (expected " << exp << ")";
errors++;
}
}
}
// unmap any inline mapping we did
if(was_virtual_mapped)
runtime->unmap_region(ctx, pr);
//return errors;
}
class UseDataProjectionFunctor : public ProjectionFunctor {
public:
UseDataProjectionFunctor(void);
virtual LogicalRegion project(Context ctx, Task *task,
unsigned index,
LogicalRegion upper_bound,
const DomainPoint &point);
virtual LogicalRegion project(Context ctx, Task *task,
unsigned index,
LogicalPartition upper_bound,
const DomainPoint &point);
virtual unsigned get_depth(void) const;
};
UseDataProjectionFunctor::UseDataProjectionFunctor(void) {}
// region -> region: UNUSED
LogicalRegion UseDataProjectionFunctor::project(Context ctx, Task *task,
unsigned index,
LogicalRegion upper_bound,
const DomainPoint &point)
{
assert(0);
return LogicalRegion::NO_REGION;
}
// partition -> region path: [index].PID_ALLOCED_DATA.0
LogicalRegion UseDataProjectionFunctor::project(Context ctx, Task *task,
unsigned index,
LogicalPartition upper_bound,
const DomainPoint &point)
{
// if our application did more than one index launch using this projection functor,
// we could consider memoizing the result of this lookup to reduce overhead on subsequent
// launches
LogicalRegion lr1 = runtime->get_logical_subregion_by_color(ctx, upper_bound, point);
LogicalPartition lp1 = runtime->get_logical_partition_by_color(ctx, lr1, PID_ALLOCED_DATA);
LogicalRegion lr2 = runtime->get_logical_subregion_by_color(ctx, lp1, 0);
return lr2;
}
unsigned UseDataProjectionFunctor::get_depth(void) const
{
return 1;
}
int main(int argc, char **argv)
{
// Register our task variants
{
TaskVariantRegistrar top_level_registrar(TOP_LEVEL_TASK_ID);
top_level_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<top_level_task>(top_level_registrar,
"Top Level Task");
Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID);
}
{
TaskVariantRegistrar make_data_registrar(MAKE_DATA_TASK_ID);
make_data_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<make_data_task>(make_data_registrar,
"Make Data Task");
}
{
TaskVariantRegistrar use_data_registrar(USE_DATA_TASK_ID);
use_data_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC));
Runtime::preregister_task_variant<use_data_task>(use_data_registrar,
"Use Data Task");
}
Runtime::preregister_projection_functor(PFID_USE_DATA_TASK,
new UseDataProjectionFunctor);
// Fire up the runtime
return Runtime::start(argc, argv);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_DOFTRANSFORM
#define MFEM_DOFTRANSFORM
#include "../config/config.hpp"
#include "../linalg/linalg.hpp"
#include "intrules.hpp"
#include "fe.hpp"
namespace mfem
{
/** The DofTransformation class is an abstract base class for a family of
transformations that map local degrees of freedom (DoFs), contained within
individual elements, to global degrees of freedom, stored within
GridFunction objects. These transformations are necessary to ensure that
basis functions in neighboring elements align correctly. Closely related but
complementary transformations are required for the entries stored in
LinearForm and BilinearForm objects. The DofTransformation class is designed
to apply the action of both of these types of DoF transformations.
Let the "primal transformation" be given by the operator T. This means that
given a local element vector v the data that must be placed into a
GridFunction object is v_t = T * v.
We also need the inverse of the primal transformation T^{-1} so that we can
recover the local element vector from data read out of a GridFunction
e.g. v = T^{-1} * v_t.
We need to preserve the action of our linear forms applied to primal
vectors. In other words, if f is the local vector computed by a linear
form then f * v = f_t * v_t (where "*" represents an inner product of
vectors). This requires that f_t = T^{-T} * f i.e. the "dual transform" is
given by the transpose of the inverse of the primal transformation.
For bilinear forms we require that v^T * A * v = v_t^T * A_t * v_t. This
implies that A_t = T^{-T} * A * T^{-1}. This can be accomplished by
performing dual transformations of the rows and columns of the matrix A.
For discrete linear operators the range must be modified with the primal
transformation rather than the dual transformation because the result is a
primal vector rather than a dual vector. This leads to the transformation
D_t = T * D * T^{-1}. This can be accomplished by using a primal
transformation on the columns of D and a dual transformation on its rows.
*/
class DofTransformation
{
protected:
int size_;
Array<int> Fo;
DofTransformation(int size)
: size_(size) {}
public:
inline int Size() const { return size_; }
inline int Height() const { return size_; }
inline int NumRows() const { return size_; }
inline int Width() const { return size_; }
inline int NumCols() const { return size_; }
/** @brief Configure the transformation using face orientations for the
current element. */
/// The face_orientation array can be obtained from Mesh::GetElementFaces.
inline void SetFaceOrientations(const Array<int> & face_orientation)
{ Fo = face_orientation; }
inline const Array<int> & GetFaceOrientations() const { return Fo; }
/** Transform local DoFs to align with the global DoFs. For example, this
transformation can be used to map the local vector computed by
FiniteElement::Project() to the transformed vector stored within a
GridFunction object. */
virtual void TransformPrimal(double *v) const = 0;
virtual void TransformPrimal(Vector &v) const;
/// Transform groups of DoFs stored as dense matrices
virtual void TransformPrimalCols(DenseMatrix &V) const;
/** Inverse transform local DoFs. Used to transform DoFs from a global vector
back to their element-local form. For example, this must be used to
transform the vector obtained using GridFunction::GetSubVector before it
can be used to compute a local interpolation.
*/
virtual void InvTransformPrimal(double *v) const = 0;
virtual void InvTransformPrimal(Vector &v) const;
/** Transform dual DoFs as computed by a LinearFormIntegrator before summing
into a LinearForm object. */
virtual void TransformDual(double *v) const = 0;
virtual void TransformDual(Vector &v) const;
/** Transform a matrix of dual DoFs entries as computed by a
BilinearFormIntegrator before summing into a BilinearForm object. */
virtual void TransformDual(DenseMatrix &V) const;
/// Transform groups of dual DoFs stored as dense matrices
virtual void TransformDualRows(DenseMatrix &V) const;
virtual void TransformDualCols(DenseMatrix &V) const;
virtual ~DofTransformation() {}
};
/** Transform a matrix of DoFs entries from different finite element spaces as
computed by a DiscreteInterpolator before copying into a
DiscreteLinearOperator.
*/
void TransformPrimal(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
DenseMatrix &elmat);
/** Transform a matrix of dual DoFs entries from different finite element spaces
as computed by a BilinearFormIntegrator before summing into a
MixedBilinearForm object.
*/
void TransformDual(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
DenseMatrix &elmat);
/** The VDofTransformation class implements a nested transformation where an
arbitrary DofTransformation is replicated with a vdim >= 1.
*/
class VDofTransformation : public DofTransformation
{
private:
int vdim_;
int ordering_;
DofTransformation * doftrans_;
public:
/** @brief Default constructor which requires that SetDofTransformation be
called before use. */
VDofTransformation(int vdim = 1, int ordering = 0)
: DofTransformation(0),
vdim_(vdim), ordering_(ordering),
doftrans_(NULL) {}
/// Constructor with a known DofTransformation
VDofTransformation(DofTransformation & doftrans, int vdim = 1,
int ordering = 0)
: DofTransformation(vdim * doftrans.Size()),
vdim_(vdim), ordering_(ordering),
doftrans_(&doftrans) {}
/// Set or change the vdim parameter
inline void SetVDim(int vdim)
{
vdim_ = vdim;
if (doftrans_)
{
size_ = vdim_ * doftrans_->Size();
}
}
/// Return the current vdim value
inline int GetVDim() const { return vdim_; }
/// Set or change the nested DofTransformation object
inline void SetDofTransformation(DofTransformation & doftrans)
{
size_ = vdim_ * doftrans.Size();
doftrans_ = &doftrans;
}
/// Return the nested DofTransformation object
inline DofTransformation * GetDofTransformation() const { return doftrans_; }
inline void SetFaceOrientation(const Array<int> & face_orientation)
{ Fo = face_orientation; doftrans_->SetFaceOrientations(face_orientation); }
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
/** Abstract base class for high-order Nedelec spaces on elements with
triangular faces.
The Nedelec DoFs on the interior of triangular faces come in pairs which
share an interpolation point but have different vector directions. These
directions depend on the orientation of the face and can therefore differ in
neighboring elements. The mapping required to transform these DoFs can be
implemented as series of 2x2 linear transformations. The raw data for these
linear transformations is stored in the T_data and TInv_data arrays and can
be accessed as DenseMatrices using the GetFaceTransform() and
GetFaceInverseTransform() methods.
*/
class ND_DofTransformation : public DofTransformation
{
protected:
static const double T_data[24];
static const double TInv_data[24];
static const DenseTensor T, TInv;
int order;
ND_DofTransformation(int size, int order);
public:
// Return the 2x2 transformation operator for the given face orientation
static const DenseMatrix & GetFaceTransform(int ori) { return T(ori); }
// Return the 2x2 inverse transformation operator
static const DenseMatrix & GetFaceInverseTransform(int ori)
{ return TInv(ori); }
};
/// DoF transformation implementation for the Nedelec basis on triangles
class ND_TriDofTransformation : public ND_DofTransformation
{
public:
ND_TriDofTransformation(int order);
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
/// DoF transformation implementation for the Nedelec basis on tetrahedra
class ND_TetDofTransformation : public ND_DofTransformation
{
public:
ND_TetDofTransformation(int order);
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
/// DoF transformation implementation for the Nedelec basis on wedge elements
/** TODO: Implementation in the nd-prism-dev branch */
class ND_WedgeDofTransformation : public ND_DofTransformation
{
public:
ND_WedgeDofTransformation(int order);
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
} // namespace mfem
#endif // MFEM_DOFTRANSFORM
<commit_msg>Adjusting comment<commit_after>// Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#ifndef MFEM_DOFTRANSFORM
#define MFEM_DOFTRANSFORM
#include "../config/config.hpp"
#include "../linalg/linalg.hpp"
#include "intrules.hpp"
#include "fe.hpp"
namespace mfem
{
/** The DofTransformation class is an abstract base class for a family of
transformations that map local degrees of freedom (DoFs), contained within
individual elements, to global degrees of freedom, stored within
GridFunction objects. These transformations are necessary to ensure that
basis functions in neighboring elements align correctly. Closely related but
complementary transformations are required for the entries stored in
LinearForm and BilinearForm objects. The DofTransformation class is designed
to apply the action of both of these types of DoF transformations.
Let the "primal transformation" be given by the operator T. This means that
given a local element vector v the data that must be placed into a
GridFunction object is v_t = T * v.
We also need the inverse of the primal transformation T^{-1} so that we can
recover the local element vector from data read out of a GridFunction
e.g. v = T^{-1} * v_t.
We need to preserve the action of our linear forms applied to primal
vectors. In other words, if f is the local vector computed by a linear
form then f * v = f_t * v_t (where "*" represents an inner product of
vectors). This requires that f_t = T^{-T} * f i.e. the "dual transform" is
given by the transpose of the inverse of the primal transformation.
For bilinear forms we require that v^T * A * v = v_t^T * A_t * v_t. This
implies that A_t = T^{-T} * A * T^{-1}. This can be accomplished by
performing dual transformations of the rows and columns of the matrix A.
For discrete linear operators the range must be modified with the primal
transformation rather than the dual transformation because the result is a
primal vector rather than a dual vector. This leads to the transformation
D_t = T * D * T^{-1}. This can be accomplished by using a primal
transformation on the columns of D and a dual transformation on its rows.
*/
class DofTransformation
{
protected:
int size_;
Array<int> Fo;
DofTransformation(int size)
: size_(size) {}
public:
inline int Size() const { return size_; }
inline int Height() const { return size_; }
inline int NumRows() const { return size_; }
inline int Width() const { return size_; }
inline int NumCols() const { return size_; }
/** @brief Configure the transformation using face orientations for the
current element. */
/// The face_orientation array can be obtained from Mesh::GetElementFaces.
inline void SetFaceOrientations(const Array<int> & face_orientation)
{ Fo = face_orientation; }
inline const Array<int> & GetFaceOrientations() const { return Fo; }
/** Transform local DoFs to align with the global DoFs. For example, this
transformation can be used to map the local vector computed by
FiniteElement::Project() to the transformed vector stored within a
GridFunction object. */
virtual void TransformPrimal(double *v) const = 0;
virtual void TransformPrimal(Vector &v) const;
/// Transform groups of DoFs stored as dense matrices
virtual void TransformPrimalCols(DenseMatrix &V) const;
/** Inverse transform local DoFs. Used to transform DoFs from a global vector
back to their element-local form. For example, this must be used to
transform the vector obtained using GridFunction::GetSubVector before it
can be used to compute a local interpolation.
*/
virtual void InvTransformPrimal(double *v) const = 0;
virtual void InvTransformPrimal(Vector &v) const;
/** Transform dual DoFs as computed by a LinearFormIntegrator before summing
into a LinearForm object. */
virtual void TransformDual(double *v) const = 0;
virtual void TransformDual(Vector &v) const;
/** Transform a matrix of dual DoFs entries as computed by a
BilinearFormIntegrator before summing into a BilinearForm object. */
virtual void TransformDual(DenseMatrix &V) const;
/// Transform groups of dual DoFs stored as dense matrices
virtual void TransformDualRows(DenseMatrix &V) const;
virtual void TransformDualCols(DenseMatrix &V) const;
virtual ~DofTransformation() {}
};
/** Transform a matrix of DoFs entries from different finite element spaces as
computed by a DiscreteInterpolator before copying into a
DiscreteLinearOperator.
*/
void TransformPrimal(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
DenseMatrix &elmat);
/** Transform a matrix of dual DoFs entries from different finite element spaces
as computed by a BilinearFormIntegrator before summing into a
MixedBilinearForm object.
*/
void TransformDual(const DofTransformation *ran_dof_trans,
const DofTransformation *dom_dof_trans,
DenseMatrix &elmat);
/** The VDofTransformation class implements a nested transformation where an
arbitrary DofTransformation is replicated with a vdim >= 1.
*/
class VDofTransformation : public DofTransformation
{
private:
int vdim_;
int ordering_;
DofTransformation * doftrans_;
public:
/** @brief Default constructor which requires that SetDofTransformation be
called before use. */
VDofTransformation(int vdim = 1, int ordering = 0)
: DofTransformation(0),
vdim_(vdim), ordering_(ordering),
doftrans_(NULL) {}
/// Constructor with a known DofTransformation
VDofTransformation(DofTransformation & doftrans, int vdim = 1,
int ordering = 0)
: DofTransformation(vdim * doftrans.Size()),
vdim_(vdim), ordering_(ordering),
doftrans_(&doftrans) {}
/// Set or change the vdim parameter
inline void SetVDim(int vdim)
{
vdim_ = vdim;
if (doftrans_)
{
size_ = vdim_ * doftrans_->Size();
}
}
/// Return the current vdim value
inline int GetVDim() const { return vdim_; }
/// Set or change the nested DofTransformation object
inline void SetDofTransformation(DofTransformation & doftrans)
{
size_ = vdim_ * doftrans.Size();
doftrans_ = &doftrans;
}
/// Return the nested DofTransformation object
inline DofTransformation * GetDofTransformation() const { return doftrans_; }
inline void SetFaceOrientation(const Array<int> & face_orientation)
{ Fo = face_orientation; doftrans_->SetFaceOrientations(face_orientation); }
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
/** Abstract base class for high-order Nedelec spaces on elements with
triangular faces.
The Nedelec DoFs on the interior of triangular faces come in pairs which
share an interpolation point but have different vector directions. These
directions depend on the orientation of the face and can therefore differ in
neighboring elements. The mapping required to transform these DoFs can be
implemented as series of 2x2 linear transformations. The raw data for these
linear transformations is stored in the T_data and TInv_data arrays and can
be accessed as DenseMatrices using the GetFaceTransform() and
GetFaceInverseTransform() methods.
*/
class ND_DofTransformation : public DofTransformation
{
protected:
static const double T_data[24];
static const double TInv_data[24];
static const DenseTensor T, TInv;
int order;
ND_DofTransformation(int size, int order);
public:
// Return the 2x2 transformation operator for the given face orientation
static const DenseMatrix & GetFaceTransform(int ori) { return T(ori); }
// Return the 2x2 inverse transformation operator
static const DenseMatrix & GetFaceInverseTransform(int ori)
{ return TInv(ori); }
};
/// DoF transformation implementation for the Nedelec basis on triangles
class ND_TriDofTransformation : public ND_DofTransformation
{
public:
ND_TriDofTransformation(int order);
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
/// DoF transformation implementation for the Nedelec basis on tetrahedra
class ND_TetDofTransformation : public ND_DofTransformation
{
public:
ND_TetDofTransformation(int order);
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
/// DoF transformation implementation for the Nedelec basis on wedge elements
/** TODO: (Under development) */
class ND_WedgeDofTransformation : public ND_DofTransformation
{
public:
ND_WedgeDofTransformation(int order);
using DofTransformation::TransformPrimal;
using DofTransformation::InvTransformPrimal;
using DofTransformation::TransformDual;
void TransformPrimal(double *v) const;
void InvTransformPrimal(double *v) const;
void TransformDual(double *v) const;
};
} // namespace mfem
#endif // MFEM_DOFTRANSFORM
<|endoftext|>
|
<commit_before>#include <cstring>
#include <fstream>
#include <list>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include "global.h"
#include "judge.h"
#include "scoreboard.h"
#include "rejudger.h"
#include "webserver.h"
using namespace std;
static pthread_mutex_t localtime_mutex = PTHREAD_MUTEX_INITIALIZER;
Settings::Settings() {
memset(this, 0, sizeof(::Settings));
fstream f("settings.txt");
if (!f.is_open()) return;
string tmp;
auto func = [&](time_t& buf) {
int Y, M, D, h, m;
f >> tmp >> Y >> M >> D >> h >> m;
time(&buf);
pthread_mutex_lock(&localtime_mutex);
tm* tinfo = localtime(&buf);
tm ti = *tinfo;
pthread_mutex_unlock(&localtime_mutex);
ti.tm_year = Y - 1900;
ti.tm_mon = M - 1;
ti.tm_mday = D;
ti.tm_hour = h;
ti.tm_min = m;
ti.tm_sec = 0;
buf = mktime(&ti);
};
func(begin);
func(end);
func(freeze);
func(noverdict);
int problems;
f >> tmp >> problems;
this->problems = vector<int>(problems);
for (int i = 0; i < problems; i++) {
f >> tmp >> this->problems[i];
}
}
rejudgemsg::rejudgemsg(int id, char verdict)
: mtype(1), id(id), verdict(verdict) {}
size_t rejudgemsg::size() const { return sizeof(rejudgemsg)-sizeof(long); }
static __suseconds_t dt(const timeval& start) {
timeval end;
gettimeofday(&end, nullptr);
return
(end.tv_sec*1000000 + end.tv_usec)-
(start.tv_sec*1000000 + start.tv_usec)
;
}
int timeout(bool& tle, int s, const char* cmd) {
tle = false;
__suseconds_t us = s*1000000;
timeval start;
gettimeofday(&start, nullptr);
pid_t proc = fork();
if (!proc) {
setpgid(0, 0); // create new process group rooted at proc
int status = system(cmd);
exit(WEXITSTATUS(status));
}
int status;
while (waitpid(proc, &status, WNOHANG) != proc) {
if (dt(start) > us) {
tle = true;
kill(-proc, SIGKILL); //the minus kills the whole group rooted at proc
waitpid(proc, &status, 0);
break;
}
usleep(10000);
}
return status;
}
void ignoresd(int sd) {
char* buf = new char[1 << 10];
while (read(sd, buf, 1 << 10) == (1 << 10));
delete[] buf;
}
template <>
string to<string, in_addr_t>(const in_addr_t& x) {
char* ptr = (char*)&x;
string ret = to<string>(int(ptr[0])&0x0ff);
for (int i = 1; i < 4; i++) ret += ("."+to<string>(int(ptr[i])&0x0ff));
return ret;
}
struct Contest {
pid_t pid;
key_t key;
Contest(pid_t pid, key_t key) : pid(pid), key(key) {
FILE* fp = fopen("contest.bin", "wb");
fwrite(this, sizeof(Contest), 1, fp);
fclose(fp);
}
Contest() : pid(0), key(0) {
FILE* fp = fopen("contest.bin", "rb");
if (!fp) return;
fread(this, sizeof(Contest), 1, fp);
fclose(fp);
}
};
static bool quit = false;
static list<pthread_t> threads;
static pthread_mutex_t attfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t nextidfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t questionfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static int msqid;
static key_t msgqueue() {
key_t key = 0x713e24a;
while ((msqid = msgget(key, (IPC_CREAT|IPC_EXCL)|0777)) < 0) key++;
return key;
}
static void term(int) {
msgctl(msqid, IPC_RMID, nullptr);
remove("contest.bin");
pthread_mutex_lock(&attfile_mutex);
pthread_mutex_lock(&nextidfile_mutex);
pthread_mutex_lock(&questionfile_mutex);
quit = true;
pthread_mutex_unlock(&questionfile_mutex);
pthread_mutex_unlock(&nextidfile_mutex);
pthread_mutex_unlock(&attfile_mutex);
for (pthread_t& thread : threads) pthread_join(thread, nullptr);
exit(0);
}
namespace Global {
vector<string> arg;
void install(const string& dir) {
mkdir(dir.c_str(), 0777);
FILE* fp = fopen((dir+"/settings.txt").c_str(), "w");
fprintf(fp,
"Begin: 2015 09 01 19 00\n"
"End: 2015 12 25 23 50\n"
"Freeze: 2015 12 25 23 50\n"
"No-verdict: 2015 12 25 23 50\n"
"Problems: 1\n"
"A-timelimit: 1\n"
);
fclose(fp);
fp = fopen((dir+"/teams.txt").c_str(), "w");
fprintf(fp, "\"Team 1\" team1 team1pass\n");
fclose(fp);
fp = fopen((dir+"/clarifications.txt").c_str(), "w");
fprintf(fp, "global A \"Question available to all teams\" \"Answer\"\n");
fprintf(fp, "team1 C \"Question privately answered to team1\" \"Answer\"\n");
fclose(fp);
mkdir((dir+"/problems").c_str(), 0777);
fp = fopen((dir+"/problems/A.in").c_str(), "w");
fclose(fp);
fp = fopen((dir+"/problems/A.sol").c_str(), "w");
fclose(fp);
system("cp -rf /usr/local/share/pjudge/www %s/www", dir.c_str());
}
void start(int argc, char** argv) {
if (Contest().pid) return;
arg = vector<string>(argc);
for (int i = 0; i < argc; i++) arg[i] = argv[i];
daemon(1, 0);
Contest(getpid(), msgqueue());
signal(SIGTERM, term);
signal(SIGPIPE, SIG_IGN);
Judge::fire();
Scoreboard::fire();
Rejudger::fire(msqid);
WebServer::fire();
for (pthread_t& thread : threads) pthread_join(thread, nullptr);
}
void stop() {
Contest c;
if (c.pid) kill(c.pid, SIGTERM);
}
void rejudge(int id, char verdict) {
Contest c;
if (!c.pid) Rejudger::rejudge(id, verdict);
else {
rejudgemsg msg(id, verdict);
msgsnd(msgget(c.key, 0), &msg, msg.size(), 0);
}
}
bool alive() {
return !quit;
}
void fire(void* (*thread)(void*)) {
threads.emplace_back();
pthread_create(&threads.back(), nullptr, thread, nullptr);
}
void lock_att_file() {
pthread_mutex_lock(&attfile_mutex);
}
void unlock_att_file() {
pthread_mutex_unlock(&attfile_mutex);
}
void lock_nextid_file() {
pthread_mutex_lock(&nextidfile_mutex);
}
void unlock_nextid_file() {
pthread_mutex_unlock(&nextidfile_mutex);
}
void lock_question_file() {
pthread_mutex_lock(&questionfile_mutex);
}
void unlock_question_file() {
pthread_mutex_unlock(&questionfile_mutex);
}
} // namespace Global
<commit_msg>Improving comments<commit_after>#include <cstring>
#include <fstream>
#include <list>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include "global.h"
#include "judge.h"
#include "scoreboard.h"
#include "rejudger.h"
#include "webserver.h"
using namespace std;
static pthread_mutex_t localtime_mutex = PTHREAD_MUTEX_INITIALIZER;
Settings::Settings() {
memset(this, 0, sizeof(::Settings));
fstream f("settings.txt");
if (!f.is_open()) return;
string tmp;
auto func = [&](time_t& buf) {
int Y, M, D, h, m;
f >> tmp >> Y >> M >> D >> h >> m;
time(&buf);
pthread_mutex_lock(&localtime_mutex);
tm* tinfo = localtime(&buf);
tm ti = *tinfo;
pthread_mutex_unlock(&localtime_mutex);
ti.tm_year = Y - 1900;
ti.tm_mon = M - 1;
ti.tm_mday = D;
ti.tm_hour = h;
ti.tm_min = m;
ti.tm_sec = 0;
buf = mktime(&ti);
};
func(begin);
func(end);
func(freeze);
func(noverdict);
int timelimit;
while (f >> tmp >> timelimit) problems.push_back(timelimit);
}
rejudgemsg::rejudgemsg(int id, char verdict)
: mtype(1), id(id), verdict(verdict) {}
size_t rejudgemsg::size() const { return sizeof(rejudgemsg)-sizeof(long); }
static __suseconds_t dt(const timeval& start) {
timeval end;
gettimeofday(&end, nullptr);
return
(end.tv_sec*1000000 + end.tv_usec)-
(start.tv_sec*1000000 + start.tv_usec)
;
}
int timeout(bool& tle, int s, const char* cmd) {
tle = false;
__suseconds_t us = s*1000000;
timeval start;
gettimeofday(&start, nullptr);
pid_t proc = fork();
if (!proc) {
setpgid(0, 0); // create new process group rooted at proc
int status = system(cmd);
exit(WEXITSTATUS(status));
}
int status;
while (waitpid(proc, &status, WNOHANG) != proc) {
if (dt(start) > us) {
tle = true;
kill(-proc, SIGKILL); //the minus kills the whole group rooted at proc
waitpid(proc, &status, 0);
break;
}
usleep(10000);
}
return status;
}
void ignoresd(int sd) {
char* buf = new char[1 << 10];
while (read(sd, buf, 1 << 10) == (1 << 10));
delete[] buf;
}
template <>
string to<string, in_addr_t>(const in_addr_t& x) {
char* ptr = (char*)&x;
string ret = to<string>(int(ptr[0])&0x0ff);
for (int i = 1; i < 4; i++) ret += ("."+to<string>(int(ptr[i])&0x0ff));
return ret;
}
struct Contest {
pid_t pid;
key_t key;
Contest(pid_t pid, key_t key) : pid(pid), key(key) {
FILE* fp = fopen("contest.bin", "wb");
fwrite(this, sizeof(Contest), 1, fp);
fclose(fp);
}
Contest() : pid(0), key(0) {
FILE* fp = fopen("contest.bin", "rb");
if (!fp) return;
fread(this, sizeof(Contest), 1, fp);
fclose(fp);
}
};
static bool quit = false;
static list<pthread_t> threads;
static pthread_mutex_t attfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t nextidfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t questionfile_mutex = PTHREAD_MUTEX_INITIALIZER;
static int msqid;
static key_t msgqueue() {
key_t key = 0x713e24a;
while ((msqid = msgget(key, (IPC_CREAT|IPC_EXCL)|0777)) < 0) key++;
return key;
}
static void term(int) {
msgctl(msqid, IPC_RMID, nullptr);
remove("contest.bin");
pthread_mutex_lock(&attfile_mutex);
pthread_mutex_lock(&nextidfile_mutex);
pthread_mutex_lock(&questionfile_mutex);
quit = true;
pthread_mutex_unlock(&questionfile_mutex);
pthread_mutex_unlock(&nextidfile_mutex);
pthread_mutex_unlock(&attfile_mutex);
for (pthread_t& thread : threads) pthread_join(thread, nullptr);
exit(0);
}
namespace Global {
vector<string> arg;
void install(const string& dir) {
mkdir(dir.c_str(), 0777);
FILE* fp = fopen((dir+"/settings.txt").c_str(), "w");
fprintf(fp,
"Begin: 2015 09 01 19 00\n"
"End: 2015 12 25 23 50\n"
"Freeze: 2015 12 25 23 50\n"
"Blind: 2015 12 25 23 50\n"
"A(time-limit-in-seconds): 4\n"
"B(these-comments-are-useless-and-can-be-removed): 3\n"
"C: 5\n"
);
fclose(fp);
fp = fopen((dir+"/teams.txt").c_str(), "w");
fprintf(fp, "\"Team 1\" team1 team1pass\n");
fclose(fp);
fp = fopen((dir+"/clarifications.txt").c_str(), "w");
fprintf(fp, "global A \"Question available to all teams\" \"Answer\"\n");
fprintf(fp, "team1 C \"Question privately answered to team1\" \"Answer\"\n");
fclose(fp);
mkdir((dir+"/problems").c_str(), 0777);
fp = fopen((dir+"/problems/A.in").c_str(), "w");
fclose(fp);
fp = fopen((dir+"/problems/A.sol").c_str(), "w");
fclose(fp);
fp = fopen((dir+"/problems/B.in").c_str(), "w");
fclose(fp);
fp = fopen((dir+"/problems/B.sol").c_str(), "w");
fclose(fp);
fp = fopen((dir+"/problems/C.in").c_str(), "w");
fclose(fp);
fp = fopen((dir+"/problems/C.sol").c_str(), "w");
fclose(fp);
system("cp -rf /usr/local/share/pjudge/www %s/www", dir.c_str());
}
void start(int argc, char** argv) {
if (Contest().pid) return;
arg = vector<string>(argc);
for (int i = 0; i < argc; i++) arg[i] = argv[i];
daemon(1, 0);
Contest(getpid(), msgqueue());
signal(SIGTERM, term);
signal(SIGPIPE, SIG_IGN);
Judge::fire();
Scoreboard::fire();
Rejudger::fire(msqid);
WebServer::fire();
for (pthread_t& thread : threads) pthread_join(thread, nullptr);
}
void stop() {
Contest c;
if (c.pid) kill(c.pid, SIGTERM);
}
void rejudge(int id, char verdict) {
Contest c;
if (!c.pid) Rejudger::rejudge(id, verdict);
else {
rejudgemsg msg(id, verdict);
msgsnd(msgget(c.key, 0), &msg, msg.size(), 0);
}
}
bool alive() {
return !quit;
}
void fire(void* (*thread)(void*)) {
threads.emplace_back();
pthread_create(&threads.back(), nullptr, thread, nullptr);
}
void lock_att_file() {
pthread_mutex_lock(&attfile_mutex);
}
void unlock_att_file() {
pthread_mutex_unlock(&attfile_mutex);
}
void lock_nextid_file() {
pthread_mutex_lock(&nextidfile_mutex);
}
void unlock_nextid_file() {
pthread_mutex_unlock(&nextidfile_mutex);
}
void lock_question_file() {
pthread_mutex_lock(&questionfile_mutex);
}
void unlock_question_file() {
pthread_mutex_unlock(&questionfile_mutex);
}
} // namespace Global
<|endoftext|>
|
<commit_before>#include <cassert>
#include <vector>
#include <sstream>
#include <boost/foreach.hpp>
#include <fnv_solution.hpp>
#include <stp/c_interface.h>
FNVSolution::FNVSolution(const FNVParam& param, const FNVAlgo& algo, VC& vc,
const std::vector<Expr>& octetExprs)
{
std::ostringstream prefixStream;
prefixStream << "FNV" << param.getWidth() << "_" << algo.getName();
prefix = prefixStream.str();
BOOST_FOREACH(const Expr& octetExpr, octetExprs)
{
assert(getVWidth(octetExpr) == 8);
const Expr octetValue = vc_getCounterExample(vc, octetExpr);
assert(getType(octetValue) == BITVECTOR_TYPE);
assert(getExprKind(octetValue) == BVCONST);
const unsigned value = getBVUnsigned(octetValue);
assert(value < 256);
octets.push_back(static_cast<unsigned char>(value));
}
}
bool FNVSolution::operator<(const FNVSolution& s) const
{
if (prefix < s.prefix)
return true;
if (prefix == s.prefix)
return octets < s.octets;
return false;
}
bool FNVSolution::operator==(const FNVSolution& s) const
{
return prefix == s.prefix && octets == s.octets;
}
void FNVSolution::write(std::ostream& out) const
{
out << prefix << "(";
for(unsigned i=0; i<octets.size(); ++i)
{
const char octet = octets[i];
static const char* digits = "0123456789abcdef";
const char first = digits[octet >> 4];
const char second = digits[octet & ((1<<4)-1)];
out << first << second << (i+1 < octets.size() ? " " : "");
}
out << ")";
}
std::ostream& operator<<(std::ostream& o, const FNVSolution& solution)
{
solution.write(o);
return o;
}
<commit_msg>Fix signed/unsigned char conversion issue.<commit_after>#include <cassert>
#include <vector>
#include <sstream>
#include <boost/foreach.hpp>
#include <fnv_solution.hpp>
#include <stp/c_interface.h>
FNVSolution::FNVSolution(const FNVParam& param, const FNVAlgo& algo, VC& vc,
const std::vector<Expr>& octetExprs)
{
std::ostringstream prefixStream;
prefixStream << "FNV" << param.getWidth() << "_" << algo.getName();
prefix = prefixStream.str();
BOOST_FOREACH(const Expr& octetExpr, octetExprs)
{
assert(getVWidth(octetExpr) == 8);
const Expr octetValue = vc_getCounterExample(vc, octetExpr);
assert(getType(octetValue) == BITVECTOR_TYPE);
assert(getExprKind(octetValue) == BVCONST);
const unsigned value = getBVUnsigned(octetValue);
assert(value < 256);
octets.push_back(static_cast<unsigned char>(value));
}
}
bool FNVSolution::operator<(const FNVSolution& s) const
{
if (prefix < s.prefix)
return true;
if (prefix == s.prefix)
return octets < s.octets;
return false;
}
bool FNVSolution::operator==(const FNVSolution& s) const
{
return prefix == s.prefix && octets == s.octets;
}
void FNVSolution::write(std::ostream& out) const
{
out << prefix << "(";
for(unsigned i=0; i<octets.size(); ++i)
{
const int octet = octets[i];
static const char* digits = "0123456789abcdef";
const char first = digits[octet >> 4];
const char second = digits[octet & ((1<<4)-1)];
out << first << second << (i+1 < octets.size() ? " " : "");
}
out << ")";
}
std::ostream& operator<<(std::ostream& o, const FNVSolution& solution)
{
solution.write(o);
return o;
}
<|endoftext|>
|
<commit_before><commit_msg>[TCling] Also add temporary debug output to InspectMembers.<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2007-2010 Digital Bazaar, Inc. All rights reserved.
*/
#include "monarch/sql/mysql/MySqlConnection.h"
#include "monarch/sql/mysql/MySqlStatement.h"
#include <mysql/errmsg.h>
using namespace std;
using namespace monarch::sql;
using namespace monarch::sql::mysql;
using namespace monarch::net;
using namespace monarch::rt;
MySqlConnection::MySqlConnection()
{
// no handle yet
mHandle = NULL;
}
MySqlConnection::~MySqlConnection()
{
// ensure connection is closed
MySqlConnection::close();
}
inline ::MYSQL* MySqlConnection::getHandle()
{
return mHandle;
}
bool MySqlConnection::connect(Url* url)
{
bool rval = false;
if(strcmp(url->getScheme().c_str(), "mysql") != 0)
{
ExceptionRef e = new Exception(
"Could not connect to mysql database. "
"Url scheme doesn't start with 'mysql'",
"monarch.sql.BadUrlScheme");
e->getDetails()["url"] = url->toString().c_str();
Exception::set(e);
}
else
{
// initialize handle
mHandle = mysql_init(NULL);
// default character set to UTF-8
mysql_options(mHandle, MYSQL_SET_CHARSET_NAME, "utf8");
// setup client flag
int clientFlag = CLIENT_FOUND_ROWS | CLIENT_COMPRESS;
// determine default database (if any)
const char* db = (url->getPath().length() <= 1 ?
NULL : url->getPath().c_str() + 1);
// FIXME: we want to add read/write/create params to the URL
// so connections can be read-only/write/etc (use query in URL)
if(mysql_real_connect(
mHandle,
url->getHost().c_str(),
url->getUser().c_str(), url->getPassword().c_str(),
db,
url->getPort(), NULL, clientFlag) == NULL)
{
// create exception, close connection
ExceptionRef e = createException();
Exception::set(e);
MySqlConnection::close();
}
else
{
// connected
rval = true;
}
}
return rval;
}
void MySqlConnection::close()
{
AbstractConnection::close();
if(mHandle != NULL)
{
mysql_close(mHandle);
mHandle = NULL;
}
}
bool MySqlConnection::begin()
{
bool rval;
if(!(rval = (mysql_query(mHandle, "START TRANSACTION") == 0)))
{
ExceptionRef e = new Exception("Could not begin transaction.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
bool MySqlConnection::commit()
{
bool rval;
if(!(rval = (mysql_query(mHandle, "COMMIT") == 0)))
{
ExceptionRef e = new Exception("Could not commit transaction.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
bool MySqlConnection::rollback()
{
bool rval;
if(!(rval = (mysql_query(mHandle, "ROLLBACK") == 0)))
{
ExceptionRef e = new Exception("Could not rollback transaction.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
bool MySqlConnection::isConnected()
{
bool rval = false;
if(mHandle != NULL)
{
rval = (mysql_ping(mHandle) == 0);
}
return rval;
}
bool MySqlConnection::setCharacterSet(const char* cset)
{
// FIXME: handle exceptions
mysql_options(mHandle, MYSQL_SET_CHARSET_NAME, cset);
return true;
}
bool MySqlConnection::query(const char* sql)
{
bool rval;
if(!(rval = (mysql_query(mHandle, sql) == 0)))
{
ExceptionRef e = new Exception("Could not execute query.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
Exception* MySqlConnection::createException()
{
Exception* e = new Exception(
mysql_error(mHandle),
"monarch.sql.mysql.MySql",
mysql_errno(mHandle));
e->getDetails()["sqlState"] = mysql_sqlstate(mHandle);
return e;
}
Statement* MySqlConnection::createStatement(const char* sql)
{
// create statement
MySqlStatement* rval = new MySqlStatement(sql);
if(!rval->initialize(this))
{
// delete statement if it could not be initialized
delete rval;
rval = NULL;
}
return rval;
}
<commit_msg>Added logging to mysql connection failures.<commit_after>/*
* Copyright (c) 2007-2010 Digital Bazaar, Inc. All rights reserved.
*/
#include "monarch/sql/mysql/MySqlConnection.h"
#include "monarch/data/json/JsonWriter.h"
#include "monarch/logging/Logging.h"
#include "monarch/sql/mysql/MySqlStatement.h"
#include <mysql/errmsg.h>
using namespace std;
using namespace monarch::sql;
using namespace monarch::sql::mysql;
using namespace monarch::net;
using namespace monarch::rt;
MySqlConnection::MySqlConnection()
{
// no handle yet
mHandle = NULL;
}
MySqlConnection::~MySqlConnection()
{
// ensure connection is closed
MySqlConnection::close();
}
inline ::MYSQL* MySqlConnection::getHandle()
{
return mHandle;
}
bool MySqlConnection::connect(Url* url)
{
bool rval = false;
if(strcmp(url->getScheme().c_str(), "mysql") != 0)
{
ExceptionRef e = new Exception(
"Could not connect to mysql database. "
"Url scheme doesn't start with 'mysql'",
"monarch.sql.BadUrlScheme");
e->getDetails()["url"] = url->toString().c_str();
Exception::set(e);
}
else
{
// initialize handle
mHandle = mysql_init(NULL);
// default character set to UTF-8
mysql_options(mHandle, MYSQL_SET_CHARSET_NAME, "utf8");
// setup client flag
int clientFlag = CLIENT_FOUND_ROWS | CLIENT_COMPRESS;
// determine default database (if any)
const char* db = (url->getPath().length() <= 1 ?
NULL : url->getPath().c_str() + 1);
// FIXME: we want to add read/write/create params to the URL
// so connections can be read-only/write/etc (use query in URL)
if(mysql_real_connect(
mHandle,
url->getHost().c_str(),
url->getUser().c_str(), url->getPassword().c_str(),
db,
url->getPort(), NULL, clientFlag) == NULL)
{
// create exception, close connection
ExceptionRef e = createException();
Exception::set(e);
MySqlConnection::close();
MO_CAT_DEBUG(MO_SQL_CAT,
"Could not connect to database host '%s:%d': %s",
url->getHost().c_str(), url->getPort(),
monarch::data::json::JsonWriter::writeToString(
Exception::convertToDynamicObject(e)).c_str());
}
else
{
// connected
rval = true;
}
}
return rval;
}
void MySqlConnection::close()
{
AbstractConnection::close();
if(mHandle != NULL)
{
mysql_close(mHandle);
mHandle = NULL;
}
}
bool MySqlConnection::begin()
{
bool rval;
if(!(rval = (mysql_query(mHandle, "START TRANSACTION") == 0)))
{
ExceptionRef e = new Exception("Could not begin transaction.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
bool MySqlConnection::commit()
{
bool rval;
if(!(rval = (mysql_query(mHandle, "COMMIT") == 0)))
{
ExceptionRef e = new Exception("Could not commit transaction.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
bool MySqlConnection::rollback()
{
bool rval;
if(!(rval = (mysql_query(mHandle, "ROLLBACK") == 0)))
{
ExceptionRef e = new Exception("Could not rollback transaction.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
bool MySqlConnection::isConnected()
{
bool rval = false;
if(mHandle != NULL)
{
rval = (mysql_ping(mHandle) == 0);
}
return rval;
}
bool MySqlConnection::setCharacterSet(const char* cset)
{
// FIXME: handle exceptions
mysql_options(mHandle, MYSQL_SET_CHARSET_NAME, cset);
return true;
}
bool MySqlConnection::query(const char* sql)
{
bool rval;
if(!(rval = (mysql_query(mHandle, sql) == 0)))
{
ExceptionRef e = new Exception("Could not execute query.");
ExceptionRef cause = createException();
e->setCause(cause);
Exception::set(e);
}
return rval;
}
Exception* MySqlConnection::createException()
{
Exception* e = new Exception(
mysql_error(mHandle),
"monarch.sql.mysql.MySql",
mysql_errno(mHandle));
e->getDetails()["sqlState"] = mysql_sqlstate(mHandle);
return e;
}
Statement* MySqlConnection::createStatement(const char* sql)
{
// create statement
MySqlStatement* rval = new MySqlStatement(sql);
if(!rval->initialize(this))
{
// delete statement if it could not be initialized
delete rval;
rval = NULL;
}
return rval;
}
<|endoftext|>
|
<commit_before>#include <opencv2/opencv.hpp>
// #include "opencv2/highgui/highgui.hpp"
// #include "opencv2/imgproc/imgproc.hpp"
//#include "opencv2/gpu/gpu.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudaobjdetect.hpp"
using namespace cv;
using namespace std;
int findObject(vector<Rect> found, Mat img,string filename);
int main (int argc, const char * argv[]){
Mat img;
//init the descriptors
cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create();
HOGDescriptor cpu_hog;
//set the svm to default people detector
gpu_hog->setSVMDetector(gpu_hog->getDefaultPeopleDetector());
cpu_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
while (true){
img = imread("../walkingPeople.jpeg",CV_LOAD_IMAGE_GRAYSCALE);
if (!img.data){
cerr<<"Couldn't open image"<<endl;
return -1;
}
// //resizing the video since it's so massive
// resize(img, img, Size(640, 360), 0, 0, INTER_CUBIC);
vector<Rect> found_cpu, found_filtered_cpu;
vector<Rect> found_gpu, found_filtered_gpu;
//comput for the gpu
cuda::GpuMat gpu_img;
gpu_img.upload(img);
gpu_hog->detectMultiScale(gpu_img, found_gpu);
//comput for the cpu
cpu_hog.detectMultiScale(img, found_cpu, 0, Size(8,8), Size(32,32), 1.05, 2);
findObject(found_cpu,img,"tracking_cpu.jpeg");
findObject(found_gpu,img,"tracking_gpu.jpeg");
}
return 0;
}
int findObject(vector<Rect> found, Mat img,string filename){
size_t j = 0, i = 0;
vector<Rect> found_filtered;
for (i=0; i<found.size(); i++){
Rect r = found[i];
for (j=0; j<found.size(); j++){
if (j!=i && (r & found[j]) == r){
break;
}
}
if (j== found.size()){
found_filtered.push_back(r);
}
}
for (i=0; i<found_filtered.size(); i++){
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
}
imwrite(filename,img);
}
<commit_msg>added timing for the functions<commit_after>#include <opencv2/opencv.hpp>
// #include "opencv2/highgui/highgui.hpp"
// #include "opencv2/imgproc/imgproc.hpp"
//#include "opencv2/gpu/gpu.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudaobjdetect.hpp"
#include "../include/timing.hpp"
using namespace cv;
using namespace std;
int findObject(vector<Rect> found, Mat img,string filename);
int main (int argc, const char * argv[]){
Mat img, temp;
//init the descriptors
cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create();
HOGDescriptor cpu_hog;
//set the svm to default people detector
gpu_hog->setSVMDetector(gpu_hog->getDefaultPeopleDetector());
cpu_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
temp = imread("../walkingPeople.jpeg");
cvtColor( temp,img, CV_RGB2GRAY);
if (!img.data){
cerr<<"Couldn't open image"<<endl;
return -1;
}
// //resizing the video since it's so massive
// resize(img, img, Size(640, 360), 0, 0, INTER_CUBIC);
vector<Rect> found_cpu, found_filtered_cpu;
vector<Rect> found_gpu, found_filtered_gpu;
Timing gpu_time;
Timing cpu_time;
gpu_time.start();
//comput for the gpu
cuda::GpuMat gpu_img;
gpu_img.upload(img);
gpu_hog->detectMultiScale(gpu_img, found_gpu);
findObject(found_gpu,img,"tracking_gpu.jpeg");
gpu_time.end();
cpu_time.start();
//comput for the cpu
cpu_hog.detectMultiScale(img, found_cpu, 0, Size(8,8), Size(32,32), 1.05, 2);
findObject(found_cpu,img,"tracking_cpu.jpeg");
cpu_time.end();
cout<<"cpu time: "<<cpu_time.get_elapse()<<" gpu time: "<<gpu_time.get_elapse()<<endl;
cout<<"Percent speed up is: "<<cpu_time.get_elapse()/gpu_time.get_elapse()<<endl;
return 0;
}
int findObject(vector<Rect> found, Mat img,string filename){
size_t j = 0, i = 0;
vector<Rect> found_filtered;
for (i=0; i<found.size(); i++){
Rect r = found[i];
for (j=0; j<found.size(); j++){
if (j!=i && (r & found[j]) == r){
break;
}
}
if (j== found.size()){
found_filtered.push_back(r);
}
}
for (i=0; i<found_filtered.size(); i++){
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
}
imwrite(filename,img);
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/LU>
template<typename MatrixType> void inverse(const MatrixType& m)
{
/* this test covers the following files:
Inverse.h
*/
int rows = m.rows();
int cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;
MatrixType m1(rows, cols),
m2(rows, cols),
mzero = MatrixType::Zero(rows, cols),
identity = MatrixType::Identity(rows, rows);
createRandomPIMatrixOfRank(rows,rows,rows,m1);
m2 = m1.inverse();
VERIFY_IS_APPROX(m1, m2.inverse() );
VERIFY_IS_APPROX((Scalar(2)*m2).inverse(), m2.inverse()*Scalar(0.5));
VERIFY_IS_APPROX(identity, m1.inverse() * m1 );
VERIFY_IS_APPROX(identity, m1 * m1.inverse() );
VERIFY_IS_APPROX(m1, m1.inverse().inverse() );
// since for the general case we implement separately row-major and col-major, test that
VERIFY_IS_APPROX(m1.transpose().inverse(), m1.inverse().transpose());
#if !defined(EIGEN_TEST_PART_5) && !defined(EIGEN_TEST_PART_6)
//computeInverseAndDetWithCheck tests
//First: an invertible matrix
bool invertible;
RealScalar det;
m2.setZero();
m1.computeInverseAndDetWithCheck(m2, det, invertible);
VERIFY(invertible);
VERIFY_IS_APPROX(identity, m1*m2);
VERIFY_IS_APPROX(det, m1.determinant());
m2.setZero();
m1.computeInverseWithCheck(m2, invertible);
VERIFY(invertible);
VERIFY_IS_APPROX(identity, m1*m2);
//Second: a rank one matrix (not invertible, except for 1x1 matrices)
VectorType v3 = VectorType::Random(rows);
MatrixType m3 = v3*v3.transpose(), m4(rows,cols);
m3.computeInverseAndDetWithCheck(m4, det, invertible);
VERIFY( rows==1 ? invertible : !invertible );
VERIFY_IS_MUCH_SMALLER_THAN(m3.determinant(), RealScalar(1));
m3.computeInverseWithCheck(m4, invertible);
VERIFY( rows==1 ? invertible : !invertible );
#endif
// check in-place inversion
if(MatrixType::RowsAtCompileTime>=2 && MatrixType::RowsAtCompileTime<=4)
{
// in-place is forbidden
VERIFY_RAISES_ASSERT(m1 = m1.inverse());
}
else
{
m2 = m1.inverse();
m1 = m1.inverse();
VERIFY_IS_APPROX(m1,m2);
}
}
void test_inverse()
{
int s;
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( inverse(Matrix<double,1,1>()) );
CALL_SUBTEST_2( inverse(Matrix2d()) );
CALL_SUBTEST_3( inverse(Matrix3f()) );
CALL_SUBTEST_4( inverse(Matrix4f()) );
s = ei_random<int>(50,320);
CALL_SUBTEST_5( inverse(MatrixXf(s,s)) );
s = ei_random<int>(25,100);
CALL_SUBTEST_6( inverse(MatrixXcd(s,s)) );
CALL_SUBTEST_7( inverse(Matrix4d()) );
}
}
<commit_msg>For 1x1 matrices we really need to check the abs diff of the determinants.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
// Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/LU>
template<typename MatrixType> void inverse(const MatrixType& m)
{
/* this test covers the following files:
Inverse.h
*/
int rows = m.rows();
int cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
typedef Matrix<Scalar, MatrixType::ColsAtCompileTime, 1> VectorType;
MatrixType m1(rows, cols),
m2(rows, cols),
mzero = MatrixType::Zero(rows, cols),
identity = MatrixType::Identity(rows, rows);
createRandomPIMatrixOfRank(rows,rows,rows,m1);
m2 = m1.inverse();
VERIFY_IS_APPROX(m1, m2.inverse() );
VERIFY_IS_APPROX((Scalar(2)*m2).inverse(), m2.inverse()*Scalar(0.5));
VERIFY_IS_APPROX(identity, m1.inverse() * m1 );
VERIFY_IS_APPROX(identity, m1 * m1.inverse() );
VERIFY_IS_APPROX(m1, m1.inverse().inverse() );
// since for the general case we implement separately row-major and col-major, test that
VERIFY_IS_APPROX(m1.transpose().inverse(), m1.inverse().transpose());
#if !defined(EIGEN_TEST_PART_5) && !defined(EIGEN_TEST_PART_6)
//computeInverseAndDetWithCheck tests
//First: an invertible matrix
bool invertible;
RealScalar det;
m2.setZero();
m1.computeInverseAndDetWithCheck(m2, det, invertible);
VERIFY(invertible);
VERIFY_IS_APPROX(identity, m1*m2);
VERIFY_IS_APPROX(det, m1.determinant());
m2.setZero();
m1.computeInverseWithCheck(m2, invertible);
VERIFY(invertible);
VERIFY_IS_APPROX(identity, m1*m2);
//Second: a rank one matrix (not invertible, except for 1x1 matrices)
VectorType v3 = VectorType::Random(rows);
MatrixType m3 = v3*v3.transpose(), m4(rows,cols);
m3.computeInverseAndDetWithCheck(m4, det, invertible);
VERIFY( rows==1 ? invertible : !invertible );
VERIFY_IS_MUCH_SMALLER_THAN(ei_abs(det-m3.determinant()), RealScalar(1));
m3.computeInverseWithCheck(m4, invertible);
VERIFY( rows==1 ? invertible : !invertible );
#endif
// check in-place inversion
if(MatrixType::RowsAtCompileTime>=2 && MatrixType::RowsAtCompileTime<=4)
{
// in-place is forbidden
VERIFY_RAISES_ASSERT(m1 = m1.inverse());
}
else
{
m2 = m1.inverse();
m1 = m1.inverse();
VERIFY_IS_APPROX(m1,m2);
}
}
void test_inverse()
{
int s;
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( inverse(Matrix<double,1,1>()) );
CALL_SUBTEST_2( inverse(Matrix2d()) );
CALL_SUBTEST_3( inverse(Matrix3f()) );
CALL_SUBTEST_4( inverse(Matrix4f()) );
s = ei_random<int>(50,320);
CALL_SUBTEST_5( inverse(MatrixXf(s,s)) );
s = ei_random<int>(25,100);
CALL_SUBTEST_6( inverse(MatrixXcd(s,s)) );
CALL_SUBTEST_7( inverse(Matrix4d()) );
}
}
<|endoftext|>
|
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType>
bool equalsIdentity(const MatrixType& A)
{
typedef typename MatrixType::Scalar Scalar;
Scalar zero = static_cast<Scalar>(0);
bool offDiagOK = true;
for (int i = 0; i < A.rows(); ++i) {
for (int j = i+1; j < A.cols(); ++j) {
offDiagOK = offDiagOK && (A(i,j) == zero);
}
}
for (int i = 0; i < A.rows(); ++i) {
for (int j = 0; j < std::min(i, A.cols()); ++j) {
offDiagOK = offDiagOK && (A(i,j) == zero);
}
}
bool diagOK = (A.diagonal().array() == 1).all();
return offDiagOK && diagOK;
}
template<typename VectorType>
void testVectorType(const VectorType& base)
{
typedef typename internal::traits<VectorType>::Index Index;
typedef typename internal::traits<VectorType>::Scalar Scalar;
Scalar low = internal::random<Scalar>(-500,500);
Scalar high = internal::random<Scalar>(-500,500);
if (low>high) std::swap(low,high);
const Index size = base.size();
const Scalar step = (high-low)/(size-1);
// check whether the result yields what we expect it to do
VectorType m(base);
m.setLinSpaced(size,low,high);
VectorType n(size);
for (int i=0; i<size; ++i)
n(i) = low+i*step;
VERIFY_IS_APPROX(m,n);
// random access version
m = VectorType::LinSpaced(size,low,high);
VERIFY_IS_APPROX(m,n);
// Assignment of a RowVectorXd to a MatrixXd (regression test for bug #79).
VERIFY( (MatrixXd(RowVectorXd::LinSpaced(3, 0, 1)) - RowVector3d(0, 0.5, 1)).norm() < std::numeric_limits<Scalar>::epsilon() );
// These guys sometimes fail! This is not good. Any ideas how to fix them!?
// VERIFY( m(m.size()-1) == high );
// VERIFY( m(0) == low );
// sequential access version
m = VectorType::LinSpaced(Sequential,size,low,high);
VERIFY_IS_APPROX(m,n);
// These guys sometimes fail! This is not good. Any ideas how to fix them!?
//VERIFY( m(m.size()-1) == high );
//VERIFY( m(0) == low );
// check whether everything works with row and col major vectors
Matrix<Scalar,Dynamic,1> row_vector(size);
Matrix<Scalar,1,Dynamic> col_vector(size);
row_vector.setLinSpaced(size,low,high);
col_vector.setLinSpaced(size,low,high);
VERIFY( row_vector.isApprox(col_vector.transpose(), NumTraits<Scalar>::epsilon()));
Matrix<Scalar,Dynamic,1> size_changer(size+50);
size_changer.setLinSpaced(size,low,high);
VERIFY( size_changer.size() == size );
}
template<typename MatrixType>
void testMatrixType(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
const Index rows = m.rows();
const Index cols = m.cols();
MatrixType A;
A.setIdentity(rows, cols);
VERIFY(equalsIdentity(A));
VERIFY(equalsIdentity(MatrixType::Identity(rows, cols)));
}
void test_nullary()
{
CALL_SUBTEST_1( testMatrixType(Matrix2d()) );
CALL_SUBTEST_2( testMatrixType(MatrixXcf(internal::random<int>(1,300),internal::random<int>(1,300))) );
CALL_SUBTEST_3( testMatrixType(MatrixXf(internal::random<int>(1,300),internal::random<int>(1,300))) );
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_4( testVectorType(VectorXd(internal::random<int>(1,300))) );
CALL_SUBTEST_5( testVectorType(VectorXd(internal::random<int>(1,300))) );
CALL_SUBTEST_6( testVectorType(Vector3d()) );
CALL_SUBTEST_7( testVectorType(VectorXf(internal::random<int>(1,300))) );
CALL_SUBTEST_8( testVectorType(VectorXf(internal::random<int>(1,300))) );
CALL_SUBTEST_9( testVectorType(Vector3f()) );
}
}
<commit_msg>Change int to Index in equalsIdentity(). This fixes compilation errors in nullary test on 64-bits machines.<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Jitse Niesen <jitse@maths.leeds.ac.uk>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
template<typename MatrixType>
bool equalsIdentity(const MatrixType& A)
{
typedef typename MatrixType::Index Index;
typedef typename MatrixType::Scalar Scalar;
Scalar zero = static_cast<Scalar>(0);
bool offDiagOK = true;
for (Index i = 0; i < A.rows(); ++i) {
for (Index j = i+1; j < A.cols(); ++j) {
offDiagOK = offDiagOK && (A(i,j) == zero);
}
}
for (Index i = 0; i < A.rows(); ++i) {
for (Index j = 0; j < std::min(i, A.cols()); ++j) {
offDiagOK = offDiagOK && (A(i,j) == zero);
}
}
bool diagOK = (A.diagonal().array() == 1).all();
return offDiagOK && diagOK;
}
template<typename VectorType>
void testVectorType(const VectorType& base)
{
typedef typename internal::traits<VectorType>::Index Index;
typedef typename internal::traits<VectorType>::Scalar Scalar;
Scalar low = internal::random<Scalar>(-500,500);
Scalar high = internal::random<Scalar>(-500,500);
if (low>high) std::swap(low,high);
const Index size = base.size();
const Scalar step = (high-low)/(size-1);
// check whether the result yields what we expect it to do
VectorType m(base);
m.setLinSpaced(size,low,high);
VectorType n(size);
for (int i=0; i<size; ++i)
n(i) = low+i*step;
VERIFY_IS_APPROX(m,n);
// random access version
m = VectorType::LinSpaced(size,low,high);
VERIFY_IS_APPROX(m,n);
// Assignment of a RowVectorXd to a MatrixXd (regression test for bug #79).
VERIFY( (MatrixXd(RowVectorXd::LinSpaced(3, 0, 1)) - RowVector3d(0, 0.5, 1)).norm() < std::numeric_limits<Scalar>::epsilon() );
// These guys sometimes fail! This is not good. Any ideas how to fix them!?
// VERIFY( m(m.size()-1) == high );
// VERIFY( m(0) == low );
// sequential access version
m = VectorType::LinSpaced(Sequential,size,low,high);
VERIFY_IS_APPROX(m,n);
// These guys sometimes fail! This is not good. Any ideas how to fix them!?
//VERIFY( m(m.size()-1) == high );
//VERIFY( m(0) == low );
// check whether everything works with row and col major vectors
Matrix<Scalar,Dynamic,1> row_vector(size);
Matrix<Scalar,1,Dynamic> col_vector(size);
row_vector.setLinSpaced(size,low,high);
col_vector.setLinSpaced(size,low,high);
VERIFY( row_vector.isApprox(col_vector.transpose(), NumTraits<Scalar>::epsilon()));
Matrix<Scalar,Dynamic,1> size_changer(size+50);
size_changer.setLinSpaced(size,low,high);
VERIFY( size_changer.size() == size );
}
template<typename MatrixType>
void testMatrixType(const MatrixType& m)
{
typedef typename MatrixType::Index Index;
const Index rows = m.rows();
const Index cols = m.cols();
MatrixType A;
A.setIdentity(rows, cols);
VERIFY(equalsIdentity(A));
VERIFY(equalsIdentity(MatrixType::Identity(rows, cols)));
}
void test_nullary()
{
CALL_SUBTEST_1( testMatrixType(Matrix2d()) );
CALL_SUBTEST_2( testMatrixType(MatrixXcf(internal::random<int>(1,300),internal::random<int>(1,300))) );
CALL_SUBTEST_3( testMatrixType(MatrixXf(internal::random<int>(1,300),internal::random<int>(1,300))) );
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_4( testVectorType(VectorXd(internal::random<int>(1,300))) );
CALL_SUBTEST_5( testVectorType(VectorXd(internal::random<int>(1,300))) );
CALL_SUBTEST_6( testVectorType(Vector3d()) );
CALL_SUBTEST_7( testVectorType(VectorXf(internal::random<int>(1,300))) );
CALL_SUBTEST_8( testVectorType(VectorXf(internal::random<int>(1,300))) );
CALL_SUBTEST_9( testVectorType(Vector3f()) );
}
}
<|endoftext|>
|
<commit_before><commit_msg>Cyber: checked return value of WriteHeader method.<commit_after><|endoftext|>
|
<commit_before>#include "catch.hpp"
#include <initializer_list>
#include "cxxopts.hpp"
class Argv {
public:
Argv(std::initializer_list<const char*> args)
: m_argv(new char*[args.size()])
, m_argc(args.size())
{
int i = 0;
auto iter = args.begin();
while (iter != args.end()) {
auto len = strlen(*iter) + 1;
auto ptr = std::unique_ptr<char[]>(new char[len]);
strcpy(ptr.get(), *iter);
m_args.push_back(std::move(ptr));
m_argv.get()[i] = m_args.back().get();
++iter;
++i;
}
}
char** argv() const {
return m_argv.get();
}
int argc() const {
return m_argc;
}
private:
std::vector<std::unique_ptr<char[]>> m_args;
std::unique_ptr<char*[]> m_argv;
int m_argc;
};
TEST_CASE("Basic options", "[options]")
{
cxxopts::Options options("tester", " - test basic options");
options.add_options()
("long", "a long option")
("s,short", "a short option")
("value", "an option with a value", cxxopts::value<std::string>())
("a,av", "a short option with a value", cxxopts::value<std::string>())
("6,six", "a short number option")
("p, space", "an option with space between short and long")
;
Argv argv({
"tester",
"--long",
"-s",
"--value",
"value",
"-a",
"b",
"-6",
"-p",
"--space",
});
char** actual_argv = argv.argv();
auto argc = argv.argc();
auto result = options.parse(argc, actual_argv);
CHECK(result.count("long") == 1);
CHECK(result.count("s") == 1);
CHECK(result.count("value") == 1);
CHECK(result.count("a") == 1);
CHECK(result["value"].as<std::string>() == "value");
CHECK(result["a"].as<std::string>() == "b");
CHECK(result.count("6") == 1);
CHECK(result.count("p") == 2);
CHECK(result.count("space") == 2);
auto& arguments = result.arguments();
REQUIRE(arguments.size() == 7);
CHECK(arguments[0].key() == "long");
CHECK(arguments[0].value() == "true");
CHECK(arguments[0].as<bool>() == true);
CHECK(arguments[1].key() == "short");
CHECK(arguments[2].key() == "value");
CHECK(arguments[3].key() == "av");
}
TEST_CASE("Short options", "[options]")
{
cxxopts::Options options("test_short", " - test short options");
options.add_options()
("a", "a short option", cxxopts::value<std::string>());
Argv argv({"test_short", "-a", "value"});
auto actual_argv = argv.argv();
auto argc = argv.argc();
auto result = options.parse(argc, actual_argv);
CHECK(result.count("a") == 1);
CHECK(result["a"].as<std::string>() == "value");
REQUIRE_THROWS_AS(options.add_options()("", "nothing option"),
cxxopts::invalid_option_format_error);
}
TEST_CASE("No positional", "[positional]")
{
cxxopts::Options options("test_no_positional",
" - test no positional options");
Argv av({"tester", "a", "b", "def"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
REQUIRE(argc == 4);
CHECK(strcmp(argv[1], "a") == 0);
}
TEST_CASE("All positional", "[positional]")
{
std::vector<std::string> positional;
cxxopts::Options options("test_all_positional", " - test all positional");
options.add_options()
("positional", "Positional parameters",
cxxopts::value<std::vector<std::string>>(positional))
;
Argv av({"tester", "a", "b", "c"});
auto argc = av.argc();
auto argv = av.argv();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(argc == 1);
REQUIRE(positional.size() == 3);
CHECK(positional[0] == "a");
CHECK(positional[1] == "b");
CHECK(positional[2] == "c");
}
TEST_CASE("Some positional explicit", "[positional]")
{
cxxopts::Options options("positional_explicit", " - test positional");
options.add_options()
("input", "Input file", cxxopts::value<std::string>())
("output", "Output file", cxxopts::value<std::string>())
("positional", "Positional parameters",
cxxopts::value<std::vector<std::string>>())
;
options.parse_positional({"input", "output", "positional"});
Argv av({"tester", "--output", "a", "b", "c", "d"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(argc == 1);
CHECK(result.count("output"));
CHECK(result["input"].as<std::string>() == "b");
CHECK(result["output"].as<std::string>() == "a");
auto& positional = result["positional"].as<std::vector<std::string>>();
REQUIRE(positional.size() == 2);
CHECK(positional[0] == "c");
CHECK(positional[1] == "d");
}
TEST_CASE("No positional with extras", "[positional]")
{
cxxopts::Options options("posargmaster", "shows incorrect handling");
options.add_options()
("dummy", "oh no", cxxopts::value<std::string>())
;
Argv av({"extras", "--", "a", "b", "c", "d"});
char** argv = av.argv();
auto argc = av.argc();
auto old_argv = argv;
auto old_argc = argc;
options.parse(argc, argv);
REQUIRE(argc == old_argc - 1);
CHECK(argv[0] == std::string("extras"));
CHECK(argv[1] == std::string("a"));
}
TEST_CASE("Empty with implicit value", "[implicit]")
{
cxxopts::Options options("empty_implicit", "doesn't handle empty");
options.add_options()
("implicit", "Has implicit", cxxopts::value<std::string>()
->implicit_value("foo"));
Argv av({"implicit", "--implicit", ""});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
REQUIRE(result.count("implicit") == 1);
REQUIRE(result["implicit"].as<std::string>() == "");
}
TEST_CASE("Default values", "[default]")
{
cxxopts::Options options("defaults", "has defaults");
options.add_options()
("default", "Has implicit", cxxopts::value<int>()
->default_value("42"));
SECTION("Sets defaults") {
Argv av({"implicit"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(result.count("default") == 1);
CHECK(result["default"].as<int>() == 42);
}
SECTION("When values provided") {
Argv av({"implicit", "--default", "5"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(result.count("default") == 1);
CHECK(result["default"].as<int>() == 5);
}
}
TEST_CASE("Parse into a reference", "[reference]")
{
int value = 0;
cxxopts::Options options("into_reference", "parses into a reference");
options.add_options()
("ref", "A reference", cxxopts::value(value));
Argv av({"into_reference", "--ref", "42"});
auto argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(result.count("ref") == 1);
CHECK(value == 42);
}
TEST_CASE("Integers", "[options]")
{
cxxopts::Options options("parses_integers", "parses integers correctly");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int>>());
Argv av({"ints", "--", "5", "6", "-6", "0", "0xab", "0xAf", "0x0"});
char** argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(result.count("positional") == 7);
auto& positional = result["positional"].as<std::vector<int>>();
REQUIRE(positional.size() == 7);
CHECK(positional[0] == 5);
CHECK(positional[1] == 6);
CHECK(positional[2] == -6);
CHECK(positional[3] == 0);
CHECK(positional[4] == 0xab);
CHECK(positional[5] == 0xaf);
CHECK(positional[6] == 0x0);
}
TEST_CASE("Unsigned integers", "[options]")
{
cxxopts::Options options("parses_unsigned", "detects unsigned errors");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<unsigned int>>());
Argv av({"ints", "--", "-2"});
char** argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type);
}
TEST_CASE("Integer bounds", "[integer]")
{
cxxopts::Options options("integer_boundaries", "check min/max integer");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int8_t>>());
SECTION("No overflow")
{
Argv av({"ints", "--", "127", "-128", "0x7f", "-0x80", "0x7e"});
auto argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(result.count("positional") == 5);
auto& positional = result["positional"].as<std::vector<int8_t>>();
CHECK(positional[0] == 127);
CHECK(positional[1] == -128);
CHECK(positional[2] == 0x7f);
CHECK(positional[3] == -0x80);
CHECK(positional[4] == 0x7e);
}
}
TEST_CASE("Overflow on boundary", "[integer]")
{
using namespace cxxopts::values;
int8_t si;
uint8_t ui;
CHECK_THROWS_AS((integer_parser("128", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("-129", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("256", ui)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("-0x81", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("0x80", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("0x100", ui)), cxxopts::argument_incorrect_type);
}
TEST_CASE("Integer overflow", "[options]")
{
cxxopts::Options options("reject_overflow", "rejects overflowing integers");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int8_t>>());
Argv av({"ints", "--", "128"});
auto argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type);
}
TEST_CASE("Floats", "[options]")
{
cxxopts::Options options("parses_floats", "parses floats correctly");
options.add_options()
("double", "Double precision", cxxopts::value<double>())
("positional", "Floats", cxxopts::value<std::vector<float>>());
Argv av({"floats", "--double", "0.5", "--", "4", "-4", "1.5e6", "-1.5e6"});
char** argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(result.count("double") == 1);
REQUIRE(result.count("positional") == 4);
CHECK(result["double"].as<double>() == 0.5);
auto& positional = result["positional"].as<std::vector<float>>();
CHECK(positional[0] == 4);
CHECK(positional[1] == -4);
CHECK(positional[2] == 1.5e6);
CHECK(positional[3] == -1.5e6);
}
TEST_CASE("Invalid integers", "[integer]") {
cxxopts::Options options("invalid_integers", "rejects invalid integers");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int>>());
Argv av({"ints", "--", "Ae"});
char **argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type);
}
TEST_CASE("Booleans", "[boolean]") {
cxxopts::Options options("parses_floats", "parses floats correctly");
options.add_options()
("bool", "A Boolean", cxxopts::value<bool>())
("debug", "Debugging", cxxopts::value<bool>())
("timing", "Timing", cxxopts::value<bool>())
;
Argv av({"booleans", "--bool=false", "--debug", "true", "--timing"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
REQUIRE(result.count("bool") == 1);
REQUIRE(result.count("debug") == 1);
REQUIRE(result.count("timing") == 1);
CHECK(result["bool"].as<bool>() == false);
CHECK(result["debug"].as<bool>() == true);
CHECK(result["timing"].as<bool>() == true);
}
<commit_msg>add a test for broken boolean options<commit_after>#include "catch.hpp"
#include <initializer_list>
#include "cxxopts.hpp"
class Argv {
public:
Argv(std::initializer_list<const char*> args)
: m_argv(new char*[args.size()])
, m_argc(args.size())
{
int i = 0;
auto iter = args.begin();
while (iter != args.end()) {
auto len = strlen(*iter) + 1;
auto ptr = std::unique_ptr<char[]>(new char[len]);
strcpy(ptr.get(), *iter);
m_args.push_back(std::move(ptr));
m_argv.get()[i] = m_args.back().get();
++iter;
++i;
}
}
char** argv() const {
return m_argv.get();
}
int argc() const {
return m_argc;
}
private:
std::vector<std::unique_ptr<char[]>> m_args;
std::unique_ptr<char*[]> m_argv;
int m_argc;
};
TEST_CASE("Basic options", "[options]")
{
cxxopts::Options options("tester", " - test basic options");
options.add_options()
("long", "a long option")
("s,short", "a short option")
("value", "an option with a value", cxxopts::value<std::string>())
("a,av", "a short option with a value", cxxopts::value<std::string>())
("6,six", "a short number option")
("p, space", "an option with space between short and long")
;
Argv argv({
"tester",
"--long",
"-s",
"--value",
"value",
"-a",
"b",
"-6",
"-p",
"--space",
});
char** actual_argv = argv.argv();
auto argc = argv.argc();
auto result = options.parse(argc, actual_argv);
CHECK(result.count("long") == 1);
CHECK(result.count("s") == 1);
CHECK(result.count("value") == 1);
CHECK(result.count("a") == 1);
CHECK(result["value"].as<std::string>() == "value");
CHECK(result["a"].as<std::string>() == "b");
CHECK(result.count("6") == 1);
CHECK(result.count("p") == 2);
CHECK(result.count("space") == 2);
auto& arguments = result.arguments();
REQUIRE(arguments.size() == 7);
CHECK(arguments[0].key() == "long");
CHECK(arguments[0].value() == "true");
CHECK(arguments[0].as<bool>() == true);
CHECK(arguments[1].key() == "short");
CHECK(arguments[2].key() == "value");
CHECK(arguments[3].key() == "av");
}
TEST_CASE("Short options", "[options]")
{
cxxopts::Options options("test_short", " - test short options");
options.add_options()
("a", "a short option", cxxopts::value<std::string>());
Argv argv({"test_short", "-a", "value"});
auto actual_argv = argv.argv();
auto argc = argv.argc();
auto result = options.parse(argc, actual_argv);
CHECK(result.count("a") == 1);
CHECK(result["a"].as<std::string>() == "value");
REQUIRE_THROWS_AS(options.add_options()("", "nothing option"),
cxxopts::invalid_option_format_error);
}
TEST_CASE("No positional", "[positional]")
{
cxxopts::Options options("test_no_positional",
" - test no positional options");
Argv av({"tester", "a", "b", "def"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
REQUIRE(argc == 4);
CHECK(strcmp(argv[1], "a") == 0);
}
TEST_CASE("All positional", "[positional]")
{
std::vector<std::string> positional;
cxxopts::Options options("test_all_positional", " - test all positional");
options.add_options()
("positional", "Positional parameters",
cxxopts::value<std::vector<std::string>>(positional))
;
Argv av({"tester", "a", "b", "c"});
auto argc = av.argc();
auto argv = av.argv();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(argc == 1);
REQUIRE(positional.size() == 3);
CHECK(positional[0] == "a");
CHECK(positional[1] == "b");
CHECK(positional[2] == "c");
}
TEST_CASE("Some positional explicit", "[positional]")
{
cxxopts::Options options("positional_explicit", " - test positional");
options.add_options()
("input", "Input file", cxxopts::value<std::string>())
("output", "Output file", cxxopts::value<std::string>())
("positional", "Positional parameters",
cxxopts::value<std::vector<std::string>>())
;
options.parse_positional({"input", "output", "positional"});
Argv av({"tester", "--output", "a", "b", "c", "d"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(argc == 1);
CHECK(result.count("output"));
CHECK(result["input"].as<std::string>() == "b");
CHECK(result["output"].as<std::string>() == "a");
auto& positional = result["positional"].as<std::vector<std::string>>();
REQUIRE(positional.size() == 2);
CHECK(positional[0] == "c");
CHECK(positional[1] == "d");
}
TEST_CASE("No positional with extras", "[positional]")
{
cxxopts::Options options("posargmaster", "shows incorrect handling");
options.add_options()
("dummy", "oh no", cxxopts::value<std::string>())
;
Argv av({"extras", "--", "a", "b", "c", "d"});
char** argv = av.argv();
auto argc = av.argc();
auto old_argv = argv;
auto old_argc = argc;
options.parse(argc, argv);
REQUIRE(argc == old_argc - 1);
CHECK(argv[0] == std::string("extras"));
CHECK(argv[1] == std::string("a"));
}
TEST_CASE("Empty with implicit value", "[implicit]")
{
cxxopts::Options options("empty_implicit", "doesn't handle empty");
options.add_options()
("implicit", "Has implicit", cxxopts::value<std::string>()
->implicit_value("foo"));
Argv av({"implicit", "--implicit", ""});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
REQUIRE(result.count("implicit") == 1);
REQUIRE(result["implicit"].as<std::string>() == "");
}
TEST_CASE("Default values", "[default]")
{
cxxopts::Options options("defaults", "has defaults");
options.add_options()
("default", "Has implicit", cxxopts::value<int>()
->default_value("42"));
SECTION("Sets defaults") {
Argv av({"implicit"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(result.count("default") == 1);
CHECK(result["default"].as<int>() == 42);
}
SECTION("When values provided") {
Argv av({"implicit", "--default", "5"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(result.count("default") == 1);
CHECK(result["default"].as<int>() == 5);
}
}
TEST_CASE("Parse into a reference", "[reference]")
{
int value = 0;
cxxopts::Options options("into_reference", "parses into a reference");
options.add_options()
("ref", "A reference", cxxopts::value(value));
Argv av({"into_reference", "--ref", "42"});
auto argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
CHECK(result.count("ref") == 1);
CHECK(value == 42);
}
TEST_CASE("Integers", "[options]")
{
cxxopts::Options options("parses_integers", "parses integers correctly");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int>>());
Argv av({"ints", "--", "5", "6", "-6", "0", "0xab", "0xAf", "0x0"});
char** argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(result.count("positional") == 7);
auto& positional = result["positional"].as<std::vector<int>>();
REQUIRE(positional.size() == 7);
CHECK(positional[0] == 5);
CHECK(positional[1] == 6);
CHECK(positional[2] == -6);
CHECK(positional[3] == 0);
CHECK(positional[4] == 0xab);
CHECK(positional[5] == 0xaf);
CHECK(positional[6] == 0x0);
}
TEST_CASE("Unsigned integers", "[options]")
{
cxxopts::Options options("parses_unsigned", "detects unsigned errors");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<unsigned int>>());
Argv av({"ints", "--", "-2"});
char** argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type);
}
TEST_CASE("Integer bounds", "[integer]")
{
cxxopts::Options options("integer_boundaries", "check min/max integer");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int8_t>>());
SECTION("No overflow")
{
Argv av({"ints", "--", "127", "-128", "0x7f", "-0x80", "0x7e"});
auto argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(result.count("positional") == 5);
auto& positional = result["positional"].as<std::vector<int8_t>>();
CHECK(positional[0] == 127);
CHECK(positional[1] == -128);
CHECK(positional[2] == 0x7f);
CHECK(positional[3] == -0x80);
CHECK(positional[4] == 0x7e);
}
}
TEST_CASE("Overflow on boundary", "[integer]")
{
using namespace cxxopts::values;
int8_t si;
uint8_t ui;
CHECK_THROWS_AS((integer_parser("128", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("-129", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("256", ui)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("-0x81", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("0x80", si)), cxxopts::argument_incorrect_type);
CHECK_THROWS_AS((integer_parser("0x100", ui)), cxxopts::argument_incorrect_type);
}
TEST_CASE("Integer overflow", "[options]")
{
cxxopts::Options options("reject_overflow", "rejects overflowing integers");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int8_t>>());
Argv av({"ints", "--", "128"});
auto argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type);
}
TEST_CASE("Floats", "[options]")
{
cxxopts::Options options("parses_floats", "parses floats correctly");
options.add_options()
("double", "Double precision", cxxopts::value<double>())
("positional", "Floats", cxxopts::value<std::vector<float>>());
Argv av({"floats", "--double", "0.5", "--", "4", "-4", "1.5e6", "-1.5e6"});
char** argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
auto result = options.parse(argc, argv);
REQUIRE(result.count("double") == 1);
REQUIRE(result.count("positional") == 4);
CHECK(result["double"].as<double>() == 0.5);
auto& positional = result["positional"].as<std::vector<float>>();
CHECK(positional[0] == 4);
CHECK(positional[1] == -4);
CHECK(positional[2] == 1.5e6);
CHECK(positional[3] == -1.5e6);
}
TEST_CASE("Invalid integers", "[integer]") {
cxxopts::Options options("invalid_integers", "rejects invalid integers");
options.add_options()
("positional", "Integers", cxxopts::value<std::vector<int>>());
Argv av({"ints", "--", "Ae"});
char **argv = av.argv();
auto argc = av.argc();
options.parse_positional("positional");
CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type);
}
TEST_CASE("Booleans", "[boolean]") {
cxxopts::Options options("parses_floats", "parses floats correctly");
options.add_options()
("bool", "A Boolean", cxxopts::value<bool>())
("debug", "Debugging", cxxopts::value<bool>())
("timing", "Timing", cxxopts::value<bool>())
("others", "Other arguments", cxxopts::value<std::vector<std::string>>())
;
options.parse_positional("others");
Argv av({"booleans", "--bool=false", "--debug", "true", "--timing", "extra"});
char** argv = av.argv();
auto argc = av.argc();
auto result = options.parse(argc, argv);
REQUIRE(result.count("bool") == 1);
REQUIRE(result.count("debug") == 1);
REQUIRE(result.count("timing") == 1);
CHECK(result["bool"].as<bool>() == false);
CHECK(result["debug"].as<bool>() == true);
CHECK(result["timing"].as<bool>() == true);
REQUIRE(result.count("others") == 1);
}
<|endoftext|>
|
<commit_before>#include "sys_local.h"
#define RAPTURE_DEFAULT_PORT 1750
#define RAPTURE_DEFAULT_BACKLOG 32
#define RAPTURE_DEFAULT_MAXCLIENTS 8
#define RAPTURE_NETPROTOCOL 0
namespace Network {
using namespace ClientPacket;
enum Netmode_e {
Netmode_Red, // No connections allowed on the server, and any current connections are terminated
Netmode_Yellow, // No new connections allowed, current connections aren't terminated
Netmode_Green, // Anything goes
};
enum Netstate_e {
Netstate_NoConnect, // Not connected to any network, not listening
Netstate_Listen, // Listening
Netstate_NeedAuth, // Connected to a server, need authorization packet
Netstate_Authorized, // Connected to a server and authorized
};
static Cvar* net_port = nullptr;
static Cvar* net_serverbacklog = nullptr;
static Cvar* net_maxclients = nullptr;
static Cvar* net_netmode = nullptr;
static Socket* localSocket = nullptr;
static map<int, Socket*> mOtherConnectedClients;
static Socket* remoteSocket = nullptr;
static vector<Packet> vPacketsAwaitingSend; // Goes in both directions
static Netstate_e currentNetState = Netstate_NoConnect;
static vector<Socket*> vTemporaryConnections;
static int numConnectedClients = 1;
static int myClientNum = 0; // Client 0 is always the host
static int lastFreeClientNum = 1;
RaptureGame* sys = nullptr;
void Netmode_Callback(int newValue) {
if (newValue == Netmode_Red) {
mOtherConnectedClients.clear();
numConnectedClients = 1;
}
}
// Initialize the network
void Init() {
Zone::NewTag("network");
net_port = Cvar::Get<int>("net_port", "Port used for networking (TCP)", (1 << CVAR_ARCHIVE), RAPTURE_DEFAULT_PORT);
net_serverbacklog
= Cvar::Get<int>("net_serverbacklog", "Maximum number of waiting connections for the server", (1 << CVAR_ARCHIVE), RAPTURE_DEFAULT_BACKLOG);
net_maxclients = Cvar::Get<int>("net_maxclients", "Maximum number of clients allowed on server", (1 << CVAR_ROM) | (1 << CVAR_ARCHIVE), RAPTURE_DEFAULT_MAXCLIENTS);
net_netmode = Cvar::Get<int>("net_netmode", "Current netmode", 0, Netmode_Red);
net_netmode->AddCallback(Netmode_Callback);
Sys_InitSockets();
// Create a local socket so we can serve as the host later
localSocket = new Socket(AF_INET6, SOCK_STREAM);
}
// Shut down the network, delete the local socket, disconnect any clients, etc.
void Shutdown() {
delete localSocket;
Sys_ExitSockets();
}
// Dispatches a single packet that's been sent to us from the server
void DispatchSingleServerPacket(Packet& packet) {
switch (packet.packetHead.type) {
case PACKET_CLIENTACCEPT:
{
// We have been accepted into the server
ClientAcceptPacket* cPacket = (ClientAcceptPacket*)(packet.packetData);
myClientNum = cPacket->clientNum;
currentNetState = Netstate_Authorized;
}
return;
case PACKET_CLIENTDENIED:
{
// We have been denied from the server
ClientDeniedPacket* cPacket = (ClientDeniedPacket*)(packet.packetData);
R_Message(PRIORITY_MESSAGE, "Denied entry from server: %s\n", cPacket->why);
currentNetState = Netstate_NoConnect;
}
return;
case PACKET_PING:
{
R_Message(PRIORITY_DEBUG, "Server PONG");
}
return;
}
if (sys && sys->trap) {
sys->trap->interpretPacketFromServer(&packet);
}
}
// Dispatches a single packet that's been sent to us from the client
void DispatchSingleClientPacket(Packet& packet) {
switch (packet.packetHead.type) {
case PACKET_PING:
R_Message(PRIORITY_DEBUG, "Server PING from %i\n", packet.packetHead.clientNum);
SendServerPacketTo(PACKET_PING, packet.packetHead.clientNum, nullptr, 0);
return;
}
if (sys && sys->trap) {
sys->trap->interpretPacketFromClient(&packet);
}
}
// Check for new incoming temporary connections
void CheckTemporaryConnections() {
Socket* newConnection = localSocket->CheckPendingConnections();
if (newConnection != nullptr) {
vTemporaryConnections.push_back(newConnection);
}
vector<Socket*> readReady, writeReady; // WriteReady is not actually used in this case
Socket::Select(vTemporaryConnections, readReady, writeReady);
for (auto& socket : readReady) {
Packet incPacket;
socket->ReadPacket(incPacket);
Packet outPacket;
if (incPacket.packetHead.type == PACKET_CLIENTATTEMPT) {
if (sys && sys->trap && sys->trap->acceptclient((ClientAttemptPacket*)incPacket.packetData)) {
// Send an acceptance packet with the new client number. Also remove this socket from temporary read packets
outPacket.packetHead.clientNum = lastFreeClientNum++;
outPacket.packetHead.direction = Packet::PD_ServerClient;
outPacket.packetHead.sendTime = 0; // FIXME
outPacket.packetHead.type = PACKET_CLIENTACCEPT;
outPacket.packetHead.packetSize = 0; // FIXME
mOtherConnectedClients[outPacket.packetHead.clientNum] = socket;
}
else {
outPacket.packetHead.clientNum = -1;
outPacket.packetHead.direction = Packet::PD_ServerClient;
outPacket.packetHead.sendTime = 0; // FIXME
outPacket.packetHead.type = PACKET_CLIENTDENIED;
outPacket.packetHead.packetSize = 0; // FIXME
}
socket->SendPacket(outPacket);
}
}
}
// Run all of the server stuff
void ServerFrame() {
// Try listening for any temporary connections
CheckTemporaryConnections();
// Create list of sockets
vector<Socket*> vSockets = { localSocket };
for (auto it = mOtherConnectedClients.begin(); it != mOtherConnectedClients.end(); ++it) {
vSockets.push_back(it->second);
}
// Poll sockets
vector<Socket*> vSocketsRead, vSocketsWrite;
Socket::Select(vSockets, vSocketsRead, vSocketsWrite);
// Deal with sockets that need reading
for (auto& socket : vSocketsRead) {
vector<Packet> vPackets;
socket->ReadAllPackets(vPackets);
for (auto& packet : vPackets) {
DispatchSingleClientPacket(packet);
}
}
// Deal with sockets that need writing
for (auto& packet : vPacketsAwaitingSend) {
int8_t clientNum = packet.packetHead.clientNum;
if (clientNum != -1) {
auto found = mOtherConnectedClients.find(clientNum);
if (found == mOtherConnectedClients.end()) {
R_Message(PRIORITY_WARNING,
"Tried to send packet %i with bad client %i\n",
packet.packetHead.type,
packet.packetHead.clientNum);
continue;
}
found->second->SendPacket(packet);
}
else {
for (auto it = mOtherConnectedClients.begin(); it != mOtherConnectedClients.end(); ++it) {
it->second->SendPacket(packet);
}
DispatchSingleServerPacket(packet); // Don't forget to send to ourselves!
}
}
vPacketsAwaitingSend.clear();
if (sys && sys->trap) {
sys->trap->runserverframe();
}
}
// Run all of the client stuff
void ClientFrame() {
bool bRead, bWrite;
Socket::SelectSingle(remoteSocket, bRead, bWrite);
if (bRead) {
vector<Packet> vPackets;
localSocket->ReadAllPackets(vPackets);
for (auto& packet : vPackets) {
DispatchSingleServerPacket(packet);
}
}
if (bWrite) {
for (auto& packet : vPacketsAwaitingSend) {
localSocket->SendPacket(packet);
}
vPacketsAwaitingSend.clear();
}
if (sys && sys->trap) {
sys->trap->runclientframe();
}
}
// Start running the client
void StartRunningClient(const char* szSaveGame, RaptureGame* pGameModule) {
sys = pGameModule;
if (sys->trap != nullptr) {
sys->trap->startclientfromsave(szSaveGame);
}
}
// Start running the server
void StartRunningServer(const char* szSaveGame, RaptureGame* pGameModule) {
sys = pGameModule;
if (sys->trap != nullptr) {
sys->trap->startserverfromsave(szSaveGame);
}
}
// Start a local server
bool StartLocalServer(const char* szSaveGame, RaptureGame* pGameModule) {
if (!localSocket->StartListening(net_port->Integer(), net_serverbacklog->Integer())) {
return false;
}
StartRunningServer(szSaveGame, pGameModule);
StartRunningClient(szSaveGame, pGameModule);
return true;
}
// Join a remote server
bool JoinServer(const char* szSaveGame, const char* hostname, RaptureGame* pGameModule) {
if (!ConnectToRemote(hostname, net_port->Integer())) {
return false;
}
StartRunningClient(szSaveGame, pGameModule);
return true;
}
// Send a server packet to a single client
void SendServerPacketTo(packetType_e packetType, int clientNum, void* packetData, size_t packetDataSize) {
Packet packet = { { packetType, clientNum, Packet::PD_ServerClient, 0, packetDataSize }, packetData };
if (clientNum == myClientNum) {
DispatchSingleServerPacket(packet);
}
else {
auto it = mOtherConnectedClients.find(clientNum);
if (it == mOtherConnectedClients.end()) {
R_Message(PRIORITY_WARNING, "Tried to send a packet (%i) to invalid client %i\n", packetType, clientNum);
return;
}
else {
it->second->SendPacket(packet);
}
}
}
// Send packet from server -> client
void SendServerPacket(packetType_e packetType, int clientNum, void* packetData, size_t packetDataSize) {
if (clientNum != -1) {
SendServerPacketTo(packetType, clientNum, packetData, packetDataSize);
}
else for (auto it = mOtherConnectedClients.begin(); it != mOtherConnectedClients.end(); ++it) {
SendServerPacketTo(packetType, it->first, packetData, packetDataSize);
}
}
// Send packet from client -> server
void SendClientPacket(packetType_e packetType, void* packetData, size_t packetDataSize) {
// FIXME: use the correct timestamp
Packet packet = { { packetType, myClientNum, Packet::PD_ClientServer, 0, packetDataSize }, packetData };
if (remoteSocket == nullptr) {
// Not connected to a remote server, send it to ourselves instead
DispatchSingleClientPacket(packet);
}
else {
remoteSocket->SendPacket(packet);
}
}
// Determine if the local server is full.
bool LocalServerFull() {
return numConnectedClients >= net_maxclients->Integer();
}
void Connect(const char* hostname) {
int port = net_port->Integer();
R_Message(PRIORITY_MESSAGE, "Connecting to %s:%i\n", hostname, port);
if (ConnectToRemote(hostname, port)) {
R_Message(PRIORITY_MESSAGE, "Connection established.\n", hostname, port);
}
else {
R_Message(PRIORITY_MESSAGE, "Could not connect to %s:%i\n", hostname, port);
DisconnectFromRemote();
}
}
// Try and connect to a server
bool ConnectToRemote(const char* hostname, int port) {
DisconnectFromRemote();
remoteSocket = new Socket(AF_INET6, SOCK_STREAM);
bool connected = remoteSocket->Connect(hostname, port);
if (!connected) {
delete remoteSocket;
remoteSocket = nullptr;
}
currentNetState = Netstate_NeedAuth;
return connected;
}
// Disconnect from current remote server
void DisconnectFromRemote() {
if (currentNetState == Netstate_NoConnect) {
// Not connected in the first place
return;
}
if (sys && sys->trap) {
sys->trap->saveandexit();
}
if (remoteSocket != nullptr) {
delete remoteSocket;
remoteSocket = nullptr;
}
currentNetState = Netstate_NoConnect;
R_Message(PRIORITY_NOTE, "--- Disconnected ---\n");
}
}<commit_msg>Cleaned up DispatchSingleClient/ServerPacket.<commit_after>#include "sys_local.h"
#define RAPTURE_DEFAULT_PORT 1750
#define RAPTURE_DEFAULT_BACKLOG 32
#define RAPTURE_DEFAULT_MAXCLIENTS 8
#define RAPTURE_NETPROTOCOL 0
namespace Network {
using namespace ClientPacket;
enum Netmode_e {
Netmode_Red, // No connections allowed on the server, and any current connections are terminated
Netmode_Yellow, // No new connections allowed, current connections aren't terminated
Netmode_Green, // Anything goes
};
enum Netstate_e {
Netstate_NoConnect, // Not connected to any network, not listening
Netstate_Listen, // Listening
Netstate_NeedAuth, // Connected to a server, need authorization packet
Netstate_Authorized, // Connected to a server and authorized
};
static Cvar* net_port = nullptr;
static Cvar* net_serverbacklog = nullptr;
static Cvar* net_maxclients = nullptr;
static Cvar* net_netmode = nullptr;
static Cvar* net_timeout = nullptr;
static Socket* localSocket = nullptr;
static map<int, Socket*> mOtherConnectedClients;
static Socket* remoteSocket = nullptr;
static vector<Packet> vPacketsAwaitingSend; // Goes in both directions
static Netstate_e currentNetState = Netstate_NoConnect;
static vector<Socket*> vTemporaryConnections;
static int numConnectedClients = 1;
static int myClientNum = 0; // Client 0 is always the host
static int lastFreeClientNum = 1;
RaptureGame* sys = nullptr;
void Netmode_Callback(int newValue) {
if (newValue == Netmode_Red) {
mOtherConnectedClients.clear();
numConnectedClients = 1;
}
}
// Initialize the network
void Init() {
Zone::NewTag("network");
net_port = Cvar::Get<int>("net_port", "Port used for networking (TCP)", (1 << CVAR_ARCHIVE), RAPTURE_DEFAULT_PORT);
net_serverbacklog
= Cvar::Get<int>("net_serverbacklog", "Maximum number of waiting connections for the server", (1 << CVAR_ARCHIVE), RAPTURE_DEFAULT_BACKLOG);
net_maxclients = Cvar::Get<int>("net_maxclients", "Maximum number of clients allowed on server", (1 << CVAR_ROM) | (1 << CVAR_ARCHIVE), RAPTURE_DEFAULT_MAXCLIENTS);
net_netmode = Cvar::Get<int>("net_netmode", "Current netmode", 0, Netmode_Red);
net_timeout = Cvar::Get<int>("net_timeout", "Timeout duration, in milliseconds", 0, 30000);
net_netmode->AddCallback(Netmode_Callback);
Sys_InitSockets();
// Create a local socket so we can serve as the host later
localSocket = new Socket(AF_INET6, SOCK_STREAM);
}
// Shut down the network, delete the local socket, disconnect any clients, etc.
void Shutdown() {
delete localSocket;
Sys_ExitSockets();
}
// Dispatches a single packet that's been sent to us from the server
void DispatchSingleServerPacket(Packet& packet) {
switch (packet.packetHead.type) {
case PACKET_CLIENTACCEPT:
{
// We have been accepted into the server
ClientAcceptPacket* cPacket = (ClientAcceptPacket*)(packet.packetData);
R_Message(PRIORITY_MESSAGE, "Authorization successful");
myClientNum = cPacket->clientNum;
currentNetState = Netstate_Authorized;
}
break;
case PACKET_CLIENTDENIED:
{
// We have been denied from the server
ClientDeniedPacket* cPacket = (ClientDeniedPacket*)(packet.packetData);
R_Message(PRIORITY_MESSAGE, "Denied entry from server: %s\n", cPacket->why);
currentNetState = Netstate_NoConnect;
}
break;
case PACKET_PING:
{
R_Message(PRIORITY_DEBUG, "Server PONG");
}
break;
default:
if (!sys || !sys->trap || !sys->trap->interpretPacketFromServer(&packet)) {
R_Message(PRIORITY_WARNING, "Unknown packet type %i\n", packet.packetHead.type);
}
break;
}
}
// Dispatches a single packet that's been sent to us from the client
void DispatchSingleClientPacket(Packet& packet) {
switch (packet.packetHead.type) {
case PACKET_PING:
R_Message(PRIORITY_DEBUG, "Server PING from %i\n", packet.packetHead.clientNum);
SendServerPacketTo(PACKET_PING, packet.packetHead.clientNum, nullptr, 0);
break;
default:
if (!sys || !sys->trap || !sys->trap->interpretPacketFromClient(&packet)) {
R_Message(PRIORITY_WARNING, "Unknown packet type %i\n", packet.packetHead.type);
}
break;
}
}
// Check for new incoming temporary connections
void CheckTemporaryConnections() {
Socket* newConnection = localSocket->CheckPendingConnections();
if (newConnection != nullptr) {
vTemporaryConnections.push_back(newConnection);
}
vector<Socket*> readReady, writeReady; // WriteReady is not actually used in this case
Socket::Select(vTemporaryConnections, readReady, writeReady);
for (auto& socket : readReady) {
Packet incPacket;
socket->ReadPacket(incPacket);
Packet outPacket;
if (incPacket.packetHead.type == PACKET_CLIENTATTEMPT) {
if (sys && sys->trap && sys->trap->acceptclient((ClientAttemptPacket*)incPacket.packetData)) {
// Send an acceptance packet with the new client number. Also remove this socket from temporary read packets
outPacket.packetHead.clientNum = lastFreeClientNum++;
outPacket.packetHead.direction = Packet::PD_ServerClient;
outPacket.packetHead.sendTime = 0; // FIXME
outPacket.packetHead.type = PACKET_CLIENTACCEPT;
outPacket.packetHead.packetSize = 0; // FIXME
mOtherConnectedClients[outPacket.packetHead.clientNum] = socket;
}
else {
outPacket.packetHead.clientNum = -1;
outPacket.packetHead.direction = Packet::PD_ServerClient;
outPacket.packetHead.sendTime = 0; // FIXME
outPacket.packetHead.type = PACKET_CLIENTDENIED;
outPacket.packetHead.packetSize = 0; // FIXME
}
socket->SendPacket(outPacket);
}
}
}
// Run all of the server stuff
void ServerFrame() {
// Try listening for any temporary connections
CheckTemporaryConnections();
// Create list of sockets
vector<Socket*> vSockets = { localSocket };
for (auto it = mOtherConnectedClients.begin(); it != mOtherConnectedClients.end(); ++it) {
vSockets.push_back(it->second);
}
// Poll sockets
vector<Socket*> vSocketsRead, vSocketsWrite;
Socket::Select(vSockets, vSocketsRead, vSocketsWrite);
// Deal with sockets that need reading
for (auto& socket : vSocketsRead) {
vector<Packet> vPackets;
socket->ReadAllPackets(vPackets);
for (auto& packet : vPackets) {
DispatchSingleClientPacket(packet);
}
}
// Deal with sockets that need writing
for (auto& packet : vPacketsAwaitingSend) {
int8_t clientNum = packet.packetHead.clientNum;
if (clientNum != -1) {
auto found = mOtherConnectedClients.find(clientNum);
if (found == mOtherConnectedClients.end()) {
R_Message(PRIORITY_WARNING,
"Tried to send packet %i with bad client %i\n",
packet.packetHead.type,
packet.packetHead.clientNum);
continue;
}
found->second->SendPacket(packet);
}
else {
for (auto it = mOtherConnectedClients.begin(); it != mOtherConnectedClients.end(); ++it) {
it->second->SendPacket(packet);
}
DispatchSingleServerPacket(packet); // Don't forget to send to ourselves!
}
}
vPacketsAwaitingSend.clear();
if (sys && sys->trap) {
sys->trap->runserverframe();
}
}
// Run all of the client stuff
void ClientFrame() {
bool bRead, bWrite;
Socket::SelectSingle(remoteSocket, bRead, bWrite);
if (bRead) {
vector<Packet> vPackets;
localSocket->ReadAllPackets(vPackets);
for (auto& packet : vPackets) {
DispatchSingleServerPacket(packet);
}
}
if (bWrite) {
for (auto& packet : vPacketsAwaitingSend) {
localSocket->SendPacket(packet);
}
vPacketsAwaitingSend.clear();
}
if (sys && sys->trap) {
sys->trap->runclientframe();
}
}
// Start running the client
void StartRunningClient(const char* szSaveGame, RaptureGame* pGameModule) {
sys = pGameModule;
if (sys->trap != nullptr) {
sys->trap->startclientfromsave(szSaveGame);
}
}
// Start running the server
void StartRunningServer(const char* szSaveGame, RaptureGame* pGameModule) {
sys = pGameModule;
if (sys->trap != nullptr) {
sys->trap->startserverfromsave(szSaveGame);
}
}
// Start a local server
bool StartLocalServer(const char* szSaveGame, RaptureGame* pGameModule) {
if (!localSocket->StartListening(net_port->Integer(), net_serverbacklog->Integer())) {
return false;
}
StartRunningServer(szSaveGame, pGameModule);
StartRunningClient(szSaveGame, pGameModule);
return true;
}
// Join a remote server
bool JoinServer(const char* szSaveGame, const char* hostname, RaptureGame* pGameModule) {
if (!ConnectToRemote(hostname, net_port->Integer())) {
return false;
}
StartRunningClient(szSaveGame, pGameModule);
return true;
}
// Send a server packet to a single client
void SendServerPacketTo(packetType_e packetType, int clientNum, void* packetData, size_t packetDataSize) {
Packet packet = { { packetType, clientNum, Packet::PD_ServerClient, 0, packetDataSize }, packetData };
if (clientNum == myClientNum) {
DispatchSingleServerPacket(packet);
}
else {
auto it = mOtherConnectedClients.find(clientNum);
if (it == mOtherConnectedClients.end()) {
R_Message(PRIORITY_WARNING, "Tried to send a packet (%i) to invalid client %i\n", packetType, clientNum);
return;
}
else {
it->second->SendPacket(packet);
}
}
}
// Send packet from server -> client
void SendServerPacket(packetType_e packetType, int clientNum, void* packetData, size_t packetDataSize) {
if (clientNum != -1) {
SendServerPacketTo(packetType, clientNum, packetData, packetDataSize);
}
else for (auto it = mOtherConnectedClients.begin(); it != mOtherConnectedClients.end(); ++it) {
SendServerPacketTo(packetType, it->first, packetData, packetDataSize);
}
}
// Send packet from client -> server
void SendClientPacket(packetType_e packetType, void* packetData, size_t packetDataSize) {
// FIXME: use the correct timestamp
Packet packet = { { packetType, myClientNum, Packet::PD_ClientServer, 0, packetDataSize }, packetData };
if (remoteSocket == nullptr) {
// Not connected to a remote server, send it to ourselves instead
DispatchSingleClientPacket(packet);
}
else {
remoteSocket->SendPacket(packet);
}
}
// Determine if the local server is full.
bool LocalServerFull() {
return numConnectedClients >= net_maxclients->Integer();
}
void Connect(const char* hostname) {
int port = net_port->Integer();
R_Message(PRIORITY_MESSAGE, "Connecting to %s:%i\n", hostname, port);
if (ConnectToRemote(hostname, port)) {
R_Message(PRIORITY_MESSAGE, "Connection established.\n", hostname, port);
}
else {
R_Message(PRIORITY_MESSAGE, "Could not connect to %s:%i\n", hostname, port);
DisconnectFromRemote();
}
}
// Try and connect to a server
bool ConnectToRemote(const char* hostname, int port) {
DisconnectFromRemote();
remoteSocket = new Socket(AF_INET6, SOCK_STREAM);
bool connected = remoteSocket->Connect(hostname, port);
if (!connected) {
delete remoteSocket;
remoteSocket = nullptr;
}
currentNetState = Netstate_NeedAuth;
return connected;
}
// Disconnect from current remote server
void DisconnectFromRemote() {
if (currentNetState == Netstate_NoConnect) {
// Not connected in the first place
return;
}
if (sys && sys->trap) {
sys->trap->saveandexit();
}
if (remoteSocket != nullptr) {
delete remoteSocket;
remoteSocket = nullptr;
}
currentNetState = Netstate_NoConnect;
R_Message(PRIORITY_NOTE, "--- Disconnected ---\n");
}
}<|endoftext|>
|
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <complex>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using af::cfloat;
using af::cdouble;
template<typename T>
class Reorder : public ::testing::Test
{
public:
virtual void SetUp() {
subMat0.push_back(af_make_seq(0, 4, 1));
subMat0.push_back(af_make_seq(2, 6, 1));
subMat0.push_back(af_make_seq(0, 2, 1));
}
vector<af_seq> subMat0;
};
// create a list of types to be tested
typedef ::testing::Types<float, double, cfloat, cdouble, int, unsigned int, char, unsigned char, short, ushort> TestTypes;
// register the type list
TYPED_TEST_CASE(Reorder, TestTypes);
template<typename T>
void reorderTest(string pTestFile, const unsigned resultIdx,
const uint x, const uint y, const uint z, const uint w,
bool isSubRef = false, const vector<af_seq> * seqv = NULL)
{
if (noDoubleTests<T>()) return;
vector<af::dim4> numDims;
vector<vector<T> > in;
vector<vector<T> > tests;
readTests<T, T, int>(pTestFile,numDims,in,tests);
af::dim4 idims = numDims[0];
af_array inArray = 0;
af_array outArray = 0;
af_array tempArray = 0;
if (isSubRef) {
ASSERT_EQ(AF_SUCCESS, af_create_array(&tempArray, &(in[0].front()), idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type));
ASSERT_EQ(AF_SUCCESS, af_index(&inArray, tempArray, seqv->size(), &seqv->front()));
} else {
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type));
}
ASSERT_EQ(AF_SUCCESS, af_reorder(&outArray, inArray, x, y, z, w));
// Get result
T* outData = new T[tests[resultIdx].size()];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));
// Compare result
size_t nElems = tests[resultIdx].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(tests[resultIdx][elIter], outData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] outData;
if(inArray != 0) af_release_array(inArray);
if(outArray != 0) af_release_array(outArray);
if(tempArray != 0) af_release_array(tempArray);
}
#define REORDER_INIT(desc, file, resultIdx, x, y, z, w) \
TYPED_TEST(Reorder, desc) \
{ \
reorderTest<TypeParam>(string(TEST_DIR"/reorder/"#file".test"), resultIdx, x, y, z, w); \
}
REORDER_INIT(Reorder012, reorder, 0, 0, 1, 2, 3);
REORDER_INIT(Reorder021, reorder, 1, 0, 2, 1, 3);
REORDER_INIT(Reorder102, reorder, 2, 1, 0, 2, 3);
REORDER_INIT(Reorder120, reorder, 3, 1, 2, 0, 3);
REORDER_INIT(Reorder201, reorder, 4, 2, 0, 1, 3);
REORDER_INIT(Reorder210, reorder, 5, 2, 1, 0, 3);
REORDER_INIT(Reorder0123, reorder4d, 0, 0, 1, 2, 3);
REORDER_INIT(Reorder0132, reorder4d, 1, 0, 1, 3, 2);
REORDER_INIT(Reorder0213, reorder4d, 2, 0, 2, 1, 3);
REORDER_INIT(Reorder0231, reorder4d, 3, 0, 2, 3, 1);
REORDER_INIT(Reorder0312, reorder4d, 4, 0, 3, 1, 2);
REORDER_INIT(Reorder0321, reorder4d, 5, 0, 3, 2, 1);
REORDER_INIT(Reorder1023, reorder4d, 6, 1, 0, 2, 3);
REORDER_INIT(Reorder1032, reorder4d, 7, 1, 0, 3, 2);
REORDER_INIT(Reorder1203, reorder4d, 8, 1, 2, 0, 3);
REORDER_INIT(Reorder1230, reorder4d, 9, 1, 2, 3, 0);
REORDER_INIT(Reorder1302, reorder4d,10, 1, 3, 0, 2);
REORDER_INIT(Reorder1320, reorder4d,11, 1, 3, 2, 0);
REORDER_INIT(Reorder2103, reorder4d,12, 2, 1, 0, 3);
REORDER_INIT(Reorder2130, reorder4d,13, 2, 1, 3, 0);
REORDER_INIT(Reorder2013, reorder4d,14, 2, 0, 1, 3);
REORDER_INIT(Reorder2031, reorder4d,15, 2, 0, 3, 1);
REORDER_INIT(Reorder2310, reorder4d,16, 2, 3, 1, 0);
REORDER_INIT(Reorder2301, reorder4d,17, 2, 3, 0, 1);
REORDER_INIT(Reorder3120, reorder4d,18, 3, 1, 2, 0);
REORDER_INIT(Reorder3102, reorder4d,19, 3, 1, 0, 2);
REORDER_INIT(Reorder3210, reorder4d,20, 3, 2, 1, 0);
REORDER_INIT(Reorder3201, reorder4d,21, 3, 2, 0, 1);
REORDER_INIT(Reorder3012, reorder4d,22, 3, 0, 1, 2);
REORDER_INIT(Reorder3021, reorder4d,23, 3, 0, 2, 1);
////////////////////////////////// CPP ///////////////////////////////////
//
TEST(Reorder, CPP)
{
if (noDoubleTests<float>()) return;
const unsigned resultIdx = 0;
const unsigned x = 0;
const unsigned y = 1;
const unsigned z = 2;
const unsigned w = 3;
vector<af::dim4> numDims;
vector<vector<float> > in;
vector<vector<float> > tests;
readTests<float, float, int>(string(TEST_DIR"/reorder/reorder4d.test"),numDims,in,tests);
af::dim4 idims = numDims[0];
af::array input(idims, &(in[0].front()));
af::array output = af::reorder(input, x, y, z, w);
// Get result
float* outData = new float[tests[resultIdx].size()];
output.host((void*)outData);
// Compare result
size_t nElems = tests[resultIdx].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(tests[resultIdx][elIter], outData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] outData;
}
<commit_msg>Adding tests for reorder after tile<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <complex>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using af::cfloat;
using af::cdouble;
template<typename T>
class Reorder : public ::testing::Test
{
public:
virtual void SetUp() {
subMat0.push_back(af_make_seq(0, 4, 1));
subMat0.push_back(af_make_seq(2, 6, 1));
subMat0.push_back(af_make_seq(0, 2, 1));
}
vector<af_seq> subMat0;
};
// create a list of types to be tested
typedef ::testing::Types<float, double, cfloat, cdouble, int, unsigned int, char, unsigned char, short, ushort> TestTypes;
// register the type list
TYPED_TEST_CASE(Reorder, TestTypes);
template<typename T>
void reorderTest(string pTestFile, const unsigned resultIdx,
const uint x, const uint y, const uint z, const uint w,
bool isSubRef = false, const vector<af_seq> * seqv = NULL)
{
if (noDoubleTests<T>()) return;
vector<af::dim4> numDims;
vector<vector<T> > in;
vector<vector<T> > tests;
readTests<T, T, int>(pTestFile,numDims,in,tests);
af::dim4 idims = numDims[0];
af_array inArray = 0;
af_array outArray = 0;
af_array tempArray = 0;
if (isSubRef) {
ASSERT_EQ(AF_SUCCESS, af_create_array(&tempArray, &(in[0].front()), idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type));
ASSERT_EQ(AF_SUCCESS, af_index(&inArray, tempArray, seqv->size(), &seqv->front()));
} else {
ASSERT_EQ(AF_SUCCESS, af_create_array(&inArray, &(in[0].front()), idims.ndims(), idims.get(), (af_dtype) af::dtype_traits<T>::af_type));
}
ASSERT_EQ(AF_SUCCESS, af_reorder(&outArray, inArray, x, y, z, w));
// Get result
T* outData = new T[tests[resultIdx].size()];
ASSERT_EQ(AF_SUCCESS, af_get_data_ptr((void*)outData, outArray));
// Compare result
size_t nElems = tests[resultIdx].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(tests[resultIdx][elIter], outData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] outData;
if(inArray != 0) af_release_array(inArray);
if(outArray != 0) af_release_array(outArray);
if(tempArray != 0) af_release_array(tempArray);
}
#define REORDER_INIT(desc, file, resultIdx, x, y, z, w) \
TYPED_TEST(Reorder, desc) \
{ \
reorderTest<TypeParam>(string(TEST_DIR"/reorder/"#file".test"), resultIdx, x, y, z, w); \
}
REORDER_INIT(Reorder012, reorder, 0, 0, 1, 2, 3);
REORDER_INIT(Reorder021, reorder, 1, 0, 2, 1, 3);
REORDER_INIT(Reorder102, reorder, 2, 1, 0, 2, 3);
REORDER_INIT(Reorder120, reorder, 3, 1, 2, 0, 3);
REORDER_INIT(Reorder201, reorder, 4, 2, 0, 1, 3);
REORDER_INIT(Reorder210, reorder, 5, 2, 1, 0, 3);
REORDER_INIT(Reorder0123, reorder4d, 0, 0, 1, 2, 3);
REORDER_INIT(Reorder0132, reorder4d, 1, 0, 1, 3, 2);
REORDER_INIT(Reorder0213, reorder4d, 2, 0, 2, 1, 3);
REORDER_INIT(Reorder0231, reorder4d, 3, 0, 2, 3, 1);
REORDER_INIT(Reorder0312, reorder4d, 4, 0, 3, 1, 2);
REORDER_INIT(Reorder0321, reorder4d, 5, 0, 3, 2, 1);
REORDER_INIT(Reorder1023, reorder4d, 6, 1, 0, 2, 3);
REORDER_INIT(Reorder1032, reorder4d, 7, 1, 0, 3, 2);
REORDER_INIT(Reorder1203, reorder4d, 8, 1, 2, 0, 3);
REORDER_INIT(Reorder1230, reorder4d, 9, 1, 2, 3, 0);
REORDER_INIT(Reorder1302, reorder4d,10, 1, 3, 0, 2);
REORDER_INIT(Reorder1320, reorder4d,11, 1, 3, 2, 0);
REORDER_INIT(Reorder2103, reorder4d,12, 2, 1, 0, 3);
REORDER_INIT(Reorder2130, reorder4d,13, 2, 1, 3, 0);
REORDER_INIT(Reorder2013, reorder4d,14, 2, 0, 1, 3);
REORDER_INIT(Reorder2031, reorder4d,15, 2, 0, 3, 1);
REORDER_INIT(Reorder2310, reorder4d,16, 2, 3, 1, 0);
REORDER_INIT(Reorder2301, reorder4d,17, 2, 3, 0, 1);
REORDER_INIT(Reorder3120, reorder4d,18, 3, 1, 2, 0);
REORDER_INIT(Reorder3102, reorder4d,19, 3, 1, 0, 2);
REORDER_INIT(Reorder3210, reorder4d,20, 3, 2, 1, 0);
REORDER_INIT(Reorder3201, reorder4d,21, 3, 2, 0, 1);
REORDER_INIT(Reorder3012, reorder4d,22, 3, 0, 1, 2);
REORDER_INIT(Reorder3021, reorder4d,23, 3, 0, 2, 1);
////////////////////////////////// CPP ///////////////////////////////////
//
TEST(Reorder, CPP)
{
const unsigned resultIdx = 0;
const unsigned x = 0;
const unsigned y = 1;
const unsigned z = 2;
const unsigned w = 3;
vector<af::dim4> numDims;
vector<vector<float> > in;
vector<vector<float> > tests;
readTests<float, float, int>(string(TEST_DIR"/reorder/reorder4d.test"),numDims,in,tests);
af::dim4 idims = numDims[0];
af::array input(idims, &(in[0].front()));
af::array output = af::reorder(input, x, y, z, w);
// Get result
float* outData = new float[tests[resultIdx].size()];
output.host((void*)outData);
// Compare result
size_t nElems = tests[resultIdx].size();
for (size_t elIter = 0; elIter < nElems; ++elIter) {
ASSERT_EQ(tests[resultIdx][elIter], outData[elIter]) << "at: " << elIter << std::endl;
}
// Delete
delete[] outData;
}
TEST(Reorder, ISSUE_1777)
{
const int m = 5;
const int n = 4;
const int k = 3;
vector<float> h_input(m * n);
for (int i = 0; i < m * n; i++) {
h_input[i] = (float)(i);
}
af::array a(m, n, &h_input[0]);
af::array a_t = af::tile(a, 1, 1, 3);
af::array a_r = af::reorder(a_t, 0, 2, 1);
vector<float> h_output(m * n * k);
a_r.host((void *)&h_output[0]);
for (int z = 0; z < n; z++) {
for (int y = 0; y < k; y++) {
for (int x = 0; x < m; x++) {
ASSERT_EQ(h_output[z * k * m + y * m + x], h_input[z * m + x]);
}
}
}
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/pqxx>
#include <pqxx/compiler-internal.hxx>
using namespace PGSTD;
using namespace pqxx;
namespace
{
#ifndef PQXX_HAVE_DISTANCE
template<typename ITERATOR> size_t distance(ITERATOR begin, ITERATOR end)
{
size_t d = 0;
while (begin != end)
{
++begin;
++d;
}
return d;
}
#endif // PQXX_HAVE_DISTANCE
void compare_results(string name, result lhs, result rhs)
{
if (lhs != rhs)
throw logic_error("Executing " + name + " as prepared statement "
"yields different results from direct execution");
if (lhs.empty())
throw logic_error("Results being compared are empty. Not much point!");
}
string stringize(transaction_base &t, const string &arg)
{
return "'" + t.esc(arg) + "'";
}
string stringize(transaction_base &t, const char arg[])
{
return arg ? stringize(t,string(arg)) : "null";
}
string stringize(transaction_base &t, char arg[])
{
return arg ? stringize(t, string(arg)) : "null";
}
template<typename T> string stringize(transaction_base &t, T i)
{
return stringize(t, to_string(i));
}
// Substitute variables in raw query. This is not likely to be very robust,
// but it should do for just this test. The main shortcomings are escaping,
// and not knowing when to quote the variables.
// Note we do the replacement backwards (meaning forward_only iterators won't
// do!) to avoid substituting e.g. "$12" as "$1" first.
template<typename ITER> string subst(transaction_base &t,
string q,
ITER patbegin,
ITER patend)
{
int i = distance(patbegin, patend);
for (ITER arg = patend; i > 0; --i)
{
--arg;
const string marker = "$" + to_string(i),
var = stringize(t, *arg);
const string::size_type msz = marker.size();
while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var);
}
return q;
}
template<typename CNTNR> string subst(transaction_base &t,
string q,
const CNTNR &patterns)
{
return subst(t, q, patterns.begin(), patterns.end());
}
} // namespace
// Test program for libpqxx. Define and use prepared statements.
//
// Usage: test085
int main()
{
try
{
/* A bit of nastiness in prepared statements: on 7.3.x backends we can't
* compare pg_tables.tablename to a string. We work around this by using
* the LIKE operator.
*
* Later backend versions do not suffer from this problem.
*/
const string QN_readpgtables = "ReadPGTables",
Q_readpgtables = "SELECT * FROM pg_tables",
QN_seetable = "SeeTable",
Q_seetable = Q_readpgtables + " WHERE tablename LIKE $1",
QN_seetables = "SeeTables",
Q_seetables = Q_seetable + " OR tablename LIKE $2";
lazyconnection C;
cout << "Preparing a simple statement..." << endl;
C.prepare(QN_readpgtables, Q_readpgtables);
nontransaction T(C, "test85");
try
{
// See if a basic prepared statement works just like a regular query
cout << "Basic correctness check on prepared statement..." << endl;
compare_results(QN_readpgtables,
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
}
catch (const exception &)
{
if (!C.supports(connection_base::cap_prepared_statements))
{
cout << "Backend version does not support prepared statements. "
"Skipping."
<< endl;
return 0;
}
throw;
}
// Try prepare_now() on an already prepared statement
C.prepare_now(QN_readpgtables);
// Pro forma check: same thing but with name passed as C-style string
compare_results(QN_readpgtables+"_char",
T.prepared(QN_readpgtables.c_str()).exec(),
T.exec(Q_readpgtables));
cout << "Dropping prepared statement..." << endl;
C.unprepare(QN_readpgtables);
bool failed = true;
try
{
disable_noticer d(C);
C.prepare_now(QN_readpgtables);
failed = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failed)
throw runtime_error("prepare_now() succeeded on dropped statement");
// Just to try and confuse things, "unprepare" twice
cout << "Testing error detection and handling..." << endl;
try { C.unprepare(QN_readpgtables); }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
// Verify that attempt to execute unprepared statement fails
bool failsOK = true;
try { T.prepared(QN_readpgtables).exec(); failsOK = false; }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
if (!failsOK) throw logic_error("Execute unprepared statement didn't fail");
// Re-prepare the same statement and test again
C.prepare(QN_readpgtables, Q_readpgtables);
C.prepare_now(QN_readpgtables);
compare_results(QN_readpgtables+"_2",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// Double preparation of identical statement should be ignored...
C.prepare(QN_readpgtables, Q_readpgtables);
compare_results(QN_readpgtables+"_double",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// ...But a modified definition shouldn't
try
{
failsOK = true;
C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename");
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("Bad redefinition of statement went unnoticed");
cout << "Testing prepared statement with parameter..." << endl;
C.prepare(QN_seetable, Q_seetable)("varchar", pqxx::prepare::treat_string);
vector<string> args;
args.push_back("pg_type");
compare_results(QN_seetable+"_seq",
T.prepared(QN_seetable)(args[0]).exec(),
T.exec(subst(T,Q_seetable,args)));
cout << "Testing prepared statement with 2 parameters..." << endl;
C.prepare(QN_seetables, Q_seetables)
("varchar",pqxx::prepare::treat_string)
("varchar",pqxx::prepare::treat_string);
args.push_back("pg_index");
compare_results(QN_seetables+"_seq",
T.prepared(QN_seetables)(args[0])(args[1]).exec(),
T.exec(subst(T,Q_seetables,args)));
cout << "Testing prepared statement with a null parameter..." << endl;
vector<const char *> ptrs;
ptrs.push_back(0);
ptrs.push_back("pg_index");
compare_results(QN_seetables+"_null1",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.exec(subst(T,Q_seetables,ptrs)));
compare_results(QN_seetables+"_null2",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)()(ptrs[1]).exec());
compare_results(QN_seetables+"_null3",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)("somestring",false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null4",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(42,false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null5",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(0,false)(ptrs[1]).exec());
cout << "Testing wrong numbers of parameters..." << endl;
try
{
failsOK = true;
T.prepared(QN_seetables)()()("hi mom!").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too many parameters");
try
{
failsOK = true;
T.prepared(QN_seetables)("who, me?").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too few parameters");
cout << "Done." << endl;
}
catch (const feature_not_supported &e)
{
cout << "Backend version does not support prepared statements. Skipping."
<< endl;
return 0;
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<commit_msg>Put compiler-internal include in a better place.<commit_after>#include <cassert>
#include <iostream>
#include <list>
#include <pqxx/compiler-internal.hxx>
#include <pqxx/pqxx>
using namespace PGSTD;
using namespace pqxx;
namespace
{
#ifndef PQXX_HAVE_DISTANCE
template<typename ITERATOR> size_t distance(ITERATOR begin, ITERATOR end)
{
size_t d = 0;
while (begin != end)
{
++begin;
++d;
}
return d;
}
#endif // PQXX_HAVE_DISTANCE
void compare_results(string name, result lhs, result rhs)
{
if (lhs != rhs)
throw logic_error("Executing " + name + " as prepared statement "
"yields different results from direct execution");
if (lhs.empty())
throw logic_error("Results being compared are empty. Not much point!");
}
string stringize(transaction_base &t, const string &arg)
{
return "'" + t.esc(arg) + "'";
}
string stringize(transaction_base &t, const char arg[])
{
return arg ? stringize(t,string(arg)) : "null";
}
string stringize(transaction_base &t, char arg[])
{
return arg ? stringize(t, string(arg)) : "null";
}
template<typename T> string stringize(transaction_base &t, T i)
{
return stringize(t, to_string(i));
}
// Substitute variables in raw query. This is not likely to be very robust,
// but it should do for just this test. The main shortcomings are escaping,
// and not knowing when to quote the variables.
// Note we do the replacement backwards (meaning forward_only iterators won't
// do!) to avoid substituting e.g. "$12" as "$1" first.
template<typename ITER> string subst(transaction_base &t,
string q,
ITER patbegin,
ITER patend)
{
int i = distance(patbegin, patend);
for (ITER arg = patend; i > 0; --i)
{
--arg;
const string marker = "$" + to_string(i),
var = stringize(t, *arg);
const string::size_type msz = marker.size();
while (q.find(marker) != string::npos) q.replace(q.find(marker),msz,var);
}
return q;
}
template<typename CNTNR> string subst(transaction_base &t,
string q,
const CNTNR &patterns)
{
return subst(t, q, patterns.begin(), patterns.end());
}
} // namespace
// Test program for libpqxx. Define and use prepared statements.
//
// Usage: test085
int main()
{
try
{
/* A bit of nastiness in prepared statements: on 7.3.x backends we can't
* compare pg_tables.tablename to a string. We work around this by using
* the LIKE operator.
*
* Later backend versions do not suffer from this problem.
*/
const string QN_readpgtables = "ReadPGTables",
Q_readpgtables = "SELECT * FROM pg_tables",
QN_seetable = "SeeTable",
Q_seetable = Q_readpgtables + " WHERE tablename LIKE $1",
QN_seetables = "SeeTables",
Q_seetables = Q_seetable + " OR tablename LIKE $2";
lazyconnection C;
cout << "Preparing a simple statement..." << endl;
C.prepare(QN_readpgtables, Q_readpgtables);
nontransaction T(C, "test85");
try
{
// See if a basic prepared statement works just like a regular query
cout << "Basic correctness check on prepared statement..." << endl;
compare_results(QN_readpgtables,
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
}
catch (const exception &)
{
if (!C.supports(connection_base::cap_prepared_statements))
{
cout << "Backend version does not support prepared statements. "
"Skipping."
<< endl;
return 0;
}
throw;
}
// Try prepare_now() on an already prepared statement
C.prepare_now(QN_readpgtables);
// Pro forma check: same thing but with name passed as C-style string
compare_results(QN_readpgtables+"_char",
T.prepared(QN_readpgtables.c_str()).exec(),
T.exec(Q_readpgtables));
cout << "Dropping prepared statement..." << endl;
C.unprepare(QN_readpgtables);
bool failed = true;
try
{
disable_noticer d(C);
C.prepare_now(QN_readpgtables);
failed = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failed)
throw runtime_error("prepare_now() succeeded on dropped statement");
// Just to try and confuse things, "unprepare" twice
cout << "Testing error detection and handling..." << endl;
try { C.unprepare(QN_readpgtables); }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
// Verify that attempt to execute unprepared statement fails
bool failsOK = true;
try { T.prepared(QN_readpgtables).exec(); failsOK = false; }
catch (const exception &e) { cout << "(Expected) " << e.what() << endl; }
if (!failsOK) throw logic_error("Execute unprepared statement didn't fail");
// Re-prepare the same statement and test again
C.prepare(QN_readpgtables, Q_readpgtables);
C.prepare_now(QN_readpgtables);
compare_results(QN_readpgtables+"_2",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// Double preparation of identical statement should be ignored...
C.prepare(QN_readpgtables, Q_readpgtables);
compare_results(QN_readpgtables+"_double",
T.prepared(QN_readpgtables).exec(),
T.exec(Q_readpgtables));
// ...But a modified definition shouldn't
try
{
failsOK = true;
C.prepare(QN_readpgtables, Q_readpgtables + " ORDER BY tablename");
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("Bad redefinition of statement went unnoticed");
cout << "Testing prepared statement with parameter..." << endl;
C.prepare(QN_seetable, Q_seetable)("varchar", pqxx::prepare::treat_string);
vector<string> args;
args.push_back("pg_type");
compare_results(QN_seetable+"_seq",
T.prepared(QN_seetable)(args[0]).exec(),
T.exec(subst(T,Q_seetable,args)));
cout << "Testing prepared statement with 2 parameters..." << endl;
C.prepare(QN_seetables, Q_seetables)
("varchar",pqxx::prepare::treat_string)
("varchar",pqxx::prepare::treat_string);
args.push_back("pg_index");
compare_results(QN_seetables+"_seq",
T.prepared(QN_seetables)(args[0])(args[1]).exec(),
T.exec(subst(T,Q_seetables,args)));
cout << "Testing prepared statement with a null parameter..." << endl;
vector<const char *> ptrs;
ptrs.push_back(0);
ptrs.push_back("pg_index");
compare_results(QN_seetables+"_null1",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.exec(subst(T,Q_seetables,ptrs)));
compare_results(QN_seetables+"_null2",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)()(ptrs[1]).exec());
compare_results(QN_seetables+"_null3",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)("somestring",false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null4",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(42,false)(ptrs[1]).exec());
compare_results(QN_seetables+"_null5",
T.prepared(QN_seetables)(ptrs[0])(ptrs[1]).exec(),
T.prepared(QN_seetables)(0,false)(ptrs[1]).exec());
cout << "Testing wrong numbers of parameters..." << endl;
try
{
failsOK = true;
T.prepared(QN_seetables)()()("hi mom!").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too many parameters");
try
{
failsOK = true;
T.prepared(QN_seetables)("who, me?").exec();
failsOK = false;
}
catch (const exception &e)
{
cout << "(Expected) " << e.what() << endl;
}
if (!failsOK)
throw logic_error("No error for too few parameters");
cout << "Done." << endl;
}
catch (const feature_not_supported &e)
{
cout << "Backend version does not support prepared statements. Skipping."
<< endl;
return 0;
}
catch (const sql_error &e)
{
cerr << "SQL error: " << e.what() << endl
<< "Query was: " << e.query() << endl;
return 1;
}
catch (const exception &e)
{
// All exceptions thrown by libpqxx are derived from std::exception
cerr << "Exception: " << e.what() << endl;
return 2;
}
catch (...)
{
// This is really unexpected (see above)
cerr << "Unhandled exception" << endl;
return 100;
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vpp/core/image2d.hh>
#include <vpp/core/pyramid.hh>
int main()
{
using namespace vpp;
image2d<vint1> img(4, 4);
int s1[] = {
1,2,3,4,
5,6,7,8,
9,10,11,12,
13,14,15,16
};
int s2[] = {
(1+2+5+6)/4, (3+4+7+8)/4,
(9+10+13+14)/4, (11+12+15+16)/4
};
int i = 0;
for (vint1& p : img) p[0] = s1[i++];
pyramid2d<vint1> pyramid(img.domain(), 2, 2);
assert(pyramid.factor() == 2);
assert(pyramid.levels().size() == 2);
assert(pyramid.levels()[0].domain() == img.domain());
assert(pyramid.levels()[1].domain() == make_box2d(2, 2));
pyramid.update(img);
i = 0;
for (const vint1& p : pyramid.levels()[1])
{
assert(p[0] == s2[i++]);
}
}
<commit_msg>Remove the deprecated pyramid test.<commit_after>#include <iostream>
#include <vpp/core/image2d.hh>
#include <vpp/core/pyramid.hh>
int main()
{
using namespace vpp;
image2d<vint1> img(4, 4);
// Todo.
}
<|endoftext|>
|
<commit_before>#include "keyword.hh"
#include <array>
#include <cassert>
using namespace std;
namespace {
struct Entry {
Keyword k;
const char* str;
};
static constexpr
array<Entry, static_cast<int>(Keyword::MAX)+1>
keyword_table{{
{ Keyword::not_keyword, "\0" },
{ Keyword::else_, "else" },
{ Keyword::r_arrow, "=>" },
{ Keyword::define, "define" },
{ Keyword::unquote, "unquote" },
{ Keyword::unquote_splicing, "unquote-splicing" },
{ Keyword::quote, "quote" },
{ Keyword::lambda, "lambda" },
{ Keyword::if_, "if" },
{ Keyword::set_, "set!" },
{ Keyword::begin, "begin" },
{ Keyword::cond, "cond" },
{ Keyword::and_, "and" },
{ Keyword::or_, "or" },
{ Keyword::case_, "case" },
{ Keyword::let, "let" },
{ Keyword::let_star, "let*" },
{ Keyword::letrec, "letrec" },
{ Keyword::do_, "do" },
{ Keyword::delay, "delay" },
{ Keyword::quasiquote, "quasiquote" },
{ Keyword::MAX, nullptr }
}};
} // namespace
const char* stringify(Keyword k){
auto& e = keyword_table.at(static_cast<int>(k));
assert(e.k == k);
return e.str;
}
Keyword to_keyword(const std::string& s){
#if 0
for(const auto& e : keyword_table){
if(s == e.str)
return e.k;
}
return Keyword::not_keyword;
#else
if(s.empty())
return Keyword::not_keyword;
Keyword ret = Keyword::not_keyword;
switch(s[0]){
case '=':
if(s.compare(1, string::npos, ">") == 0)
ret = Keyword::r_arrow;
break;
case 'a':
if(s.compare(1, string::npos, "nd") == 0)
ret = Keyword::and_;
break;
case 'b':
if(s.compare(1, string::npos, "egin") == 0)
ret = Keyword::begin;
break;
case 'c':
if(s.length() != 4) break;
switch(s[1]){
case 'a':
if(s.compare(2, string::npos, "se") == 0)
ret = Keyword::case_;
break;
case 'o':
if(s.compare(2, string::npos, "nd") == 0)
ret = Keyword::cond;
break;
}
break;
case 'd':
if(s.length() < 2) break;
switch(s[1]){
case 'e':
if(s.length() < 5) break;
switch(s[2]){
case 'f':
if(s.compare(3, string::npos, "ine") == 0)
ret = Keyword::define;
break;
case 'l':
if(s.compare(3, string::npos, "ay") == 0)
ret = Keyword::delay;
break;
}
break;
case 'o':
if(s.length() == 2)
ret = Keyword::do_;
break;
}
break;
case 'e':
if(s.compare(1, string::npos, "lse") == 0)
ret = Keyword::else_;
break;
case 'i':
if(s.compare(1, string::npos, "f") == 0)
ret = Keyword::if_;
break;
case 'l':
if(s.length() < 3) break;
switch(s[1]){
case 'a':
if(s.compare(2, string::npos, "mbda") == 0)
ret = Keyword::lambda;
break;
case 'e':
if(s[2] != 't') break;
if(s.length() == 3)
ret = Keyword::let;
else if(s.compare(3, string::npos, "*") == 0)
ret = Keyword::let_star;
else if(s.compare(3, string::npos, "rec") == 0)
ret = Keyword::letrec;
break;
}
break;
case 'o':
if(s.compare(1, string::npos, "r") == 0)
ret = Keyword::or_;
break;
case 'q':
if(s.length() < 5 || s[1] != 'u') break;
switch(s[2]){
case 'a':
if(s.compare(3, string::npos, "siquote") == 0)
ret = Keyword::quasiquote;
break;
case 'o':
if(s.compare(3, string::npos, "te") == 0)
ret = Keyword::quote;
break;
}
break;
case 's':
if(s.compare(1, string::npos, "et!") == 0)
ret = Keyword::set_;
break;
case 'u': {
auto cmp = s.compare(1, 7, "nquote");
if(cmp == 0){
ret = Keyword::unquote;
}else if(cmp > 0 &&
s.compare(7, string::npos, "-splicing") == 0)
ret = Keyword::unquote_splicing;
}
break;
}
return ret;
#endif
}
<commit_msg>bitly cleanup<commit_after>#include "keyword.hh"
using namespace std;
const char* stringify(Keyword k){
switch(k){
case Keyword::else_:
return "else";
case Keyword::r_arrow:
return "=>";
case Keyword::define:
return "define";
case Keyword::unquote:
return "unquote";
case Keyword::unquote_splicing:
return "unquote-splicing";
case Keyword::quote:
return "quote";
case Keyword::lambda:
return "lambda";
case Keyword::if_:
return "if";
case Keyword::set_:
return "set!";
case Keyword::begin:
return "begin";
case Keyword::cond:
return "cond";
case Keyword::and_:
return "and";
case Keyword::or_:
return "or";
case Keyword::case_:
return "case";
case Keyword::let:
return "let";
case Keyword::let_star:
return "let*";
case Keyword::letrec:
return "letrec";
case Keyword::do_:
return "do";
case Keyword::delay:
return "delay";
case Keyword::quasiquote:
return "quasiquote";
default:
return "(unknown keyword type)";
}
}
Keyword to_keyword(const std::string& s){
if(s.empty())
return Keyword::not_keyword;
Keyword ret = Keyword::not_keyword;
switch(s[0]){
case '=':
if(s.compare(1, string::npos, ">") == 0)
ret = Keyword::r_arrow;
break;
case 'a':
if(s.compare(1, string::npos, "nd") == 0)
ret = Keyword::and_;
break;
case 'b':
if(s.compare(1, string::npos, "egin") == 0)
ret = Keyword::begin;
break;
case 'c':
if(s.length() != 4) break;
switch(s[1]){
case 'a':
if(s.compare(2, string::npos, "se") == 0)
ret = Keyword::case_;
break;
case 'o':
if(s.compare(2, string::npos, "nd") == 0)
ret = Keyword::cond;
break;
}
break;
case 'd':
if(s.length() < 2) break;
switch(s[1]){
case 'e':
if(s.length() < 5) break;
switch(s[2]){
case 'f':
if(s.compare(3, string::npos, "ine") == 0)
ret = Keyword::define;
break;
case 'l':
if(s.compare(3, string::npos, "ay") == 0)
ret = Keyword::delay;
break;
}
break;
case 'o':
if(s.length() == 2)
ret = Keyword::do_;
break;
}
break;
case 'e':
if(s.compare(1, string::npos, "lse") == 0)
ret = Keyword::else_;
break;
case 'i':
if(s.compare(1, string::npos, "f") == 0)
ret = Keyword::if_;
break;
case 'l':
if(s.length() < 3) break;
switch(s[1]){
case 'a':
if(s.compare(2, string::npos, "mbda") == 0)
ret = Keyword::lambda;
break;
case 'e':
if(s[2] != 't') break;
if(s.length() == 3)
ret = Keyword::let;
else if(s.compare(3, string::npos, "*") == 0)
ret = Keyword::let_star;
else if(s.compare(3, string::npos, "rec") == 0)
ret = Keyword::letrec;
break;
}
break;
case 'o':
if(s.compare(1, string::npos, "r") == 0)
ret = Keyword::or_;
break;
case 'q':
if(s.length() < 5 || s[1] != 'u') break;
switch(s[2]){
case 'a':
if(s.compare(3, string::npos, "siquote") == 0)
ret = Keyword::quasiquote;
break;
case 'o':
if(s.compare(3, string::npos, "te") == 0)
ret = Keyword::quote;
break;
}
break;
case 's':
if(s.compare(1, string::npos, "et!") == 0)
ret = Keyword::set_;
break;
case 'u': {
auto cmp = s.compare(1, 7, "nquote");
if(cmp == 0){
ret = Keyword::unquote;
}else if(cmp > 0 &&
s.compare(7, string::npos, "-splicing") == 0)
ret = Keyword::unquote_splicing;
}
break;
}
return ret;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "server.hh"
#include "handler.hh"
#include "core/future-util.hh"
#include "core/circular_buffer.hh"
#include <seastar/core/metrics.hh>
#include "net/byteorder.hh"
#include "core/scattered_message.hh"
#include "log.hh"
#include <thrift/server/TServer.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/TProcessor.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/async/TAsyncProcessor.h>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <limits>
#include <cctype>
#include <vector>
#include <boost/make_shared.hpp>
static logging::logger tlogger("thrift");
using namespace apache::thrift;
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
using namespace apache::thrift::async;
using namespace ::cassandra;
using namespace std::chrono_literals;
class thrift_stats {
seastar::metrics::metric_groups _metrics;
public:
thrift_stats(thrift_server& server);
};
thrift_server::thrift_server(distributed<database>& db,
distributed<cql3::query_processor>& qp)
: _stats(new thrift_stats(*this))
, _handler_factory(create_handler_factory(db, qp).release())
, _protocol_factory(new TBinaryProtocolFactoryT<TMemoryBuffer>())
, _processor_factory(new CassandraAsyncProcessorFactory(_handler_factory)) {
}
thrift_server::~thrift_server() {
}
future<> thrift_server::stop() {
std::for_each(_connections_list.begin(), _connections_list.end(), std::mem_fn(&connection::shutdown));
return make_ready_future<>();
}
struct handler_deleter {
CassandraCobSvIfFactory* hf;
void operator()(CassandraCobSvIf* h) const {
hf->releaseHandler(h);
}
};
// thrift uses a shared_ptr to refer to the transport (= connection),
// while we do not, so we can't have connection inherit from TTransport.
struct thrift_server::connection::fake_transport : TTransport {
fake_transport(thrift_server::connection* c) : conn(c) {}
thrift_server::connection* conn;
};
thrift_server::connection::connection(thrift_server& server, connected_socket&& fd, socket_address addr)
: _server(server), _fd(std::move(fd)), _read_buf(_fd.input())
, _write_buf(_fd.output())
, _transport(boost::make_shared<thrift_server::connection::fake_transport>(this))
, _input(boost::make_shared<TMemoryBuffer>())
, _output(boost::make_shared<TMemoryBuffer>())
, _in_proto(_server._protocol_factory->getProtocol(_input))
, _out_proto(_server._protocol_factory->getProtocol(_output))
, _processor(_server._processor_factory->getProcessor({ _in_proto, _out_proto, _transport })) {
++_server._total_connections;
++_server._current_connections;
_server._connections_list.push_back(*this);
}
thrift_server::connection::~connection() {
if (is_linked()) {
--_server._current_connections;
_server._connections_list.erase(_server._connections_list.iterator_to(*this));
}
}
thrift_server::connection::connection(connection&& other)
: _server(other._server)
, _fd(std::move(other._fd))
, _read_buf(std::move(other._read_buf))
, _write_buf(std::move(other._write_buf))
, _transport(std::move(other._transport))
, _input(std::move(other._input))
, _output(std::move(other._output))
, _in_proto(std::move(other._in_proto))
, _out_proto(std::move(other._out_proto))
, _processor(std::move(other._processor)) {
if (other.is_linked()) {
boost::intrusive::list<connection>::node_algorithms::init(this_ptr());
boost::intrusive::list<connection>::node_algorithms::swap_nodes(other.this_ptr(), this_ptr());
}
}
future<>
thrift_server::connection::process() {
return do_until([this] { return _read_buf.eof(); },
[this] { return process_one_request(); })
.finally([this] {
return _write_buf.close();
});
}
future<>
thrift_server::connection::process_one_request() {
_input->resetBuffer();
_output->resetBuffer();
return read().then([this] {
++_server._requests_served;
auto ret = _processor_promise.get_future();
// adapt from "continuation object style" to future/promise
auto complete = [this] (bool success) mutable {
// FIXME: look at success?
write().forward_to(std::move(_processor_promise));
_processor_promise = promise<>();
};
_processor->process(complete, _in_proto, _out_proto);
return ret;
});
}
future<>
thrift_server::connection::read() {
return _read_buf.read_exactly(4).then([this] (temporary_buffer<char> size_buf) {
if (size_buf.size() != 4) {
return make_ready_future<>();
}
union {
uint32_t n;
char b[4];
} data;
std::copy_n(size_buf.get(), 4, data.b);
auto n = ntohl(data.n);
return _read_buf.read_exactly(n).then([this, n] (temporary_buffer<char> buf) {
if (buf.size() != n) {
// FIXME: exception perhaps?
return;
}
_in_tmp = std::move(buf); // keep ownership of the data
auto b = reinterpret_cast<uint8_t*>(_in_tmp.get_write());
_input->resetBuffer(b, _in_tmp.size());
});
});
}
future<>
thrift_server::connection::write() {
uint8_t* data;
uint32_t len;
_output->getBuffer(&data, &len);
net::packed<uint32_t> plen = { net::hton(len) };
return _write_buf.write(reinterpret_cast<char*>(&plen), 4).then([this, data, len] {
// FIXME: zero-copy
return _write_buf.write(reinterpret_cast<char*>(data), len);
}).then([this] {
return _write_buf.flush();
});
}
void
thrift_server::connection::shutdown() {
try {
_fd.shutdown_input();
_fd.shutdown_output();
} catch (...) {
}
}
future<>
thrift_server::listen(ipv4_addr addr, bool keepalive) {
listen_options lo;
lo.reuse_address = true;
_listeners.push_back(engine().listen(make_ipv4_address(addr), lo));
do_accepts(_listeners.size() - 1, keepalive);
return make_ready_future<>();
}
void
thrift_server::do_accepts(int which, bool keepalive) {
_listeners[which].accept().then([this, which, keepalive] (connected_socket fd, socket_address addr) mutable {
fd.set_nodelay(true);
fd.set_keepalive(keepalive);
auto conn = new connection(*this, std::move(fd), addr);
conn->process().then_wrapped([this, conn] (future<> f) {
conn->shutdown();
delete conn;
try {
f.get();
} catch (std::exception& ex) {
tlogger.debug("request error {}", ex.what());
}
});
do_accepts(which, keepalive);
}).handle_exception([this, which, keepalive] (auto ex) {
tlogger.debug("accept failed {}", ex);
maybe_retry_accept(which, keepalive, std::move(ex));
});
}
void thrift_server::maybe_retry_accept(int which, bool keepalive, std::exception_ptr ex) {
auto retry = [this, which, keepalive] {
tlogger.debug("retrying accept after failure");
do_accepts(which, keepalive);
};
auto retry_with_backoff = [&] {
// FIXME: Consider using exponential backoff
sleep(1ms).then([retry = std::move(retry)] { retry(); });
};
try {
std::rethrow_exception(std::move(ex));
} catch (const std::system_error& e) {
switch (e.code().value()) {
// FIXME: Don't retry for other fatal errors
case EBADF:
break;
case ENFILE:
case EMFILE:
case ENOMEM:
retry_with_backoff();
default:
retry();
}
} catch (const std::bad_alloc&) {
retry_with_backoff();
} catch (...) {
retry();
}
}
uint64_t
thrift_server::total_connections() const {
return _total_connections;
}
uint64_t
thrift_server::current_connections() const {
return _current_connections;
}
uint64_t
thrift_server::requests_served() const {
return _requests_served;
}
thrift_stats::thrift_stats(thrift_server& server) {
namespace sm = seastar::metrics;
_metrics.add_group("thrift", {
sm::make_derive("thrift-connections", [&server] { return server.total_connections(); },
sm::description("Rate of creation of new Thrift connections.")),
sm::make_gauge("current_connections", [&server] { return server.current_connections(); },
sm::description("Holds a current number of opened Thrift connections.")),
sm::make_derive("served", [&server] { return server.requests_served(); },
sm::description("Rate of serving Thrift requests.")),
});
}
<commit_msg>thrift/server: Avoid manual memory management<commit_after>/*
* Copyright (C) 2014 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "server.hh"
#include "handler.hh"
#include "core/future-util.hh"
#include "core/circular_buffer.hh"
#include <seastar/core/metrics.hh>
#include "net/byteorder.hh"
#include "core/scattered_message.hh"
#include "log.hh"
#include <thrift/server/TServer.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/TProcessor.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/async/TAsyncProcessor.h>
#include <iostream>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <bitset>
#include <limits>
#include <cctype>
#include <vector>
#include <boost/make_shared.hpp>
static logging::logger tlogger("thrift");
using namespace apache::thrift;
using namespace apache::thrift::transport;
using namespace apache::thrift::protocol;
using namespace apache::thrift::async;
using namespace ::cassandra;
using namespace std::chrono_literals;
class thrift_stats {
seastar::metrics::metric_groups _metrics;
public:
thrift_stats(thrift_server& server);
};
thrift_server::thrift_server(distributed<database>& db,
distributed<cql3::query_processor>& qp)
: _stats(new thrift_stats(*this))
, _handler_factory(create_handler_factory(db, qp).release())
, _protocol_factory(new TBinaryProtocolFactoryT<TMemoryBuffer>())
, _processor_factory(new CassandraAsyncProcessorFactory(_handler_factory)) {
}
thrift_server::~thrift_server() {
}
future<> thrift_server::stop() {
std::for_each(_connections_list.begin(), _connections_list.end(), std::mem_fn(&connection::shutdown));
return make_ready_future<>();
}
struct handler_deleter {
CassandraCobSvIfFactory* hf;
void operator()(CassandraCobSvIf* h) const {
hf->releaseHandler(h);
}
};
// thrift uses a shared_ptr to refer to the transport (= connection),
// while we do not, so we can't have connection inherit from TTransport.
struct thrift_server::connection::fake_transport : TTransport {
fake_transport(thrift_server::connection* c) : conn(c) {}
thrift_server::connection* conn;
};
thrift_server::connection::connection(thrift_server& server, connected_socket&& fd, socket_address addr)
: _server(server), _fd(std::move(fd)), _read_buf(_fd.input())
, _write_buf(_fd.output())
, _transport(boost::make_shared<thrift_server::connection::fake_transport>(this))
, _input(boost::make_shared<TMemoryBuffer>())
, _output(boost::make_shared<TMemoryBuffer>())
, _in_proto(_server._protocol_factory->getProtocol(_input))
, _out_proto(_server._protocol_factory->getProtocol(_output))
, _processor(_server._processor_factory->getProcessor({ _in_proto, _out_proto, _transport })) {
++_server._total_connections;
++_server._current_connections;
_server._connections_list.push_back(*this);
}
thrift_server::connection::~connection() {
if (is_linked()) {
--_server._current_connections;
_server._connections_list.erase(_server._connections_list.iterator_to(*this));
}
}
thrift_server::connection::connection(connection&& other)
: _server(other._server)
, _fd(std::move(other._fd))
, _read_buf(std::move(other._read_buf))
, _write_buf(std::move(other._write_buf))
, _transport(std::move(other._transport))
, _input(std::move(other._input))
, _output(std::move(other._output))
, _in_proto(std::move(other._in_proto))
, _out_proto(std::move(other._out_proto))
, _processor(std::move(other._processor)) {
if (other.is_linked()) {
boost::intrusive::list<connection>::node_algorithms::init(this_ptr());
boost::intrusive::list<connection>::node_algorithms::swap_nodes(other.this_ptr(), this_ptr());
}
}
future<>
thrift_server::connection::process() {
return do_until([this] { return _read_buf.eof(); },
[this] { return process_one_request(); })
.finally([this] {
return _write_buf.close();
});
}
future<>
thrift_server::connection::process_one_request() {
_input->resetBuffer();
_output->resetBuffer();
return read().then([this] {
++_server._requests_served;
auto ret = _processor_promise.get_future();
// adapt from "continuation object style" to future/promise
auto complete = [this] (bool success) mutable {
// FIXME: look at success?
write().forward_to(std::move(_processor_promise));
_processor_promise = promise<>();
};
_processor->process(complete, _in_proto, _out_proto);
return ret;
});
}
future<>
thrift_server::connection::read() {
return _read_buf.read_exactly(4).then([this] (temporary_buffer<char> size_buf) {
if (size_buf.size() != 4) {
return make_ready_future<>();
}
union {
uint32_t n;
char b[4];
} data;
std::copy_n(size_buf.get(), 4, data.b);
auto n = ntohl(data.n);
return _read_buf.read_exactly(n).then([this, n] (temporary_buffer<char> buf) {
if (buf.size() != n) {
// FIXME: exception perhaps?
return;
}
_in_tmp = std::move(buf); // keep ownership of the data
auto b = reinterpret_cast<uint8_t*>(_in_tmp.get_write());
_input->resetBuffer(b, _in_tmp.size());
});
});
}
future<>
thrift_server::connection::write() {
uint8_t* data;
uint32_t len;
_output->getBuffer(&data, &len);
net::packed<uint32_t> plen = { net::hton(len) };
return _write_buf.write(reinterpret_cast<char*>(&plen), 4).then([this, data, len] {
// FIXME: zero-copy
return _write_buf.write(reinterpret_cast<char*>(data), len);
}).then([this] {
return _write_buf.flush();
});
}
void
thrift_server::connection::shutdown() {
try {
_fd.shutdown_input();
_fd.shutdown_output();
} catch (...) {
}
}
future<>
thrift_server::listen(ipv4_addr addr, bool keepalive) {
listen_options lo;
lo.reuse_address = true;
_listeners.push_back(engine().listen(make_ipv4_address(addr), lo));
do_accepts(_listeners.size() - 1, keepalive);
return make_ready_future<>();
}
void
thrift_server::do_accepts(int which, bool keepalive) {
_listeners[which].accept().then([this, which, keepalive] (connected_socket fd, socket_address addr) mutable {
fd.set_nodelay(true);
fd.set_keepalive(keepalive);
do_with(connection(*this, std::move(fd), addr), [this] (auto& conn) {
return conn.process().then_wrapped([this, &conn] (future<> f) {
conn.shutdown();
try {
f.get();
} catch (std::exception& ex) {
tlogger.debug("request error {}", ex.what());
}
});
});
do_accepts(which, keepalive);
}).handle_exception([this, which, keepalive] (auto ex) {
tlogger.debug("accept failed {}", ex);
maybe_retry_accept(which, keepalive, std::move(ex));
});
}
void thrift_server::maybe_retry_accept(int which, bool keepalive, std::exception_ptr ex) {
auto retry = [this, which, keepalive] {
tlogger.debug("retrying accept after failure");
do_accepts(which, keepalive);
};
auto retry_with_backoff = [&] {
// FIXME: Consider using exponential backoff
sleep(1ms).then([retry = std::move(retry)] { retry(); });
};
try {
std::rethrow_exception(std::move(ex));
} catch (const std::system_error& e) {
switch (e.code().value()) {
// FIXME: Don't retry for other fatal errors
case EBADF:
break;
case ENFILE:
case EMFILE:
case ENOMEM:
retry_with_backoff();
default:
retry();
}
} catch (const std::bad_alloc&) {
retry_with_backoff();
} catch (...) {
retry();
}
}
uint64_t
thrift_server::total_connections() const {
return _total_connections;
}
uint64_t
thrift_server::current_connections() const {
return _current_connections;
}
uint64_t
thrift_server::requests_served() const {
return _requests_served;
}
thrift_stats::thrift_stats(thrift_server& server) {
namespace sm = seastar::metrics;
_metrics.add_group("thrift", {
sm::make_derive("thrift-connections", [&server] { return server.total_connections(); },
sm::description("Rate of creation of new Thrift connections.")),
sm::make_gauge("current_connections", [&server] { return server.current_connections(); },
sm::description("Holds a current number of opened Thrift connections.")),
sm::make_derive("served", [&server] { return server.requests_served(); },
sm::description("Rate of serving Thrift requests.")),
});
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <boost/cstdint.hpp>
#include <boost/integer/static_log2.hpp>
void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);
class Tiles;
template<int Ntiles> class PackedTiles {
friend class Tiles;
enum {
Nbits = boost::static_log2<Ntiles>::value,
Nbytes = (int) ((Nbits / 8.0) * Ntiles),
};
unsigned char bytes[Nbytes];
public:
void pack(Tiles::Tile ts[]) {
fatal("Tiles::pack is unimplemented");
}
Tiles::Pos unpack(Tiles::Tile ts[]) {
fatal("Tiles::unpack is unimplemented");
return 0;
}
Tiles::Pos unpack_md(const unsigned int md[][Ntiles], Tiles::Tile ts[], Tiles::Cost *h) {
*h = 0;
fatal("Tiles::unpack_md is unimplemented");
return 0;
}
unsigned long hash(const void*) {
return hashbytes(bytes, sizeof(bytes));
}
bool eq(const void*, PackedTiles &o) const {
return memcmp(bytes, o.bytes, sizeof(bytes)) == 0;
}
};
template<> class PackedTiles<16> {
friend class Tiles;
enum { Ntiles = 16 };
boost::uint64_t word;
public:
void pack(Tiles::Tile ts[]) {
word = 0;
for (int i = 0; i < Ntiles; i++)
word = (word << 4) | ts[i];
}
Tiles::Pos unpack(Tiles::Tile ts[]) {
int b;
boost::uint64_t w = word;
for (int i = Ntiles - 1; i >= 0; i--) {
Tiles::Tile t = w & 0xF;
w >>= 4;
ts[i] = t;
if (t == 0)
b = i;
}
return b;
}
Tiles::Pos unpack_md(const unsigned int md[][Ntiles], Tiles::Tile ts[], Tiles::Cost *hp) {
int b = -1;
Tiles::Cost h = 0;
boost::uint64_t w = word;
for (int i = Ntiles - 1; i >= 0; i--) {
Tiles::Tile t = w & 0xF;
w >>= 4;
ts[i] = t;
if (t == 0)
b = i;
else
h += md[t][i];
}
*hp = h;
return b;
}
unsigned long hash(const void*) {
return word;
}
bool eq(const void*, const PackedTiles &o) const {
return word == o.word;
}
};
<commit_msg>tiles: support 8 puzzles.<commit_after>#include <cassert>
#include <boost/cstdint.hpp>
#include <boost/integer/static_log2.hpp>
void fatal(const char*, ...);
extern "C" unsigned long hashbytes(unsigned char[], unsigned int);
class Tiles;
template<int Ntiles> class PackedTiles {
friend class Tiles;
enum {
Nbits = boost::static_log2<Ntiles>::value,
Nbytes = (int) ((Nbits / 8.0) * Ntiles),
};
unsigned char bytes[Nbytes];
public:
void pack(Tiles::Tile ts[]) {
fatal("Tiles::pack is unimplemented");
}
Tiles::Pos unpack(Tiles::Tile ts[]) {
fatal("Tiles::unpack is unimplemented");
return 0;
}
Tiles::Pos unpack_md(const unsigned int md[][Ntiles], Tiles::Tile ts[], Tiles::Cost *h) {
*h = 0;
fatal("Tiles::unpack_md is unimplemented");
return 0;
}
unsigned long hash(const void*) {
return hashbytes(bytes, sizeof(bytes));
}
bool eq(const void*, PackedTiles &o) const {
return memcmp(bytes, o.bytes, sizeof(bytes)) == 0;
}
};
template<int Ntiles> class PackedTiles64 {
friend class Tiles;
boost::uint64_t word;
public:
void pack(Tiles::Tile ts[]) {
word = 0;
for (int i = 0; i < Ntiles; i++)
word = (word << 4) | ts[i];
}
Tiles::Pos unpack(Tiles::Tile ts[]) {
int b;
boost::uint64_t w = word;
for (int i = Ntiles - 1; i >= 0; i--) {
Tiles::Tile t = w & 0xF;
w >>= 4;
ts[i] = t;
if (t == 0)
b = i;
}
return b;
}
Tiles::Pos unpack_md(const unsigned int md[][Ntiles], Tiles::Tile ts[], Tiles::Cost *hp) {
int b = -1;
Tiles::Cost h = 0;
boost::uint64_t w = word;
for (int i = Ntiles - 1; i >= 0; i--) {
Tiles::Tile t = w & 0xF;
w >>= 4;
ts[i] = t;
if (t == 0)
b = i;
else
h += md[t][i];
}
*hp = h;
return b;
}
unsigned long hash(const void*) {
return word;
}
bool eq(const void*, const PackedTiles64 &o) const {
return word == o.word;
}
};
template<> class PackedTiles<16> : public PackedTiles64<16> {
};
template<> class PackedTiles<9> : public PackedTiles64<9> {
};
<|endoftext|>
|
<commit_before>{
// .........................macro dirs.C............................
// This macro illustrates how to create a hierarchy of directories
// in a Root file.
// 10 directories called plane0, plane1, plane9 are created.
// Each plane directory contains 200 histograms.
//
// Run this macro (Note that the macro delete the TFile object at the end!)
// Connect the file again in read mode:
// Root > TFile *top = new TFile("top.root");
// The hierarchy can be browsed by the Root browser as shown below
// Root > TBrowser b;
// click on the left pane on one of the plane directories.
// this shows the list of all histograms in this directory.
// Double click on one histogram to draw it (left mouse button).
// Select different options with the right mouse button.
//
// You can see the begin_html <a href="gif/dirs.gif" >picture of the browser </a> end_html
//
// Instead of using the browser, you can also do:
// Root > top->cd();
// Root > plane3->cd();
// Root > h3_90N->Draw();
gROOT->Reset();
// create a new Root file
TFile *top = new TFile("top.root","recreate");
// create a subdirectory "tof" in this file
TDirectory *cdtof = top->mkdir("tof");
cdtof->cd(); // make the "tof" directory the current directory
// create a new subdirectory for each plane
const Int_t nplanes = 10;
const Int_t ncounters = 100;
char dirname[50];
char hname[20];
char htitle[80];
Int_t i,j,k;
TDirectory *cdplane[nplanes];
TH1F *hn[nplanes][ncounters];
TH1F *hs[nplanes][ncounters];
for (i=0;i<nplanes;i++) {
sprintf(dirname,"plane%d",i);
cdplane[i] = cdtof->mkdir(dirname);
cdplane[i]->cd();
// create counter histograms
for (j=0;j<ncounters;j++) {
sprintf(hname,"h%d_%dN",i,j);
sprintf(htitle,"hist for counter:%d in plane:%d North",j,i);
hn[i][j] = new TH1F(hname,htitle,100,0,100);
sprintf(hname,"h%d_%dS",i,j);
sprintf(htitle,"hist for counter:%d in plane:%d South",j,i);
hs[i][j] = new TH1F(hname,htitle,100,0,100);
}
cdtof->cd(); // change current directory to top
}
// .. fill histograms
TRandom r;
for (i=0;i<nplanes;i++) {
cdplane[i]->cd();
for (j=0;j<ncounters;j++) {
for (k=0;k<100;k++) {
hn[i][j]->Fill(100*r.Rndm(),i+j);
hs[i][j]->Fill(100*r.Rndm(),i+j+k);
}
}
}
// save histogram hierarchy in the file
top->Write();
delete top;
}
<commit_msg>Fix a typo<commit_after>{
// .........................macro dirs.C............................
// This macro illustrates how to create a hierarchy of directories
// in a Root file.
// 10 directories called plane0, plane1, plane9 are created.
// Each plane directory contains 200 histograms.
//
// Run this macro (Note that the macro delete the TFile object at the end!)
// Connect the file again in read mode:
// Root > TFile *top = new TFile("top.root");
// The hierarchy can be browsed by the Root browser as shown below
// Root > TBrowser b;
// click on the left pane on one of the plane directories.
// this shows the list of all histograms in this directory.
// Double click on one histogram to draw it (left mouse button).
// Select different options with the right mouse button.
//
// You can see the begin_html <a href="gif/dirs.gif" >picture of the browser </a> end_html
//
// Instead of using the browser, you can also do:
// Root > tof->cd();
// Root > plane3->cd();
// Root > h3_90N->Draw();
gROOT->Reset();
// create a new Root file
TFile *top = new TFile("top.root","recreate");
// create a subdirectory "tof" in this file
TDirectory *cdtof = top->mkdir("tof");
cdtof->cd(); // make the "tof" directory the current directory
// create a new subdirectory for each plane
const Int_t nplanes = 10;
const Int_t ncounters = 100;
char dirname[50];
char hname[20];
char htitle[80];
Int_t i,j,k;
TDirectory *cdplane[nplanes];
TH1F *hn[nplanes][ncounters];
TH1F *hs[nplanes][ncounters];
for (i=0;i<nplanes;i++) {
sprintf(dirname,"plane%d",i);
cdplane[i] = cdtof->mkdir(dirname);
cdplane[i]->cd();
// create counter histograms
for (j=0;j<ncounters;j++) {
sprintf(hname,"h%d_%dN",i,j);
sprintf(htitle,"hist for counter:%d in plane:%d North",j,i);
hn[i][j] = new TH1F(hname,htitle,100,0,100);
sprintf(hname,"h%d_%dS",i,j);
sprintf(htitle,"hist for counter:%d in plane:%d South",j,i);
hs[i][j] = new TH1F(hname,htitle,100,0,100);
}
cdtof->cd(); // change current directory to top
}
// .. fill histograms
TRandom r;
for (i=0;i<nplanes;i++) {
cdplane[i]->cd();
for (j=0;j<ncounters;j++) {
for (k=0;k<100;k++) {
hn[i][j]->Fill(100*r.Rndm(),i+j);
hs[i][j]->Fill(100*r.Rndm(),i+j+k);
}
}
}
// save histogram hierarchy in the file
top->Write();
delete top;
}
<|endoftext|>
|
<commit_before>/**\file
* \ingroup example-programmes
* \brief Matrix-esque terminal animation
*
* This is a terminal programme that uses libefgy's vt100 code to render a text
* version of the matrix 'scrolling streams of text' animation. It's really
* fairly simple but also kinda nice to see how the vt100 output is performing.
*
* \image html matrix.png "Screenshot of the programme running in Terminal.app"
*
* \copyright
* This file is part of the libefgy project, which is released as open source
* under the terms of an MIT/X11-style licence, described in the COPYING file.
*
* \see Project Documentation: https://ef.gy/documentation/libefgy
* \see Project Source Code: https://github.com/ef-gy/libefgy
* \see Licence Terms: https://github.com/ef-gy/libefgy/blob/master/COPYING
*/
#include <iostream>
#include <ef.gy/vt100.h>
#include <chrono>
#include <csignal>
#include <cmath>
#include <sched.h>
#include <random>
using namespace efgy;
using namespace std::chrono;
/**\brief Data and functions related to the matrix demo
*
* Contains global variables and classes used by the 'matrix' demo animation.
* This is a separate namespace to keep things all neat, clean and tidy.
*/
namespace thematrix {
/**\brief VT100 output buffer
*
* Encapsulates stdio to automatically generate the terminal escape
* sequences to write things at specific positions with specific colours.
*/
terminal::vt100<> output;
/**\brief Random number generator
*
* A seeded instance of the mersenne twister RNG; used to position the
* streams and to add and remove glyphs randomly.
*/
std::mt19937 rng(1337);
/**\brief Current time
*
* The point in time when processing of the current streams started; used
* to determine when streams should be updated.
*/
system_clock::time_point now;
/**\brief A stream of data
*
* A 'stream' is what I dubbed the individual columns of text in the
* animation. These are generated randomly and they mutate randomly as
* well.
*/
class stream {
public:
/**\brief A single glyph in a stream
*
* To create the animation, each of the glyphs in the output needs
* to be tagges with the time it was created, in order to know
* which colour to draw the glyph in.
*/
class cell {
public:
/**\brief Construct with glyph
*
* Constructs an instance of the class using the given
* character and the current system time.
*
* \param[in] pCharacter A unicode code point.
*/
cell(const unsigned long &pCharacter)
: character(pCharacter), created(now) {}
/**\brief The glyph
*
* This is the glyph to output; must be a valid unicode
* glyph as the vt100 code will expect one to send to the
* terminal.
*/
unsigned long character;
/**\brief When was this object created?
*
* Contains the time point of this object's creation; used
* to determine the colour of the glyph in the output;
*/
system_clock::time_point created;
};
/**\brief Construct with position
*
* Initialises an instance of the class given the line and column
* of where the stream should appear.
*
* \param[in] pLine The line at which to create the stream; must
* be less than output.size()[1].
* \param[in] pColumn The column at which to create the stream;
* must be less than output.size()[0].
*/
stream(const std::size_t &pLine, const std::size_t &pColumn)
: line(pLine), column(pColumn), last(now), doDelete(false) {}
/**\brief Line component of stream position
*
* This is the line at which the stream is rendered to the
* terminal.
*/
std::size_t line;
/**\brief Column component of stream position
*
* This is the column at which the stream is rendered to the
* terminal.
*/
std::size_t column;
/**\brief The stream contents to render
*
* A vector of glyphs and the time at which they were inserted into
* the stream; this vector is placed vertically at the coordinates
* given by line and column. Recent glyphs are rendered in white,
* older ones in green.
*/
std::vector<cell> data;
/**\brief Time of last update
*
* Records the last time a glyph was inserted into or removed from
* the stream; used to determine when to add new glyphs.
*/
system_clock::time_point last;
/**\brief Should this stream be deleted?
*
* Set to true when the upper part of the stream reaches the bottom
* of the screen; the stream should then be deleted in the main
* loop because it won't produce any output on the screen when this
* happens.
*/
bool doDelete;
/**\brief Update and render stream
*
* Render the current contents of the stream to the screen; if it
* so happens that enough time has passed since the last time this
* method was called then this function will also randomly add or
* remove glyphs, or move the stream further down.
*
* \returns 'true' if the update went smoothly; 'false' otherwise.
* There is currently no way this function can fail, so
* at the moment it will always return 'true'.
*/
bool update(void) {
if ((now - last) > std::chrono::milliseconds(10)) {
last = now;
switch (rng() % 3) {
case 0:
if (data.size() > 0) {
data.erase(data.begin() + (rng() % data.size()));
break;
}
default:
data.push_back(cell(rng() % (1 << 7)));
}
}
std::array<std::size_t, 2> s = output.size();
if (data.size() > (s[1] / 2)) {
if (line < s[1]) {
if (rng() % 5 == 0) {
output.target[line][column].content = ' ';
line++;
}
} else {
doDelete = true;
}
data.erase(data.begin());
}
int i = line;
for (cell &d : data) {
if (i >= s[1]) {
break;
}
output.target[i][column].content = d.character;
output.target[i][column].foregroundColour =
(now - d.created) > std::chrono::milliseconds(120) ? 2 : 7;
output.target[i][column].backgroundColour = 0;
i++;
}
return true;
}
};
/**\brief SIGINT handler
*
* Signal handler that calls exit() properly; the SIGINT handler is
* replaced by this function. While SIGINT would ordinarily terminate the
* programme anyway, it doesn't do so with a proper call to exit(), meaning
* that destructors will not be called, further meaning that the terminal
* can't be reset to a proper state by the terminal handling code, because
* not using exit() properly means destructors won't run.
*/
void handle_interrupt(int signal) { exit(0); }
/**\brief Green-tinted post processing function
*
* A simple post-processing function for the vt100 code, which makes sure
* that any output cell is always either white or green. This makes it
* easier for the optimiser as it won't have to switch colours quite as
* often as it otherwise might.
*/
terminal::cell<long> postProcess(const terminal::terminal<long> &t,
const std::size_t &l, const std::size_t &c) {
terminal::cell<long> rv = t.target[l][c];
rv.content = rv.content == 0 ? ' ' : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
/**\brief Alternative post processing function
*
* Adds some curviness to the output by modifying the input coordinates a
* bit before creating the output. Kinda looks funky, but not really
* matrix-y. You'll have to modify the main() function yourself if you want
* to see this in action.
*/
terminal::cell<long> postProcessPolar(const terminal::terminal<long> &t,
const std::size_t &pl,
const std::size_t &pc) {
double l = pl;
double c = pc;
std::array<std::size_t, 2> s = t.size();
double hl = s[1] / 2;
double hc = s[0] / 2;
double loff = l - hl;
double coff = c - hc;
double r2 = loff * loff + coff * coff;
double r = std::sqrt(r2);
l = hl + loff + std::sin(r) * 1.0;
c = hc + coff + std::cos(r) * 1.0;
const std::size_t tl = (std::size_t)l < s[1] ? (std::size_t)l : (s[1] - 1);
const std::size_t tc = (std::size_t)c < s[0] ? (std::size_t)c : (s[0] - 1);
terminal::cell<long> rv = t.target[tl][tc];
terminal::cell<long> cv = t.current[tl][tc];
rv.content =
rv.content == 0 ? (cv.content == 0 ? ' ' : cv.content) : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
};
using namespace thematrix;
/**\brief Matrix demo main function
*
* Entry point for the matrix programme; resizes the output buffer to encompass
* the whole terminal, sets up a SIGINT handler and then maintains a vector of
* thematrix::stream objects at random positions.
*
* Use CTRL+C to terminate the programme.
*
* \note Command line arguments and the programme environment are ignored.
*
* \returns 0 for 'success', but this should never be reached as the SIGINT
* handler calls exit(), which is the only way to break out of the main
* loop.
*/
int main(int, char **) {
output.resize(output.getOSDimensions());
std::array<std::size_t, 2> s = output.size();
std::size_t i;
std::vector<stream> streams;
std::signal(SIGINT, handle_interrupt);
while (1) {
i++;
now = system_clock::now();
if ((streams.size() <= 100) && (i % 50 == 0)) {
std::size_t l = rng() % (s[1] / 3);
std::size_t c = rng() % s[0];
streams.push_back(stream(l, c));
}
for (stream &s : streams) {
s.update();
}
for (unsigned int i = 0; i < streams.size(); i++) {
if (streams[i].doDelete) {
streams.erase(streams.begin() + i);
}
}
if (output.flush(postProcess) == 0) {
sched_yield();
}
}
while ((i = output.flush(postProcess)) > 0)
;
return 0;
}
<commit_msg>move the matrix demo main function into the matrix namespace.<commit_after>/**\file
* \ingroup example-programmes
* \brief Matrix-esque terminal animation
*
* This is a terminal programme that uses libefgy's vt100 code to render a text
* version of the matrix 'scrolling streams of text' animation. It's really
* fairly simple but also kinda nice to see how the vt100 output is performing.
*
* \image html matrix.png "Screenshot of the programme running in Terminal.app"
*
* \copyright
* This file is part of the libefgy project, which is released as open source
* under the terms of an MIT/X11-style licence, described in the COPYING file.
*
* \see Project Documentation: https://ef.gy/documentation/libefgy
* \see Project Source Code: https://github.com/ef-gy/libefgy
* \see Licence Terms: https://github.com/ef-gy/libefgy/blob/master/COPYING
*/
#include <iostream>
#include <ef.gy/vt100.h>
#include <chrono>
#include <csignal>
#include <cmath>
#include <sched.h>
#include <random>
using namespace efgy;
using namespace std::chrono;
/**\brief Data and functions related to the matrix demo
*
* Contains global variables and classes used by the 'matrix' demo animation.
* This is a separate namespace to keep things all neat, clean and tidy.
*/
namespace thematrix {
/**\brief VT100 output buffer
*
* Encapsulates stdio to automatically generate the terminal escape
* sequences to write things at specific positions with specific colours.
*/
terminal::vt100<> output;
/**\brief Random number generator
*
* A seeded instance of the mersenne twister RNG; used to position the
* streams and to add and remove glyphs randomly.
*/
std::mt19937 rng(1337);
/**\brief Current time
*
* The point in time when processing of the current streams started; used
* to determine when streams should be updated.
*/
system_clock::time_point now;
/**\brief A stream of data
*
* A 'stream' is what I dubbed the individual columns of text in the
* animation. These are generated randomly and they mutate randomly as
* well.
*/
class stream {
public:
/**\brief A single glyph in a stream
*
* To create the animation, each of the glyphs in the output needs
* to be tagges with the time it was created, in order to know
* which colour to draw the glyph in.
*/
class cell {
public:
/**\brief Construct with glyph
*
* Constructs an instance of the class using the given
* character and the current system time.
*
* \param[in] pCharacter A unicode code point.
*/
cell(const unsigned long &pCharacter)
: character(pCharacter), created(now) {}
/**\brief The glyph
*
* This is the glyph to output; must be a valid unicode
* glyph as the vt100 code will expect one to send to the
* terminal.
*/
unsigned long character;
/**\brief When was this object created?
*
* Contains the time point of this object's creation; used
* to determine the colour of the glyph in the output;
*/
system_clock::time_point created;
};
/**\brief Construct with position
*
* Initialises an instance of the class given the line and column
* of where the stream should appear.
*
* \param[in] pLine The line at which to create the stream; must
* be less than output.size()[1].
* \param[in] pColumn The column at which to create the stream;
* must be less than output.size()[0].
*/
stream(const std::size_t &pLine, const std::size_t &pColumn)
: line(pLine), column(pColumn), last(now), doDelete(false) {}
/**\brief Line component of stream position
*
* This is the line at which the stream is rendered to the
* terminal.
*/
std::size_t line;
/**\brief Column component of stream position
*
* This is the column at which the stream is rendered to the
* terminal.
*/
std::size_t column;
/**\brief The stream contents to render
*
* A vector of glyphs and the time at which they were inserted into
* the stream; this vector is placed vertically at the coordinates
* given by line and column. Recent glyphs are rendered in white,
* older ones in green.
*/
std::vector<cell> data;
/**\brief Time of last update
*
* Records the last time a glyph was inserted into or removed from
* the stream; used to determine when to add new glyphs.
*/
system_clock::time_point last;
/**\brief Should this stream be deleted?
*
* Set to true when the upper part of the stream reaches the bottom
* of the screen; the stream should then be deleted in the main
* loop because it won't produce any output on the screen when this
* happens.
*/
bool doDelete;
/**\brief Update and render stream
*
* Render the current contents of the stream to the screen; if it
* so happens that enough time has passed since the last time this
* method was called then this function will also randomly add or
* remove glyphs, or move the stream further down.
*
* \returns 'true' if the update went smoothly; 'false' otherwise.
* There is currently no way this function can fail, so
* at the moment it will always return 'true'.
*/
bool update(void) {
if ((now - last) > std::chrono::milliseconds(10)) {
last = now;
switch (rng() % 3) {
case 0:
if (data.size() > 0) {
data.erase(data.begin() + (rng() % data.size()));
break;
}
default:
data.push_back(cell(rng() % (1 << 7)));
}
}
std::array<std::size_t, 2> s = output.size();
if (data.size() > (s[1] / 2)) {
if (line < s[1]) {
if (rng() % 5 == 0) {
output.target[line][column].content = ' ';
line++;
}
} else {
doDelete = true;
}
data.erase(data.begin());
}
int i = line;
for (cell &d : data) {
if (i >= s[1]) {
break;
}
output.target[i][column].content = d.character;
output.target[i][column].foregroundColour =
(now - d.created) > std::chrono::milliseconds(120) ? 2 : 7;
output.target[i][column].backgroundColour = 0;
i++;
}
return true;
}
};
/**\brief SIGINT handler
*
* Signal handler that calls exit() properly; the SIGINT handler is
* replaced by this function. While SIGINT would ordinarily terminate the
* programme anyway, it doesn't do so with a proper call to exit(), meaning
* that destructors will not be called, further meaning that the terminal
* can't be reset to a proper state by the terminal handling code, because
* not using exit() properly means destructors won't run.
*/
void handle_interrupt(int signal) { exit(0); }
/**\brief Green-tinted post processing function
*
* A simple post-processing function for the vt100 code, which makes sure
* that any output cell is always either white or green. This makes it
* easier for the optimiser as it won't have to switch colours quite as
* often as it otherwise might.
*/
terminal::cell<long> postProcess(const terminal::terminal<long> &t,
const std::size_t &l, const std::size_t &c) {
terminal::cell<long> rv = t.target[l][c];
rv.content = rv.content == 0 ? ' ' : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
/**\brief Alternative post processing function
*
* Adds some curviness to the output by modifying the input coordinates a
* bit before creating the output. Kinda looks funky, but not really
* matrix-y. You'll have to modify the main() function yourself if you want
* to see this in action.
*/
terminal::cell<long> postProcessPolar(const terminal::terminal<long> &t,
const std::size_t &pl,
const std::size_t &pc) {
double l = pl;
double c = pc;
std::array<std::size_t, 2> s = t.size();
double hl = s[1] / 2;
double hc = s[0] / 2;
double loff = l - hl;
double coff = c - hc;
double r2 = loff * loff + coff * coff;
double r = std::sqrt(r2);
l = hl + loff + std::sin(r) * 1.0;
c = hc + coff + std::cos(r) * 1.0;
const std::size_t tl = (std::size_t)l < s[1] ? (std::size_t)l : (s[1] - 1);
const std::size_t tc = (std::size_t)c < s[0] ? (std::size_t)c : (s[0] - 1);
terminal::cell<long> rv = t.target[tl][tc];
terminal::cell<long> cv = t.current[tl][tc];
rv.content =
rv.content == 0 ? (cv.content == 0 ? ' ' : cv.content) : rv.content;
rv.foregroundColour = rv.foregroundColour == 7 ? 7 : 2;
rv.backgroundColour = 0;
return rv;
}
/**\brief Matrix demo main function
*
* Entry point for the matrix programme; resizes the output buffer to encompass
* the whole terminal, sets up a SIGINT handler and then maintains a vector of
* thematrix::stream objects at random positions.
*
* Use CTRL+C to terminate the programme.
*
* \note Command line arguments and the programme environment are ignored.
*
* \returns 0 for 'success', but this should never be reached as the SIGINT
* handler calls exit(), which is the only way to break out of the main
* loop.
*/
extern "C" int main(int, char **) {
output.resize(output.getOSDimensions());
std::array<std::size_t, 2> s = output.size();
std::size_t i;
std::vector<stream> streams;
std::signal(SIGINT, handle_interrupt);
while (1) {
i++;
now = system_clock::now();
if ((streams.size() <= 100) && (i % 50 == 0)) {
std::size_t l = rng() % (s[1] / 3);
std::size_t c = rng() % s[0];
streams.push_back(stream(l, c));
}
for (stream &s : streams) {
s.update();
}
for (unsigned int i = 0; i < streams.size(); i++) {
if (streams[i].doDelete) {
streams.erase(streams.begin() + i);
}
}
if (output.flush(postProcess) == 0) {
sched_yield();
}
}
while ((i = output.flush(postProcess)) > 0)
;
return 0;
}
}
<|endoftext|>
|
<commit_before>#include "tensorflow_types.hpp"
// TODO: Capture ... (named and un-named args) and forward to call
// TODO: py_object_convert (convert from Python to R). could be as.character,
// as.matrix, as.logical, etc. Could also be done automatically or via
// some sort of dynamic type annotation mechanism
// TODO: consider R6 wrapper (would allow custom $ functions)
// TODO: .DollarNames
// TODO: Globally available import function
using namespace Rcpp;
// https://docs.python.org/2/c-api/object.html
// [[Rcpp::export]]
void py_initialize() {
::Py_Initialize();
}
// [[Rcpp::export]]
void py_finalize() {
::Py_Finalize();
}
// wrap a PyObject in an XPtr
PyObjectPtr py_object_ptr(PyObject* object, bool decref = true) {
PyObjectPtr ptr(object);
ptr.attr("class") = "py_object";
return ptr;
}
// get a string representing the last python error
std::string py_fetch_error() {
std::ostringstream ostr;
PyObject *pExcType , *pExcValue , *pExcTraceback;
::PyErr_Fetch(&pExcType , &pExcValue , &pExcTraceback) ;
if (pExcType != NULL) {
PyObject* pRepr = ::PyObject_Repr(pExcType ) ;
ostr << PyString_AsString(pRepr) << " ";
Py_DecRef(pRepr);
Py_DecRef(pExcType);
}
if (pExcValue != NULL) {
PyObject* pRepr = ::PyObject_Repr(pExcValue) ;
ostr << ::PyString_AsString(pRepr);
Py_DecRef(pRepr) ;
Py_DecRef(pExcValue) ;
}
return ostr.str();
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_main_module() {
PyObject* main = ::PyImport_AddModule("__main__");
if (main == NULL)
stop(py_fetch_error());
return py_object_ptr(main, false);
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_run_string(const std::string& code)
{
PyObjectPtr main = py_main_module();
PyObject* dict = PyModule_GetDict(main);
PyObject* res = PyRun_StringFlags(code.c_str(), Py_file_input, dict, dict, NULL);
if (res == NULL)
stop(py_fetch_error());
return py_object_ptr(res);
}
//' @export
// [[Rcpp::export]]
void py_run_file(const std::string& file)
{
FILE* fp = ::fopen(file.c_str(), "r");
if (fp)
::PyRun_SimpleFile(fp, file.c_str());
else
stop("Unable to read script file '%s' (does the file exist?)", file);
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_import(const std::string& module) {
PyObject* pModule = ::PyImport_ImportModule(module.c_str());
if (pModule == NULL)
stop(py_fetch_error());
return py_object_ptr(pModule);
}
//' @export
// [[Rcpp::export(print.py_object)]]
void py_object_print(PyObjectPtr pObject) {
::PyObject_Print(pObject.get(), stdout, Py_PRINT_RAW);
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_object_get_attr(PyObjectPtr pObject, const std::string& name) {
PyObject* attr = ::PyObject_GetAttrString(pObject.get(), name.c_str());
if (attr == NULL)
stop(py_fetch_error());
return py_object_ptr(attr);
}
//' @export
// [[Rcpp::export]]
bool py_object_is_callable(PyObjectPtr pObject) {
return ::PyCallable_Check(pObject.get()) == 1;
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_object_call(PyObjectPtr pObject) {
PyObject *args = PyTuple_New(0);
PyObject *keywords = ::PyDict_New();
PyObject* res = ::PyObject_Call(pObject.get(), args, keywords);
::Py_DecRef(args);
::Py_DecRef(keywords);
if (res == NULL)
stop(py_fetch_error());
return py_object_ptr(res);
}
<commit_msg>improved error reporting<commit_after>#include "tensorflow_types.hpp"
// TODO: Capture ... (named and un-named args) and forward to call
// TODO: py_object_convert (convert from Python to R). could be as.character,
// as.matrix, as.logical, etc. Could also be done automatically or via
// some sort of dynamic type annotation mechanism
// TODO: consider R6 wrapper (would allow custom $ functions)
// TODO: .DollarNames
// TODO: Globally available import function
using namespace Rcpp;
// https://docs.python.org/2/c-api/object.html
// [[Rcpp::export]]
void py_initialize() {
::Py_Initialize();
}
// [[Rcpp::export]]
void py_finalize() {
::Py_Finalize();
}
// wrap a PyObject in an XPtr
PyObjectPtr py_object_ptr(PyObject* object, bool decref = true) {
PyObjectPtr ptr(object);
ptr.attr("class") = "py_object";
return ptr;
}
// get a string representing the last python error
std::string py_fetch_error() {
PyObject *pExcType , *pExcValue , *pExcTraceback;
::PyErr_Fetch(&pExcType , &pExcValue , &pExcTraceback) ;
if (pExcValue != NULL) {
std::ostringstream ostr;
PyObject* pStr = ::PyObject_Str(pExcValue) ;
ostr << ::PyString_AsString(pStr);
Py_DecRef(pStr) ;
Py_DecRef(pExcValue);
return ostr.str();
} else {
return "<unknown error>";
}
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_main_module() {
PyObject* main = ::PyImport_AddModule("__main__");
if (main == NULL)
stop(py_fetch_error());
return py_object_ptr(main, false);
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_run_string(const std::string& code)
{
PyObjectPtr main = py_main_module();
PyObject* dict = PyModule_GetDict(main);
PyObject* res = PyRun_StringFlags(code.c_str(), Py_file_input, dict, dict, NULL);
if (res == NULL)
stop(py_fetch_error());
return py_object_ptr(res);
}
//' @export
// [[Rcpp::export]]
void py_run_file(const std::string& file)
{
FILE* fp = ::fopen(file.c_str(), "r");
if (fp)
::PyRun_SimpleFile(fp, file.c_str());
else
stop("Unable to read script file '%s' (does the file exist?)", file);
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_import(const std::string& module) {
PyObject* pModule = ::PyImport_ImportModule(module.c_str());
if (pModule == NULL)
stop(py_fetch_error());
return py_object_ptr(pModule);
}
//' @export
// [[Rcpp::export(print.py_object)]]
void py_object_print(PyObjectPtr pObject) {
::PyObject_Print(pObject.get(), stdout, Py_PRINT_RAW);
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_object_get_attr(PyObjectPtr pObject, const std::string& name) {
PyObject* attr = ::PyObject_GetAttrString(pObject.get(), name.c_str());
if (attr == NULL)
stop(py_fetch_error());
return py_object_ptr(attr);
}
//' @export
// [[Rcpp::export]]
bool py_object_is_callable(PyObjectPtr pObject) {
return ::PyCallable_Check(pObject.get()) == 1;
}
//' @export
// [[Rcpp::export]]
PyObjectPtr py_object_call(PyObjectPtr pObject) {
PyObject *args = PyTuple_New(0);
PyObject *keywords = ::PyDict_New();
PyObject* res = ::PyObject_Call(pObject.get(), args, keywords);
::Py_DecRef(args);
::Py_DecRef(keywords);
if (res == NULL)
stop(py_fetch_error());
return py_object_ptr(res);
}
<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
*
* FILE
* result.cxx
*
* DESCRIPTION
* implementation of the pqxx::result class and support classes.
* pqxx::result represents the set of result tuples from a database query
*
* Copyright (c) 2001-2006, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-internal.hxx"
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/except"
#include "pqxx/result"
using namespace PGSTD;
const string pqxx::result::s_empty_string;
pqxx::internal::result_data::result_data() : data(0), protocol(0), query() {}
pqxx::internal::result_data::result_data(pqxx::internal::pq::PGresult *d,
int p,
const string &q) :
data(d),
protocol(p),
query(q)
{}
pqxx::internal::result_data::~result_data() { PQclear(data); }
void pqxx::internal::freemem_result_data(result_data *d) throw () { delete d; }
pqxx::result::result(pqxx::internal::pq::PGresult *rhs,
int protocol,
const string &Query) :
super(new internal::result_data(rhs, protocol, Query)),
m_data(rhs)
{}
bool pqxx::result::operator==(const result &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
for (size_type i=0; i<s; ++i)
if ((*this)[i] != rhs[i]) return false;
return true;
}
bool pqxx::result::tuple::operator==(const tuple &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
// TODO: Depends on how null is handled!
for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false;
return true;
}
void pqxx::result::tuple::swap(tuple &rhs) throw ()
{
const result *const h(m_Home);
const result::size_type i(m_Index);
m_Home = rhs.m_Home;
m_Index = rhs.m_Index;
rhs.m_Home = h;
rhs.m_Index = i;
}
bool pqxx::result::field::operator==(const field &rhs) const
{
if (is_null() != rhs.is_null()) return false;
// TODO: Verify null handling decision
const size_type s = size();
if (s != rhs.size()) return false;
const char *const l(c_str()), *const r(rhs.c_str());
for (size_type i = 0; i < s; ++i) if (l[i] != r[i]) return false;
return true;
}
pqxx::result::size_type pqxx::result::size() const throw ()
{
return m_data ? PQntuples(m_data) : 0;
}
bool pqxx::result::empty() const throw ()
{
return !m_data || !PQntuples(m_data);
}
void pqxx::result::swap(result &rhs) throw ()
{
super::swap(rhs);
m_data = (c_ptr() ? c_ptr()->data : 0);
rhs.m_data = (rhs.c_ptr() ? rhs.c_ptr()->data : 0);
}
const pqxx::result::tuple pqxx::result::at(pqxx::result::size_type i) const
throw (out_of_range)
{
if (i >= size())
throw out_of_range("Tuple number out of range");
return operator[](i);
}
void pqxx::result::ThrowSQLError(const PGSTD::string &Err,
const PGSTD::string &Query) const
{
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
// Try to establish more precise error type, and throw corresponding exception
const char *const code = PQresultErrorField(m_data, PG_DIAG_SQLSTATE);
if (code) switch (code[0])
{
case '0':
switch (code[1])
{
case '8':
throw broken_connection(Err);
case 'A':
throw feature_not_supported(Err, Query);
}
break;
case '2':
switch (code[1])
{
case '2':
throw data_exception(Err, Query);
case '3':
throw integrity_constraint_violation(Err, Query);
case '4':
throw invalid_cursor_state(Err, Query);
case '6':
throw invalid_sql_statement_name(Err, Query);
}
break;
case '3':
switch (code[1])
{
case '4':
throw invalid_cursor_name(Err, Query);
}
break;
case '4':
switch (code[1])
{
case '2':
if (strcmp(code,"42501")==0) throw insufficient_privilege(Err, Query);
if (strcmp(code,"42601")==0) throw syntax_error(Err, Query);
if (strcmp(code,"42703")==0) throw undefined_column(Err, Query);
if (strcmp(code,"42883")==0) throw undefined_function(Err, Query);
if (strcmp(code,"42P01")==0) throw undefined_table(Err, Query);
}
break;
case '5':
switch (code[1])
{
case '3':
if (strcmp(code,"53100")==0) throw disk_full(Err, Query);
if (strcmp(code,"53200")==0) throw out_of_memory(Err, Query);
if (strcmp(code,"53300")==0) throw too_many_connections(Err);
throw insufficient_resources(Err, Query);
}
break;
}
#endif
throw sql_error(Err, Query);
}
void pqxx::result::CheckStatus() const
{
const string Err = StatusError();
if (!Err.empty()) ThrowSQLError(Err, query());
}
string pqxx::result::StatusError() const
{
if (!m_data)
throw runtime_error("No result set given");
string Err;
switch (PQresultStatus(m_data))
{
case PGRES_EMPTY_QUERY: // The string sent to the backend was empty.
case PGRES_COMMAND_OK: // Successful completion of a command returning no data
case PGRES_TUPLES_OK: // The query successfully executed
break;
case PGRES_COPY_OUT: // Copy Out (from server) data transfer started
case PGRES_COPY_IN: // Copy In (to server) data transfer started
break;
case PGRES_BAD_RESPONSE: // The server's response was not understood
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
Err = PQresultErrorMessage(m_data);
break;
default:
throw internal_error("pqxx::result: Unrecognized response code " +
to_string(int(PQresultStatus(m_data))));
}
return Err;
}
const char *pqxx::result::CmdStatus() const throw ()
{
return PQcmdStatus(m_data);
}
const string &pqxx::result::query() const throw ()
{
return c_ptr() ? c_ptr()->query : s_empty_string;
}
pqxx::oid pqxx::result::inserted_oid() const
{
if (!m_data)
throw logic_error("Attempt to read oid of inserted row without an INSERT "
"result");
return PQoidValue(m_data);
}
pqxx::result::size_type pqxx::result::affected_rows() const
{
const char *const RowsStr = PQcmdTuples(m_data);
return RowsStr[0] ? atoi(RowsStr) : 0;
}
const char *pqxx::result::GetValue(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetvalue(m_data, Row, Col);
}
bool pqxx::result::GetIsNull(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetisnull(m_data, Row, Col) != 0;
}
pqxx::result::field::size_type
pqxx::result::GetLength(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetlength(m_data, Row, Col);
}
pqxx::oid pqxx::result::column_type(tuple::size_type ColNum) const
{
const oid T = PQftype(m_data, ColNum);
if (T == oid_none)
throw PGSTD::invalid_argument(
"Attempt to retrieve type of nonexistant column " +
to_string(ColNum) + " of query result");
return T;
}
#ifdef PQXX_HAVE_PQFTABLE
pqxx::oid pqxx::result::column_table(tuple::size_type ColNum) const
{
const oid T = PQftable(m_data, ColNum);
/* If we get oid_none, it may be because the column is computed, or because we
* got an invalid row number.
*/
if (T == oid_none && ColNum >= columns())
throw PGSTD::invalid_argument("Attempt to retrieve table ID for column " +
to_string(ColNum) + " out of " + to_string(columns()));
return T;
}
#endif
#ifdef PQXX_HAVE_PQFTABLECOL
pqxx::result::tuple::size_type
pqxx::result::table_column(tuple::size_type ColNum) const
{
const tuple::size_type n = PQftablecol(m_data, ColNum);
if (n) return n-1;
// Failed. Now find out why, so we can throw a sensible exception.
// Possible reasons:
// 1. Column out of range
// 2. Not using protocol 3.0 or better
// 3. Column not taken directly from a table
if (ColNum > columns())
throw out_of_range("Invalid column index in table_column(): " +
to_string(ColNum));
if (!c_ptr() || c_ptr()->protocol < 3)
throw feature_not_supported("Backend version does not support querying of "
"column's original number",
"[TABLE_COLUMN]");
throw logic_error("Can't query origin of column " + to_string(ColNum) + ": "
"not derived from table column");
}
#endif
int pqxx::result::errorposition() const throw ()
{
int pos = -1;
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
if (m_data)
{
const char *p = PQresultErrorField(m_data, PG_DIAG_STATEMENT_POSITION);
if (p) from_string(p, pos);
}
#endif // PQXX_HAVE_PQRESULTERRORFIELD
return pos;
}
// tuple
pqxx::result::field pqxx::result::tuple::operator[](const char f[]) const
{
return field(*this, m_Home->column_number(f));
}
pqxx::result::field pqxx::result::tuple::at(const char f[]) const
{
const int fnum = m_Home->column_number(f);
// TODO: Should this be an out_of_range?
if (fnum == -1)
throw invalid_argument(string("Unknown field '") + f + "'");
return field(*this, fnum);
}
pqxx::result::field
pqxx::result::tuple::at(pqxx::result::tuple::size_type i) const throw (out_of_range)
{
if (i >= size())
throw out_of_range("Invalid field number");
return operator[](i);
}
const char *
pqxx::result::column_name(pqxx::result::tuple::size_type Number) const
{
const char *const N = PQfname(m_data, Number);
if (!N)
throw out_of_range("Invalid column number: " + to_string(Number));
return N;
}
pqxx::result::tuple::size_type pqxx::result::columns() const throw ()
{
return m_data ? PQnfields(m_data) : 0;
}
pqxx::result::tuple::size_type
pqxx::result::column_number(const char ColName[]) const
{
const int N = PQfnumber(m_data, ColName);
// TODO: Should this be an out_of_range?
if (N == -1)
throw invalid_argument("Unknown column name: '" + string(ColName) + "'");
return tuple::size_type(N);
}
// const_iterator
pqxx::result::const_iterator
pqxx::result::const_iterator::operator++(int)
{
const_iterator old(*this);
m_Index++;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_iterator::operator--(int)
{
const_iterator old(*this);
m_Index--;
return old;
}
// const_fielditerator
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator++(int)
{
const_fielditerator old(*this);
m_col++;
return old;
}
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator--(int)
{
const_fielditerator old(*this);
m_col--;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_reverse_iterator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator++(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator--();
return tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator--(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator++();
return tmp;
}
pqxx::result::const_fielditerator
pqxx::result::const_reverse_fielditerator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator++(int)
{
const_reverse_fielditerator tmp(*this);
operator++();
return tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator--(int)
{
const_reverse_fielditerator tmp(*this);
operator--();
return tmp;
}
<commit_msg>Copyright update<commit_after>/*-------------------------------------------------------------------------
*
* FILE
* result.cxx
*
* DESCRIPTION
* implementation of the pqxx::result class and support classes.
* pqxx::result represents the set of result tuples from a database query
*
* Copyright (c) 2001-2007, Jeroen T. Vermeulen <jtv@xs4all.nl>
*
* See COPYING for copyright license. If you did not receive a file called
* COPYING with this source code, please notify the distributor of this mistake,
* or contact the author.
*
*-------------------------------------------------------------------------
*/
#include "pqxx/compiler-internal.hxx"
#include <stdexcept>
#include "libpq-fe.h"
#include "pqxx/except"
#include "pqxx/result"
using namespace PGSTD;
const string pqxx::result::s_empty_string;
pqxx::internal::result_data::result_data() : data(0), protocol(0), query() {}
pqxx::internal::result_data::result_data(pqxx::internal::pq::PGresult *d,
int p,
const string &q) :
data(d),
protocol(p),
query(q)
{}
pqxx::internal::result_data::~result_data() { PQclear(data); }
void pqxx::internal::freemem_result_data(result_data *d) throw () { delete d; }
pqxx::result::result(pqxx::internal::pq::PGresult *rhs,
int protocol,
const string &Query) :
super(new internal::result_data(rhs, protocol, Query)),
m_data(rhs)
{}
bool pqxx::result::operator==(const result &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
for (size_type i=0; i<s; ++i)
if ((*this)[i] != rhs[i]) return false;
return true;
}
bool pqxx::result::tuple::operator==(const tuple &rhs) const throw ()
{
if (&rhs == this) return true;
const size_type s(size());
if (rhs.size() != s) return false;
// TODO: Depends on how null is handled!
for (size_type i=0; i<s; ++i) if ((*this)[i] != rhs[i]) return false;
return true;
}
void pqxx::result::tuple::swap(tuple &rhs) throw ()
{
const result *const h(m_Home);
const result::size_type i(m_Index);
m_Home = rhs.m_Home;
m_Index = rhs.m_Index;
rhs.m_Home = h;
rhs.m_Index = i;
}
bool pqxx::result::field::operator==(const field &rhs) const
{
if (is_null() != rhs.is_null()) return false;
// TODO: Verify null handling decision
const size_type s = size();
if (s != rhs.size()) return false;
const char *const l(c_str()), *const r(rhs.c_str());
for (size_type i = 0; i < s; ++i) if (l[i] != r[i]) return false;
return true;
}
pqxx::result::size_type pqxx::result::size() const throw ()
{
return m_data ? PQntuples(m_data) : 0;
}
bool pqxx::result::empty() const throw ()
{
return !m_data || !PQntuples(m_data);
}
void pqxx::result::swap(result &rhs) throw ()
{
super::swap(rhs);
m_data = (c_ptr() ? c_ptr()->data : 0);
rhs.m_data = (rhs.c_ptr() ? rhs.c_ptr()->data : 0);
}
const pqxx::result::tuple pqxx::result::at(pqxx::result::size_type i) const
throw (out_of_range)
{
if (i >= size())
throw out_of_range("Tuple number out of range");
return operator[](i);
}
void pqxx::result::ThrowSQLError(const PGSTD::string &Err,
const PGSTD::string &Query) const
{
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
// Try to establish more precise error type, and throw corresponding exception
const char *const code = PQresultErrorField(m_data, PG_DIAG_SQLSTATE);
if (code) switch (code[0])
{
case '0':
switch (code[1])
{
case '8':
throw broken_connection(Err);
case 'A':
throw feature_not_supported(Err, Query);
}
break;
case '2':
switch (code[1])
{
case '2':
throw data_exception(Err, Query);
case '3':
throw integrity_constraint_violation(Err, Query);
case '4':
throw invalid_cursor_state(Err, Query);
case '6':
throw invalid_sql_statement_name(Err, Query);
}
break;
case '3':
switch (code[1])
{
case '4':
throw invalid_cursor_name(Err, Query);
}
break;
case '4':
switch (code[1])
{
case '2':
if (strcmp(code,"42501")==0) throw insufficient_privilege(Err, Query);
if (strcmp(code,"42601")==0) throw syntax_error(Err, Query);
if (strcmp(code,"42703")==0) throw undefined_column(Err, Query);
if (strcmp(code,"42883")==0) throw undefined_function(Err, Query);
if (strcmp(code,"42P01")==0) throw undefined_table(Err, Query);
}
break;
case '5':
switch (code[1])
{
case '3':
if (strcmp(code,"53100")==0) throw disk_full(Err, Query);
if (strcmp(code,"53200")==0) throw out_of_memory(Err, Query);
if (strcmp(code,"53300")==0) throw too_many_connections(Err);
throw insufficient_resources(Err, Query);
}
break;
}
#endif
throw sql_error(Err, Query);
}
void pqxx::result::CheckStatus() const
{
const string Err = StatusError();
if (!Err.empty()) ThrowSQLError(Err, query());
}
string pqxx::result::StatusError() const
{
if (!m_data)
throw runtime_error("No result set given");
string Err;
switch (PQresultStatus(m_data))
{
case PGRES_EMPTY_QUERY: // The string sent to the backend was empty.
case PGRES_COMMAND_OK: // Successful completion of a command returning no data
case PGRES_TUPLES_OK: // The query successfully executed
break;
case PGRES_COPY_OUT: // Copy Out (from server) data transfer started
case PGRES_COPY_IN: // Copy In (to server) data transfer started
break;
case PGRES_BAD_RESPONSE: // The server's response was not understood
case PGRES_NONFATAL_ERROR:
case PGRES_FATAL_ERROR:
Err = PQresultErrorMessage(m_data);
break;
default:
throw internal_error("pqxx::result: Unrecognized response code " +
to_string(int(PQresultStatus(m_data))));
}
return Err;
}
const char *pqxx::result::CmdStatus() const throw ()
{
return PQcmdStatus(m_data);
}
const string &pqxx::result::query() const throw ()
{
return c_ptr() ? c_ptr()->query : s_empty_string;
}
pqxx::oid pqxx::result::inserted_oid() const
{
if (!m_data)
throw logic_error("Attempt to read oid of inserted row without an INSERT "
"result");
return PQoidValue(m_data);
}
pqxx::result::size_type pqxx::result::affected_rows() const
{
const char *const RowsStr = PQcmdTuples(m_data);
return RowsStr[0] ? atoi(RowsStr) : 0;
}
const char *pqxx::result::GetValue(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetvalue(m_data, Row, Col);
}
bool pqxx::result::GetIsNull(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetisnull(m_data, Row, Col) != 0;
}
pqxx::result::field::size_type
pqxx::result::GetLength(pqxx::result::size_type Row,
pqxx::result::tuple::size_type Col) const
{
return PQgetlength(m_data, Row, Col);
}
pqxx::oid pqxx::result::column_type(tuple::size_type ColNum) const
{
const oid T = PQftype(m_data, ColNum);
if (T == oid_none)
throw PGSTD::invalid_argument(
"Attempt to retrieve type of nonexistant column " +
to_string(ColNum) + " of query result");
return T;
}
#ifdef PQXX_HAVE_PQFTABLE
pqxx::oid pqxx::result::column_table(tuple::size_type ColNum) const
{
const oid T = PQftable(m_data, ColNum);
/* If we get oid_none, it may be because the column is computed, or because we
* got an invalid row number.
*/
if (T == oid_none && ColNum >= columns())
throw PGSTD::invalid_argument("Attempt to retrieve table ID for column " +
to_string(ColNum) + " out of " + to_string(columns()));
return T;
}
#endif
#ifdef PQXX_HAVE_PQFTABLECOL
pqxx::result::tuple::size_type
pqxx::result::table_column(tuple::size_type ColNum) const
{
const tuple::size_type n = PQftablecol(m_data, ColNum);
if (n) return n-1;
// Failed. Now find out why, so we can throw a sensible exception.
// Possible reasons:
// 1. Column out of range
// 2. Not using protocol 3.0 or better
// 3. Column not taken directly from a table
if (ColNum > columns())
throw out_of_range("Invalid column index in table_column(): " +
to_string(ColNum));
if (!c_ptr() || c_ptr()->protocol < 3)
throw feature_not_supported("Backend version does not support querying of "
"column's original number",
"[TABLE_COLUMN]");
throw logic_error("Can't query origin of column " + to_string(ColNum) + ": "
"not derived from table column");
}
#endif
int pqxx::result::errorposition() const throw ()
{
int pos = -1;
#if defined(PQXX_HAVE_PQRESULTERRORFIELD)
if (m_data)
{
const char *p = PQresultErrorField(m_data, PG_DIAG_STATEMENT_POSITION);
if (p) from_string(p, pos);
}
#endif // PQXX_HAVE_PQRESULTERRORFIELD
return pos;
}
// tuple
pqxx::result::field pqxx::result::tuple::operator[](const char f[]) const
{
return field(*this, m_Home->column_number(f));
}
pqxx::result::field pqxx::result::tuple::at(const char f[]) const
{
const int fnum = m_Home->column_number(f);
// TODO: Should this be an out_of_range?
if (fnum == -1)
throw invalid_argument(string("Unknown field '") + f + "'");
return field(*this, fnum);
}
pqxx::result::field
pqxx::result::tuple::at(pqxx::result::tuple::size_type i) const throw (out_of_range)
{
if (i >= size())
throw out_of_range("Invalid field number");
return operator[](i);
}
const char *
pqxx::result::column_name(pqxx::result::tuple::size_type Number) const
{
const char *const N = PQfname(m_data, Number);
if (!N)
throw out_of_range("Invalid column number: " + to_string(Number));
return N;
}
pqxx::result::tuple::size_type pqxx::result::columns() const throw ()
{
return m_data ? PQnfields(m_data) : 0;
}
pqxx::result::tuple::size_type
pqxx::result::column_number(const char ColName[]) const
{
const int N = PQfnumber(m_data, ColName);
// TODO: Should this be an out_of_range?
if (N == -1)
throw invalid_argument("Unknown column name: '" + string(ColName) + "'");
return tuple::size_type(N);
}
// const_iterator
pqxx::result::const_iterator
pqxx::result::const_iterator::operator++(int)
{
const_iterator old(*this);
m_Index++;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_iterator::operator--(int)
{
const_iterator old(*this);
m_Index--;
return old;
}
// const_fielditerator
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator++(int)
{
const_fielditerator old(*this);
m_col++;
return old;
}
pqxx::result::const_fielditerator
pqxx::result::const_fielditerator::operator--(int)
{
const_fielditerator old(*this);
m_col--;
return old;
}
pqxx::result::const_iterator
pqxx::result::const_reverse_iterator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator++(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator--();
return tmp;
}
pqxx::result::const_reverse_iterator
pqxx::result::const_reverse_iterator::operator--(int)
{
const_reverse_iterator tmp(*this);
iterator_type::operator++();
return tmp;
}
pqxx::result::const_fielditerator
pqxx::result::const_reverse_fielditerator::base() const throw ()
{
iterator_type tmp(*this);
return ++tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator++(int)
{
const_reverse_fielditerator tmp(*this);
operator++();
return tmp;
}
pqxx::result::const_reverse_fielditerator
pqxx::result::const_reverse_fielditerator::operator--(int)
{
const_reverse_fielditerator tmp(*this);
operator--();
return tmp;
}
<|endoftext|>
|
<commit_before>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
//using namespace boost;
using namespace std;
int main()
{
using namespace boost;
string args;
while(1 != 2)
{
cout << "$ ";
getline(cin, args);
char *argv[9];
int i = 0;
vector<string> arg_s;
typedef tokenizer< char_separator<char> > tokenizer;
char_separator<char> sep(" ", "-;||&&", drop_empty_tokens);
tokenizer tokens(args, sep);
for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) {
if(*tok_iter == "&&" || *tok_iter == "||" || *tok_iter == ";") {
// argv[i] = NULL;
// int pidb = fork();
// if(pidb == -1) {
// perror("fork");
// }
// if(pidb == 0) {
// int t = execvp(argv[0], argv);
// if(t == -1) {
// perror("execvp");
// }
// }
// else {
// if(-1 == waitpid(pidb, &pidb, 0)) {
// perror("waitpid");
// }
// }
}
else {
arg_s.push_back(*tok_iter);
argv[i] = new char[12];
strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));
if(*tok_iter == "exit")
exit(1);
++i;
}
}
argv[i] = NULL;
int pid = fork();
if(pid == -1) {
perror("fork");
exit(1);
}
if(pid == 0) {
int r = execvp(argv[0], argv);
if(r == -1) {
perror("execvp");
exit(1);
}
}
else {
if(-1 == waitpid(pid, &pid, 0)) {
perror("waitpid");
}
}
// int pid = fork();
// if(pid == -1) {
// perror("fork");
// exit(1);
// }
// if(pid == 0)
// {
//char *argv2[4];
//argv2[0] = new char[6];
//strcpy(argv[0], "ls");
//argv2[1] = new char[6];
//strcpy(argv[1], "-a");
//argv2[2] = new char [6];
//strcpy(argv[2], "-l");
// int pid2 = fork();
// if(pid2 == -1) {
// perror("fork");
// exit(1);
// }
// if(pid2 == 0) {
/// if(execvp(argv[0], argv) == -1) {
// perror("execvp");
// exit(1);
// }
// }
// else {
// if(-1 == waitpid(pid2,&pid2,0 ))
// perror("waitpid");
// }
//
// if(execvp(argv[1], argv) == -1) {
// perror("execvp");
// exit(1);
// }
//
// cout << "after" << endl;
// }
// else {
// if(-1 == waitpid(pid, &pid, 0))
// perror("waitpid");
// }
}
return 0;
}
<commit_msg>rshell.cpp making progress<commit_after>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
//using namespace boost;
using namespace std;
int main()
{
using namespace boost;
string args;
while(1 != 2)
{
cout << "$ ";
getline(cin, args);
char *argv[9];
int i = 0;
vector<string> arg_s;
typedef tokenizer< char_separator<char> > tokenizer;
char_separator<char> sep(" ", "-;||&&", drop_empty_tokens);
tokenizer tokens(args, sep);
for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) {
if(*tok_iter == "&&" || *tok_iter == "||" || *tok_iter == ";") {
}
else {
arg_s.push_back(*tok_iter);
argv[i] = new char[12];
strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));
if(*tok_iter == "exit")
exit(1);
++i;
}
}
argv[i] = NULL;
int pid = fork();
if(pid == -1) {
perror("fork");
exit(1);
}
if(pid == 0) {
int r = execvp(argv[0], argv);
if(r == -1) {
perror("execvp");
exit(1);
}
}
else {
if(-1 == waitpid(pid, &pid, 0)) {
perror("waitpid");
}
}
// int pid = fork();
// if(pid == -1) {
// perror("fork");
// exit(1);
// }
// if(pid == 0)
// {
//char *argv2[4];
//argv2[0] = new char[6];
//strcpy(argv[0], "ls");
//argv2[1] = new char[6];
//strcpy(argv[1], "-a");
//argv2[2] = new char [6];
//strcpy(argv[2], "-l");
// int pid2 = fork();
// if(pid2 == -1) {
// perror("fork");
// exit(1);
// }
// if(pid2 == 0) {
/// if(execvp(argv[0], argv) == -1) {
// perror("execvp");
// exit(1);
// }
// }
// else {
// if(-1 == waitpid(pid2,&pid2,0 ))
// perror("waitpid");
// }
//
// if(execvp(argv[1], argv) == -1) {
// perror("execvp");
// exit(1);
// }
//
// cout << "after" << endl;
// }
// else {
// if(-1 == waitpid(pid, &pid, 0))
// perror("waitpid");
// }
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
using namespace std;
using namespace boost;
class Connector
{
public:
Connector();
~Connector();
bool run;
int type;
bool runNext();
bool precedence;
};
Connector::Connector()
{
// the semicolon connector allows the next command to be execute always
run = true;
type = 0; // semicolon connector set to 0
precedence = false;
}
Connector::~Connector()
{
}
bool Connector::runNext()
{
if (type == 1) // && connector
{
if (!run) // if the first command doesn't succeed it wont run the next command
{
return false;
}
}
else if (type == 2) // || connector
{
if (run) // if the first command succeed it wont run the next command
{
return false;
}
}
return true;
}
void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag);
void commandifier(string command, string argument, Connector& connect, string flag);
void test_function(string command, string flag, string argument, Connector& connect);
int main()
{
string flag;
string str;
string command;
string argument;
Connector connect;
char hostname[100];
int position = 0;
while (true)
{
printf("%s",getlogin()); // returns string containing name of user logged in
gethostname(hostname, sizeof hostname); // returns the standard host name for the current machine
cout << "@" << hostname << "$ ";
getline(cin, str);
if (str == "exit") // special command of exit
{
break;
}
vector<string> instruction; // vector of strings
typedef tokenizer<boost::char_separator<char> > Tok;
char_separator<char> sep; // default constructed
Tok tok(str, sep);;
for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) // parses the input into a command and argument
{
instruction.push_back(*tok_iter);
}
if (instruction[0] != "#") // checks for user input except for comments (#)
{
parseinator(instruction, command, argument, position, connect, flag); // parses the input into a command and argument
commandifier(command, argument, connect, flag); // runs a command with a given argument
command = "";
argument = "";
int vector_size = instruction.size();
for (; position < vector_size;) // run until the end of the instruction
{
parseinator(instruction, command, argument, position, connect, flag);
if (connect.runNext()) // checks connector to see if the next command should be ran
{
commandifier(command, argument, connect, flag);
}
else
{
while(connect.precedence && position < vector_size)
{
if(instruction[position] == ")")
{
connect.precedence = false;
}
position++;
}
connect.run = true;
command = "";
}
command = "";
argument = "";
}
position = 0;
}
}
return 0;
}
void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag)
{
if (input[position] == "&") // check if string is equal to & connector
{
connect.type = 1; // set & connector to 1
position += 2; // +=2 in order to take && connect
}
if (input[position] == "|")
{
connect.type = 2; // set | connector to 2
position += 2; // +=2 in order to take || connector
}
if (input[position] == ";")
{
connect.type = 0; // set ; connector to 0
position ++;
}
if (input[position] == "(")
{
connect.precedence = true;
position++;
}
if (input[position] != "#")
{
command = input[position];
position++;
}
if (command == "test")
{
if(input[position] == "-")
{
position++;
if (input[position] == "f")
{
flag = "-e";
position++;
}
else if (input[position] == "d")
{
flag = "-d";
position++;
}
else // DEFAULT E
{
flag = "-e";
position++;
}
}
}
int input_size = input.size();
for (; position < input_size; position++)
{
if (input[position] == ")")
{
connect.precedence = false;
position++;
break;
}
if(command == "echo" && input[position] == "\"")
{
position++;
while(input[position] != "\"" && position <= input_size)
{
argument += input[position];
if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0)))
{
}
else
{
argument += " ";
}
position++;
}
position++;
break;
}
if (input[position] == "#")
{
position = input.size();
break;
}
if (input[position] == "&" || input[position] == "|" || input[position] == ";")
{
break;
}
argument += input[position];
int input_size1 = input.size();
if (position+1 != input_size1 && command == "echo")
{
//adds spaces when echoing
argument += " ";
}
}
}
void commandifier(string command, string argument, Connector& connect, string flag)
{
const char * const_command = command.c_str();
char * char_command = new char[command.size()];
const char * const_argument = argument.c_str();
char * char_argument = new char[argument.size()];
strcpy (char_command, const_command);
strcpy (char_argument, const_argument);
char * args[2]; // char pointer array that holds command, and NULL
char * args1[3]; // char pointer array that holds command, argument, and NULL
bool no_arg = true;
bool failed = false;
if(command == "test" || command == "[")
{
test_function(command,flag,argument,connect);
return;
}
// exit command
if(command == "exit" || argument == "exit")
{
exit(1);
}
if (argument.size() == 0) // no arguments
{
args[0] = char_command; // args will contain the command
args[1] = NULL;
}
else
{
no_arg = false; // sets bool no_arg to false
args1[0] = char_command; // args1 contains command and argument
args1[1] = char_argument;
args1[2] = NULL;
}
pid_t c_pid, pid; // data type to reporesent process ID's
int status;
c_pid = fork(); // create our fork
if (c_pid < 0) // indicates the fork has fail if its less than 0
{
perror("fork failed");
exit(1);
}
else if (c_pid == 0) // in child process
{
if (no_arg) // no argument
{
execvp( args[0], args); // execvp the char pointer array that holds the command only
if (execvp(args[0], args) == -1) // if it returns -1 it failed
{
perror("execvp failed");
connect.run = false;
failed = true;
}
exit(3);
}
else // with command and argument
{
execvp(args1[0], args1); // execvp the char pointer array that holds the command, and argument
if (execvp(args1[0], args1) == -1) // if it returns -1 it failed
{
perror("execvp failed");
connect.run = false;
failed = true;
}
exit(3);
}
}
else if (c_pid > 0) // parent process
{
if((pid = wait(&status)) < 0 )
{
perror("wait");
exit(3);
}
if (WIFEXITED(status)) //Evaluates to a non-zero value if status was returned for a child process that terminated normally.
{
if (WEXITSTATUS(status) != 0)
{
connect.run = false;
}
else
{
connect.run = true;
}
}
else
{
connect.run = true;
}
}
}
void test_function(string command, string flag, string argument, Connector &connect)
{
const char * arg = argument.c_str();
struct stat sb;
if(flag == "-f")
{
switch (sb.st_mode & S_IFMT){
case S_IFREG: connect.run = true;
}
}
if(flag == "-d")
{
switch(sb.st_mode & S_IFMT){
case S_IFDIR: connect.run = true;
}
}
if(stat(arg,&sb)==0)
{
connect.run = true;
}
else
{
connect.run = false;
}
}
<commit_msg>Fixed empty command<commit_after>#include <iostream>
#include <string.h>
#include <boost/tokenizer.hpp>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
using namespace std;
using namespace boost;
class Connector
{
public:
Connector();
~Connector();
bool run;
int type;
bool runNext();
bool precedence;
};
Connector::Connector()
{
// the semicolon connector allows the next command to be execute always
run = true;
type = 0; // semicolon connector set to 0
precedence = false;
}
Connector::~Connector()
{
}
bool Connector::runNext()
{
if (type == 1) // && connector
{
if (!run) // if the first command doesn't succeed it wont run the next command
{
return false;
}
}
else if (type == 2) // || connector
{
if (run) // if the first command succeed it wont run the next command
{
return false;
}
}
return true;
}
void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag);
void commandifier(string command, string argument, Connector& connect, string flag);
void test_function(string command, string flag, string argument, Connector& connect);
int main()
{
string flag;
string str;
string command;
string argument;
Connector connect;
char hostname[100];
int position = 0;
while (true)
{
printf("%s",getlogin()); // returns string containing name of user logged in
gethostname(hostname, sizeof hostname); // returns the standard host name for the current machine
cout << "@" << hostname << "$ ";
getline(cin, str);
if (str == "exit") // special command of exit
{
break;
}
vector<string> instruction; // vector of strings
typedef tokenizer<boost::char_separator<char> > Tok;
char_separator<char> sep; // default constructed
Tok tok(str, sep);;
for (Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) // parses the input into a command and argument
{
instruction.push_back(*tok_iter);
}
if (instruction[0] != "#") // checks for user input except for comments (#)
{
parseinator(instruction, command, argument, position, connect, flag); // parses the input into a command and argument
commandifier(command, argument, connect, flag); // runs a command with a given argument
command = "";
argument = "";
int vector_size = instruction.size();
for (; position < vector_size;) // run until the end of the instruction
{
parseinator(instruction, command, argument, position, connect, flag);
if (connect.runNext() && command != "") // checks connector to see if the next command should be ran
{
commandifier(command, argument, connect, flag);
}
else
{
while(connect.precedence && position < vector_size)
{
if(instruction[position] == ")")
{
connect.precedence = false;
}
position++;
}
connect.run = true;
command = "";
}
command = "";
argument = "";
}
position = 0;
}
}
return 0;
}
void parseinator(vector<string> input, string& command, string& argument, int& position, Connector& connect, string& flag)
{
if (input[position] == "&") // check if string is equal to & connector
{
connect.type = 1; // set & connector to 1
position += 2; // +=2 in order to take && connect
}
if (input[position] == "|")
{
connect.type = 2; // set | connector to 2
position += 2; // +=2 in order to take || connector
}
if (input[position] == ";")
{
connect.type = 0; // set ; connector to 0
position ++;
}
if (input[position] == "(")
{
connect.precedence = true;
position++;
}
if (input[position] != "#")
{
command = input[position];
position++;
}
if (command == "test")
{
if(input[position] == "-")
{
position++;
if (input[position] == "f")
{
flag = "-e";
position++;
}
else if (input[position] == "d")
{
flag = "-d";
position++;
}
else // DEFAULT E
{
flag = "-e";
position++;
}
}
}
int input_size = input.size();
for (; position < input_size; position++)
{
if (input[position] == ")")
{
connect.precedence = false;
position++;
break;
}
if(command == "echo" && input[position] == "\"")
{
position++;
while(input[position] != "\"" && position <= input_size)
{
argument += input[position];
if(!isalnum(input[position].at(0)) && !isalnum(input[position+1].at(0)))
{
}
else
{
argument += " ";
}
position++;
}
position++;
break;
}
if (input[position] == "#")
{
position = input.size();
break;
}
if (input[position] == "&" || input[position] == "|" || input[position] == ";")
{
break;
}
argument += input[position];
int input_size1 = input.size();
if (position+1 != input_size1 && command == "echo")
{
//adds spaces when echoing
argument += " ";
}
}
}
void commandifier(string command, string argument, Connector& connect, string flag)
{
const char * const_command = command.c_str();
char * char_command = new char[command.size()];
const char * const_argument = argument.c_str();
char * char_argument = new char[argument.size()];
strcpy (char_command, const_command);
strcpy (char_argument, const_argument);
char * args[2]; // char pointer array that holds command, and NULL
char * args1[3]; // char pointer array that holds command, argument, and NULL
bool no_arg = true;
bool failed = false;
if(command == "test" || command == "[")
{
test_function(command,flag,argument,connect);
return;
}
// exit command
if(command == "exit" || argument == "exit")
{
exit(1);
}
if (argument.size() == 0) // no arguments
{
args[0] = char_command; // args will contain the command
args[1] = NULL;
}
else
{
no_arg = false; // sets bool no_arg to false
args1[0] = char_command; // args1 contains command and argument
args1[1] = char_argument;
args1[2] = NULL;
}
pid_t c_pid, pid; // data type to reporesent process ID's
int status;
c_pid = fork(); // create our fork
if (c_pid < 0) // indicates the fork has fail if its less than 0
{
perror("fork failed");
exit(1);
}
else if (c_pid == 0) // in child process
{
if (no_arg) // no argument
{
execvp( args[0], args); // execvp the char pointer array that holds the command only
if (execvp(args[0], args) == -1) // if it returns -1 it failed
{
perror("execvp failed");
connect.run = false;
failed = true;
}
exit(3);
}
else // with command and argument
{
execvp(args1[0], args1); // execvp the char pointer array that holds the command, and argument
if (execvp(args1[0], args1) == -1) // if it returns -1 it failed
{
perror("execvp failed");
connect.run = false;
failed = true;
}
exit(3);
}
}
else if (c_pid > 0) // parent process
{
if((pid = wait(&status)) < 0 )
{
perror("wait");
exit(3);
}
if (WIFEXITED(status)) //Evaluates to a non-zero value if status was returned for a child process that terminated normally.
{
if (WEXITSTATUS(status) != 0)
{
connect.run = false;
}
else
{
connect.run = true;
}
}
else
{
connect.run = true;
}
}
}
void test_function(string command, string flag, string argument, Connector &connect)
{
const char * arg = argument.c_str();
struct stat sb;
if(flag == "-f")
{
switch (sb.st_mode & S_IFMT){
case S_IFREG: connect.run = true;
}
}
if(flag == "-d")
{
switch(sb.st_mode & S_IFMT){
case S_IFDIR: connect.run = true;
}
}
if(stat(arg,&sb)==0)
{
connect.run = true;
}
else
{
connect.run = false;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include "scalloc.h"
#include <errno.h>
#include <string.h>
#include "allocators/block_pool.h"
#include "allocators/large_allocator.h"
#include "allocators/small_allocator.h"
#include "allocators/span_pool.h"
#include "assert.h"
#include "common.h"
#include "distributed_queue.h"
#include "override.h"
#include "scalloc_arenas.h"
#include "scalloc_guard.h"
#include "size_classes_raw.h"
#include "size_classes.h"
#include "thread_cache.h"
#include "utils.h"
#ifdef PROFILER_ON
#include "profiler.h"
#endif // PROFILER_ON
namespace scalloc {
cache_aligned Arena InternalArena;
cache_aligned Arena SmallArena;
cache_aligned const uint64_t ClassToObjects[] = {
#define SIZE_CLASS(a, b, c, d) (d),
SIZE_CLASSES
#undef SIZE_CLASS
};
cache_aligned const uint64_t ClassToSize[] = {
#define SIZE_CLASS(a, b, c, d) (b),
SIZE_CLASSES
#undef SIZE_CLASS
};
cache_aligned const uint64_t ClassToSpanSize[] = {
#define SIZE_CLASS(a, b, c, d) (c),
SIZE_CLASSES
#undef SIZE_CLASS
};
} // namespace scalloc
static int scallocguard_refcount = 0;
ScallocGuard::ScallocGuard() {
if (scallocguard_refcount++ == 0) {
ReplaceSystemAlloc();
scalloc::InternalArena.Init(kInternalSpace);
scalloc::SmallArena.Init(kSmallSpace);
DistributedQueue::InitModule();
scalloc::SpanPool::InitModule();
scalloc::BlockPool::InitModule();
scalloc::SmallAllocator::InitModule();
scalloc::ThreadCache::InitModule();
free(malloc(1));
#ifdef PROFILER_ON
scalloc::GlobalProfiler::Instance().Init();
scalloc::Profiler::Enable();
#endif // PROFILER_ON
}
}
ScallocGuard::~ScallocGuard() {
if (--scallocguard_refcount == 0) {
}
}
static ScallocGuard StartupExitHook;
namespace scalloc {
void* malloc(const size_t size) {
void* p;
if (LIKELY(size <= kMaxMediumSize && SmallAllocator::Enabled())) {
p = ThreadCache::GetCache().Allocate(size);
} else {
p = LargeAllocator::Alloc(size);
}
if (UNLIKELY(p == NULL)) {
errno = ENOMEM;
}
return p;
}
void free(void* p) {
if (UNLIKELY(p == NULL)) {
return;
}
if (SmallArena.Contains(p)) {
ThreadCache::GetCache().Free(p, reinterpret_cast<SpanHeader*>(
SpanHeader::GetFromObject(p)));
} else {
LargeAllocator::Free(reinterpret_cast<LargeObjectHeader*>(
LargeObjectHeader::GetFromObject(p)));
}
return;
}
void* calloc(size_t nmemb, size_t size) {
const size_t malloc_size = nmemb * size;
if (size != 0 && (malloc_size / size) != nmemb) {
return NULL;
}
void* result = malloc(malloc_size); // also sets errno
if (result != NULL) {
memset(result, 0, malloc_size);
}
return result;
}
void* realloc(void* ptr, size_t size) {
if (ptr == NULL) {
return malloc(size);
}
void* new_ptr;
size_t old_size;
if (scalloc::SmallArena.Contains(ptr)) {
old_size = ClassToSize[reinterpret_cast<SpanHeader*>(
SpanHeader::GetFromObject(ptr))->size_class];
} else {
old_size =
reinterpret_cast<LargeObjectHeader*>(
LargeObjectHeader::GetFromObject(ptr))->size
- sizeof(LargeObjectHeader);
}
if (size <= old_size) {
return ptr;
} else {
new_ptr = malloc(size);
if (LIKELY(new_ptr != NULL)) {
memcpy(new_ptr, ptr, old_size);
free(ptr);
}
}
return new_ptr;
}
int posix_memalign(void** ptr, size_t align, size_t size) {
if (UNLIKELY(size == 0)) { // Return free-able pointer if
*ptr = NULL; // size == 0.
return 0;
}
const size_t size_needed = align + size;
if (UNLIKELY(!utils::IsPowerOfTwo(align)) || // Power of 2 requirement.
size_needed < size) { // Overflow check.
return EINVAL;
}
uintptr_t start = reinterpret_cast<uintptr_t>(malloc(size_needed));
if (UNLIKELY(start == 0)) {
return ENOMEM;
}
if (SmallArena.Contains(reinterpret_cast<void*>(start))) {
start += (start % align);
ScallocAssert((start % align) == 0);
} else {
LargeObjectHeader* original_header = LargeObjectHeader::GetFromObject(
reinterpret_cast<void*>(start));
start += (start % align);
if ((start % kPageSize) == 0) {
uintptr_t new_hdr_adr = start - kPageSize;
if (new_hdr_adr != reinterpret_cast<uintptr_t>(original_header)) {
reinterpret_cast<LargeObjectHeader*>(new_hdr_adr)->Reset(0);
reinterpret_cast<LargeObjectHeader*>(new_hdr_adr)->fwd =
original_header;
}
}
}
*ptr = reinterpret_cast<void*>(start);
return 0;
}
void* memalign(size_t __alignment, size_t __size) {
void* mem;
if (posix_memalign(&mem, __alignment, __size)) {
return NULL;
}
return mem;
}
void* valloc(size_t __size) {
return memalign(kPageSize, __size);
}
void* pvalloc(size_t __size) {
return memalign(kPageSize, utils::PadSize(__size, kPageSize));
}
void malloc_stats(void) {}
int mallopt(int cmd, int value) {
return 0;
}
bool Ours(const void* p) {
return SmallArena.Contains(const_cast<void*>(p)) || LargeAllocator::Owns(p);
}
} // namespace scalloc
#ifndef __THROW
#define __THROW
#endif
extern "C" {
void* scalloc_malloc(size_t size) __THROW {
return scalloc::malloc(size);
}
void scalloc_free(void* p) __THROW {
scalloc::free(p);
}
void* scalloc_calloc(size_t nmemb, size_t size) __THROW {
return scalloc::calloc(nmemb, size);
}
void* scalloc_realloc(void* ptr, size_t size) __THROW {
return scalloc::realloc(ptr, size);
}
void* scalloc_memalign(size_t __alignment, size_t __size) __THROW {
return scalloc::memalign(__alignment, __size);
}
int scalloc_posix_memalign(void** ptr, size_t align, size_t size) __THROW {
return scalloc::posix_memalign(ptr, align, size);
}
void* scalloc_valloc(size_t __size) __THROW {
return scalloc::valloc(__size);
}
void* scalloc_pvalloc(size_t __size) __THROW {
return scalloc::pvalloc(__size);
}
void scalloc_malloc_stats() __THROW {
scalloc::malloc_stats();
}
int scalloc_mallopt(int cmd, int value) __THROW {
return scalloc::mallopt(cmd, value);
}
}
<commit_msg>Fix alignment in posix_memalign.<commit_after>// Copyright (c) 2012-2013, the scalloc Project Authors. All rights reserved.
// Please see the AUTHORS file for details. Use of this source code is governed
// by a BSD license that can be found in the LICENSE file.
#include "scalloc.h"
#include <errno.h>
#include <string.h>
#include "allocators/block_pool.h"
#include "allocators/large_allocator.h"
#include "allocators/small_allocator.h"
#include "allocators/span_pool.h"
#include "assert.h"
#include "common.h"
#include "distributed_queue.h"
#include "override.h"
#include "scalloc_arenas.h"
#include "scalloc_guard.h"
#include "size_classes_raw.h"
#include "size_classes.h"
#include "thread_cache.h"
#include "utils.h"
#ifdef PROFILER_ON
#include "profiler.h"
#endif // PROFILER_ON
namespace scalloc {
cache_aligned Arena InternalArena;
cache_aligned Arena SmallArena;
cache_aligned const uint64_t ClassToObjects[] = {
#define SIZE_CLASS(a, b, c, d) (d),
SIZE_CLASSES
#undef SIZE_CLASS
};
cache_aligned const uint64_t ClassToSize[] = {
#define SIZE_CLASS(a, b, c, d) (b),
SIZE_CLASSES
#undef SIZE_CLASS
};
cache_aligned const uint64_t ClassToSpanSize[] = {
#define SIZE_CLASS(a, b, c, d) (c),
SIZE_CLASSES
#undef SIZE_CLASS
};
} // namespace scalloc
static int scallocguard_refcount = 0;
ScallocGuard::ScallocGuard() {
if (scallocguard_refcount++ == 0) {
ReplaceSystemAlloc();
scalloc::InternalArena.Init(kInternalSpace);
scalloc::SmallArena.Init(kSmallSpace);
DistributedQueue::InitModule();
scalloc::SpanPool::InitModule();
scalloc::BlockPool::InitModule();
scalloc::SmallAllocator::InitModule();
scalloc::ThreadCache::InitModule();
free(malloc(1));
#ifdef PROFILER_ON
scalloc::GlobalProfiler::Instance().Init();
scalloc::Profiler::Enable();
#endif // PROFILER_ON
}
}
ScallocGuard::~ScallocGuard() {
if (--scallocguard_refcount == 0) {
}
}
static ScallocGuard StartupExitHook;
namespace scalloc {
void* malloc(const size_t size) {
void* p;
if (LIKELY(size <= kMaxMediumSize && SmallAllocator::Enabled())) {
p = ThreadCache::GetCache().Allocate(size);
} else {
p = LargeAllocator::Alloc(size);
}
if (UNLIKELY(p == NULL)) {
errno = ENOMEM;
}
return p;
}
void free(void* p) {
if (UNLIKELY(p == NULL)) {
return;
}
if (SmallArena.Contains(p)) {
ThreadCache::GetCache().Free(p, reinterpret_cast<SpanHeader*>(
SpanHeader::GetFromObject(p)));
} else {
LargeAllocator::Free(reinterpret_cast<LargeObjectHeader*>(
LargeObjectHeader::GetFromObject(p)));
}
return;
}
void* calloc(size_t nmemb, size_t size) {
const size_t malloc_size = nmemb * size;
if (size != 0 && (malloc_size / size) != nmemb) {
return NULL;
}
void* result = malloc(malloc_size); // also sets errno
if (result != NULL) {
memset(result, 0, malloc_size);
}
return result;
}
void* realloc(void* ptr, size_t size) {
if (ptr == NULL) {
return malloc(size);
}
void* new_ptr;
size_t old_size;
if (scalloc::SmallArena.Contains(ptr)) {
old_size = ClassToSize[reinterpret_cast<SpanHeader*>(
SpanHeader::GetFromObject(ptr))->size_class];
} else {
old_size =
reinterpret_cast<LargeObjectHeader*>(
LargeObjectHeader::GetFromObject(ptr))->size
- sizeof(LargeObjectHeader);
}
if (size <= old_size) {
return ptr;
} else {
new_ptr = malloc(size);
if (LIKELY(new_ptr != NULL)) {
memcpy(new_ptr, ptr, old_size);
free(ptr);
}
}
return new_ptr;
}
int posix_memalign(void** ptr, size_t align, size_t size) {
if (UNLIKELY(size == 0)) { // Return free-able pointer if
*ptr = NULL; // size == 0.
return 0;
}
const size_t size_needed = align + size;
if (UNLIKELY(!utils::IsPowerOfTwo(align)) || // Power of 2 requirement.
size_needed < size) { // Overflow check.
return EINVAL;
}
uintptr_t start = reinterpret_cast<uintptr_t>(malloc(size_needed));
if (UNLIKELY(start == 0)) {
return ENOMEM;
}
if (SmallArena.Contains(reinterpret_cast<void*>(start))) {
start += align - (start % align);
ScallocAssert((start % align) == 0);
} else {
LargeObjectHeader* original_header = LargeObjectHeader::GetFromObject(
reinterpret_cast<void*>(start));
start += align - (start % align);
if ((start % kPageSize) == 0) {
uintptr_t new_hdr_adr = start - kPageSize;
if (new_hdr_adr != reinterpret_cast<uintptr_t>(original_header)) {
reinterpret_cast<LargeObjectHeader*>(new_hdr_adr)->Reset(0);
reinterpret_cast<LargeObjectHeader*>(new_hdr_adr)->fwd =
original_header;
}
}
}
*ptr = reinterpret_cast<void*>(start);
return 0;
}
void* memalign(size_t __alignment, size_t __size) {
void* mem;
if (posix_memalign(&mem, __alignment, __size)) {
return NULL;
}
return mem;
}
void* valloc(size_t __size) {
return memalign(kPageSize, __size);
}
void* pvalloc(size_t __size) {
return memalign(kPageSize, utils::PadSize(__size, kPageSize));
}
void malloc_stats(void) {}
int mallopt(int cmd, int value) {
return 0;
}
bool Ours(const void* p) {
return SmallArena.Contains(const_cast<void*>(p)) || LargeAllocator::Owns(p);
}
} // namespace scalloc
#ifndef __THROW
#define __THROW
#endif
extern "C" {
void* scalloc_malloc(size_t size) __THROW {
return scalloc::malloc(size);
}
void scalloc_free(void* p) __THROW {
scalloc::free(p);
}
void* scalloc_calloc(size_t nmemb, size_t size) __THROW {
return scalloc::calloc(nmemb, size);
}
void* scalloc_realloc(void* ptr, size_t size) __THROW {
return scalloc::realloc(ptr, size);
}
void* scalloc_memalign(size_t __alignment, size_t __size) __THROW {
return scalloc::memalign(__alignment, __size);
}
int scalloc_posix_memalign(void** ptr, size_t align, size_t size) __THROW {
return scalloc::posix_memalign(ptr, align, size);
}
void* scalloc_valloc(size_t __size) __THROW {
return scalloc::valloc(__size);
}
void* scalloc_pvalloc(size_t __size) __THROW {
return scalloc::pvalloc(__size);
}
void scalloc_malloc_stats() __THROW {
scalloc::malloc_stats();
}
int scalloc_mallopt(int cmd, int value) __THROW {
return scalloc::mallopt(cmd, value);
}
}
<|endoftext|>
|
<commit_before>#include "debug.h"
#include "scanner.h"
namespace flora {
// Public Methods
Scanner::Scanner() {
state_ = Scanner::State::Uninitialized;
stream_ = nullptr;
peek = 0;
}
Scanner::~Scanner() {
}
void Scanner::Initialize(CharacterStream *stream) {
stream_ = stream;
state_ = Scanner::State::Running;
peek = stream->Advance();
}
Token Scanner::Advance() {
switch (state_) {
case Scanner::State::Uninitialized:
ReportScannerError("the scanner is uninitialized");
return Token::Illegal;
case Scanner::State::Running:
return Scan();
case Scanner::State::Recording: {
Token token = Scan();
records_.push(std::make_pair(token, literal_));
return token;
}
case Scanner::State::Restoring: {
// Sequeeze the first recorded token
std::pair<Token, std::string> &token = records_.front();
records_.pop();
// Check if no more recorded tokens
if (records_.empty())
state_ = Scanner::State::Running;
SetTokenLiteral(token.second);
return token.first;
}
case Scanner::State::End:
return Token::EndOfSource;
case Scanner::State::Error:
return Token::Illegal;
}
UNREACHABLE();
}
void Scanner::SaveBookmark() {
// Clean the recording queue
while (!records_.empty())
records_.pop();
// Set state to recording
state_ = Scanner::State::Recording;
}
void Scanner::LoadBookmark() {
// Set state to restoring
state_ = Scanner::State::Restoring;
}
void Scanner::ClearBookmark() {
// Clean the recording queue
while (!records_.empty())
records_.pop();
// Set state to running
state_ = Scanner::State::Running;
}
const std::string& Scanner::GetTokenLiteral() {
return literal_;
}
// Private methods
char32_t Scanner::Next() {
char32_t save = peek;
peek = stream_->Advance();
return save;
}
bool Scanner::Match(char32_t expected) {
if (expected == peek) {
peek = stream_->Advance();
return true;
}
return false;
}
void Scanner::SetTokenLiteral(const char *literal) {
literal_.assign(literal);
}
void Scanner::SetTokenLiteral(std::string &literal) {
literal_ = std::move(literal);
}
void Scanner::SetTokenLiteral(char literal) {
literal_.clear();
literal_.push_back(literal);
}
void Scanner::ClearTokenLiteral() {
literal_.clear();
}
void Scanner::ReportScannerError(const char *message) {
state_ = Scanner::State::Error;
SetTokenLiteral(message);
}
void Scanner::MarkEndOfSource() {
state_ = Scanner::State::End;
}
Token Scanner::Scan() {
DEBUG_LOG("Scanning...");
ClearTokenLiteral();
char32_t ch;
while (true) {
switch (ch = Next()) {
case character::EOS:
MarkEndOfSource();
return Token::EndOfSource;
case '\n':
case ' ':
case '\t':
continue;
case '(': return Token::LeftParenthesis;
case ')': return Token::RightParenthesis;
case '[': return Token::LeftBracket;
case ']': return Token::RightBracket;
case '{': return Token::LeftBrace;
case '}': return Token::RightBrace;
case ':': return Token::Colon;
case ';': return Token::Semicolon;
case '~': return Token::BitwiseNot;
case '?': return Token::Conditional;
case ',': return Token::Comma;
case '.': // . ...
if (Match('.')) {
if (Match('.')) {
return Token::Ellipsis;
} else {
ReportScannerError("illegal token");
return Token::Illegal;
}
}
return Token::Period;
case '&': // & && &=
if (Match('&')) {
return Token::LogicalAnd;
} else if (Match('=')) {
return Token::AssignmentBitwiseAnd;
} else {
return Token::BitwiseAnd;
}
case '|': // | || |=
if (Match('|')) {
return Token::LogicalOr;
} else if (Match('=')) {
return Token::AssignmentBitwiseOr;
} else {
return Token::BitwiseOr;
}
case '^': // ^ ^=
return Match('=') ? Token::AssignmentBitwiseXor : Token::BitwiseXor;
case '<': // < << <= <<=
if (Match('<')) {
return Match('=') ? Token::AssignmentShiftLeft : Token::ShiftLeft;
} else if (Match('=')) {
return Token::LessThanOrEqual;
} else {
return Token::LessThan;
}
case '>': // > >> >= >>=
if (Match('>')) {
return Match('=') ? Token::AssignmentShiftRight : Token::ShiftRight;
} else if (Match('=')) {
return Token::GreaterThanOrEqual;
} else {
return Token::GreaterThan;
}
case '!': // ! !=
return Match('=') ? Token::NotEqual : Token::LogicalNot;
case '=': // = == =>
if (Match('>')) {
return Token::Arrow;
} else if (Match('=')) {
return Token::Equal;
} else {
return Token::Assignment;
}
case '+': // + ++ +=
if (Match('+')) {
return Token::Increment;
} else if (Match('=')) {
return Token::AssignmentAddition;
} else {
return Token::Addition;
}
case '-': // - -- -=
if (Match('-')) {
return Token::Decrement;
} else if (Match('=')) {
return Token::AssignmentSubtraction;
} else {
return Token::Subtraction;
}
case '*': // * *=
return Match('=') ? Token::AssignmentMultiplication:Token::Multiplication;
case '/': // / /= /* multiple line comment */ // single line comment
if (Match('=')) {
return Token::AssignmentDivision;
} else if (Match('*')) {
SkipMultipleLineComment();
} else if (Match('/')) {
SkipSingleLineComment();
} else {
return Token::Division;
}
continue;
case '%': // % %=
return Match('=') ? Token::AssignmentModulus : Token::Modulus;
case '"': // string literal
return ScanStringLiteral();
case '\'': // character literal
return ScanCharacterLiteral();
default:
if (character::IsIdentifierStart(ch)) {
return ScanIdentifierOrKeyword(ch);
} else if (character::IsDecimalDigit(ch)) {
return ScanIntegerOrRealNumber(ch);
} else {
ReportScannerError("unknown token");
return Token::Illegal;
}
}
}
}
bool Scanner::SkipMultipleLineComment() {
int cascade = 1;
char ch;
while (true) {
ch = Next();
if (ch == '/') {
if (peek == '*') {
Next();
cascade++;
}
} else if (ch == '*') {
if (peek == '/') {
Next();
cascade--;
if (cascade == 0) break;
}
} else if (ch == character::EOS) {
ReportScannerError("unexpected end of source in multiple line comment");
return false;
}
}
return true;
}
void Scanner::SkipSingleLineComment() {
while (!character::IsLineFeed(peek) && peek != character::EOS)
Next();
}
Token Scanner::ScanStringLiteral() {
std::string literal;
char32_t ch;
while (true) {
ch = Next();
if (ch == character::EOS) {
ReportScannerError("unexpected EOF in string literal");
return Token::Illegal;
} else if (ch == '\\') {
ch = ScanCharacterEscape();
if (ch == character::EOS)
return Token::Illegal;
literal.push_back(ch);
} else if (ch == '"') {
break;
} else {
literal.push_back(ch);
}
}
SetTokenLiteral(literal);
return Token::String;
}
Token Scanner::ScanCharacterLiteral() {
char32_t literal = Next();
if (literal == character::EOS) {
ReportScannerError("unexpected EOF in character literal");
return Token::Illegal;
} else if (literal == '\\') {
literal = ScanCharacterEscape();
if (literal == character::EOS)
return Token::Illegal;
}
// to ensure that there is only one character in literal
if (Next() != '\'') {
ReportScannerError("too more character in literal");
return Token::Illegal;
}
SetTokenLiteral(literal);
return Token::Character;
}
char32_t Scanner::ScanCharacterEscape() {
char32_t codepoint = 0;
switch (peek) {
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case '\\': return '\\';
case '\'': return '\'';
case '\"': return '\"';
case 'u':
Next();
while (character::IsDecimalDigit(peek)) {
codepoint *= 10;
codepoint += peek - '0';
Next();
}
return codepoint;
case 'x':
Next();
while (character::IsHexDigit(peek)) {
codepoint *= 16;
if (character::IsDecimalDigit(peek)) {
codepoint += peek - '0';
} else {
codepoint += 10 + character::AsciiToLowerCase(peek) - 'a';
}
Next();
}
return codepoint;
default:
ReportScannerError("illegal character escape");
return character::EOS;
}
}
Token Scanner::ScanIdentifierOrKeyword(char32_t firstChar) {
std::string identifier;
identifier.push_back(firstChar);
while (character::IsIdentifierBody(peek)) {
identifier.push_back(Next());
}
Token token = Tokens::LookupKeyword(identifier);
if (token == Token::Identifier)
SetTokenLiteral(identifier);
return token;
}
Token Scanner::ScanIntegerOrRealNumber(char32_t firstChar) {
// There are 4 kinds of integer:
// (1) Hexidecimal integer
// (2) Decimal integer
// (3) Octal integer
// (4) Binary integer
// (1), (3) and (4) has a prefix, so we can easily dintinguish them
std::string num;
if (firstChar == '0') {
if (peek == 'x') {
Next();
return ScanHexInteger();
} else if (peek == 'o') {
Next();
return ScanOctalInteger();
} else if (peek == 'b') {
Next();
return ScanBinaryInteger();
}
}
num.push_back(firstChar);
// Scan the integral part
while (character::IsDecimalDigit(peek)) {
num.push_back(firstChar);
}
// Real number
if (peek == '.' || character::AsciiToLowerCase(peek) == 'e') {
return ScanRealNumber(&num);
}
// Integer
SetTokenLiteral(num);
return Token::Integer;
}
Token Scanner::ScanRealNumber(const std::string *integral_part,
bool scanned_period) {
std::string num;
if (integral_part) {
num = *integral_part;
} else {
num.push_back('0');
}
// Fraction part
if (Match('.')) {
while (character::IsDecimalDigit(peek)) {
num.push_back(Next());
}
}
// Exponent part
if (peek == 'E' || peek == 'e') {
num.push_back(Next());
if (peek == '+' || peek == '-')
num.push_back(Next());
// An error circumstance: 1.234E
if (!character::IsDecimalDigit(peek)) {
ReportScannerError("unexpected end of source in real number literal");
return Token::Illegal;
}
while (character::IsDecimalDigit(peek)) {
num.push_back(Next());
}
}
SetTokenLiteral(num);
return Token::RealNumber;
}
#define SCAN_INTEGER(base, ch, checker)\
Token Scanner::Scan##base##Integer() {\
std::string num;\
num.push_back(ch);\
if (!checker(peek)) {\
ReportScannerError("unexpected end of source in integer literal");\
return Token::Illegal;\
}\
while (checker(peek))\
num.push_back(Next());\
SetTokenLiteral(num);\
return Token::Integer;\
}
SCAN_INTEGER(Hex, 'x', character::IsHexDigit)
SCAN_INTEGER(Octal, 'o', character::IsOctalDigit)
SCAN_INTEGER(Binary, 'b', character::IsBinaryDigit)
}<commit_msg>Remove debug print...<commit_after>#include "debug.h"
#include "scanner.h"
namespace flora {
// Public Methods
Scanner::Scanner() {
state_ = Scanner::State::Uninitialized;
stream_ = nullptr;
peek = 0;
}
Scanner::~Scanner() {
}
void Scanner::Initialize(CharacterStream *stream) {
stream_ = stream;
state_ = Scanner::State::Running;
peek = stream->Advance();
}
Token Scanner::Advance() {
switch (state_) {
case Scanner::State::Uninitialized:
ReportScannerError("the scanner is uninitialized");
return Token::Illegal;
case Scanner::State::Running:
return Scan();
case Scanner::State::Recording: {
Token token = Scan();
records_.push(std::make_pair(token, literal_));
return token;
}
case Scanner::State::Restoring: {
// Sequeeze the first recorded token
std::pair<Token, std::string> &token = records_.front();
records_.pop();
// Check if no more recorded tokens
if (records_.empty())
state_ = Scanner::State::Running;
SetTokenLiteral(token.second);
return token.first;
}
case Scanner::State::End:
return Token::EndOfSource;
case Scanner::State::Error:
return Token::Illegal;
}
UNREACHABLE();
}
void Scanner::SaveBookmark() {
// Clean the recording queue
while (!records_.empty())
records_.pop();
// Set state to recording
state_ = Scanner::State::Recording;
}
void Scanner::LoadBookmark() {
// Set state to restoring
state_ = Scanner::State::Restoring;
}
void Scanner::ClearBookmark() {
// Clean the recording queue
while (!records_.empty())
records_.pop();
// Set state to running
state_ = Scanner::State::Running;
}
const std::string& Scanner::GetTokenLiteral() {
return literal_;
}
// Private methods
char32_t Scanner::Next() {
char32_t save = peek;
peek = stream_->Advance();
return save;
}
bool Scanner::Match(char32_t expected) {
if (expected == peek) {
peek = stream_->Advance();
return true;
}
return false;
}
void Scanner::SetTokenLiteral(const char *literal) {
literal_.assign(literal);
}
void Scanner::SetTokenLiteral(std::string &literal) {
literal_ = std::move(literal);
}
void Scanner::SetTokenLiteral(char literal) {
literal_.clear();
literal_.push_back(literal);
}
void Scanner::ClearTokenLiteral() {
literal_.clear();
}
void Scanner::ReportScannerError(const char *message) {
state_ = Scanner::State::Error;
SetTokenLiteral(message);
}
void Scanner::MarkEndOfSource() {
state_ = Scanner::State::End;
}
Token Scanner::Scan() {
ClearTokenLiteral();
char32_t ch;
while (true) {
switch (ch = Next()) {
case character::EOS:
MarkEndOfSource();
return Token::EndOfSource;
case '\n':
case ' ':
case '\t':
continue;
case '(': return Token::LeftParenthesis;
case ')': return Token::RightParenthesis;
case '[': return Token::LeftBracket;
case ']': return Token::RightBracket;
case '{': return Token::LeftBrace;
case '}': return Token::RightBrace;
case ':': return Token::Colon;
case ';': return Token::Semicolon;
case '~': return Token::BitwiseNot;
case '?': return Token::Conditional;
case ',': return Token::Comma;
case '.': // . ...
if (Match('.')) {
if (Match('.')) {
return Token::Ellipsis;
} else {
ReportScannerError("illegal token");
return Token::Illegal;
}
}
return Token::Period;
case '&': // & && &=
if (Match('&')) {
return Token::LogicalAnd;
} else if (Match('=')) {
return Token::AssignmentBitwiseAnd;
} else {
return Token::BitwiseAnd;
}
case '|': // | || |=
if (Match('|')) {
return Token::LogicalOr;
} else if (Match('=')) {
return Token::AssignmentBitwiseOr;
} else {
return Token::BitwiseOr;
}
case '^': // ^ ^=
return Match('=') ? Token::AssignmentBitwiseXor : Token::BitwiseXor;
case '<': // < << <= <<=
if (Match('<')) {
return Match('=') ? Token::AssignmentShiftLeft : Token::ShiftLeft;
} else if (Match('=')) {
return Token::LessThanOrEqual;
} else {
return Token::LessThan;
}
case '>': // > >> >= >>=
if (Match('>')) {
return Match('=') ? Token::AssignmentShiftRight : Token::ShiftRight;
} else if (Match('=')) {
return Token::GreaterThanOrEqual;
} else {
return Token::GreaterThan;
}
case '!': // ! !=
return Match('=') ? Token::NotEqual : Token::LogicalNot;
case '=': // = == =>
if (Match('>')) {
return Token::Arrow;
} else if (Match('=')) {
return Token::Equal;
} else {
return Token::Assignment;
}
case '+': // + ++ +=
if (Match('+')) {
return Token::Increment;
} else if (Match('=')) {
return Token::AssignmentAddition;
} else {
return Token::Addition;
}
case '-': // - -- -=
if (Match('-')) {
return Token::Decrement;
} else if (Match('=')) {
return Token::AssignmentSubtraction;
} else {
return Token::Subtraction;
}
case '*': // * *=
return Match('=') ? Token::AssignmentMultiplication:Token::Multiplication;
case '/': // / /= /* multiple line comment */ // single line comment
if (Match('=')) {
return Token::AssignmentDivision;
} else if (Match('*')) {
SkipMultipleLineComment();
} else if (Match('/')) {
SkipSingleLineComment();
} else {
return Token::Division;
}
continue;
case '%': // % %=
return Match('=') ? Token::AssignmentModulus : Token::Modulus;
case '"': // string literal
return ScanStringLiteral();
case '\'': // character literal
return ScanCharacterLiteral();
default:
if (character::IsIdentifierStart(ch)) {
return ScanIdentifierOrKeyword(ch);
} else if (character::IsDecimalDigit(ch)) {
return ScanIntegerOrRealNumber(ch);
} else {
ReportScannerError("unknown token");
return Token::Illegal;
}
}
}
}
bool Scanner::SkipMultipleLineComment() {
int cascade = 1;
char ch;
while (true) {
ch = Next();
if (ch == '/') {
if (peek == '*') {
Next();
cascade++;
}
} else if (ch == '*') {
if (peek == '/') {
Next();
cascade--;
if (cascade == 0) break;
}
} else if (ch == character::EOS) {
ReportScannerError("unexpected end of source in multiple line comment");
return false;
}
}
return true;
}
void Scanner::SkipSingleLineComment() {
while (!character::IsLineFeed(peek) && peek != character::EOS)
Next();
}
Token Scanner::ScanStringLiteral() {
std::string literal;
char32_t ch;
while (true) {
ch = Next();
if (ch == character::EOS) {
ReportScannerError("unexpected EOF in string literal");
return Token::Illegal;
} else if (ch == '\\') {
ch = ScanCharacterEscape();
if (ch == character::EOS)
return Token::Illegal;
literal.push_back(ch);
} else if (ch == '"') {
break;
} else {
literal.push_back(ch);
}
}
SetTokenLiteral(literal);
return Token::String;
}
Token Scanner::ScanCharacterLiteral() {
char32_t literal = Next();
if (literal == character::EOS) {
ReportScannerError("unexpected EOF in character literal");
return Token::Illegal;
} else if (literal == '\\') {
literal = ScanCharacterEscape();
if (literal == character::EOS)
return Token::Illegal;
}
// to ensure that there is only one character in literal
if (Next() != '\'') {
ReportScannerError("too more character in literal");
return Token::Illegal;
}
SetTokenLiteral(literal);
return Token::Character;
}
char32_t Scanner::ScanCharacterEscape() {
char32_t codepoint = 0;
switch (peek) {
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case '\\': return '\\';
case '\'': return '\'';
case '\"': return '\"';
case 'u':
Next();
while (character::IsDecimalDigit(peek)) {
codepoint *= 10;
codepoint += peek - '0';
Next();
}
return codepoint;
case 'x':
Next();
while (character::IsHexDigit(peek)) {
codepoint *= 16;
if (character::IsDecimalDigit(peek)) {
codepoint += peek - '0';
} else {
codepoint += 10 + character::AsciiToLowerCase(peek) - 'a';
}
Next();
}
return codepoint;
default:
ReportScannerError("illegal character escape");
return character::EOS;
}
}
Token Scanner::ScanIdentifierOrKeyword(char32_t firstChar) {
std::string identifier;
identifier.push_back(firstChar);
while (character::IsIdentifierBody(peek)) {
identifier.push_back(Next());
}
Token token = Tokens::LookupKeyword(identifier);
if (token == Token::Identifier)
SetTokenLiteral(identifier);
return token;
}
Token Scanner::ScanIntegerOrRealNumber(char32_t firstChar) {
// There are 4 kinds of integer:
// (1) Hexidecimal integer
// (2) Decimal integer
// (3) Octal integer
// (4) Binary integer
// (1), (3) and (4) has a prefix, so we can easily dintinguish them
std::string num;
if (firstChar == '0') {
if (peek == 'x') {
Next();
return ScanHexInteger();
} else if (peek == 'o') {
Next();
return ScanOctalInteger();
} else if (peek == 'b') {
Next();
return ScanBinaryInteger();
}
}
num.push_back(firstChar);
// Scan the integral part
while (character::IsDecimalDigit(peek)) {
num.push_back(firstChar);
}
// Real number
if (peek == '.' || character::AsciiToLowerCase(peek) == 'e') {
return ScanRealNumber(&num);
}
// Integer
SetTokenLiteral(num);
return Token::Integer;
}
Token Scanner::ScanRealNumber(const std::string *integral_part,
bool scanned_period) {
std::string num;
if (integral_part) {
num = *integral_part;
} else {
num.push_back('0');
}
// Fraction part
if (Match('.')) {
while (character::IsDecimalDigit(peek)) {
num.push_back(Next());
}
}
// Exponent part
if (peek == 'E' || peek == 'e') {
num.push_back(Next());
if (peek == '+' || peek == '-')
num.push_back(Next());
// An error circumstance: 1.234E
if (!character::IsDecimalDigit(peek)) {
ReportScannerError("unexpected end of source in real number literal");
return Token::Illegal;
}
while (character::IsDecimalDigit(peek)) {
num.push_back(Next());
}
}
SetTokenLiteral(num);
return Token::RealNumber;
}
#define SCAN_INTEGER(base, ch, checker)\
Token Scanner::Scan##base##Integer() {\
std::string num;\
num.push_back(ch);\
if (!checker(peek)) {\
ReportScannerError("unexpected end of source in integer literal");\
return Token::Illegal;\
}\
while (checker(peek))\
num.push_back(Next());\
SetTokenLiteral(num);\
return Token::Integer;\
}
SCAN_INTEGER(Hex, 'x', character::IsHexDigit)
SCAN_INTEGER(Octal, 'o', character::IsOctalDigit)
SCAN_INTEGER(Binary, 'b', character::IsBinaryDigit)
}<|endoftext|>
|
<commit_before>#include <string>
#include <nds.h>
#include <nds/debug.h>
#include "./math.h"
#include "./sprite.h"
#include "./debug.h"
namespace FMAW {
//------------------------------------------------------------------------------
// Common sprite helpers.
//------------------------------------------------------------------------------
void clearAllSprites() {
for ( sprite_id id = 0; id < TOTAL_SPRITES; id++ ) {
Sprite sprite (id);
sprite.clear();
}
}
//------------------------------------------------------------------------------
// Sprite class.
//------------------------------------------------------------------------------
uint8 Sprite::nextEmptySprite = 0;
//----------//------------------------------------------------------------------
//----------// Position.
//----------//------------------------------------------------------------------
bool Sprite::setXPosition( int x ) {
bool isNegative = x < 0;
if ( isNegative ) x = -x;
uint16 xCapped = x & 0x00FF;
printf("X Original: %d New: %u", x, xCapped);
if ( x != xCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) x = twosComplement9B(x);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
x |= 0xFE00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr1 |= 0x01FF;
// Now we can set position with a simple AND.
sprites[this->id].attr1 &= x;
return true;
}
bool Sprite::setYPosition( int y ) {
bool isNegative = y < 0;
if ( isNegative ) y = -y;
uint16 yCapped = y & 0x007F;
printf("Y Original: %d New: %u", y, yCapped);
if ( y != yCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) y = twosComplement8B(y);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
y |= 0xFF00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr0 |= 0x00FF;
// Now we can set position with a simple AND.
sprites[this->id].attr0 &= y;
return true;
}
bool Sprite::setPosition( int x, int y ) {
Point previousPosition = this->getPosition();
if ( this->setXPosition( x ) && this->setYPosition( y ) ) return true;
else {
this->setXPosition( previousPosition.x );
this->setYPosition( previousPosition.y );
return false;
}
return true;
}
bool Sprite::setPosition( Point point ) {
return this->setPosition( point.x, point.y );
}
int Sprite::getXPosition() {
uint8 x = sprites[this->id].attr1 & 0x01FF;
// If x-position was a negative number...
if ( (x & 0x0100) != 0 ) return -twosComplement9B(x);
return x;
}
int Sprite::getYPosition() {
uint8 y = sprites[this->id].attr0 & 0x00FF;
// If y-position was a negative number...
if ( (y & 0x0080) != 0 ) return -twosComplement8B(y);
return y;
}
Point Sprite::getPosition() {
Point p {};
p.x = this->getXPosition();
p.y = this->getYPosition();
return p;
}
//----------//------------------------------------------------------------------
//----------// Tile & palette settings.
//----------//------------------------------------------------------------------
bool Sprite::setTile( uint16 tileIndex ) {
uint16 tileIndexCapped = tileIndex & 0x01FF;
if ( tileIndex != tileIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0x01FF;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= tileIndexCapped;
return true;
}
uint16 Sprite::getTile() {
return sprites[this->id].attr2 & 0x01FF;
}
bool Sprite::setPalette( uint8 paletteIndex ) {
uint8 paletteIndexCapped = paletteIndex & 0x000F;
if ( paletteIndex != paletteIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0xF000;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= paletteIndexCapped << 12;
return true;
}
uint8 Sprite::getPalette() {
return (sprites[this->id].attr2 & 0xF000) >> 12;
}
//----------//------------------------------------------------------------------
//----------// Rotation & scale settings.
//----------//------------------------------------------------------------------
void Sprite::enableRotationAndScale() {
sprites[this->id].attr0 |= 0x0100;
}
void Sprite::disableRotationAndScale() {
sprites[this->id].attr0 &= 0xFEFF;
}
bool Sprite::rotationAndScaleAreEnabled() {
return (sprites[this->id].attr0 & 0x0100) != 0 ;
}
bool Sprite::rotationAndScaleAreDisabled() {
return !this->rotationAndScaleAreEnabled();
}
void Sprite::enableDoubleSize() {
sprites[this->id].attr0 |= 0x0200;
}
void Sprite::disableDoubleSize() {
sprites[this->id].attr0 &= 0xFDFF;
}
bool Sprite::doubleSizeEnabled() {
return (sprites[this->id].attr0 = 0x0200) != 0;
}
bool Sprite::doubleSizeDisabled() {
return !this->doubleSizeEnabled();
}
//----------//------------------------------------------------------------------
//----------// Object mode settings.
//----------//------------------------------------------------------------------
void Sprite::setObjectMode( SpriteObjectMode newMode ) {
sprites[this->id].attr0 |= 0x0C00;
sprites[this->id].attr0 &= newMode;
}
SpriteObjectMode Sprite::getObjectMode() {
uint16 half_word = sprites[this->id].attr0 | 0xF3FF;
switch (half_word) {
case normal:
return normal;
case alpha_first_target:
return normal;
case add_to_window:
return add_to_window;
case bitmap:
return bitmap;
default:
// This won't ever happen.
return normal;
}
}
//----------//------------------------------------------------------------------
//----------// Mosaic & color settings.
//----------//------------------------------------------------------------------
void Sprite::enableMosaic() {
sprites[this->id].attr0 |= 0x1000;
}
void Sprite::disableMosaic() {
sprites[this->id].attr0 &= 0xEFFF;
}
bool Sprite::mosaicIsEnabled() {
return (sprites[this->id].attr0 & 0x1000) != 0;
}
bool Sprite::mosaicIsDisabled() {
return !this->mosaicIsEnabled();
}
void Sprite::use16BitColors() {
sprites[this->id].attr0 &= 0xDFFF;
}
void Sprite::use256BitColors() {
sprites[this->id].attr0 |= 0x2000;
}
bool Sprite::isUsing16BitColors() {
return (sprites[this->id].attr0 & 0x2000) != 0;
}
bool Sprite::isUsing256BitColors() {
return !this->isUsing16BitColors();
}
//----------//------------------------------------------------------------------
//----------// Shape & size settings.
//----------//------------------------------------------------------------------
bool Sprite::setSizeMode( SpriteSizeMode newMode ) {
uint16 attr0mask;
uint16 attr1mask;
switch ( newMode ) {
case square8x8:
case square16x16:
case square32x32:
case square64x64:
attr0mask = 0x3FFF;
break;
case wide16x8:
case wide32x8:
case wide32x16:
case wide64x32:
attr0mask = 0x7FFF;
break;
case tall8x16:
case tall8x32:
case tall16x32:
case tall32x64:
attr0mask = 0xBFFF;
break;
default:
return false;
}
switch ( newMode ) {
case square8x8:
case wide16x8:
case tall8x16:
attr1mask = 0x3FFF;
break;
case square16x16:
case wide32x8:
case tall8x32:
attr1mask = 0x7FFF;
break;
case square32x32:
case wide32x16:
case tall16x32:
attr1mask = 0xBFFF;
break;
case square64x64:
case wide64x32:
case tall32x64:
attr1mask = 0xFFFF;
break;
default:
return false;
}
// We first set the size bits to 1.
sprites[this->id].attr0 |= 0XC000;
sprites[this->id].attr1 |= 0XC000;
// And then we apply the mask.
sprites[this->id].attr0 &= attr0mask;
sprites[this->id].attr1 &= attr1mask;
return true;
}
SpriteSizeMode Sprite::getSizeMode() {
uint16 shape = sprites[this->id].attr0 & 0xC000;
uint16 size = sprites[this->id].attr1 & 0xC000;
SpriteSizeMode sizeMode;
switch ( shape ) {
// Square.
case 0x0000:
switch (size) {
case 0x0000:
sizeMode = square8x8;
break;
case 0x4000:
sizeMode = square16x16;
break;
case 0x8000:
sizeMode = square32x32;
break;
case 0xC000:
sizeMode = square64x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Wide.
case 0x4000:
switch (size) {
case 0x0000:
sizeMode = wide16x8;
break;
case 0x4000:
sizeMode = wide32x8;
break;
case 0x8000:
sizeMode = wide32x16;
break;
case 0xC000:
sizeMode = wide64x32;
break;
default:
sizeMode = unknown;
break;
}
break;
// Tall.
case 0x8000:
switch (size) {
case 0x0000:
sizeMode = tall8x16;
break;
case 0x4000:
sizeMode = tall8x32;
break;
case 0x8000:
sizeMode = tall16x32;
break;
case 0xC000:
sizeMode = tall32x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Not used.
case 0xC000:
default:
sizeMode = unknown;
break;
}
return sizeMode;
}
//----------//------------------------------------------------------------------
//----------// Flip settings.
//----------//------------------------------------------------------------------
void Sprite::enableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 |= 0x1000;
}
void Sprite::disableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 &= 0xEFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::horizontalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !horizontalFlipIsEnabled() !!
bool Sprite::horizontalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) == 0;
}
void Sprite::enableVerticalFlip() {
sprites[this->id].attr1 |= 0x2000;
}
void Sprite::disableVerticalFlip() {
sprites[this->id].attr1 &= 0xDFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::verticalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !verticalFlipIsEnabled() !!
bool Sprite::verticalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) == 0;
}
//----------//------------------------------------------------------------------
//----------// Priority settings.
//----------//------------------------------------------------------------------
void Sprite::setPriority( SpritePriority priority ) {
sprites[this->id].attr2 |= 0x0C00;
sprites[this->id].attr2 &= priority;
}
SpritePriority Sprite::getPriority() {
uint16 half_word = sprites[this->id].attr2 | 0xF3FF;
switch (half_word) {
case spHIGHEST:
return spHIGHEST;
case spHIGH:
return spHIGH;
case spLOW:
return spLOW;
case spLOWEST:
return spLOWEST;
default:
// This won't ever happen.
return spHIGHEST;
}
}
//----------//------------------------------------------------------------------
//----------// Other settings.
//----------//------------------------------------------------------------------
void Sprite::clear() {
sprites[this->id].attr0 = ATTR0_DISABLED;
sprites[this->id].attr1 = 0;
sprites[this->id].attr2 = 0;
sprites[this->id].affine_data = 0;
}
void Sprite::disable() {
uint16 disableMask = 0xFEFF;
sprites[this->id].attr0 &= disableMask;
}
void Sprite::enable() {
uint16 enableMask = 0xFCFF;
sprites[this->id].attr0 &= enableMask;
}
void Sprite::print() {
FMAW::printf("%s\r\n Sprite %u:%s\r\n|%s|",
"\r\n|----------------|", this->id, "\r\n|----------------|",
half_word_to_binary(sprites[this->id].attr0).c_str());
FMAW::printf("|%s|\r\n|%s|",
half_word_to_binary(sprites[this->id].attr1).c_str(),
half_word_to_binary(sprites[this->id].attr2).c_str());
FMAW::printf("|%s|\r\n%s",
half_word_to_binary(sprites[this->id].affine_data).c_str(),
"|----------------|");
}
}<commit_msg>Minor type change<commit_after>#include <string>
#include <nds.h>
#include "./math.h"
#include "./sprite.h"
#include "./debug.h"
namespace FMAW {
//------------------------------------------------------------------------------
// Common sprite helpers.
//------------------------------------------------------------------------------
void clearAllSprites() {
for ( sprite_id id = 0; id < TOTAL_SPRITES; id++ ) {
Sprite sprite (id);
sprite.clear();
}
}
//------------------------------------------------------------------------------
// Sprite class.
//------------------------------------------------------------------------------
sprite_id Sprite::nextEmptySprite = 0;
//----------//------------------------------------------------------------------
//----------// Position.
//----------//------------------------------------------------------------------
bool Sprite::setXPosition( int x ) {
bool isNegative = x < 0;
if ( isNegative ) x = -x;
uint16 xCapped = x & 0x00FF;
printf("X Original: %d New: %u", x, xCapped);
if ( x != xCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) x = twosComplement9B(x);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
x |= 0xFE00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr1 |= 0x01FF;
// Now we can set position with a simple AND.
sprites[this->id].attr1 &= x;
return true;
}
bool Sprite::setYPosition( int y ) {
bool isNegative = y < 0;
if ( isNegative ) y = -y;
uint16 yCapped = y & 0x007F;
printf("Y Original: %d New: %u", y, yCapped);
if ( y != yCapped ) return false;
// If x was negative we have to apply 2's complement.
if ( isNegative ) y = twosComplement8B(y);
// We have to set the upper part of the half-word to 1 so AND doesn't
// break anything.
y |= 0xFF00;
// We have to set position's bits to 1 so we can then make an AND.
sprites[this->id].attr0 |= 0x00FF;
// Now we can set position with a simple AND.
sprites[this->id].attr0 &= y;
return true;
}
bool Sprite::setPosition( int x, int y ) {
Point previousPosition = this->getPosition();
if ( this->setXPosition( x ) && this->setYPosition( y ) ) return true;
else {
this->setXPosition( previousPosition.x );
this->setYPosition( previousPosition.y );
return false;
}
return true;
}
bool Sprite::setPosition( Point point ) {
return this->setPosition( point.x, point.y );
}
int Sprite::getXPosition() {
uint8 x = sprites[this->id].attr1 & 0x01FF;
// If x-position was a negative number...
if ( (x & 0x0100) != 0 ) return -twosComplement9B(x);
return x;
}
int Sprite::getYPosition() {
uint8 y = sprites[this->id].attr0 & 0x00FF;
// If y-position was a negative number...
if ( (y & 0x0080) != 0 ) return -twosComplement8B(y);
return y;
}
Point Sprite::getPosition() {
Point p {};
p.x = this->getXPosition();
p.y = this->getYPosition();
return p;
}
//----------//------------------------------------------------------------------
//----------// Tile & palette settings.
//----------//------------------------------------------------------------------
bool Sprite::setTile( uint16 tileIndex ) {
uint16 tileIndexCapped = tileIndex & 0x01FF;
if ( tileIndex != tileIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0x01FF;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= tileIndexCapped;
return true;
}
uint16 Sprite::getTile() {
return sprites[this->id].attr2 & 0x01FF;
}
bool Sprite::setPalette( uint8 paletteIndex ) {
uint8 paletteIndexCapped = paletteIndex & 0x000F;
if ( paletteIndex != paletteIndexCapped ) return false;
// We first set tile bits to 1 so we can apply an AND later.
sprites[this->id].attr2 |= 0xF000;
// We apply and AND to set the bits properly.
sprites[this->id].attr2 &= paletteIndexCapped << 12;
return true;
}
uint8 Sprite::getPalette() {
return (sprites[this->id].attr2 & 0xF000) >> 12;
}
//----------//------------------------------------------------------------------
//----------// Rotation & scale settings.
//----------//------------------------------------------------------------------
void Sprite::enableRotationAndScale() {
sprites[this->id].attr0 |= 0x0100;
}
void Sprite::disableRotationAndScale() {
sprites[this->id].attr0 &= 0xFEFF;
}
bool Sprite::rotationAndScaleAreEnabled() {
return (sprites[this->id].attr0 & 0x0100) != 0 ;
}
bool Sprite::rotationAndScaleAreDisabled() {
return !this->rotationAndScaleAreEnabled();
}
void Sprite::enableDoubleSize() {
sprites[this->id].attr0 |= 0x0200;
}
void Sprite::disableDoubleSize() {
sprites[this->id].attr0 &= 0xFDFF;
}
bool Sprite::doubleSizeEnabled() {
return (sprites[this->id].attr0 = 0x0200) != 0;
}
bool Sprite::doubleSizeDisabled() {
return !this->doubleSizeEnabled();
}
//----------//------------------------------------------------------------------
//----------// Object mode settings.
//----------//------------------------------------------------------------------
void Sprite::setObjectMode( SpriteObjectMode newMode ) {
sprites[this->id].attr0 |= 0x0C00;
sprites[this->id].attr0 &= newMode;
}
SpriteObjectMode Sprite::getObjectMode() {
uint16 half_word = sprites[this->id].attr0 | 0xF3FF;
switch (half_word) {
case normal:
return normal;
case alpha_first_target:
return normal;
case add_to_window:
return add_to_window;
case bitmap:
return bitmap;
default:
// This won't ever happen.
return normal;
}
}
//----------//------------------------------------------------------------------
//----------// Mosaic & color settings.
//----------//------------------------------------------------------------------
void Sprite::enableMosaic() {
sprites[this->id].attr0 |= 0x1000;
}
void Sprite::disableMosaic() {
sprites[this->id].attr0 &= 0xEFFF;
}
bool Sprite::mosaicIsEnabled() {
return (sprites[this->id].attr0 & 0x1000) != 0;
}
bool Sprite::mosaicIsDisabled() {
return !this->mosaicIsEnabled();
}
void Sprite::use16BitColors() {
sprites[this->id].attr0 &= 0xDFFF;
}
void Sprite::use256BitColors() {
sprites[this->id].attr0 |= 0x2000;
}
bool Sprite::isUsing16BitColors() {
return (sprites[this->id].attr0 & 0x2000) != 0;
}
bool Sprite::isUsing256BitColors() {
return !this->isUsing16BitColors();
}
//----------//------------------------------------------------------------------
//----------// Shape & size settings.
//----------//------------------------------------------------------------------
bool Sprite::setSizeMode( SpriteSizeMode newMode ) {
uint16 attr0mask;
uint16 attr1mask;
switch ( newMode ) {
case square8x8:
case square16x16:
case square32x32:
case square64x64:
attr0mask = 0x3FFF;
break;
case wide16x8:
case wide32x8:
case wide32x16:
case wide64x32:
attr0mask = 0x7FFF;
break;
case tall8x16:
case tall8x32:
case tall16x32:
case tall32x64:
attr0mask = 0xBFFF;
break;
default:
return false;
}
switch ( newMode ) {
case square8x8:
case wide16x8:
case tall8x16:
attr1mask = 0x3FFF;
break;
case square16x16:
case wide32x8:
case tall8x32:
attr1mask = 0x7FFF;
break;
case square32x32:
case wide32x16:
case tall16x32:
attr1mask = 0xBFFF;
break;
case square64x64:
case wide64x32:
case tall32x64:
attr1mask = 0xFFFF;
break;
default:
return false;
}
// We first set the size bits to 1.
sprites[this->id].attr0 |= 0XC000;
sprites[this->id].attr1 |= 0XC000;
// And then we apply the mask.
sprites[this->id].attr0 &= attr0mask;
sprites[this->id].attr1 &= attr1mask;
return true;
}
SpriteSizeMode Sprite::getSizeMode() {
uint16 shape = sprites[this->id].attr0 & 0xC000;
uint16 size = sprites[this->id].attr1 & 0xC000;
SpriteSizeMode sizeMode;
switch ( shape ) {
// Square.
case 0x0000:
switch (size) {
case 0x0000:
sizeMode = square8x8;
break;
case 0x4000:
sizeMode = square16x16;
break;
case 0x8000:
sizeMode = square32x32;
break;
case 0xC000:
sizeMode = square64x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Wide.
case 0x4000:
switch (size) {
case 0x0000:
sizeMode = wide16x8;
break;
case 0x4000:
sizeMode = wide32x8;
break;
case 0x8000:
sizeMode = wide32x16;
break;
case 0xC000:
sizeMode = wide64x32;
break;
default:
sizeMode = unknown;
break;
}
break;
// Tall.
case 0x8000:
switch (size) {
case 0x0000:
sizeMode = tall8x16;
break;
case 0x4000:
sizeMode = tall8x32;
break;
case 0x8000:
sizeMode = tall16x32;
break;
case 0xC000:
sizeMode = tall32x64;
break;
default:
sizeMode = unknown;
break;
}
break;
// Not used.
case 0xC000:
default:
sizeMode = unknown;
break;
}
return sizeMode;
}
//----------//------------------------------------------------------------------
//----------// Flip settings.
//----------//------------------------------------------------------------------
void Sprite::enableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 |= 0x1000;
}
void Sprite::disableHorizontalFlip() {
this->disableRotationAndScale();
sprites[this->id].attr1 &= 0xEFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::horizontalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !horizontalFlipIsEnabled() !!
bool Sprite::horizontalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x1000) == 0;
}
void Sprite::enableVerticalFlip() {
sprites[this->id].attr1 |= 0x2000;
}
void Sprite::disableVerticalFlip() {
sprites[this->id].attr1 &= 0xDFFF;
}
// If rotation/scaling is disabled it'll return false.
bool Sprite::verticalFlipIsEnabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) != 0;
}
// If rotation/scaling is disabled it'll return false.
// THIS IS NOT EQUIVALENT TO !verticalFlipIsEnabled() !!
bool Sprite::verticalFlipIsDisabled() {
if ( this->rotationAndScaleAreDisabled() )
return false;
return (sprites[this->id].attr1 & 0x2000) == 0;
}
//----------//------------------------------------------------------------------
//----------// Priority settings.
//----------//------------------------------------------------------------------
void Sprite::setPriority( SpritePriority priority ) {
sprites[this->id].attr2 |= 0x0C00;
sprites[this->id].attr2 &= priority;
}
SpritePriority Sprite::getPriority() {
uint16 half_word = sprites[this->id].attr2 | 0xF3FF;
switch (half_word) {
case spHIGHEST:
return spHIGHEST;
case spHIGH:
return spHIGH;
case spLOW:
return spLOW;
case spLOWEST:
return spLOWEST;
default:
// This won't ever happen.
return spHIGHEST;
}
}
//----------//------------------------------------------------------------------
//----------// Other settings.
//----------//------------------------------------------------------------------
void Sprite::clear() {
sprites[this->id].attr0 = ATTR0_DISABLED;
sprites[this->id].attr1 = 0;
sprites[this->id].attr2 = 0;
sprites[this->id].affine_data = 0;
}
void Sprite::disable() {
uint16 disableMask = 0xFEFF;
sprites[this->id].attr0 &= disableMask;
}
void Sprite::enable() {
uint16 enableMask = 0xFCFF;
sprites[this->id].attr0 &= enableMask;
}
void Sprite::print() {
FMAW::printf("%s\r\n Sprite %u:%s\r\n|%s|",
"\r\n|----------------|", this->id, "\r\n|----------------|",
half_word_to_binary(sprites[this->id].attr0).c_str());
FMAW::printf("|%s|\r\n|%s|",
half_word_to_binary(sprites[this->id].attr1).c_str(),
half_word_to_binary(sprites[this->id].attr2).c_str());
FMAW::printf("|%s|\r\n%s",
half_word_to_binary(sprites[this->id].affine_data).c_str(),
"|----------------|");
}
}<|endoftext|>
|
<commit_before>/*
* Copyright 2010-2020 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bx#license-bsd-2-clause
*/
#include "bx_p.h"
#include <bx/thread.h>
#if BX_CONFIG_SUPPORTS_THREADING
#if BX_PLATFORM_WINDOWS && !BX_CRT_NONE
# include <bx/string.h>
#endif
#if BX_CRT_NONE
# include "crt0.h"
#elif BX_PLATFORM_ANDROID \
|| BX_PLATFORM_BSD \
|| BX_PLATFORM_HAIKU \
|| BX_PLATFORM_LINUX \
|| BX_PLATFORM_IOS \
|| BX_PLATFORM_OSX \
|| BX_PLATFORM_PS4 \
|| BX_PLATFORM_RPI
# include <pthread.h>
# if defined(__FreeBSD__)
# include <pthread_np.h>
# endif
# if BX_PLATFORM_LINUX && (BX_CRT_GLIBC < 21200)
# include <sys/prctl.h>
# endif // BX_PLATFORM_
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOXONE
# include <windows.h>
# include <limits.h>
# include <errno.h>
# if BX_PLATFORM_WINRT
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::System::Threading;
# endif // BX_PLATFORM_WINRT
#endif // BX_PLATFORM_
namespace bx
{
static AllocatorI* getAllocator()
{
static DefaultAllocator s_allocator;
return &s_allocator;
}
struct ThreadInternal
{
#if BX_CRT_NONE
static int32_t threadFunc(void* _arg);
int32_t m_handle;
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOXONE
static DWORD WINAPI threadFunc(LPVOID _arg);
HANDLE m_handle;
DWORD m_threadId;
#elif BX_PLATFORM_POSIX
static void* threadFunc(void* _arg);
pthread_t m_handle;
#endif // BX_PLATFORM_
};
#if BX_CRT_NONE
int32_t ThreadInternal::threadFunc(void* _arg)
{
Thread* thread = (Thread*)_arg;
int32_t result = thread->entry();
return result;
}
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_XBOXONE \
|| BX_PLATFORM_WINRT
DWORD WINAPI ThreadInternal::threadFunc(LPVOID _arg)
{
Thread* thread = (Thread*)_arg;
int32_t result = thread->entry();
return result;
}
#else
void* ThreadInternal::threadFunc(void* _arg)
{
Thread* thread = (Thread*)_arg;
union
{
void* ptr;
int32_t i;
} cast;
cast.i = thread->entry();
return cast.ptr;
}
#endif // BX_PLATFORM_
Thread::Thread()
: m_fn(NULL)
, m_userData(NULL)
, m_queue(getAllocator() )
, m_stackSize(0)
, m_exitCode(kExitSuccess)
, m_running(false)
{
BX_STATIC_ASSERT(sizeof(ThreadInternal) <= sizeof(m_internal) );
ThreadInternal* ti = (ThreadInternal*)m_internal;
#if BX_CRT_NONE
ti->m_handle = INT32_MIN;
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOXONE
ti->m_handle = INVALID_HANDLE_VALUE;
ti->m_threadId = UINT32_MAX;
#elif BX_PLATFORM_POSIX
ti->m_handle = 0;
#endif // BX_PLATFORM_
}
Thread::~Thread()
{
if (m_running)
{
shutdown();
}
}
bool Thread::init(ThreadFn _fn, void* _userData, uint32_t _stackSize, const char* _name)
{
BX_ASSERT(!m_running, "Already running!");
m_fn = _fn;
m_userData = _userData;
m_stackSize = _stackSize;
ThreadInternal* ti = (ThreadInternal*)m_internal;
#if BX_CRT_NONE
ti->m_handle = crt0::threadCreate(&ti->threadFunc, _userData, m_stackSize, _name);
if (NULL == ti->m_handle)
{
return false;
}
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_XBOXONE
ti->m_handle = ::CreateThread(NULL
, m_stackSize
, (LPTHREAD_START_ROUTINE)ti->threadFunc
, this
, 0
, NULL
);
if (NULL == ti->m_handle)
{
return false;
}
#elif BX_PLATFORM_WINRT
ti->m_handle = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
if (NULL == ti->m_handle)
{
return false;
}
auto workItemHandler = ref new WorkItemHandler([=](IAsyncAction^)
{
m_exitCode = ti->threadFunc(this);
SetEvent(ti->m_handle);
}
, CallbackContext::Any
);
ThreadPool::RunAsync(workItemHandler, WorkItemPriority::Normal, WorkItemOptions::TimeSliced);
#elif BX_PLATFORM_POSIX
int result;
BX_UNUSED(result);
pthread_attr_t attr;
result = pthread_attr_init(&attr);
BX_WARN(0 == result, "pthread_attr_init failed! %d", result);
if (0 != result)
{
return false;
}
if (0 != m_stackSize)
{
result = pthread_attr_setstacksize(&attr, m_stackSize);
BX_WARN(0 == result, "pthread_attr_setstacksize failed! %d", result);
if (0 != result)
{
return false;
}
}
result = pthread_create(&ti->m_handle, &attr, &ti->threadFunc, this);
BX_WARN(0 == result, "pthread_attr_setschedparam failed! %d", result);
if (0 != result)
{
return false;
}
#else
# error "Not implemented!"
#endif // BX_PLATFORM_
m_running = true;
m_sem.wait();
if (NULL != _name)
{
setThreadName(_name);
}
return true;
}
void Thread::shutdown()
{
BX_ASSERT(m_running, "Not running!");
ThreadInternal* ti = (ThreadInternal*)m_internal;
#if BX_CRT_NONE
crt0::threadJoin(ti->m_handle, NULL);
#elif BX_PLATFORM_WINDOWS
WaitForSingleObject(ti->m_handle, INFINITE);
GetExitCodeThread(ti->m_handle, (DWORD*)&m_exitCode);
CloseHandle(ti->m_handle);
ti->m_handle = INVALID_HANDLE_VALUE;
#elif BX_PLATFORM_WINRT || BX_PLATFORM_XBOXONE
WaitForSingleObjectEx(ti->m_handle, INFINITE, FALSE);
CloseHandle(ti->m_handle);
ti->m_handle = INVALID_HANDLE_VALUE;
#elif BX_PLATFORM_POSIX
union
{
void* ptr;
int32_t i;
} cast;
pthread_join(ti->m_handle, &cast.ptr);
m_exitCode = cast.i;
ti->m_handle = 0;
#endif // BX_PLATFORM_
m_running = false;
}
bool Thread::isRunning() const
{
return m_running;
}
int32_t Thread::getExitCode() const
{
return m_exitCode;
}
void Thread::setThreadName(const char* _name)
{
ThreadInternal* ti = (ThreadInternal*)m_internal;
BX_UNUSED(ti);
#if BX_CRT_NONE
BX_UNUSED(_name);
#elif BX_PLATFORM_OSX \
|| BX_PLATFORM_IOS
pthread_setname_np(_name);
#elif (BX_CRT_GLIBC >= 21200) && ! BX_PLATFORM_HURD
pthread_setname_np(ti->m_handle, _name);
#elif BX_PLATFORM_LINUX
prctl(PR_SET_NAME,_name, 0, 0, 0);
#elif BX_PLATFORM_BSD
# if defined(__NetBSD__)
pthread_setname_np(ti->m_handle, "%s", (void*)_name);
# else
pthread_set_name_np(ti->m_handle, _name);
# endif // defined(__NetBSD__)
#elif BX_PLATFORM_WINDOWS
// Try to use the new thread naming API from Win10 Creators update onwards if we have it
typedef HRESULT (WINAPI *SetThreadDescriptionProc)(HANDLE, PCWSTR);
SetThreadDescriptionProc SetThreadDescription = bx::functionCast<SetThreadDescriptionProc>(
GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetThreadDescription")
);
if (SetThreadDescription)
{
uint32_t length = (uint32_t)bx::strLen(_name)+1;
uint32_t size = length*sizeof(wchar_t);
wchar_t* name = (wchar_t*)alloca(size);
mbstowcs(name, _name, size-2);
SetThreadDescription(ti->m_handle, name);
}
# if BX_COMPILER_MSVC
# pragma pack(push, 8)
struct ThreadName
{
DWORD type;
LPCSTR name;
DWORD id;
DWORD flags;
};
# pragma pack(pop)
ThreadName tn;
tn.type = 0x1000;
tn.name = _name;
tn.id = ti->m_threadId;
tn.flags = 0;
__try
{
RaiseException(0x406d1388
, 0
, sizeof(tn)/4
, reinterpret_cast<ULONG_PTR*>(&tn)
);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
# endif // BX_COMPILER_MSVC
#else
BX_UNUSED(_name);
#endif // BX_PLATFORM_
}
void Thread::push(void* _ptr)
{
m_queue.push(_ptr);
}
void* Thread::pop()
{
void* ptr = m_queue.pop();
return ptr;
}
int32_t Thread::entry()
{
#if BX_PLATFORM_WINDOWS
ThreadInternal* ti = (ThreadInternal*)m_internal;
ti->m_threadId = ::GetCurrentThreadId();
#endif // BX_PLATFORM_WINDOWS
m_sem.post();
int32_t result = m_fn(this, m_userData);
return result;
}
struct TlsDataInternal
{
#if BX_CRT_NONE
#elif BX_PLATFORM_WINDOWS
uint32_t m_id;
#elif !(BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT)
pthread_key_t m_id;
#endif // BX_PLATFORM_*
};
#if BX_CRT_NONE
TlsData::TlsData()
{
BX_STATIC_ASSERT(sizeof(TlsDataInternal) <= sizeof(m_internal) );
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BX_UNUSED(ti);
}
TlsData::~TlsData()
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BX_UNUSED(ti);
}
void* TlsData::get() const
{
return NULL;
}
void TlsData::set(void* _ptr)
{
BX_UNUSED(_ptr);
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BX_UNUSED(ti);
}
#elif BX_PLATFORM_WINDOWS
TlsData::TlsData()
{
BX_STATIC_ASSERT(sizeof(TlsDataInternal) <= sizeof(m_internal) );
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
ti->m_id = TlsAlloc();
BX_ASSERT(TLS_OUT_OF_INDEXES != ti->m_id, "Failed to allocated TLS index (err: 0x%08x).", GetLastError() );
}
TlsData::~TlsData()
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BOOL result = TlsFree(ti->m_id);
BX_ASSERT(0 != result, "Failed to free TLS index (err: 0x%08x).", GetLastError() ); BX_UNUSED(result);
}
void* TlsData::get() const
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
return TlsGetValue(ti->m_id);
}
void TlsData::set(void* _ptr)
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
TlsSetValue(ti->m_id, _ptr);
}
#elif !(BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT)
TlsData::TlsData()
{
BX_STATIC_ASSERT(sizeof(TlsDataInternal) <= sizeof(m_internal) );
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
int result = pthread_key_create(&ti->m_id, NULL);
BX_ASSERT(0 == result, "pthread_key_create failed %d.", result); BX_UNUSED(result);
}
TlsData::~TlsData()
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
int result = pthread_key_delete(ti->m_id);
BX_ASSERT(0 == result, "pthread_key_delete failed %d.", result); BX_UNUSED(result);
}
void* TlsData::get() const
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
return pthread_getspecific(ti->m_id);
}
void TlsData::set(void* _ptr)
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
int result = pthread_setspecific(ti->m_id, _ptr);
BX_ASSERT(0 == result, "pthread_setspecific failed %d.", result); BX_UNUSED(result);
}
#endif // BX_PLATFORM_*
} // namespace bx
#endif // BX_CONFIG_SUPPORTS_THREADING
<commit_msg>Fixed build.<commit_after>/*
* Copyright 2010-2020 Branimir Karadzic. All rights reserved.
* License: https://github.com/bkaradzic/bx#license-bsd-2-clause
*/
#include "bx_p.h"
#include <bx/thread.h>
#if BX_CONFIG_SUPPORTS_THREADING
#if BX_PLATFORM_WINDOWS && !BX_CRT_NONE
# include <bx/string.h>
#endif
#if BX_CRT_NONE
# include "crt0.h"
#elif BX_PLATFORM_ANDROID \
|| BX_PLATFORM_BSD \
|| BX_PLATFORM_HAIKU \
|| BX_PLATFORM_LINUX \
|| BX_PLATFORM_IOS \
|| BX_PLATFORM_OSX \
|| BX_PLATFORM_PS4 \
|| BX_PLATFORM_RPI
# include <pthread.h>
# if defined(__FreeBSD__)
# include <pthread_np.h>
# endif
# if BX_PLATFORM_LINUX && (BX_CRT_GLIBC < 21200)
# include <sys/prctl.h>
# endif // BX_PLATFORM_
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOXONE
# include <windows.h>
# include <limits.h>
# include <errno.h>
# if BX_PLATFORM_WINRT
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::System::Threading;
# endif // BX_PLATFORM_WINRT
#endif // BX_PLATFORM_
namespace bx
{
static AllocatorI* getAllocator()
{
static DefaultAllocator s_allocator;
return &s_allocator;
}
struct ThreadInternal
{
#if BX_CRT_NONE
static int32_t threadFunc(void* _arg);
int32_t m_handle;
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOXONE
static DWORD WINAPI threadFunc(LPVOID _arg);
HANDLE m_handle;
DWORD m_threadId;
#elif BX_PLATFORM_POSIX
static void* threadFunc(void* _arg);
pthread_t m_handle;
#endif // BX_PLATFORM_
};
#if BX_CRT_NONE
int32_t ThreadInternal::threadFunc(void* _arg)
{
Thread* thread = (Thread*)_arg;
int32_t result = thread->entry();
return result;
}
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_XBOXONE \
|| BX_PLATFORM_WINRT
DWORD WINAPI ThreadInternal::threadFunc(LPVOID _arg)
{
Thread* thread = (Thread*)_arg;
int32_t result = thread->entry();
return result;
}
#else
void* ThreadInternal::threadFunc(void* _arg)
{
Thread* thread = (Thread*)_arg;
union
{
void* ptr;
int32_t i;
} cast;
cast.i = thread->entry();
return cast.ptr;
}
#endif // BX_PLATFORM_
Thread::Thread()
: m_fn(NULL)
, m_userData(NULL)
, m_queue(getAllocator() )
, m_stackSize(0)
, m_exitCode(kExitSuccess)
, m_running(false)
{
BX_STATIC_ASSERT(sizeof(ThreadInternal) <= sizeof(m_internal) );
ThreadInternal* ti = (ThreadInternal*)m_internal;
#if BX_CRT_NONE
ti->m_handle = INT32_MIN;
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_WINRT \
|| BX_PLATFORM_XBOXONE
ti->m_handle = INVALID_HANDLE_VALUE;
ti->m_threadId = UINT32_MAX;
#elif BX_PLATFORM_POSIX
ti->m_handle = 0;
#endif // BX_PLATFORM_
}
Thread::~Thread()
{
if (m_running)
{
shutdown();
}
}
bool Thread::init(ThreadFn _fn, void* _userData, uint32_t _stackSize, const char* _name)
{
BX_ASSERT(!m_running, "Already running!");
m_fn = _fn;
m_userData = _userData;
m_stackSize = _stackSize;
ThreadInternal* ti = (ThreadInternal*)m_internal;
#if BX_CRT_NONE
ti->m_handle = crt0::threadCreate(&ti->threadFunc, _userData, m_stackSize, _name);
if (NULL == ti->m_handle)
{
return false;
}
#elif BX_PLATFORM_WINDOWS \
|| BX_PLATFORM_XBOXONE
ti->m_handle = ::CreateThread(NULL
, m_stackSize
, (LPTHREAD_START_ROUTINE)ti->threadFunc
, this
, 0
, NULL
);
if (NULL == ti->m_handle)
{
return false;
}
#elif BX_PLATFORM_WINRT
ti->m_handle = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);
if (NULL == ti->m_handle)
{
return false;
}
auto workItemHandler = ref new WorkItemHandler([=](IAsyncAction^)
{
m_exitCode = ti->threadFunc(this);
SetEvent(ti->m_handle);
}
, CallbackContext::Any
);
ThreadPool::RunAsync(workItemHandler, WorkItemPriority::Normal, WorkItemOptions::TimeSliced);
#elif BX_PLATFORM_POSIX
int result;
BX_UNUSED(result);
pthread_attr_t attr;
result = pthread_attr_init(&attr);
BX_WARN(0 == result, "pthread_attr_init failed! %d", result);
if (0 != result)
{
return false;
}
if (0 != m_stackSize)
{
result = pthread_attr_setstacksize(&attr, m_stackSize);
BX_WARN(0 == result, "pthread_attr_setstacksize failed! %d", result);
if (0 != result)
{
return false;
}
}
result = pthread_create(&ti->m_handle, &attr, &ti->threadFunc, this);
BX_WARN(0 == result, "pthread_attr_setschedparam failed! %d", result);
if (0 != result)
{
return false;
}
#else
# error "Not implemented!"
#endif // BX_PLATFORM_
m_running = true;
m_sem.wait();
if (NULL != _name)
{
setThreadName(_name);
}
return true;
}
void Thread::shutdown()
{
BX_ASSERT(m_running, "Not running!");
ThreadInternal* ti = (ThreadInternal*)m_internal;
#if BX_CRT_NONE
crt0::threadJoin(ti->m_handle, NULL);
#elif BX_PLATFORM_WINDOWS
WaitForSingleObject(ti->m_handle, INFINITE);
GetExitCodeThread(ti->m_handle, (DWORD*)&m_exitCode);
CloseHandle(ti->m_handle);
ti->m_handle = INVALID_HANDLE_VALUE;
#elif BX_PLATFORM_WINRT || BX_PLATFORM_XBOXONE
WaitForSingleObjectEx(ti->m_handle, INFINITE, FALSE);
CloseHandle(ti->m_handle);
ti->m_handle = INVALID_HANDLE_VALUE;
#elif BX_PLATFORM_POSIX
union
{
void* ptr;
int32_t i;
} cast;
pthread_join(ti->m_handle, &cast.ptr);
m_exitCode = cast.i;
ti->m_handle = 0;
#endif // BX_PLATFORM_
m_running = false;
}
bool Thread::isRunning() const
{
return m_running;
}
int32_t Thread::getExitCode() const
{
return m_exitCode;
}
void Thread::setThreadName(const char* _name)
{
ThreadInternal* ti = (ThreadInternal*)m_internal;
BX_UNUSED(ti);
#if BX_CRT_NONE
BX_UNUSED(_name);
#elif BX_PLATFORM_OSX \
|| BX_PLATFORM_IOS
pthread_setname_np(_name);
#elif (BX_CRT_GLIBC >= 21200) && ! BX_PLATFORM_HURD
pthread_setname_np(ti->m_handle, _name);
#elif BX_PLATFORM_LINUX
prctl(PR_SET_NAME,_name, 0, 0, 0);
#elif BX_PLATFORM_BSD
# if defined(__NetBSD__)
pthread_setname_np(ti->m_handle, "%s", (void*)_name);
# else
pthread_set_name_np(ti->m_handle, _name);
# endif // defined(__NetBSD__)
#elif BX_PLATFORM_WINDOWS
// Try to use the new thread naming API from Win10 Creators update onwards if we have it
typedef HRESULT (WINAPI *SetThreadDescriptionProc)(HANDLE, PCWSTR);
SetThreadDescriptionProc SetThreadDescription = bx::functionCast<SetThreadDescriptionProc>(
bx::dlsym(GetModuleHandleA("Kernel32.dll"), "SetThreadDescription")
);
if (SetThreadDescription)
{
uint32_t length = (uint32_t)bx::strLen(_name)+1;
uint32_t size = length*sizeof(wchar_t);
wchar_t* name = (wchar_t*)alloca(size);
mbstowcs(name, _name, size-2);
SetThreadDescription(ti->m_handle, name);
}
# if BX_COMPILER_MSVC
# pragma pack(push, 8)
struct ThreadName
{
DWORD type;
LPCSTR name;
DWORD id;
DWORD flags;
};
# pragma pack(pop)
ThreadName tn;
tn.type = 0x1000;
tn.name = _name;
tn.id = ti->m_threadId;
tn.flags = 0;
__try
{
RaiseException(0x406d1388
, 0
, sizeof(tn)/4
, reinterpret_cast<ULONG_PTR*>(&tn)
);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
}
# endif // BX_COMPILER_MSVC
#else
BX_UNUSED(_name);
#endif // BX_PLATFORM_
}
void Thread::push(void* _ptr)
{
m_queue.push(_ptr);
}
void* Thread::pop()
{
void* ptr = m_queue.pop();
return ptr;
}
int32_t Thread::entry()
{
#if BX_PLATFORM_WINDOWS
ThreadInternal* ti = (ThreadInternal*)m_internal;
ti->m_threadId = ::GetCurrentThreadId();
#endif // BX_PLATFORM_WINDOWS
m_sem.post();
int32_t result = m_fn(this, m_userData);
return result;
}
struct TlsDataInternal
{
#if BX_CRT_NONE
#elif BX_PLATFORM_WINDOWS
uint32_t m_id;
#elif !(BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT)
pthread_key_t m_id;
#endif // BX_PLATFORM_*
};
#if BX_CRT_NONE
TlsData::TlsData()
{
BX_STATIC_ASSERT(sizeof(TlsDataInternal) <= sizeof(m_internal) );
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BX_UNUSED(ti);
}
TlsData::~TlsData()
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BX_UNUSED(ti);
}
void* TlsData::get() const
{
return NULL;
}
void TlsData::set(void* _ptr)
{
BX_UNUSED(_ptr);
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BX_UNUSED(ti);
}
#elif BX_PLATFORM_WINDOWS
TlsData::TlsData()
{
BX_STATIC_ASSERT(sizeof(TlsDataInternal) <= sizeof(m_internal) );
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
ti->m_id = TlsAlloc();
BX_ASSERT(TLS_OUT_OF_INDEXES != ti->m_id, "Failed to allocated TLS index (err: 0x%08x).", GetLastError() );
}
TlsData::~TlsData()
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
BOOL result = TlsFree(ti->m_id);
BX_ASSERT(0 != result, "Failed to free TLS index (err: 0x%08x).", GetLastError() ); BX_UNUSED(result);
}
void* TlsData::get() const
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
return TlsGetValue(ti->m_id);
}
void TlsData::set(void* _ptr)
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
TlsSetValue(ti->m_id, _ptr);
}
#elif !(BX_PLATFORM_XBOXONE || BX_PLATFORM_WINRT)
TlsData::TlsData()
{
BX_STATIC_ASSERT(sizeof(TlsDataInternal) <= sizeof(m_internal) );
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
int result = pthread_key_create(&ti->m_id, NULL);
BX_ASSERT(0 == result, "pthread_key_create failed %d.", result); BX_UNUSED(result);
}
TlsData::~TlsData()
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
int result = pthread_key_delete(ti->m_id);
BX_ASSERT(0 == result, "pthread_key_delete failed %d.", result); BX_UNUSED(result);
}
void* TlsData::get() const
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
return pthread_getspecific(ti->m_id);
}
void TlsData::set(void* _ptr)
{
TlsDataInternal* ti = (TlsDataInternal*)m_internal;
int result = pthread_setspecific(ti->m_id, _ptr);
BX_ASSERT(0 == result, "pthread_setspecific failed %d.", result); BX_UNUSED(result);
}
#endif // BX_PLATFORM_*
} // namespace bx
#endif // BX_CONFIG_SUPPORTS_THREADING
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.