text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "AgnosticApp.h"
#include "Renderer\D3D\RendererD3D.h"
#include "Renderer\GL\RendererGL.h"
using namespace DirectX;
AgnosticApp::AgnosticApp()
{
}
void AgnosticApp::Initialize(float windowWidth, float windowHeight)
{
// Set up the projection matrices for the scene
float fovAngleY = 70.0f * XM_PI / 180.0f;
m_projectionMatrix = glm::perspectiveFov(fovAngleY, windowWidth, windowHeight, 0.01f, 100.0f);
UINT seed = 4741;
// One renderer can be shared across all cubes. This uses a D3D11 backend to render the cubes
mRenderer = new RendererGL();
// Get the list of moves required to solve the cube
CubeSolver* solver = new CubeSolver();
CubeCommandList* commandList = NULL;
solver->GetCube()->Randomize(seed);
solver->Solve();
solver->GetCubeCommandList(&commandList);
// Cut things like repetition out of the solution
commandList->Optimize();
// Configure the CubePlayer
CubePlayerDesc cubePlayerDesc;
cubePlayerDesc.unfoldCubeAtStart = true;
// Initialize the CubePlayer, which will play back the moves to solve the cube
mCubePlayer = new CubePlayer(&cubePlayerDesc);
mCubePlayer->GetCube()->Randomize(seed);
mCubePlayer->UseCommandList(commandList);
}
bool tripledSpeed = false;
void AgnosticApp::Update(float timeTotal, float timeDelta)
{
(void) timeDelta; // Unused parameter.
if (timeTotal <= 7.2f)
{
mCubePlayer->Play();
}
else if(timeTotal <= 10.2f)
{
mCubePlayer->Pause();
}
else
{
if (!tripledSpeed)
{
// Triple speed
mCubePlayer->UpdateSolvingSpeed(mCubePlayer->GetDesc().speeds.solvingSpeed / 3);
tripledSpeed = true;
}
mCubePlayer->Play();
}
mCubePlayer->Update(timeTotal, timeDelta);
glm::vec3 eye = glm::vec3(7.7f, -7.7f, -7.5f);
glm::vec3 at = glm::vec3(0.0f, -0.1f, 0.0f);
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
m_viewMatrix = glm::lookAt(eye, at, up) * glm::rotate(glm::mat4(), timeTotal / 2.0f, glm::vec3(0, 1, 0));
}
void AgnosticApp::Render()
{
mRenderer->Clear();
mRenderer->DrawCube(mCubePlayer->GetCube(), &m_viewMatrix, &m_projectionMatrix);
// glm::vec3 eye = glm::vec3(7.7f, -7.7f, -7.5f);
// glm::vec3 at = glm::vec3(0.0f, -0.1f, 0.0f);
// glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
// m_viewMatrix = glm::lookAt(eye, at, up) * glm::rotate(glm::mat4(), 0 / 2.0f, glm::vec3(0, 1, 0));
// m_viewMatrix *= glm::translate(glm::mat4(), glm::vec3(-5, 0, -5));
//// XMStoreFloat4x4(&m_viewMatrix, XMMatrixMultiply(XMLoadFloat4x4(&m_viewMatrix), XMMatrixTranslation(10, 0, 0)));
// mRenderer->DrawCube(mCubePlayer->GetCube(), &m_viewMatrix, &m_projectionMatrix);
}
// This method is called in the event handler for the SizeChanged event.
void AgnosticApp::UpdateForWindowSizeChange()
{
mRenderer->UpdateForWindowSizeChange();
}
void AgnosticApp::Present()
{
mRenderer->Swap();
}<commit_msg>Switch to D3D renderer<commit_after>#include "AgnosticApp.h"
#include "Renderer\D3D\RendererD3D.h"
#include "Renderer\GL\RendererGL.h"
using namespace DirectX;
AgnosticApp::AgnosticApp()
{
}
void AgnosticApp::Initialize(float windowWidth, float windowHeight)
{
// Set up the projection matrices for the scene
float fovAngleY = 70.0f * XM_PI / 180.0f;
m_projectionMatrix = glm::perspectiveFov(fovAngleY, windowWidth, windowHeight, 0.01f, 100.0f);
UINT seed = 4741;
// One renderer can be shared across all cubes. This uses a D3D11 backend to render the cubes
mRenderer = new RendererD3D();
// Get the list of moves required to solve the cube
CubeSolver* solver = new CubeSolver();
CubeCommandList* commandList = NULL;
solver->GetCube()->Randomize(seed);
solver->Solve();
solver->GetCubeCommandList(&commandList);
// Cut things like repetition out of the solution
commandList->Optimize();
// Configure the CubePlayer
CubePlayerDesc cubePlayerDesc;
cubePlayerDesc.unfoldCubeAtStart = true;
// Initialize the CubePlayer, which will play back the moves to solve the cube
mCubePlayer = new CubePlayer(&cubePlayerDesc);
mCubePlayer->GetCube()->Randomize(seed);
mCubePlayer->UseCommandList(commandList);
}
bool tripledSpeed = false;
void AgnosticApp::Update(float timeTotal, float timeDelta)
{
(void) timeDelta; // Unused parameter.
if (timeTotal <= 7.2f)
{
mCubePlayer->Play();
}
else if(timeTotal <= 10.2f)
{
mCubePlayer->Pause();
}
else
{
if (!tripledSpeed)
{
// Triple speed
mCubePlayer->UpdateSolvingSpeed(mCubePlayer->GetDesc().speeds.solvingSpeed / 3);
tripledSpeed = true;
}
mCubePlayer->Play();
}
mCubePlayer->Update(timeTotal, timeDelta);
glm::vec3 eye = glm::vec3(7.7f, -7.7f, -7.5f);
glm::vec3 at = glm::vec3(0.0f, -0.1f, 0.0f);
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
m_viewMatrix = glm::lookAt(eye, at, up) * glm::rotate(glm::mat4(), timeTotal / 2.0f, glm::vec3(0, 1, 0));
}
void AgnosticApp::Render()
{
mRenderer->Clear();
mRenderer->DrawCube(mCubePlayer->GetCube(), &m_viewMatrix, &m_projectionMatrix);
// glm::vec3 eye = glm::vec3(7.7f, -7.7f, -7.5f);
// glm::vec3 at = glm::vec3(0.0f, -0.1f, 0.0f);
// glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
// m_viewMatrix = glm::lookAt(eye, at, up) * glm::rotate(glm::mat4(), 0 / 2.0f, glm::vec3(0, 1, 0));
// m_viewMatrix *= glm::translate(glm::mat4(), glm::vec3(-5, 0, -5));
//// XMStoreFloat4x4(&m_viewMatrix, XMMatrixMultiply(XMLoadFloat4x4(&m_viewMatrix), XMMatrixTranslation(10, 0, 0)));
// mRenderer->DrawCube(mCubePlayer->GetCube(), &m_viewMatrix, &m_projectionMatrix);
}
// This method is called in the event handler for the SizeChanged event.
void AgnosticApp::UpdateForWindowSizeChange()
{
mRenderer->UpdateForWindowSizeChange();
}
void AgnosticApp::Present()
{
mRenderer->Swap();
}<|endoftext|>
|
<commit_before>
/*
* AudioStream.cpp
* sfeMovie project
*
* Copyright (C) 2010-2014 Lucas Soltic
* lucas.soltic@orange.fr
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/samplefmt.h>
#include <libavutil/opt.h>
#include <libavutil/channel_layout.h>
#include <libswresample/swresample.h>
}
#include <cstring>
#include <iostream>
#include "AudioStream.hpp"
#include "Log.hpp"
#include <sfeMovie/Movie.hpp>
namespace sfe
{
AudioStream::AudioStream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource,
std::shared_ptr<Timer> timer) :
Stream(formatCtx, stream, dataSource, timer),
// Public properties
m_sampleRate(0),
// Private data
m_samplesBuffer(nullptr),
m_audioFrame(nullptr),
// Resampling
m_swrCtx(nullptr),
m_dstNbSamples(0),
m_maxDstNbSamples(0),
m_dstNbChannels(0),
m_dstLinesize(0),
m_dstData(nullptr)
{
m_audioFrame = av_frame_alloc();
CHECK(m_audioFrame, "AudioStream::AudioStream() - out of memory");
// Get some audio informations
m_sampleRate = m_stream->codec->sample_rate;
// Alloc a two seconds buffer
m_samplesBuffer = (sf::Int16*)av_malloc(sizeof(sf::Int16) * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate * 2);
CHECK(m_samplesBuffer, "AudioStream::AudioStream() - out of memory");
// Initialize the sf::SoundStream
// Whatever the channel count is, it'll we resampled to stereo
sf::SoundStream::initialize(av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), m_sampleRate);
// Initialize resampler to be able to give signed 16 bits samples to SFML
initResampler();
}
/** Default destructor
*/
AudioStream::~AudioStream()
{
if (m_audioFrame)
{
av_frame_free(&m_audioFrame);
}
if (m_samplesBuffer)
{
av_free(m_samplesBuffer);
}
if (m_dstData)
{
av_freep(&m_dstData[0]);
}
av_freep(&m_dstData);
swr_free(&m_swrCtx);
}
void AudioStream::flushBuffers()
{
// To be removed once issue with sf::SoundStream::getStatus() is fixed:
// http://en.sfml-dev.org/forums/index.php?topic=17095.msg122898#msg122898
// This should never happen as this stream has already been notified to pause and
// sf::SoundStream::pause() has been called
while (sf::SoundStream::getStatus() == sf::SoundStream::Playing)
sf::sleep(sf::microseconds(1));
sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();
CHECK (sfStatus != sf::SoundStream::Playing, "Trying to flush while audio is playing, this will introduce an audio glitch!");
// Flush audio driver/OpenAL/SFML buffer
if (sfStatus != sf::SoundStream::Stopped)
sf::SoundStream::stop();
Stream::flushBuffers();
}
MediaType AudioStream::getStreamKind() const
{
return Audio;
}
void AudioStream::update()
{
sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();
switch (sfStatus)
{
case sf::SoundStream::Playing:
setStatus(sfe::Playing);
break;
case sf::SoundStream::Paused:
setStatus(sfe::Paused);
break;
case sf::SoundStream::Stopped:
setStatus(sfe::Stopped);
break;
default:
break;
}
}
bool AudioStream::onGetData(sf::SoundStream::Chunk& data)
{
AVPacket* packet = nullptr;
data.samples = m_samplesBuffer;
while (data.sampleCount < av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate &&
(nullptr != (packet = popEncodedData())))
{
bool needsMoreDecoding = false;
bool gotFrame = false;
do
{
needsMoreDecoding = decodePacket(packet, m_audioFrame, gotFrame);
if (gotFrame)
{
uint8_t* samples = nullptr;
int nbSamples = 0;
int samplesLength = 0;
resampleFrame(m_audioFrame, samples, nbSamples, samplesLength);
CHECK(samples, "AudioStream::onGetData() - resampleFrame() error");
CHECK(nbSamples > 0, "AudioStream::onGetData() - resampleFrame() error");
CHECK(nbSamples == samplesLength / 2, "AudioStream::onGetData() resampleFrame() inconsistency");
CHECK(data.sampleCount + nbSamples < m_sampleRate * 2 * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), "AudioStream::onGetData() - Going to overflow!!");
std::memcpy((void *)(data.samples + data.sampleCount),
samples, samplesLength);
data.sampleCount += nbSamples;
}
} while (needsMoreDecoding);
av_free_packet(packet);
av_free(packet);
}
if (!packet)
{
sfeLogDebug("No more audio packets, do not go further");
}
return (packet != nullptr);
}
void AudioStream::onSeek(sf::Time timeOffset)
{
// CHECK(0, "AudioStream::onSeek() - not implemented");
}
bool AudioStream::decodePacket(AVPacket* packet, AVFrame* outputFrame, bool& gotFrame)
{
bool needsMoreDecoding = false;
int igotFrame = 0;
int decodedLength = avcodec_decode_audio4(m_stream->codec, outputFrame, &igotFrame, packet);
gotFrame = (igotFrame != 0);
CHECK(decodedLength >= 0, "AudioStream::decodePacket() - error: decodedLength=" + s(decodedLength));
if (decodedLength < packet->size)
{
needsMoreDecoding = true;
packet->data += decodedLength;
packet->size -= decodedLength;
}
return needsMoreDecoding;
}
void AudioStream::initResampler()
{
CHECK0(m_swrCtx, "AudioStream::initResampler() - resampler already initialized");
int err = 0;
/* create resampler context */
m_swrCtx = swr_alloc();
CHECK(m_swrCtx, "AudioStream::initResampler() - out of memory");
// Some media files don't define the channel layout, in this case take a default one
// according to the channels' count
if (m_stream->codec->channel_layout == 0)
{
m_stream->codec->channel_layout = av_get_default_channel_layout(m_stream->codec->channels);
}
/* set options */
av_opt_set_int (m_swrCtx, "in_channel_layout", m_stream->codec->channel_layout, 0);
av_opt_set_int (m_swrCtx, "in_sample_rate", m_stream->codec->sample_rate, 0);
av_opt_set_sample_fmt (m_swrCtx, "in_sample_fmt", m_stream->codec->sample_fmt, 0);
av_opt_set_int (m_swrCtx, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
av_opt_set_int (m_swrCtx, "out_sample_rate", m_stream->codec->sample_rate, 0);
av_opt_set_sample_fmt (m_swrCtx, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
/* initialize the resampling context */
err = swr_init(m_swrCtx);
CHECK(err >= 0, "AudioStream::initResampler() - resampling context initialization error");
/* compute the number of converted samples: buffering is avoided
* ensuring that the output buffer will contain at least all the
* converted input samples */
m_maxDstNbSamples = m_dstNbSamples = 1024;
/* Create the resampling output buffer */
m_dstNbChannels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO);
err = av_samples_alloc_array_and_samples(&m_dstData, &m_dstLinesize, m_dstNbChannels,
m_dstNbSamples, AV_SAMPLE_FMT_S16, 0);
CHECK(err >= 0, "AudioStream::initResampler() - av_samples_alloc_array_and_samples error");
}
void AudioStream::resampleFrame(const AVFrame* frame, uint8_t*& outSamples, int& outNbSamples, int& outSamplesLength)
{
CHECK(m_swrCtx, "AudioStream::resampleFrame() - resampler is not initialized, call AudioStream::initResamplerFirst() !");
CHECK(frame, "AudioStream::resampleFrame() - invalid argument");
int src_rate, dst_rate, err, dst_bufsize;
src_rate = dst_rate = frame->sample_rate;
/* compute destination number of samples */
m_dstNbSamples = av_rescale_rnd(swr_get_delay(m_swrCtx, src_rate) +
frame->nb_samples, dst_rate, src_rate, AV_ROUND_UP);
if (m_dstNbSamples > m_maxDstNbSamples)
{
av_free(m_dstData[0]);
err = av_samples_alloc(m_dstData, &m_dstLinesize, m_dstNbChannels,
m_dstNbSamples, AV_SAMPLE_FMT_S16, 1);
CHECK(err >= 0, "AudioStream::resampleFrame() - out of memory");
m_maxDstNbSamples = m_dstNbSamples;
}
/* convert to destination format */
err = swr_convert(m_swrCtx, m_dstData, m_dstNbSamples, (const uint8_t **)frame->extended_data, frame->nb_samples);
CHECK(err >= 0, "AudioStream::resampleFrame() - swr_convert() error");
dst_bufsize = av_samples_get_buffer_size(&m_dstLinesize, m_dstNbChannels,
err, AV_SAMPLE_FMT_S16, 1);
CHECK(dst_bufsize >= 0, "AudioStream::resampleFrame() - av_samples_get_buffer_size() error");
outNbSamples = dst_bufsize / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
outSamplesLength = dst_bufsize;
outSamples = m_dstData[0];
}
void AudioStream::willPlay(const Timer &timer)
{
Stream::willPlay(timer);
if (Stream::getStatus() == sfe::Stopped)
{
sf::Time initialTime = sf::SoundStream::getPlayingOffset();
sf::Clock timeout;
sf::SoundStream::play();
// Some audio drivers take time before the sound is actually played
// To avoid desynchronization with the timer, we don't return
// until the audio stream is actually started
while (sf::SoundStream::getPlayingOffset() == initialTime && timeout.getElapsedTime() < sf::seconds(5))
sf::sleep(sf::microseconds(10));
CHECK(sf::SoundStream::getPlayingOffset() != initialTime, "is your audio device broken? Audio did not start within 5 seconds");
}
else
{
sf::SoundStream::play();
sf::Clock timeout;
while (sf::SoundStream::getStatus() != sf::SoundStream::Playing && timeout.getElapsedTime() < sf::seconds(5))
sf::sleep(sf::microseconds(10));
CHECK(timeout.getElapsedTime() < sf::seconds(5), "Audio did not start within 5 seconds");
}
}
void AudioStream::didPlay(const Timer& timer, sfe::Status previousStatus)
{
CHECK(SoundStream::getStatus() == SoundStream::Playing, "AudioStream::didPlay() - willPlay() not executed!");
Stream::didPlay(timer, previousStatus);
}
void AudioStream::didPause(const Timer& timer, sfe::Status previousStatus)
{
sf::SoundStream::pause();
Stream::didPause(timer, previousStatus);
}
void AudioStream::didStop(const Timer& timer, sfe::Status previousStatus)
{
sf::SoundStream::stop();
Stream::didStop(timer, previousStatus);
}
}
<commit_msg>#6 Wait sound stream status to update: fixes sanity check failure<commit_after>
/*
* AudioStream.cpp
* sfeMovie project
*
* Copyright (C) 2010-2014 Lucas Soltic
* lucas.soltic@orange.fr
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
extern "C"
{
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/samplefmt.h>
#include <libavutil/opt.h>
#include <libavutil/channel_layout.h>
#include <libswresample/swresample.h>
}
#include <cstring>
#include <iostream>
#include "AudioStream.hpp"
#include "Log.hpp"
#include <sfeMovie/Movie.hpp>
namespace sfe
{
namespace
{
void waitForStatusUpdate(const sf::SoundStream& stream, sf::SoundStream::Status expectedStatus)
{
// Wait for status to update
sf::Clock timeout;
while (stream.getStatus() != expectedStatus && timeout.getElapsedTime() < sf::seconds(5))
sf::sleep(sf::microseconds(10));
CHECK(timeout.getElapsedTime() < sf::seconds(5), "Audio did not reach state " + s(expectedStatus) + " within 5 seconds");
}
}
AudioStream::AudioStream(AVFormatContext*& formatCtx, AVStream*& stream, DataSource& dataSource,
std::shared_ptr<Timer> timer) :
Stream(formatCtx, stream, dataSource, timer),
// Public properties
m_sampleRate(0),
// Private data
m_samplesBuffer(nullptr),
m_audioFrame(nullptr),
// Resampling
m_swrCtx(nullptr),
m_dstNbSamples(0),
m_maxDstNbSamples(0),
m_dstNbChannels(0),
m_dstLinesize(0),
m_dstData(nullptr)
{
m_audioFrame = av_frame_alloc();
CHECK(m_audioFrame, "AudioStream::AudioStream() - out of memory");
// Get some audio informations
m_sampleRate = m_stream->codec->sample_rate;
// Alloc a two seconds buffer
m_samplesBuffer = (sf::Int16*)av_malloc(sizeof(sf::Int16) * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate * 2);
CHECK(m_samplesBuffer, "AudioStream::AudioStream() - out of memory");
// Initialize the sf::SoundStream
// Whatever the channel count is, it'll we resampled to stereo
sf::SoundStream::initialize(av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), m_sampleRate);
// Initialize resampler to be able to give signed 16 bits samples to SFML
initResampler();
}
/** Default destructor
*/
AudioStream::~AudioStream()
{
if (m_audioFrame)
{
av_frame_free(&m_audioFrame);
}
if (m_samplesBuffer)
{
av_free(m_samplesBuffer);
}
if (m_dstData)
{
av_freep(&m_dstData[0]);
}
av_freep(&m_dstData);
swr_free(&m_swrCtx);
}
void AudioStream::flushBuffers()
{
sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();
CHECK (sfStatus != sf::SoundStream::Playing, "Trying to flush while audio is playing, this will introduce an audio glitch!");
// Flush audio driver/OpenAL/SFML buffer
if (sfStatus != sf::SoundStream::Stopped)
sf::SoundStream::stop();
Stream::flushBuffers();
}
MediaType AudioStream::getStreamKind() const
{
return Audio;
}
void AudioStream::update()
{
sf::SoundStream::Status sfStatus = sf::SoundStream::getStatus();
switch (sfStatus)
{
case sf::SoundStream::Playing:
setStatus(sfe::Playing);
break;
case sf::SoundStream::Paused:
setStatus(sfe::Paused);
break;
case sf::SoundStream::Stopped:
setStatus(sfe::Stopped);
break;
default:
break;
}
}
bool AudioStream::onGetData(sf::SoundStream::Chunk& data)
{
AVPacket* packet = nullptr;
data.samples = m_samplesBuffer;
while (data.sampleCount < av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO) * m_sampleRate &&
(nullptr != (packet = popEncodedData())))
{
bool needsMoreDecoding = false;
bool gotFrame = false;
do
{
needsMoreDecoding = decodePacket(packet, m_audioFrame, gotFrame);
if (gotFrame)
{
uint8_t* samples = nullptr;
int nbSamples = 0;
int samplesLength = 0;
resampleFrame(m_audioFrame, samples, nbSamples, samplesLength);
CHECK(samples, "AudioStream::onGetData() - resampleFrame() error");
CHECK(nbSamples > 0, "AudioStream::onGetData() - resampleFrame() error");
CHECK(nbSamples == samplesLength / 2, "AudioStream::onGetData() resampleFrame() inconsistency");
CHECK(data.sampleCount + nbSamples < m_sampleRate * 2 * av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO), "AudioStream::onGetData() - Going to overflow!!");
std::memcpy((void *)(data.samples + data.sampleCount),
samples, samplesLength);
data.sampleCount += nbSamples;
}
} while (needsMoreDecoding);
av_free_packet(packet);
av_free(packet);
}
if (!packet)
{
sfeLogDebug("No more audio packets, do not go further");
}
return (packet != nullptr);
}
void AudioStream::onSeek(sf::Time timeOffset)
{
// CHECK(0, "AudioStream::onSeek() - not implemented");
}
bool AudioStream::decodePacket(AVPacket* packet, AVFrame* outputFrame, bool& gotFrame)
{
bool needsMoreDecoding = false;
int igotFrame = 0;
int decodedLength = avcodec_decode_audio4(m_stream->codec, outputFrame, &igotFrame, packet);
gotFrame = (igotFrame != 0);
CHECK(decodedLength >= 0, "AudioStream::decodePacket() - error: decodedLength=" + s(decodedLength));
if (decodedLength < packet->size)
{
needsMoreDecoding = true;
packet->data += decodedLength;
packet->size -= decodedLength;
}
return needsMoreDecoding;
}
void AudioStream::initResampler()
{
CHECK0(m_swrCtx, "AudioStream::initResampler() - resampler already initialized");
int err = 0;
/* create resampler context */
m_swrCtx = swr_alloc();
CHECK(m_swrCtx, "AudioStream::initResampler() - out of memory");
// Some media files don't define the channel layout, in this case take a default one
// according to the channels' count
if (m_stream->codec->channel_layout == 0)
{
m_stream->codec->channel_layout = av_get_default_channel_layout(m_stream->codec->channels);
}
/* set options */
av_opt_set_int (m_swrCtx, "in_channel_layout", m_stream->codec->channel_layout, 0);
av_opt_set_int (m_swrCtx, "in_sample_rate", m_stream->codec->sample_rate, 0);
av_opt_set_sample_fmt (m_swrCtx, "in_sample_fmt", m_stream->codec->sample_fmt, 0);
av_opt_set_int (m_swrCtx, "out_channel_layout", AV_CH_LAYOUT_STEREO, 0);
av_opt_set_int (m_swrCtx, "out_sample_rate", m_stream->codec->sample_rate, 0);
av_opt_set_sample_fmt (m_swrCtx, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
/* initialize the resampling context */
err = swr_init(m_swrCtx);
CHECK(err >= 0, "AudioStream::initResampler() - resampling context initialization error");
/* compute the number of converted samples: buffering is avoided
* ensuring that the output buffer will contain at least all the
* converted input samples */
m_maxDstNbSamples = m_dstNbSamples = 1024;
/* Create the resampling output buffer */
m_dstNbChannels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO);
err = av_samples_alloc_array_and_samples(&m_dstData, &m_dstLinesize, m_dstNbChannels,
m_dstNbSamples, AV_SAMPLE_FMT_S16, 0);
CHECK(err >= 0, "AudioStream::initResampler() - av_samples_alloc_array_and_samples error");
}
void AudioStream::resampleFrame(const AVFrame* frame, uint8_t*& outSamples, int& outNbSamples, int& outSamplesLength)
{
CHECK(m_swrCtx, "AudioStream::resampleFrame() - resampler is not initialized, call AudioStream::initResamplerFirst() !");
CHECK(frame, "AudioStream::resampleFrame() - invalid argument");
int src_rate, dst_rate, err, dst_bufsize;
src_rate = dst_rate = frame->sample_rate;
/* compute destination number of samples */
m_dstNbSamples = av_rescale_rnd(swr_get_delay(m_swrCtx, src_rate) +
frame->nb_samples, dst_rate, src_rate, AV_ROUND_UP);
if (m_dstNbSamples > m_maxDstNbSamples)
{
av_free(m_dstData[0]);
err = av_samples_alloc(m_dstData, &m_dstLinesize, m_dstNbChannels,
m_dstNbSamples, AV_SAMPLE_FMT_S16, 1);
CHECK(err >= 0, "AudioStream::resampleFrame() - out of memory");
m_maxDstNbSamples = m_dstNbSamples;
}
/* convert to destination format */
err = swr_convert(m_swrCtx, m_dstData, m_dstNbSamples, (const uint8_t **)frame->extended_data, frame->nb_samples);
CHECK(err >= 0, "AudioStream::resampleFrame() - swr_convert() error");
dst_bufsize = av_samples_get_buffer_size(&m_dstLinesize, m_dstNbChannels,
err, AV_SAMPLE_FMT_S16, 1);
CHECK(dst_bufsize >= 0, "AudioStream::resampleFrame() - av_samples_get_buffer_size() error");
outNbSamples = dst_bufsize / av_get_bytes_per_sample(AV_SAMPLE_FMT_S16);
outSamplesLength = dst_bufsize;
outSamples = m_dstData[0];
}
void AudioStream::willPlay(const Timer &timer)
{
Stream::willPlay(timer);
if (Stream::getStatus() == sfe::Stopped)
{
sf::Time initialTime = sf::SoundStream::getPlayingOffset();
sf::Clock timeout;
sf::SoundStream::play();
// Some audio drivers take time before the sound is actually played
// To avoid desynchronization with the timer, we don't return
// until the audio stream is actually started
while (sf::SoundStream::getPlayingOffset() == initialTime && timeout.getElapsedTime() < sf::seconds(5))
sf::sleep(sf::microseconds(10));
CHECK(sf::SoundStream::getPlayingOffset() != initialTime, "is your audio device broken? Audio did not start within 5 seconds");
}
else
{
sf::SoundStream::play();
waitForStatusUpdate(*this, sf::SoundStream::Playing);
}
}
void AudioStream::didPlay(const Timer& timer, sfe::Status previousStatus)
{
CHECK(SoundStream::getStatus() == SoundStream::Playing, "AudioStream::didPlay() - willPlay() not executed!");
Stream::didPlay(timer, previousStatus);
}
void AudioStream::didPause(const Timer& timer, sfe::Status previousStatus)
{
sf::SoundStream::pause();
waitForStatusUpdate(*this, sf::SoundStream::Paused);
Stream::didPause(timer, previousStatus);
}
void AudioStream::didStop(const Timer& timer, sfe::Status previousStatus)
{
sf::SoundStream::stop();
waitForStatusUpdate(*this, sf::SoundStream::Stopped);
Stream::didStop(timer, previousStatus);
}
}
<|endoftext|>
|
<commit_before>#ifndef _SNARKFRONT_HPP_
#define _SNARKFRONT_HPP_
////////////////////////////////////////////////////////////////////////////////
// this header file includes everything applications need
//
// not part of the EDSL but convenient for command line applications
#include <snarkfront/CompilePPZK_query.hpp>
#include <snarkfront/CompilePPZK_witness.hpp>
#include <snarkfront/CompileQAP.hpp>
#include <snarkfront/Getopt.hpp>
// read and write useful types for applications
#include <snarkfront/Serialize.hpp>
// the basic language
#include <snarkfront/DSL_algo.hpp>
#include <snarkfront/DSL_base.hpp>
#include <snarkfront/DSL_bless.hpp>
#include <snarkfront/DSL_identity.hpp>
#include <snarkfront/DSL_ppzk.hpp>
#include <snarkfront/DSL_utility.hpp>
// progress bar for proof generation and verification
#include <snarkfront/GenericProgressBar.hpp>
// input and printing of hexadecimal text
#include <snarkfront/HexUtil.hpp>
// initialize elliptic curves
#include <snarkfront/InitPairing.hpp>
// Merkle tree
#include <snarkfront/MerkleAuthPath.hpp>
#include <snarkfront/MerkleBundle.hpp>
#include <snarkfront/MerkleTree.hpp>
// Secure Hash Algorithms
#include <snarkfront/SHA_1.hpp>
#include <snarkfront/SHA_224.hpp>
#include <snarkfront/SHA_256.hpp>
#include <snarkfront/SHA_384.hpp>
#include <snarkfront/SHA_512.hpp>
#include <snarkfront/SHA_512_224.hpp>
#include <snarkfront/SHA_512_256.hpp>
// Advanced Encryption Algorithm
#include <snarkfront/AdvancedEncryptionStd.hpp>
#include <snarkfront/AES_Cipher.hpp>
#include <snarkfront/AES_InvCipher.hpp>
#include <snarkfront/AES_InvSBox.hpp>
#include <snarkfront/AES_KeyExpansion.hpp>
#include <snarkfront/AES_SBox.hpp>
#endif
<commit_msg>AES and SHA in cryptl<commit_after>#ifndef _SNARKFRONT_HPP_
#define _SNARKFRONT_HPP_
////////////////////////////////////////////////////////////////////////////////
// this header file includes everything applications need
//
// not part of the EDSL but convenient for command line applications
#include <snarkfront/CompilePPZK_query.hpp>
#include <snarkfront/CompilePPZK_witness.hpp>
#include <snarkfront/CompileQAP.hpp>
#include <snarkfront/Getopt.hpp>
// read and write useful types for applications
#include <snarkfront/Serialize.hpp>
// the basic language
#include <snarkfront/DSL_algo.hpp>
#include <snarkfront/DSL_base.hpp>
#include <snarkfront/DSL_bless.hpp>
#include <snarkfront/DSL_identity.hpp>
#include <snarkfront/DSL_ppzk.hpp>
#include <snarkfront/DSL_utility.hpp>
// progress bar for proof generation and verification
#include <snarkfront/GenericProgressBar.hpp>
// input and printing of hexadecimal text
#include <snarkfront/HexDumper.hpp>
// initialize elliptic curves
#include <snarkfront/InitPairing.hpp>
// Merkle tree
#include <snarkfront/MerkleAuthPath.hpp>
#include <snarkfront/MerkleBundle.hpp>
#include <snarkfront/MerkleTree.hpp>
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2016 Jeremy Starnes
This file is part of TDSE.
TDSE 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.
TDSE 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 TDSE; see the file COPYING. If not, see <http://www.gnu.org/licenses/agpl>
*/
#include "physics.h"
glm::mat2 bt_to_glm2d(const btMatrix3x3 & btmat)
{
btVector3 cols[2] = {btmat.getColumn(0), btmat.getColumn(1)};
return glm::mat2(
cols[0].getX(), cols[0].getY(),
cols[1].getX(), cols[1].getY()
);
}
glm::mat3 bt_to_glm2d(const btTransform & bttrans)
{
return compose_transform(
glm::vec2( bttrans.getOrigin().getX(), bttrans.getOrigin().getY() ),
bt_to_glm2d( bttrans.getBasis() )
);
}
btTransform glm2d_to_bt(const glm::mat3 & glmtrans)
{
return btTransform(
btMatrix3x3(
glmtrans[0][0], glmtrans[1][0], 0.0,
glmtrans[0][1], glmtrans[1][1], 0.0,
0.0, 0.0, 1.0
),
btVector3(glmtrans[2].x, glmtrans[2].y, 0.0)
);
}
bullet_components::bullet_components()
: dispatcher(&collision_config),
convexAlgo2d(&simplex, &pdsolver)
{
dispatcher.registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,
CONVEX_2D_SHAPE_PROXYTYPE, &convexAlgo2d);
}
bullet_world::bullet_world()
: btDiscreteDynamicsWorld(&dispatcher, &overlapping_pair_cache, &solver,
&collision_config)
{
setGravity(btVector3(0, 0, 0));
}
const float_seconds bullet_world::fixed_substep(1.0f/60.0f);
void bullet_world::step(float_seconds step_time)
{
// Limit to 10 substeps
stepSimulation( step_time.count(), 10, fixed_substep.count() );
}
void bullet_world::presubstep(float_seconds substep_time)
{
// Trigger all collision callbacks
btDispatcher & dispatcher = *( getDispatcher() );
int manifolds = dispatcher.getNumManifolds();
for(int i = 0; i != manifolds; ++i)
{
btPersistentManifold & manifold =
*( dispatcher.getManifoldByIndexInternal(i) );
int contacts = manifold.getNumContacts();
for(int contact = 0; contact != contacts; ++contact)
{
if(manifold.getContactPoint(contact).getDistance() <= 0.0)
{
// All btCollisionObect instances are assumed to be body instances
// It's safe to modify bodies between substeps
body * body0 = static_cast<body *>
( const_cast<btCollisionObject *>(manifold.getBody0()) );
body * body1 = static_cast<body *>
( const_cast<btCollisionObject *>(manifold.getBody1()) );
needs_collision * ptr;
if( (ptr = dynamic_cast<needs_collision *>(body0)) )
ptr->collision(*body1);
if( (ptr = dynamic_cast<needs_collision *>(body1)) )
ptr->collision(*body0);
break;
}
}
}
// Trigger all presubstep callbacks
for(auto i = presubsteps.begin(); i != presubsteps.end(); ++i)
(*i)->presubstep( *this, substep_time );
// Step physics world
btDiscreteDynamicsWorld::internalSingleStepSimulation( substep_time.count() );
}
void bullet_world::add_callback(needs_presubstep & callback)
{
presubsteps.insert(&callback);
}
void bullet_world::remove_callback(needs_presubstep & callback)
{
presubsteps.erase(&callback);
}
void bullet_world::add_body(body & b)
{
addRigidBody(&b);
}
void bullet_world::remove_body(body & b)
{
removeRigidBody(&b);
}
void bullet_world::internalSingleStepSimulation(btScalar timeStep)
{
presubstep( float_seconds(timeStep) );
}
motion_state::motion_state(const glm::mat3 & transform_)
: transform( glm2d_to_bt(transform_) )
{}
glm::mat3 motion_state::model() const
{
const btMatrix3x3 & ori = transform.getBasis();
const btVector3 & pos = transform.getOrigin();
btVector3 cols[3] = {ori.getColumn(0), ori.getColumn(1), ori.getColumn(2)};
return glm::mat3(
cols[0].getX(), cols[0].getY(), 0.0f,
cols[1].getX(), cols[1].getY(), 0.0f,
pos.getX(), pos.getY(), 1.0f
);
}
glm::mat2 motion_state::orientation() const
{
return bt_to_glm2d( transform.getBasis() );
}
glm::vec2 motion_state::position() const
{
const btVector3 & pos = transform.getOrigin();
return glm::vec2(pos.getX(), pos.getY());
}
void motion_state::getWorldTransform(btTransform & world_trans) const
{
world_trans = transform;
}
void motion_state::setWorldTransform(const btTransform & world_trans)
{
transform = world_trans;
}
btRigidBody::btRigidBodyConstructionInfo body::info
(btScalar mass,
btMotionState & state,
const btCollisionShape & shape,
const btVector3 & inertia)
{
btRigidBody::btRigidBodyConstructionInfo _info(
mass, &state,
// Bodies never modify collision shapes, so I dunno why this isn't const
const_cast<btCollisionShape *>(&shape),
inertia
);
_info.m_rollingFriction = 0.2;
return _info;
}
btVector3 body::calc_local_inertia
(
const btCollisionShape & shape,
float mass
)
{
btVector3 inertia;
shape.calculateLocalInertia(mass, inertia);
return inertia;
}
#include <glm/gtc/matrix_transform.hpp>
body::body(float mass,
const btCollisionShape & shape,
const glm::mat3 & transform)
: motion_state(transform),
btRigidBody( info(
mass, *this, shape,
calc_local_inertia(shape, mass)
) )
{
// Restrict linear movement to the XY plane
setLinearFactor(btVector3(1, 1, 0));
// Restrict angular movement to the z axis
setAngularFactor(btVector3(0, 0, 1));
}
glm::mat3 body::real_transform() const
{
return bt_to_glm2d( btRigidBody::getWorldTransform() );
}
glm::mat2 body::real_orientation() const
{
return bt_to_glm2d( btRigidBody::getWorldTransform().getBasis() );
}
glm::vec2 body::real_position() const
{
const btVector3 & origin = btRigidBody::getWorldTransform().getOrigin();
return glm::vec2( origin.getX(), origin.getY() );
}
void body::warp(const glm::mat3 & new_trans)
{
btRigidBody::setWorldTransform( glm2d_to_bt(new_trans) );
}
<commit_msg>reorder substep routine in class bullet_world<commit_after>/*
Copyright (C) 2016 Jeremy Starnes
This file is part of TDSE.
TDSE 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.
TDSE 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 TDSE; see the file COPYING. If not, see <http://www.gnu.org/licenses/agpl>
*/
#include "physics.h"
glm::mat2 bt_to_glm2d(const btMatrix3x3 & btmat)
{
btVector3 cols[2] = {btmat.getColumn(0), btmat.getColumn(1)};
return glm::mat2(
cols[0].getX(), cols[0].getY(),
cols[1].getX(), cols[1].getY()
);
}
glm::mat3 bt_to_glm2d(const btTransform & bttrans)
{
return compose_transform(
glm::vec2( bttrans.getOrigin().getX(), bttrans.getOrigin().getY() ),
bt_to_glm2d( bttrans.getBasis() )
);
}
btTransform glm2d_to_bt(const glm::mat3 & glmtrans)
{
return btTransform(
btMatrix3x3(
glmtrans[0][0], glmtrans[1][0], 0.0,
glmtrans[0][1], glmtrans[1][1], 0.0,
0.0, 0.0, 1.0
),
btVector3(glmtrans[2].x, glmtrans[2].y, 0.0)
);
}
bullet_components::bullet_components()
: dispatcher(&collision_config),
convexAlgo2d(&simplex, &pdsolver)
{
dispatcher.registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,
CONVEX_2D_SHAPE_PROXYTYPE, &convexAlgo2d);
}
bullet_world::bullet_world()
: btDiscreteDynamicsWorld(&dispatcher, &overlapping_pair_cache, &solver,
&collision_config)
{
setGravity(btVector3(0, 0, 0));
}
const float_seconds bullet_world::fixed_substep(1.0f/60.0f);
void bullet_world::step(float_seconds step_time)
{
// Limit to 10 substeps
stepSimulation( step_time.count(), 10, fixed_substep.count() );
}
void bullet_world::presubstep(float_seconds substep_time)
{
// Trigger all presubstep callbacks
for(auto i = presubsteps.begin(); i != presubsteps.end(); ++i)
(*i)->presubstep( *this, substep_time );
// Step physics world
btDiscreteDynamicsWorld::internalSingleStepSimulation( substep_time.count() );
// Trigger all collision callbacks
btDispatcher & dispatcher = *( getDispatcher() );
int manifolds = dispatcher.getNumManifolds();
for(int i = 0; i != manifolds; ++i)
{
btPersistentManifold & manifold =
*( dispatcher.getManifoldByIndexInternal(i) );
int contacts = manifold.getNumContacts();
for(int contact = 0; contact != contacts; ++contact)
{
if(manifold.getContactPoint(contact).getDistance() <= 0.0)
{
// All btCollisionObect instances are assumed to be body instances
// It's safe to modify bodies between substeps
body * body0 = static_cast<body *>
( const_cast<btCollisionObject *>(manifold.getBody0()) );
body * body1 = static_cast<body *>
( const_cast<btCollisionObject *>(manifold.getBody1()) );
needs_collision * ptr;
if( (ptr = dynamic_cast<needs_collision *>(body0)) )
ptr->collision(*body1);
if( (ptr = dynamic_cast<needs_collision *>(body1)) )
ptr->collision(*body0);
break;
}
}
}
}
void bullet_world::add_callback(needs_presubstep & callback)
{
presubsteps.insert(&callback);
}
void bullet_world::remove_callback(needs_presubstep & callback)
{
presubsteps.erase(&callback);
}
void bullet_world::add_body(body & b)
{
addRigidBody(&b);
}
void bullet_world::remove_body(body & b)
{
removeRigidBody(&b);
}
void bullet_world::internalSingleStepSimulation(btScalar timeStep)
{
presubstep( float_seconds(timeStep) );
}
motion_state::motion_state(const glm::mat3 & transform_)
: transform( glm2d_to_bt(transform_) )
{}
glm::mat3 motion_state::model() const
{
const btMatrix3x3 & ori = transform.getBasis();
const btVector3 & pos = transform.getOrigin();
btVector3 cols[3] = {ori.getColumn(0), ori.getColumn(1), ori.getColumn(2)};
return glm::mat3(
cols[0].getX(), cols[0].getY(), 0.0f,
cols[1].getX(), cols[1].getY(), 0.0f,
pos.getX(), pos.getY(), 1.0f
);
}
glm::mat2 motion_state::orientation() const
{
return bt_to_glm2d( transform.getBasis() );
}
glm::vec2 motion_state::position() const
{
const btVector3 & pos = transform.getOrigin();
return glm::vec2(pos.getX(), pos.getY());
}
void motion_state::getWorldTransform(btTransform & world_trans) const
{
world_trans = transform;
}
void motion_state::setWorldTransform(const btTransform & world_trans)
{
transform = world_trans;
}
btRigidBody::btRigidBodyConstructionInfo body::info
(btScalar mass,
btMotionState & state,
const btCollisionShape & shape,
const btVector3 & inertia)
{
btRigidBody::btRigidBodyConstructionInfo _info(
mass, &state,
// Bodies never modify collision shapes, so I dunno why this isn't const
const_cast<btCollisionShape *>(&shape),
inertia
);
_info.m_rollingFriction = 0.2;
return _info;
}
btVector3 body::calc_local_inertia
(
const btCollisionShape & shape,
float mass
)
{
btVector3 inertia;
shape.calculateLocalInertia(mass, inertia);
return inertia;
}
#include <glm/gtc/matrix_transform.hpp>
body::body(float mass,
const btCollisionShape & shape,
const glm::mat3 & transform)
: motion_state(transform),
btRigidBody( info(
mass, *this, shape,
calc_local_inertia(shape, mass)
) )
{
// Restrict linear movement to the XY plane
setLinearFactor(btVector3(1, 1, 0));
// Restrict angular movement to the z axis
setAngularFactor(btVector3(0, 0, 1));
}
glm::mat3 body::real_transform() const
{
return bt_to_glm2d( btRigidBody::getWorldTransform() );
}
glm::mat2 body::real_orientation() const
{
return bt_to_glm2d( btRigidBody::getWorldTransform().getBasis() );
}
glm::vec2 body::real_position() const
{
const btVector3 & origin = btRigidBody::getWorldTransform().getOrigin();
return glm::vec2( origin.getX(), origin.getY() );
}
void body::warp(const glm::mat3 & new_trans)
{
btRigidBody::setWorldTransform( glm2d_to_bt(new_trans) );
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013 Gustaf Räntilä
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIBQ_TYPE_TRAITS_ARGUMENTS_IMPL_HPP
#define LIBQ_TYPE_TRAITS_ARGUMENTS_IMPL_HPP
namespace q {
namespace detail {
template< typename Tuple, class Args >
struct tuple_convertible_to_arguments
: public std::true_type
{
// forward_decay
// TODO: Implement
};
} // namespace detail
template< typename A, typename B >
struct is_argument_same
: two_fold< A, B, q::logic_and, std::true_type, q::is_same_type, std::false_type >
{ };
template< typename A, typename B >
struct is_argument_same_or_convertible
: bool_type<
( A::empty_or_void::value and B::empty_or_void::value )
or
two_fold<
A,
B,
q::logic_and,
std::true_type,
q::is_convertible_to, std::false_type
>::value
>
{ };
template< typename A, typename B >
struct is_argument_same_or_convertible_incl_void
: bool_type<
( A::empty_or_voidish::value and B::empty_or_voidish::value )
or
two_fold<
A,
B,
q::logic_and,
std::true_type,
q::is_convertible_to, std::false_type
>::value
>
{ };
template< typename Superset, typename Subset >
struct argument_contains_all
: fold<
Subset,
generic_operator<
Superset::template has, logic_and
>::template fold_type,
std::true_type
>
{ };
namespace detail {
template< typename A, typename B >
struct merge_two_arguments;
template< typename... A, typename... B >
struct merge_two_arguments< ::q::arguments< A... >, ::q::arguments< B... > >
: ::q::arguments< A..., B... >
{
typedef ::q::arguments< A..., B... > type;
};
} // namespace detail
/**
* Merges the inner arguments of the list of q::arguments Arguments and injects
* in T.
*
* A typical usage is to merge multiple q::arguments into one.
*/
template< template< typename... > class T, typename... Arguments >
struct merge
{
typedef typename fold<
q::arguments< Arguments... >,
detail::merge_two_arguments,
q::arguments< >
>::template apply< T >::type type;
};
template< typename... Args >
struct are_all_unique;
template< typename First, typename... Rest >
struct are_all_unique< First, Rest... >
: ::q::bool_type<
arguments< Rest... >
::template filter< same< First >::template as >::type
::empty::value
and
are_all_unique< Rest... >::value
>
{ };
template< >
struct are_all_unique< >
: std::true_type
{ };
} // namespace q
#endif // LIBQ_TYPE_TRAITS_ARGUMENTS_IMPL_HPP
<commit_msg>q::get_tuple_element< T >( tuple )<commit_after>/*
* Copyright 2013 Gustaf Räntilä
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIBQ_TYPE_TRAITS_ARGUMENTS_IMPL_HPP
#define LIBQ_TYPE_TRAITS_ARGUMENTS_IMPL_HPP
namespace q {
namespace detail {
template< typename Tuple, class Args >
struct tuple_convertible_to_arguments
: public std::true_type
{
// forward_decay
// TODO: Implement
};
} // namespace detail
template< typename A, typename B >
struct is_argument_same
: two_fold< A, B, q::logic_and, std::true_type, q::is_same_type, std::false_type >
{ };
template< typename A, typename B >
struct is_argument_same_or_convertible
: bool_type<
( A::empty_or_void::value and B::empty_or_void::value )
or
two_fold<
A,
B,
q::logic_and,
std::true_type,
q::is_convertible_to, std::false_type
>::value
>
{ };
template< typename A, typename B >
struct is_argument_same_or_convertible_incl_void
: bool_type<
( A::empty_or_voidish::value and B::empty_or_voidish::value )
or
two_fold<
A,
B,
q::logic_and,
std::true_type,
q::is_convertible_to, std::false_type
>::value
>
{ };
template< typename Superset, typename Subset >
struct argument_contains_all
: fold<
Subset,
generic_operator<
Superset::template has, logic_and
>::template fold_type,
std::true_type
>
{ };
namespace detail {
template< typename A, typename B >
struct merge_two_arguments;
template< typename... A, typename... B >
struct merge_two_arguments< ::q::arguments< A... >, ::q::arguments< B... > >
: ::q::arguments< A..., B... >
{
typedef ::q::arguments< A..., B... > type;
};
} // namespace detail
/**
* Merges the inner arguments of the list of q::arguments Arguments and injects
* in T.
*
* A typical usage is to merge multiple q::arguments into one.
*/
template< template< typename... > class T, typename... Arguments >
struct merge
{
typedef typename fold<
q::arguments< Arguments... >,
detail::merge_two_arguments,
q::arguments< >
>::template apply< T >::type type;
};
template< typename... Args >
struct are_all_unique;
template< typename First, typename... Rest >
struct are_all_unique< First, Rest... >
: ::q::bool_type<
arguments< Rest... >
::template filter< same< First >::template as >::type
::empty::value
and
are_all_unique< Rest... >::value
>
{ };
template< >
struct are_all_unique< >
: std::true_type
{ };
template< typename T, typename... Types >
typename std::enable_if<
are_all_unique< Types... >::value,
T&
>::type
get_tuple_element( std::tuple< Types... >& t )
{
#ifdef LIBQ_WITH_CPP14
return std::get< T >( t );
#else
typedef typename arguments< Types... >::template index_of< T > Index;
static_assert( Index::value != -1, "No such type in the given tuple" );
return std::get< Index::value >( t );
#endif
}
template< typename T, typename... Types >
typename std::enable_if<
are_all_unique< Types... >::value,
T&&
>::type
get_tuple_element( std::tuple< Types... >&& t )
{
#ifdef LIBQ_WITH_CPP14
return std::get< T >( std::move( t ) );
#else
typedef typename arguments< Types... >::template index_of< T > Index;
static_assert( Index::value != -1, "No such type in the given tuple" );
return std::get< Index::value >( std::move( t ) );
#endif
}
template< typename T, typename... Types >
typename std::enable_if<
are_all_unique< Types... >::value,
const T&
>::type
get_tuple_element( const std::tuple< Types... >& t )
{
#ifdef LIBQ_WITH_CPP14
return std::get< T >( t );
#else
typedef typename arguments< Types... >::template index_of< T > Index;
static_assert( Index::value != -1, "No such type in the given tuple" );
return std::get< Index::value >( t );
#endif
}
} // namespace q
#endif // LIBQ_TYPE_TRAITS_ARGUMENTS_IMPL_HPP
<|endoftext|>
|
<commit_before>/// @brief provides CORDIC for cos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"
namespace std {
/// @brief computes square root by CORDIC-algorithm
/// @ref page 11
template<typename T, size_t n, size_t f, class op, class up>
core::fixed_point<T, n, f, op, up> sqrt(core::fixed_point<T, n, f, op, up> const val)
{
typedef core::fixed_point<T, n, f, op, up> fp;
assert(("sqrt parameter is negative", val > fp(0)));
if (val < fp(0)) {
throw std::exception("sqrt: arg is negative");
}
if (val == fp(0.0)) {
return fp(0.0);
}
else if (val == fp(1.0)) {
return fp(1.0);
}
// Chosen fixed-point format must have several bits to represent
// lut. Also format must enable argument translating to interval [1.0, 2.0].
// So format must reserve two bits at least for integer part.
typedef core::fixed_point<boost::int_t<1u+f+2u>::least, f+2u, f, op, up> work_type;
typedef core::cordic::lut<f, work_type> lut;
int power(0);
fp arg(val);
while (arg >= fp(2.0 )) {
as_native(arg) >>= 1u;
power--;
}
while (arg < fp(1.0)) {
as_native(arg) <<= 1u;
power++;
}
// CORDIC vectoring mode:
lut const angles = lut::hyperbolic_wo_repeated_iterations();
fp const norm(1.0 / lut::hyperbolic_scale_with_repeated_iterations(n));
work_type x(work_type(arg) + 0.25), y(work_type(arg) - 0.25), z(arg);
{
size_t repeated(4u);
size_t num(0);
for (size_t i(1u); i < f + 1u; ++i)
{
int const sign = ((x.value() < 0)? -1 : +1) * ((y.value() < 0)? -1 : +1);
work_type::word_type const store(x.value());
x = x - work_type::wrap(sign * (y.value() >> (num + 1u)));
y = y - work_type::wrap(sign * (store >> (num + 1u)));
z = (sign > 0) ? z + angles[num] : z - angles[num];
// do repetition to receive convergence
if (i == repeated && i != n - 1) {
int const sign = ((x.value() < 0)? -1 : +1) * ((y.value() < 0)? -1 : +1);
work_type::word_type const store(x.value());
x = x - work_type::wrap(sign * (y.value() >> (num + 1u)));
y = y - work_type::wrap(sign * (store >> (num + 1u)));
z = (sign > 0) ? z + angles[num] : z - angles[num];
i += 1u;
repeated = 3u * repeated + 1u;
}
num += 1u;
}
}
fp result(norm * x); // interval [1.0, 2.0]
if (power > 0) {
as_native(result) >>= (power >> 1u);
if (power & 1u) {
result = result * work_type::CONST_SQRT1_2;
}
}
else {
size_t const p(-power);
as_native(result) <<= (p >> 1u);
if (p & 1u) {
result = result * work_type::CONST_SQRT2;
}
}
return result;
}
}
<commit_msg>sqrt.inl: extend range of available Q-formats<commit_after>/// @brief provides CORDIC for cos function
/// @ref see H. Dawid, H. Meyr, "CORDIC Algorithms and Architectures"
namespace std {
/// @brief computes square root by CORDIC-algorithm
/// @ref page 11
template<typename T, size_t n, size_t f, class op, class up>
core::fixed_point<T, n, f, op, up> sqrt(core::fixed_point<T, n, f, op, up> const val)
{
typedef core::fixed_point<T, n, f, op, up> fp;
assert(("sqrt parameter is negative", val >= fp(0)));
if (val < fp(0)) {
throw std::exception("sqrt: arg is negative");
}
if (val == fp(0.0)) {
return fp(0.0);
}
else if (val == fp(1.0)) {
return fp(1.0);
}
// Chosen fixed-point format must have several bits to represent
// lut. Also format must enable argument translating to interval [1.0, 2.0].
// So format must reserve two bits at least for integer part.
typedef core::fixed_point<boost::int_t<1u+f+2u>::least, f+2u, f, op, up> work_type;
typedef core::cordic::lut<f, work_type> lut;
int power(0);
fp arg(val);
while (arg >= fp(2.0 )) {
as_native(arg) >>= 1u;
power--;
}
while (arg < fp(1.0)) {
as_native(arg) <<= 1u;
power++;
}
// CORDIC vectoring mode:
lut const angles = lut::hyperbolic_wo_repeated_iterations();
typename core::U_fixed_point<f + 1u, f>::type const norm(1.0 / lut::hyperbolic_scale_with_repeated_iterations(n));
work_type x(work_type(arg) + 0.25), y(work_type(arg) - 0.25), z(arg);
{
size_t repeated(4u);
size_t num(0);
for (size_t i(1u); i < f + 1u; ++i)
{
int const sign = ((x.value() < 0)? -1 : +1) * ((y.value() < 0)? -1 : +1);
work_type::word_type const store(x.value());
x = x - work_type::wrap(sign * (y.value() >> (num + 1u)));
y = y - work_type::wrap(sign * (store >> (num + 1u)));
z = (sign > 0) ? z + angles[num] : z - angles[num];
// do repetition to receive convergence
if (i == repeated && i != n - 1) {
int const sign = ((x.value() < 0)? -1 : +1) * ((y.value() < 0)? -1 : +1);
work_type::word_type const store(x.value());
x = x - work_type::wrap(sign * (y.value() >> (num + 1u)));
y = y - work_type::wrap(sign * (store >> (num + 1u)));
z = (sign > 0) ? z + angles[num] : z - angles[num];
i += 1u;
repeated = 3u * repeated + 1u;
}
num += 1u;
}
}
fp result(x * norm); // interval [1.0, 2.0]
if (power > 0) {
as_native(result) >>= (power >> 1u);
if (power & 1u) {
result = result * work_type::CONST_SQRT1_2;
}
}
else {
size_t const p(-power);
as_native(result) <<= (p >> 1u);
if (p & 1u) {
result = result * work_type::CONST_SQRT2;
}
}
return result;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-13T04:03:21";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<commit_msg>Update WebRTC code version (2021-01-15T04:04:08).<commit_after>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-15T04:04:08";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-18T04:04:58";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<commit_msg>Update WebRTC code version (2020-12-21T04:04:21).<commit_after>/*
* Copyright (c) 2020 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "call/version.h"
namespace webrtc {
// The timestamp is always in UTC.
const char* const kSourceTimestamp = "WebRTC source stamp 2020-12-21T04:04:21";
void LoadWebRTCVersionInRegister() {
// Using volatile to instruct the compiler to not optimize `p` away even
// if it looks unused.
const char* volatile p = kSourceTimestamp;
static_cast<void>(p);
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#include "exodus/createtx.h"
#include "exodus/errors.h"
#include "exodus/encoding.h"
#include "exodus/exodus.h"
#include "exodus/wallettxs.h"
#include "base58.h"
#include "coins.h"
#include "core_io.h"
#include "main.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/standard.h"
#include "test/test_bitcoin.h"
#include "test/fixtures.h"
#include "utilstrencodings.h"
#include "exodus/utilsbitcoin.h"
#include "wallet/wallet.h"
#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
BOOST_FIXTURE_TEST_SUITE(exodus_build_tx_tests, ZerocoinTestingSetup200)
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_normal_b)
{
std::vector<unsigned char> data(nMaxDatacarrierBytes + 1);
std::string fromAddress = CBitcoinAddress(pubkey.GetID()).ToString();
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
0, // No error
exodus::WalletTxBuilder(fromAddress, "", "", 0, data, txid, rawHex, false)
);
CTransaction decTx;
BOOST_CHECK(DecodeHexTx(decTx, rawHex));
BOOST_CHECK(!decTx.IsSigmaSpend());
BOOST_CHECK_EQUAL(
EXODUS_CLASS_B,
exodus::GetEncodingClass(decTx, chainActive.Height())
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_normal_c)
{
std::vector<unsigned char> data(80);
std::string fromAddress = CBitcoinAddress(pubkey.GetID()).ToString();
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
0, // No error
exodus::WalletTxBuilder(fromAddress, "", "", 0, data, txid, rawHex, false)
);
CTransaction decTx;
BOOST_CHECK(DecodeHexTx(decTx, rawHex));
BOOST_CHECK(!decTx.IsSigmaSpend());
BOOST_CHECK_EQUAL(
EXODUS_CLASS_C,
exodus::GetEncodingClass(decTx, chainActive.Height())
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_sigma_without_mints)
{
pwalletMain->SetBroadcastTransactions(true);
CreateAndProcessEmptyBlocks(200, scriptPubKey);
std::vector<unsigned char> data(80);
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
MPRPCErrorCode::MP_INPUTS_INVALID,
exodus::WalletTxBuilder("", "", "", 0, data, txid, rawHex, false, exodus::InputMode::SIGMA)
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_sigma_with_toolarge_data)
{
pwalletMain->SetBroadcastTransactions(true);
CreateAndProcessEmptyBlocks(200, scriptPubKey);
string stringError;
BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(
stringError, {{"1", 10}}, SIGMA), stringError + " - Create Mint failed");
CreateAndProcessBlock({}, scriptPubKey);
CreateAndProcessEmptyBlocks(5, scriptPubKey);
std::vector<unsigned char> data(nMaxDatacarrierBytes + 1);
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
MPRPCErrorCode::MP_ENCODING_ERROR,
exodus::WalletTxBuilder("", "", "", 0, data, txid, rawHex, false, exodus::InputMode::SIGMA)
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_sigma_success)
{
pwalletMain->SetBroadcastTransactions(true);
CreateAndProcessEmptyBlocks(200, scriptPubKey);
string stringError;
BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(
stringError, {{"1", 10}}, SIGMA), stringError + " - Create Mint failed");
CreateAndProcessBlock({}, scriptPubKey);
CreateAndProcessEmptyBlocks(5, scriptPubKey);
std::vector<unsigned char> data(80);
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
0, // No error
exodus::WalletTxBuilder("", "", "", 0, data, txid, rawHex, false, exodus::InputMode::SIGMA)
);
CTransaction decTx;
BOOST_CHECK(DecodeHexTx(decTx, rawHex));
BOOST_CHECK(decTx.IsSigmaSpend());
BOOST_CHECK_EQUAL(
EXODUS_CLASS_C,
exodus::GetEncodingClass(decTx, chainActive.Height())
);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix test fail<commit_after>#include "exodus/createtx.h"
#include "exodus/errors.h"
#include "exodus/encoding.h"
#include "exodus/exodus.h"
#include "exodus/wallettxs.h"
#include "base58.h"
#include "coins.h"
#include "core_io.h"
#include "main.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/standard.h"
#include "test/test_bitcoin.h"
#include "test/fixtures.h"
#include "utilstrencodings.h"
#include "exodus/utilsbitcoin.h"
#include "wallet/wallet.h"
#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
BOOST_FIXTURE_TEST_SUITE(exodus_build_tx_tests, ZerocoinTestingSetup200)
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_normal_b)
{
std::vector<unsigned char> data(nMaxDatacarrierBytes + 1);
std::string fromAddress = CBitcoinAddress(pubkey.GetID()).ToString();
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
0, // No error
exodus::WalletTxBuilder(fromAddress, "", "", 0, data, txid, rawHex, false)
);
CTransaction decTx;
BOOST_CHECK(DecodeHexTx(decTx, rawHex));
BOOST_CHECK(!decTx.IsSigmaSpend());
BOOST_CHECK_EQUAL(
EXODUS_CLASS_B,
exodus::GetEncodingClass(decTx, chainActive.Height())
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_normal_c)
{
std::vector<unsigned char> data(80);
std::string fromAddress = CBitcoinAddress(pubkey.GetID()).ToString();
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
0, // No error
exodus::WalletTxBuilder(fromAddress, "", "", 0, data, txid, rawHex, false)
);
CTransaction decTx;
BOOST_CHECK(DecodeHexTx(decTx, rawHex));
BOOST_CHECK(!decTx.IsSigmaSpend());
BOOST_CHECK_EQUAL(
EXODUS_CLASS_C,
exodus::GetEncodingClass(decTx, chainActive.Height())
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_sigma_without_mints)
{
pwalletMain->SetBroadcastTransactions(true);
CreateAndProcessEmptyBlocks(200, scriptPubKey);
std::vector<unsigned char> data(80);
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
MPRPCErrorCode::MP_SIGMA_INPUTS_INVALID,
exodus::WalletTxBuilder("", "", "", 0, data, txid, rawHex, false, exodus::InputMode::SIGMA)
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_sigma_with_toolarge_data)
{
pwalletMain->SetBroadcastTransactions(true);
CreateAndProcessEmptyBlocks(200, scriptPubKey);
string stringError;
BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(
stringError, {{"1", 10}}, SIGMA), stringError + " - Create Mint failed");
CreateAndProcessBlock({}, scriptPubKey);
CreateAndProcessEmptyBlocks(5, scriptPubKey);
std::vector<unsigned char> data(nMaxDatacarrierBytes + 1);
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
MPRPCErrorCode::MP_ENCODING_ERROR,
exodus::WalletTxBuilder("", "", "", 0, data, txid, rawHex, false, exodus::InputMode::SIGMA)
);
}
BOOST_AUTO_TEST_CASE(wallettxbuilder_create_sigma_success)
{
pwalletMain->SetBroadcastTransactions(true);
CreateAndProcessEmptyBlocks(200, scriptPubKey);
string stringError;
BOOST_CHECK_MESSAGE(pwalletMain->CreateZerocoinMintModel(
stringError, {{"1", 10}}, SIGMA), stringError + " - Create Mint failed");
CreateAndProcessBlock({}, scriptPubKey);
CreateAndProcessEmptyBlocks(5, scriptPubKey);
std::vector<unsigned char> data(80);
uint256 txid;
std::string rawHex;
BOOST_CHECK_EQUAL(
0, // No error
exodus::WalletTxBuilder("", "", "", 0, data, txid, rawHex, false, exodus::InputMode::SIGMA)
);
CTransaction decTx;
BOOST_CHECK(DecodeHexTx(decTx, rawHex));
BOOST_CHECK(decTx.IsSigmaSpend());
BOOST_CHECK_EQUAL(
EXODUS_CLASS_C,
exodus::GetEncodingClass(decTx, chainActive.Height())
);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>#include "tiles.hpp"
#include "../incl/utils.hpp"
#include <cerrno>
#include <cstdio>
#include <ctime>
bool Tiles::hashvecinit = false;
unsigned long Tiles::hashvec[Ntiles][Ntiles];
Tiles::Tiles(FILE *in) {
readruml(in);
initops();
if (!hashvecinit)
inithashvec();
}
void Tiles::readruml(FILE *in) {
unsigned int w, h;
if (fscanf(in, " %u %u", &w, &h) != 2)
fatalx(errno, "Failed to read width and height");
if (w != Width && h != HEIGHT)
fatal("Width and height instance/compiler option mismatch");
if (fscanf(in, " starting positions for each tile:") != 0)
fatalx(errno, "Failed to read the starting position label");
for (Tile t = 0; t < Ntiles; t++) {
unsigned int p;
int r = fscanf(in, " %u", &p);
if (r != 1)
fatalx(errno, "Failed to read the starting positions: r=%d", r);
init[p] = t;
}
if (fscanf(in, " goal positions:") != 0)
fatalx(errno, "Failed to read the goal position label");
for (Tile t = 0; t < Ntiles; t++) {
unsigned int p;
if (fscanf(in, " %u", &p) != 1)
fatalx(errno, "Failed to read the goal positions");
goalpos[t] = p;
}
}
void Tiles::initops(void) {
for (int i = 0; i < Ntiles; i++) {
ops[i].n = 0;
if (i >= Width)
ops[i].mvs[ops[i].n++] = i - Width;
if (i % Width > 0)
ops[i].mvs[ops[i].n++] = i - 1;
if (i % Width < Width - 1)
ops[i].mvs[ops[i].n++] = i + 1;
if (i < Ntiles - Width)
ops[i].mvs[ops[i].n++] = i + Width;
}
}
void Tiles::inithashvec(void) {
hashvecinit = true;
Rand r(time(NULL));
for (int i = 0; i < Ntiles; i++) {
for (int j = 0; j < Ntiles; j++)
hashvec[i][j] = r.bits();
}
}
void Tiles::dumptiles(FILE *out, Tile ts[]) {
for (int i = 0; i < Ntiles; i++) {
if (i > 0 && i % Width == 0)
fprintf(out, "\n");
else if (i > 0)
fprintf(out, "\t");
fprintf(out, "%2d", ts[i]);
}
fprintf(out, "\n");
}<commit_msg>Add newlines to fatal() calls.<commit_after>#include "tiles.hpp"
#include "../incl/utils.hpp"
#include <cerrno>
#include <cstdio>
#include <ctime>
bool Tiles::hashvecinit = false;
unsigned long Tiles::hashvec[Ntiles][Ntiles];
Tiles::Tiles(FILE *in) {
readruml(in);
initops();
if (!hashvecinit)
inithashvec();
}
void Tiles::readruml(FILE *in) {
unsigned int w, h;
if (fscanf(in, " %u %u", &w, &h) != 2)
fatalx(errno, "Failed to read width and height\n");
if (w != Width && h != HEIGHT)
fatal("Width and height instance/compiler option mismatch\n");
if (fscanf(in, " starting positions for each tile:") != 0)
fatalx(errno, "Failed to read the starting position label\n");
for (Tile t = 0; t < Ntiles; t++) {
unsigned int p;
int r = fscanf(in, " %u", &p);
if (r != 1)
fatalx(errno, "Failed to read the starting positions: r=%d\n", r);
init[p] = t;
}
if (fscanf(in, " goal positions:") != 0)
fatalx(errno, "Failed to read the goal position label\n");
for (Tile t = 0; t < Ntiles; t++) {
unsigned int p;
if (fscanf(in, " %u", &p) != 1)
fatalx(errno, "Failed to read the goal position\n");
goalpos[t] = p;
}
}
void Tiles::initops(void) {
for (int i = 0; i < Ntiles; i++) {
ops[i].n = 0;
if (i >= Width)
ops[i].mvs[ops[i].n++] = i - Width;
if (i % Width > 0)
ops[i].mvs[ops[i].n++] = i - 1;
if (i % Width < Width - 1)
ops[i].mvs[ops[i].n++] = i + 1;
if (i < Ntiles - Width)
ops[i].mvs[ops[i].n++] = i + Width;
}
}
void Tiles::inithashvec(void) {
hashvecinit = true;
Rand r(time(NULL));
for (int i = 0; i < Ntiles; i++) {
for (int j = 0; j < Ntiles; j++)
hashvec[i][j] = r.bits();
}
}
void Tiles::dumptiles(FILE *out, Tile ts[]) {
for (int i = 0; i < Ntiles; i++) {
if (i > 0 && i % Width == 0)
fprintf(out, "\n");
else if (i > 0)
fprintf(out, "\t");
fprintf(out, "%2d", ts[i]);
}
fprintf(out, "\n");
}<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/environment.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/task.h"
#include "base/synchronization/waitable_event.h"
#include "media/audio/audio_output_controller.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Exactly;
using ::testing::InvokeWithoutArgs;
using ::testing::NotNull;
using ::testing::Return;
static const int kSampleRate = AudioParameters::kAudioCDSampleRate;
static const int kBitsPerSample = 16;
static const int kChannels = 2;
static const int kSamplesPerPacket = kSampleRate / 10;
static const int kHardwareBufferSize = kSamplesPerPacket * kChannels *
kBitsPerSample / 8;
static const int kBufferCapacity = 3 * kHardwareBufferSize;
namespace media {
class MockAudioOutputControllerEventHandler
: public AudioOutputController::EventHandler {
public:
MockAudioOutputControllerEventHandler() {}
MOCK_METHOD1(OnCreated, void(AudioOutputController* controller));
MOCK_METHOD1(OnPlaying, void(AudioOutputController* controller));
MOCK_METHOD1(OnPaused, void(AudioOutputController* controller));
MOCK_METHOD2(OnError, void(AudioOutputController* controller,
int error_code));
MOCK_METHOD2(OnMoreData, void(AudioOutputController* controller,
AudioBuffersState buffers_state));
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioOutputControllerEventHandler);
};
class MockAudioOutputControllerSyncReader
: public AudioOutputController::SyncReader {
public:
MockAudioOutputControllerSyncReader() {}
MOCK_METHOD1(UpdatePendingBytes, void(uint32 bytes));
MOCK_METHOD2(Read, uint32(void* data, uint32 size));
MOCK_METHOD0(Close, void());
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioOutputControllerSyncReader);
};
static bool HasAudioOutputDevices() {
AudioManager* audio_man = AudioManager::GetAudioManager();
CHECK(audio_man);
return audio_man->HasAudioOutputDevices();
}
static bool IsRunningHeadless() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar("CHROME_HEADLESS"))
return true;
return false;
}
ACTION_P(SignalEvent, event) {
event->Signal();
}
// Helper functions used to close audio controller.
static void SignalClosedEvent(base::WaitableEvent* event) {
event->Signal();
}
// Closes AudioOutputController synchronously.
static void CloseAudioController(AudioOutputController* controller) {
base::WaitableEvent closed_event(true, false);
controller->Close(NewRunnableFunction(&SignalClosedEvent, &closed_event));
closed_event.Wait();
}
// This test fails in Release on Windows.
// http://crbug.com/72718
#if defined(OS_WIN) && defined(NDEBUG)
#define CreateAndClose DISABLED_CreateAndClose
#endif
TEST(AudioOutputControllerTest, CreateAndClose) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.Times(1);
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Close the controller immediately.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, PlayAndClose) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.WillOnce(SignalEvent(&event));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1));
// If OnMoreData is called enough then signal the event.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(10))
.WillRepeatedly(SignalEvent(&event));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// Now stop the controller.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, PlayPauseClose) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
base::WaitableEvent pause_event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&event, &base::WaitableEvent::Signal));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1));
// If OnMoreData is called enough then signal the event.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(10))
.WillRepeatedly(SignalEvent(&event));
// And then OnPaused() will be called.
EXPECT_CALL(event_handler, OnPaused(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&pause_event, &base::WaitableEvent::Signal));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// And then wait for pause to complete.
ASSERT_FALSE(pause_event.IsSignaled());
controller->Pause();
pause_event.Wait();
// Now stop the controller.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, PlayPausePlay) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
base::WaitableEvent pause_event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&event, &base::WaitableEvent::Signal));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1))
.RetiresOnSaturation();
// If OnMoreData() is called enough then signal the event.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(1))
.WillRepeatedly(SignalEvent(&event));
// And then OnPaused() will be called.
EXPECT_CALL(event_handler, OnPaused(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&pause_event, &base::WaitableEvent::Signal));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1))
.RetiresOnSaturation();
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// And then wait for pause to complete.
ASSERT_FALSE(pause_event.IsSignaled());
controller->Pause();
pause_event.Wait();
// Then we play again.
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// Now stop the controller.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, HardwareBufferTooLarge) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
// Create an audio device with a very large hardware buffer size.
MockAudioOutputControllerEventHandler event_handler;
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample,
kSamplesPerPacket * 1000);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params,
kBufferCapacity);
// Use assert because we don't stop the device and assume we can't
// create one.
ASSERT_FALSE(controller);
}
TEST(AudioOutputControllerTest, CloseTwice) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.WillOnce(SignalEvent(&event));
// One OnMoreData() is expected.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(1))
.WillRepeatedly(SignalEvent(&event));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
// Wait for OnMoreData() to be called.
event.Wait();
base::WaitableEvent closed_event_1(true, false);
controller->Close(NewRunnableFunction(&SignalClosedEvent, &closed_event_1));
base::WaitableEvent closed_event_2(true, false);
controller->Close(NewRunnableFunction(&SignalClosedEvent, &closed_event_2));
closed_event_1.Wait();
closed_event_2.Wait();
}
} // namespace media
<commit_msg>Revert 74590 - Disable AudioOutputControllerTest.CreateAndClose since it crashes on Windows in release.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/environment.h"
#include "base/basictypes.h"
#include "base/logging.h"
#include "base/task.h"
#include "base/synchronization/waitable_event.h"
#include "media/audio/audio_output_controller.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Exactly;
using ::testing::InvokeWithoutArgs;
using ::testing::NotNull;
using ::testing::Return;
static const int kSampleRate = AudioParameters::kAudioCDSampleRate;
static const int kBitsPerSample = 16;
static const int kChannels = 2;
static const int kSamplesPerPacket = kSampleRate / 10;
static const int kHardwareBufferSize = kSamplesPerPacket * kChannels *
kBitsPerSample / 8;
static const int kBufferCapacity = 3 * kHardwareBufferSize;
namespace media {
class MockAudioOutputControllerEventHandler
: public AudioOutputController::EventHandler {
public:
MockAudioOutputControllerEventHandler() {}
MOCK_METHOD1(OnCreated, void(AudioOutputController* controller));
MOCK_METHOD1(OnPlaying, void(AudioOutputController* controller));
MOCK_METHOD1(OnPaused, void(AudioOutputController* controller));
MOCK_METHOD2(OnError, void(AudioOutputController* controller,
int error_code));
MOCK_METHOD2(OnMoreData, void(AudioOutputController* controller,
AudioBuffersState buffers_state));
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioOutputControllerEventHandler);
};
class MockAudioOutputControllerSyncReader
: public AudioOutputController::SyncReader {
public:
MockAudioOutputControllerSyncReader() {}
MOCK_METHOD1(UpdatePendingBytes, void(uint32 bytes));
MOCK_METHOD2(Read, uint32(void* data, uint32 size));
MOCK_METHOD0(Close, void());
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioOutputControllerSyncReader);
};
static bool HasAudioOutputDevices() {
AudioManager* audio_man = AudioManager::GetAudioManager();
CHECK(audio_man);
return audio_man->HasAudioOutputDevices();
}
static bool IsRunningHeadless() {
scoped_ptr<base::Environment> env(base::Environment::Create());
if (env->HasVar("CHROME_HEADLESS"))
return true;
return false;
}
ACTION_P(SignalEvent, event) {
event->Signal();
}
// Helper functions used to close audio controller.
static void SignalClosedEvent(base::WaitableEvent* event) {
event->Signal();
}
// Closes AudioOutputController synchronously.
static void CloseAudioController(AudioOutputController* controller) {
base::WaitableEvent closed_event(true, false);
controller->Close(NewRunnableFunction(&SignalClosedEvent, &closed_event));
closed_event.Wait();
}
TEST(AudioOutputControllerTest, CreateAndClose) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.Times(1);
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Close the controller immediately.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, PlayAndClose) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.WillOnce(SignalEvent(&event));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1));
// If OnMoreData is called enough then signal the event.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(10))
.WillRepeatedly(SignalEvent(&event));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// Now stop the controller.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, PlayPauseClose) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
base::WaitableEvent pause_event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&event, &base::WaitableEvent::Signal));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1));
// If OnMoreData is called enough then signal the event.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(10))
.WillRepeatedly(SignalEvent(&event));
// And then OnPaused() will be called.
EXPECT_CALL(event_handler, OnPaused(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&pause_event, &base::WaitableEvent::Signal));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// And then wait for pause to complete.
ASSERT_FALSE(pause_event.IsSignaled());
controller->Pause();
pause_event.Wait();
// Now stop the controller.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, PlayPausePlay) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
base::WaitableEvent pause_event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&event, &base::WaitableEvent::Signal));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1))
.RetiresOnSaturation();
// If OnMoreData() is called enough then signal the event.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(1))
.WillRepeatedly(SignalEvent(&event));
// And then OnPaused() will be called.
EXPECT_CALL(event_handler, OnPaused(NotNull()))
.Times(Exactly(1))
.WillOnce(InvokeWithoutArgs(&pause_event, &base::WaitableEvent::Signal));
// OnPlaying() will be called only once.
EXPECT_CALL(event_handler, OnPlaying(NotNull()))
.Times(Exactly(1))
.RetiresOnSaturation();
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// And then wait for pause to complete.
ASSERT_FALSE(pause_event.IsSignaled());
controller->Pause();
pause_event.Wait();
// Then we play again.
controller->Play();
// Wait until the date is requested at least 10 times.
for (int i = 0; i < 10; i++) {
event.Wait();
uint8 buf[1];
controller->EnqueueData(buf, 0);
}
// Now stop the controller.
CloseAudioController(controller);
}
TEST(AudioOutputControllerTest, HardwareBufferTooLarge) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
// Create an audio device with a very large hardware buffer size.
MockAudioOutputControllerEventHandler event_handler;
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample,
kSamplesPerPacket * 1000);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params,
kBufferCapacity);
// Use assert because we don't stop the device and assume we can't
// create one.
ASSERT_FALSE(controller);
}
TEST(AudioOutputControllerTest, CloseTwice) {
if (!HasAudioOutputDevices() || IsRunningHeadless())
return;
MockAudioOutputControllerEventHandler event_handler;
base::WaitableEvent event(false, false);
// If OnCreated is called then signal the event.
EXPECT_CALL(event_handler, OnCreated(NotNull()))
.WillOnce(SignalEvent(&event));
// One OnMoreData() is expected.
EXPECT_CALL(event_handler, OnMoreData(NotNull(), _))
.Times(AtLeast(1))
.WillRepeatedly(SignalEvent(&event));
AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kChannels,
kSampleRate, kBitsPerSample, kSamplesPerPacket);
scoped_refptr<AudioOutputController> controller =
AudioOutputController::Create(&event_handler, params, kBufferCapacity);
ASSERT_TRUE(controller.get());
// Wait for OnCreated() to be called.
event.Wait();
// Wait for OnMoreData() to be called.
event.Wait();
base::WaitableEvent closed_event_1(true, false);
controller->Close(NewRunnableFunction(&SignalClosedEvent, &closed_event_1));
base::WaitableEvent closed_event_2(true, false);
controller->Close(NewRunnableFunction(&SignalClosedEvent, &closed_event_2));
closed_event_1.Wait();
closed_event_2.Wait();
}
} // namespace media
<|endoftext|>
|
<commit_before>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
// @file Name: respawn_dialog.hpp
// @file Author: His_Shadow, AgentRev
#include "respawn_defines.hpp"
class RespawnSelectionDialog
{
idd = respawn_dialog;
movingEnable = false;
enableSimulation = true;
onLoad = "uiNamespace setVariable ['RespawnSelectionDialog', _this select 0]";
class ControlsBackground
{
class RspnMainBG: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(1,1,1,0.09)";
#define RspnMainBG_W ((0.809 * X_SCALE) min safezoneW)
#define RspnMainBG_H ((0.620 * Y_SCALE) min safezoneH)
#define RspnMainBG_X (CENTER(1, RspnMainBG_W) max safezoneX) // centered to screen
#define RspnMainBG_Y (CENTER(1, RspnMainBG_H) max safezoneY) // centered to screen
x = RspnMainBG_X;
y = RspnMainBG_Y;
w = RspnMainBG_W;
h = RspnMainBG_H;
};
class RspnTopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)";
// relative to RspnMainBG
#define RspnTopBar_W RspnMainBG_W // match RspnMainBG width
#define RspnTopBar_H (0.072 * Y_SCALE)
#define RspnTopBar_X RspnMainBG_X // aligned to RspnMainBG
#define RspnTopBar_Y RspnMainBG_Y // aligned to RspnMainBG
x = RspnTopBar_X;
y = RspnTopBar_Y;
w = RspnTopBar_W;
h = RspnTopBar_H;
};
class RspnMenuTitle: w_RscTextCenter
{
idc = -1;
text = "Respawn Menu";
sizeEx = 0.06 * TEXT_SCALE;
// relative to RspnTopBar
#define RspnMenuTitle_W (0.267 * X_SCALE)
#define RspnMenuTitle_H (0.035 * Y_SCALE)
#define RspnMenuTitle_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnMenuTitle_W)) // centered in RspnTopBar
#define RspnMenuTitle_Y (RspnTopBar_Y + CENTER(RspnTopBar_H, RspnMenuTitle_H)) // centered in RspnTopBar
x = RspnMenuTitle_X;
y = RspnMenuTitle_Y;
w = RspnMenuTitle_W;
h = RspnMenuTitle_H;
};
class RspnStructText: w_RscStructuredText
{
idc = respawn_Content_Text;
text = "";
size = 0.04 * TEXT_SCALE;
// relative to RspnTopBar
#define RspnStructText_W (0.533 * X_SCALE)
#define RspnStructText_H (0.060 * Y_SCALE)
#define RspnStructText_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnStructText_W)) // centered to RspnTopBar
#define RspnStructText_Y (RspnTopBar_Y + RspnTopBar_H + (0.008 * Y_SCALE)) // under RspnTopBar
x = RspnStructText_X;
y = RspnStructText_Y;
w = RspnStructText_W;
h = RspnStructText_H;
};
#define RspnButton_H (0.033 * Y_SCALE)
// relative to RspnTopBar
#define RspnRandomButton_Y (RspnTopBar_Y + RspnTopBar_H + (0.072 * Y_SCALE)) // under RspnTopBar
#define RspnLine_W (RspnMainBG_W - (0.1 * X_SCALE))
#define RspnLine_H (0.002 * SZ_SCALE_ABS) // (0.002 * Y_SCALE)
#define RspnLine_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnLine_W)) // centered to RspnTopBar
class RspnTopLine: w_RscPicture
{
idc = -1;
text = "#(argb,8,8,3)color(1,1,1,1)";
#define RspnTopLine_Y (RspnRandomButton_Y + RspnButton_H + (0.015 * Y_SCALE)) // under RspnRandomButton
x = RspnLine_X;
y = RspnTopLine_Y;
w = RspnLine_W;
h = RspnLine_H;
};
// above bottom of RspnMainBG
#define RspnLobbyButton_Y ((RspnMainBG_Y + RspnMainBG_H) - (RspnButton_H + (0.040 * Y_SCALE)))
class RspnBottomLine: w_RscPicture
{
idc = -1;
text = "#(argb,8,8,3)color(1,1,1,1)";
#define RspnBottomLine_Y (RspnLobbyButton_Y - (RspnLine_H + (0.015 * Y_SCALE))) // above RspnLobbyButton
x = RspnLine_X;
y = RspnBottomLine_Y;
w = RspnLine_W;
h = RspnLine_H;
};
class RspnMissionUptime: w_RscStructuredTextLeft
{
idc = respawn_MissionUptime_Text;
text = "Mission Uptime: 00:00:00";
size = 0.04 * TEXT_SCALE;
#define RspnMissionUptime_W (0.23 * X_SCALE)
#define RspnMissionUptime_H (0.025 * Y_SCALE)
#define RspnMissionUptime_X ((RspnLine_X + RspnLine_W) - RspnMissionUptime_W) // aligned right to RspnBottomLine
#define RspnMissionUptime_Y (RspnLobbyButton_Y + CENTER(RspnButton_H, RspnMissionUptime_H)) // centered to RspnLobbyButton
x = RspnMissionUptime_X;
y = RspnMissionUptime_Y;
w = RspnMissionUptime_W;
h = RspnMissionUptime_H;
};
};
class RspnButton: w_RscButton
{
sizeEx = 0.04 * TEXT_SCALE;
#define RspnButton_W (0.139 * X_SCALE)
w = RspnButton_W;
h = RspnButton_H;
};
class Controls
{
class RspnRandomButton: RspnButton
{
idc = respawn_Random_Button;
onButtonClick = ""; // Action is now set dynamically in loadRespawnDialog.sqf using buttonSetAction
text = "Random";
// relative to RspnTopBar
#define RspnRandomButton_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnButton_W)) // centered under RspnTopBar
x = RspnRandomButton_X;
y = RspnRandomButton_Y;
};
class RspnPreloadChk: w_RscCheckBox
{
idc = respawn_Preload_Checkbox;
// left of RspnRandomButton
#define RspnPreloadChk_W (0.026 * X_SCALE)
#define RspnPreloadChk_H (0.026 * Y_SCALE)
#define RspnPreloadChk_X RspnLine_X
#define RspnPreloadChk_Y ((RspnRandomButton_Y + RspnButton_H) - RspnPreloadChk_H)
x = RspnPreloadChk_X;
y = RspnPreloadChk_Y;
w = RspnPreloadChk_W;
h = RspnPreloadChk_H;
};
class RspnPreloadChkText: w_RscText
{
idc = -1;
text = "Preload";
sizeEx = 0.036 * TEXT_SCALE;
// right of RspnPreloadChk
#define RspnPreloadChkText_W (0.08 * X_SCALE)
#define RspnPreloadChkText_H (0.03 * Y_SCALE)
#define RspnPreloadChkText_X (RspnPreloadChk_X + RspnPreloadChk_W + (0.001 * X_SCALE))
#define RspnPreloadChkText_Y ((RspnPreloadChk_Y + CENTER(RspnPreloadChk_H, RspnPreloadChkText_H)) - (0.0015 * Y_SCALE))
x = RspnPreloadChkText_X;
y = RspnPreloadChkText_Y;
w = RspnPreloadChkText_W;
h = RspnPreloadChkText_H;
};
#define RspnLocType_X RspnLine_X
#define RspnLocType_Y (RspnTopLine_Y + RspnLine_H + (0.015 * Y_SCALE))
#define RspnLocType_W (0.225 * X_SCALE)
#define RspnLocType_H (0.0225 * Y_SCALE)
class RspnLocType: w_RscXListBox
{
idc = respawn_Locations_Type;
x = RspnLocType_X;
y = RspnLocType_Y;
w = RspnLocType_W;
h = RspnLocType_H;
};
#define RspnSpawnButton_W RspnLocType_W
#define RspnSpawnButton_H (0.04 * Y_SCALE)
#define RspnSpawnButton_X RspnLocType_X
#define RspnSpawnButton_Y ((RspnBottomLine_Y - (0.015 * Y_SCALE)) - RspnSpawnButton_H)
class RspnSpawnButton: RspnButton
{
idc = respawn_Spawn_Button;
text = "Spawn"; // text alternates between "Loading..." and "Spawn" in loadRespawnDialog.sqf
x = RspnSpawnButton_X;
y = RspnSpawnButton_Y;
w = RspnSpawnButton_W;
h = RspnSpawnButton_H;
};
#define RspnLocList_X RspnLocType_X
#define RspnLocList_Y (RspnLocType_Y + RspnLocType_H + (0.0075 * Y_SCALE))
#define RspnLocList_W RspnLocType_W
#define RspnLocList_H ((RspnSpawnButton_Y - RspnLocList_Y) - (0.0075 * Y_SCALE))
class RspnLocList: w_RscList
{
idc = respawn_Locations_List;
rowHeight = 0.0225 * Y_SCALE;
x = RspnLocList_X;
y = RspnLocList_Y;
w = RspnLocList_W;
h = RspnLocList_H;
};
#define RspnLocText_X (RspnLocList_X + RspnLocList_W + (0.0075 * X_SCALE))
#define RspnLocText_W ((RspnLine_X + RspnLine_W) - RspnLocText_X)
#define RspnLocText_H RspnSpawnButton_H
#define RspnLocText_Y ((RspnBottomLine_Y - (0.015 * Y_SCALE)) - RspnLocText_H)
class RspnLocText: w_RscStructuredTextLeft
{
idc = respawn_Locations_Text;
size = 0.034 * TEXT_SCALE;
colorBackground[] = {0, 0, 0, 0.3};
shadow = 0;
x = RspnLocText_X;
y = RspnLocText_Y;
w = RspnLocText_W;
h = RspnLocText_H;
};
#define RspnLocMap_X RspnLocText_X
#define RspnLocMap_Y RspnLocType_Y
#define RspnLocMap_W RspnLocText_W
#define RspnLocMap_H ((RspnLocText_Y - (0.0075 * Y_SCALE)) - RspnLocMap_Y)
class RspnLocMap: w_RscMapControl
{
idc = respawn_Locations_Map;
scaleMax = 3;
x = RspnLocMap_X;
y = RspnLocMap_Y;
w = RspnLocMap_W;
h = RspnLocMap_H;
};
#define RspnLobbyButton_X RspnLine_X
class RspnLobbyButton: RspnButton
{
idc = -1;
onButtonClick = "endMission 'LOSER'";
text = "Lobby";
x = RspnLobbyButton_X;
y = RspnLobbyButton_Y;
};
#define RspnGroupButton_X (RspnLobbyButton_X + RspnButton_W + (0.015 * X_SCALE))
#define RspnGroupButton_W (0.175 * X_SCALE)
class RspnGroupButton: RspnButton
{
idc = -1;
text = "Group Management";
onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
x = RspnGroupButton_X;
y = RspnLobbyButton_Y;
w = RspnGroupButton_W;
};
};
};
<commit_msg>Update respawn_dialog.hpp<commit_after>// ******************************************************************************************
// * This project is licensed under the GNU Affero GPL v3. Copyright © 2014 A3Wasteland.com *
// ******************************************************************************************
// @file Name: respawn_dialog.hpp
// @file Author: His_Shadow, AgentRev
#include "respawn_defines.hpp"
class RespawnSelectionDialog
{
idd = respawn_dialog;
movingEnable = false;
enableSimulation = true;
onLoad = "uiNamespace setVariable ['RespawnSelectionDialog', _this select 0]";
class ControlsBackground
{
class RspnMainBG: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(1,1,1,0.09)";
#define RspnMainBG_W ((0.809 * X_SCALE) min safezoneW)
#define RspnMainBG_H ((0.620 * Y_SCALE) min safezoneH)
#define RspnMainBG_X (CENTER(1, RspnMainBG_W) max safezoneX) // centered to screen
#define RspnMainBG_Y (CENTER(1, RspnMainBG_H) max safezoneY) // centered to screen
x = RspnMainBG_X;
y = RspnMainBG_Y;
w = RspnMainBG_W;
h = RspnMainBG_H;
};
class RspnTopBar: w_RscPicture
{
idc = -1;
colorText[] = {1, 1, 1, 1};
colorBackground[] = {0,0,0,0};
text = "#(argb,8,8,3)color(0.25,0.51,0.96,0.8)";
// relative to RspnMainBG
#define RspnTopBar_W RspnMainBG_W // match RspnMainBG width
#define RspnTopBar_H (0.072 * Y_SCALE)
#define RspnTopBar_X RspnMainBG_X // aligned to RspnMainBG
#define RspnTopBar_Y RspnMainBG_Y // aligned to RspnMainBG
x = RspnTopBar_X;
y = RspnTopBar_Y;
w = RspnTopBar_W;
h = RspnTopBar_H;
};
class RspnMenuTitle: w_RscTextCenter
{
idc = -1;
text = "Menú de reaparición";
sizeEx = 0.06 * TEXT_SCALE;
// relative to RspnTopBar
#define RspnMenuTitle_W (0.267 * X_SCALE)
#define RspnMenuTitle_H (0.035 * Y_SCALE)
#define RspnMenuTitle_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnMenuTitle_W)) // centered in RspnTopBar
#define RspnMenuTitle_Y (RspnTopBar_Y + CENTER(RspnTopBar_H, RspnMenuTitle_H)) // centered in RspnTopBar
x = RspnMenuTitle_X;
y = RspnMenuTitle_Y;
w = RspnMenuTitle_W;
h = RspnMenuTitle_H;
};
class RspnStructText: w_RscStructuredText
{
idc = respawn_Content_Text;
text = "";
size = 0.04 * TEXT_SCALE;
// relative to RspnTopBar
#define RspnStructText_W (0.533 * X_SCALE)
#define RspnStructText_H (0.060 * Y_SCALE)
#define RspnStructText_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnStructText_W)) // centered to RspnTopBar
#define RspnStructText_Y (RspnTopBar_Y + RspnTopBar_H + (0.008 * Y_SCALE)) // under RspnTopBar
x = RspnStructText_X;
y = RspnStructText_Y;
w = RspnStructText_W;
h = RspnStructText_H;
};
#define RspnButton_H (0.033 * Y_SCALE)
// relative to RspnTopBar
#define RspnRandomButton_Y (RspnTopBar_Y + RspnTopBar_H + (0.072 * Y_SCALE)) // under RspnTopBar
#define RspnLine_W (RspnMainBG_W - (0.1 * X_SCALE))
#define RspnLine_H (0.002 * SZ_SCALE_ABS) // (0.002 * Y_SCALE)
#define RspnLine_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnLine_W)) // centered to RspnTopBar
class RspnTopLine: w_RscPicture
{
idc = -1;
text = "#(argb,8,8,3)color(1,1,1,1)";
#define RspnTopLine_Y (RspnRandomButton_Y + RspnButton_H + (0.015 * Y_SCALE)) // under RspnRandomButton
x = RspnLine_X;
y = RspnTopLine_Y;
w = RspnLine_W;
h = RspnLine_H;
};
// above bottom of RspnMainBG
#define RspnLobbyButton_Y ((RspnMainBG_Y + RspnMainBG_H) - (RspnButton_H + (0.040 * Y_SCALE)))
class RspnBottomLine: w_RscPicture
{
idc = -1;
text = "#(argb,8,8,3)color(1,1,1,1)";
#define RspnBottomLine_Y (RspnLobbyButton_Y - (RspnLine_H + (0.015 * Y_SCALE))) // above RspnLobbyButton
x = RspnLine_X;
y = RspnBottomLine_Y;
w = RspnLine_W;
h = RspnLine_H;
};
class RspnMissionUptime: w_RscStructuredTextLeft
{
idc = respawn_MissionUptime_Text;
text = "Misión activa durante: 00:00:00";
size = 0.04 * TEXT_SCALE;
#define RspnMissionUptime_W (0.23 * X_SCALE)
#define RspnMissionUptime_H (0.025 * Y_SCALE)
#define RspnMissionUptime_X ((RspnLine_X + RspnLine_W) - RspnMissionUptime_W) // aligned right to RspnBottomLine
#define RspnMissionUptime_Y (RspnLobbyButton_Y + CENTER(RspnButton_H, RspnMissionUptime_H)) // centered to RspnLobbyButton
x = RspnMissionUptime_X;
y = RspnMissionUptime_Y;
w = RspnMissionUptime_W;
h = RspnMissionUptime_H;
};
};
class RspnButton: w_RscButton
{
sizeEx = 0.04 * TEXT_SCALE;
#define RspnButton_W (0.139 * X_SCALE)
w = RspnButton_W;
h = RspnButton_H;
};
class Controls
{
class RspnRandomButton: RspnButton
{
idc = respawn_Random_Button;
onButtonClick = ""; // Action is now set dynamically in loadRespawnDialog.sqf using buttonSetAction
text = "Aleatorio";
// relative to RspnTopBar
#define RspnRandomButton_X (RspnTopBar_X + CENTER(RspnTopBar_W, RspnButton_W)) // centered under RspnTopBar
x = RspnRandomButton_X;
y = RspnRandomButton_Y;
};
class RspnPreloadChk: w_RscCheckBox
{
idc = respawn_Preload_Checkbox;
// left of RspnRandomButton
#define RspnPreloadChk_W (0.026 * X_SCALE)
#define RspnPreloadChk_H (0.026 * Y_SCALE)
#define RspnPreloadChk_X RspnLine_X
#define RspnPreloadChk_Y ((RspnRandomButton_Y + RspnButton_H) - RspnPreloadChk_H)
x = RspnPreloadChk_X;
y = RspnPreloadChk_Y;
w = RspnPreloadChk_W;
h = RspnPreloadChk_H;
};
class RspnPreloadChkText: w_RscText
{
idc = -1;
text = "Precargados";
sizeEx = 0.036 * TEXT_SCALE;
// right of RspnPreloadChk
#define RspnPreloadChkText_W (0.08 * X_SCALE)
#define RspnPreloadChkText_H (0.03 * Y_SCALE)
#define RspnPreloadChkText_X (RspnPreloadChk_X + RspnPreloadChk_W + (0.001 * X_SCALE))
#define RspnPreloadChkText_Y ((RspnPreloadChk_Y + CENTER(RspnPreloadChk_H, RspnPreloadChkText_H)) - (0.0015 * Y_SCALE))
x = RspnPreloadChkText_X;
y = RspnPreloadChkText_Y;
w = RspnPreloadChkText_W;
h = RspnPreloadChkText_H;
};
#define RspnLocType_X RspnLine_X
#define RspnLocType_Y (RspnTopLine_Y + RspnLine_H + (0.015 * Y_SCALE))
#define RspnLocType_W (0.225 * X_SCALE)
#define RspnLocType_H (0.0225 * Y_SCALE)
class RspnLocType: w_RscXListBox
{
idc = respawn_Locations_Type;
x = RspnLocType_X;
y = RspnLocType_Y;
w = RspnLocType_W;
h = RspnLocType_H;
};
#define RspnSpawnButton_W RspnLocType_W
#define RspnSpawnButton_H (0.04 * Y_SCALE)
#define RspnSpawnButton_X RspnLocType_X
#define RspnSpawnButton_Y ((RspnBottomLine_Y - (0.015 * Y_SCALE)) - RspnSpawnButton_H)
class RspnSpawnButton: RspnButton
{
idc = respawn_Spawn_Button;
text = "Reaparecer"; // text alternates between "Loading..." and "Spawn" in loadRespawnDialog.sqf
x = RspnSpawnButton_X;
y = RspnSpawnButton_Y;
w = RspnSpawnButton_W;
h = RspnSpawnButton_H;
};
#define RspnLocList_X RspnLocType_X
#define RspnLocList_Y (RspnLocType_Y + RspnLocType_H + (0.0075 * Y_SCALE))
#define RspnLocList_W RspnLocType_W
#define RspnLocList_H ((RspnSpawnButton_Y - RspnLocList_Y) - (0.0075 * Y_SCALE))
class RspnLocList: w_RscList
{
idc = respawn_Locations_List;
rowHeight = 0.0225 * Y_SCALE;
x = RspnLocList_X;
y = RspnLocList_Y;
w = RspnLocList_W;
h = RspnLocList_H;
};
#define RspnLocText_X (RspnLocList_X + RspnLocList_W + (0.0075 * X_SCALE))
#define RspnLocText_W ((RspnLine_X + RspnLine_W) - RspnLocText_X)
#define RspnLocText_H RspnSpawnButton_H
#define RspnLocText_Y ((RspnBottomLine_Y - (0.015 * Y_SCALE)) - RspnLocText_H)
class RspnLocText: w_RscStructuredTextLeft
{
idc = respawn_Locations_Text;
size = 0.034 * TEXT_SCALE;
colorBackground[] = {0, 0, 0, 0.3};
shadow = 0;
x = RspnLocText_X;
y = RspnLocText_Y;
w = RspnLocText_W;
h = RspnLocText_H;
};
#define RspnLocMap_X RspnLocText_X
#define RspnLocMap_Y RspnLocType_Y
#define RspnLocMap_W RspnLocText_W
#define RspnLocMap_H ((RspnLocText_Y - (0.0075 * Y_SCALE)) - RspnLocMap_Y)
class RspnLocMap: w_RscMapControl
{
idc = respawn_Locations_Map;
scaleMax = 3;
x = RspnLocMap_X;
y = RspnLocMap_Y;
w = RspnLocMap_W;
h = RspnLocMap_H;
};
#define RspnLobbyButton_X RspnLine_X
class RspnLobbyButton: RspnButton
{
idc = -1;
onButtonClick = "endMission 'LOSER'";
text = "Sala de entrada";
x = RspnLobbyButton_X;
y = RspnLobbyButton_Y;
};
#define RspnGroupButton_X (RspnLobbyButton_X + RspnButton_W + (0.015 * X_SCALE))
#define RspnGroupButton_W (0.175 * X_SCALE)
class RspnGroupButton: RspnButton
{
idc = -1;
text = "Gestión de grupo";
onButtonClick = "[] execVM 'client\systems\groups\loadGroupManagement.sqf'";
x = RspnGroupButton_X;
y = RspnLobbyButton_Y;
w = RspnGroupButton_W;
};
};
};
<|endoftext|>
|
<commit_before>// Author: Enrico Guiraud, Danilo Piparo CERN 09/2018
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RCUSTOMCOLUMN
#define ROOT_RCUSTOMCOLUMN
#include "ROOT/RDF/RCustomColumnBase.hxx"
#include "ROOT/RIntegerSequence.hxx"
#include "ROOT/RStringView.hxx"
#include "ROOT/TypeTraits.hxx"
#include "RtypesCore.h"
#include <deque>
#include <type_traits>
#include <vector>
class TTreeReader;
namespace ROOT {
namespace Detail {
namespace RDF {
using namespace ROOT::TypeTraits;
// clang-format off
namespace CustomColExtraArgs {
struct None{};
struct Slot{};
struct SlotAndEntry{};
}
// clang-format on
template <typename F, typename ExtraArgsTag = CustomColExtraArgs::None>
class RCustomColumn final : public RCustomColumnBase {
// shortcuts
using NoneTag = CustomColExtraArgs::None;
using SlotTag = CustomColExtraArgs::Slot;
using SlotAndEntryTag = CustomColExtraArgs::SlotAndEntry;
// other types
using FunParamTypes_t = typename CallableTraits<F>::arg_types;
using ColumnTypesTmp_t =
RDFInternal::RemoveFirstParameterIf_t<std::is_same<ExtraArgsTag, SlotTag>::value, FunParamTypes_t>;
using ColumnTypes_t =
RDFInternal::RemoveFirstTwoParametersIf_t<std::is_same<ExtraArgsTag, SlotAndEntryTag>::value, ColumnTypesTmp_t>;
using TypeInd_t = std::make_index_sequence<ColumnTypes_t::list_size>;
using ret_type = typename CallableTraits<F>::ret_type;
// Avoid instantiating vector<bool> as `operator[]` returns temporaries in that case. Use std::deque instead.
using ValuesPerSlot_t =
typename std::conditional<std::is_same<ret_type, bool>::value, std::deque<ret_type>, std::vector<ret_type>>::type;
F fExpression;
const ColumnNames_t fBranches;
ValuesPerSlot_t fLastResults;
std::vector<RDFInternal::RDFValueTuple_t<ColumnTypes_t>> fValues;
public:
RCustomColumn(RLoopManager *lm, std::string_view name, F &&expression, const ColumnNames_t &bl, unsigned int nSlots,
const RDFInternal::RBookedCustomColumns &customColumns, bool isDSColumn = false)
: RCustomColumnBase(lm, name, nSlots, isDSColumn, customColumns), fExpression(std::forward<F>(expression)),
fBranches(bl), fLastResults(fNSlots), fValues(fNSlots)
{
}
RCustomColumn(const RCustomColumn &) = delete;
RCustomColumn &operator=(const RCustomColumn &) = delete;
void InitSlot(TTreeReader *r, unsigned int slot) final
{
// TODO: Each node calls this method for each column it uses. Multiple nodes may share the same columns, and this
// would lead to this method being called multiple times.
RDFInternal::InitRDFValues(slot, fValues[slot], r, fBranches, fCustomColumns, TypeInd_t());
}
void *GetValuePtr(unsigned int slot) final { return static_cast<void *>(&fLastResults[slot]); }
void Update(unsigned int slot, Long64_t entry) final
{
if (entry != fLastCheckedEntry[slot]) {
// evaluate this filter, cache the result
UpdateHelper(slot, entry, TypeInd_t(), ColumnTypes_t(), ExtraArgsTag{});
fLastCheckedEntry[slot] = entry;
}
}
const std::type_info &GetTypeId() const
{
return fIsDataSourceColumn ? typeid(typename std::remove_pointer<ret_type>::type) : typeid(ret_type);
}
template <std::size_t... S, typename... BranchTypes>
void UpdateHelper(unsigned int slot, Long64_t entry, std::index_sequence<S...>, TypeList<BranchTypes...>, NoneTag)
{
fLastResults[slot] = fExpression(std::get<S>(fValues[slot]).Get(entry)...);
// silence "unused parameter" warnings in gcc
(void)slot;
(void)entry;
}
template <std::size_t... S, typename... BranchTypes>
void UpdateHelper(unsigned int slot, Long64_t entry, std::index_sequence<S...>, TypeList<BranchTypes...>, SlotTag)
{
fLastResults[slot] = fExpression(slot, std::get<S>(fValues[slot]).Get(entry)...);
// silence "unused parameter" warnings in gcc
(void)slot;
(void)entry;
}
template <std::size_t... S, typename... BranchTypes>
void
UpdateHelper(unsigned int slot, Long64_t entry, std::index_sequence<S...>, TypeList<BranchTypes...>, SlotAndEntryTag)
{
fLastResults[slot] = fExpression(slot, entry, std::get<S>(fValues[slot]).Get(entry)...);
// silence "unused parameter" warnings in gcc
(void)slot;
(void)entry;
}
void ClearValueReaders(unsigned int slot) final
{
// TODO: Each node calls this method for each column it uses. Multiple nodes may share the same columns, and this
// would lead to this method being called multiple times.
RDFInternal::ResetRDFValueTuple(fValues[slot], TypeInd_t());
}
};
} // ns RDF
} // ns Detail
} // ns ROOT
#endif // ROOT_RCUSTOMCOLUMN
<commit_msg>Fixing runtime module compilation for RCustomColumm.hxx<commit_after>// Author: Enrico Guiraud, Danilo Piparo CERN 09/2018
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RCUSTOMCOLUMN
#define ROOT_RCUSTOMCOLUMN
#include "ROOT/RDF/NodesUtils.hxx"
#include "ROOT/RDF/RColumnValue.hxx"
#include "ROOT/RDF/RCustomColumnBase.hxx"
#include "ROOT/RDF/Utils.hxx"
#include "ROOT/RIntegerSequence.hxx"
#include "ROOT/RStringView.hxx"
#include "ROOT/TypeTraits.hxx"
#include "RtypesCore.h"
#include <deque>
#include <type_traits>
#include <vector>
class TTreeReader;
namespace ROOT {
namespace Detail {
namespace RDF {
using namespace ROOT::TypeTraits;
// clang-format off
namespace CustomColExtraArgs {
struct None{};
struct Slot{};
struct SlotAndEntry{};
}
// clang-format on
template <typename F, typename ExtraArgsTag = CustomColExtraArgs::None>
class RCustomColumn final : public RCustomColumnBase {
// shortcuts
using NoneTag = CustomColExtraArgs::None;
using SlotTag = CustomColExtraArgs::Slot;
using SlotAndEntryTag = CustomColExtraArgs::SlotAndEntry;
// other types
using FunParamTypes_t = typename CallableTraits<F>::arg_types;
using ColumnTypesTmp_t =
RDFInternal::RemoveFirstParameterIf_t<std::is_same<ExtraArgsTag, SlotTag>::value, FunParamTypes_t>;
using ColumnTypes_t =
RDFInternal::RemoveFirstTwoParametersIf_t<std::is_same<ExtraArgsTag, SlotAndEntryTag>::value, ColumnTypesTmp_t>;
using TypeInd_t = std::make_index_sequence<ColumnTypes_t::list_size>;
using ret_type = typename CallableTraits<F>::ret_type;
// Avoid instantiating vector<bool> as `operator[]` returns temporaries in that case. Use std::deque instead.
using ValuesPerSlot_t =
typename std::conditional<std::is_same<ret_type, bool>::value, std::deque<ret_type>, std::vector<ret_type>>::type;
F fExpression;
const ColumnNames_t fBranches;
ValuesPerSlot_t fLastResults;
std::vector<RDFInternal::RDFValueTuple_t<ColumnTypes_t>> fValues;
public:
RCustomColumn(RLoopManager *lm, std::string_view name, F &&expression, const ColumnNames_t &bl, unsigned int nSlots,
const RDFInternal::RBookedCustomColumns &customColumns, bool isDSColumn = false)
: RCustomColumnBase(lm, name, nSlots, isDSColumn, customColumns), fExpression(std::forward<F>(expression)),
fBranches(bl), fLastResults(fNSlots), fValues(fNSlots)
{
}
RCustomColumn(const RCustomColumn &) = delete;
RCustomColumn &operator=(const RCustomColumn &) = delete;
void InitSlot(TTreeReader *r, unsigned int slot) final
{
// TODO: Each node calls this method for each column it uses. Multiple nodes may share the same columns, and this
// would lead to this method being called multiple times.
RDFInternal::InitRDFValues(slot, fValues[slot], r, fBranches, fCustomColumns, TypeInd_t());
}
void *GetValuePtr(unsigned int slot) final { return static_cast<void *>(&fLastResults[slot]); }
void Update(unsigned int slot, Long64_t entry) final
{
if (entry != fLastCheckedEntry[slot]) {
// evaluate this filter, cache the result
UpdateHelper(slot, entry, TypeInd_t(), ColumnTypes_t(), ExtraArgsTag{});
fLastCheckedEntry[slot] = entry;
}
}
const std::type_info &GetTypeId() const
{
return fIsDataSourceColumn ? typeid(typename std::remove_pointer<ret_type>::type) : typeid(ret_type);
}
template <std::size_t... S, typename... BranchTypes>
void UpdateHelper(unsigned int slot, Long64_t entry, std::index_sequence<S...>, TypeList<BranchTypes...>, NoneTag)
{
fLastResults[slot] = fExpression(std::get<S>(fValues[slot]).Get(entry)...);
// silence "unused parameter" warnings in gcc
(void)slot;
(void)entry;
}
template <std::size_t... S, typename... BranchTypes>
void UpdateHelper(unsigned int slot, Long64_t entry, std::index_sequence<S...>, TypeList<BranchTypes...>, SlotTag)
{
fLastResults[slot] = fExpression(slot, std::get<S>(fValues[slot]).Get(entry)...);
// silence "unused parameter" warnings in gcc
(void)slot;
(void)entry;
}
template <std::size_t... S, typename... BranchTypes>
void
UpdateHelper(unsigned int slot, Long64_t entry, std::index_sequence<S...>, TypeList<BranchTypes...>, SlotAndEntryTag)
{
fLastResults[slot] = fExpression(slot, entry, std::get<S>(fValues[slot]).Get(entry)...);
// silence "unused parameter" warnings in gcc
(void)slot;
(void)entry;
}
void ClearValueReaders(unsigned int slot) final
{
// TODO: Each node calls this method for each column it uses. Multiple nodes may share the same columns, and this
// would lead to this method being called multiple times.
RDFInternal::ResetRDFValueTuple(fValues[slot], TypeInd_t());
}
};
} // ns RDF
} // ns Detail
} // ns ROOT
#endif // ROOT_RCUSTOMCOLUMN
<|endoftext|>
|
<commit_before><commit_msg>New test for `yli::load::load_CSV_file`.<commit_after><|endoftext|>
|
<commit_before>#ifndef __QUAD_TRIANGULATION_HPP_INCLUDED
#define __QUAD_TRIANGULATION_HPP_INCLUDED
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#include "face_normals.hpp"
#include "vertex_normals.hpp"
#include "vertices.hpp"
#include "triangulation_enums.hpp"
#include "triangulation_templates.hpp"
#include "indexing.hpp"
#include "code/ylikuutio/geometry/transformation.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <stdint.h> // uint32_t etc.
#include <vector> // std::vector
namespace geometry
{
template<class T1>
bool triangulate_quads(
T1* input_vertex_pointer,
TriangulateQuadsStruct triangulate_quads_struct,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals)
{
// Input vertices (`T1* input_vertex_pointer`)
// can be `float`, `int32_t` or `uint32_t`.
int32_t image_width = triangulate_quads_struct.image_width;
int32_t image_height = triangulate_quads_struct.image_height;
int32_t x_step = triangulate_quads_struct.x_step;
int32_t z_step = triangulate_quads_struct.z_step;
int32_t actual_image_width = (image_width - 1) / x_step + 1;
int32_t actual_image_height = (image_height - 1) / z_step + 1;
std::string triangulation_type = triangulate_quads_struct.triangulation_type;
double sphere_radius = triangulate_quads_struct.sphere_radius;
SphericalWorldStruct spherical_world_struct = triangulate_quads_struct.spherical_world_struct;
if (image_width < 2 || image_height < 2 || actual_image_width < 2 || actual_image_height < 2)
{
return false;
}
if (x_step < 1 || z_step < 1)
{
return false;
}
const char* char_triangulation_type = triangulation_type.c_str();
bool is_bilinear_interpolation_in_use = false;
bool is_southwest_northeast_edges_in_use = false;
bool is_southeast_northwest_edges_in_use = false;
bool is_triangulation_type_valid = false;
if (std::strcmp(char_triangulation_type, "bilinear_interpolation") == 0)
{
// *---*
// |\ /|
// | * |
// |/ \|
// *---*
is_bilinear_interpolation_in_use = true;
is_triangulation_type_valid = true;
}
else if ((std::strcmp(char_triangulation_type, "southwest_northeast_edges") == 0) || (std::strcmp(char_triangulation_type, "northeast_southwest_edges") == 0))
{
// *---*
// | /|
// | / |
// |/ |
// *---*
is_southwest_northeast_edges_in_use = true;
is_triangulation_type_valid = true;
}
else if ((std::strcmp(char_triangulation_type, "southeast_northwest_edges") == 0) || (std::strcmp(char_triangulation_type, "northwest_southeast_edges") == 0))
{
// *---*
// |\ |
// | \ |
// | \|
// *---*
is_southeast_northwest_edges_in_use = true;
is_triangulation_type_valid = true;
}
std::cout << "triangulation type in use: " << triangulation_type << "\n";
if (!is_triangulation_type_valid)
{
std::cerr << "invalid triangulation type!\n";
return false;
}
std::vector<GLuint> vertexIndices, uvIndices, normalIndices;
std::vector<glm::vec3> temp_vertices;
std::vector<glm::vec2> temp_UVs;
std::vector<glm::vec3> temp_normals;
// Processing stages:
// 1. Define the (GLfloat) vertices for vertices loaded from file, `push_back` to `temp_vertices` and `temp_UVs`.
// 2. Interpolate the (GLfloat) vertices between, using bilinear interpolation, `push_back` to `temp_vertices` and `temp_UVs`.
// 3a. Transform spherical coordinates loaded from file (and computed this far as being in horizontal plane) to a curved surface.
// 3b. For bilinear interpolation: Transform interpolated coordinates (and computed this far as being in horizontal plane) to a curved surface.
// 4. Compute the face normals, `push_back` to `face_normals`.
// 5. Compute the vertex normals for vertices loaded from file and for interpolated vertices (for `"bilinear_interpolation"`), `push_back` to `temp_normals`.
// 6. Loop through all vertices and `geometry::output_triangle_vertices`.
//
// stg. `"bilinear_interpolation"` `"southwest_northeast_edges"` `"southeast_northwest_edges"`
// 1. `define_vertices` `define_vertices` `define_vertices`
// 2. `interpolate_and_define_vertices_using_bilinear_interpolation` N/A N/A
// 3. `transform_coordinates_to_curved_surface` `transform_coordinates_to_curved_surface` `transform_coordinates_to_curved_surface`
// 4. `compute_face_normals` `compute_face_normals` `compute_face_normals`
// 5. `compute_vertex_normals` `compute_vertex_normals` `compute_vertex_normals`
// 6. `define_vertices_UVs_and_normals` `define_vertices_UVs_and_normals` `define_vertices_UVs_and_normals`
//
// stg. = stage
// 1. Define the vertices for vertices loaded from file, `push_back` to `temp_vertices`.
if (!geometry::define_vertices(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
triangulate_quads_struct.should_ylikuutio_use_real_texture_coordinates,
temp_vertices,
temp_UVs))
{
return false;
}
int32_t n_faces_for_each_vertex;
int32_t n_faces;
if (is_bilinear_interpolation_in_use)
{
n_faces_for_each_vertex = 4;
}
else if (is_southwest_northeast_edges_in_use || is_southeast_northwest_edges_in_use)
{
n_faces_for_each_vertex = 2;
}
std::cout << "image width: " << image_width << " pixels.\n";
std::cout << "image height: " << image_height << " pixels.\n";
std::cout << "actual image width: " << actual_image_width << " pixels.\n";
std::cout << "actual image height: " << actual_image_height << " pixels.\n";
std::cout << "number of faces: " << n_faces << ".\n";
n_faces = n_faces_for_each_vertex * (actual_image_width - 1) * (actual_image_height - 1);
uint32_t vertexIndex[3], uvIndex[3], normalIndex[3];
if (is_bilinear_interpolation_in_use)
{
// 2. Interpolate the vertices between, using bilinear interpolation, `push_back` to `temp_vertices`.
if (!geometry::interpolate_and_define_vertices_using_bilinear_interpolation(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
triangulate_quads_struct.should_ylikuutio_use_real_texture_coordinates,
temp_vertices,
temp_UVs))
{
return false;
}
}
if (!std::isnan(sphere_radius))
{
// 3a. Transform spherical coordinates loaded from file (and computed this far as being in horizontal plane) to a curved surface.
// 3b. For bilinear interpolation: Transform interpolated coordinates (and computed this far as being in horizontal plane) to a curved surface.
//
// Wikipedia:
// https://en.wikipedia.org/wiki/List_of_common_coordinate_transformations#From_spherical_coordinates
//
// x = rho * sin(theta) * cos(phi)
// y = rho * sin(theta) * sin(phi)
// z = rho * cos(theta)
TransformationStruct transformation_struct;
transformation_struct.image_width = image_width;
transformation_struct.image_height = image_height;
transformation_struct.sphere_radius = sphere_radius;
transformation_struct.is_bilinear_interpolation_in_use = is_bilinear_interpolation_in_use;
transformation_struct.spherical_world_struct = spherical_world_struct;
geometry::transform_coordinates_to_curved_surface(transformation_struct, temp_vertices);
}
else
{
std::cout << "no coordinate transformation is needed.\n";
}
// 4. Compute the face normals, `push_back` to `face_normals`.
// Triangle order: S - W - N - E.
//
// First triangle: center, southeast, southwest.
// Second triangle: center, southwest, northwest.
// Third triangle: center, northwest, northeast.
// Fourth triangle: center, northeast, southeast.
std::cout << "computing face normals.\n";
std::vector<glm::vec3> face_normal_vector_vec3;
if (!geometry::compute_face_normals(
temp_vertices,
face_normal_vector_vec3,
actual_image_width,
actual_image_height,
is_bilinear_interpolation_in_use,
is_southwest_northeast_edges_in_use,
is_southeast_northwest_edges_in_use))
{
return false;
}
// 5. Compute the vertex normals for vertices loaded from file, `push_back` to `temp_normals`.
geometry::compute_vertex_normals(
temp_normals,
face_normal_vector_vec3,
actual_image_width,
actual_image_height,
is_bilinear_interpolation_in_use,
is_southwest_northeast_edges_in_use,
is_southeast_northwest_edges_in_use);
// 6. Loop through all vertices and `geometry::output_triangle_vertices`.
geometry::define_vertices_UVs_and_normals(
triangulate_quads_struct,
temp_vertices,
temp_UVs,
temp_normals,
vertexIndex,
uvIndex,
normalIndex,
out_vertices,
out_UVs,
out_normals,
actual_image_width,
actual_image_height,
is_bilinear_interpolation_in_use,
is_southwest_northeast_edges_in_use,
is_southeast_northwest_edges_in_use);
std::cout << "number of vertices: " << out_vertices.size() << ".\n";
std::cout << "number of UVs: " << out_UVs.size() << ".\n";
std::cout << "number of normals: " << out_normals.size() << ".\n";
return true;
}
}
#endif
<commit_msg>Auto-indented code.<commit_after>#ifndef __QUAD_TRIANGULATION_HPP_INCLUDED
#define __QUAD_TRIANGULATION_HPP_INCLUDED
#ifndef GLM_FORCE_RADIANS
#define GLM_FORCE_RADIANS
#define DEGREES_TO_RADIANS(x) (x * PI / 180.0f)
#endif
#include "face_normals.hpp"
#include "vertex_normals.hpp"
#include "vertices.hpp"
#include "triangulation_enums.hpp"
#include "triangulation_templates.hpp"
#include "indexing.hpp"
#include "code/ylikuutio/geometry/transformation.hpp"
#include "code/ylikuutio/common/globals.hpp"
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp
#include <stdint.h> // uint32_t etc.
#include <vector> // std::vector
namespace geometry
{
template<class T1>
bool triangulate_quads(
T1* input_vertex_pointer,
TriangulateQuadsStruct triangulate_quads_struct,
std::vector<glm::vec3>& out_vertices,
std::vector<glm::vec2>& out_UVs,
std::vector<glm::vec3>& out_normals)
{
// Input vertices (`T1* input_vertex_pointer`)
// can be `float`, `int32_t` or `uint32_t`.
int32_t image_width = triangulate_quads_struct.image_width;
int32_t image_height = triangulate_quads_struct.image_height;
int32_t x_step = triangulate_quads_struct.x_step;
int32_t z_step = triangulate_quads_struct.z_step;
int32_t actual_image_width = (image_width - 1) / x_step + 1;
int32_t actual_image_height = (image_height - 1) / z_step + 1;
std::string triangulation_type = triangulate_quads_struct.triangulation_type;
double sphere_radius = triangulate_quads_struct.sphere_radius;
SphericalWorldStruct spherical_world_struct = triangulate_quads_struct.spherical_world_struct;
if (image_width < 2 || image_height < 2 || actual_image_width < 2 || actual_image_height < 2)
{
return false;
}
if (x_step < 1 || z_step < 1)
{
return false;
}
const char* char_triangulation_type = triangulation_type.c_str();
bool is_bilinear_interpolation_in_use = false;
bool is_southwest_northeast_edges_in_use = false;
bool is_southeast_northwest_edges_in_use = false;
bool is_triangulation_type_valid = false;
if (std::strcmp(char_triangulation_type, "bilinear_interpolation") == 0)
{
// *---*
// |\ /|
// | * |
// |/ \|
// *---*
is_bilinear_interpolation_in_use = true;
is_triangulation_type_valid = true;
}
else if ((std::strcmp(char_triangulation_type, "southwest_northeast_edges") == 0) || (std::strcmp(char_triangulation_type, "northeast_southwest_edges") == 0))
{
// *---*
// | /|
// | / |
// |/ |
// *---*
is_southwest_northeast_edges_in_use = true;
is_triangulation_type_valid = true;
}
else if ((std::strcmp(char_triangulation_type, "southeast_northwest_edges") == 0) || (std::strcmp(char_triangulation_type, "northwest_southeast_edges") == 0))
{
// *---*
// |\ |
// | \ |
// | \|
// *---*
is_southeast_northwest_edges_in_use = true;
is_triangulation_type_valid = true;
}
std::cout << "triangulation type in use: " << triangulation_type << "\n";
if (!is_triangulation_type_valid)
{
std::cerr << "invalid triangulation type!\n";
return false;
}
std::vector<GLuint> vertexIndices, uvIndices, normalIndices;
std::vector<glm::vec3> temp_vertices;
std::vector<glm::vec2> temp_UVs;
std::vector<glm::vec3> temp_normals;
// Processing stages:
// 1. Define the (GLfloat) vertices for vertices loaded from file, `push_back` to `temp_vertices` and `temp_UVs`.
// 2. Interpolate the (GLfloat) vertices between, using bilinear interpolation, `push_back` to `temp_vertices` and `temp_UVs`.
// 3a. Transform spherical coordinates loaded from file (and computed this far as being in horizontal plane) to a curved surface.
// 3b. For bilinear interpolation: Transform interpolated coordinates (and computed this far as being in horizontal plane) to a curved surface.
// 4. Compute the face normals, `push_back` to `face_normals`.
// 5. Compute the vertex normals for vertices loaded from file and for interpolated vertices (for `"bilinear_interpolation"`), `push_back` to `temp_normals`.
// 6. Loop through all vertices and `geometry::output_triangle_vertices`.
//
// stg. `"bilinear_interpolation"` `"southwest_northeast_edges"` `"southeast_northwest_edges"`
// 1. `define_vertices` `define_vertices` `define_vertices`
// 2. `interpolate_and_define_vertices_using_bilinear_interpolation` N/A N/A
// 3. `transform_coordinates_to_curved_surface` `transform_coordinates_to_curved_surface` `transform_coordinates_to_curved_surface`
// 4. `compute_face_normals` `compute_face_normals` `compute_face_normals`
// 5. `compute_vertex_normals` `compute_vertex_normals` `compute_vertex_normals`
// 6. `define_vertices_UVs_and_normals` `define_vertices_UVs_and_normals` `define_vertices_UVs_and_normals`
//
// stg. = stage
// 1. Define the vertices for vertices loaded from file, `push_back` to `temp_vertices`.
if (!geometry::define_vertices(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
triangulate_quads_struct.should_ylikuutio_use_real_texture_coordinates,
temp_vertices,
temp_UVs))
{
return false;
}
int32_t n_faces_for_each_vertex;
int32_t n_faces;
if (is_bilinear_interpolation_in_use)
{
n_faces_for_each_vertex = 4;
}
else if (is_southwest_northeast_edges_in_use || is_southeast_northwest_edges_in_use)
{
n_faces_for_each_vertex = 2;
}
std::cout << "image width: " << image_width << " pixels.\n";
std::cout << "image height: " << image_height << " pixels.\n";
std::cout << "actual image width: " << actual_image_width << " pixels.\n";
std::cout << "actual image height: " << actual_image_height << " pixels.\n";
std::cout << "number of faces: " << n_faces << ".\n";
n_faces = n_faces_for_each_vertex * (actual_image_width - 1) * (actual_image_height - 1);
uint32_t vertexIndex[3], uvIndex[3], normalIndex[3];
if (is_bilinear_interpolation_in_use)
{
// 2. Interpolate the vertices between, using bilinear interpolation, `push_back` to `temp_vertices`.
if (!geometry::interpolate_and_define_vertices_using_bilinear_interpolation(
input_vertex_pointer,
image_width,
image_height,
x_step,
z_step,
triangulate_quads_struct.should_ylikuutio_use_real_texture_coordinates,
temp_vertices,
temp_UVs))
{
return false;
}
}
if (!std::isnan(sphere_radius))
{
// 3a. Transform spherical coordinates loaded from file (and computed this far as being in horizontal plane) to a curved surface.
// 3b. For bilinear interpolation: Transform interpolated coordinates (and computed this far as being in horizontal plane) to a curved surface.
//
// Wikipedia:
// https://en.wikipedia.org/wiki/List_of_common_coordinate_transformations#From_spherical_coordinates
//
// x = rho * sin(theta) * cos(phi)
// y = rho * sin(theta) * sin(phi)
// z = rho * cos(theta)
TransformationStruct transformation_struct;
transformation_struct.image_width = image_width;
transformation_struct.image_height = image_height;
transformation_struct.sphere_radius = sphere_radius;
transformation_struct.is_bilinear_interpolation_in_use = is_bilinear_interpolation_in_use;
transformation_struct.spherical_world_struct = spherical_world_struct;
geometry::transform_coordinates_to_curved_surface(transformation_struct, temp_vertices);
}
else
{
std::cout << "no coordinate transformation is needed.\n";
}
// 4. Compute the face normals, `push_back` to `face_normals`.
// Triangle order: S - W - N - E.
//
// First triangle: center, southeast, southwest.
// Second triangle: center, southwest, northwest.
// Third triangle: center, northwest, northeast.
// Fourth triangle: center, northeast, southeast.
std::cout << "computing face normals.\n";
std::vector<glm::vec3> face_normal_vector_vec3;
if (!geometry::compute_face_normals(
temp_vertices,
face_normal_vector_vec3,
actual_image_width,
actual_image_height,
is_bilinear_interpolation_in_use,
is_southwest_northeast_edges_in_use,
is_southeast_northwest_edges_in_use))
{
return false;
}
// 5. Compute the vertex normals for vertices loaded from file, `push_back` to `temp_normals`.
geometry::compute_vertex_normals(
temp_normals,
face_normal_vector_vec3,
actual_image_width,
actual_image_height,
is_bilinear_interpolation_in_use,
is_southwest_northeast_edges_in_use,
is_southeast_northwest_edges_in_use);
// 6. Loop through all vertices and `geometry::output_triangle_vertices`.
geometry::define_vertices_UVs_and_normals(
triangulate_quads_struct,
temp_vertices,
temp_UVs,
temp_normals,
vertexIndex,
uvIndex,
normalIndex,
out_vertices,
out_UVs,
out_normals,
actual_image_width,
actual_image_height,
is_bilinear_interpolation_in_use,
is_southwest_northeast_edges_in_use,
is_southeast_northwest_edges_in_use);
std::cout << "number of vertices: " << out_vertices.size() << ".\n";
std::cout << "number of UVs: " << out_UVs.size() << ".\n";
std::cout << "number of normals: " << out_normals.size() << ".\n";
return true;
}
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Cleaning up code.<commit_after><|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float)
{
this->SetName("Output Image");
this->SetKey("out");
this->InitializeWriters();
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_Int8Writer = Int8WriterType::New();
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorInt8Writer = VectorInt8WriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBAInt8Writer = RGBAInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
m_RGBAInt16Writer = RGBAInt16WriterType::New();
m_RGBAUInt16Writer = RGBAUInt16WriterType::New();
m_RGBAInt32Writer = RGBAInt32WriterType::New();
m_RGBAUInt32Writer = RGBAUInt32WriterType::New();
m_RGBAFloatWriter = RGBAFloatWriterType::New();
m_RGBADoubleWriter = RGBADoubleWriterType::New();
}
#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType; \
typename CastFilterType::Pointer caster = CastFilterType::New(); \
caster->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(caster->GetOutput()); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);
break;
}
case ImagePixelType_uint8:
{
std::cout<<"Write, output is image uint8"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
std::cout<<"Write, output is image float"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
std::cout<<"Write, output is image double"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int8RGBAImageType, m_RGBAInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int16RGBAImageType, m_RGBAInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt16RGBAImageType, m_RGBAUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int32RGBAImageType, m_RGBAInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt32RGBAImageType, m_RGBAUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, FloatRGBAImageType, m_RGBAFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, DoubleRGBAImageType, m_RGBADoubleWriter);
break;
}
}
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int8ImageType>();
}
else if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
std::cout<<"Write, input is image uint8"<<std::endl;
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<Int8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int8VectorImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int8RGBAImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else if (dynamic_cast<Int16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int16RGBAImageType>();
}
else if (dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt16RGBAImageType>();
}
else if (dynamic_cast<Int32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int32RGBAImageType>();
}
else if (dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt32RGBAImageType>();
}
else if (dynamic_cast<FloatRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<FloatRGBAImageType>();
}
else if (dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<DoubleRGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
if ( dynamic_cast<Int8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatVectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()) )
{
type = 1;
}
else if( dynamic_cast<Int8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatRGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()) )
{
type = 2;
}
itk::ProcessObject* writer = 0;
switch ( GetPixelType() )
{
case ImagePixelType_int8:
{
if( type == 1 )
writer = m_VectorInt8Writer;
else if(type == 0)
writer = m_Int8Writer;
else
writer = m_RGBAInt8Writer;
break;
}
case ImagePixelType_uint8:
{
if( type == 1 )
writer = m_VectorUInt8Writer;
else if(type == 0)
writer = m_UInt8Writer;
else
writer = m_RGBAUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if( type == 1 )
writer = m_VectorInt16Writer;
else if(type == 0)
writer = m_Int16Writer;
else
writer = m_RGBAInt16Writer;
break;
}
case ImagePixelType_uint16:
{
if( type == 1 )
writer = m_VectorUInt16Writer;
else if(type == 0)
writer = m_UInt16Writer;
else
writer = m_RGBAUInt16Writer;
break;
}
case ImagePixelType_int32:
{
if( type == 1 )
writer = m_VectorInt32Writer;
else if(type == 0)
writer = m_Int32Writer;
else
writer = m_RGBAInt32Writer;
break;
}
case ImagePixelType_uint32:
{
if( type == 1 )
writer = m_VectorUInt32Writer;
else if(type == 0)
writer = m_UInt32Writer;
else
writer = m_RGBAUInt32Writer;
break;
}
case ImagePixelType_float:
{
if( type == 1 )
writer = m_VectorFloatWriter;
else if(type == 0)
writer = m_FloatWriter;
else
writer = m_RGBAFloatWriter;
break;
}
case ImagePixelType_double:
{
if( type == 1 )
writer = m_VectorDoubleWriter;
else if(type == 0)
writer = m_DoubleWriter;
else
writer = m_RGBADoubleWriter;
break;
}
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<commit_msg>STYLE<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "itkCastImageFilter.h"
#include "itkVectorCastImageFilter.h"
namespace otb
{
namespace Wrapper
{
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float)
{
this->SetName("Output Image");
this->SetKey("out");
this->InitializeWriters();
}
OutputImageParameter::~OutputImageParameter()
{
}
void OutputImageParameter::InitializeWriters()
{
m_Int8Writer = Int8WriterType::New();
m_UInt8Writer = UInt8WriterType::New();
m_Int16Writer = Int16WriterType::New();
m_UInt16Writer = UInt16WriterType::New();
m_Int32Writer = Int32WriterType::New();
m_UInt32Writer = UInt32WriterType::New();
m_FloatWriter = FloatWriterType::New();
m_DoubleWriter = DoubleWriterType::New();
m_VectorInt8Writer = VectorInt8WriterType::New();
m_VectorUInt8Writer = VectorUInt8WriterType::New();
m_VectorInt16Writer = VectorInt16WriterType::New();
m_VectorUInt16Writer = VectorUInt16WriterType::New();
m_VectorInt32Writer = VectorInt32WriterType::New();
m_VectorUInt32Writer = VectorUInt32WriterType::New();
m_VectorFloatWriter = VectorFloatWriterType::New();
m_VectorDoubleWriter = VectorDoubleWriterType::New();
m_RGBAInt8Writer = RGBAInt8WriterType::New();
m_RGBAUInt8Writer = RGBAUInt8WriterType::New();
m_RGBAInt16Writer = RGBAInt16WriterType::New();
m_RGBAUInt16Writer = RGBAUInt16WriterType::New();
m_RGBAInt32Writer = RGBAInt32WriterType::New();
m_RGBAUInt32Writer = RGBAUInt32WriterType::New();
m_RGBAFloatWriter = RGBAFloatWriterType::New();
m_RGBADoubleWriter = RGBADoubleWriterType::New();
}
#define otbCastAndWriteImageMacro(InputImageType, OutputImageType, writer) \
{ \
typedef itk::CastImageFilter<InputImageType, OutputImageType> CastFilterType; \
typename CastFilterType::Pointer caster = CastFilterType::New(); \
caster->SetInput( dynamic_cast<InputImageType*>(m_Image.GetPointer()) ); \
writer->SetFileName( this->GetFileName() ); \
writer->SetInput(caster->GetOutput()); \
writer->Update(); \
}
template <class TInputImageType>
void
OutputImageParameter::SwitchImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputImageType, Int8ImageType, m_Int8Writer);
break;
}
case ImagePixelType_uint8:
{
std::cout<<"Write, output is image uint8"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, UInt8ImageType, m_UInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputImageType, Int16ImageType, m_Int16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputImageType, UInt16ImageType, m_UInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputImageType, Int32ImageType, m_Int32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputImageType, UInt32ImageType, m_UInt32Writer);
break;
}
case ImagePixelType_float:
{
std::cout<<"Write, output is image float"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, FloatImageType, m_FloatWriter);
break;
}
case ImagePixelType_double:
{
std::cout<<"Write, output is image double"<<std::endl;
otbCastAndWriteImageMacro(TInputImageType, DoubleImageType, m_DoubleWriter);
break;
}
}
}
template <class TInputVectorImageType>
void
OutputImageParameter::SwitchVectorImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int8VectorImageType, m_VectorInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt8VectorImageType, m_VectorUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int16VectorImageType, m_VectorInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt16VectorImageType, m_VectorUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, Int32VectorImageType, m_VectorInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputVectorImageType, UInt32VectorImageType, m_VectorUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputVectorImageType, FloatVectorImageType, m_VectorFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputVectorImageType, DoubleVectorImageType, m_VectorDoubleWriter);
break;
}
}
}
template <class TInputRGBAImageType>
void
OutputImageParameter::SwitchRGBAImageWrite()
{
switch(m_PixelType )
{
case ImagePixelType_int8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int8RGBAImageType, m_RGBAInt8Writer);
break;
}
case ImagePixelType_uint8:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt8RGBAImageType, m_RGBAUInt8Writer);
break;
}
case ImagePixelType_int16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int16RGBAImageType, m_RGBAInt16Writer);
break;
}
case ImagePixelType_uint16:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt16RGBAImageType, m_RGBAUInt16Writer);
break;
}
case ImagePixelType_int32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, Int32RGBAImageType, m_RGBAInt32Writer);
break;
}
case ImagePixelType_uint32:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, UInt32RGBAImageType, m_RGBAUInt32Writer);
break;
}
case ImagePixelType_float:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, FloatRGBAImageType, m_RGBAFloatWriter);
break;
}
case ImagePixelType_double:
{
otbCastAndWriteImageMacro(TInputRGBAImageType, DoubleRGBAImageType, m_RGBADoubleWriter);
break;
}
}
}
void
OutputImageParameter::Write()
{
m_Image->UpdateOutputInformation();
if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int8ImageType>();
}
else if (dynamic_cast<UInt8ImageType*>(m_Image.GetPointer()))
{
std::cout<<"Write, input is image uint8"<<std::endl;
SwitchImageWrite<UInt8ImageType>();
}
else if (dynamic_cast<Int16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int16ImageType>();
}
else if (dynamic_cast<UInt16ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt16ImageType>();
}
else if (dynamic_cast<Int32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<Int32ImageType>();
}
else if (dynamic_cast<UInt32ImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<UInt32ImageType>();
}
else if (dynamic_cast<FloatImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<FloatImageType>();
}
else if (dynamic_cast<DoubleImageType*>(m_Image.GetPointer()))
{
SwitchImageWrite<DoubleImageType>();
}
else if (dynamic_cast<Int8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int8VectorImageType>();
}
else if (dynamic_cast<UInt8VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt8VectorImageType>();
}
else if (dynamic_cast<Int16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int16VectorImageType>();
}
else if (dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt16VectorImageType>();
}
else if (dynamic_cast<Int32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<Int32VectorImageType>();
}
else if (dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<UInt32VectorImageType>();
}
else if (dynamic_cast<FloatVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<FloatVectorImageType>();
}
else if (dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()))
{
SwitchVectorImageWrite<DoubleVectorImageType>();
}
else if (dynamic_cast<Int8ImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int8RGBAImageType>();
}
else if (dynamic_cast<UInt8RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt8RGBAImageType>();
}
else if (dynamic_cast<Int16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int16RGBAImageType>();
}
else if (dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt16RGBAImageType>();
}
else if (dynamic_cast<Int32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<Int32RGBAImageType>();
}
else if (dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<UInt32RGBAImageType>();
}
else if (dynamic_cast<FloatRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<FloatRGBAImageType>();
}
else if (dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()))
{
SwitchRGBAImageWrite<DoubleRGBAImageType>();
}
else
{
itkExceptionMacro("Unknown image type");
}
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
int type = 0;
// 0 : image
// 1 : VectorImage
// 2 : RGBAImage
if ( dynamic_cast<Int8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32VectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32VectorImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatVectorImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleVectorImageType*>(m_Image.GetPointer()) )
{
type = 1;
}
else if( dynamic_cast<Int8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt8RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<Int16RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt16RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<Int32RGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<UInt32RGBAImageType*>(m_Image.GetPointer()) ||
dynamic_cast<FloatRGBAImageType*>( m_Image.GetPointer()) ||
dynamic_cast<DoubleRGBAImageType*>(m_Image.GetPointer()) )
{
type = 2;
}
itk::ProcessObject* writer = 0;
switch ( GetPixelType() )
{
case ImagePixelType_int8:
{
if( type == 1 )
writer = m_VectorInt8Writer;
else if(type == 0)
writer = m_Int8Writer;
else
writer = m_RGBAInt8Writer;
break;
}
case ImagePixelType_uint8:
{
if( type == 1 )
writer = m_VectorUInt8Writer;
else if(type == 0)
writer = m_UInt8Writer;
else
writer = m_RGBAUInt8Writer;
break;
}
case ImagePixelType_int16:
{
if( type == 1 )
writer = m_VectorInt16Writer;
else if(type == 0)
writer = m_Int16Writer;
else
writer = m_RGBAInt16Writer;
break;
}
case ImagePixelType_uint16:
{
if( type == 1 )
writer = m_VectorUInt16Writer;
else if(type == 0)
writer = m_UInt16Writer;
else
writer = m_RGBAUInt16Writer;
break;
}
case ImagePixelType_int32:
{
if( type == 1 )
writer = m_VectorInt32Writer;
else if(type == 0)
writer = m_Int32Writer;
else
writer = m_RGBAInt32Writer;
break;
}
case ImagePixelType_uint32:
{
if( type == 1 )
writer = m_VectorUInt32Writer;
else if(type == 0)
writer = m_UInt32Writer;
else
writer = m_RGBAUInt32Writer;
break;
}
case ImagePixelType_float:
{
if( type == 1 )
writer = m_VectorFloatWriter;
else if(type == 0)
writer = m_FloatWriter;
else
writer = m_RGBAFloatWriter;
break;
}
case ImagePixelType_double:
{
if( type == 1 )
writer = m_VectorDoubleWriter;
else if(type == 0)
writer = m_DoubleWriter;
else
writer = m_RGBADoubleWriter;
break;
}
}
return writer;
}
OutputImageParameter::ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter::HasValue() const
{
std::string filename(this->GetFileName());
return !filename.empty();
}
}
}
<|endoftext|>
|
<commit_before>// Do not remove the include below
#include "farmbot_arduino_controller.h"
#include "pins.h"
#include "Config.h"
#include "ServoControl.h"
static char commandEndChar = 0x0A;
static GCodeProcessor* gCodeProcessor = new GCodeProcessor();
//The setup function is called once at startup of the sketch
void setup() {
pinMode(X_STEP_PIN , OUTPUT);
pinMode(X_DIR_PIN , OUTPUT);
pinMode(X_ENABLE_PIN, OUTPUT);
pinMode(X_MIN_PIN , INPUT );
pinMode(X_MAX_PIN , INPUT );
pinMode(Y_STEP_PIN , OUTPUT);
pinMode(Y_DIR_PIN , OUTPUT);
pinMode(Y_ENABLE_PIN, OUTPUT);
pinMode(Y_MIN_PIN , INPUT );
pinMode(Y_MAX_PIN , INPUT );
pinMode(Z_STEP_PIN , OUTPUT);
pinMode(Z_DIR_PIN , OUTPUT);
pinMode(Z_ENABLE_PIN, OUTPUT);
pinMode(Z_MIN_PIN , INPUT );
pinMode(Z_MAX_PIN , INPUT );
pinMode(HEATER_0_PIN, OUTPUT);
pinMode(HEATER_1_PIN, OUTPUT);
pinMode(FAN_PIN , OUTPUT);
pinMode(LED_PIN , OUTPUT);
//pinMode(SERVO_0_PIN , OUTPUT);
//pinMode(SERVO_1_PIN , OUTPUT);
digitalWrite(X_ENABLE_PIN, HIGH);
digitalWrite(Y_ENABLE_PIN, HIGH);
digitalWrite(Z_ENABLE_PIN, HIGH);
Serial.begin(115200);
ServoControl::getInstance()->attach();
}
// The loop function is called in an endless loop
void loop() {
//unsigned long lastAction;
//unsigned long currentTime;
if (Serial.available()) {
String commandString = Serial.readStringUntil(commandEndChar);
if (commandString && commandString.length() > 0) {
Command* command = new Command(commandString);
if(LOGGING) {
command->print();
}
gCodeProcessor->execute(command);
free(command);
}
}
delay(100);
Serial.print("R00\n");
//ServoControl::getInstance()->SetAngle(90);
}
<commit_msg>R00 only on activity time-out<commit_after>// Do not remove the include below
#include "farmbot_arduino_controller.h"
#include "pins.h"
#include "Config.h"
#include "ServoControl.h"
static char commandEndChar = 0x0A;
static GCodeProcessor* gCodeProcessor = new GCodeProcessor();
unsigned long lastAction;
unsigned long currentTime;
//The setup function is called once at startup of the sketch
void setup() {
pinMode(X_STEP_PIN , OUTPUT);
pinMode(X_DIR_PIN , OUTPUT);
pinMode(X_ENABLE_PIN, OUTPUT);
pinMode(X_MIN_PIN , INPUT );
pinMode(X_MAX_PIN , INPUT );
pinMode(Y_STEP_PIN , OUTPUT);
pinMode(Y_DIR_PIN , OUTPUT);
pinMode(Y_ENABLE_PIN, OUTPUT);
pinMode(Y_MIN_PIN , INPUT );
pinMode(Y_MAX_PIN , INPUT );
pinMode(Z_STEP_PIN , OUTPUT);
pinMode(Z_DIR_PIN , OUTPUT);
pinMode(Z_ENABLE_PIN, OUTPUT);
pinMode(Z_MIN_PIN , INPUT );
pinMode(Z_MAX_PIN , INPUT );
pinMode(HEATER_0_PIN, OUTPUT);
pinMode(HEATER_1_PIN, OUTPUT);
pinMode(FAN_PIN , OUTPUT);
pinMode(LED_PIN , OUTPUT);
//pinMode(SERVO_0_PIN , OUTPUT);
//pinMode(SERVO_1_PIN , OUTPUT);
digitalWrite(X_ENABLE_PIN, HIGH);
digitalWrite(Y_ENABLE_PIN, HIGH);
digitalWrite(Z_ENABLE_PIN, HIGH);
Serial.begin(115200);
ServoControl::getInstance()->attach();
lastAction = millis();
}
// The loop function is called in an endless loop
void loop() {
if (Serial.available()) {
String commandString = Serial.readStringUntil(commandEndChar);
if (commandString && commandString.length() > 0) {
lastAction = millis();
Command* command = new Command(commandString);
if(LOGGING) {
command->print();
}
gCodeProcessor->execute(command);
free(command);
}
}
delay(10);
currentTime = millis();
if (currentTime < lastAction) {
// If the device timer overruns, reset the idle counter
lastAction = millis();
}
else {
if ((currentTime - lastAction) > 5000) {
// After an idle time, send the idle message
Serial.print("R00\n");
lastAction = millis();
}
}
}
<|endoftext|>
|
<commit_before>#include <aidu_vision/laserscancombination.h>
#include <geometry_msgs/Twist.h>
#include <math.h>
#include <vector>
using namespace aidu;
LaserScanCombination::LaserScanCombination(): core::Node::Node(){
//subscribing and pubishing
scanmsg = nh->subscribe("/scan", 1, &LaserScanCombination::LaserScanCallback, this);
distmsg= nh->subscribe("/sensors", 1, &LaserScanCombination::DistCallback, this);
laserscanpublisher= nh->advertise<sensor_msgs::LaserScan>("/scan2",1);
}
void LaserScanCombination::DistCallback(const aidu_vision::DistanceSensors::ConstPtr& distmsg){
distLeft=distmsg->Left/1000.0;
distRight=distmsg->Right/1000.0;
}
void LaserScanCombination::LaserScanCallback(const sensor_msgs::LaserScan::ConstPtr& scanmsg){
// Distance sensor position
const double xSensor=0.3; // x distance from kinect
const double ySensor=0.3; // y distance from kinect
const double rMin=sqrt(pow(xSensor,2)+pow(ySensor,2));
const double thetaMax=asin(ySensor/rMin)+1.5705;
ROS_INFO("thetamax:%f",thetaMax);
//getting lasercan data
sensor_msgs::LaserScan scanmsg2;
double angle_min=scanmsg->angle_min;
double angle_max=scanmsg->angle_max;
double angle_increment=scanmsg->angle_increment;
int size =(scanmsg->angle_max-scanmsg->angle_min)/(scanmsg->angle_increment);
ROS_INFO("size:%d", size);
//adding left and right sensor data to laserscan
int negaddionalPoints=floor((thetaMax+angle_min)/angle_increment);
int posaddionalPoints=ceil((thetaMax-angle_max)/angle_increment);
int totalsize=negaddionalPoints+size+posaddionalPoints;
ROS_INFO("totalsize:%d",totalsize);
//Copying laser scan data to new array filled with NaNs
float* ranges = new float[totalsize];
for (int i=0;i<negaddionalPoints;i++){
ranges[i]=std::numeric_limits<double>::quiet_NaN();
}
for (int i=negaddionalPoints;i<(negaddionalPoints+size);i++){
ranges[i]=scanmsg->ranges[i-negaddionalPoints];
}
for (int i=(negaddionalPoints+size);i<(totalsize);i++){
ranges[i]=std::numeric_limits<double>::quiet_NaN();
}
//transforming coordinate frame of the ultrasonic sensor data to lasercan frame
double rLeft=sqrt(pow((xSensor+distLeft),2)+pow(ySensor,2));
double rRight=sqrt(pow((xSensor+distRight),2)+pow(ySensor,2));
double thetaLeft=asin(ySensor/rLeft)+1.5705;
double thetaRight=asin(ySensor/rRight)+1.5705;
ROS_INFO("thetaleft:%f thetaright:%f",thetaLeft,thetaRight);
// Adding ultrasonic sensor data in the laserscan array
int posLeft=floor((thetaMax-thetaLeft)/angle_increment);
int posRight=totalsize-ceil((thetaMax-thetaRight)/angle_increment);
ROS_INFO("posleft=%d posright:%d",posLeft,posRight);
ranges[posLeft]=distLeft;
ranges[posRight]=distRight;
ROS_INFO("sizeof:%d", sizeof(ranges));
std::vector<float> ranges2 (ranges, ranges + totalsize);
//setting new laserscan msg
scanmsg2.angle_min=-thetaMax;
scanmsg2.angle_max=-thetaMax+totalsize*angle_increment;
scanmsg2.ranges=ranges2;
scanmsg2.angle_increment=scanmsg->angle_increment;
scanmsg2.range_max=scanmsg->range_max;
scanmsg2.range_min=scanmsg->range_min;
scanmsg2.scan_time=scanmsg->scan_time;
scanmsg2.time_increment=scanmsg->time_increment;
scanmsg2.header.frame_id=scanmsg->header.frame_id;
scanmsg2.header.stamp=scanmsg2.header.stamp;
scanmsg2.intensities=scanmsg->intensities;
laserscanpublisher.publish(scanmsg2);
delete[] ranges;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "laserscancombination");
LaserScanCombination laserscancombination;
laserscancombination.spin();
return 0;
}<commit_msg>changed position of the distance sensor<commit_after>#include <aidu_vision/laserscancombination.h>
#include <geometry_msgs/Twist.h>
#include <math.h>
#include <vector>
using namespace aidu;
LaserScanCombination::LaserScanCombination(): core::Node::Node(){
//subscribing and pubishing
scanmsg = nh->subscribe("/scan", 1, &LaserScanCombination::LaserScanCallback, this);
distmsg= nh->subscribe("/sensors", 1, &LaserScanCombination::DistCallback, this);
laserscanpublisher= nh->advertise<sensor_msgs::LaserScan>("/scan2",1);
}
void LaserScanCombination::DistCallback(const aidu_vision::DistanceSensors::ConstPtr& distmsg){
distLeft=distmsg->Left/1000.0;
distRight=distmsg->Right/1000.0;
}
void LaserScanCombination::LaserScanCallback(const sensor_msgs::LaserScan::ConstPtr& scanmsg){
// Distance sensor position
const double xSensor=0.23; // x distance from kinect
const double ySensor=0.38; // y distance from kinect
const double rMin=sqrt(pow(xSensor,2)+pow(ySensor,2));
const double thetaMax=asin(ySensor/rMin)+1.5705;
ROS_INFO("thetamax:%f",thetaMax);
//getting lasercan data
sensor_msgs::LaserScan scanmsg2;
double angle_min=scanmsg->angle_min;
double angle_max=scanmsg->angle_max;
double angle_increment=scanmsg->angle_increment;
int size =(scanmsg->angle_max-scanmsg->angle_min)/(scanmsg->angle_increment);
ROS_INFO("size:%d", size);
//adding left and right sensor data to laserscan
int negaddionalPoints=floor((thetaMax+angle_min)/angle_increment);
int posaddionalPoints=ceil((thetaMax-angle_max)/angle_increment);
int totalsize=negaddionalPoints+size+posaddionalPoints;
ROS_INFO("totalsize:%d",totalsize);
//Copying laser scan data to new array filled with NaNs
float* ranges = new float[totalsize];
for (int i=0;i<negaddionalPoints;i++){
ranges[i]=std::numeric_limits<double>::quiet_NaN();
}
for (int i=negaddionalPoints;i<(negaddionalPoints+size);i++){
ranges[i]=scanmsg->ranges[i-negaddionalPoints];
}
for (int i=(negaddionalPoints+size);i<(totalsize);i++){
ranges[i]=std::numeric_limits<double>::quiet_NaN();
}
//transforming coordinate frame of the ultrasonic sensor data to lasercan frame
double rLeft=sqrt(pow((xSensor+distLeft),2)+pow(ySensor,2));
double rRight=sqrt(pow((xSensor+distRight),2)+pow(ySensor,2));
double thetaLeft=asin(ySensor/rLeft)+1.5705;
double thetaRight=asin(ySensor/rRight)+1.5705;
ROS_INFO("thetaleft:%f thetaright:%f",thetaLeft,thetaRight);
// Adding ultrasonic sensor data in the laserscan array
int posLeft=totalsize-ceil((thetaMax-thetaLeft)/angle_increment);
int posRight=floor((thetaMax-thetaRight)/angle_increment);
ROS_INFO("posleft=%d posright:%d",posLeft,posRight);
ranges[posLeft]=distLeft;
ranges[posRight]=distRight;
ROS_INFO("sizeof:%d", sizeof(ranges));
std::vector<float> ranges2 (ranges, ranges + totalsize);
//setting new laserscan msg
scanmsg2.angle_min=-thetaMax;
scanmsg2.angle_max=-thetaMax+totalsize*angle_increment;
scanmsg2.ranges=ranges2;
scanmsg2.angle_increment=scanmsg->angle_increment;
scanmsg2.range_max=scanmsg->range_max;
scanmsg2.range_min=scanmsg->range_min;
scanmsg2.scan_time=scanmsg->scan_time;
scanmsg2.time_increment=scanmsg->time_increment;
scanmsg2.header.frame_id=scanmsg->header.frame_id;
scanmsg2.header.stamp=scanmsg2.header.stamp;
scanmsg2.intensities=scanmsg->intensities;
laserscanpublisher.publish(scanmsg2);
delete[] ranges;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "laserscancombination");
LaserScanCombination laserscancombination;
laserscancombination.spin();
return 0;
}<|endoftext|>
|
<commit_before>#include "mitkManualSegmentationToSurfaceFilter.h"
mitk::ManualSegmentationToSurfaceFilter::ManualSegmentationToSurfaceFilter()
: m_MedianKernelSizeX(3), m_MedianKernelSizeY(3), m_MedianKernelSizeZ(3), m_StandardDeviation(1.5){};
mitk::ManualSegmentationToSurfaceFilter::~ManualSegmentationToSurfaceFilter(){};
void mitk::ManualSegmentationToSurfaceFilter::GenerateData()
{
mitk::Surface *surface = this->GetOutput();
mitk::Image * image = (mitk::Image*)GetInput();
mitk::Image::RegionType outputRegion = image->GetRequestedRegion();
int tstart=outputRegion.GetIndex(3);
int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst
ScalarType thresholdExpanded = this->m_Threshold;
for( int t=tstart; t<tmax; t++ )
{
vtkImageData *vtkimage = image->GetVtkImageData(t);
//Inkrement Referenzcounter Counter (hier: RC)
vtkimage->Register(NULL);
// Median -->smooth 3D
if(m_MedianFilter3D)
{
vtkImageMedian3D *median = vtkImageMedian3D::New();
median->SetInput(vtkimage); //RC++
vtkimage->Delete();//RC--
median->SetKernelSize(m_MedianKernelSizeX,m_MedianKernelSizeY,m_MedianKernelSizeZ);//Std: 3x3x3
median->ReleaseDataFlagOn();
median->UpdateInformation();
vtkimage = median->GetOutput();
}
//Interpolate image spacing
if(m_Interpolation)
{
vtkImageResample * imageresample = vtkImageResample::New();
imageresample->SetInput(vtkimage);
//Spacing Manual or Original (Original spacing is lost during image processing)
imageresample->SetAxisOutputSpacing(0, 1);
imageresample->SetAxisOutputSpacing(1, 1);
imageresample->SetAxisOutputSpacing(2, 1); //auf 1 interpoliert
imageresample->InterpolateOn();//OFF: pixel replication is used
vtkimage=imageresample->GetOutput();
vtkimage->UpdateInformation();
}
if(m_UseStandardDeviation)//gauss
{
vtkImageThreshold* vtkimagethreshold = vtkImageThreshold::New();
vtkimagethreshold->SetInput(vtkimage);//RC++
vtkimage->Delete();//RC--
vtkimagethreshold->SetInValue( 100 );
vtkimagethreshold->SetOutValue( 0 );
vtkimagethreshold->ThresholdByUpper( this->m_Threshold );
thresholdExpanded = 49;
vtkimagethreshold->SetOutputScalarTypeToUnsignedChar();
vtkimagethreshold->ReleaseDataFlagOn();
vtkImageGaussianSmooth *gaussian = vtkImageGaussianSmooth::New();
gaussian->SetInput(vtkimagethreshold->GetOutput()); //RC ++
vtkimagethreshold->Delete(); //RC--
gaussian->SetDimensionality(3);
gaussian->SetRadiusFactor(0.49);
gaussian->SetStandardDeviation( m_StandardDeviation );
gaussian->ReleaseDataFlagOn();
gaussian->UpdateInformation();
vtkimage = gaussian->GetOutput();
}
// Create sureface for t-Slice
CreateSurface(t, vtkimage, surface, thresholdExpanded);
}
};
/**
* Set Kernel for Median3D.
*/
void mitk::ManualSegmentationToSurfaceFilter::SetMedianKernelSize(int x, int y, int z)
{
m_MedianKernelSizeX = x;
m_MedianKernelSizeY = y;
m_MedianKernelSizeZ = z;
}
<commit_msg>RMV: unused and in vtk4.2 not supported function from vtkImageResample<commit_after>#include "mitkManualSegmentationToSurfaceFilter.h"
mitk::ManualSegmentationToSurfaceFilter::ManualSegmentationToSurfaceFilter()
: m_MedianKernelSizeX(3), m_MedianKernelSizeY(3), m_MedianKernelSizeZ(3), m_StandardDeviation(1.5){};
mitk::ManualSegmentationToSurfaceFilter::~ManualSegmentationToSurfaceFilter(){};
void mitk::ManualSegmentationToSurfaceFilter::GenerateData()
{
mitk::Surface *surface = this->GetOutput();
mitk::Image * image = (mitk::Image*)GetInput();
mitk::Image::RegionType outputRegion = image->GetRequestedRegion();
int tstart=outputRegion.GetIndex(3);
int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst
ScalarType thresholdExpanded = this->m_Threshold;
for( int t=tstart; t<tmax; t++ )
{
vtkImageData *vtkimage = image->GetVtkImageData(t);
//Inkrement Referenzcounter Counter (hier: RC)
vtkimage->Register(NULL);
// Median -->smooth 3D
if(m_MedianFilter3D)
{
vtkImageMedian3D *median = vtkImageMedian3D::New();
median->SetInput(vtkimage); //RC++
vtkimage->Delete();//RC--
median->SetKernelSize(m_MedianKernelSizeX,m_MedianKernelSizeY,m_MedianKernelSizeZ);//Std: 3x3x3
median->ReleaseDataFlagOn();
median->UpdateInformation();
vtkimage = median->GetOutput();
}
//Interpolate image spacing
if(m_Interpolation)
{
vtkImageResample * imageresample = vtkImageResample::New();
imageresample->SetInput(vtkimage);
//Set Spacing Manual to 1mm in each direction (Original spacing is lost during image processing)
imageresample->SetAxisOutputSpacing(0, 1);
imageresample->SetAxisOutputSpacing(1, 1);
imageresample->SetAxisOutputSpacing(2, 1);
vtkimage=imageresample->GetOutput();
vtkimage->UpdateInformation();
}
if(m_UseStandardDeviation)//gauss
{
vtkImageThreshold* vtkimagethreshold = vtkImageThreshold::New();
vtkimagethreshold->SetInput(vtkimage);//RC++
vtkimage->Delete();//RC--
vtkimagethreshold->SetInValue( 100 );
vtkimagethreshold->SetOutValue( 0 );
vtkimagethreshold->ThresholdByUpper( this->m_Threshold );
thresholdExpanded = 49;
vtkimagethreshold->SetOutputScalarTypeToUnsignedChar();
vtkimagethreshold->ReleaseDataFlagOn();
vtkImageGaussianSmooth *gaussian = vtkImageGaussianSmooth::New();
gaussian->SetInput(vtkimagethreshold->GetOutput()); //RC ++
vtkimagethreshold->Delete(); //RC--
gaussian->SetDimensionality(3);
gaussian->SetRadiusFactor(0.49);
gaussian->SetStandardDeviation( m_StandardDeviation );
gaussian->ReleaseDataFlagOn();
gaussian->UpdateInformation();
vtkimage = gaussian->GetOutput();
}
// Create sureface for t-Slice
CreateSurface(t, vtkimage, surface, thresholdExpanded);
}
};
/**
* Set Kernel for Median3D.
*/
void mitk::ManualSegmentationToSurfaceFilter::SetMedianKernelSize(int x, int y, int z)
{
m_MedianKernelSizeX = x;
m_MedianKernelSizeY = y;
m_MedianKernelSizeZ = z;
}
<|endoftext|>
|
<commit_before><commit_msg>Update g_network_client.cpp<commit_after><|endoftext|>
|
<commit_before>/*
Copyright 2014 Larry Gritz and the other authors and contributors.
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 software's owners 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.
(This is the Modified BSD License)
*/
extern "C" { // ffmpeg is a C api
#include <errno.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}
#include <boost/shared_ptr.hpp>
#include <boost/thread/once.hpp>
#include "OpenImageIO/imageio.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
class FFmpegInput : public ImageInput {
public:
FFmpegInput ();
virtual ~FFmpegInput();
virtual const char *format_name (void) const { return "FFmpeg movie"; }
virtual bool open (const std::string &name, ImageSpec &spec);
virtual bool close (void);
virtual int current_subimage (void) const { return m_subimage; }
virtual bool seek_subimage (int subimage, int miplevel, ImageSpec &newspec);
virtual bool read_native_scanline (int y, int z, void *data);
void read_frame(int pos);
#if 0
const char *metadata (const char * key);
bool has_metadata (const char * key);
#endif
bool seek (int pos);
double fps() const;
int64_t time_stamp(int pos) const;
private:
std::string m_filename;
int m_subimage;
int m_nsubimages;
AVFormatContext * m_format_context;
AVCodecContext * m_codec_context;
AVCodec *m_codec;
AVFrame *m_frame;
AVFrame *m_rgb_frame;
SwsContext *m_sws_rgb_context;
AVRational m_frame_rate;
std::vector<uint8_t> m_rgb_buffer;
std::vector<int> m_video_indexes;
int m_video_stream;
int m_frames;
int m_last_search_pos;
int m_last_decoded_pos;
bool m_offset_time;
bool m_read_frame;
// init to initialize state
void init (void) {
m_filename.clear ();
m_format_context = 0;
m_codec_context = 0;
m_codec = 0;
m_frame = 0;
m_rgb_frame = 0;
m_sws_rgb_context = 0;
m_rgb_buffer.clear();
m_video_indexes.clear();
m_video_stream = -1;
m_frames = 0;
m_last_search_pos = 0;
m_last_decoded_pos = 0;
m_offset_time = true;
m_read_frame = false;
}
};
// Obligatory material to make this a recognizeable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT int ffmpeg_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT ImageInput *ffmpeg_input_imageio_create () {
return new FFmpegInput;
}
// FFmpeg hints:
// AVI (Audio Video Interleaved)
// QuickTime / MOV
// raw MPEG-4 video
// MPEG-1 Systems / MPEG program stream
OIIO_EXPORT const char *ffmpeg_input_extensions[] = {
"avi", "mov", "qt", "mp4", "m4a", "3gp", "3g2", "mj2", "m4v", "mpg", NULL
};
OIIO_PLUGIN_EXPORTS_END
FFmpegInput::FFmpegInput ()
{
init();
}
FFmpegInput::~FFmpegInput()
{
close();
}
bool
FFmpegInput::open (const std::string &name, ImageSpec &spec)
{
static boost::once_flag init_flag = BOOST_ONCE_INIT;
boost::call_once (&av_register_all, init_flag);
const char *file_name = name.c_str();
av_log_set_level (AV_LOG_FATAL);
if (avformat_open_input (&m_format_context, file_name, NULL, NULL) != 0) // avformat_open_input allocs format_context
{
error ("\"%s\" could not open input", file_name);
return false;
}
if (avformat_find_stream_info (m_format_context, NULL) < 0)
{
error ("\"%s\" could not find stream info", file_name);
return false;
}
m_video_stream = -1;
for (int i=0; i<m_format_context->nb_streams; i++) {
if (m_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
if (m_video_stream < 0) {
m_video_stream=i;
}
m_video_indexes.push_back (i); // needed for later use
break;
}
}
if (m_video_stream == -1) {
error ("\"%s\" could not find a valid videostream", file_name);
return false;
}
m_codec_context = m_format_context->streams[m_video_stream]->codec; // codec context for videostream
m_codec = avcodec_find_decoder (m_codec_context->codec_id);
if (!m_codec) {
error ("\"%s\" unsupported codec", file_name);
return false;
}
if (avcodec_open2 (m_codec_context, m_codec, NULL) < 0) {
error ("\"%s\" could not open codec", file_name);
return false;
}
if (!strcmp (m_codec_context->codec->name, "mjpeg") ||
!strcmp (m_codec_context->codec->name, "dvvideo")) {
m_offset_time = false;
}
AVStream *stream = m_format_context->streams[m_video_stream];
if (stream->r_frame_rate.num != 0 && stream->r_frame_rate.den != 0) {
m_frame_rate = stream->r_frame_rate;
}
if (static_cast<uint64_t> (m_format_context->duration) != AV_NOPTS_VALUE) {
m_frames = static_cast<uint64_t> ((fps() * static_cast<double>(m_format_context->duration) /
static_cast<uint64_t>(AV_TIME_BASE)));
} else {
m_frames = 1 << 29;
}
AVPacket pkt;
if (!m_frames) {
seek (0);
av_init_packet (&pkt);
av_read_frame (m_format_context, &pkt);
uint64_t first_pts = pkt.pts;
uint64_t max_pts = first_pts;
seek (1 << 29);
av_init_packet (&pkt);
while (stream && av_read_frame (m_format_context, &pkt) >= 0) {
uint64_t current_pts = static_cast<uint64_t> (av_q2d(stream->time_base) * (pkt.pts - first_pts) * fps());
if (current_pts > max_pts) {
max_pts = current_pts;
}
}
m_frames = max_pts;
}
m_frame = av_frame_alloc();
m_rgb_frame = av_frame_alloc();
m_rgb_buffer.resize(
avpicture_get_size (PIX_FMT_RGB24,
m_codec_context->width,
m_codec_context->height),
0
);
AVPixelFormat pixFormat;
switch (m_codec_context->pix_fmt) { // deprecation warning for YUV formats
case AV_PIX_FMT_YUVJ420P:
pixFormat = AV_PIX_FMT_YUV420P;
break;
case AV_PIX_FMT_YUVJ422P:
pixFormat = AV_PIX_FMT_YUV422P;
break;
case AV_PIX_FMT_YUVJ444P:
pixFormat = AV_PIX_FMT_YUV444P;
break;
case AV_PIX_FMT_YUVJ440P:
pixFormat = AV_PIX_FMT_YUV440P;
default:
pixFormat = m_codec_context->pix_fmt;
break;
}
m_sws_rgb_context = sws_getContext(
m_codec_context->width,
m_codec_context->height,
pixFormat,
m_codec_context->width,
m_codec_context->height,
PIX_FMT_RGB24,
SWS_AREA,
NULL,
NULL,
NULL
);
m_spec = ImageSpec (m_codec_context->width, m_codec_context->height, 3, TypeDesc::UINT8);
AVDictionaryEntry *tag = NULL;
while ((tag = av_dict_get (m_format_context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
m_spec.attribute (tag->key, tag->value);
}
m_spec.attribute ("fps", m_frame_rate.num / static_cast<float> (m_frame_rate.den));
m_spec.attribute ("oiio:Movie", true);
m_nsubimages = m_frames;
spec = m_spec;
return true;
}
bool
FFmpegInput::seek_subimage (int subimage, int miplevel, ImageSpec &newspec)
{
if (subimage < 0 || subimage >= m_nsubimages || miplevel > 0) {
return false;
}
if (subimage == m_subimage) {
newspec = m_spec;
return true;
}
newspec = m_spec;
m_subimage = subimage;
m_read_frame = false;
return true;
}
bool
FFmpegInput::read_native_scanline (int y, int z, void *data)
{
if (!m_read_frame) {
read_frame (m_subimage);
}
memcpy (data, m_rgb_frame->data[0] + y * m_rgb_frame->linesize[0], m_spec.width*3);
return true;
}
bool
FFmpegInput::close (void)
{
avcodec_close (m_codec_context);
avformat_close_input (&m_format_context);
av_free (m_format_context); // will free m_codec and m_codec_context
av_frame_free (&m_frame); // free after close input
av_frame_free (&m_rgb_frame);
sws_freeContext (m_sws_rgb_context);
init ();
return true;
}
void
FFmpegInput::read_frame(int pos)
{
if (m_last_decoded_pos + 1 != m_subimage) {
seek (0);
seek (m_subimage);
}
AVPacket pkt;
int finished = 0;
while (av_read_frame (m_format_context, &pkt) >=0) {
if (pkt.stream_index == m_video_stream) {
double pts = 0;
if (static_cast<uint64_t> (pkt.dts) != AV_NOPTS_VALUE) {
pts = av_q2d (m_format_context->streams[m_video_stream]->time_base) * pkt.dts;
}
int current_pos = int(pts * fps() + 0.5f);
if (current_pos == m_last_search_pos) {
current_pos = m_last_search_pos + 1;
}
m_last_search_pos = current_pos;
if (static_cast<uint64_t> (m_format_context->start_time) != AV_NOPTS_VALUE) {
current_pos -= static_cast<int> (m_format_context->start_time * fps() / AV_TIME_BASE);
}
if (current_pos >= m_subimage) {
avcodec_decode_video2 (m_codec_context, m_frame, &finished, &pkt);
}
if(finished)
{
avpicture_fill
(
reinterpret_cast<AVPicture*>(m_rgb_frame),
&m_rgb_buffer[0],
PIX_FMT_RGB24,
m_codec_context->width,
m_codec_context->height
);
sws_scale
(
m_sws_rgb_context,
static_cast<uint8_t const * const *> (m_frame->data),
m_frame->linesize,
0,
m_codec_context->height,
m_rgb_frame->data,
m_rgb_frame->linesize
);
m_last_decoded_pos = m_last_search_pos;
av_free_packet (&pkt);
break;
}
}
av_free_packet (&pkt);
}
m_read_frame = true;
}
#if 0
const char *
FFmpegInput::metadata (const char * key)
{
AVDictionaryEntry * entry = av_dict_get (m_format_context->metadata, key, NULL, 0);
return entry ? av_strdup(entry->value) : NULL;
// FIXME -- that looks suspiciously like a memory leak
}
bool
FFmpegInput::has_metadata (const char * key)
{
return av_dict_get (m_format_context->metadata, key, NULL, 0); // is there a better to check exists?
}
#endif
bool
FFmpegInput::seek (int pos)
{
int64_t offset = time_stamp (pos);
if (m_offset_time) {
offset -= AV_TIME_BASE;
if (offset < m_format_context->start_time) {
offset = 0;
}
}
avcodec_flush_buffers (m_codec_context);
if (av_seek_frame (m_format_context, -1, offset, AVSEEK_FLAG_BACKWARD) < 0) {
return false;
}
return true;
}
int64_t
FFmpegInput::time_stamp(int pos) const
{
int64_t timestamp = static_cast<int64_t>((static_cast<double> (pos) / fps()) * AV_TIME_BASE);
if (static_cast<uint64_t> (m_format_context->start_time) != AV_NOPTS_VALUE) {
timestamp += m_format_context->start_time;
}
return timestamp;
}
double
FFmpegInput::fps() const
{
if (m_frame_rate.den) {
return m_frame_rate.num / static_cast<double> (m_frame_rate.den);
}
return 1.0f;
}
OIIO_PLUGIN_NAMESPACE_END
<commit_msg>Fix -Werror=sign-compare<commit_after>/*
Copyright 2014 Larry Gritz and the other authors and contributors.
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 software's owners 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.
(This is the Modified BSD License)
*/
extern "C" { // ffmpeg is a C api
#include <errno.h>
#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}
#include <boost/shared_ptr.hpp>
#include <boost/thread/once.hpp>
#include "OpenImageIO/imageio.h"
OIIO_PLUGIN_NAMESPACE_BEGIN
class FFmpegInput : public ImageInput {
public:
FFmpegInput ();
virtual ~FFmpegInput();
virtual const char *format_name (void) const { return "FFmpeg movie"; }
virtual bool open (const std::string &name, ImageSpec &spec);
virtual bool close (void);
virtual int current_subimage (void) const { return m_subimage; }
virtual bool seek_subimage (int subimage, int miplevel, ImageSpec &newspec);
virtual bool read_native_scanline (int y, int z, void *data);
void read_frame(int pos);
#if 0
const char *metadata (const char * key);
bool has_metadata (const char * key);
#endif
bool seek (int pos);
double fps() const;
int64_t time_stamp(int pos) const;
private:
std::string m_filename;
int m_subimage;
int m_nsubimages;
AVFormatContext * m_format_context;
AVCodecContext * m_codec_context;
AVCodec *m_codec;
AVFrame *m_frame;
AVFrame *m_rgb_frame;
SwsContext *m_sws_rgb_context;
AVRational m_frame_rate;
std::vector<uint8_t> m_rgb_buffer;
std::vector<int> m_video_indexes;
int m_video_stream;
int m_frames;
int m_last_search_pos;
int m_last_decoded_pos;
bool m_offset_time;
bool m_read_frame;
// init to initialize state
void init (void) {
m_filename.clear ();
m_format_context = 0;
m_codec_context = 0;
m_codec = 0;
m_frame = 0;
m_rgb_frame = 0;
m_sws_rgb_context = 0;
m_rgb_buffer.clear();
m_video_indexes.clear();
m_video_stream = -1;
m_frames = 0;
m_last_search_pos = 0;
m_last_decoded_pos = 0;
m_offset_time = true;
m_read_frame = false;
}
};
// Obligatory material to make this a recognizeable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT int ffmpeg_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT ImageInput *ffmpeg_input_imageio_create () {
return new FFmpegInput;
}
// FFmpeg hints:
// AVI (Audio Video Interleaved)
// QuickTime / MOV
// raw MPEG-4 video
// MPEG-1 Systems / MPEG program stream
OIIO_EXPORT const char *ffmpeg_input_extensions[] = {
"avi", "mov", "qt", "mp4", "m4a", "3gp", "3g2", "mj2", "m4v", "mpg", NULL
};
OIIO_PLUGIN_EXPORTS_END
FFmpegInput::FFmpegInput ()
{
init();
}
FFmpegInput::~FFmpegInput()
{
close();
}
bool
FFmpegInput::open (const std::string &name, ImageSpec &spec)
{
static boost::once_flag init_flag = BOOST_ONCE_INIT;
boost::call_once (&av_register_all, init_flag);
const char *file_name = name.c_str();
av_log_set_level (AV_LOG_FATAL);
if (avformat_open_input (&m_format_context, file_name, NULL, NULL) != 0) // avformat_open_input allocs format_context
{
error ("\"%s\" could not open input", file_name);
return false;
}
if (avformat_find_stream_info (m_format_context, NULL) < 0)
{
error ("\"%s\" could not find stream info", file_name);
return false;
}
m_video_stream = -1;
for (unsigned int i=0; i<m_format_context->nb_streams; i++) {
if (m_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
if (m_video_stream < 0) {
m_video_stream=i;
}
m_video_indexes.push_back (i); // needed for later use
break;
}
}
if (m_video_stream == -1) {
error ("\"%s\" could not find a valid videostream", file_name);
return false;
}
m_codec_context = m_format_context->streams[m_video_stream]->codec; // codec context for videostream
m_codec = avcodec_find_decoder (m_codec_context->codec_id);
if (!m_codec) {
error ("\"%s\" unsupported codec", file_name);
return false;
}
if (avcodec_open2 (m_codec_context, m_codec, NULL) < 0) {
error ("\"%s\" could not open codec", file_name);
return false;
}
if (!strcmp (m_codec_context->codec->name, "mjpeg") ||
!strcmp (m_codec_context->codec->name, "dvvideo")) {
m_offset_time = false;
}
AVStream *stream = m_format_context->streams[m_video_stream];
if (stream->r_frame_rate.num != 0 && stream->r_frame_rate.den != 0) {
m_frame_rate = stream->r_frame_rate;
}
if (static_cast<int64_t> (m_format_context->duration) != AV_NOPTS_VALUE) {
m_frames = static_cast<uint64_t> ((fps() * static_cast<double>(m_format_context->duration) /
static_cast<uint64_t>(AV_TIME_BASE)));
} else {
m_frames = 1 << 29;
}
AVPacket pkt;
if (!m_frames) {
seek (0);
av_init_packet (&pkt);
av_read_frame (m_format_context, &pkt);
uint64_t first_pts = pkt.pts;
uint64_t max_pts = first_pts;
seek (1 << 29);
av_init_packet (&pkt);
while (stream && av_read_frame (m_format_context, &pkt) >= 0) {
uint64_t current_pts = static_cast<uint64_t> (av_q2d(stream->time_base) * (pkt.pts - first_pts) * fps());
if (current_pts > max_pts) {
max_pts = current_pts;
}
}
m_frames = max_pts;
}
m_frame = av_frame_alloc();
m_rgb_frame = av_frame_alloc();
m_rgb_buffer.resize(
avpicture_get_size (PIX_FMT_RGB24,
m_codec_context->width,
m_codec_context->height),
0
);
AVPixelFormat pixFormat;
switch (m_codec_context->pix_fmt) { // deprecation warning for YUV formats
case AV_PIX_FMT_YUVJ420P:
pixFormat = AV_PIX_FMT_YUV420P;
break;
case AV_PIX_FMT_YUVJ422P:
pixFormat = AV_PIX_FMT_YUV422P;
break;
case AV_PIX_FMT_YUVJ444P:
pixFormat = AV_PIX_FMT_YUV444P;
break;
case AV_PIX_FMT_YUVJ440P:
pixFormat = AV_PIX_FMT_YUV440P;
default:
pixFormat = m_codec_context->pix_fmt;
break;
}
m_sws_rgb_context = sws_getContext(
m_codec_context->width,
m_codec_context->height,
pixFormat,
m_codec_context->width,
m_codec_context->height,
PIX_FMT_RGB24,
SWS_AREA,
NULL,
NULL,
NULL
);
m_spec = ImageSpec (m_codec_context->width, m_codec_context->height, 3, TypeDesc::UINT8);
AVDictionaryEntry *tag = NULL;
while ((tag = av_dict_get (m_format_context->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
m_spec.attribute (tag->key, tag->value);
}
m_spec.attribute ("fps", m_frame_rate.num / static_cast<float> (m_frame_rate.den));
m_spec.attribute ("oiio:Movie", true);
m_nsubimages = m_frames;
spec = m_spec;
return true;
}
bool
FFmpegInput::seek_subimage (int subimage, int miplevel, ImageSpec &newspec)
{
if (subimage < 0 || subimage >= m_nsubimages || miplevel > 0) {
return false;
}
if (subimage == m_subimage) {
newspec = m_spec;
return true;
}
newspec = m_spec;
m_subimage = subimage;
m_read_frame = false;
return true;
}
bool
FFmpegInput::read_native_scanline (int y, int z, void *data)
{
if (!m_read_frame) {
read_frame (m_subimage);
}
memcpy (data, m_rgb_frame->data[0] + y * m_rgb_frame->linesize[0], m_spec.width*3);
return true;
}
bool
FFmpegInput::close (void)
{
avcodec_close (m_codec_context);
avformat_close_input (&m_format_context);
av_free (m_format_context); // will free m_codec and m_codec_context
av_frame_free (&m_frame); // free after close input
av_frame_free (&m_rgb_frame);
sws_freeContext (m_sws_rgb_context);
init ();
return true;
}
void
FFmpegInput::read_frame(int pos)
{
if (m_last_decoded_pos + 1 != m_subimage) {
seek (0);
seek (m_subimage);
}
AVPacket pkt;
int finished = 0;
while (av_read_frame (m_format_context, &pkt) >=0) {
if (pkt.stream_index == m_video_stream) {
double pts = 0;
if (static_cast<int64_t> (pkt.dts) != AV_NOPTS_VALUE) {
pts = av_q2d (m_format_context->streams[m_video_stream]->time_base) * pkt.dts;
}
int current_pos = int(pts * fps() + 0.5f);
if (current_pos == m_last_search_pos) {
current_pos = m_last_search_pos + 1;
}
m_last_search_pos = current_pos;
if (static_cast<int64_t> (m_format_context->start_time) != AV_NOPTS_VALUE) {
current_pos -= static_cast<int> (m_format_context->start_time * fps() / AV_TIME_BASE);
}
if (current_pos >= m_subimage) {
avcodec_decode_video2 (m_codec_context, m_frame, &finished, &pkt);
}
if(finished)
{
avpicture_fill
(
reinterpret_cast<AVPicture*>(m_rgb_frame),
&m_rgb_buffer[0],
PIX_FMT_RGB24,
m_codec_context->width,
m_codec_context->height
);
sws_scale
(
m_sws_rgb_context,
static_cast<uint8_t const * const *> (m_frame->data),
m_frame->linesize,
0,
m_codec_context->height,
m_rgb_frame->data,
m_rgb_frame->linesize
);
m_last_decoded_pos = m_last_search_pos;
av_free_packet (&pkt);
break;
}
}
av_free_packet (&pkt);
}
m_read_frame = true;
}
#if 0
const char *
FFmpegInput::metadata (const char * key)
{
AVDictionaryEntry * entry = av_dict_get (m_format_context->metadata, key, NULL, 0);
return entry ? av_strdup(entry->value) : NULL;
// FIXME -- that looks suspiciously like a memory leak
}
bool
FFmpegInput::has_metadata (const char * key)
{
return av_dict_get (m_format_context->metadata, key, NULL, 0); // is there a better to check exists?
}
#endif
bool
FFmpegInput::seek (int pos)
{
int64_t offset = time_stamp (pos);
if (m_offset_time) {
offset -= AV_TIME_BASE;
if (offset < m_format_context->start_time) {
offset = 0;
}
}
avcodec_flush_buffers (m_codec_context);
if (av_seek_frame (m_format_context, -1, offset, AVSEEK_FLAG_BACKWARD) < 0) {
return false;
}
return true;
}
int64_t
FFmpegInput::time_stamp(int pos) const
{
int64_t timestamp = static_cast<int64_t>((static_cast<double> (pos) / fps()) * AV_TIME_BASE);
if (static_cast<int64_t> (m_format_context->start_time) != AV_NOPTS_VALUE) {
timestamp += m_format_context->start_time;
}
return timestamp;
}
double
FFmpegInput::fps() const
{
if (m_frame_rate.den) {
return m_frame_rate.num / static_cast<double> (m_frame_rate.den);
}
return 1.0f;
}
OIIO_PLUGIN_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2014 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "action_header.h"
namespace
{
struct SUsed
{
SUsed(void):used(0) {}
SUsed(const std::wstring &pTdate_full, const std::wstring &pTdate, double pUsed): tdate_full(pTdate_full), tdate(pTdate), used(pUsed) {}
std::wstring tdate_full;
std::wstring tdate;
double used;
};
}
ACTION_IMPL(usagegraph)
{
Helper helper(tid, &GET, &PARAMS);
IDatabase *db=helper.getDatabase();
int clientid=-1;
std::wstring s_clientid=GET[L"clientid"];
if(!s_clientid.empty())
{
IQuery *q=db->Prepare("SELECT id,name FROM clients WHERE id=?");
q->Bind(s_clientid);
db_results res=q->Read();
q->Reset();
if(!res.empty())
{
clientid=watoi(res[0][L"id"]);
}
}
std::string rights=helper.getRights("piegraph");
bool client_id_found=false;
if(rights!="all" && rights!="none" )
{
std::vector<int> v_clientid;
std::vector<std::string> s_clientid;
Tokenize(rights, s_clientid, ",");
for(size_t i=0;i<s_clientid.size();++i)
{
v_clientid.push_back(atoi(s_clientid[i].c_str()));
}
if(clientid!=-1)
{
for(size_t i=0;i<v_clientid.size();++i)
{
if(clientid==v_clientid[i])
{
client_id_found=true;
break;
}
}
}
}
JSON::Object ret;
SUser *session=helper.getSession();
if(session!=NULL && session->id==-1) return;
if(session!=NULL &&
( ( clientid==-1 && helper.getRights("piegraph")=="all" ) || ( clientid!=-1 && (client_id_found || rights=="all") ) )
)
{
helper.releaseAll();
std::string scale = wnarrow(GET[L"scale"]);
if(scale.empty())
{
scale="d";
}
std::string t_where=" 0=0";
if(clientid!=-1)
{
t_where+=" AND id="+nconvert(clientid)+" ";
}
int c_lim=1;
if(clientid==-1)
{
IQuery *q_count_clients=db->Prepare("SELECT count(*) AS c FROM clients");
db_results res_c=q_count_clients->Read();
q_count_clients->Reset();
if(!res_c.empty())
c_lim=watoi(res_c[0][L"c"]);
}
unsigned int n_items;
std::string back;
std::string date_fmt;
if(scale=="y")
{
back="-10 year";
n_items=10;
date_fmt="%Y";
}
else if(scale=="m")
{
back="-1 year";
n_items=12;
date_fmt="%Y-%m";
}
else
{
back="-1 month";
n_items=31;
date_fmt="%Y-%m-%d";
}
db_results cache_res;
if(db->getEngineName()=="sqlite")
{
cache_res=db->Read("PRAGMA cache_size");
ServerSettings server_settings(db);
db->Write("PRAGMA cache_size = -51200"); //50MB
}
IQuery *q=db->Prepare("SELECT id, (MAX(b.bytes_used_files)+MAX(b.bytes_used_images)) AS used, strftime('"+date_fmt+"', MAX(b.created), 'localtime') AS tdate, strftime('%Y-%m-%d', MAX(b.created), 'localtime') AS tdate_full "
"FROM "
"("
"SELECT MAX(created) AS mcreated "
"FROM "
"(SELECT * FROM clients_hist WHERE "+t_where+" AND created>date('now','"+back+"') ) "
"GROUP BY strftime('"+date_fmt+"', created, 'localtime'), id "
"HAVING mcreated>date('now','"+back+"') "
"ORDER BY mcreated DESC "
"LIMIT "+nconvert(c_lim*(n_items*2))+" "
") a "
"INNER JOIN clients_hist b ON a.mcreated=b.created WHERE "+t_where+" AND b.created>date('now','"+back+"') "
"GROUP BY strftime('"+date_fmt+"', b.created, 'localtime'), id "
"ORDER BY b.created DESC");
db_results res=q->Read();
std::vector<SUsed > used;
for(size_t i=0;i<res.size();++i)
{
bool found=false;
for(size_t j=0;j<used.size();++j)
{
if(used[j].tdate==res[i][L"tdate"])
{
found=true;
used[j].used+=atof(wnarrow(res[i][L"used"]).c_str());
}
}
if(!found && used.size()<n_items)
{
used.push_back(SUsed(res[i][L"tdate_full"], res[i][L"tdate"], atof(wnarrow(res[i][L"used"]).c_str()) ) );
}
}
if(!cache_res.empty())
{
db->Write("PRAGMA cache_size = "+wnarrow(cache_res[0][L"cache_size"]));
}
bool size_gb=false;
for(size_t i=0;i<used.size();++i)
{
if(used[i].used>1024*1024*1024)
size_gb=true;
}
JSON::Array data;
for(int i=(int)used.size()-1;i>=0;--i)
{
double size=used[i].used;
if(size_gb)
{
size/=1024*1024*1024;
}
else
{
size/=1024*1024;
}
JSON::Object obj;
obj.set("xlabel", Server->ConvertToUTF8(used[i].tdate_full));
obj.set("data", (float)size);
data.add(obj);
}
ret.set("data", data);
if(size_gb)
ret.set("ylabel", "GB");
else
ret.set("ylabel", "MB");
helper.update(tid, &GET, &PARAMS);
}
else
{
ret.set("error", 1);
}
helper.Write(ret.get(false));
}
#endif //CLIENT_ONLY<commit_msg>Larger cache size for usage graph<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011-2014 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#ifndef CLIENT_ONLY
#include "action_header.h"
namespace
{
struct SUsed
{
SUsed(void):used(0) {}
SUsed(const std::wstring &pTdate_full, const std::wstring &pTdate, double pUsed): tdate_full(pTdate_full), tdate(pTdate), used(pUsed) {}
std::wstring tdate_full;
std::wstring tdate;
double used;
};
}
ACTION_IMPL(usagegraph)
{
Helper helper(tid, &GET, &PARAMS);
IDatabase *db=helper.getDatabase();
int clientid=-1;
std::wstring s_clientid=GET[L"clientid"];
if(!s_clientid.empty())
{
IQuery *q=db->Prepare("SELECT id,name FROM clients WHERE id=?");
q->Bind(s_clientid);
db_results res=q->Read();
q->Reset();
if(!res.empty())
{
clientid=watoi(res[0][L"id"]);
}
}
std::string rights=helper.getRights("piegraph");
bool client_id_found=false;
if(rights!="all" && rights!="none" )
{
std::vector<int> v_clientid;
std::vector<std::string> s_clientid;
Tokenize(rights, s_clientid, ",");
for(size_t i=0;i<s_clientid.size();++i)
{
v_clientid.push_back(atoi(s_clientid[i].c_str()));
}
if(clientid!=-1)
{
for(size_t i=0;i<v_clientid.size();++i)
{
if(clientid==v_clientid[i])
{
client_id_found=true;
break;
}
}
}
}
JSON::Object ret;
SUser *session=helper.getSession();
if(session!=NULL && session->id==-1) return;
if(session!=NULL &&
( ( clientid==-1 && helper.getRights("piegraph")=="all" ) || ( clientid!=-1 && (client_id_found || rights=="all") ) )
)
{
helper.releaseAll();
std::string scale = wnarrow(GET[L"scale"]);
if(scale.empty())
{
scale="d";
}
std::string t_where=" 0=0";
if(clientid!=-1)
{
t_where+=" AND id="+nconvert(clientid)+" ";
}
int c_lim=1;
if(clientid==-1)
{
IQuery *q_count_clients=db->Prepare("SELECT count(*) AS c FROM clients");
db_results res_c=q_count_clients->Read();
q_count_clients->Reset();
if(!res_c.empty())
c_lim=watoi(res_c[0][L"c"]);
}
unsigned int n_items;
std::string back;
std::string date_fmt;
if(scale=="y")
{
back="-10 year";
n_items=10;
date_fmt="%Y";
}
else if(scale=="m")
{
back="-1 year";
n_items=12;
date_fmt="%Y-%m";
}
else
{
back="-1 month";
n_items=31;
date_fmt="%Y-%m-%d";
}
db_results cache_res;
if(db->getEngineName()=="sqlite")
{
cache_res=db->Read("PRAGMA cache_size");
db->Write("PRAGMA cache_size = -51200"); //50MB
}
IQuery *q=db->Prepare("SELECT id, (MAX(b.bytes_used_files)+MAX(b.bytes_used_images)) AS used, strftime('"+date_fmt+"', MAX(b.created), 'localtime') AS tdate, strftime('%Y-%m-%d', MAX(b.created), 'localtime') AS tdate_full "
"FROM "
"("
"SELECT MAX(created) AS mcreated "
"FROM "
"(SELECT * FROM clients_hist WHERE "+t_where+" AND created>date('now','"+back+"') ) "
"GROUP BY strftime('"+date_fmt+"', created, 'localtime'), id "
"HAVING mcreated>date('now','"+back+"') "
"ORDER BY mcreated DESC "
"LIMIT "+nconvert(c_lim*(n_items*2))+" "
") a "
"INNER JOIN clients_hist b ON a.mcreated=b.created WHERE "+t_where+" AND b.created>date('now','"+back+"') "
"GROUP BY strftime('"+date_fmt+"', b.created, 'localtime'), id "
"ORDER BY b.created DESC");
db_results res=q->Read();
std::vector<SUsed > used;
for(size_t i=0;i<res.size();++i)
{
bool found=false;
for(size_t j=0;j<used.size();++j)
{
if(used[j].tdate==res[i][L"tdate"])
{
found=true;
used[j].used+=atof(wnarrow(res[i][L"used"]).c_str());
}
}
if(!found && used.size()<n_items)
{
used.push_back(SUsed(res[i][L"tdate_full"], res[i][L"tdate"], atof(wnarrow(res[i][L"used"]).c_str()) ) );
}
}
if(!cache_res.empty())
{
db->Write("PRAGMA cache_size = "+wnarrow(cache_res[0][L"cache_size"]));
}
bool size_gb=false;
for(size_t i=0;i<used.size();++i)
{
if(used[i].used>1024*1024*1024)
size_gb=true;
}
JSON::Array data;
for(int i=(int)used.size()-1;i>=0;--i)
{
double size=used[i].used;
if(size_gb)
{
size/=1024*1024*1024;
}
else
{
size/=1024*1024;
}
JSON::Object obj;
obj.set("xlabel", Server->ConvertToUTF8(used[i].tdate_full));
obj.set("data", (float)size);
data.add(obj);
}
ret.set("data", data);
if(size_gb)
ret.set("ylabel", "GB");
else
ret.set("ylabel", "MB");
helper.update(tid, &GET, &PARAMS);
}
else
{
ret.set("error", 1);
}
helper.Write(ret.get(false));
}
#endif //CLIENT_ONLY<|endoftext|>
|
<commit_before>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "analysisresult.h"
#include "deblineanalyzer.h"
#include "streamendanalyzer.h"
#include "strigiconfig.h"
#include "fieldtypes.h"
#include <iostream>
using namespace Strigi;
using namespace std;
const string DebLineAnalyzerFactory::nameFieldName("software.name");
const string DebLineAnalyzerFactory::versionFieldName("software.version");
const string DebLineAnalyzerFactory::summaryFieldName("content.description");
const string DebLineAnalyzerFactory::maintainerFieldName("software.maintainer");
const string DebLineAnalyzerFactory::sectionFieldName("software.section");
const string DebLineAnalyzerFactory::dependsFieldName("software.depends");
void
DebLineAnalyzerFactory::registerFields(FieldRegister& r) {
nameField = r.registerField(nameFieldName, FieldRegister::stringType,
1, 0);
versionField = r.registerField(versionFieldName, FieldRegister::stringType,
1, 0);
summaryField = r.registerField(summaryFieldName, FieldRegister::stringType,
1, 0);
maintainerField = r.registerField(maintainerFieldName, FieldRegister::stringType,
1, 0);
sectionField = r.registerField(sectionFieldName, FieldRegister::stringType,
1, 0);
dependsField = r.registerField(dependsFieldName, FieldRegister::stringType,
0, 0);
}
void
DebLineAnalyzer::startAnalysis(AnalysisResult* res)
{
// let's assume that it is not .deb file and set isReadyWithStream() to true
finished=6;
if (res->fileName()!="control") return;
res=res->parent();
if (!res) return;
if (res->fileName()!="control.tar.gz") return;
res=res->parent();
if (!res) return;
if (strcmp(res->endAnalyzer()->name(),"ArEndAnalyzer")) return ;
// it is .deb file after all
result=res;
finished=0;
}
void
DebLineAnalyzer::handleLine(const char* data, uint32_t length)
{
std::string line(data,length);
if (line.find("Package: ",0)==0) { result->addValue(factory->nameField, line.substr(9,line.size())); finished++; }
if (line.find("Description: ",0)==0) { result->addValue(factory->summaryField, line.substr(13,line.size())); finished++; }
if (line.find("Version: ")==0) { result->addValue(factory->versionField, line.substr(9,line.size())); finished++; }
if (line.find("Maintainer: ")==0) { result->addValue(factory->maintainerField, line.substr(12,line.size())); finished++; }
if (line.find("Section: ")==0) { result->addValue(factory->sectionField, line.substr(9,line.size())); finished++; }
if (line.find("Depends: ")==0) {
unsigned int start=9;
unsigned int end;
do {
end=line.find(", ",start);
if (end==std::string::npos) end=length;
result->addValue(factory->dependsField, line.substr(start, end-start));
start=end+2;
} while (start<length);
finished++;
}
}
bool
DebLineAnalyzer::isReadyWithStream()
{
// analysis is finished after all 6 fields were found (name, summary, version, deps, maintainer, section)
return finished==6;
}
class Factory : public AnalyzerFactoryFactory {
public:
std::list<StreamLineAnalyzerFactory*>
streamLineAnalyzerFactories() const {
std::list<StreamLineAnalyzerFactory*> af;
af.push_back(new DebLineAnalyzerFactory());
return af;
}
};
STRIGI_ANALYZER_FACTORY(Factory)
<commit_msg>64 bit fix:<commit_after>/* This file is part of Strigi Desktop Search
*
* Copyright (C) 2006 Jos van den Oever <jos@vandenoever.info>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "analysisresult.h"
#include "deblineanalyzer.h"
#include "streamendanalyzer.h"
#include "strigiconfig.h"
#include "fieldtypes.h"
#include <iostream>
using namespace Strigi;
using namespace std;
const string DebLineAnalyzerFactory::nameFieldName("software.name");
const string DebLineAnalyzerFactory::versionFieldName("software.version");
const string DebLineAnalyzerFactory::summaryFieldName("content.description");
const string DebLineAnalyzerFactory::maintainerFieldName("software.maintainer");
const string DebLineAnalyzerFactory::sectionFieldName("software.section");
const string DebLineAnalyzerFactory::dependsFieldName("software.depends");
void
DebLineAnalyzerFactory::registerFields(FieldRegister& r) {
nameField = r.registerField(nameFieldName, FieldRegister::stringType,
1, 0);
versionField = r.registerField(versionFieldName, FieldRegister::stringType,
1, 0);
summaryField = r.registerField(summaryFieldName, FieldRegister::stringType,
1, 0);
maintainerField = r.registerField(maintainerFieldName, FieldRegister::stringType,
1, 0);
sectionField = r.registerField(sectionFieldName, FieldRegister::stringType,
1, 0);
dependsField = r.registerField(dependsFieldName, FieldRegister::stringType,
0, 0);
}
void
DebLineAnalyzer::startAnalysis(AnalysisResult* res)
{
// let's assume that it is not .deb file and set isReadyWithStream() to true
finished=6;
if (res->fileName()!="control") return;
res=res->parent();
if (!res) return;
if (res->fileName()!="control.tar.gz") return;
res=res->parent();
if (!res) return;
if (strcmp(res->endAnalyzer()->name(),"ArEndAnalyzer")) return ;
// it is .deb file after all
result=res;
finished=0;
}
void
DebLineAnalyzer::handleLine(const char* data, uint32_t length)
{
std::string line(data,length);
if (line.find("Package: ",0)==0) { result->addValue(factory->nameField, line.substr(9,line.size())); finished++; }
if (line.find("Description: ",0)==0) { result->addValue(factory->summaryField, line.substr(13,line.size())); finished++; }
if (line.find("Version: ")==0) { result->addValue(factory->versionField, line.substr(9,line.size())); finished++; }
if (line.find("Maintainer: ")==0) { result->addValue(factory->maintainerField, line.substr(12,line.size())); finished++; }
if (line.find("Section: ")==0) { result->addValue(factory->sectionField, line.substr(9,line.size())); finished++; }
if (line.find("Depends: ")==0) {
size_t start=9;
size_t end;
do {
end=line.find(", ",start);
if (end==std::string::npos) end=length;
result->addValue(factory->dependsField, line.substr(start, end-start));
start=end+2;
} while (start<length);
finished++;
}
}
bool
DebLineAnalyzer::isReadyWithStream()
{
// analysis is finished after all 6 fields were found (name, summary, version, deps, maintainer, section)
return finished==6;
}
class Factory : public AnalyzerFactoryFactory {
public:
std::list<StreamLineAnalyzerFactory*>
streamLineAnalyzerFactories() const {
std::list<StreamLineAnalyzerFactory*> af;
af.push_back(new DebLineAnalyzerFactory());
return af;
}
};
STRIGI_ANALYZER_FACTORY(Factory)
<|endoftext|>
|
<commit_before>// Copyright (C) 2016 xaizek <xaizek@openmailbox.org>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#ifndef UNCOV__FILEPRINTER_HPP__
#define UNCOV__FILEPRINTER_HPP__
#include <srchilite/sourcehighlight.h>
#include <srchilite/langmap.h>
#include <iosfwd>
#include <string>
#include <vector>
class FileComparator;
/**
* @brief FilePrinter-specific settings.
*/
class FilePrinterSettings
{
public:
/**
* @brief Enable polymorphic destruction.
*/
virtual ~FilePrinterSettings() = default;
public:
/**
* @brief Retrieves number of spaces that comprise a tabulation.
*
* @returns The number.
*/
virtual int getTabSize() const = 0;
/**
* @brief Retrieves information about availability of color processing.
*
* @returns @c true if output can be colorized, @c false otherwise.
*/
virtual bool isColorOutputAllowed() const = 0;
/**
* @brief Retrieves information about required output format.
*
* @returns @c true if output is HTML, @c false otherwise.
*/
virtual bool isHtmlOutput() const = 0;
};
class FilePrinter
{
public:
/**
* @brief Constructs an object performing some highlighting preparations.
*
* @param settings FilePrinter settings.
* @param allowColors Highlight source file.
*/
explicit FilePrinter(const FilePrinterSettings &settings,
bool allowColors = true);
public:
void print(std::ostream &os, const std::string &path,
const std::string &contents, const std::vector<int> &coverage,
bool leaveMissedOnly = false);
/**
* @brief Finds and prints differences between two versions of a file.
*
* Implements solution for longest common subsequence problem that matches
* modified finding of edit distance (substitution operation excluded) with
* backtracking afterward to compose result. Requires lots of memory for
* very big files.
*
* @param os Stream to print output to.
* @param path Name of the file (for highlighting detection).
* @param oText Old version of the file.
* @param oCov Coverage of old version.
* @param nText New version of the file.
* @param nCov Coverage of new version.
* @param comparator Object with loaded file diffing results.
*
* @note `oText.size() == oCov.size() && nText.size() == nCov.size()` is
* assumed.
*/
void printDiff(std::ostream &os, const std::string &path,
std::istream &oText, const std::vector<int> &oCov,
std::istream &nText, const std::vector<int> &nCov,
const FileComparator &comparator);
private:
std::string getLang(const std::string &path);
void highlight(std::stringstream &ss, std::istream &text,
const std::string &lang,
srchilite::LineRanges *ranges = nullptr);
private:
const bool colorizeOutput;
srchilite::SourceHighlight highlighter;
srchilite::LangMap langMap;
};
#endif // UNCOV__FILEPRINTER_HPP__
<commit_msg>Add missing documentation in FilePrinter.hpp<commit_after>// Copyright (C) 2016 xaizek <xaizek@openmailbox.org>
//
// This file is part of uncov.
//
// uncov 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.
//
// uncov 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 uncov. If not, see <http://www.gnu.org/licenses/>.
#ifndef UNCOV__FILEPRINTER_HPP__
#define UNCOV__FILEPRINTER_HPP__
#include <srchilite/sourcehighlight.h>
#include <srchilite/langmap.h>
#include <iosfwd>
#include <string>
#include <vector>
/**
* @file FilePrinter.hpp
*
* Implements printing files or their diffs annotated with coverage information.
*/
class FileComparator;
/**
* @brief FilePrinter-specific settings.
*/
class FilePrinterSettings
{
public:
/**
* @brief Enable polymorphic destruction.
*/
virtual ~FilePrinterSettings() = default;
public:
/**
* @brief Retrieves number of spaces that comprise a tabulation.
*
* @returns The number.
*/
virtual int getTabSize() const = 0;
/**
* @brief Retrieves information about availability of color processing.
*
* @returns @c true if output can be colorized, @c false otherwise.
*/
virtual bool isColorOutputAllowed() const = 0;
/**
* @brief Retrieves information about required output format.
*
* @returns @c true if output is HTML, @c false otherwise.
*/
virtual bool isHtmlOutput() const = 0;
};
/**
* @brief Prints highlighted files or their diffs annotated with coverage.
*/
class FilePrinter
{
public:
/**
* @brief Constructs an object performing some highlighting preparations.
*
* @param settings FilePrinter settings.
* @param allowColors Highlight source file.
*/
explicit FilePrinter(const FilePrinterSettings &settings,
bool allowColors = true);
public:
/**
* @brief Prints highlighted file with optional folding of covered lines.
*
* @param os Stream to print output to.
* @param path Name of the file (for highlighting detection).
* @param contents Contents of the file.
* @param coverage Coverage information per line of contents.
* @param leaveMissedOnly Fold lines which are covered or not relevant.
*
* @note @c coverage.size() should match lines in @p contents.
*/
void print(std::ostream &os, const std::string &path,
const std::string &contents, const std::vector<int> &coverage,
bool leaveMissedOnly = false);
/**
* @brief Finds and prints differences between two versions of a file.
*
* Implements solution for longest common subsequence problem that matches
* modified finding of edit distance (substitution operation excluded) with
* backtracking afterward to compose result. Requires lots of memory for
* very big files.
*
* @param os Stream to print output to.
* @param path Name of the file (for highlighting detection).
* @param oText Old version of the file.
* @param oCov Coverage of old version.
* @param nText New version of the file.
* @param nCov Coverage of new version.
* @param comparator Object with loaded file diffing results.
*
* @note `oText.size() == oCov.size() && nText.size() == nCov.size()` is
* assumed.
*/
void printDiff(std::ostream &os, const std::string &path,
std::istream &oText, const std::vector<int> &oCov,
std::istream &nText, const std::vector<int> &nCov,
const FileComparator &comparator);
private:
/**
* @brief Derives language from path.
*
* @param path Path to analyze.
*
* @returns Determined language.
*/
std::string getLang(const std::string &path);
/**
* @brief Highlights source code.
*
* @param ss Stream for highlighted output.
* @param text Code to highlight.
* @param lang Language in which the code is written.
* @param ranges Ranges of lines to be highlighted.
*/
void highlight(std::stringstream &ss, std::istream &text,
const std::string &lang,
srchilite::LineRanges *ranges = nullptr);
private:
//! Whether code highlighting is enabled.
const bool colorizeOutput;
//! Code highlighting object.
srchilite::SourceHighlight highlighter;
//! Loaded language map.
srchilite::LangMap langMap;
};
#endif // UNCOV__FILEPRINTER_HPP__
<|endoftext|>
|
<commit_before>#ifndef MISC_UI_HPP
#define MISC_UI_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include <map>
#include <utility>
#include "Settings.hpp"
#include "Log.hpp"
#include "Point.hpp"
/// Macro to build std::wstring that slic3r::log expects using << syntax of wxString
/// Avoids wx pollution of libslic3r
#define LOG_WSTRING(...) ((wxString("") << __VA_ARGS__).ToStdWstring())
/// Common static (that is, free-standing) functions, not part of an object hierarchy.
namespace Slic3r { namespace GUI {
enum class OS { Linux, Mac, Windows } ;
// constants to reduce the proliferation of macros in the rest of the code
#ifdef __WIN32
constexpr OS the_os = OS::Windows;
#elif __APPLE__
constexpr OS the_os = OS::Mac;
#elif __linux__
constexpr OS the_os = OS::Linux;
#ifdef __WXGTK__
constexpr bool wxGTK {true};
#else
constexpr bool wxGTK {false};
#endif
#endif
#ifdef SLIC3R_DEV
constexpr bool isDev = true;
#else
constexpr bool isDev = false;
#endif
constexpr bool threaded = false;
// hopefully the compiler is smart enough to figure this out
const std::map<const std::string, const std::string> FILE_WILDCARDS {
std::make_pair("known", "Known files (*.stl, *.obj, *.amf, *.xml, *.3mf)|*.3mf;*.3MF;*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("stl", "STL files (*.stl)|*.stl;*.STL"),
std::make_pair("obj", "OBJ files (*.obj)|*.obj;*.OBJ"),
std::make_pair("amf", "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("tmf", "3MF files (*.3mf)|*.3mf;*.3MF"),
std::make_pair("ini", "INI files *.ini|*.ini;*.INI"),
std::make_pair("gcode", "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC"),
std::make_pair("svg", "SVG files *.svg|*.svg;*.SVG")
};
const std::string MODEL_WILDCARD { FILE_WILDCARDS.at("known") + std::string("|") + FILE_WILDCARDS.at("stl")+ std::string("|") + FILE_WILDCARDS.at("obj") + std::string("|") + FILE_WILDCARDS.at("amf")+ std::string("|") + FILE_WILDCARDS.at("tmf")};
const std::string STL_MODEL_WILDCARD { FILE_WILDCARDS.at("stl") };
const std::string AMF_MODEL_WILDCARD { FILE_WILDCARDS.at("amf") };
const std::string TMF_MODEL_WILDCARD { FILE_WILDCARDS.at("tmf") };
/// Mostly useful for Linux distro maintainers, this will change where Slic3r assumes
/// its ./var directory lives (where its art assets are).
/// Define VAR_ABS and VAR_ABS_PATH
#ifndef VAR_ABS
#define VAR_ABS false
#else
#define VAR_ABS true
#endif
#ifndef VAR_ABS_PATH
#define VAR_ABS_PATH "/usr/share/Slic3r/var"
#endif
#ifndef VAR_REL // Redefine on compile
#define VAR_REL L"/../var"
#endif
/// Performs a check via the Internet for a new version of Slic3r.
/// If this version of Slic3r was compiled with -DSLIC3R_DEV, check the development
/// space instead of release.
void check_version(bool manual = false);
/// Provides a path to Slic3r's var dir.
const wxString var(const wxString& in);
/// Provide a path to where Slic3r exec'd from.
const wxString bin();
/// Always returns path to home directory.
const wxString home(const wxString& in = "Slic3r");
/// Shows an error messagebox
void show_error(wxWindow* parent, const wxString& message);
/// Shows an info messagebox.
void show_info(wxWindow* parent, const wxString& message, const wxString& title);
/// Show an error messagebox and then throw an exception.
void fatal_error(wxWindow* parent, const wxString& message);
template <typename T>
void append_menu_item(wxMenu* menu, const wxString& name,const wxString& help, T lambda, int id = wxID_ANY, const wxString& icon = "", const wxString& accel = "") {
wxMenuItem* tmp = menu->Append(wxID_ANY, name, help);
wxAcceleratorEntry* a = new wxAcceleratorEntry();
if (!accel.IsEmpty()) {
a->FromString(accel);
tmp->SetAccel(a); // set the accelerator if and only if the accelerator is fine
}
tmp->SetHelp(help);
if (!icon.IsEmpty()) {
wxBitmap ico;
if(ico.LoadFile(var(icon), wxBITMAP_TYPE_PNG))
tmp->SetBitmap(ico);
else
std::cerr<< var(icon) << " failed to load \n";
}
if (typeid(lambda) != typeid(nullptr))
menu->Bind(wxEVT_MENU, lambda, tmp->GetId(), tmp->GetId());
}
/*
sub CallAfter {
my ($self, $cb) = @_;
push @cb, $cb;
}
*/
wxString decode_path(const wxString& in);
wxString encode_path(const wxString& in);
std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top);
inline Slic3r::Point new_scale(const wxPoint& p) { return Slic3r::Point::new_scale(p.x, p.y); }
}} // namespace Slic3r::GUI
#endif // MISC_UI_HPP
<commit_msg>Define wxGTK as false under win32 or osx<commit_after>#ifndef MISC_UI_HPP
#define MISC_UI_HPP
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/filename.h>
#include <wx/stdpaths.h>
#include <map>
#include <utility>
#include "Settings.hpp"
#include "Log.hpp"
#include "Point.hpp"
/// Macro to build std::wstring that slic3r::log expects using << syntax of wxString
/// Avoids wx pollution of libslic3r
#define LOG_WSTRING(...) ((wxString("") << __VA_ARGS__).ToStdWstring())
/// Common static (that is, free-standing) functions, not part of an object hierarchy.
namespace Slic3r { namespace GUI {
enum class OS { Linux, Mac, Windows } ;
// constants to reduce the proliferation of macros in the rest of the code
#ifdef __WIN32
constexpr OS the_os = OS::Windows;
constexpr bool wxGTK {false};
#elif __APPLE__
constexpr OS the_os = OS::Mac;
constexpr bool wxGTK {false};
#elif __linux__
constexpr OS the_os = OS::Linux;
#ifdef __WXGTK__
constexpr bool wxGTK {true};
#else
constexpr bool wxGTK {false};
#endif
#endif
#ifdef SLIC3R_DEV
constexpr bool isDev = true;
#else
constexpr bool isDev = false;
#endif
constexpr bool threaded = false;
// hopefully the compiler is smart enough to figure this out
const std::map<const std::string, const std::string> FILE_WILDCARDS {
std::make_pair("known", "Known files (*.stl, *.obj, *.amf, *.xml, *.3mf)|*.3mf;*.3MF;*.stl;*.STL;*.obj;*.OBJ;*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("stl", "STL files (*.stl)|*.stl;*.STL"),
std::make_pair("obj", "OBJ files (*.obj)|*.obj;*.OBJ"),
std::make_pair("amf", "AMF files (*.amf)|*.amf;*.AMF;*.xml;*.XML"),
std::make_pair("tmf", "3MF files (*.3mf)|*.3mf;*.3MF"),
std::make_pair("ini", "INI files *.ini|*.ini;*.INI"),
std::make_pair("gcode", "G-code files (*.gcode, *.gco, *.g, *.ngc)|*.gcode;*.GCODE;*.gco;*.GCO;*.g;*.G;*.ngc;*.NGC"),
std::make_pair("svg", "SVG files *.svg|*.svg;*.SVG")
};
const std::string MODEL_WILDCARD { FILE_WILDCARDS.at("known") + std::string("|") + FILE_WILDCARDS.at("stl")+ std::string("|") + FILE_WILDCARDS.at("obj") + std::string("|") + FILE_WILDCARDS.at("amf")+ std::string("|") + FILE_WILDCARDS.at("tmf")};
const std::string STL_MODEL_WILDCARD { FILE_WILDCARDS.at("stl") };
const std::string AMF_MODEL_WILDCARD { FILE_WILDCARDS.at("amf") };
const std::string TMF_MODEL_WILDCARD { FILE_WILDCARDS.at("tmf") };
/// Mostly useful for Linux distro maintainers, this will change where Slic3r assumes
/// its ./var directory lives (where its art assets are).
/// Define VAR_ABS and VAR_ABS_PATH
#ifndef VAR_ABS
#define VAR_ABS false
#else
#define VAR_ABS true
#endif
#ifndef VAR_ABS_PATH
#define VAR_ABS_PATH "/usr/share/Slic3r/var"
#endif
#ifndef VAR_REL // Redefine on compile
#define VAR_REL L"/../var"
#endif
/// Performs a check via the Internet for a new version of Slic3r.
/// If this version of Slic3r was compiled with -DSLIC3R_DEV, check the development
/// space instead of release.
void check_version(bool manual = false);
/// Provides a path to Slic3r's var dir.
const wxString var(const wxString& in);
/// Provide a path to where Slic3r exec'd from.
const wxString bin();
/// Always returns path to home directory.
const wxString home(const wxString& in = "Slic3r");
/// Shows an error messagebox
void show_error(wxWindow* parent, const wxString& message);
/// Shows an info messagebox.
void show_info(wxWindow* parent, const wxString& message, const wxString& title);
/// Show an error messagebox and then throw an exception.
void fatal_error(wxWindow* parent, const wxString& message);
template <typename T>
void append_menu_item(wxMenu* menu, const wxString& name,const wxString& help, T lambda, int id = wxID_ANY, const wxString& icon = "", const wxString& accel = "") {
wxMenuItem* tmp = menu->Append(wxID_ANY, name, help);
wxAcceleratorEntry* a = new wxAcceleratorEntry();
if (!accel.IsEmpty()) {
a->FromString(accel);
tmp->SetAccel(a); // set the accelerator if and only if the accelerator is fine
}
tmp->SetHelp(help);
if (!icon.IsEmpty()) {
wxBitmap ico;
if(ico.LoadFile(var(icon), wxBITMAP_TYPE_PNG))
tmp->SetBitmap(ico);
else
std::cerr<< var(icon) << " failed to load \n";
}
if (typeid(lambda) != typeid(nullptr))
menu->Bind(wxEVT_MENU, lambda, tmp->GetId(), tmp->GetId());
}
/*
sub CallAfter {
my ($self, $cb) = @_;
push @cb, $cb;
}
*/
wxString decode_path(const wxString& in);
wxString encode_path(const wxString& in);
std::vector<wxString> open_model(wxWindow* parent, const Settings& settings, wxWindow* top);
inline Slic3r::Point new_scale(const wxPoint& p) { return Slic3r::Point::new_scale(p.x, p.y); }
}} // namespace Slic3r::GUI
#endif // MISC_UI_HPP
<|endoftext|>
|
<commit_before>#include "Game/Square.h"
#include <cmath>
#include <algorithm>
#include <cassert>
#include <cstddef>
//! The default constructor creates an invalid square location.
Square::Square() : square_file('\0'), square_rank(0)
{
}
//! This constructor creates a user-defined square.
Square::Square(char file_in, int rank_in) : square_file(file_in), square_rank(rank_in)
{
}
//! Creates a square from an index given by Board::square_index().
Square::Square(size_t index) : square_file('a' + index/8), square_rank(1 + index%8)
{
assert(index < 64);
}
//! The file of the square.
//! \returns The letter label of the square file.
char Square::file() const
{
return square_file;
}
//! The rank of the square.
//! \returns The numerical label of the rank.
int Square::rank() const
{
return square_rank;
}
//! Check if the square is valid.
//! \returns Whether the file and rank are zero (i.e., invalid).
Square::operator bool() const
{
return file() != '\0' && rank() != 0;
}
//! Check if two squares are the same.
//! \returns Whether two squares have the same file and rank.
bool operator==(const Square& a, const Square& b)
{
return (a.file() == b.file()) && (a.rank() == b.rank());
}
//! Check if two squares are not the same.
//! \returns Whether two squares differ in their file or rank.
bool operator!=(const Square& a, const Square& b)
{
return !(a == b);
}
<commit_msg>Make signed/unsigned conversion explicit<commit_after>#include "Game/Square.h"
#include <cmath>
#include <algorithm>
#include <cassert>
#include <cstddef>
//! The default constructor creates an invalid square location.
Square::Square() : square_file('\0'), square_rank(0)
{
}
//! This constructor creates a user-defined square.
Square::Square(char file_in, int rank_in) : square_file(file_in), square_rank(rank_in)
{
}
//! Creates a square from an index given by Board::square_index().
Square::Square(size_t index) : square_file(char('a' + index/8)), square_rank(1 + index%8)
{
assert(index < 64);
}
//! The file of the square.
//! \returns The letter label of the square file.
char Square::file() const
{
return square_file;
}
//! The rank of the square.
//! \returns The numerical label of the rank.
int Square::rank() const
{
return square_rank;
}
//! Check if the square is valid.
//! \returns Whether the file and rank are zero (i.e., invalid).
Square::operator bool() const
{
return file() != '\0' && rank() != 0;
}
//! Check if two squares are the same.
//! \returns Whether two squares have the same file and rank.
bool operator==(const Square& a, const Square& b)
{
return (a.file() == b.file()) && (a.rank() == b.rank());
}
//! Check if two squares are not the same.
//! \returns Whether two squares differ in their file or rank.
bool operator!=(const Square& a, const Square& b)
{
return !(a == b);
}
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 "InformationManagerDriver.h"
#include "NebulaLog.h"
#include "Nebula.h"
#include "NebulaUtil.h"
#include "VirtualMachineManagerDriver.h"
#include <sstream>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
InformationManagerDriver::InformationManagerDriver(
int userid,
const map<string,string>& attrs,
bool sudo,
HostPool * pool):
Mad(userid,attrs,sudo),hpool(pool)
{
dspool = Nebula::instance().get_dspool();
};
/* ************************************************************************** */
/* Driver ASCII Protocol Implementation */
/* ************************************************************************** */
void InformationManagerDriver::monitor(int oid,
const string& host,
const string& dsloc,
bool update) const
{
ostringstream os;
os << "MONITOR " << oid << " " << host << " " << dsloc << " " << update << endl;
write(os);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void InformationManagerDriver::protocol(const string& message) const
{
istringstream is(message);
//stores the action name
string action;
//stores the action result
string result;
//stores the action id of the associated HOST
int id;
ostringstream ess;
Host * host;
set<int> vm_ids;
string hinfo64;
string* hinfo;
// Parse the driver message
if ( is.good() )
{
is >> action >> ws;
}
else
{
goto error_parse;
}
if ( is.good() )
{
is >> result >> ws;
}
else
{
goto error_parse;
}
if ( is.good() )
{
is >> id >> ws;
}
else
{
goto error_parse;
}
// -----------------------
// Protocol implementation
// -----------------------
if ( action == "MONITOR" )
{
bool vm_poll;
set<int> lost;
map<int,string> found;
set<int> non_shared_ds;
map<int,const VectorAttribute*> datastores;
Template tmpl;
Datastore * ds;
map<int, const VectorAttribute*>::iterator itm;
int rc;
// ---------------------------------------------------------------------
// Get information from driver and decode from base64
// ---------------------------------------------------------------------
getline (is, hinfo64);
if (hinfo64.empty())
{
return;
}
host = hpool->get(id,true);
if ( host == 0 )
{
goto error_host;
}
hinfo = one_util::base64_decode(hinfo64);
// ---------------------------------------------------------------------
// Monitoring Error
// ---------------------------------------------------------------------
if (result != "SUCCESS")
{
set<int> vm_ids;
host->error_info(*hinfo, vm_ids);
Nebula &ne = Nebula::instance();
LifeCycleManager *lcm = ne.get_lcm();
for (set<int>::iterator it = vm_ids.begin(); it != vm_ids.end(); it++)
{
lcm->trigger(LifeCycleManager::MONITOR_DONE, *it);
}
delete hinfo;
hpool->update(host);
host->unlock();
return;
}
// ---------------------------------------------------------------------
// Get DS Information from Moniroting Information
// ---------------------------------------------------------------------
rc = host->extract_ds_info(*hinfo, tmpl, datastores);
delete hinfo;
host->unlock();
if (rc != 0)
{
return;
}
for (itm = datastores.begin(); itm != datastores.end(); itm++)
{
ds = dspool->get(itm->first, true);
if (ds == 0)
{
continue;
}
if (ds->get_type() == Datastore::SYSTEM_DS)
{
if (ds->is_shared())
{
float total = 0, free = 0, used = 0;
ostringstream oss;
(itm->second)->vector_value("TOTAL_MB", total);
(itm->second)->vector_value("FREE_MB", free);
(itm->second)->vector_value("USED_MB", used);
ds->update_monitor(total, free, used);
oss << "Datastore " << ds->get_name() <<
" (" << ds->get_oid() << ") successfully monitored.";
NebulaLog::log("ImM", Log::INFO, oss);
}
else
{
non_shared_ds.insert(itm->first);
}
}
ds->unlock();
}
// ---------------------------------------------------------------------
// Parse Host information
// ---------------------------------------------------------------------
host = hpool->get(id,true);
if ( host == 0 )
{
delete hinfo;
goto error_host;
}
rc = host->update_info(tmpl, vm_poll, lost, found, non_shared_ds);
hpool->update(host);
if (rc != 0)
{
host->unlock();
return;
}
hpool->update_monitoring(host);
ess << "Host " << host->get_name() << " (" << host->get_oid() << ")"
<< " successfully monitored.";
NebulaLog::log("InM", Log::DEBUG, ess);
host->unlock();
if (vm_poll)
{
set<int>::iterator its;
map<int,string>::iterator itm;
Nebula &ne = Nebula::instance();
LifeCycleManager *lcm = ne.get_lcm();
for (its = lost.begin(); its != lost.end(); its++)
{
lcm->trigger(LifeCycleManager::MONITOR_DONE, *its);
}
for (itm = found.begin(); itm != found.end(); itm++)
{
VirtualMachineManagerDriver::process_poll(itm->first, itm->second);
}
}
}
else if (action == "LOG")
{
string info;
getline(is,info);
NebulaLog::log("InM",log_type(result[0]),info.c_str());
}
return;
error_host:
ess << "Could not get host " << id;
NebulaLog::log("InM",Log::ERROR,ess);
return;
error_parse:
ess << "Error while parsing driver message: " << message;
NebulaLog::log("InM",Log::ERROR,ess);
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void InformationManagerDriver::recover()
{
NebulaLog::log("InM", Log::ERROR,
"Information driver crashed, recovering...");
}
<commit_msg>feature #1678: Add missing update<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2013, OpenNebula Project (OpenNebula.org), C12G Labs */
/* */
/* 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 "InformationManagerDriver.h"
#include "NebulaLog.h"
#include "Nebula.h"
#include "NebulaUtil.h"
#include "VirtualMachineManagerDriver.h"
#include <sstream>
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
InformationManagerDriver::InformationManagerDriver(
int userid,
const map<string,string>& attrs,
bool sudo,
HostPool * pool):
Mad(userid,attrs,sudo),hpool(pool)
{
dspool = Nebula::instance().get_dspool();
};
/* ************************************************************************** */
/* Driver ASCII Protocol Implementation */
/* ************************************************************************** */
void InformationManagerDriver::monitor(int oid,
const string& host,
const string& dsloc,
bool update) const
{
ostringstream os;
os << "MONITOR " << oid << " " << host << " " << dsloc << " " << update << endl;
write(os);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void InformationManagerDriver::protocol(const string& message) const
{
istringstream is(message);
//stores the action name
string action;
//stores the action result
string result;
//stores the action id of the associated HOST
int id;
ostringstream ess;
Host * host;
set<int> vm_ids;
string hinfo64;
string* hinfo;
// Parse the driver message
if ( is.good() )
{
is >> action >> ws;
}
else
{
goto error_parse;
}
if ( is.good() )
{
is >> result >> ws;
}
else
{
goto error_parse;
}
if ( is.good() )
{
is >> id >> ws;
}
else
{
goto error_parse;
}
// -----------------------
// Protocol implementation
// -----------------------
if ( action == "MONITOR" )
{
bool vm_poll;
set<int> lost;
map<int,string> found;
set<int> non_shared_ds;
map<int,const VectorAttribute*> datastores;
Template tmpl;
Datastore * ds;
map<int, const VectorAttribute*>::iterator itm;
int rc;
// ---------------------------------------------------------------------
// Get information from driver and decode from base64
// ---------------------------------------------------------------------
getline (is, hinfo64);
if (hinfo64.empty())
{
return;
}
host = hpool->get(id,true);
if ( host == 0 )
{
goto error_host;
}
hinfo = one_util::base64_decode(hinfo64);
// ---------------------------------------------------------------------
// Monitoring Error
// ---------------------------------------------------------------------
if (result != "SUCCESS")
{
set<int> vm_ids;
host->error_info(*hinfo, vm_ids);
Nebula &ne = Nebula::instance();
LifeCycleManager *lcm = ne.get_lcm();
for (set<int>::iterator it = vm_ids.begin(); it != vm_ids.end(); it++)
{
lcm->trigger(LifeCycleManager::MONITOR_DONE, *it);
}
delete hinfo;
hpool->update(host);
host->unlock();
return;
}
// ---------------------------------------------------------------------
// Get DS Information from Moniroting Information
// ---------------------------------------------------------------------
rc = host->extract_ds_info(*hinfo, tmpl, datastores);
delete hinfo;
host->unlock();
if (rc != 0)
{
return;
}
for (itm = datastores.begin(); itm != datastores.end(); itm++)
{
ds = dspool->get(itm->first, true);
if (ds == 0)
{
continue;
}
if (ds->get_type() == Datastore::SYSTEM_DS)
{
if (ds->is_shared())
{
float total = 0, free = 0, used = 0;
ostringstream oss;
(itm->second)->vector_value("TOTAL_MB", total);
(itm->second)->vector_value("FREE_MB", free);
(itm->second)->vector_value("USED_MB", used);
ds->update_monitor(total, free, used);
oss << "Datastore " << ds->get_name() <<
" (" << ds->get_oid() << ") successfully monitored.";
NebulaLog::log("ImM", Log::INFO, oss);
dspool->update(ds);
}
else
{
non_shared_ds.insert(itm->first);
}
}
ds->unlock();
}
// ---------------------------------------------------------------------
// Parse Host information
// ---------------------------------------------------------------------
host = hpool->get(id,true);
if ( host == 0 )
{
delete hinfo;
goto error_host;
}
rc = host->update_info(tmpl, vm_poll, lost, found, non_shared_ds);
hpool->update(host);
if (rc != 0)
{
host->unlock();
return;
}
hpool->update_monitoring(host);
ess << "Host " << host->get_name() << " (" << host->get_oid() << ")"
<< " successfully monitored.";
NebulaLog::log("InM", Log::DEBUG, ess);
host->unlock();
if (vm_poll)
{
set<int>::iterator its;
map<int,string>::iterator itm;
Nebula &ne = Nebula::instance();
LifeCycleManager *lcm = ne.get_lcm();
for (its = lost.begin(); its != lost.end(); its++)
{
lcm->trigger(LifeCycleManager::MONITOR_DONE, *its);
}
for (itm = found.begin(); itm != found.end(); itm++)
{
VirtualMachineManagerDriver::process_poll(itm->first, itm->second);
}
}
}
else if (action == "LOG")
{
string info;
getline(is,info);
NebulaLog::log("InM",log_type(result[0]),info.c_str());
}
return;
error_host:
ess << "Could not get host " << id;
NebulaLog::log("InM",Log::ERROR,ess);
return;
error_parse:
ess << "Error while parsing driver message: " << message;
NebulaLog::log("InM",Log::ERROR,ess);
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void InformationManagerDriver::recover()
{
NebulaLog::log("InM", Log::ERROR,
"Information driver crashed, recovering...");
}
<|endoftext|>
|
<commit_before>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret == 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = path.size() >= 1 && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<commit_msg>GetCurrentDirectoryA() returns nonzero for success<commit_after>#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "CodeGen_LLVM.h"
#include "CodeGen_C.h"
#include "CodeGen_Internal.h"
#include <iostream>
#include <fstream>
#ifdef _WIN32
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
namespace Halide {
std::unique_ptr<llvm::raw_fd_ostream> make_raw_fd_ostream(const std::string &filename) {
std::string error_string;
std::error_code err;
std::unique_ptr<llvm::raw_fd_ostream> raw_out(new llvm::raw_fd_ostream(filename, err, llvm::sys::fs::F_None));
if (err) error_string = err.message();
internal_assert(error_string.empty())
<< "Error opening output " << filename << ": " << error_string << "\n";
return raw_out;
}
void emit_file(llvm::Module &module, Internal::LLVMOStream& out, llvm::TargetMachine::CodeGenFileType file_type) {
Internal::debug(1) << "emit_file.Compiling to native code...\n";
Internal::debug(2) << "Target triple: " << module.getTargetTriple() << "\n";
// Get the target specific parser.
auto target_machine = Internal::make_target_machine(module);
internal_assert(target_machine.get()) << "Could not allocate target machine!\n";
#if LLVM_VERSION == 37
llvm::DataLayout target_data_layout(*(target_machine->getDataLayout()));
#else
llvm::DataLayout target_data_layout(target_machine->createDataLayout());
#endif
if (!(target_data_layout == module.getDataLayout())) {
internal_error << "Warning: module's data layout does not match target machine's\n"
<< target_data_layout.getStringRepresentation() << "\n"
<< module.getDataLayout().getStringRepresentation() << "\n";
}
// Build up all of the passes that we want to do to the module.
llvm::legacy::PassManager pass_manager;
pass_manager.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module.getTargetTriple())));
// Make sure things marked as always-inline get inlined
#if LLVM_VERSION < 40
pass_manager.add(llvm::createAlwaysInlinerPass());
#else
pass_manager.add(llvm::createAlwaysInlinerLegacyPass());
#endif
// Enable symbol rewriting. This allows code outside libHalide to
// use symbol rewriting when compiling Halide code (for example, by
// using cl::ParseCommandLineOption and then passing the appropriate
// rewrite options via -mllvm flags).
pass_manager.add(llvm::createRewriteSymbolsPass());
// Override default to generate verbose assembly.
target_machine->Options.MCOptions.AsmVerbose = true;
// Ask the target to add backend passes as necessary.
target_machine->addPassesToEmitFile(pass_manager, out, file_type);
pass_manager.run(module);
}
std::unique_ptr<llvm::Module> compile_module_to_llvm_module(const Module &module, llvm::LLVMContext &context) {
return codegen_llvm(module, context);
}
void compile_llvm_module_to_object(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_ObjectFile);
}
void compile_llvm_module_to_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
emit_file(module, out, llvm::TargetMachine::CGFT_AssemblyFile);
}
void compile_llvm_module_to_llvm_bitcode(llvm::Module &module, Internal::LLVMOStream& out) {
WriteBitcodeToFile(&module, out);
}
void compile_llvm_module_to_llvm_assembly(llvm::Module &module, Internal::LLVMOStream& out) {
module.print(out, nullptr);
}
// Note that the utilities for get/set working directory are deliberately *not* in Util.h;
// generally speaking, you shouldn't ever need or want to do this, and doing so is asking for
// trouble. This exists solely to work around an issue with LLVM, hence its restricted
// location. If we ever legitimately need this elsewhere, consider moving it to Util.h.
namespace {
std::string get_current_directory() {
#ifdef _WIN32
std::string dir;
char p[MAX_PATH];
DWORD ret = GetCurrentDirectoryA(MAX_PATH, p);
internal_assert(ret != 0) << "GetCurrentDirectoryA() failed";
dir = p;
return dir;
#else
std::string dir;
char *p = getcwd(nullptr, 0);
internal_assert(p != NULL) << "getcwd() failed";
dir = p;
free(p);
return dir;
#endif
}
void set_current_directory(const std::string &d) {
#ifdef _WIN32
internal_assert(SetCurrentDirectoryA(d.c_str())) << "SetCurrentDirectoryA() failed";
#else
internal_assert(chdir(d.c_str()) == 0) << "chdir() failed";
#endif
}
std::pair<std::string, std::string> dir_and_file(const std::string &path) {
std::string dir, file;
size_t slash_pos = path.rfind('/');
#ifdef _WIN32
if (slash_pos == std::string::npos) {
// Windows is a thing
slash_pos = path.rfind('\\');
}
#endif
if (slash_pos != std::string::npos) {
dir = path.substr(0, slash_pos);
file = path.substr(slash_pos + 1);
} else {
file = path;
}
return { dir, file };
}
std::string make_absolute_path(const std::string &path) {
bool is_absolute = path.size() >= 1 && path[0] == '/';
char sep = '/';
#ifdef _WIN32
// Allow for C:\whatever or c:/whatever on Windows
if (path.size() >= 3 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
is_absolute = true;
sep = path[2];
}
#endif
if (!is_absolute) {
return get_current_directory() + sep + path;
}
return path;
}
struct SetCwd {
const std::string original_directory;
explicit SetCwd(const std::string &d) : original_directory(get_current_directory()) {
if (!d.empty()) {
set_current_directory(d);
}
}
~SetCwd() {
set_current_directory(original_directory);
}
};
}
void create_static_library(const std::vector<std::string> &src_files_in, const Target &target,
const std::string &dst_file_in, bool deterministic) {
internal_assert(!src_files_in.empty());
// Ensure that dst_file is an absolute path, since we're going to change the
// working directory temporarily.
std::string dst_file = make_absolute_path(dst_file_in);
// If we give absolute paths to LLVM, it will dutifully embed them in the resulting
// .a file; some versions of 'ar x' are unable to deal with the resulting files,
// which is inconvenient. So let's doctor the inputs to be simple filenames,
// and temporarily change the working directory. (Note that this requires all the
// input files be in the same directory; this is currently always the case for
// our existing usage.)
std::string src_dir = dir_and_file(src_files_in.front()).first;
std::vector<std::string> src_files;
for (auto &s_in : src_files_in) {
auto df = dir_and_file(s_in);
internal_assert(df.first == src_dir) << "All inputs to create_static_library() must be in the same directory";
for (auto &s_existing : src_files) {
internal_assert(s_existing != df.second) << "create_static_library() does not allow duplicate filenames.";
}
src_files.push_back(df.second);
}
SetCwd set_cwd(src_dir);
#if LLVM_VERSION >= 39
std::vector<llvm::NewArchiveMember> new_members;
for (auto &src : src_files) {
llvm::Expected<llvm::NewArchiveMember> new_member =
llvm::NewArchiveMember::getFile(src, /*Deterministic=*/true);
if (!new_member) {
// Don't use internal_assert: the call to new_member.takeError() will be evaluated
// even if the assert does not fail, leaving new_member in an indeterminate
// state.
internal_error << src << ": " << llvm::toString(new_member.takeError()) << "\n";
}
new_members.push_back(std::move(*new_member));
}
#elif LLVM_VERSION == 38
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src));
}
#else
std::vector<llvm::NewArchiveIterator> new_members;
for (auto &src : src_files) {
new_members.push_back(llvm::NewArchiveIterator(src, src));
}
#endif
const bool write_symtab = true;
const auto kind = Internal::get_triple_for_target(target).isOSDarwin()
? llvm::object::Archive::K_BSD
: llvm::object::Archive::K_GNU;
#if LLVM_VERSION == 37
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic);
#elif LLVM_VERSION == 38
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin);
#else
const bool thin = false;
auto result = llvm::writeArchive(dst_file, new_members,
write_symtab, kind,
deterministic, thin, nullptr);
#endif
internal_assert(!result.second) << "Failed to write archive: " << dst_file
<< ", reason: " << result.second << "\n";
}
} // namespace Halide
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/drivers/video/video_driver_component.h"
#include "cyber/common/file.h"
namespace apollo {
namespace drivers {
namespace video {
using cyber::common::EnsureDirectory;
bool CompCameraH265Compressed::Init() {
AINFO << "Initialize video driver component.";
CameraH265Config video_config;
if (!GetProtoConfig(&video_config)) {
return false;
}
AINFO << "Velodyne config: " << video_config.DebugString();
camera_deivce_.reset(new CameraDriver(&video_config));
camera_deivce_->Init();
if (camera_deivce_->Record()) {
// Use current directory to save record file if H265_SAVE_FOLDER environment
// is not set.
record_folder_ = cyber::common::GetEnv("H265_SAVE_FOLDER", ".");
AINFO << "Record folder: " << record_folder_;
struct stat st;
if (stat(record_folder_.c_str(), &st) < 0) {
bool ret = EnsureDirectory(record_folder_);
AINFO_IF(ret) << "Record folder is created successfully.";
}
}
pb_image_.reset(new CompressedImage);
pb_image_->mutable_data()->reserve(1920 * 1080 * 4);
writer_ = node_->CreateWriter<CompressedImage>(
video_config.compress_conf().output_channel());
runing_ = true;
video_thread_ = std::shared_ptr<std::thread>(
new std::thread(std::bind(&CompCameraH265Compressed::VideoPoll, this)));
video_thread_->detach();
return true;
}
void CompCameraH265Compressed::VideoPoll() {
std::ofstream fout;
if (camera_deivce_->Record()) {
char name[256];
snprintf(name, sizeof(name), "%s/encode_%d.h265", record_folder_.c_str(),
camera_deivce_->Port());
AINFO << "Output file: " << name;
fout.open(name, std::ios::binary);
if (!fout.good()) {
AERROR << "Failed to open output file: " << name;
}
}
int poll_failure_number = 0;
while (!apollo::cyber::IsShutdown()) {
if (!camera_deivce_->Poll(pb_image_)) {
AERROR << "H265 poll failed on port: " << camera_deivce_->Port();
static constexpr int kTolerance = 256;
if (++poll_failure_number > kTolerance) {
AERROR << "H265 poll keep failing for " << kTolerance << " times, Exit";
break;
}
continue;
}
poll_failure_number = 0;
pb_image_->mutable_header()->set_timestamp_sec(
cyber::Time::Now().ToSecond());
AINFO << "Send compressed image.";
writer_->Write(pb_image_);
if (camera_deivce_->Record()) {
fout.write(pb_image_->data().c_str(), pb_image_->data().size());
}
}
if (camera_deivce_->Record()) {
fout.close();
}
}
} // namespace video
} // namespace drivers
} // namespace apollo
<commit_msg>Update video_driver_component.cc<commit_after>/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/drivers/video/video_driver_component.h"
#include "cyber/common/file.h"
namespace apollo {
namespace drivers {
namespace video {
using cyber::common::EnsureDirectory;
bool CompCameraH265Compressed::Init() {
AINFO << "Initialize video driver component.";
CameraH265Config video_config;
if (!GetProtoConfig(&video_config)) {
return false;
}
AINFO << "Velodyne config: " << video_config.DebugString();
camera_deivce_.reset(new CameraDriver(&video_config));
camera_deivce_->Init();
if (camera_deivce_->Record()) {
// Use current directory to save record file if H265_SAVE_FOLDER environment
// is not set.
record_folder_ = cyber::common::GetEnv("H265_SAVE_FOLDER", ".");
AINFO << "Record folder: " << record_folder_;
struct stat st;
if (stat(record_folder_.c_str(), &st) < 0) {
bool ret = EnsureDirectory(record_folder_);
AINFO_IF(ret) << "Record folder is created successfully.";
}
}
pb_image_.reset(new CompressedImage);
pb_image_->mutable_data()->reserve(1920 * 1080 * 4);
writer_ = node_->CreateWriter<CompressedImage>(
video_config.compress_conf().output_channel());
runing_ = true;
video_thread_ = std::shared_ptr<std::thread>(
new std::thread(std::bind(&CompCameraH265Compressed::VideoPoll, this)));
video_thread_->detach();
return true;
}
void CompCameraH265Compressed::VideoPoll() {
std::ofstream fout;
if (camera_deivce_->Record()) {
char name[256];
snprintf(name, sizeof(name), "%s/encode_%d.h265", record_folder_.c_str(),
camera_deivce_->Port());
AINFO << "Output file: " << name;
fout.open(name, std::ios::binary);
if (!fout.good()) {
AERROR << "Failed to open output file: " << name;
}
}
int poll_failure_number = 0;
while (!apollo::cyber::IsShutdown()) {
if (!camera_deivce_->Poll(pb_image_)) {
AERROR << "H265 poll failed on port: " << camera_deivce_->Port();
static constexpr int kTolerance = 256;
if (poll_failure_number > kTolerance) {
AERROR << "H265 poll keep failing for " << kTolerance << " times, Exit";
break;
}
++poll_failure_number;
continue;
}
poll_failure_number = 0;
pb_image_->mutable_header()->set_timestamp_sec(
cyber::Time::Now().ToSecond());
AINFO << "Send compressed image.";
writer_->Write(pb_image_);
if (camera_deivce_->Record()) {
fout.write(pb_image_->data().c_str(), pb_image_->data().size());
}
}
if (camera_deivce_->Record()) {
fout.close();
}
}
} // namespace video
} // namespace drivers
} // namespace apollo
<|endoftext|>
|
<commit_before>
#include <constrained_ik/collision_robot_fcl_detailed.h>
#include <ros/ros.h>
namespace constrained_ik
{
using namespace collision_detection;
CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state) const
{
return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL);
}
CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm) const
{
return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm);
}
CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailedHelper(const robot_state::RobotState &state, const AllowedCollisionMatrix *acm) const
{
FCLManager manager;
CollisionRobotFCL::allocSelfCollisionBroadPhase(state, manager);
DistanceResultDetailed drd(acm);
drd.enableGroup(getRobotModel());
//distance_detailed_.clear();
manager.manager_->distance(&drd, &CollisionRobotFCLDetailed::distanceDetailedCallback);
return drd.distance_detailed_;
}
bool CollisionRobotFCLDetailed::distanceDetailedCallback(fcl::CollisionObject* o1, fcl::CollisionObject* o2, void* data, double& min_dist)
{
DistanceResultDetailed* cdata = reinterpret_cast<DistanceResultDetailed*>(data);
const CollisionGeometryData* cd1 = static_cast<const CollisionGeometryData*>(o1->collisionGeometry()->getUserData());
const CollisionGeometryData* cd2 = static_cast<const CollisionGeometryData*>(o2->collisionGeometry()->getUserData());
// If active components are specified
if (cdata->active_components_only_)
{
const robot_model::LinkModel *l1 = cd1->type == BodyTypes::ROBOT_LINK ? cd1->ptr.link : (cd1->type == BodyTypes::ROBOT_ATTACHED ? cd1->ptr.ab->getAttachedLink() : NULL);
const robot_model::LinkModel *l2 = cd2->type == BodyTypes::ROBOT_LINK ? cd2->ptr.link : (cd2->type == BodyTypes::ROBOT_ATTACHED ? cd2->ptr.ab->getAttachedLink() : NULL);
// If neither of the involved components is active
if ((!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end()) &&
(!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end()))
{
return false;
}
}
// use the collision matrix (if any) to avoid certain distance checks
bool always_allow_collision = false;
if (cdata->acm_)
{
AllowedCollision::Type type;
bool found = cdata->acm_->getAllowedCollision(cd1->getID(), cd2->getID(), type);
if (found)
{
// if we have an entry in the collision matrix, we read it
if (type == AllowedCollision::ALWAYS)
{
always_allow_collision = true;
if (!cdata->verbose)
logDebug("Collision between '%s' and '%s' is always allowed. No contacts are computed.",
cd1->getID().c_str(), cd2->getID().c_str());
}
}
}
// check if a link is touching an attached object
if (cd1->type == BodyTypes::ROBOT_LINK && cd2->type == BodyTypes::ROBOT_ATTACHED)
{
const std::set<std::string> &tl = cd2->ptr.ab->getTouchLinks();
if (tl.find(cd1->getID()) != tl.end())
{
always_allow_collision = true;
if (!cdata->verbose)
logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
cd1->getID().c_str(), cd2->getID().c_str());
}
}
else
{
if (cd2->type == BodyTypes::ROBOT_LINK && cd1->type == BodyTypes::ROBOT_ATTACHED)
{
const std::set<std::string> &tl = cd1->ptr.ab->getTouchLinks();
if (tl.find(cd2->getID()) != tl.end())
{
always_allow_collision = true;
if (!cdata->verbose)
logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
cd2->getID().c_str(), cd1->getID().c_str());
}
}
}
if(always_allow_collision)
{
return false;
}
if (!cdata->verbose)
logDebug("Actually checking collisions between %s and %s", cd1->getID().c_str(), cd2->getID().c_str());
fcl::DistanceResult dist_result;
double d = fcl::distance(o1, o2, fcl::DistanceRequest(true), dist_result);
// Check if either object is already in the map. If not add it or if present
// check to see if the new distance is closer. If closer remove the existing
// one and add the new distance information.
std::map<std::string, fcl::DistanceResult>::iterator it;
it = cdata->distance_detailed_.find(cd1->ptr.obj->id_);
if (it == cdata->distance_detailed_.end())
{
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
}
else
{
if (dist_result.min_distance < it->second.min_distance)
{
cdata->distance_detailed_.erase(cd1->ptr.obj->id_);
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
}
}
it = cdata->distance_detailed_.find(cd2->ptr.obj->id_);
if (it == cdata->distance_detailed_.end())
{
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
}
else
{
if (dist_result.min_distance < it->second.min_distance)
{
cdata->distance_detailed_.erase(cd2->ptr.obj->id_);
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
}
}
return false;
}
bool CollisionRobotFCLDetailed::getDistanceInfo(const DistanceDetailedMap distance_detailed, const std::string link_name, CollisionRobotFCLDetailed::DistanceInfo &dist_info)
{
std::map<std::string, fcl::DistanceResult>::const_iterator it;
it = distance_detailed.find(link_name);
if (it != distance_detailed.end())
{
fcl::DistanceResult dist = static_cast<const fcl::DistanceResult>(it->second);
const collision_detection::CollisionGeometryData* cd1 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o1->getUserData());
const collision_detection::CollisionGeometryData* cd2 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o2->getUserData());
if (cd1->ptr.link->getName() == link_name)
{
dist_info.nearest_obsticle = cd2->ptr.link->getName();
dist_info.link_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[1]-dist.nearest_points[0]).data.vs);
dist_info.avoidance_vector.norm();
dist_info.distance = dist.min_distance;
}
else if (cd2->ptr.link->getName() == link_name)
{
dist_info.nearest_obsticle = cd1->ptr.link->getName();
dist_info.link_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[0]-dist.nearest_points[1]).data.vs);
dist_info.avoidance_vector.norm();
dist_info.distance = dist.min_distance;
}
else
{
ROS_ERROR("getDistanceInfo was unable to find link after match!");
return false;
}
return true;
}
else
{
ROS_ERROR("couldn't find link with that name %s", link_name.c_str());
for( it=distance_detailed.begin(); it != distance_detailed.end(); it++)
{
ROS_ERROR("name: %s", it->first.c_str());
}
return false;
}
}
void CollisionRobotFCLDetailed::DistanceResultDetailed::enableGroup(const robot_model::RobotModelConstPtr &kmodel)
{
if (kmodel->hasJointModelGroup(group_name))
active_components_only_ = &kmodel->getJointModelGroup(group_name)->getUpdatedLinkModelsWithGeometrySet();
else
active_components_only_ = NULL;
}
}//namespace constrained_ik
<commit_msg>Fix incorrect data type<commit_after>
#include <constrained_ik/collision_robot_fcl_detailed.h>
#include <ros/ros.h>
namespace constrained_ik
{
using namespace collision_detection;
CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state) const
{
return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, NULL);
}
CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailed(const robot_state::RobotState &state, const AllowedCollisionMatrix &acm) const
{
return CollisionRobotFCLDetailed::distanceSelfDetailedHelper(state, &acm);
}
CollisionRobotFCLDetailed::DistanceDetailedMap CollisionRobotFCLDetailed::distanceSelfDetailedHelper(const robot_state::RobotState &state, const AllowedCollisionMatrix *acm) const
{
FCLManager manager;
CollisionRobotFCLDetailed::allocSelfCollisionBroadPhase(state, manager);
DistanceResultDetailed drd(acm);
drd.enableGroup(getRobotModel());
//distance_detailed_.clear();
manager.manager_->distance(&drd, &CollisionRobotFCLDetailed::distanceDetailedCallback);
return drd.distance_detailed_;
}
bool CollisionRobotFCLDetailed::distanceDetailedCallback(fcl::CollisionObject* o1, fcl::CollisionObject* o2, void* data, double& min_dist)
{
DistanceResultDetailed* cdata = reinterpret_cast<DistanceResultDetailed*>(data);
const CollisionGeometryData* cd1 = static_cast<const CollisionGeometryData*>(o1->collisionGeometry()->getUserData());
const CollisionGeometryData* cd2 = static_cast<const CollisionGeometryData*>(o2->collisionGeometry()->getUserData());
// If active components are specified
if (cdata->active_components_only_)
{
const robot_model::LinkModel *l1 = cd1->type == BodyTypes::ROBOT_LINK ? cd1->ptr.link : (cd1->type == BodyTypes::ROBOT_ATTACHED ? cd1->ptr.ab->getAttachedLink() : NULL);
const robot_model::LinkModel *l2 = cd2->type == BodyTypes::ROBOT_LINK ? cd2->ptr.link : (cd2->type == BodyTypes::ROBOT_ATTACHED ? cd2->ptr.ab->getAttachedLink() : NULL);
// If neither of the involved components is active
if ((!l1 || cdata->active_components_only_->find(l1) == cdata->active_components_only_->end()) &&
(!l2 || cdata->active_components_only_->find(l2) == cdata->active_components_only_->end()))
{
return false;
}
}
// use the collision matrix (if any) to avoid certain distance checks
bool always_allow_collision = false;
if (cdata->acm_)
{
AllowedCollision::Type type;
bool found = cdata->acm_->getAllowedCollision(cd1->getID(), cd2->getID(), type);
if (found)
{
// if we have an entry in the collision matrix, we read it
if (type == AllowedCollision::ALWAYS)
{
always_allow_collision = true;
if (!cdata->verbose)
logDebug("Collision between '%s' and '%s' is always allowed. No contacts are computed.",
cd1->getID().c_str(), cd2->getID().c_str());
}
}
}
// check if a link is touching an attached object
if (cd1->type == BodyTypes::ROBOT_LINK && cd2->type == BodyTypes::ROBOT_ATTACHED)
{
const std::set<std::string> &tl = cd2->ptr.ab->getTouchLinks();
if (tl.find(cd1->getID()) != tl.end())
{
always_allow_collision = true;
if (!cdata->verbose)
logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
cd1->getID().c_str(), cd2->getID().c_str());
}
}
else
{
if (cd2->type == BodyTypes::ROBOT_LINK && cd1->type == BodyTypes::ROBOT_ATTACHED)
{
const std::set<std::string> &tl = cd1->ptr.ab->getTouchLinks();
if (tl.find(cd2->getID()) != tl.end())
{
always_allow_collision = true;
if (!cdata->verbose)
logDebug("Robot link '%s' is allowed to touch attached object '%s'. No contacts are computed.",
cd2->getID().c_str(), cd1->getID().c_str());
}
}
}
if(always_allow_collision)
{
return false;
}
if (!cdata->verbose)
logDebug("Actually checking collisions between %s and %s", cd1->getID().c_str(), cd2->getID().c_str());
fcl::DistanceResult dist_result;
double d = fcl::distance(o1, o2, fcl::DistanceRequest(true), dist_result);
// Check if either object is already in the map. If not add it or if present
// check to see if the new distance is closer. If closer remove the existing
// one and add the new distance information.
std::map<std::string, fcl::DistanceResult>::iterator it;
it = cdata->distance_detailed_.find(cd1->ptr.obj->id_);
if (it == cdata->distance_detailed_.end())
{
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
}
else
{
if (dist_result.min_distance < it->second.min_distance)
{
cdata->distance_detailed_.erase(cd1->ptr.obj->id_);
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd1->ptr.obj->id_, dist_result));
}
}
it = cdata->distance_detailed_.find(cd2->ptr.obj->id_);
if (it == cdata->distance_detailed_.end())
{
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
}
else
{
if (dist_result.min_distance < it->second.min_distance)
{
cdata->distance_detailed_.erase(cd2->ptr.obj->id_);
cdata->distance_detailed_.insert(std::make_pair<std::string, fcl::DistanceResult>(cd2->ptr.obj->id_, dist_result));
}
}
return false;
}
bool CollisionRobotFCLDetailed::getDistanceInfo(const DistanceDetailedMap distance_detailed, const std::string link_name, CollisionRobotFCLDetailed::DistanceInfo &dist_info)
{
std::map<std::string, fcl::DistanceResult>::const_iterator it;
it = distance_detailed.find(link_name);
if (it != distance_detailed.end())
{
fcl::DistanceResult dist = static_cast<const fcl::DistanceResult>(it->second);
const collision_detection::CollisionGeometryData* cd1 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o1->getUserData());
const collision_detection::CollisionGeometryData* cd2 = static_cast<const collision_detection::CollisionGeometryData*>(dist.o2->getUserData());
if (cd1->ptr.link->getName() == link_name)
{
dist_info.nearest_obsticle = cd2->ptr.link->getName();
dist_info.link_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[1]-dist.nearest_points[0]).data.vs);
dist_info.avoidance_vector.norm();
dist_info.distance = dist.min_distance;
}
else if (cd2->ptr.link->getName() == link_name)
{
dist_info.nearest_obsticle = cd1->ptr.link->getName();
dist_info.link_point = Eigen::Vector3d(dist.nearest_points[1].data.vs);
dist_info.obsticle_point = Eigen::Vector3d(dist.nearest_points[0].data.vs);
dist_info.avoidance_vector = Eigen::Vector3d((dist.nearest_points[0]-dist.nearest_points[1]).data.vs);
dist_info.avoidance_vector.norm();
dist_info.distance = dist.min_distance;
}
else
{
ROS_ERROR("getDistanceInfo was unable to find link after match!");
return false;
}
return true;
}
else
{
ROS_ERROR("couldn't find link with that name %s", link_name.c_str());
for( it=distance_detailed.begin(); it != distance_detailed.end(); it++)
{
ROS_ERROR("name: %s", it->first.c_str());
}
return false;
}
}
void CollisionRobotFCLDetailed::DistanceResultDetailed::enableGroup(const robot_model::RobotModelConstPtr &kmodel)
{
if (kmodel->hasJointModelGroup(group_name))
active_components_only_ = &kmodel->getJointModelGroup(group_name)->getUpdatedLinkModelsWithGeometrySet();
else
active_components_only_ = NULL;
}
}//namespace constrained_ik
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <memory>
#include <vector>
#include "api/test/mock_video_decoder.h"
#include "modules/video_coding/include/mock/mock_vcm_callbacks.h"
#include "modules/video_coding/include/video_coding.h"
#include "modules/video_coding/timing.h"
#include "modules/video_coding/video_coding_impl.h"
#include "system_wrappers/include/clock.h"
#include "test/gtest.h"
#include "test/video_codec_settings.h"
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::NiceMock;
namespace webrtc {
namespace vcm {
namespace {
class TestVideoReceiver : public ::testing::Test {
protected:
static const int kUnusedPayloadType = 10;
TestVideoReceiver() : clock_(0) {}
virtual void SetUp() {
timing_.reset(new VCMTiming(&clock_));
receiver_.reset(new VideoReceiver(&clock_, timing_.get()));
receiver_->RegisterExternalDecoder(&decoder_, kUnusedPayloadType);
const size_t kMaxNackListSize = 250;
const int kMaxPacketAgeToNack = 450;
receiver_->SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack, 0);
webrtc::test::CodecSettings(kVideoCodecVP8, &settings_);
settings_.plType = kUnusedPayloadType; // Use the mocked encoder.
EXPECT_EQ(0, receiver_->RegisterReceiveCodec(&settings_, 1, true));
// Since we call Decode, we need to provide a valid receive callback.
// However, for the purposes of these tests, we ignore the callbacks.
EXPECT_CALL(receive_callback_, OnIncomingPayloadType(_)).Times(AnyNumber());
EXPECT_CALL(receive_callback_, OnDecoderImplementationName(_))
.Times(AnyNumber());
receiver_->RegisterReceiveCallback(&receive_callback_);
}
void InsertAndVerifyPaddingFrame(const uint8_t* payload,
WebRtcRTPHeader* header) {
ASSERT_TRUE(header != NULL);
for (int j = 0; j < 5; ++j) {
// Padding only packets are passed to the VCM with payload size 0.
EXPECT_EQ(0, receiver_->IncomingPacket(payload, 0, *header));
++header->header.sequenceNumber;
}
receiver_->Process();
EXPECT_CALL(decoder_, Decode(_, _, _, _)).Times(0);
EXPECT_EQ(VCM_FRAME_NOT_READY, receiver_->Decode(100));
}
void InsertAndVerifyDecodableFrame(const uint8_t* payload,
size_t length,
WebRtcRTPHeader* header) {
ASSERT_TRUE(header != NULL);
EXPECT_EQ(0, receiver_->IncomingPacket(payload, length, *header));
++header->header.sequenceNumber;
EXPECT_CALL(packet_request_callback_, ResendPackets(_, _)).Times(0);
receiver_->Process();
EXPECT_CALL(decoder_, Decode(_, _, _, _)).Times(1);
EXPECT_EQ(0, receiver_->Decode(100));
}
SimulatedClock clock_;
VideoCodec settings_;
NiceMock<MockVideoDecoder> decoder_;
NiceMock<MockPacketRequestCallback> packet_request_callback_;
std::unique_ptr<VCMTiming> timing_;
MockVCMReceiveCallback receive_callback_;
std::unique_ptr<VideoReceiver> receiver_;
};
TEST_F(TestVideoReceiver, PaddingOnlyFrames) {
EXPECT_EQ(0, receiver_->SetVideoProtection(kProtectionNack, true));
EXPECT_EQ(
0, receiver_->RegisterPacketRequestCallback(&packet_request_callback_));
const size_t kPaddingSize = 220;
const uint8_t payload[kPaddingSize] = {0};
WebRtcRTPHeader header = {};
header.frameType = kEmptyFrame;
header.header.markerBit = false;
header.header.paddingLength = kPaddingSize;
header.header.payloadType = kUnusedPayloadType;
header.header.ssrc = 1;
header.header.headerLength = 12;
header.video_header().codec = kVideoCodecVP8;
for (int i = 0; i < 10; ++i) {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, _)).Times(0);
InsertAndVerifyPaddingFrame(payload, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
}
TEST_F(TestVideoReceiver, PaddingOnlyFramesWithLosses) {
EXPECT_EQ(0, receiver_->SetVideoProtection(kProtectionNack, true));
EXPECT_EQ(
0, receiver_->RegisterPacketRequestCallback(&packet_request_callback_));
const size_t kFrameSize = 1200;
const size_t kPaddingSize = 220;
const uint8_t payload[kFrameSize] = {0};
WebRtcRTPHeader header = {};
header.frameType = kEmptyFrame;
header.header.markerBit = false;
header.header.paddingLength = kPaddingSize;
header.header.payloadType = kUnusedPayloadType;
header.header.ssrc = 1;
header.header.headerLength = 12;
header.video_header().codec = kVideoCodecVP8;
header.video_header().video_type_header.emplace<RTPVideoHeaderVP8>();
// Insert one video frame to get one frame decoded.
header.frameType = kVideoFrameKey;
header.video_header().is_first_packet_in_frame = true;
header.header.markerBit = true;
InsertAndVerifyDecodableFrame(payload, kFrameSize, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
header.frameType = kEmptyFrame;
header.video_header().is_first_packet_in_frame = false;
header.header.markerBit = false;
// Insert padding frames.
for (int i = 0; i < 10; ++i) {
// Lose one packet from the 6th frame.
if (i == 5) {
++header.header.sequenceNumber;
}
// Lose the 4th frame.
if (i == 3) {
header.header.sequenceNumber += 5;
} else {
if (i > 3 && i < 5) {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, 5)).Times(1);
} else if (i >= 5) {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, 6)).Times(1);
} else {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, _)).Times(0);
}
InsertAndVerifyPaddingFrame(payload, &header);
}
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
}
TEST_F(TestVideoReceiver, PaddingOnlyAndVideo) {
EXPECT_EQ(0, receiver_->SetVideoProtection(kProtectionNack, true));
EXPECT_EQ(
0, receiver_->RegisterPacketRequestCallback(&packet_request_callback_));
const size_t kFrameSize = 1200;
const size_t kPaddingSize = 220;
const uint8_t payload[kFrameSize] = {0};
WebRtcRTPHeader header = {};
header.frameType = kEmptyFrame;
header.video_header().is_first_packet_in_frame = false;
header.header.markerBit = false;
header.header.paddingLength = kPaddingSize;
header.header.payloadType = kUnusedPayloadType;
header.header.ssrc = 1;
header.header.headerLength = 12;
header.video_header().codec = kVideoCodecVP8;
auto& vp8_header =
header.video.video_type_header.emplace<RTPVideoHeaderVP8>();
vp8_header.pictureId = -1;
vp8_header.tl0PicIdx = -1;
for (int i = 0; i < 3; ++i) {
// Insert 2 video frames.
for (int j = 0; j < 2; ++j) {
if (i == 0 && j == 0) // First frame should be a key frame.
header.frameType = kVideoFrameKey;
else
header.frameType = kVideoFrameDelta;
header.video_header().is_first_packet_in_frame = true;
header.header.markerBit = true;
InsertAndVerifyDecodableFrame(payload, kFrameSize, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
// Insert 2 padding only frames.
header.frameType = kEmptyFrame;
header.video_header().is_first_packet_in_frame = false;
header.header.markerBit = false;
for (int j = 0; j < 2; ++j) {
// InsertAndVerifyPaddingFrame(payload, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
}
}
} // namespace
} // namespace vcm
} // namespace webrtc
<commit_msg>Minor changes to TestVideoReceiver.<commit_after>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "api/test/mock_video_decoder.h"
#include "modules/video_coding/include/mock/mock_vcm_callbacks.h"
#include "modules/video_coding/include/video_coding.h"
#include "modules/video_coding/timing.h"
#include "modules/video_coding/video_coding_impl.h"
#include "system_wrappers/include/clock.h"
#include "test/gtest.h"
#include "test/video_codec_settings.h"
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::NiceMock;
namespace webrtc {
namespace vcm {
namespace {
class TestVideoReceiver : public ::testing::Test {
protected:
static const int kUnusedPayloadType = 10;
static const uint16_t kMaxWaitTimeMs = 100;
TestVideoReceiver()
: clock_(0), timing_(&clock_), receiver_(&clock_, &timing_) {}
virtual void SetUp() {
// Register decoder.
receiver_.RegisterExternalDecoder(&decoder_, kUnusedPayloadType);
webrtc::test::CodecSettings(kVideoCodecVP8, &settings_);
settings_.plType = kUnusedPayloadType;
EXPECT_EQ(0, receiver_.RegisterReceiveCodec(&settings_, 1, true));
// Set protection mode.
const size_t kMaxNackListSize = 250;
const int kMaxPacketAgeToNack = 450;
receiver_.SetNackSettings(kMaxNackListSize, kMaxPacketAgeToNack, 0);
EXPECT_EQ(0, receiver_.SetVideoProtection(kProtectionNack, true));
EXPECT_EQ(
0, receiver_.RegisterPacketRequestCallback(&packet_request_callback_));
// Since we call Decode, we need to provide a valid receive callback.
// However, for the purposes of these tests, we ignore the callbacks.
EXPECT_CALL(receive_callback_, OnIncomingPayloadType(_)).Times(AnyNumber());
EXPECT_CALL(receive_callback_, OnDecoderImplementationName(_))
.Times(AnyNumber());
receiver_.RegisterReceiveCallback(&receive_callback_);
}
WebRtcRTPHeader GetDefaultVp8Header() const {
WebRtcRTPHeader header = {};
header.frameType = kEmptyFrame;
header.header.markerBit = false;
header.header.payloadType = kUnusedPayloadType;
header.header.ssrc = 1;
header.header.headerLength = 12;
header.video_header().codec = kVideoCodecVP8;
return header;
}
void InsertAndVerifyPaddingFrame(const uint8_t* payload,
WebRtcRTPHeader* header) {
for (int j = 0; j < 5; ++j) {
// Padding only packets are passed to the VCM with payload size 0.
EXPECT_EQ(0, receiver_.IncomingPacket(payload, 0, *header));
++header->header.sequenceNumber;
}
receiver_.Process();
EXPECT_CALL(decoder_, Decode(_, _, _, _)).Times(0);
EXPECT_EQ(VCM_FRAME_NOT_READY, receiver_.Decode(kMaxWaitTimeMs));
}
void InsertAndVerifyDecodableFrame(const uint8_t* payload,
size_t length,
WebRtcRTPHeader* header) {
EXPECT_EQ(0, receiver_.IncomingPacket(payload, length, *header));
++header->header.sequenceNumber;
EXPECT_CALL(packet_request_callback_, ResendPackets(_, _)).Times(0);
receiver_.Process();
EXPECT_CALL(decoder_, Decode(_, _, _, _)).Times(1);
EXPECT_EQ(0, receiver_.Decode(kMaxWaitTimeMs));
}
SimulatedClock clock_;
VideoCodec settings_;
NiceMock<MockVideoDecoder> decoder_;
NiceMock<MockPacketRequestCallback> packet_request_callback_;
VCMTiming timing_;
MockVCMReceiveCallback receive_callback_;
VideoReceiver receiver_;
};
TEST_F(TestVideoReceiver, PaddingOnlyFrames) {
const size_t kPaddingSize = 220;
const uint8_t kPayload[kPaddingSize] = {0};
WebRtcRTPHeader header = GetDefaultVp8Header();
header.header.paddingLength = kPaddingSize;
for (int i = 0; i < 10; ++i) {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, _)).Times(0);
InsertAndVerifyPaddingFrame(kPayload, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
}
TEST_F(TestVideoReceiver, PaddingOnlyFramesWithLosses) {
const size_t kFrameSize = 1200;
const size_t kPaddingSize = 220;
const uint8_t kPayload[kFrameSize] = {0};
WebRtcRTPHeader header = GetDefaultVp8Header();
header.header.paddingLength = kPaddingSize;
header.video_header().video_type_header.emplace<RTPVideoHeaderVP8>();
// Insert one video frame to get one frame decoded.
header.frameType = kVideoFrameKey;
header.video_header().is_first_packet_in_frame = true;
header.header.markerBit = true;
InsertAndVerifyDecodableFrame(kPayload, kFrameSize, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
header.frameType = kEmptyFrame;
header.video_header().is_first_packet_in_frame = false;
header.header.markerBit = false;
// Insert padding frames.
for (int i = 0; i < 10; ++i) {
// Lose one packet from the 6th frame.
if (i == 5) {
++header.header.sequenceNumber;
}
// Lose the 4th frame.
if (i == 3) {
header.header.sequenceNumber += 5;
} else {
if (i > 3 && i < 5) {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, 5)).Times(1);
} else if (i >= 5) {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, 6)).Times(1);
} else {
EXPECT_CALL(packet_request_callback_, ResendPackets(_, _)).Times(0);
}
InsertAndVerifyPaddingFrame(kPayload, &header);
}
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
}
TEST_F(TestVideoReceiver, PaddingOnlyAndVideo) {
const size_t kFrameSize = 1200;
const size_t kPaddingSize = 220;
const uint8_t kPayload[kFrameSize] = {0};
WebRtcRTPHeader header = GetDefaultVp8Header();
header.video_header().is_first_packet_in_frame = false;
header.header.paddingLength = kPaddingSize;
auto& vp8_header =
header.video.video_type_header.emplace<RTPVideoHeaderVP8>();
vp8_header.pictureId = -1;
vp8_header.tl0PicIdx = -1;
for (int i = 0; i < 3; ++i) {
// Insert 2 video frames.
for (int j = 0; j < 2; ++j) {
if (i == 0 && j == 0) // First frame should be a key frame.
header.frameType = kVideoFrameKey;
else
header.frameType = kVideoFrameDelta;
header.video_header().is_first_packet_in_frame = true;
header.header.markerBit = true;
InsertAndVerifyDecodableFrame(kPayload, kFrameSize, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
// Insert 2 padding only frames.
header.frameType = kEmptyFrame;
header.video_header().is_first_packet_in_frame = false;
header.header.markerBit = false;
for (int j = 0; j < 2; ++j) {
// InsertAndVerifyPaddingFrame(kPayload, &header);
clock_.AdvanceTimeMilliseconds(33);
header.header.timestamp += 3000;
}
}
}
} // namespace
} // namespace vcm
} // namespace webrtc
<|endoftext|>
|
<commit_before>/* Copyright (c) 2010-2014 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <signal.h>
#include <boost/version.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <fstream>
#include "Common.h"
#include "Transport.h"
#include "OptionParser.h"
#include "PcapFile.h"
#include "ShortMacros.h"
#include "PerfCounter.h"
#include "StringUtil.h"
namespace RAMCloud {
/**
* Parse the common RAMCloud command line options and store
* them in #options.
*
* \param argc
* Count of the number of elements in argv.
* \param argv
* A Unix style word tokenized array of command arguments including
* the executable name as argv[0].
*/
OptionParser::OptionParser(int argc,
char* argv[])
: options()
, allOptions("Usage")
, appOptions()
{
setup(argc, argv);
}
/**
* Parse the common RAMCloud command line options and store
* them in #options as well as additional application-specific options.
*
* \param appOptions
* The OptionsDescription to be parsed. Each of the options that are
* part of it should include a pointer to where the value should be
* stored after parsing. See boost::program_options::options_description
* for details.
* \param argc
* Count of the number of elements in argv.
* \param argv
* A Unix style word tokenized array of command arguments including
* the executable name as argv[0].
*/
OptionParser::OptionParser(
const OptionsDescription& appOptions,
int argc,
char* argv[])
: options()
, allOptions("Usage")
, appOptions(appOptions)
{
setup(argc, argv);
}
/// Print program option documentation to stderr.
void
OptionParser::usage() const
{
std::cerr << allOptions << std::endl;
}
/**
* Print program option documentation to stderr and exit the program with
* failure.
*/
void
OptionParser::usageAndExit() const
{
usage();
exit(EXIT_FAILURE);
}
/**
* Signal handler which invokes gdb on segfault for ease of debugging.
*/
char* executableName;
void invokeGDB(int signum) {
// Prevent repeated invocation of gdb when the server suicides
if (signum == SIGABRT)
signal(SIGINT, SIG_DFL);
char buf[256];
snprintf(buf, sizeof(buf), "/usr/bin/gdb %s %d", executableName, getpid());
system(buf);
}
/**
* Internal method to do the heavy lifting of parsing the command line.
*
* Parses both application-specific and common options aborting and
* printing usage if the --help flag is encountered.
*
* \param argc
* Count of the number of elements in argv.
* \param argv
* A Unix style word tokenized array of command arguments including
* the executable name as argv[0].
*/
void
OptionParser::setup(int argc, char* argv[])
{
executableName = argv[0];
namespace po = ProgramOptions;
try {
string defaultLogLevel;
string logFile;
vector<string> logLevels;
string configFile(".ramcloud");
bool debugOnSegfault = false;
// Basic options supported on the command line of all apps
OptionsDescription commonOptions("Common");
commonOptions.add_options()
("help", "Produce help message")
("c,config",
po::value<string>(&configFile)->
default_value(".ramcloud"),
"Specify a path to a config file");
// Options allowed on command line and in config file for all apps
OptionsDescription configOptions("RAMCloud");
configOptions.add_options()
("logFile",
po::value<string>(&logFile),
"File to use for log messages")
("logLevel,l",
po::value<string>(&defaultLogLevel)->
default_value("NOTICE"),
"Default log level for all modules, see LogLevel")
("logModule",
po::value<vector<string> >(&logLevels),
"One or more module-specific log levels, specified in the form "
"moduleName=level")
("coordinator,C",
po::value<string>(&options.coordinatorLocator)->
default_value("fast+udp:host=0.0.0.0,port=12246"),
"Service locator where the coordinator can be contacted; "
"Ignored if --externalStorage is specified. Deprecated "
"and doesn't support rollover between coordinators; use "
"--externalStorage and --clusterName instead).")
("externalStorage,x",
po::value<string>(&options.externalStorageLocator),
"Locator for external storage server containing cluster "
"configuration information")
("clusterName",
ProgramOptions::value<string>(&options.clusterName)->
default_value("main"),
"Name of the cluster. Allows different cluster (such as one "
"for testing and one for production) to coexist. On servers "
"running backups, the name '__unnamed__' is special and never "
"matches any existing cluster name (even itself), so it "
"guarantees all stored replicas are discarded on start; all "
"replicas created by this process are discarded by future "
"backups.")
("local,L",
po::value<string>(&options.localLocator)->
default_value("fast+udp:host=0.0.0.0,port=12242"),
"Service locator to listen on")
("pcapFile",
po::value<string>(&options.pcapFilePath)->
default_value(""),
"File to log transmitted and received packets to in pcap format. "
"Only works with InfUdDriver based transports for now; "
"use tcpdump to capture kernel-based packet formats.")
("timeout",
ProgramOptions::value<uint32_t>(&options.sessionTimeout)->
default_value(0),
"How long transports should wait (ms) before declaring that a "
"client connection for each rpc session is dead."
"0 means use transport-specific default.")
("portTimeout",
ProgramOptions::value<int32_t>(&options.portTimeout)->
default_value(-1), // Overriding to the initial value.
"How long transports should wait (ms) before declaring that a "
"server connection for listening client requests is dead."
"0 means use transport-specific default."
"Negative number means disabling the timer.")
("debugOnSegfault",
ProgramOptions::bool_switch(&debugOnSegfault),
"Whether or not this application should drop to debugger"
"on segfault")
("debugXXX",
ProgramOptions::value<uint64_t>(&debugXXX)->
default_value(0ul),
"Spare option used for debugging and experimentation; the meaning "
"is determined by the experiment. This option should be not be "
"specified during production but will have no effect if specified."
)
("debugYYY",
ProgramOptions::value<double>(&debugYYY)->
default_value(0),
"Spare option used for debugging and experimentation; the meaning "
"is determined by the experiment. This option should be not be"
"specified during production but will have no effect if specified."
); // NOLINT
// Do one pass with just help/config file options so we can get
// the alternate config file location, if specified. Then
// do a second pass with all the options for real.
po::variables_map throwAway;
// Need to skip unknown parameters since we'll repeat the parsing
// once we know which config file to read in.
po::store(po::command_line_parser(argc, argv).options(commonOptions)
.allow_unregistered()
.run(),
throwAway);
po::notify(throwAway);
allOptions.add(commonOptions).add(configOptions).add(appOptions);
po::variables_map vm;
std::ifstream configInput(configFile.c_str());
po::store(po::parse_command_line(argc, argv, allOptions), vm);
// true here lets config files contain unknown key/value pairs
// this lets a config file be used for multiple programs
po::store(po::parse_config_file(configInput, allOptions, true), vm);
po::notify(vm);
if (vm.count("help"))
usageAndExit();
if (logFile.size() != 0) {
Logger::get().setLogFile(logFile.c_str());
/**
* In the code below, we extract the name of the current server
* and the log path prefix, and feed them to the Performance
* framework.
*
* We assume that logFile is a relative or absolute path
* containing at least one directory, followed by a filename
* consisting of the name of the server followed by the string
* ".log"
*
* Here is a sample of a valid logFileName:
* logs/20140206192029/server2.rc03.log
*/
vector<std::string> a = StringUtil::split(logFile, '/');
std::string s = a.back();
std::string serverName = s.substr(0, s.size() - 4);
std::string logPath = logFile.substr(0, logFile.size() - s.size());
Perf::setNameAndPath(serverName, logPath);
}
Logger::get().setLogLevels(defaultLogLevel);
foreach (auto moduleLevel, logLevels) {
auto pos = moduleLevel.find("=");
if (pos == string::npos) {
LOG(WARNING, "Bad log module level format: %s, "
"example moduleName=3", moduleLevel.c_str());
continue;
}
auto name = moduleLevel.substr(0, pos);
auto level = moduleLevel.substr(pos + 1);
Logger::get().setLogLevel(name, level);
}
if (options.pcapFilePath != "")
pcapFile.construct(options.pcapFilePath.c_str(),
PcapFile::LinkType::ETHERNET);
if (debugOnSegfault) {
signal(SIGSEGV, invokeGDB);
signal(SIGABRT, invokeGDB);
}
}
catch (po::multiple_occurrences& e) {
// This clause provides a more understandable error message
// (the default is fairly opaque).
#if BOOST_VERSION >= 104200 // get_option_name introduced in Boost 1.4.2
throw po::error(format("command-line option '%s' occurs multiple times",
e.get_option_name().c_str()));
#else
throw po::error("command-line option occurs multiple times");
#endif
}
}
} // end RAMCloud
<commit_msg>Fixed a -Werror=unused-result in OptionParser.cc<commit_after>/* Copyright (c) 2010-2014 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <signal.h>
#include <boost/version.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <fstream>
#include "Common.h"
#include "Transport.h"
#include "OptionParser.h"
#include "PcapFile.h"
#include "ShortMacros.h"
#include "PerfCounter.h"
#include "StringUtil.h"
namespace RAMCloud {
/**
* Parse the common RAMCloud command line options and store
* them in #options.
*
* \param argc
* Count of the number of elements in argv.
* \param argv
* A Unix style word tokenized array of command arguments including
* the executable name as argv[0].
*/
OptionParser::OptionParser(int argc,
char* argv[])
: options()
, allOptions("Usage")
, appOptions()
{
setup(argc, argv);
}
/**
* Parse the common RAMCloud command line options and store
* them in #options as well as additional application-specific options.
*
* \param appOptions
* The OptionsDescription to be parsed. Each of the options that are
* part of it should include a pointer to where the value should be
* stored after parsing. See boost::program_options::options_description
* for details.
* \param argc
* Count of the number of elements in argv.
* \param argv
* A Unix style word tokenized array of command arguments including
* the executable name as argv[0].
*/
OptionParser::OptionParser(
const OptionsDescription& appOptions,
int argc,
char* argv[])
: options()
, allOptions("Usage")
, appOptions(appOptions)
{
setup(argc, argv);
}
/// Print program option documentation to stderr.
void
OptionParser::usage() const
{
std::cerr << allOptions << std::endl;
}
/**
* Print program option documentation to stderr and exit the program with
* failure.
*/
void
OptionParser::usageAndExit() const
{
usage();
exit(EXIT_FAILURE);
}
/**
* Signal handler which invokes gdb on segfault for ease of debugging.
*/
char* executableName;
void invokeGDB(int signum) {
// Prevent repeated invocation of gdb when the server suicides
if (signum == SIGABRT)
signal(SIGINT, SIG_DFL);
char buf[256];
snprintf(buf, sizeof(buf), "/usr/bin/gdb %s %d", executableName, getpid());
int ret = system(buf);
if (ret == -1) {
std::cerr << "Failed to attach gdb upon receiving the signal "
<< strsignal(signum) << std::endl;
}
}
/**
* Internal method to do the heavy lifting of parsing the command line.
*
* Parses both application-specific and common options aborting and
* printing usage if the --help flag is encountered.
*
* \param argc
* Count of the number of elements in argv.
* \param argv
* A Unix style word tokenized array of command arguments including
* the executable name as argv[0].
*/
void
OptionParser::setup(int argc, char* argv[])
{
executableName = argv[0];
namespace po = ProgramOptions;
try {
string defaultLogLevel;
string logFile;
vector<string> logLevels;
string configFile(".ramcloud");
bool debugOnSegfault = false;
// Basic options supported on the command line of all apps
OptionsDescription commonOptions("Common");
commonOptions.add_options()
("help", "Produce help message")
("c,config",
po::value<string>(&configFile)->
default_value(".ramcloud"),
"Specify a path to a config file");
// Options allowed on command line and in config file for all apps
OptionsDescription configOptions("RAMCloud");
configOptions.add_options()
("logFile",
po::value<string>(&logFile),
"File to use for log messages")
("logLevel,l",
po::value<string>(&defaultLogLevel)->
default_value("NOTICE"),
"Default log level for all modules, see LogLevel")
("logModule",
po::value<vector<string> >(&logLevels),
"One or more module-specific log levels, specified in the form "
"moduleName=level")
("coordinator,C",
po::value<string>(&options.coordinatorLocator)->
default_value("fast+udp:host=0.0.0.0,port=12246"),
"Service locator where the coordinator can be contacted; "
"Ignored if --externalStorage is specified. Deprecated "
"and doesn't support rollover between coordinators; use "
"--externalStorage and --clusterName instead).")
("externalStorage,x",
po::value<string>(&options.externalStorageLocator),
"Locator for external storage server containing cluster "
"configuration information")
("clusterName",
ProgramOptions::value<string>(&options.clusterName)->
default_value("main"),
"Name of the cluster. Allows different cluster (such as one "
"for testing and one for production) to coexist. On servers "
"running backups, the name '__unnamed__' is special and never "
"matches any existing cluster name (even itself), so it "
"guarantees all stored replicas are discarded on start; all "
"replicas created by this process are discarded by future "
"backups.")
("local,L",
po::value<string>(&options.localLocator)->
default_value("fast+udp:host=0.0.0.0,port=12242"),
"Service locator to listen on")
("pcapFile",
po::value<string>(&options.pcapFilePath)->
default_value(""),
"File to log transmitted and received packets to in pcap format. "
"Only works with InfUdDriver based transports for now; "
"use tcpdump to capture kernel-based packet formats.")
("timeout",
ProgramOptions::value<uint32_t>(&options.sessionTimeout)->
default_value(0),
"How long transports should wait (ms) before declaring that a "
"client connection for each rpc session is dead."
"0 means use transport-specific default.")
("portTimeout",
ProgramOptions::value<int32_t>(&options.portTimeout)->
default_value(-1), // Overriding to the initial value.
"How long transports should wait (ms) before declaring that a "
"server connection for listening client requests is dead."
"0 means use transport-specific default."
"Negative number means disabling the timer.")
("debugOnSegfault",
ProgramOptions::bool_switch(&debugOnSegfault),
"Whether or not this application should drop to debugger"
"on segfault")
("debugXXX",
ProgramOptions::value<uint64_t>(&debugXXX)->
default_value(0ul),
"Spare option used for debugging and experimentation; the meaning "
"is determined by the experiment. This option should be not be "
"specified during production but will have no effect if specified."
)
("debugYYY",
ProgramOptions::value<double>(&debugYYY)->
default_value(0),
"Spare option used for debugging and experimentation; the meaning "
"is determined by the experiment. This option should be not be"
"specified during production but will have no effect if specified."
); // NOLINT
// Do one pass with just help/config file options so we can get
// the alternate config file location, if specified. Then
// do a second pass with all the options for real.
po::variables_map throwAway;
// Need to skip unknown parameters since we'll repeat the parsing
// once we know which config file to read in.
po::store(po::command_line_parser(argc, argv).options(commonOptions)
.allow_unregistered()
.run(),
throwAway);
po::notify(throwAway);
allOptions.add(commonOptions).add(configOptions).add(appOptions);
po::variables_map vm;
std::ifstream configInput(configFile.c_str());
po::store(po::parse_command_line(argc, argv, allOptions), vm);
// true here lets config files contain unknown key/value pairs
// this lets a config file be used for multiple programs
po::store(po::parse_config_file(configInput, allOptions, true), vm);
po::notify(vm);
if (vm.count("help"))
usageAndExit();
if (logFile.size() != 0) {
Logger::get().setLogFile(logFile.c_str());
/**
* In the code below, we extract the name of the current server
* and the log path prefix, and feed them to the Performance
* framework.
*
* We assume that logFile is a relative or absolute path
* containing at least one directory, followed by a filename
* consisting of the name of the server followed by the string
* ".log"
*
* Here is a sample of a valid logFileName:
* logs/20140206192029/server2.rc03.log
*/
vector<std::string> a = StringUtil::split(logFile, '/');
std::string s = a.back();
std::string serverName = s.substr(0, s.size() - 4);
std::string logPath = logFile.substr(0, logFile.size() - s.size());
Perf::setNameAndPath(serverName, logPath);
}
Logger::get().setLogLevels(defaultLogLevel);
foreach (auto moduleLevel, logLevels) {
auto pos = moduleLevel.find("=");
if (pos == string::npos) {
LOG(WARNING, "Bad log module level format: %s, "
"example moduleName=3", moduleLevel.c_str());
continue;
}
auto name = moduleLevel.substr(0, pos);
auto level = moduleLevel.substr(pos + 1);
Logger::get().setLogLevel(name, level);
}
if (options.pcapFilePath != "")
pcapFile.construct(options.pcapFilePath.c_str(),
PcapFile::LinkType::ETHERNET);
if (debugOnSegfault) {
signal(SIGSEGV, invokeGDB);
signal(SIGABRT, invokeGDB);
}
}
catch (po::multiple_occurrences& e) {
// This clause provides a more understandable error message
// (the default is fairly opaque).
#if BOOST_VERSION >= 104200 // get_option_name introduced in Boost 1.4.2
throw po::error(format("command-line option '%s' occurs multiple times",
e.get_option_name().c_str()));
#else
throw po::error("command-line option occurs multiple times");
#endif
}
}
} // end RAMCloud
<|endoftext|>
|
<commit_before>
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "Platform.h"
#include <webrtc/base/ssladapter.h>
#include <webrtc/base/macsocketserver.h>
#include <webrtc/base/maccocoasocketserver.h>
using namespace WebRTC;
class PlatformWorker : public rtc::Thread {
public:
explicit PlatformWorker(rtc::SocketServer* ss = nullptr);
virtual void Run();
};
PlatformWorker::PlatformWorker(rtc::SocketServer* ss) : rtc::Thread(ss) {
SetAllowBlockingCalls(true);
}
void PlatformWorker::Run() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
bool running = false;
do {
running = rtc::Thread::ProcessMessages(1);
} while(running);
}
rtc::MacCFSocketServer ss;
PlatformWorker *worker;
void Platform::Init() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
worker = new PlatformWorker(&ss);
worker->Start();
rtc::InitializeSSL();
rtc::ThreadManager::Instance()->SetCurrentThread(worker);
if (rtc::ThreadManager::Instance()->CurrentThread() != worker) {
LOG(LS_ERROR) << "Internal Thread Error!";
abort();
}
}
void Platform::Dispose() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
worker->Stop();
if (rtc::ThreadManager::Instance()->CurrentThread() == worker) {
rtc::ThreadManager::Instance()->SetCurrentThread(NULL);
}
rtc::CleanupSSL();
delete worker;
}<commit_msg>Fix Typo<commit_after>
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa)
*
* 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 "Platform.h"
#include <webrtc/base/ssladapter.h>
#include <webrtc/base/macsocketserver.h>
#include <webrtc/base/maccocoasocketserver.h>
using namespace WebRTC;
class PlatformWorker : public rtc::Thread {
public:
explicit PlatformWorker(rtc::SocketServer* ss = nullptr);
virtual void Run();
};
PlatformWorker::PlatformWorker(rtc::SocketServer* ss) : rtc::Thread(ss) {
}
void PlatformWorker::Run() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
bool running = false;
rtc::Thread::SetAllowBlockingCalls(true);
do {
running = rtc::Thread::ProcessMessages(1);
} while(running);
}
rtc::MacCFSocketServer ss;
PlatformWorker *worker;
void Platform::Init() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
worker = new PlatformWorker(&ss);
worker->Start();
rtc::InitializeSSL();
rtc::ThreadManager::Instance()->SetCurrentThread(worker);
if (rtc::ThreadManager::Instance()->CurrentThread() != worker) {
LOG(LS_ERROR) << "Internal Thread Error!";
abort();
}
}
void Platform::Dispose() {
LOG(LS_INFO) << __PRETTY_FUNCTION__;
worker->Stop();
if (rtc::ThreadManager::Instance()->CurrentThread() == worker) {
rtc::ThreadManager::Instance()->SetCurrentThread(NULL);
}
rtc::CleanupSSL();
delete worker;
}<|endoftext|>
|
<commit_before>/*
*
* Copyright 2019 gRPC 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.
*
*/
#if defined(GRPC_WINSOCK_SOCKET)
#include <vector>
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/iocp_windows.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_windows.h"
#include "src/core/lib/surface/init.h"
#include "test/core/util/test_config.h"
struct ThreadParams {
gpr_cv cv;
gpr_mu mu;
int complete;
};
int main(int argc, char** argv) {
grpc_init();
// Create three threads that all start queueing for work.
//
// The first one becomes the active poller for work and the two other
// threads go into the poller queue.
//
// When work arrives, the first one notifies the next active poller,
// this wakes the second thread - however all this does is return from
// the grpc_pollset_work function. It's up to that thread to figure
// out if it still wants to queue for more work or if it should kick
// other pollers.
//
// Previously that kick only affected pollers in the same pollset, thus
// leaving the third thread stuck in the poller queue. Now the pollset-
// specific grpc_pollset_kick will also kick pollers from other pollsets
// if there are no pollers in the current pollset. This frees up the
// last thread and completes the test.
ThreadParams params = {};
gpr_cv_init(¶ms.cv);
gpr_mu_init(¶ms.mu);
std::vector<grpc_core::Thread> threads;
for (int i = 0; i < 3; i++) {
grpc_core::Thread thd(
"Poller",
[](void* params) {
ThreadParams* tparams = static_cast<ThreadParams*>(params);
grpc_core::ExecCtx exec_ctx;
gpr_mu* mu;
grpc_pollset pollset = {};
grpc_pollset_init(&pollset, &mu);
gpr_mu_lock(mu);
// Queue for work and once we're done, make sure to kick the remaining
// threads.
grpc_millis deadline = grpc_timespec_to_millis_round_up(
grpc_timeout_seconds_to_deadline(5));
grpc_error* error;
error = grpc_pollset_work(&pollset, NULL, deadline);
error = grpc_pollset_kick(&pollset, NULL);
gpr_mu_unlock(mu);
{
gpr_mu_lock(&tparams->mu);
tparams->complete++;
gpr_cv_signal(&tparams->cv);
gpr_mu_unlock(&tparams->mu);
}
},
¶ms);
thd.Start();
threads.push_back(std::move(thd));
}
// Wait for the threads to start working and then kick one of them.
gpr_sleep_until(grpc_timeout_milliseconds_to_deadline(10));
grpc_iocp_kick();
// Wait for the threads to complete.
gpr_timespec deadline = grpc_timeout_seconds_to_deadline(1);
gpr_mu_lock(¶ms.mu);
while (params.complete != 3 && !gpr_cv_wait(¶ms.cv, ¶ms.mu, deadline))
;
if (params.complete != 3) {
gpr_mu_unlock(¶ms.mu);
for (auto& t : threads) t.Join();
return EXIT_FAILURE;
}
gpr_mu_unlock(¶ms.mu);
for (auto& t : threads) t.Join();
return EXIT_SUCCESS;
}
#else /* defined(GRPC_WINSOCK_SOCKET) */
int main(int /*argc*/, char** /*argv*/) { return 0; }
#endif
<commit_msg>Make the test more reliable<commit_after>/*
*
* Copyright 2019 gRPC 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 <vector>
#include <grpc/grpc.h>
#include <grpc/support/time.h>
#include "src/core/lib/gprpp/thd.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/iocp_windows.h"
#include "src/core/lib/iomgr/iomgr_internal.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/pollset_windows.h"
#include "src/core/lib/surface/init.h"
#include "test/core/util/test_config.h"
#if defined(GRPC_WINSOCK_SOCKET)
// At least three threads are required to reproduce #18848
const size_t THREADS = 3;
struct ThreadParams {
gpr_cv cv;
gpr_mu mu;
int complete;
int queuing;
gpr_mu* pollset_mu[THREADS];
};
int main(int argc, char** argv) {
grpc_init();
// Create the threads that all start queueing for work.
//
// The first one becomes the active poller for work and the two other
// threads go into the poller queue.
//
// When work arrives, the first one notifies the next queued poller,
// this wakes the second thread - however all this does is return from
// the grpc_pollset_work function. It's up to that thread to figure
// out if it still wants to queue for more work or if it should kick
// other pollers.
//
// Previously that kick only affected pollers in the same pollset, thus
// leaving the other threads stuck in the poller queue. Now the pollset-
// specific grpc_pollset_kick will also kick pollers from other pollsets
// if there are no pollers in the current pollset. This frees up the
// last threads and completes the test.
ThreadParams params = {};
gpr_cv_init(¶ms.cv);
gpr_mu_init(¶ms.mu);
std::vector<grpc_core::Thread> threads;
for (int i = 0; i < THREADS; i++) {
grpc_core::Thread thd(
"Poller",
[](void* params) {
ThreadParams* tparams = static_cast<ThreadParams*>(params);
grpc_core::ExecCtx exec_ctx;
gpr_mu* mu;
grpc_pollset pollset = {};
grpc_pollset_init(&pollset, &mu);
// Lock the pollset mutex before notifying the test runner thread that
// one more thread is queuing. This allows the test runner thread to
// wait for all threads to be queued before sending the first kick by
// waiting for the mutexes to be released, which happens in
// gpr_pollset_work when the poller is queued.
gpr_mu_lock(mu);
gpr_mu_lock(&tparams->mu);
tparams->pollset_mu[tparams->queuing] = mu;
tparams->queuing++;
gpr_cv_signal(&tparams->cv);
gpr_mu_unlock(&tparams->mu);
// Queue for work and once we're done, make sure to kick the remaining
// threads.
grpc_error* error;
error = grpc_pollset_work(&pollset, NULL, GRPC_MILLIS_INF_FUTURE);
error = grpc_pollset_kick(&pollset, NULL);
gpr_mu_unlock(mu);
gpr_mu_lock(&tparams->mu);
tparams->complete++;
gpr_cv_signal(&tparams->cv);
gpr_mu_unlock(&tparams->mu);
},
¶ms);
thd.Start();
threads.push_back(std::move(thd));
}
// Wait for all three threads to be queuing.
gpr_mu_lock(¶ms.mu);
while (
params.queuing != THREADS &&
!gpr_cv_wait(¶ms.cv, ¶ms.mu, gpr_inf_future(GPR_CLOCK_REALTIME)))
;
gpr_mu_unlock(¶ms.mu);
// Wait for the mutexes to be released. This indicates that the threads have
// entered the work wait.
//
// At least currently these are essentially all references to the same global
// pollset mutex, but we are still waiting on them once for each thread in
// the case this ever changes.
for (int i = 0; i < THREADS; i++) {
gpr_mu_lock(params.pollset_mu[i]);
gpr_mu_unlock(params.pollset_mu[i]);
}
grpc_iocp_kick();
// Wait for the threads to complete.
gpr_mu_lock(¶ms.mu);
while (
params.complete != THREADS &&
!gpr_cv_wait(¶ms.cv, ¶ms.mu, gpr_inf_future(GPR_CLOCK_REALTIME)))
;
gpr_mu_unlock(¶ms.mu);
for (auto& t : threads) t.Join();
return EXIT_SUCCESS;
}
#else /* defined(GRPC_WINSOCK_SOCKET) */
int main(int /*argc*/, char** /*argv*/) { return 0; }
#endif
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE "test_read_dihedral_angle_interaction"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/input/read_local_interaction.hpp>
BOOST_AUTO_TEST_CASE(read_dihedral_angle_harmonic)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "Harmonic"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::HarmonicPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_go_contact)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "ClementiDihedral"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::ClementiDihedralPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_gaussian)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "Gaussian"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::PeriodicGaussianPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_periodic_gaussian)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "PeriodicGaussian"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::PeriodicGaussianPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_flexible_local)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "FlexibleLocalDihedral"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::FlexibleLocalDihedralPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_cosine)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "Cosine"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::CosinePotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
<commit_msg>test: remove test for removed feature<commit_after>#define BOOST_TEST_MODULE "test_read_dihedral_angle_interaction"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/input/read_local_interaction.hpp>
BOOST_AUTO_TEST_CASE(read_dihedral_angle_harmonic)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "Harmonic"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::HarmonicPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_go_contact)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "ClementiDihedral"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::ClementiDihedralPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_gaussian)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "Gaussian"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::PeriodicGaussianPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_flexible_local)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "FlexibleLocalDihedral"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::FlexibleLocalDihedralPotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
BOOST_AUTO_TEST_CASE(read_dihedral_angle_cosine)
{
mjolnir::LoggerManager::set_default_logger("test_read_dihedral_angle_interaction.log");
using traits_type = mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>;
using real_type = traits_type::real_type;
{
using namespace toml::literals;
const toml::value v = u8R"(
interaction = "DihedralAngle"
potential = "Cosine"
topology = "none"
parameters = []
)"_toml;
const auto base = mjolnir::read_local_interaction<traits_type>(v);
BOOST_TEST(static_cast<bool>(base));
const auto derv = dynamic_cast<mjolnir::DihedralAngleInteraction<
traits_type, mjolnir::CosinePotential<real_type>>*
>(base.get()); // check the expected type is contained
BOOST_TEST(static_cast<bool>(derv));
}
}
<|endoftext|>
|
<commit_before>
#include "AbstractState.h"
#include "DataStructures.h"
#include <assert.h>
#if !defined CATCH_CONFIG_MAIN
#if defined ENABLE_CATCH
#include "Tests.h"
#include "catch.hpp"
static int inputs[] = {
CoolProp::DmolarT_INPUTS,
CoolProp::SmolarT_INPUTS,
CoolProp::HmolarT_INPUTS,
CoolProp::TUmolar_INPUTS,
CoolProp::DmolarP_INPUTS,
CoolProp::DmolarHmolar_INPUTS,
CoolProp::DmolarSmolar_INPUTS,
CoolProp::DmolarUmolar_INPUTS,
/*
CoolProp::HmolarP_INPUTS,
CoolProp::PSmolar_INPUTS,
CoolProp::PUmolar_INPUTS,
*/
/*
CoolProp::HmolarSmolar_INPUTS,
CoolProp::HmolarUmolar_INPUTS,
CoolProp::SmolarUmolar_INPUTS
*/
};
class ConsistencyFixture
{
protected:
long double hmolar, pmolar, smolar, umolar, rhomolar, T, p, x1, x2;
CoolProp::AbstractState *pState;
int pair;
public:
ConsistencyFixture(){
pState = NULL;
}
~ConsistencyFixture(){
delete pState;
}
void set_backend(std::string backend, std::string fluid_name){
pState = CoolProp::AbstractState::factory(backend, fluid_name);
}
void set_pair(int pair){
this->pair = pair;
}
void set_TP(long double T, long double p)
{
this->T = T; this->p = p;
CoolProp::AbstractState &State = *pState;
// Start with T,P as inputs, cycle through all the other pairs that are supported
State.update(CoolProp::PT_INPUTS, p, T);
// Set the other state variables
rhomolar = State.rhomolar(); hmolar = State.hmolar(); smolar = State.smolar(); umolar = State.umolar();
}
void get_variables()
{
CoolProp::AbstractState &State = *pState;
switch (pair)
{
/// In this group, T is one of the known inputs, iterate for the other one (easy)
case CoolProp::HmolarT_INPUTS:
x1 = hmolar; x2 = T; break;
case CoolProp::SmolarT_INPUTS:
x1 = smolar; x2 = T; break;
case CoolProp::TUmolar_INPUTS:
x1 = T; x2 = umolar; break;
case CoolProp::DmolarT_INPUTS:
x1 = rhomolar; x2 = T; break;
/// In this group, D is one of the known inputs, iterate for the other one (a little bit harder)
case CoolProp::DmolarHmolar_INPUTS:
x1 = rhomolar; x2 = hmolar; break;
case CoolProp::DmolarSmolar_INPUTS:
x1 = rhomolar; x2 = smolar; break;
case CoolProp::DmolarUmolar_INPUTS:
x1 = rhomolar; x2 = umolar; break;
case CoolProp::DmolarP_INPUTS:
x1 = rhomolar; x2 = p; break;
/// In this group, p is one of the known inputs (a little less easy)
case CoolProp::HmolarP_INPUTS:
x1 = hmolar; x2 = p; break;
case CoolProp::PSmolar_INPUTS:
x1 = p; x2 = smolar; break;
case CoolProp::PUmolar_INPUTS:
x1 = p; x2 = umolar; break;
case CoolProp::HmolarSmolar_INPUTS:
x1 = hmolar; x2 = smolar; break;
case CoolProp::SmolarUmolar_INPUTS:
x1 = smolar; x2 = umolar; break;
}
}
void single_phase_consistency_check()
{
CoolProp::AbstractState &State = *pState;
State.update(pair, x1, x2);
// Make sure we end up back at the same temperature and pressure we started out with
if(fabs(T-State.T()) > 1e-2) throw CoolProp::ValueError(format("Error on T [%g K] is greater than 1e-2",fabs(State.T()-T)));
if(fabs(p-State.p())/p*100 > 1e-2) throw CoolProp::ValueError(format("Error on p [%g %%] is greater than 1e-2 %%",fabs(p-State.p())/p ));
}
};
TEST_CASE_METHOD(ConsistencyFixture, "Test all input pairs for CO2 using all valid backends", "[]")
{
CHECK_NOTHROW(set_backend("HEOS", "CO2"));
int inputsN = sizeof(inputs)/sizeof(inputs[0]);
for (double p = 600000; p < 800000000.0; p *= 5)
{
for (double T = 220; T < pState->Tmax(); T += 5)
{
CHECK_NOTHROW(set_TP(T, p));
for (int i = 0; i < inputsN; ++i)
{
int pair = inputs[i];
std::string pair_desc = CoolProp::get_input_pair_short_desc(pair);
set_pair(pair);
CAPTURE(pair_desc);
CAPTURE(T);
CAPTURE(p);
get_variables();
CAPTURE(x1);
CAPTURE(x2);
CHECK_NOTHROW(single_phase_consistency_check());
}
}
}
}
static Catch::Session session; // There must be exactly one instance
#endif
int run_fast_tests()
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
config.testsOrTags.push_back("[fast]");
session.useConfigData(config);
return session.run();
#else
return 0;
#endif
}
int run_not_slow_tests()
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
config.testsOrTags.push_back("~[slow]");
session.useConfigData(config);
time_t t1, t2;
t1 = clock();
session.run();
t2 = clock();
printf("Elapsed time for not slow tests: %g s",(double)(t2-t1)/CLOCKS_PER_SEC);
return 1;
#else
return 0;
#endif
}
int run_user_defined_tests(const std::vector<std::string> & tests_or_tags)
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
for (unsigned int i = 0; i < tests_or_tags.size(); i++)
{
config.testsOrTags.push_back(tests_or_tags[i]);
}
session.useConfigData(config);
time_t t1, t2;
t1 = clock();
session.run();
t2 = clock();
printf("Elapsed time for user defined tests: %g s",(double)(t2-t1)/CLOCKS_PER_SEC);
return 1;
#else
return 0;
#endif
}
void run_tests()
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
//config.shouldDebugBreak = true;
session.useConfigData(config);
session.run();
#else
#endif
}
#endif //!defined CATCH_CONFIG_MAIN
<commit_msg>Cleaned up Tests.cpp<commit_after>
#include "Tests.h"
#if defined ENABLE_CATCH
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
static Catch::Session session; // There must be exactly one instance
#endif // ENABLE_CATCH
int run_fast_tests()
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
config.testsOrTags.push_back("[fast]");
session.useConfigData(config);
return session.run();
#else
return 0;
#endif
}
int run_not_slow_tests()
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
config.testsOrTags.push_back("~[slow]");
session.useConfigData(config);
time_t t1, t2;
t1 = clock();
session.run();
t2 = clock();
printf("Elapsed time for not slow tests: %g s",(double)(t2-t1)/CLOCKS_PER_SEC);
return 1;
#else
return 0;
#endif
}
int run_user_defined_tests(const std::vector<std::string> & tests_or_tags)
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
for (unsigned int i = 0; i < tests_or_tags.size(); i++)
{
config.testsOrTags.push_back(tests_or_tags[i]);
}
session.useConfigData(config);
time_t t1, t2;
t1 = clock();
session.run();
t2 = clock();
printf("Elapsed time for user defined tests: %g s",(double)(t2-t1)/CLOCKS_PER_SEC);
return 1;
#else
return 0;
#endif
}
void run_tests()
{
#ifdef ENABLE_CATCH
Catch::ConfigData &config = session.configData();
config.testsOrTags.clear();
//config.shouldDebugBreak = true;
session.useConfigData(config);
session.run();
#endif
}
<|endoftext|>
|
<commit_before>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/intpoint.h" //To normalize vectors.
#include "utils/math.h" //For round_up_divide.
#include "utils/MinimumSpanningTree.h" //For the
#include "utils/polygonUtils.h" //For moveInside.
#include "TreeSupport.h"
#define SQRT_2 1.4142135623730950488 //Square root of 2.
namespace cura
{
TreeSupport::TreeSupport()
{
}
void TreeSupport::generateSupportAreas(SliceDataStorage& storage)
{
std::vector<std::unordered_set<Point>> contact_points;
contact_points.reserve(storage.support.supportLayers.size());
for (size_t layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) //Generate empty layers to store the points in.
{
contact_points.emplace_back();
}
for (SliceMeshStorage& mesh : storage.meshes)
{
if (!mesh.getSettingBoolean("support_tree_enable"))
{
return;
}
generateContactPoints(mesh, contact_points);
}
//Generate areas that have to be avoided.
const coord_t layer_height = storage.getSettingInMicrons("layer_height");
const double angle = storage.getSettingInAngleRadians("support_tree_angle");
const coord_t maximum_move_distance = tan(angle) * layer_height;
std::vector<Polygons> model_collision;
constexpr bool include_helper_parts = false;
model_collision.push_back(storage.getLayerOutlines(0, include_helper_parts));
//TODO: If allowing support to rest on model, these need to be just the model outlines.
for (size_t layer_nr = 1; layer_nr < storage.print_layer_count; layer_nr ++)
{
//Generate an area above the current layer where you'd still collide with the current layer if you were to move with at most maximum_move_distance.
model_collision.push_back(model_collision[layer_nr - 1].offset(-maximum_move_distance)); //Inset previous layer with maximum_move_distance to allow some movement.
model_collision[layer_nr] = model_collision[layer_nr].unionPolygons(storage.getLayerOutlines(layer_nr, include_helper_parts)); //Add current layer's collision to that.
}
//Use Minimum Spanning Tree to connect the points on each layer and move them while dropping them down.
for (size_t layer_nr = contact_points.size() - 1; layer_nr > 0; layer_nr--) //Skip layer 0, since we can't drop down the vertices there.
{
MinimumSpanningTree mst(contact_points[layer_nr]);
for (Point vertex : contact_points[layer_nr])
{
std::vector<Point> neighbours = mst.adjacentNodes(vertex);
if (neighbours.size() == 1) //This is a leaf.
{
Point direction = neighbours[0] - vertex;
if (vSize2(direction) < maximum_move_distance * maximum_move_distance) //Smaller than one step. Leave this one out.
{
continue;
}
Point motion = normal(direction, maximum_move_distance);
Point next_layer_vertex = vertex + motion;
constexpr coord_t xy_distance = 1000;
PolygonUtils::moveOutside(model_collision[layer_nr], next_layer_vertex, xy_distance, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(next_layer_vertex);
}
else //Not a leaf or just a single vertex.
{
constexpr coord_t xy_distance = 1000;
PolygonUtils::moveOutside(model_collision[layer_nr], vertex, xy_distance, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(vertex); //Just drop the leaves directly down.
//TODO: Avoid collisions.
}
}
}
//TODO: When reaching the bottom, cut away all edges of the MST that are still not contracted.
//TODO: Do a second pass of dropping down but with leftover edges removed.
//Placeholder to test with that generates a simple diamond at each contact point (without generating any trees yet).
for (size_t layer_nr = 0; layer_nr < contact_points.size(); layer_nr++)
{
for (Point point : contact_points[layer_nr])
{
PolygonsPart outline;
Polygon diamond;
diamond.add(point + Point(0, 1000));
diamond.add(point + Point(-1000, 0));
diamond.add(point + Point(0, -1000));
diamond.add(point + Point(1000, 0));
outline.add(diamond);
storage.support.supportLayers[layer_nr].support_infill_parts.emplace_back(outline, 350);
}
if (!contact_points[layer_nr].empty())
{
storage.support.layer_nr_max_filled_layer = layer_nr;
}
}
//TODO: Apply some diameter to the tree branches.
storage.support.generated = true;
}
void TreeSupport::generateContactPoints(const SliceMeshStorage& mesh, std::vector<std::unordered_set<Point>>& contact_points)
{
const coord_t layer_height = mesh.getSettingInMicrons("layer_height");
const coord_t z_distance_top = mesh.getSettingInMicrons("support_top_distance");
const size_t z_distance_top_layers = std::max(0U, round_up_divide(z_distance_top, layer_height)) + 1; //Support must always be 1 layer below overhang.
for (size_t layer_nr = 0; layer_nr < mesh.overhang_areas.size() - z_distance_top_layers; layer_nr++)
{
const Polygons& overhang = mesh.overhang_areas[layer_nr + z_distance_top_layers];
if (overhang.empty())
{
continue;
}
//First generate a lot of points in a grid pattern.
Polygons outside_polygons = overhang.getOutsidePolygons();
AABB bounding_box(outside_polygons); //To know how far we should generate points.
coord_t point_spread = mesh.getSettingInMicrons("support_tree_branch_distance");
point_spread *= SQRT_2; //We'll rotate these points 45 degrees, so this is the point distance when axis-aligned.
bounding_box.round(point_spread);
for (PolygonRef overhang_part : outside_polygons)
{
AABB bounding_box(outside_polygons);
bounding_box.round(point_spread);
bool added = false; //Did we add a point this way?
for (coord_t x = bounding_box.min.X; x <= bounding_box.max.X; x += point_spread << 1)
{
for (coord_t y = bounding_box.min.Y + (point_spread << 1) * (x % 2); y <= bounding_box.max.Y; y += point_spread) //This produces points in a 45-degree rotated grid.
{
Point candidate(x, y);
constexpr bool border_is_inside = true;
if (overhang_part.inside(candidate, border_is_inside))
{
contact_points[layer_nr].insert(candidate);
added = true;
}
}
}
if (!added) //If we didn't add any points due to bad luck, we want to add one anyway such that loose parts are also supported.
{
Point candidate = bounding_box.getMiddle();
PolygonUtils::moveInside(overhang_part, candidate);
contact_points[layer_nr].insert(candidate);
}
}
}
}
}<commit_msg>Avoid objects with proper support XY distance<commit_after>//Copyright (c) 2017 Ultimaker B.V.
//CuraEngine is released under the terms of the AGPLv3 or higher.
#include "utils/intpoint.h" //To normalize vectors.
#include "utils/math.h" //For round_up_divide.
#include "utils/MinimumSpanningTree.h" //For the
#include "utils/polygonUtils.h" //For moveInside.
#include "TreeSupport.h"
#define SQRT_2 1.4142135623730950488 //Square root of 2.
namespace cura
{
TreeSupport::TreeSupport()
{
}
void TreeSupport::generateSupportAreas(SliceDataStorage& storage)
{
std::vector<std::unordered_set<Point>> contact_points;
contact_points.reserve(storage.support.supportLayers.size());
for (size_t layer_nr = 0; layer_nr < storage.support.supportLayers.size(); layer_nr++) //Generate empty layers to store the points in.
{
contact_points.emplace_back();
}
for (SliceMeshStorage& mesh : storage.meshes)
{
if (!mesh.getSettingBoolean("support_tree_enable"))
{
return;
}
generateContactPoints(mesh, contact_points);
}
//Generate areas that have to be avoided.
const coord_t layer_height = storage.getSettingInMicrons("layer_height");
const double angle = storage.getSettingInAngleRadians("support_tree_angle");
const coord_t maximum_move_distance = tan(angle) * layer_height;
std::vector<Polygons> model_collision;
constexpr bool include_helper_parts = false;
model_collision.push_back(storage.getLayerOutlines(0, include_helper_parts));
//TODO: If allowing support to rest on model, these need to be just the model outlines.
for (size_t layer_nr = 1; layer_nr < storage.print_layer_count; layer_nr ++)
{
//Generate an area above the current layer where you'd still collide with the current layer if you were to move with at most maximum_move_distance.
model_collision.push_back(model_collision[layer_nr - 1].offset(-maximum_move_distance)); //Inset previous layer with maximum_move_distance to allow some movement.
model_collision[layer_nr] = model_collision[layer_nr].unionPolygons(storage.getLayerOutlines(layer_nr, include_helper_parts)); //Add current layer's collision to that.
}
//Use Minimum Spanning Tree to connect the points on each layer and move them while dropping them down.
const coord_t xy_distance = storage.getSettingInMicrons("support_xy_distance"); //TODO: Add branch thickness.
for (size_t layer_nr = contact_points.size() - 1; layer_nr > 0; layer_nr--) //Skip layer 0, since we can't drop down the vertices there.
{
MinimumSpanningTree mst(contact_points[layer_nr]);
for (Point vertex : contact_points[layer_nr])
{
std::vector<Point> neighbours = mst.adjacentNodes(vertex);
if (neighbours.size() == 1) //This is a leaf.
{
Point direction = neighbours[0] - vertex;
if (vSize2(direction) < maximum_move_distance * maximum_move_distance) //Smaller than one step. Leave this one out.
{
continue;
}
Point motion = normal(direction, maximum_move_distance);
Point next_layer_vertex = vertex + motion;
PolygonUtils::moveOutside(model_collision[layer_nr], next_layer_vertex, xy_distance, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(next_layer_vertex);
}
else //Not a leaf or just a single vertex.
{
PolygonUtils::moveOutside(model_collision[layer_nr], vertex, xy_distance, maximum_move_distance); //Avoid collision.
contact_points[layer_nr - 1].insert(vertex); //Just drop the leaves directly down.
//TODO: Avoid collisions.
}
}
}
//TODO: When reaching the bottom, cut away all edges of the MST that are still not contracted.
//TODO: Do a second pass of dropping down but with leftover edges removed.
//Placeholder to test with that generates a simple diamond at each contact point (without generating any trees yet).
for (size_t layer_nr = 0; layer_nr < contact_points.size(); layer_nr++)
{
for (Point point : contact_points[layer_nr])
{
PolygonsPart outline;
Polygon diamond;
diamond.add(point + Point(0, 1000));
diamond.add(point + Point(-1000, 0));
diamond.add(point + Point(0, -1000));
diamond.add(point + Point(1000, 0));
outline.add(diamond);
storage.support.supportLayers[layer_nr].support_infill_parts.emplace_back(outline, 350);
}
if (!contact_points[layer_nr].empty())
{
storage.support.layer_nr_max_filled_layer = layer_nr;
}
}
//TODO: Apply some diameter to the tree branches.
storage.support.generated = true;
}
void TreeSupport::generateContactPoints(const SliceMeshStorage& mesh, std::vector<std::unordered_set<Point>>& contact_points)
{
const coord_t layer_height = mesh.getSettingInMicrons("layer_height");
const coord_t z_distance_top = mesh.getSettingInMicrons("support_top_distance");
const size_t z_distance_top_layers = std::max(0U, round_up_divide(z_distance_top, layer_height)) + 1; //Support must always be 1 layer below overhang.
for (size_t layer_nr = 0; layer_nr < mesh.overhang_areas.size() - z_distance_top_layers; layer_nr++)
{
const Polygons& overhang = mesh.overhang_areas[layer_nr + z_distance_top_layers];
if (overhang.empty())
{
continue;
}
//First generate a lot of points in a grid pattern.
Polygons outside_polygons = overhang.getOutsidePolygons();
AABB bounding_box(outside_polygons); //To know how far we should generate points.
coord_t point_spread = mesh.getSettingInMicrons("support_tree_branch_distance");
point_spread *= SQRT_2; //We'll rotate these points 45 degrees, so this is the point distance when axis-aligned.
bounding_box.round(point_spread);
for (PolygonRef overhang_part : outside_polygons)
{
AABB bounding_box(outside_polygons);
bounding_box.round(point_spread);
bool added = false; //Did we add a point this way?
for (coord_t x = bounding_box.min.X; x <= bounding_box.max.X; x += point_spread << 1)
{
for (coord_t y = bounding_box.min.Y + (point_spread << 1) * (x % 2); y <= bounding_box.max.Y; y += point_spread) //This produces points in a 45-degree rotated grid.
{
Point candidate(x, y);
constexpr bool border_is_inside = true;
if (overhang_part.inside(candidate, border_is_inside))
{
contact_points[layer_nr].insert(candidate);
added = true;
}
}
}
if (!added) //If we didn't add any points due to bad luck, we want to add one anyway such that loose parts are also supported.
{
Point candidate = bounding_box.getMiddle();
PolygonUtils::moveInside(overhang_part, candidate);
contact_points[layer_nr].insert(candidate);
}
}
}
}
}<|endoftext|>
|
<commit_before>#include "TriacDimmer.h"
#include <Arduino.h>
#include <assert.h>
volatile uint16_t TriacDimmer::detail::pulse_length;
volatile uint16_t TriacDimmer::detail::period = 16667;
volatile uint16_t TriacDimmer::detail::ch_A_up;
volatile uint16_t TriacDimmer::detail::ch_A_dn;
volatile uint16_t TriacDimmer::detail::ch_B_up;
volatile uint16_t TriacDimmer::detail::ch_B_dn;
void TriacDimmer::begin(uint16_t pulse_length){
TriacDimmer::detail::pulse_length = pulse_length;
TCCR1A = 0;
TCCR1B = _BV(ICNC1) //input capture noise cancel
| _BV(ICES1) //positive edge
| _BV(CS11); // /8 prescaler
pinMode(8, INPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
TIFR1 = _BV(ICF1); //clear IC interrupt flag
TIMSK1 = _BV(ICIE1); //enable input capture interrupt
}
void TriacDimmer::end(){
TIMSK1 = 0; //disable the interrupts first!
TIFR1 = 0xFF; //clear all flags
TCCR1A = 0; //clear to reset state
TCCR1B = 0;
}
void TriacDimmer::setBrightness(uint8_t pin, float value){
assert(pin == 9 || pin == 10);
if ((pin & 0x01) == 0x01){ // if (pin == 9){
TriacDimmer::detail::setChannelA(1 - value);
} else { // if (pin == 10){
TriacDimmer::detail::setChannelB(1 - value);
}
}
float TriacDimmer::getCurrentBrightness(uint8_t pin){
assert(pin == 9 || pin == 10);
if ((pin & 0x01) == 0x01){ // if (pin == 9){
1 - TriacDimmer::detail::getChannelA();
} else { // if (pin == 10){
1 - TriacDimmer::detail::getChannelB();
}
}
void TriacDimmer::detail::setChannelA(float value){
TriacDimmer::detail::ch_A_up = TriacDimmer::detail::period * value;
TriacDimmer::detail::ch_A_dn = TriacDimmer::detail::ch_A_up + TriacDimmer::detail::pulse_length;
}
void TriacDimmer::detail::setChannelB(float value){
TriacDimmer::detail::ch_B_up = TriacDimmer::detail::period * value;
TriacDimmer::detail::ch_B_dn = TriacDimmer::detail::ch_B_up + TriacDimmer::detail::pulse_length;
}
float TriacDimmer::detail::getChannelA(){
return (float)TriacDimmer::detail::ch_A_up / TriacDimmer::detail::period;
}
float TriacDimmer::detail::getChannelB(){
return (float)TriacDimmer::detail::ch_B_up / TriacDimmer::detail::period;
}
ISR(TIMER1_CAPT_vect){
TIMSK1 &=~ (_BV(OCIE1A) | _BV(OCIE1B)); //clear interrupts, in case they haven't run yet
TCCR1A &=~ (_BV(COM1A1) | _BV(COM1B1));
TCCR1C = _BV(FOC1A) | _BV(FOC1B); //ensure outputs are properly cleared
OCR1A = ICR1 + TriacDimmer::detail::ch_A_up;
OCR1B = ICR1 + TriacDimmer::detail::ch_B_up;
TCCR1A |= _BV(COM1A0) | _BV(COM1A1) | _BV(COM1B0) | _BV(COM1B1); //set OC1x on compare match
TIFR1 = _BV(OCF1A) | _BV(OCF1B); //clear compare match flags
TIMSK1 |= _BV(OCIE1A) | _BV(OCIE1B); //enable input capture and compare match interrupts
static uint16_t last_icr = 0;
TriacDimmer::detail::period = ICR1 - last_icr;
last_icr = ICR1;
}
ISR(TIMER1_COMPA_vect){
TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
TCCR1A |= _BV(COM1A1); //clear OC1x on compare match
OCR1A = ICR1 + TriacDimmer::detail::ch_A_dn;
if((signed)(TCNT1 - OCR1A) >= 0){
TCCR1C = _BV(FOC1A); //interrupt ran late, trigger match manually
}
}
ISR(TIMER1_COMPB_vect){
TIMSK1 &=~ _BV(OCIE1B); //disable match interrupt
TCCR1A |= _BV(COM1B1); //clear OC1x on compare match
OCR1B = ICR1 + TriacDimmer::detail::ch_B_dn;
if((signed)(TCNT1 - OCR1B) >= 0){
TCCR1C = _BV(FOC1B); //interrupt ran late, trigger match manually
}
}
<commit_msg>added late guard to ISR<commit_after>#include "TriacDimmer.h"
#include <Arduino.h>
#include <assert.h>
volatile uint16_t TriacDimmer::detail::pulse_length;
volatile uint16_t TriacDimmer::detail::period = 16667;
volatile uint16_t TriacDimmer::detail::ch_A_up;
volatile uint16_t TriacDimmer::detail::ch_A_dn;
volatile uint16_t TriacDimmer::detail::ch_B_up;
volatile uint16_t TriacDimmer::detail::ch_B_dn;
void TriacDimmer::begin(uint16_t pulse_length){
TriacDimmer::detail::pulse_length = pulse_length;
TCCR1A = 0;
TCCR1B = _BV(ICNC1) //input capture noise cancel
| _BV(ICES1) //positive edge
| _BV(CS11); // /8 prescaler
pinMode(8, INPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
TIFR1 = _BV(ICF1); //clear IC interrupt flag
TIMSK1 = _BV(ICIE1); //enable input capture interrupt
}
void TriacDimmer::end(){
TIMSK1 = 0; //disable the interrupts first!
TIFR1 = 0xFF; //clear all flags
TCCR1A = 0; //clear to reset state
TCCR1B = 0;
}
void TriacDimmer::setBrightness(uint8_t pin, float value){
assert(pin == 9 || pin == 10);
if ((pin & 0x01) == 0x01){ // if (pin == 9){
TriacDimmer::detail::setChannelA(1 - value);
} else { // if (pin == 10){
TriacDimmer::detail::setChannelB(1 - value);
}
}
float TriacDimmer::getCurrentBrightness(uint8_t pin){
assert(pin == 9 || pin == 10);
if ((pin & 0x01) == 0x01){ // if (pin == 9){
1 - TriacDimmer::detail::getChannelA();
} else { // if (pin == 10){
1 - TriacDimmer::detail::getChannelB();
}
}
void TriacDimmer::detail::setChannelA(float value){
TriacDimmer::detail::ch_A_up = TriacDimmer::detail::period * value;
TriacDimmer::detail::ch_A_dn = TriacDimmer::detail::ch_A_up + TriacDimmer::detail::pulse_length;
}
void TriacDimmer::detail::setChannelB(float value){
TriacDimmer::detail::ch_B_up = TriacDimmer::detail::period * value;
TriacDimmer::detail::ch_B_dn = TriacDimmer::detail::ch_B_up + TriacDimmer::detail::pulse_length;
}
float TriacDimmer::detail::getChannelA(){
return (float)TriacDimmer::detail::ch_A_up / TriacDimmer::detail::period;
}
float TriacDimmer::detail::getChannelB(){
return (float)TriacDimmer::detail::ch_B_up / TriacDimmer::detail::period;
}
ISR(TIMER1_CAPT_vect){
TIMSK1 &=~ (_BV(OCIE1A) | _BV(OCIE1B)); //clear interrupts, in case they haven't run yet
TCCR1A &=~ (_BV(COM1A1) | _BV(COM1B1));
TCCR1C = _BV(FOC1A) | _BV(FOC1B); //ensure outputs are properly cleared
OCR1A = ICR1 + TriacDimmer::detail::ch_A_up;
OCR1B = ICR1 + TriacDimmer::detail::ch_B_up;
TCCR1A |= _BV(COM1A0) | _BV(COM1A1) | _BV(COM1B0) | _BV(COM1B1); //set OC1x on compare match
TIFR1 = _BV(OCF1A) | _BV(OCF1B); //clear compare match flags
TIMSK1 |= _BV(OCIE1A) | _BV(OCIE1B); //enable input capture and compare match interrupts
static uint16_t last_icr = 0;
TriacDimmer::detail::period = ICR1 - last_icr;
last_icr = ICR1;
if((signed)(TCNT1 - OCR1A) >= 0){
TCCR1C = _BV(FOC1A); //interrupt ran late, trigger match manually
}
if((signed)(TCNT1 - OCR1B) >= 0){
TCCR1C = _BV(FOC1B); //interrupt ran late, trigger match manually
}
}
ISR(TIMER1_COMPA_vect){
TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt
TCCR1A |= _BV(COM1A1); //clear OC1x on compare match
OCR1A = ICR1 + TriacDimmer::detail::ch_A_dn;
if((signed)(TCNT1 - OCR1A) >= 0){
TCCR1C = _BV(FOC1A); //interrupt ran late, trigger match manually
}
}
ISR(TIMER1_COMPB_vect){
TIMSK1 &=~ _BV(OCIE1B); //disable match interrupt
TCCR1A |= _BV(COM1B1); //clear OC1x on compare match
OCR1B = ICR1 + TriacDimmer::detail::ch_B_dn;
if((signed)(TCNT1 - OCR1B) >= 0){
TCCR1C = _BV(FOC1B); //interrupt ran late, trigger match manually
}
}
<|endoftext|>
|
<commit_before>#ifndef __UTIL_RANDOM_HPP__
#define __UTIL_RANDOM_HPP__
#include <cstdlib>
namespace Util
{
struct Random
{
uint64_t nextInt ()
{
return std::rand();
}
/*
** Generate a number in [0, max]
*/
uint64_t nextInt (uint64_t max)
{
uint64_t num_bins = max + 1;
uint64_t num_rand = (uint64_t)RAND_MAX + 1;
uint64_t bin_size = num_rand / num_bins;
uint64_t defect = num_rand % num_bins;
int64_t x;
do
{
x = nextInt();
}
while (num_rand - defect <= (unsigned long)x);
return x / bin_size;
}
/*
** Generate a number in [1, max]
*/
int64_t nextInt (int64_t min, int64_t max)
{
return nextInt((uint64_t)(max - min)) + min;
}
double nextDouble ()
{
return (double)nextInt() / RAND_MAX;
}
double nextDouble (double min, double max)
{
return (nextDouble() * (max - min)) + min;
}
};
class GaussianRandom
{
};
}
#endif /* end of include guard: __UTIL_RANDOM_HPP__ */
<commit_msg>separate files<commit_after>#ifndef __UTIL_RANDOM_HPP__
#define __UTIL_RANDOM_HPP__
#include <cinttypes>
namespace Util
{
struct Random
{
uint64_t nextInt () const;
/*
** Generate a number in [0, max]
*/
uint64_t nextInt (uint64_t max) const;
/*
** Generate a number in [1, max]
*/
int64_t nextInt (int64_t min, int64_t max) const;
double nextDouble () const;
double nextDouble (double min, double max) const;
};
class GaussianRandom
{
};
}
#endif /* end of include guard: __UTIL_RANDOM_HPP__ */
<|endoftext|>
|
<commit_before>#ifndef VIDEO_DEVICE_H
#define VIDEO_DEVICE_H
#include <opencv2/opencv.hpp>
using namespace cv;
class VideoDevice
{
public:
VideoDevice();
void startCapture(int id);
Mat getImage();
private:
void takeImage();
//data
VideoCapture camera;
Mat image;
int isFinished;
int isReady;
bool isInitialized;
};
#endif
<commit_msg>Deleting old files<commit_after><|endoftext|>
|
<commit_before>/*
dbWatson
Database Structur Exporter
https://github.com/Zer0Knowledge/dbWatson
BSD 2-Clause License
Copyright (c) 2016 | Kevin Klein, Tobias Donix, Leonard Franke
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <stdio.h>
#include <string>
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
#include <vector>
#include "XMLExporter.h"
#include "common.h"
#include "DbConnector.h"
void
XMLExporter::exportToFS()
{
int rc;
xmlTextWriterPtr writer;
std::vector<xmlChar> encBuffer;
for ( DbTableDesc tbl : this->m_tbls )
{
std::string uri = wstring_tostring( tbl.tblName );
uri.append( ".xml" );
writer = xmlNewTextWriterFilename( uri.c_str(), 0 );
if ( writer == NULL ) {
std::cerr << "testXmlwriterFilename: Error creating the xml writer\n";
return;
}
rc = xmlTextWriterStartDocument( writer, NULL, "UTF-8", NULL );
if ( rc < 0 ) {
std::cerr << "testXmlwriterFilename: Error at xmlTextWriterStartDocument\n";
return;
}
rc = xmlTextWriterStartElement( writer, BAD_CAST "table" );
if ( rc < 0 ) {
std::cerr << "testXmlwriterFilename: Error at xmlTextWriterStartElement\n";
return;
}
wstring_toxmlChar( tbl.tblName, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "tablename", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "testXmlwriterFilename: Error at xmlTextWriterWriteElement\n";
return;
}
wstring_toxmlChar( tbl.tblType, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "tabletyp", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "testXmlwriterFilename: Error at xmlTextWriterWriteElement\n";
return;
}
rc = xmlTextWriterEndDocument( writer );
if ( rc < 0 ) {
std::cerr << "testXmlwriterFilename: Error at xmlTextWriterEndDocument\n";
return;
}
xmlFreeTextWriter(writer);
for ( DbColDesc cl : tbl.tblCols )
{
std::wcout << cl.colName
<< L" - " << cl.colType
<< L'(' << cl.colLength << L')'
<< L" Default: " << cl.colDefaultVal
<< L" Nullable: " << cl.colNullable
<< std::endl;
}
}
}
<commit_msg>Schreiben der Spalten<commit_after>/*
dbWatson
Database Structur Exporter
https://github.com/Zer0Knowledge/dbWatson
BSD 2-Clause License
Copyright (c) 2016 | Kevin Klein, Tobias Donix, Leonard Franke
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
#include <stdio.h>
#include <string>
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
#include <vector>
#include "XMLExporter.h"
#include "common.h"
#include "DbConnector.h"
void
XMLExporter::exportToFS()
{
int rc;
xmlTextWriterPtr writer;
std::vector<xmlChar> encBuffer;
for ( DbTableDesc tbl : this->m_tbls )
{
std::string uri = wstring_tostring( tbl.tblName );
uri.append( ".xml" );
writer = xmlNewTextWriterFilename( uri.c_str(), 0 );
if ( writer == NULL ) {
std::cerr << "xmlWriter: Error creating the xml writer\n";
return;
}
rc = xmlTextWriterStartDocument( writer, NULL, "UTF-8", NULL );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterStartDocument\n";
return;
}
rc = xmlTextWriterStartElement( writer, BAD_CAST "table" );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterStartElement\n";
return;
}
wstring_toxmlChar( tbl.tblName, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "tablename", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
wstring_toxmlChar( tbl.tblType, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "tabletype", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
rc = xmlTextWriterEndDocument( writer );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterEndDocument\n";
return;
}
rc = xmlTextWriterStartElement( writer, BAD_CAST "columns" );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterStartElement\n";
return;
}
for ( DbColDesc cl : tbl.tblCols )
{
rc = xmlTextWriterStartElement( writer, BAD_CAST "column" );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterStartElement\n";
return;
}
wstring_toxmlChar( cl.colName, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "columnname", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
wstring_toxmlChar( cl.colType, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "columntype", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
wstring_toxmlChar( cl.colLength, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "columnlength", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
wstring_toxmlChar( cl.colDefaultVal, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "columndefaultval", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
wstring_toxmlChar( cl.colNullable, encBuffer );
rc = xmlTextWriterWriteElement( writer, BAD_CAST "columnnullable", &encBuffer[0] );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterWriteElement\n";
return;
}
/* Close Column */
rc = xmlTextWriterEndElement( writer );
if ( rc < 0 ) {
std::cerr << "xmlWriter: Error at xmlTextWriterEndElement\n";
return;
}
}
//**Zer0Knowledge
//closes all tags
xmlFreeTextWriter(writer);
}
}
<|endoftext|>
|
<commit_before>#include <sqlite3.h>
#include <glib.h>
#include <errno.h>
#include <stdio.h>
#include <algorithm>
#include <QDateTime>
#include "account-mgr.h"
#include "configurator.h"
#include "seafile-applet.h"
#include "utils/utils.h"
#include "api/api-error.h"
#include "api/requests.h"
#include "rpc/rpc-client.h"
namespace {
const char *kRepoRelayAddrProperty = "relay-address";
bool compareAccount(const Account& a, const Account& b)
{
if (!a.isValid()) {
return false;
} else if (!b.isValid()) {
return true;
} else if (a.lastVisited < b.lastVisited) {
return false;
} else if (a.lastVisited > b.lastVisited) {
return true;
}
return true;
}
struct UserData {
std::vector<Account> *accounts;
struct sqlite3 *db;
};
inline void setServerInfoKeyValue(struct sqlite3 *db, const Account &account, const QString& key, const QString &value)
{
char *zql = sqlite3_mprintf(
"REPLACE INTO ServerInfo(url, username, key, value) VALUES (%Q, %Q, %Q, %Q)",
account.serverUrl.toEncoded().data(), account.username.toUtf8().data(),
key.toUtf8().data(), value.toUtf8().data());
sqlite_query_exec(db, zql);
sqlite3_free(zql);
}
}
AccountManager::AccountManager()
{
db = NULL;
}
AccountManager::~AccountManager()
{
if (db)
sqlite3_close(db);
}
int AccountManager::start()
{
const char *errmsg;
const char *sql;
QString db_path = QDir(seafApplet->configurator()->seafileDir()).filePath("accounts.db");
if (sqlite3_open (toCStr(db_path), &db)) {
errmsg = sqlite3_errmsg (db);
qCritical("failed to open account database %s: %s",
toCStr(db_path), errmsg ? errmsg : "no error given");
seafApplet->errorAndExit(tr("failed to open account database"));
return -1;
}
// enabling foreign keys, it must be done manually from each connection
// and this feature is only supported from sqlite 3.6.19
sql = "PRAGMA foreign_keys=ON;";
if (sqlite_query_exec (db, sql) < 0) {
qCritical("sqlite version is too low to support foreign key feature\n");
sqlite3_close(db);
db = NULL;
return -1;
}
sql = "CREATE TABLE IF NOT EXISTS Accounts (url VARCHAR(24), "
"username VARCHAR(15), token VARCHAR(40), lastVisited INTEGER, "
"PRIMARY KEY(url, username))";
if (sqlite_query_exec (db, sql) < 0) {
qCritical("failed to create accounts table\n");
sqlite3_close(db);
db = NULL;
return -1;
}
// create ServerInfo table
sql = "CREATE TABLE IF NOT EXISTS ServerInfo ("
"key TEXT NOT NULL, value TEXT, "
"url VARCHAR(24), username VARCHAR(15), "
"PRIMARY KEY(url, username, key), "
"FOREIGN KEY(url, username) REFERENCES Accounts(url, username) "
"ON DELETE CASCADE ON UPDATE CASCADE )";
if (sqlite_query_exec (db, sql) < 0) {
qCritical("failed to create server_info table\n");
sqlite3_close(db);
db = NULL;
return -1;
}
loadAccounts();
connect(this, SIGNAL(accountsChanged()), this, SLOT(onAccountsChanged()));
return 0;
}
bool AccountManager::loadAccountsCB(sqlite3_stmt *stmt, void *data)
{
UserData *userdata = static_cast<UserData*>(data);
const char *url = (const char *)sqlite3_column_text (stmt, 0);
const char *username = (const char *)sqlite3_column_text (stmt, 1);
const char *token = (const char *)sqlite3_column_text (stmt, 2);
qint64 atime = (qint64)sqlite3_column_int64 (stmt, 3);
if (!token) {
token = "";
}
Account account = Account(QUrl(QString(url)), QString(username), QString(token), atime);
char* zql = sqlite3_mprintf("SELECT key, value FROM ServerInfo WHERE url = %Q AND username = %Q", url, username);
sqlite_foreach_selected_row (userdata->db, zql, loadServerInfoCB, &account.serverInfo);
sqlite3_free(zql);
userdata->accounts->push_back(account);
return true;
}
bool AccountManager::loadServerInfoCB(sqlite3_stmt *stmt, void *data)
{
ServerInfo *info = static_cast<ServerInfo*>(data);
const char *key = (const char *)sqlite3_column_text (stmt, 0);
const char *value = (const char *)sqlite3_column_text (stmt, 1);
QString key_string = key;
QString value_string = value;
if (key_string == "version") {
info->parseVersionFromString(value_string);
} else {
info->parseFeatureFromString(key_string, value_string.toLower() == "true");
}
return true;
}
const std::vector<Account>& AccountManager::loadAccounts()
{
const char *sql = "SELECT url, username, token, lastVisited FROM Accounts ";
accounts_.clear();
UserData userdata = { .accounts = &accounts_, .db = db };
sqlite_foreach_selected_row (db, sql, loadAccountsCB, &userdata);
std::stable_sort(accounts_.begin(), accounts_.end(), compareAccount);
return accounts_;
}
int AccountManager::saveAccount(const Account& account)
{
Account new_account = account;
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i] == account) {
accounts_.erase(accounts_.begin() + i);
break;
}
}
accounts_.insert(accounts_.begin(), new_account);
updateServerInfo(0);
QString url = new_account.serverUrl.toEncoded().data();
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
QString sql = "REPLACE INTO Accounts VALUES ('%1', '%2', '%3', %4) ";
sql = sql.arg(url).arg(new_account.username).arg(new_account.token).arg(QString::number(timestamp));
sqlite_query_exec (db, toCStr(sql));
emit accountsChanged();
return 0;
}
int AccountManager::removeAccount(const Account& account)
{
QString url = account.serverUrl.toEncoded().data();
QString sql = "DELETE FROM Accounts WHERE url = '%1' AND username = '%2'";
sql = sql.arg(url).arg(account.username);
sqlite_query_exec (db, toCStr(sql));
accounts_.erase(std::remove(accounts_.begin(), accounts_.end(), account),
accounts_.end());
emit accountsChanged();
return 0;
}
void AccountManager::updateAccountLastVisited(const Account& account)
{
const char *url = account.serverUrl.toEncoded().data();
QString sql = "UPDATE Accounts SET lastVisited = %1 "
"WHERE username = '%2' AND url = '%3'";
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
sql = sql.arg(QString::number(timestamp)).arg(account.username).arg(url);
sqlite_query_exec (db, toCStr(sql));
}
bool AccountManager::accountExists(const QUrl& url, const QString& username)
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].serverUrl == url && accounts_[i].username == username) {
return true;
}
}
return false;
}
bool AccountManager::setCurrentAccount(const Account& account)
{
if (account == currentAccount()) {
return false;
}
emit beforeAccountChanged();
// Would emit "accountsChanged" signal
saveAccount(account);
return true;
}
int AccountManager::replaceAccount(const Account& old_account, const Account& new_account)
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i] == old_account) {
accounts_[i] = new_account;
updateServerInfo(i);
break;
}
}
QString old_url = old_account.serverUrl.toEncoded().data();
QString new_url = new_account.serverUrl.toEncoded().data();
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
QString sql =
"UPDATE Accounts "
"SET url = '%1', "
" username = '%2', "
" token = '%3', "
" lastVisited = '%4' "
"WHERE url = '%5' "
" AND username = '%2'";
sql = sql.arg(new_url).arg(new_account.username). \
arg(new_account.token).arg(QString::number(timestamp)) \
.arg(old_url);
sqlite_query_exec (db, toCStr(sql));
emit accountsChanged();
return 0;
}
Account AccountManager::getAccountByHostAndUsername(const QString& host,
const QString& username) const
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].serverUrl.host() == host
&& accounts_[i].username == username) {
return accounts_[i];
}
}
return Account();
}
Account AccountManager::getAccountBySignature(const QString& account_sig) const
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].getSignature() == account_sig) {
return accounts_[i];
}
}
return Account();
}
void AccountManager::updateServerInfo()
{
for (size_t i = 0; i < accounts_.size(); i++)
updateServerInfo(i);
}
void AccountManager::updateServerInfo(unsigned index)
{
ServerInfoRequest *request;
// request is taken owner by Account object
request = accounts_[index].createServerInfoRequest();
connect(request, SIGNAL(success(const Account&, const ServerInfo &)),
this, SLOT(serverInfoSuccess(const Account&, const ServerInfo &)));
connect(request, SIGNAL(failed(const ApiError&)),
this, SLOT(serverInfoFailed(const ApiError&)));
request->send();
}
void AccountManager::serverInfoSuccess(const Account &account, const ServerInfo &info)
{
const QStringList features = info.getFeatureStrings();
setServerInfoKeyValue(db, account, "version", info.getVersionString());
Q_FOREACH(const QString& feature, features)
{
setServerInfoKeyValue(db, account, feature, "true");
}
bool changed = account.serverInfo != info;
if (!changed)
return;
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i] == account) {
if (i == 0)
emit beforeAccountChanged();
accounts_[i].serverInfo = info;
if (i == 0)
emit accountsChanged();
break;
}
}
}
void AccountManager::serverInfoFailed(const ApiError &error)
{
qWarning("update server info failed %s\n", error.toString().toUtf8().data());
}
bool AccountManager::clearAccountToken(const Account& account)
{
Account new_account = account;
new_account.token = "";
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].serverUrl.toString() == account.serverUrl.toString()
&& accounts_[i].username == account.username) {
accounts_.erase(accounts_.begin() + i);
break;
}
}
accounts_.push_back(new_account);
QString url = new_account.serverUrl.toEncoded().data();
QString sql =
"UPDATE Accounts "
"SET token = NULL "
"WHERE url = '%1' "
" AND username = '%2'";
sql = sql.arg(url).arg(new_account.username);
sqlite_query_exec (db, toCStr(sql));
emit accountsChanged();
return true;
}
Account AccountManager::getAccountByRepo(const QString& repo_id)
{
SeafileRpcClient *rpc = seafApplet->rpcClient();
if (!accounts_cache_.contains(repo_id)) {
QString relay_addr;
if (rpc->getRepoProperty(repo_id, kRepoRelayAddrProperty, &relay_addr) < 0) {
return Account();
}
const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
for (unsigned i = 0; i < accounts.size(); i++) {
const Account& account = accounts[i];
if (account.serverUrl.host() == relay_addr) {
accounts_cache_[repo_id] = account;
break;
}
}
}
return accounts_cache_.value(repo_id, Account());
}
void AccountManager::onAccountsChanged()
{
accounts_cache_.clear();
}
void AccountManager::invalidateCurrentLogin()
{
// make sure we have accounts there
if (!hasAccount())
return;
const Account &account = accounts().front();
// if the token is already invalidated, ignore
if (account.token.isEmpty())
return;
clearAccountToken(account);
seafApplet->warningBox(tr("Authorization expired, please re-login"));
// we have the expire account at the last position
emit accountRequireRelogin(accounts().back());
}
<commit_msg>account-mgr: use sqlite3_mprintf<commit_after>#include <sqlite3.h>
#include <glib.h>
#include <errno.h>
#include <stdio.h>
#include <algorithm>
#include <QDateTime>
#include "account-mgr.h"
#include "configurator.h"
#include "seafile-applet.h"
#include "utils/utils.h"
#include "api/api-error.h"
#include "api/requests.h"
#include "rpc/rpc-client.h"
namespace {
const char *kRepoRelayAddrProperty = "relay-address";
bool compareAccount(const Account& a, const Account& b)
{
if (!a.isValid()) {
return false;
} else if (!b.isValid()) {
return true;
} else if (a.lastVisited < b.lastVisited) {
return false;
} else if (a.lastVisited > b.lastVisited) {
return true;
}
return true;
}
struct UserData {
std::vector<Account> *accounts;
struct sqlite3 *db;
};
inline void setServerInfoKeyValue(struct sqlite3 *db, const Account &account, const QString& key, const QString &value)
{
char *zql = sqlite3_mprintf(
"REPLACE INTO ServerInfo(url, username, key, value) VALUES (%Q, %Q, %Q, %Q)",
account.serverUrl.toEncoded().data(), account.username.toUtf8().data(),
key.toUtf8().data(), value.toUtf8().data());
sqlite_query_exec(db, zql);
sqlite3_free(zql);
}
}
AccountManager::AccountManager()
{
db = NULL;
}
AccountManager::~AccountManager()
{
if (db)
sqlite3_close(db);
}
int AccountManager::start()
{
const char *errmsg;
const char *sql;
QString db_path = QDir(seafApplet->configurator()->seafileDir()).filePath("accounts.db");
if (sqlite3_open (toCStr(db_path), &db)) {
errmsg = sqlite3_errmsg (db);
qCritical("failed to open account database %s: %s",
toCStr(db_path), errmsg ? errmsg : "no error given");
seafApplet->errorAndExit(tr("failed to open account database"));
return -1;
}
// enabling foreign keys, it must be done manually from each connection
// and this feature is only supported from sqlite 3.6.19
sql = "PRAGMA foreign_keys=ON;";
if (sqlite_query_exec (db, sql) < 0) {
qCritical("sqlite version is too low to support foreign key feature\n");
sqlite3_close(db);
db = NULL;
return -1;
}
sql = "CREATE TABLE IF NOT EXISTS Accounts (url VARCHAR(24), "
"username VARCHAR(15), token VARCHAR(40), lastVisited INTEGER, "
"PRIMARY KEY(url, username))";
if (sqlite_query_exec (db, sql) < 0) {
qCritical("failed to create accounts table\n");
sqlite3_close(db);
db = NULL;
return -1;
}
// create ServerInfo table
sql = "CREATE TABLE IF NOT EXISTS ServerInfo ("
"key TEXT NOT NULL, value TEXT, "
"url VARCHAR(24), username VARCHAR(15), "
"PRIMARY KEY(url, username, key), "
"FOREIGN KEY(url, username) REFERENCES Accounts(url, username) "
"ON DELETE CASCADE ON UPDATE CASCADE )";
if (sqlite_query_exec (db, sql) < 0) {
qCritical("failed to create server_info table\n");
sqlite3_close(db);
db = NULL;
return -1;
}
loadAccounts();
connect(this, SIGNAL(accountsChanged()), this, SLOT(onAccountsChanged()));
return 0;
}
bool AccountManager::loadAccountsCB(sqlite3_stmt *stmt, void *data)
{
UserData *userdata = static_cast<UserData*>(data);
const char *url = (const char *)sqlite3_column_text (stmt, 0);
const char *username = (const char *)sqlite3_column_text (stmt, 1);
const char *token = (const char *)sqlite3_column_text (stmt, 2);
qint64 atime = (qint64)sqlite3_column_int64 (stmt, 3);
if (!token) {
token = "";
}
Account account = Account(QUrl(QString(url)), QString(username), QString(token), atime);
char* zql = sqlite3_mprintf("SELECT key, value FROM ServerInfo WHERE url = %Q AND username = %Q", url, username);
sqlite_foreach_selected_row (userdata->db, zql, loadServerInfoCB, &account.serverInfo);
sqlite3_free(zql);
userdata->accounts->push_back(account);
return true;
}
bool AccountManager::loadServerInfoCB(sqlite3_stmt *stmt, void *data)
{
ServerInfo *info = static_cast<ServerInfo*>(data);
const char *key = (const char *)sqlite3_column_text (stmt, 0);
const char *value = (const char *)sqlite3_column_text (stmt, 1);
QString key_string = key;
QString value_string = value;
if (key_string == "version") {
info->parseVersionFromString(value_string);
} else {
info->parseFeatureFromString(key_string, value_string.toLower() == "true");
}
return true;
}
const std::vector<Account>& AccountManager::loadAccounts()
{
const char *sql = "SELECT url, username, token, lastVisited FROM Accounts ";
accounts_.clear();
UserData userdata = { .accounts = &accounts_, .db = db };
sqlite_foreach_selected_row (db, sql, loadAccountsCB, &userdata);
std::stable_sort(accounts_.begin(), accounts_.end(), compareAccount);
return accounts_;
}
int AccountManager::saveAccount(const Account& account)
{
Account new_account = account;
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i] == account) {
accounts_.erase(accounts_.begin() + i);
break;
}
}
accounts_.insert(accounts_.begin(), new_account);
updateServerInfo(0);
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
char *zql = sqlite3_mprintf(
"REPLACE INTO Accounts(url, username, token, lastVisited) VALUES (%Q, %Q, %Q, %Q) ",
// url
new_account.serverUrl.toEncoded().data(),
// username
new_account.username.toUtf8().data(),
// token
new_account.token.toUtf8().data(),
// lastVisited
QString::number(timestamp).toUtf8().data());
sqlite_query_exec(db, zql);
sqlite3_free(zql);
emit accountsChanged();
return 0;
}
int AccountManager::removeAccount(const Account& account)
{
char *zql = sqlite3_mprintf(
"DELETE FROM Accounts WHERE url = %Q AND username = %Q",
// url
account.serverUrl.toEncoded().data(),
// username
account.username.toUtf8().data());
sqlite_query_exec(db, zql);
sqlite3_free(zql);
accounts_.erase(std::remove(accounts_.begin(), accounts_.end(), account),
accounts_.end());
emit accountsChanged();
return 0;
}
void AccountManager::updateAccountLastVisited(const Account& account)
{
char *zql = sqlite3_mprintf(
"UPDATE Accounts SET lastVisited = %Q "
"WHERE url = %Q AND username = %Q",
// lastVisted
QString::number(QDateTime::currentMSecsSinceEpoch()).toUtf8().data(),
// url
account.serverUrl.toEncoded().data(),
// username
account.username.toUtf8().data());
sqlite_query_exec(db, zql);
sqlite3_free(zql);
}
bool AccountManager::accountExists(const QUrl& url, const QString& username)
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].serverUrl == url && accounts_[i].username == username) {
return true;
}
}
return false;
}
bool AccountManager::setCurrentAccount(const Account& account)
{
if (account == currentAccount()) {
return false;
}
emit beforeAccountChanged();
// Would emit "accountsChanged" signal
saveAccount(account);
return true;
}
int AccountManager::replaceAccount(const Account& old_account, const Account& new_account)
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i] == old_account) {
// TODO copy new_account and old_account before this operation
// we might have invalid old_account or new_account after it
accounts_[i] = new_account;
updateServerInfo(i);
break;
}
}
qint64 timestamp = QDateTime::currentMSecsSinceEpoch();
char *zql = sqlite3_mprintf(
"UPDATE Accounts "
"SET url = %Q, "
" username = %Q, "
" token = %Q, "
" lastVisited = %Q "
"WHERE url = %Q "
" AND username = %Q",
// new_url
new_account.serverUrl.toEncoded().data(),
// username
new_account.username.toUtf8().data(),
// token
new_account.token.toUtf8().data(),
// lastvisited
QString::number(timestamp).toUtf8().data(),
// old_url
old_account.serverUrl.toEncoded().data(),
// username
new_account.username.toUtf8().data()
);
sqlite_query_exec(db, zql);
sqlite3_free(zql);
emit accountsChanged();
return 0;
}
Account AccountManager::getAccountByHostAndUsername(const QString& host,
const QString& username) const
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].serverUrl.host() == host
&& accounts_[i].username == username) {
return accounts_[i];
}
}
return Account();
}
Account AccountManager::getAccountBySignature(const QString& account_sig) const
{
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].getSignature() == account_sig) {
return accounts_[i];
}
}
return Account();
}
void AccountManager::updateServerInfo()
{
for (size_t i = 0; i < accounts_.size(); i++)
updateServerInfo(i);
}
void AccountManager::updateServerInfo(unsigned index)
{
ServerInfoRequest *request;
// request is taken owner by Account object
request = accounts_[index].createServerInfoRequest();
connect(request, SIGNAL(success(const Account&, const ServerInfo &)),
this, SLOT(serverInfoSuccess(const Account&, const ServerInfo &)));
connect(request, SIGNAL(failed(const ApiError&)),
this, SLOT(serverInfoFailed(const ApiError&)));
request->send();
}
void AccountManager::serverInfoSuccess(const Account &account, const ServerInfo &info)
{
const QStringList features = info.getFeatureStrings();
setServerInfoKeyValue(db, account, "version", info.getVersionString());
Q_FOREACH(const QString& feature, features)
{
setServerInfoKeyValue(db, account, feature, "true");
}
bool changed = account.serverInfo != info;
if (!changed)
return;
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i] == account) {
if (i == 0)
emit beforeAccountChanged();
accounts_[i].serverInfo = info;
if (i == 0)
emit accountsChanged();
break;
}
}
}
void AccountManager::serverInfoFailed(const ApiError &error)
{
qWarning("update server info failed %s\n", error.toString().toUtf8().data());
}
bool AccountManager::clearAccountToken(const Account& account)
{
Account new_account = account;
new_account.token = "";
for (size_t i = 0; i < accounts_.size(); i++) {
if (accounts_[i].serverUrl.toString() == account.serverUrl.toString()
&& accounts_[i].username == account.username) {
accounts_.erase(accounts_.begin() + i);
break;
}
}
accounts_.push_back(new_account);
char *zql = sqlite3_mprintf(
"UPDATE Accounts "
"SET token = NULL "
"WHERE url = %Q "
" AND username = %Q",
// url
new_account.serverUrl.toEncoded().data(),
// username
new_account.username.toUtf8().data()
);
sqlite_query_exec(db, zql);
sqlite3_free(zql);
emit accountsChanged();
return true;
}
Account AccountManager::getAccountByRepo(const QString& repo_id)
{
SeafileRpcClient *rpc = seafApplet->rpcClient();
if (!accounts_cache_.contains(repo_id)) {
QString relay_addr;
if (rpc->getRepoProperty(repo_id, kRepoRelayAddrProperty, &relay_addr) < 0) {
return Account();
}
const std::vector<Account>& accounts = seafApplet->accountManager()->accounts();
for (unsigned i = 0; i < accounts.size(); i++) {
const Account& account = accounts[i];
if (account.serverUrl.host() == relay_addr) {
accounts_cache_[repo_id] = account;
break;
}
}
}
return accounts_cache_.value(repo_id, Account());
}
void AccountManager::onAccountsChanged()
{
accounts_cache_.clear();
}
void AccountManager::invalidateCurrentLogin()
{
// make sure we have accounts there
if (!hasAccount())
return;
const Account &account = accounts().front();
// if the token is already invalidated, ignore
if (account.token.isEmpty())
return;
clearAccountToken(account);
seafApplet->warningBox(tr("Authorization expired, please re-login"));
// we have the expire account at the last position
emit accountRequireRelogin(accounts().back());
}
<|endoftext|>
|
<commit_before>// 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/.
//
// Copyright (C) 2012-2016, Ryan P. Wilson
//
// Authority FX, Inc.
// www.authorityfx.com
#include <DDImage/Iop.h>
#include <DDImage/Row.h>
#include <DDImage/Knobs.h>
#include <DDImage/ImagePlane.h>
#include <DDImage/Thread.h>
#include <cuda_runtime.h>
#include "cuda_helper.h"
#include "median.h"
#include "color_op.h"
// The class name must match exactly what is in the meny.py: nuke.createNode(CLASS)
static const char* CLASS = "AFXDeSpill";
static const char* HELP = "Remove Spill";
#define ThisClass AFXDeSpill
extern "C" void EdgeMatteCuda(afx::Bounds in_bnds);
enum inputs
{
iSource = 0,
iMatte = 1
};
const char* algorithm_list[8] =
{
"Light",
"Medium",
"Hard",
"Harder",
"Even Harder",
"Extreme",
"Uber",
0
};
using namespace DD::Image;
class ThisClass : public Iop {
private:
// members to store knob values
float k_amount_;
int k_algorithm_;
ChannelSet k_spill_matte_channel_;
float k_screen_color_[3];
// members to store processed knob values
afx::Bounds req_bnds_, format_bnds, format_f_bnds_;
float proxy_scale_;
afx::CudaProcess cuda_process_;
afx::CudaImageArray row_imgs_;
afx::CudaImageArray in_imgs_;
afx::CudaStreamArray streams_;
afx::RotateColor hue_shifter_;
afx::RotateColor hue_shifter_inv_;
float ref_suppression_;
void MetricsCPU(afx::Bounds region, const ImagePlane& source, const ImagePlane& matte, float* ref_hsv, double* sum, double* sum_sqrs, unsigned int& num);
void ProcessCUDA(int y, int x, int r, ChannelMask channels, Row& row);
void ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row);
public:
ThisClass(Node* node);
void knobs(Knob_Callback);
int knob_changed(Knob* k);
const char* Class() const;
const char* node_help() const;
static const Iop::Description d;
Op* default_input(int input) const;
const char* input_label(int input, char* buffer) const;
void _validate(bool);
void _request(int x, int y, int r, int t, ChannelMask channels, int count);
void _open();
void _close();
void engine(int y, int x, int r, ChannelMask channels, Row& row);
};
ThisClass::ThisClass(Node* node) : Iop(node) {
//Set inputs
inputs(2);
try {
cuda_process_.MakeReady();
} catch (cudaError err) {}
//initialize knobs
k_algorithm_ = afx::kHard;
k_amount_ = 1.0f;
k_screen_color_[0] = k_screen_color_[2] = 0.0f;
k_screen_color_[1] = 1.0f;
}
void ThisClass::knobs(Knob_Callback f) {
Color_knob(f, k_screen_color_, "screen_color", "Screen Color");
Tooltip(f, "Color of Chroma Screen");
ClearFlags(f, Knob::MAGNITUDE | Knob::SLIDER);
Divider(f, "Settings");
Float_knob(f, &k_amount_, "amount", "Amount");
Tooltip(f, "Amount to remove");
SetRange(f, 0.0, 1.0);
Enumeration_knob(f, &k_algorithm_, algorithm_list, "algorithm", "Algorithm");
Tooltip(f, "Spill Algorithm");
Divider(f, "Output");
ChannelMask_knob(f, &k_spill_matte_channel_, "Spill Matte");
}
int ThisClass::knob_changed(Knob* k) {
return Iop::knob_changed(k);
}
const char* ThisClass::Class() const { return CLASS; }
const char* ThisClass::node_help() const { return HELP; }
static Iop* build(Node* node) { return new ThisClass(node); }
const Op::Description ThisClass::d(CLASS, "AuthorityFX/AFX Smart Median", build);
Op* ThisClass::default_input(int input) const {
if (input == 0) { return Iop::default_input(0); }
return 0;
}
const char* ThisClass::input_label(int input, char* buffer) const {
switch (input) {
case 0: {
input_longlabel(input) = "Source Image";
return "Source";
}
case 1: {
input_longlabel(input) = "Spill Matte";
return "Spill Matte";
}
default: {
return 0;
}
}
}
void ThisClass::_validate(bool) {
if (input(iSource) != default_input(iSource)) {
//Copy source info
copy_info(0);
req_bnds_.SetBounds(info_.x(), info_.y(), info_.r() - 1, info_.t() - 1);
format_bnds.SetBounds(input(0)->format().x(), input(0)->format().y(), input(0)->format().r() - 1, input(0)->format().t() - 1);
format_f_bnds_.SetBounds(input(0)->full_size_format().x(), input(0)->full_size_format().y(), input(0)->full_size_format().r() - 1,
input(0)->full_size_format().t() - 1);
proxy_scale_ = (float)format_bnds.GetWidth() / (float)format_f_bnds_.GetWidth();
ChannelSet out_channels = channels();
out_channels += Chan_Red;
out_channels += Chan_Green;
out_channels += Chan_Blue;
out_channels += k_spill_matte_channel_;
set_out_channels(out_channels);
info_.turn_on(out_channels);
// Process knob values
// 1/3 hue is pure green. (1/3 - mean) * 360 is the degress from pure green
float hsv[3];
float ref_rgb[3];
for (int i = 0; i < 3; i++) { ref_rgb[i] = k_screen_color_[i]; }
afx::RGBtoHSV(ref_rgb, hsv);
float hue_rotation = 360.0f * (1.0f/3.0f - hsv[0]);
hue_shifter_.BuildMatrix(hue_rotation); //Initialize hue shifter object
hue_shifter_.Rotate(ref_rgb); // Rotate hue of ref RGB so that the mean hue is pure green
ref_suppression_ = afx::SpillSupression(ref_rgb, afx::kLight); // Spill suppressoin of ref_rgb
hue_shifter_inv_ = hue_shifter_;
hue_shifter_inv_.Invert();
} else {
set_out_channels(Mask_None);
copy_info();
}
}
void ThisClass::_request(int x, int y, int r, int t, ChannelMask channels, int count) {
//Request source
if (input(iSource) != default_input(iSource)) {
input(iSource)->request(x, y, r, t, channels, count);
}
//Request ignore matte
if (input(iMatte) != nullptr) {
input(iMatte)->request(x, y, r, t, Mask_Alpha, count);
}
}
void ThisClass::_open() {
}
void ThisClass::_close() {
}
void ThisClass::engine(int y, int x, int r, ChannelMask channels, Row& row) {
callCloseAfter(0);
ProcessCPU(y, x, r, channels, row);
}
void ThisClass::ProcessCUDA(int y, int x, int r, ChannelMask channels, Row& row) {
}
void ThisClass::ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row) {
Channel rgb_chan[3];
rgb_chan[0] = Chan_Red;
rgb_chan[1] = Chan_Green;
rgb_chan[2] = Chan_Blue;
// Must call get before initializing any pointers
row.get(input0(), y, x, r, channels);
// Copy all other channels through unchanged
ChannelSet copy_mask = channels - Mask_RGB - k_spill_matte_channel_;
row.pre_copy(row, copy_mask);
row.copy(row, copy_mask, x, r);
Row m_row(x, r);
if (input(iMatte) != nullptr) { m_row.get(*input(iMatte), y, x, r, Mask_Alpha); }
float rgb[3] = {0, 0, 0};
afx::ReadOnlyPixel in_px(3);
afx::Pixel out_px(3);
for (int i = 0; i < 3; i++) {
in_px.SetPtr(row[rgb_chan[i]] + x, i);// Set const in pointers RGB
out_px.SetPtr(row.writable(rgb_chan[i]) + x, i); // Set out pointers RGB
}
const float* m_ptr = nullptr;
if (input(iMatte) != nullptr) { m_ptr = m_row[Chan_Alpha] + x; }
for (int x0 = x; x0 < r; ++x0) { // Loop through pixels in row
float suppression_matte = 0.0f;
float m = 1.0f;
if (input(iMatte) != nullptr) { m = *m_ptr; }
for (int i = 0; i < 3; i++) { rgb[i] = in_px.GetVal(i); }
hue_shifter_.Rotate(rgb); //Shift hue so mean hue is 1/3 on hue scale
float suppression = k_amount_ * m * afx::SpillSupression(rgb, k_algorithm_); //Calculate suppression
rgb[1] -= suppression;
hue_shifter_inv_.Rotate(rgb);
for (int i = 0; i < 3; i++) { rgb[i] = fmaxf(rgb[i], 0.0f); }
suppression_matte = clamp(suppression / ref_suppression_, 0.0f, 1.0f);
for (int i = 0; i < 3; i++) {
out_px[i] = rgb[i];
}
foreach (z, k_spill_matte_channel_) { *(row.writable(z) + x0) = suppression_matte; }
in_px++;
out_px++;
if (input(iMatte) != nullptr) { m_ptr++; }
}
}
<commit_msg>Added Lightness Adjustment control Changed default algo to Harder<commit_after>// 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/.
//
// Copyright (C) 2012-2016, Ryan P. Wilson
//
// Authority FX, Inc.
// www.authorityfx.com
#include <DDImage/Iop.h>
#include <DDImage/Row.h>
#include <DDImage/Knobs.h>
#include <DDImage/ImagePlane.h>
#include <DDImage/Thread.h>
#include <cuda_runtime.h>
#include "cuda_helper.h"
#include "median.h"
#include "color_op.h"
// The class name must match exactly what is in the meny.py: nuke.createNode(CLASS)
static const char* CLASS = "AFXDeSpill";
static const char* HELP = "Remove Spill";
#define ThisClass AFXDeSpill
enum inputs
{
iSource = 0,
iMatte = 1
};
const char* algorithm_list[8] =
{
"Light",
"Medium",
"Hard",
"Harder",
"Even Harder",
"Extreme",
"Uber",
0
};
using namespace DD::Image;
class ThisClass : public Iop {
private:
// members to store knob values
float k_amount_;
float k_lightness_adj;
int k_algorithm_;
ChannelSet k_spill_matte_channel_;
float k_screen_color_[3];
// members to store processed knob values
afx::Bounds req_bnds_, format_bnds, format_f_bnds_;
float proxy_scale_;
afx::CudaProcess cuda_process_;
afx::CudaImageArray row_imgs_;
afx::CudaImageArray in_imgs_;
afx::CudaStreamArray streams_;
afx::RotateColor hue_shifter_;
afx::RotateColor hue_shifter_inv_;
float ref_suppression_;
void MetricsCPU(afx::Bounds region, const ImagePlane& source, const ImagePlane& matte, float* ref_hsv, double* sum, double* sum_sqrs, unsigned int& num);
void ProcessCUDA(int y, int x, int r, ChannelMask channels, Row& row);
void ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row);
public:
ThisClass(Node* node);
void knobs(Knob_Callback);
int knob_changed(Knob* k);
const char* Class() const;
const char* node_help() const;
static const Iop::Description d;
Op* default_input(int input) const;
const char* input_label(int input, char* buffer) const;
void _validate(bool);
void _request(int x, int y, int r, int t, ChannelMask channels, int count);
void _open();
void _close();
void engine(int y, int x, int r, ChannelMask channels, Row& row);
};
ThisClass::ThisClass(Node* node) : Iop(node) {
//Set inputs
inputs(2);
try {
cuda_process_.MakeReady();
} catch (cudaError err) {}
//initialize knobs
k_algorithm_ = afx::kHarder;
k_amount_ = 1.0f;
k_lightness_adj = 1.0f;
k_screen_color_[0] = k_screen_color_[2] = 0.0f;
k_screen_color_[1] = 1.0f;
}
void ThisClass::knobs(Knob_Callback f) {
Color_knob(f, k_screen_color_, "screen_color", "Screen Color");
Tooltip(f, "Color of Chroma Screen");
ClearFlags(f, Knob::MAGNITUDE | Knob::SLIDER);
Divider(f, "Settings");
Float_knob(f, &k_amount_, "amount", "Spill Amount");
Tooltip(f, "Amount of spill to remove");
SetRange(f, 0.0, 1.0);
SetFlags(f, Knob::FORCE_RANGE);
Float_knob(f, &k_lightness_adj, "lightness_adj", "Lightness Adjustment");
Tooltip(f, "Adjust perceived lightness");
SetRange(f, 0.0, 1.0);
SetFlags(f, Knob::FORCE_RANGE);
Enumeration_knob(f, &k_algorithm_, algorithm_list, "algorithm", "Algorithm");
Tooltip(f, "Spill Algorithm");
Divider(f, "Output");
ChannelMask_knob(f, &k_spill_matte_channel_, "Spill Matte");
}
int ThisClass::knob_changed(Knob* k) {
return Iop::knob_changed(k);
}
const char* ThisClass::Class() const { return CLASS; }
const char* ThisClass::node_help() const { return HELP; }
static Iop* build(Node* node) { return new ThisClass(node); }
const Op::Description ThisClass::d(CLASS, "AuthorityFX/AFX Smart Median", build);
Op* ThisClass::default_input(int input) const {
if (input == 0) { return Iop::default_input(0); }
return 0;
}
const char* ThisClass::input_label(int input, char* buffer) const {
switch (input) {
case 0: {
input_longlabel(input) = "Source Image";
return "Source";
}
case 1: {
input_longlabel(input) = "Spill Matte";
return "Spill Matte";
}
default: {
return 0;
}
}
}
void ThisClass::_validate(bool) {
if (input(iSource) != default_input(iSource)) {
//Copy source info
copy_info(0);
req_bnds_.SetBounds(info_.x(), info_.y(), info_.r() - 1, info_.t() - 1);
format_bnds.SetBounds(input(0)->format().x(), input(0)->format().y(), input(0)->format().r() - 1, input(0)->format().t() - 1);
format_f_bnds_.SetBounds(input(0)->full_size_format().x(), input(0)->full_size_format().y(), input(0)->full_size_format().r() - 1,
input(0)->full_size_format().t() - 1);
proxy_scale_ = (float)format_bnds.GetWidth() / (float)format_f_bnds_.GetWidth();
ChannelSet out_channels = channels();
out_channels += Chan_Red;
out_channels += Chan_Green;
out_channels += Chan_Blue;
out_channels += k_spill_matte_channel_;
set_out_channels(out_channels);
info_.turn_on(out_channels);
// Process knob values
// 1/3 hue is pure green. (1/3 - mean) * 360 is the angular distance in degrees form pure green
float hsv[3];
float ref_rgb[3];
for (int i = 0; i < 3; i++) { ref_rgb[i] = k_screen_color_[i]; }
afx::RGBtoHSV(ref_rgb, hsv);
float hue_rotation = 360.0f * (1.0f/3.0f - hsv[0]);
hue_shifter_.BuildMatrix(hue_rotation); //Initialize hue shifter object
hue_shifter_.Rotate(ref_rgb); // Rotate hue of ref RGB so that the mean hue is pure green
ref_suppression_ = afx::SpillSupression(ref_rgb, k_algorithm_); // Spill suppressoin of ref_rgb
hue_shifter_inv_ = hue_shifter_;
hue_shifter_inv_.Invert();
} else {
set_out_channels(Mask_None);
copy_info();
}
}
void ThisClass::_request(int x, int y, int r, int t, ChannelMask channels, int count) {
//Request source
if (input(iSource) != default_input(iSource)) {
input(iSource)->request(x, y, r, t, channels, count);
}
//Request ignore matte
if (input(iMatte) != nullptr) {
input(iMatte)->request(x, y, r, t, Mask_Alpha, count);
}
}
void ThisClass::_open() {
}
void ThisClass::_close() {
}
void ThisClass::engine(int y, int x, int r, ChannelMask channels, Row& row) {
callCloseAfter(0);
ProcessCPU(y, x, r, channels, row);
}
void ThisClass::ProcessCUDA(int y, int x, int r, ChannelMask channels, Row& row) {
}
void ThisClass::ProcessCPU(int y, int x, int r, ChannelMask channels, Row& row) {
Channel rgb_chan[3];
rgb_chan[0] = Chan_Red;
rgb_chan[1] = Chan_Green;
rgb_chan[2] = Chan_Blue;
// Must call get before initializing any pointers
row.get(input0(), y, x, r, channels);
// Copy all other channels through unchanged
ChannelSet copy_mask = channels - Mask_RGB - k_spill_matte_channel_;
row.pre_copy(row, copy_mask);
row.copy(row, copy_mask, x, r);
Row m_row(x, r);
if (input(iMatte) != nullptr) { m_row.get(*input(iMatte), y, x, r, Mask_Alpha); }
float rgb[3] = {0, 0, 0};
afx::ReadOnlyPixel in_px(3);
afx::Pixel out_px(3);
for (int i = 0; i < 3; i++) {
in_px.SetPtr(row[rgb_chan[i]] + x, i);// Set const in pointers RGB
out_px.SetPtr(row.writable(rgb_chan[i]) + x, i); // Set out pointers RGB
}
const float* m_ptr = nullptr;
if (input(iMatte) != nullptr) { m_ptr = m_row[Chan_Alpha] + x; }
for (int x0 = x; x0 < r; ++x0) { // Loop through pixels in row
float suppression_matte = 0.0f;
float m = 1.0f;
if (input(iMatte) != nullptr) { m = *m_ptr; }
for (int i = 0; i < 3; i++) { rgb[i] = in_px.GetVal(i); }
float L1 = powf(0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2], 1.0f / 3.0f); // Lightness - cubic root of relative luminance
hue_shifter_.Rotate(rgb); //Shift hue so mean hue is 1/3 on hue scale
float suppression = k_amount_ * m * afx::SpillSupression(rgb, k_algorithm_); //Calculate suppression
rgb[1] -= suppression;
hue_shifter_inv_.Rotate(rgb);
float L2 = powf(0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2], 1.0f / 3.0f);
float lightness_adjust = k_lightness_adj * (L1 / L2 - 1) + 1;
for (int i = 0; i < 3; i++) { rgb[i] = fmaxf(rgb[i] * lightness_adjust, 0.0f); }
suppression_matte = afx::Clamp(suppression / ref_suppression_, 0.0f, 1.0f);
for (int i = 0; i < 3; i++) {
out_px[i] = rgb[i];
}
foreach (z, k_spill_matte_channel_) { *(row.writable(z) + x0) = suppression_matte; }
in_px++;
out_px++;
if (input(iMatte) != nullptr) { m_ptr++; }
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
/*
* NAOQI
*/
#include <qi/anyobject.hpp>
/*
* BOOST
*/
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
/*
* PUBLIC INTERFACE
*/
#include <alrosbridge/alrosbridge.hpp>
/*
* publishers
*/
#include "publishers/string.hpp"
#include "publishers/int.hpp"
#include "publishers/joint_state.hpp"
#include "publishers/camera.hpp"
/*
* STATIC FUNCTIONS INCLUDE
*/
#include "ros_env.hpp"
#include "helpers.hpp"
namespace alros
{
Bridge::Bridge( qi::SessionPtr& session )
: sessionPtr_( session ),
freq_(15),
publish_enabled_(false)
{
std::cout << "application started " << std::endl;
}
Bridge::~Bridge()
{
std::cout << "BridgeService is shutting down.." << std::endl;
stop();
// destroy nodehandle?
nhPtr_->shutdown();
ros::shutdown();
publisherThread_.join();
}
void Bridge::rosLoop()
{
while( ros::ok() )
{
if ( isAlive() )
{
// Wait for the next Publisher to be ready
alros::publisher::Publisher* pub = pub_queue_.top().pub_;
ros::Time schedule = pub_queue_.top().schedule_;
ros::Duration(schedule - ros::Time::now()).sleep();
if ( pub->isSubscribed() && pub->isInitialized() )
{
// std::cout << "******************************" << std::endl;
// std::cout << "Publisher name:\t" << pub->name() << std::endl;
// std::cout << "Publisher subscribed:\t" << pub->isSubscribed() << std::endl;
// std::cout << "Publisher init:\t" << pub->isInitialized() << std::endl;
pub->publish();
}
// Schedule for a future time
pub_queue_.pop();
pub_queue_.push(ScheduledPublish(schedule + ros::Duration(1.0f / pub->frequency()), pub));
}
ros::spinOnce();
}
}
// public interface here
void Bridge::registerPublisher( publisher::Publisher pub )
{
std::vector<publisher::Publisher>::iterator it;
it = std::find( all_publisher_.begin(), all_publisher_.end(), pub );
// if publisher is not found, register it!
if (it == all_publisher_.end() )
{
all_publisher_.push_back( pub );
it = all_publisher_.end() - 1;
std::cout << "registered publisher:\t" << pub.name() << std::endl;
}
// if found, re-init them
else
{
std::cout << "re-initialized existing publisher:\t" << it->name() << std::endl;
}
// Schedule it for the next publish
pub_queue_.push(ScheduledPublish(ros::Time::now() + ros::Duration(1.0f / pub.frequency()), &(*it)));
}
void Bridge::registerDefaultPublisher()
{
qi::AnyObject p_motion = sessionPtr_->service("ALMotion");
qi::AnyObject p_video = sessionPtr_->service("ALVideoDevice");
// registerPublisher( alros::publisher::StringPublisher( "string_pub", "string_pub", 15) );
// registerPublisher( alros::publisher::IntPublisher("int_pub", "int_pub", 15) );
// registerPublisher( alros::publisher::JointStatePublisher("/joint_states", "/joint_states", 15, p_motion) );
registerPublisher( alros::publisher::CameraPublisher("camera", "camera/front", 15, p_video) );
}
void Bridge::initPublisher()
{
foreach( publisher::Publisher& pub, all_publisher_ )
{
pub.reset( *nhPtr_ );
}
}
/*
* EXPOSED FUNCTIONS
*/
std::string Bridge::getMasterURI() const
{
return ros_env::getMasterURI();
}
void Bridge::setMasterURI( const std::string& uri )
{
boost::mutex::scoped_lock lock( mutex_reinit_ );
nhPtr_.reset();
std::cout << "nodehandle reset " << std::endl;
ros_env::setMasterURI( uri );
nhPtr_.reset( new ros::NodeHandle("~") );
lock.unlock();
publisherThread_ = boost::thread( &Bridge::rosLoop, this );
// first register publisher
registerDefaultPublisher();
// second initialize them with nodehandle
initPublisher();
start();
}
void Bridge::start()
{
boost::mutex::scoped_lock( mutex_reinit_ );
publish_enabled_ = true;
}
void Bridge::stop()
{
boost::mutex::scoped_lock( mutex_reinit_ );
publish_enabled_ = false;
}
bool Bridge::isAlive() const
{
boost::mutex::scoped_lock( mutex_reinit_ );
return publish_enabled_;
}
QI_REGISTER_OBJECT( Bridge, start, stop, getMasterURI, setMasterURI );
} //alros
<commit_msg>enable all default publisher<commit_after>#include <iostream>
/*
* NAOQI
*/
#include <qi/anyobject.hpp>
/*
* BOOST
*/
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
/*
* PUBLIC INTERFACE
*/
#include <alrosbridge/alrosbridge.hpp>
/*
* publishers
*/
#include "publishers/string.hpp"
#include "publishers/int.hpp"
#include "publishers/joint_state.hpp"
#include "publishers/camera.hpp"
/*
* STATIC FUNCTIONS INCLUDE
*/
#include "ros_env.hpp"
#include "helpers.hpp"
namespace alros
{
Bridge::Bridge( qi::SessionPtr& session )
: sessionPtr_( session ),
freq_(15),
publish_enabled_(false)
{
std::cout << "application started " << std::endl;
}
Bridge::~Bridge()
{
std::cout << "ALRosBridge is shutting down.." << std::endl;
stop();
// destroy nodehandle?
nhPtr_->shutdown();
ros::shutdown();
publisherThread_.join();
}
void Bridge::rosLoop()
{
while( ros::ok() )
{
if ( isAlive() )
{
// Wait for the next Publisher to be ready
alros::publisher::Publisher* pub = pub_queue_.top().pub_;
ros::Time schedule = pub_queue_.top().schedule_;
ros::Duration(schedule - ros::Time::now()).sleep();
if ( pub->isSubscribed() && pub->isInitialized() )
{
// std::cout << "******************************" << std::endl;
// std::cout << "Publisher name:\t" << pub->name() << std::endl;
// std::cout << "Publisher subscribed:\t" << pub->isSubscribed() << std::endl;
// std::cout << "Publisher init:\t" << pub->isInitialized() << std::endl;
pub->publish();
}
// Schedule for a future time
pub_queue_.pop();
pub_queue_.push(ScheduledPublish(schedule + ros::Duration(1.0f / pub->frequency()), pub));
}
ros::spinOnce();
}
}
// public interface here
void Bridge::registerPublisher( publisher::Publisher pub )
{
std::vector<publisher::Publisher>::iterator it;
it = std::find( all_publisher_.begin(), all_publisher_.end(), pub );
// if publisher is not found, register it!
if (it == all_publisher_.end() )
{
all_publisher_.push_back( pub );
it = all_publisher_.end() - 1;
std::cout << "registered publisher:\t" << pub.name() << std::endl;
}
// if found, re-init them
else
{
std::cout << "re-initialized existing publisher:\t" << it->name() << std::endl;
}
// Schedule it for the next publish
pub_queue_.push(ScheduledPublish(ros::Time::now() + ros::Duration(1.0f / pub.frequency()), &(*it)));
}
void Bridge::registerDefaultPublisher()
{
qi::AnyObject p_motion = sessionPtr_->service("ALMotion");
qi::AnyObject p_video = sessionPtr_->service("ALVideoDevice");
registerPublisher( alros::publisher::StringPublisher( "string_pub", "string_pub", 15) );
registerPublisher( alros::publisher::IntPublisher("int_pub", "int_pub", 15) );
registerPublisher( alros::publisher::JointStatePublisher("/joint_states", "/joint_states", 15, p_motion) );
registerPublisher( alros::publisher::CameraPublisher("camera", "camera/front", 15, p_video) );
}
void Bridge::initPublisher()
{
foreach( publisher::Publisher& pub, all_publisher_ )
{
pub.reset( *nhPtr_ );
}
}
/*
* EXPOSED FUNCTIONS
*/
std::string Bridge::getMasterURI() const
{
return ros_env::getMasterURI();
}
void Bridge::setMasterURI( const std::string& uri )
{
boost::mutex::scoped_lock lock( mutex_reinit_ );
nhPtr_.reset();
std::cout << "nodehandle reset " << std::endl;
ros_env::setMasterURI( uri );
nhPtr_.reset( new ros::NodeHandle("~") );
lock.unlock();
publisherThread_ = boost::thread( &Bridge::rosLoop, this );
// first register publisher
registerDefaultPublisher();
// second initialize them with nodehandle
initPublisher();
start();
}
void Bridge::start()
{
boost::mutex::scoped_lock( mutex_reinit_ );
publish_enabled_ = true;
}
void Bridge::stop()
{
boost::mutex::scoped_lock( mutex_reinit_ );
publish_enabled_ = false;
}
bool Bridge::isAlive() const
{
boost::mutex::scoped_lock( mutex_reinit_ );
return publish_enabled_;
}
QI_REGISTER_OBJECT( Bridge, start, stop, getMasterURI, setMasterURI );
} //alros
<|endoftext|>
|
<commit_before>#include "../warnings-disable.h"
WARNINGS_DISABLE
#include <QtTest/QtTest>
#include <QCheckBox>
#include <QComboBox>
#include <QDialog>
#include <QFileSystemModel>
#include <QFontMetrics>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QRadioButton>
#include <QSequentialAnimationGroup>
#include <QStackedWidget>
#include <QTreeView>
#include <QVBoxLayout>
WARNINGS_ENABLE
class TestQTestWeird : public QObject
{
Q_OBJECT
private slots:
void pl_nothing();
void pl_setvisible();
void pl_stackedwidget1();
void pl_stackedwidget2();
void pl_messagebox_icon();
void pl_messagebox_buttons();
};
void TestQTestWeird::pl_nothing()
{
}
void TestQTestWeird::pl_setvisible()
{
QWidget *wid = new QWidget();
wid->setLayout(new QVBoxLayout());
QWidget *p1 = new QWidget();
QWidget *p2 = new QWidget();
wid->layout()->addWidget(p1);
wid->layout()->addWidget(p2);
// We only need to set this on one of them.
p1->setLayout(new QVBoxLayout());
wid->show();
p1->hide();
p1->show();
delete wid;
}
void TestQTestWeird::pl_stackedwidget1()
{
QWidget *wid = new QWidget();
wid->setLayout(new QVBoxLayout());
QStackedWidget *p1 = new QStackedWidget();
QStackedWidget *p2 = new QStackedWidget();
wid->layout()->addWidget(p1);
wid->layout()->addWidget(p2);
QWidget *hideme = new QWidget();
hideme->setLayout(new QVBoxLayout());
QWidget *inner = new QWidget();
inner->setLayout(new QVBoxLayout());
inner->layout()->addWidget(new QLabel());
inner->layout()->addWidget(new QLineEdit());
hideme->layout()->addWidget(inner);
hideme->hide();
wid->layout()->addWidget(hideme);
wid->show();
hideme->show();
hideme->hide();
p1->hide();
p1->show();
p2->hide();
p2->show();
delete wid;
}
void TestQTestWeird::pl_stackedwidget2()
{
QStackedWidget *wid = new QStackedWidget();
QStackedWidget *p1 = new QStackedWidget();
QStackedWidget *p2 = new QStackedWidget();
wid->addWidget(p1);
wid->addWidget(p2);
QWidget *hideme = new QWidget();
hideme->setLayout(new QVBoxLayout());
QWidget *inner = new QWidget();
inner->setLayout(new QVBoxLayout());
inner->layout()->addWidget(new QLabel());
inner->layout()->addWidget(new QLineEdit());
hideme->layout()->addWidget(inner);
hideme->hide();
p1->addWidget(hideme);
wid->show();
wid->setCurrentIndex(1);
wid->setCurrentIndex(0);
delete wid;
}
void TestQTestWeird::pl_messagebox_icon()
{
QMessageBox *box = new QMessageBox();
box->setIcon(QMessageBox::Critical);
delete box;
}
void TestQTestWeird::pl_messagebox_buttons()
{
QMessageBox *box = new QMessageBox();
box->setStandardButtons(QMessageBox::Cancel);
delete box;
}
QTEST_MAIN(TestQTestWeird)
#include "qtest-gui-weird.moc"
<commit_msg>tests/valgrind: check QMessageBox::exec()<commit_after>#include "../warnings-disable.h"
WARNINGS_DISABLE
#include <QtTest/QtTest>
#include <QCheckBox>
#include <QComboBox>
#include <QDialog>
#include <QFileSystemModel>
#include <QFontMetrics>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QRadioButton>
#include <QSequentialAnimationGroup>
#include <QStackedWidget>
#include <QTreeView>
#include <QVBoxLayout>
WARNINGS_ENABLE
class TestQTestWeird : public QObject
{
Q_OBJECT
private slots:
void pl_nothing();
void pl_setvisible();
void pl_stackedwidget1();
void pl_stackedwidget2();
void pl_messagebox_icon();
void pl_messagebox_buttons();
void pl_messagebox_exec();
};
void TestQTestWeird::pl_nothing()
{
}
void TestQTestWeird::pl_setvisible()
{
QWidget *wid = new QWidget();
wid->setLayout(new QVBoxLayout());
QWidget *p1 = new QWidget();
QWidget *p2 = new QWidget();
wid->layout()->addWidget(p1);
wid->layout()->addWidget(p2);
// We only need to set this on one of them.
p1->setLayout(new QVBoxLayout());
wid->show();
p1->hide();
p1->show();
delete wid;
}
void TestQTestWeird::pl_stackedwidget1()
{
QWidget *wid = new QWidget();
wid->setLayout(new QVBoxLayout());
QStackedWidget *p1 = new QStackedWidget();
QStackedWidget *p2 = new QStackedWidget();
wid->layout()->addWidget(p1);
wid->layout()->addWidget(p2);
QWidget *hideme = new QWidget();
hideme->setLayout(new QVBoxLayout());
QWidget *inner = new QWidget();
inner->setLayout(new QVBoxLayout());
inner->layout()->addWidget(new QLabel());
inner->layout()->addWidget(new QLineEdit());
hideme->layout()->addWidget(inner);
hideme->hide();
wid->layout()->addWidget(hideme);
wid->show();
hideme->show();
hideme->hide();
p1->hide();
p1->show();
p2->hide();
p2->show();
delete wid;
}
void TestQTestWeird::pl_stackedwidget2()
{
QStackedWidget *wid = new QStackedWidget();
QStackedWidget *p1 = new QStackedWidget();
QStackedWidget *p2 = new QStackedWidget();
wid->addWidget(p1);
wid->addWidget(p2);
QWidget *hideme = new QWidget();
hideme->setLayout(new QVBoxLayout());
QWidget *inner = new QWidget();
inner->setLayout(new QVBoxLayout());
inner->layout()->addWidget(new QLabel());
inner->layout()->addWidget(new QLineEdit());
hideme->layout()->addWidget(inner);
hideme->hide();
p1->addWidget(hideme);
wid->show();
wid->setCurrentIndex(1);
wid->setCurrentIndex(0);
delete wid;
}
void TestQTestWeird::pl_messagebox_icon()
{
QMessageBox *box = new QMessageBox();
box->setIcon(QMessageBox::Critical);
delete box;
}
void TestQTestWeird::pl_messagebox_buttons()
{
QMessageBox *box = new QMessageBox();
box->setStandardButtons(QMessageBox::Cancel);
delete box;
}
void TestQTestWeird::pl_messagebox_exec()
{
QMessageBox *box = new QMessageBox();
QMetaObject::invokeMethod(box, "close", Qt::QueuedConnection);
box->exec();
delete box;
}
QTEST_MAIN(TestQTestWeird)
#include "qtest-gui-weird.moc"
<|endoftext|>
|
<commit_before>#include "factory.h"
#include "opencv_video_source.h"
namespace gg {
IVideoSource * Factory::_sources[1] = { NULL };
IVideoSource * Factory::connect(enum Device type) {
switch (type) {
case DVI2PCIeDuo:
if (_sources[Device::DVI2PCIeDuo] == NULL)
{
int start = 0, end = 4;
bool found = false;
for (int deviceId = start; deviceId <= end; deviceId++)
{
try
{
IVideoSource * src = new VideoSourceOpenCV(deviceId);
int width = -1, height = -1;
if (src->get_frame_dimensions(width, height))
if (width > 0 and height > 0) {
found = true;
_sources[Device::DVI2PCIeDuo] = src;
break;
}
}
catch (DeviceNotFound & dnf)
{
continue;
}
}
if (not found)
{
std::string error = "Tried to locate Epiphan DVI2PCIeDuo in devices ";
error.append(std::to_string(start));
error.append(" (e.g. /dev/video");
error.append(std::to_string(start));
error.append(" on Linux)");
error.append(" to ");
error.append(std::to_string(end));
error.append(" with no success");
throw DeviceNotFound(error);
}
}
return _sources[Device::DVI2PCIeDuo];
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(type))
.append(" not recognised");
throw DeviceNotFound(msg);
}
}
void Factory::disconnect(enum Device type) {
switch (type) {
case DVI2PCIeDuo:
if (_sources[Device::DVI2PCIeDuo]) {
delete _sources[Device::DVI2PCIeDuo];
_sources[Device::DVI2PCIeDuo] = NULL;
}
break;
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(type))
.append(" not recognised");
throw DeviceNotFound(msg);
}
}
}
<commit_msg>added more verbose information to thrown exception when device not found<commit_after>#include "factory.h"
#include "opencv_video_source.h"
namespace gg {
IVideoSource * Factory::_sources[1] = { NULL };
IVideoSource * Factory::connect(enum Device type) {
switch (type) {
case DVI2PCIeDuo:
if (_sources[Device::DVI2PCIeDuo] == NULL)
{
std::string framerate_checks = "";
int start = 0, end = 4;
bool found = false;
for (int deviceId = start; deviceId <= end; deviceId++)
{
try
{
IVideoSource * src = new VideoSourceOpenCV(deviceId);
int width = -1, height = -1;
if (src->get_frame_dimensions(width, height))
if (width > 0 and height > 0) {
found = true;
_sources[Device::DVI2PCIeDuo] = src;
break;
}
// meaningless frame dimensions, or unsuccessful query:
if (not framerate_checks.empty())
framerate_checks.append(", ");
framerate_checks.append(std::to_string(deviceId));
}
catch (DeviceNotFound & dnf)
{
continue;
}
}
if (not found)
{
std::string error = "Tried to locate Epiphan DVI2PCIeDuo in devices ";
error.append(std::to_string(start));
error.append(" (e.g. /dev/video");
error.append(std::to_string(start));
error.append(" on Linux)");
error.append(" to ");
error.append(std::to_string(end));
error.append(" with no success");
if (not framerate_checks.empty())
{
error.append(" (");
error.append(framerate_checks);
error.append(" could be connected to, ");
error.append("but replied with meaningless frame dimensions)");
}
throw DeviceNotFound(error);
}
}
return _sources[Device::DVI2PCIeDuo];
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(type))
.append(" not recognised");
throw DeviceNotFound(msg);
}
}
void Factory::disconnect(enum Device type) {
switch (type) {
case DVI2PCIeDuo:
if (_sources[Device::DVI2PCIeDuo]) {
delete _sources[Device::DVI2PCIeDuo];
_sources[Device::DVI2PCIeDuo] = NULL;
}
break;
default:
std::string msg;
msg.append("Device ")
.append(std::to_string(type))
.append(" not recognised");
throw DeviceNotFound(msg);
}
}
}
<|endoftext|>
|
<commit_before>#include "application.hpp"
#include "titlestate.hpp"
#include "gamestate.hpp"
#include <menustate.hpp>
#include "editlevelstate.hpp"
#include <iostream>
Application::Application(State::Context context)
: mStateStack(context)
, mWindow(context.window)
{
registerStates();
mStateStack.pushState(States::Title);
sf::Event event;
mStateStack.handleEvent(event);
}
void Application::registerStates()
{
mStateStack.registerState<TitleState>(States::Title);
mStateStack.registerState<MenuState>(States::Menu);
mStateStack.registerState<GameState>(States::Game);
//mStateStack.registerState<EditLevelState>(States::Editor);
//mStateStack.registerState<PauseState>(States::Pause);
//mStateStack.registerState<SpeechState>(States::Speech);
}
void Application::processInput()
{
sf::Event event;
while(mWindow->pollEvent(event))
{
if (event.type == sf::Event::Closed) {
mWindow->close();
mStateStack.clearStates();
}
mStateStack.handleEvent(event);
}
}
void Application::update(sf::Time dt)
{
mStateStack.update(dt);
}
void Application::render()
{
mStateStack.draw();
}
int Application::run()
{
sf::Clock clock;
sf::Time dt=clock.restart();
while(!mStateStack.isEmpty())
{
dt = clock.restart();
processInput();
update(dt);
render();
}
mWindow->close();
return 0;
}
<commit_msg>Fix EditLevelState crashing errors.<commit_after>#include "application.hpp"
#include "titlestate.hpp"
#include "gamestate.hpp"
#include <menustate.hpp>
#include "editlevelstate.hpp"
#include <iostream>
Application::Application(State::Context context)
: mStateStack(context)
, mWindow(context.window)
{
registerStates();
mStateStack.pushState(States::Title);
sf::Event event;
mStateStack.handleEvent(event);
}
void Application::registerStates()
{
mStateStack.registerState<TitleState>(States::Title);
mStateStack.registerState<MenuState>(States::Menu);
mStateStack.registerState<GameState>(States::Game);
mStateStack.registerState<EditLevelState>(States::Editor);
//mStateStack.registerState<PauseState>(States::Pause);
//mStateStack.registerState<SpeechState>(States::Speech);
}
void Application::processInput()
{
sf::Event event;
while(mWindow->pollEvent(event))
{
if (event.type == sf::Event::Closed) {
mWindow->close();
mStateStack.clearStates();
}
mStateStack.handleEvent(event);
}
}
void Application::update(sf::Time dt)
{
mStateStack.update(dt);
}
void Application::render()
{
mStateStack.draw();
}
int Application::run()
{
sf::Clock clock;
sf::Time dt=clock.restart();
while(!mStateStack.isEmpty())
{
dt = clock.restart();
processInput();
update(dt);
render();
}
mWindow->close();
return 0;
}
<|endoftext|>
|
<commit_before>#include "./application.h"
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <vector>
#include "./window.h"
#include "./scene.h"
#include "./scene_controller.h"
#include "./nodes.h"
#include "./nodes_controller.h"
#include "./label_node.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_model.h"
#include "./placement_labeller_model.h"
#include "./labels_model.h"
#include "./camera_positions_model.h"
#include "./labelling/labels.h"
#include "./labelling_coordinator.h"
#include "./labelling_controller.h"
#include "./picking_controller.h"
#include "./forces_visualizer_node.h"
#include "./camera_node.h"
#include "./default_scene_creator.h"
#include "./video_recorder.h"
#include "./video_recorder_controller.h"
#include "./texture_mapper_manager.h"
#include "./texture_mapper_manager_controller.h"
#include "./utils/memory.h"
#include "./utils/path_helper.h"
#include "./recording_automation.h"
#include "./recording_automation_controller.h"
Application::Application(int &argc, char **argv) : application(argc, argv)
{
application.setApplicationName("voly-labeller");
application.setApplicationVersion("0.0.1");
application.setOrganizationName("LBI");
setupCommandLineParser();
parser.process(application);
invokeManager = std::make_shared<InvokeManager>();
nodes = std::make_shared<Nodes>();
nodesController = std::make_shared<NodesController>(nodes);
labels = std::make_shared<Labels>();
forcesLabeller = std::make_shared<Forces::Labeller>(labels);
int layerCount = parseLayerCount();
auto labellingCoordinator = std::make_shared<LabellingCoordinator>(
layerCount, forcesLabeller, labels, nodes);
bool synchronousCapturing = parser.isSet("offline");
const float offlineFPS = 24;
videoRecorder =
std::make_shared<VideoRecorder>(synchronousCapturing, offlineFPS);
videoRecorderController =
std::make_unique<VideoRecorderController>(videoRecorder);
recordingAutomation = std::make_shared<RecordingAutomation>(
labellingCoordinator, nodes, videoRecorder);
if (parser.isSet("screenshot"))
recordingAutomation->takeScreenshotOfPositionAndExit(
parser.value("screenshot").toStdString());
recordingAutomationController =
std::make_unique<RecordingAutomationController>(recordingAutomation);
const int postProcessingTextureSize = 1024;
textureMapperManager =
std::make_shared<TextureMapperManager>(postProcessingTextureSize);
textureMapperManagerController =
std::make_unique<TextureMapperManagerController>(textureMapperManager);
scene = std::make_shared<Scene>(layerCount, invokeManager, nodes, labels,
labellingCoordinator, textureMapperManager,
recordingAutomation);
float offlineRenderingFrameTime =
parser.isSet("offline") ? 1.0f / offlineFPS : 0.0f;
window =
std::make_unique<Window>(scene, videoRecorder, offlineRenderingFrameTime);
QObject::connect(window.get(), &Window::initializationDone, this,
&Application::onInitializationDone);
sceneController = std::make_unique<SceneController>(scene);
labellerModel = std::make_unique<LabellerModel>(forcesLabeller);
placementLabellerModel =
std::make_unique<PlacementLabellerModel>(labellingCoordinator);
cameraPositionsModel = std::make_unique<CameraPositionsModel>(nodes);
mouseShapeController = std::make_unique<MouseShapeController>();
pickingController = std::make_shared<PickingController>(scene);
labelsModel = std::make_unique<LabelsModel>(labels, pickingController);
labellingController =
std::make_unique<LabellingController>(labellingCoordinator);
}
Application::~Application()
{
}
int Application::execute()
{
qInfo() << "Application start";
auto unsubscribeLabelChanges = labels->subscribe(
std::bind(&Application::onLabelChangedUpdateLabelNodes, this,
std::placeholders::_1, std::placeholders::_2));
setupWindow();
connect(labellerModel.get(), &LabellerModel::isVisibleChanged, this,
&Application::onFocesLabellerModelIsVisibleChanged);
window->setSource(QUrl("qrc:ui.qml"));
forcesLabeller->resize(window->size().width(), window->size().height());
nodes->setOnNodeAdded(
[this](std::shared_ptr<Node> node) { this->onNodeAdded(node); });
nodes->getCameraNode()->setOnCameraPositionsChanged(
[this](std::vector<CameraPosition> cameraPositions) {
this->cameraPositionsModel->update(cameraPositions);
});
if (parser.positionalArguments().size())
{
auto absolutePath = QDir(parser.positionalArguments()[0]).absolutePath();
auto filename = absolutePathToProjectRelativePath(absolutePath);
qInfo() << "import scene:" << filename;
nodesController->addSceneNodesFrom(filename);
}
else
{
DefaultSceneCreator sceneCreator(nodes, labels);
sceneCreator.create();
}
createAndStartStateMachine();
window->show();
auto resultCode = application.exec();
unsubscribeLabelChanges();
return resultCode;
}
void Application::setupCommandLineParser()
{
QGuiApplication::setApplicationName("voly-labeller");
QGuiApplication::setApplicationVersion("0.1");
parser.setApplicationDescription(
"Multiple labelling implementations for volume rendered medical data");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument(
"scene", QCoreApplication::translate("main", "Scene file to load."));
QCommandLineOption offlineRenderingOption("offline",
"Enables offline rendering");
parser.addOption(offlineRenderingOption);
QCommandLineOption layersOption("layers", "Number of layers. Default is 4",
"layerCount", "4");
parser.addOption(layersOption);
QCommandLineOption hardConstraintsOption("hard-constraints",
"Simulate hard constraints");
parser.addOption(hardConstraintsOption);
QCommandLineOption apolloniusOption(
"apollonius", "Use apollonius graph to determine label insertion order");
parser.addOption(apolloniusOption);
QCommandLineOption disableLabellingOption("disable-labelling",
"Disable drawing lables");
parser.addOption(disableLabellingOption);
QCommandLineOption optimizeOnIdleOption(
"optimize-on-idle", "Optimize costs when the camera is not moving");
parser.addOption(optimizeOnIdleOption);
QCommandLineOption screenshotOption(
QStringList() << "s"
<< "screenshot",
"Takes a screenshot of the given camera position. Characters after a '_' "
"are ignored but added to the filename",
"Camera Position");
parser.addOption(screenshotOption);
}
void Application::setupWindow()
{
window->setResizeMode(QQuickView::SizeRootObjectToView);
auto context = window->rootContext();
auto assetsPath =
QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("assets")));
context->setContextProperty("assetsPath", assetsPath);
auto projectRootPath =
QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString(".")));
context->setContextProperty("projectRootPath", projectRootPath);
context->setContextProperty("window", window.get());
context->setContextProperty("nodes", nodesController.get());
context->setContextProperty("bufferTextures",
textureMapperManagerController.get());
context->setContextProperty("scene", sceneController.get());
context->setContextProperty("labeller", labellerModel.get());
context->setContextProperty("placement", placementLabellerModel.get());
context->setContextProperty("cameraPositions", cameraPositionsModel.get());
context->setContextProperty("labels", labelsModel.get());
context->setContextProperty("labelling", labellingController.get());
context->setContextProperty("videoRecorder", videoRecorderController.get());
context->setContextProperty("automation",
recordingAutomationController.get());
}
void Application::createAndStartStateMachine()
{
auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
invokeManager, signalManager);
invokeManager->addHandler(window.get());
invokeManager->addHandler("mouseShape", mouseShapeController.get());
invokeManager->addHandler("picking", pickingController.get());
invokeManager->addHandler("scene", sceneController.get());
signalManager->addSender("KeyboardEventSender", window.get());
signalManager->addSender("window", window.get());
signalManager->addSender("labels", labelsModel.get());
stateMachine = importer.import();
// just for printCurrentState slot for debugging
window->stateMachine = stateMachine;
stateMachine->start();
}
void Application::onNodeAdded(std::shared_ptr<Node> node)
{
std::shared_ptr<LabelNode> labelNode =
std::dynamic_pointer_cast<LabelNode>(node);
if (labelNode.get())
{
labelNode->anchorSize = nodesController->getAnchorSize();
labels->add(labelNode->label);
}
std::shared_ptr<CameraNode> cameraNode =
std::dynamic_pointer_cast<CameraNode>(node);
if (cameraNode.get())
{
cameraNode->setOnCameraPositionsChanged(
[this](std::vector<CameraPosition> cameraPositions) {
this->cameraPositionsModel->update(cameraPositions);
});
}
}
void Application::onLabelChangedUpdateLabelNodes(Labels::Action action,
const Label &label)
{
auto labelNodes = nodes->getLabelNodes();
auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(),
[label](std::shared_ptr<LabelNode> labelNode) {
return labelNode->label.id == label.id;
});
if (labelNode == labelNodes.end())
{
nodes->addNode(std::make_shared<LabelNode>(label));
}
else if (action == Labels::Action::Delete)
{
nodes->removeNode(*labelNode);
}
else
{
(*labelNode)->label = label;
}
};
void Application::onFocesLabellerModelIsVisibleChanged()
{
if (labellerModel->getIsVisible())
{
nodes->addForcesVisualizerNode(
std::make_shared<ForcesVisualizerNode>(forcesLabeller));
}
else
{
nodes->removeForcesVisualizerNode();
}
}
int Application::parseLayerCount()
{
int layerCount = 4;
if (parser.isSet("layers"))
{
bool gotLayerCount = true;
layerCount = parser.value("layers").toInt(&gotLayerCount);
if (!gotLayerCount)
{
layerCount = 4;
qWarning() << "Problem parsing layer count from"
<< parser.value("layers");
}
if (layerCount < 1 || layerCount > 6)
qFatal("Layer count must be between 1 and 6");
}
return layerCount;
}
void Application::onInitializationDone()
{
if (parser.isSet("hard-constraints"))
placementLabellerModel->simulateHardConstraints();
if (parser.isSet("apollonius"))
labellingController->toggleApollonius();
if (parser.isSet("disable-labelling"))
scene->enableLabelling(false);
if (parser.isSet("optimize-on-idle"))
labellingController->toggleOptimizeOnIdle();
}
<commit_msg>Add --internal-labelling option.<commit_after>#include "./application.h"
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <vector>
#include "./window.h"
#include "./scene.h"
#include "./scene_controller.h"
#include "./nodes.h"
#include "./nodes_controller.h"
#include "./label_node.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_model.h"
#include "./placement_labeller_model.h"
#include "./labels_model.h"
#include "./camera_positions_model.h"
#include "./labelling/labels.h"
#include "./labelling_coordinator.h"
#include "./labelling_controller.h"
#include "./picking_controller.h"
#include "./forces_visualizer_node.h"
#include "./camera_node.h"
#include "./default_scene_creator.h"
#include "./video_recorder.h"
#include "./video_recorder_controller.h"
#include "./texture_mapper_manager.h"
#include "./texture_mapper_manager_controller.h"
#include "./utils/memory.h"
#include "./utils/path_helper.h"
#include "./recording_automation.h"
#include "./recording_automation_controller.h"
Application::Application(int &argc, char **argv) : application(argc, argv)
{
application.setApplicationName("voly-labeller");
application.setApplicationVersion("0.0.1");
application.setOrganizationName("LBI");
setupCommandLineParser();
parser.process(application);
invokeManager = std::make_shared<InvokeManager>();
nodes = std::make_shared<Nodes>();
nodesController = std::make_shared<NodesController>(nodes);
labels = std::make_shared<Labels>();
forcesLabeller = std::make_shared<Forces::Labeller>(labels);
int layerCount = parseLayerCount();
auto labellingCoordinator = std::make_shared<LabellingCoordinator>(
layerCount, forcesLabeller, labels, nodes);
bool synchronousCapturing = parser.isSet("offline");
const float offlineFPS = 24;
videoRecorder =
std::make_shared<VideoRecorder>(synchronousCapturing, offlineFPS);
videoRecorderController =
std::make_unique<VideoRecorderController>(videoRecorder);
recordingAutomation = std::make_shared<RecordingAutomation>(
labellingCoordinator, nodes, videoRecorder);
if (parser.isSet("screenshot"))
recordingAutomation->takeScreenshotOfPositionAndExit(
parser.value("screenshot").toStdString());
recordingAutomationController =
std::make_unique<RecordingAutomationController>(recordingAutomation);
const int postProcessingTextureSize = 1024;
textureMapperManager =
std::make_shared<TextureMapperManager>(postProcessingTextureSize);
textureMapperManagerController =
std::make_unique<TextureMapperManagerController>(textureMapperManager);
scene = std::make_shared<Scene>(layerCount, invokeManager, nodes, labels,
labellingCoordinator, textureMapperManager,
recordingAutomation);
float offlineRenderingFrameTime =
parser.isSet("offline") ? 1.0f / offlineFPS : 0.0f;
window =
std::make_unique<Window>(scene, videoRecorder, offlineRenderingFrameTime);
QObject::connect(window.get(), &Window::initializationDone, this,
&Application::onInitializationDone);
sceneController = std::make_unique<SceneController>(scene);
labellerModel = std::make_unique<LabellerModel>(forcesLabeller);
placementLabellerModel =
std::make_unique<PlacementLabellerModel>(labellingCoordinator);
cameraPositionsModel = std::make_unique<CameraPositionsModel>(nodes);
mouseShapeController = std::make_unique<MouseShapeController>();
pickingController = std::make_shared<PickingController>(scene);
labelsModel = std::make_unique<LabelsModel>(labels, pickingController);
labellingController =
std::make_unique<LabellingController>(labellingCoordinator);
if (parser.isSet("internal-labelling"))
labellingController->toggleInternalLabelling();
}
Application::~Application()
{
}
int Application::execute()
{
qInfo() << "Application start";
auto unsubscribeLabelChanges = labels->subscribe(
std::bind(&Application::onLabelChangedUpdateLabelNodes, this,
std::placeholders::_1, std::placeholders::_2));
setupWindow();
connect(labellerModel.get(), &LabellerModel::isVisibleChanged, this,
&Application::onFocesLabellerModelIsVisibleChanged);
window->setSource(QUrl("qrc:ui.qml"));
forcesLabeller->resize(window->size().width(), window->size().height());
nodes->setOnNodeAdded(
[this](std::shared_ptr<Node> node) { this->onNodeAdded(node); });
nodes->getCameraNode()->setOnCameraPositionsChanged(
[this](std::vector<CameraPosition> cameraPositions) {
this->cameraPositionsModel->update(cameraPositions);
});
if (parser.positionalArguments().size())
{
auto absolutePath = QDir(parser.positionalArguments()[0]).absolutePath();
auto filename = absolutePathToProjectRelativePath(absolutePath);
qInfo() << "import scene:" << filename;
nodesController->addSceneNodesFrom(filename);
}
else
{
DefaultSceneCreator sceneCreator(nodes, labels);
sceneCreator.create();
}
createAndStartStateMachine();
window->show();
auto resultCode = application.exec();
unsubscribeLabelChanges();
return resultCode;
}
void Application::setupCommandLineParser()
{
QGuiApplication::setApplicationName("voly-labeller");
QGuiApplication::setApplicationVersion("0.1");
parser.setApplicationDescription(
"Multiple labelling implementations for volume rendered medical data");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument(
"scene", QCoreApplication::translate("main", "Scene file to load."));
QCommandLineOption offlineRenderingOption("offline",
"Enables offline rendering");
parser.addOption(offlineRenderingOption);
QCommandLineOption layersOption("layers", "Number of layers. Default is 4",
"layerCount", "4");
parser.addOption(layersOption);
QCommandLineOption hardConstraintsOption("hard-constraints",
"Simulate hard constraints");
parser.addOption(hardConstraintsOption);
QCommandLineOption apolloniusOption(
"apollonius", "Use apollonius graph to determine label insertion order");
parser.addOption(apolloniusOption);
QCommandLineOption disableLabellingOption("disable-labelling",
"Disable drawing lables");
parser.addOption(disableLabellingOption);
parser.addOption({ "internal-labelling", "Enable internal labelling" });
QCommandLineOption optimizeOnIdleOption(
"optimize-on-idle", "Optimize costs when the camera is not moving");
parser.addOption(optimizeOnIdleOption);
QCommandLineOption screenshotOption(
QStringList() << "s"
<< "screenshot",
"Takes a screenshot of the given camera position. Characters after a '_' "
"are ignored but added to the filename",
"Camera Position");
parser.addOption(screenshotOption);
}
void Application::setupWindow()
{
window->setResizeMode(QQuickView::SizeRootObjectToView);
auto context = window->rootContext();
auto assetsPath =
QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString("assets")));
context->setContextProperty("assetsPath", assetsPath);
auto projectRootPath =
QUrl::fromLocalFile(absolutePathOfProjectRelativePath(QString(".")));
context->setContextProperty("projectRootPath", projectRootPath);
context->setContextProperty("window", window.get());
context->setContextProperty("nodes", nodesController.get());
context->setContextProperty("bufferTextures",
textureMapperManagerController.get());
context->setContextProperty("scene", sceneController.get());
context->setContextProperty("labeller", labellerModel.get());
context->setContextProperty("placement", placementLabellerModel.get());
context->setContextProperty("cameraPositions", cameraPositionsModel.get());
context->setContextProperty("labels", labelsModel.get());
context->setContextProperty("labelling", labellingController.get());
context->setContextProperty("videoRecorder", videoRecorderController.get());
context->setContextProperty("automation",
recordingAutomationController.get());
}
void Application::createAndStartStateMachine()
{
auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
invokeManager, signalManager);
invokeManager->addHandler(window.get());
invokeManager->addHandler("mouseShape", mouseShapeController.get());
invokeManager->addHandler("picking", pickingController.get());
invokeManager->addHandler("scene", sceneController.get());
signalManager->addSender("KeyboardEventSender", window.get());
signalManager->addSender("window", window.get());
signalManager->addSender("labels", labelsModel.get());
stateMachine = importer.import();
// just for printCurrentState slot for debugging
window->stateMachine = stateMachine;
stateMachine->start();
}
void Application::onNodeAdded(std::shared_ptr<Node> node)
{
std::shared_ptr<LabelNode> labelNode =
std::dynamic_pointer_cast<LabelNode>(node);
if (labelNode.get())
{
labelNode->anchorSize = nodesController->getAnchorSize();
labels->add(labelNode->label);
}
std::shared_ptr<CameraNode> cameraNode =
std::dynamic_pointer_cast<CameraNode>(node);
if (cameraNode.get())
{
cameraNode->setOnCameraPositionsChanged(
[this](std::vector<CameraPosition> cameraPositions) {
this->cameraPositionsModel->update(cameraPositions);
});
}
}
void Application::onLabelChangedUpdateLabelNodes(Labels::Action action,
const Label &label)
{
auto labelNodes = nodes->getLabelNodes();
auto labelNode = std::find_if(labelNodes.begin(), labelNodes.end(),
[label](std::shared_ptr<LabelNode> labelNode) {
return labelNode->label.id == label.id;
});
if (labelNode == labelNodes.end())
{
nodes->addNode(std::make_shared<LabelNode>(label));
}
else if (action == Labels::Action::Delete)
{
nodes->removeNode(*labelNode);
}
else
{
(*labelNode)->label = label;
}
};
void Application::onFocesLabellerModelIsVisibleChanged()
{
if (labellerModel->getIsVisible())
{
nodes->addForcesVisualizerNode(
std::make_shared<ForcesVisualizerNode>(forcesLabeller));
}
else
{
nodes->removeForcesVisualizerNode();
}
}
int Application::parseLayerCount()
{
int layerCount = 4;
if (parser.isSet("layers"))
{
bool gotLayerCount = true;
layerCount = parser.value("layers").toInt(&gotLayerCount);
if (!gotLayerCount)
{
layerCount = 4;
qWarning() << "Problem parsing layer count from"
<< parser.value("layers");
}
if (layerCount < 1 || layerCount > 6)
qFatal("Layer count must be between 1 and 6");
}
return layerCount;
}
void Application::onInitializationDone()
{
if (parser.isSet("hard-constraints"))
placementLabellerModel->simulateHardConstraints();
if (parser.isSet("apollonius"))
labellingController->toggleApollonius();
if (parser.isSet("disable-labelling"))
scene->enableLabelling(false);
if (parser.isSet("optimize-on-idle"))
labellingController->toggleOptimizeOnIdle();
}
<|endoftext|>
|
<commit_before>#include "application.h"
#include <QtQml>
#include <QScreen>
#include <QKeyEvent>
#include <QQuickView>
#include <QStandardPaths>
#include <QDebug>
#include <QDir>
#include "imageprovider.h"
#include "models/albumlistmodel.h"
#include "models/albumbrowsemodel.h"
#include "quick/enums.h"
#include "quick/models.h"
#include "quick/quicktrackinfo.h"
#include "quick/quicksearch.h"
#include "quick/quickmosaicgenerator.h"
#include "../appkey.c"
namespace sp = Spotinetta;
namespace Sonetta {
namespace {
void deleteAudioOutputLater(AudioOutput * output) { output->deleteLater(); }
void deleteSettingsLater(Settings * settings) { settings->deleteLater(); }
}
Application::Application(int &argc, char **argv)
: QGuiApplication(argc, argv), m_view(new QQuickView), m_nav(new Navigation(this)),
m_output(new AudioOutput, deleteAudioOutputLater), m_settings(new Settings, deleteSettingsLater), m_exiting(false)
{
QGuiApplication::addLibraryPath(applicationDirPath() + QStringLiteral("/plugins"));
createSession();
m_player = new Player(m_session, m_output.data(), this);
m_ui = new UIStateCoordinator(this);
m_search = new SearchEngine(m_session, m_settings, this);
connect(m_session, &sp::Session::loggedOut, this, &Application::onLogout);
connect(m_session, &sp::Session::log, [] (const QString &msg) { qDebug() << msg; });
connect(m_settings.data(), &Settings::mouseEnabledChanged, this, &Application::updateCursor);
}
int Application::run()
{
registerQmlTypes();
if (m_session->error() == sp::Error::Ok)
{
setupQuickEnvironment();
showUi();
// Start event loop
return exec();
}
else
{
const QByteArray msg = QByteArray("Session creation failed. Error: ") + sp::errorMessage(m_session->error()).toUtf8();
qFatal(msg.constData());
return 1;
}
}
void Application::onExit()
{
m_exiting = true;
m_session->logout();
}
void Application::onLogout()
{
if (m_exiting)
{
quit();
}
}
void Application::updateCursor()
{
if (m_view.isNull())
return;
if (m_settings->mouseEnabled())
{
m_view->unsetCursor();
}
else
{
m_view->setCursor(QCursor(Qt::BlankCursor));
}
}
Application * Application::instance()
{
QCoreApplication * inst = QCoreApplication::instance();
return inst == nullptr ? nullptr : static_cast<Application *>(inst);
}
sp::Session * Application::session() const
{
return m_session;
}
bool Application::notify(QObject *receiver, QEvent *event)
{
switch (event->type())
{
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
if (!m_settings->mouseEnabled())
break;
case QEvent::KeyPress:
{
QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
// Ignore Alt + Enter
if (!(keyEvent->key() == Qt::Key_Return && keyEvent->modifiers() & Qt::AltModifier))
{
if (Navigation::dispatchKeyEvent(keyEvent))
return true;
}
}
break;
default:
return QGuiApplication::notify(receiver, event);
}
return true;
}
void Application::registerQmlTypes()
{
qmlRegisterType<Navigation>("Sonetta", 0, 1, "Navigation");
qmlRegisterType<NavigationAttached>();
qmlRegisterUncreatableType<QuickNavEvent>("Sonetta", 0, 1, "NavEvent", "Cannot instantiate navigation event. ");
qmlRegisterType<QuickPlaylistContainerModel>("Sonetta", 0, 1, "PlaylistContainerModel");
qmlRegisterType<QuickPlaylistModel>("Sonetta", 0, 1, "PlaylistModel");
qmlRegisterType<QuickTrackInfo>("Sonetta", 0, 1, "TrackInfo");
qmlRegisterType<QuickSearch>("Sonetta", 0, 1, "SearchEngine");
qmlRegisterType<QuickMosaicGenerator>("Sonetta", 0, 1, "MosaicGenerator");
qmlRegisterUncreatableType<Spotinetta::Session>("Sonetta", 0, 1, "Session", "Cannot instantiate Session.");
// Enums
qmlRegisterUncreatableType<AlbumEnums>("Sonetta", 0, 1, "Album", "Cannot instantiate Album.");
qmlRegisterUncreatableType<TrackEnums>("Sonetta", 0, 1, "Track", "Cannot instantiate Track.");
}
void Application::setupQuickEnvironment()
{
connect(m_view->engine(), &QQmlEngine::quit, this, &Application::onExit);
QString applicationDir = applicationDirPath();
ImageProvider * provider = new ImageProvider(m_session, m_view.data());
m_view->engine()->addImageProvider(QLatin1String("sp"), provider);
m_view->engine()->addImportPath(applicationDir + QStringLiteral("/quick"));
m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/quick"));
m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/plugins"));
m_view->engine()->rootContext()->setContextProperty("player", m_player);
m_view->engine()->rootContext()->setContextProperty("ui", m_ui);
m_view->engine()->rootContext()->setContextProperty("session", m_session);
m_view->engine()->rootContext()->setContextProperty("search", m_search);
m_view->engine()->addImportPath(applicationDir + QStringLiteral("/qml/modules"));
m_view->setSource(QUrl::fromLocalFile(applicationDir + QStringLiteral("/qml/rework2/main.qml")));
m_view->setResizeMode(QQuickView::SizeRootObjectToView);
}
void Application::showUi()
{
updateCursor();
// Center view
QScreen * screen = m_view->screen();
QPoint screenCenter = screen->availableGeometry().center();
QPoint windowCenter = m_view->geometry().center();
m_view->setPosition(screenCenter - windowCenter);
m_view->showFullScreen();
}
void Application::createSession()
{
sp::SessionConfig config;
config.applicationKey = sp::ApplicationKey(g_appkey, g_appkey_size);
config.userAgent = "Sonetta";
config.audioOutput = m_output;
config.settingsLocation = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/libspotify";
config.cacheLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/libspotify";
// Create directories if they don't exist
QDir dir;
dir.mkpath(config.settingsLocation);
dir.mkpath(config.cacheLocation);
m_session = new sp::Session(config, this);
}
}
<commit_msg>Fixed: Application did not exit upon exit() signal when user was not logged in<commit_after>#include "application.h"
#include <QtQml>
#include <QScreen>
#include <QKeyEvent>
#include <QQuickView>
#include <QStandardPaths>
#include <QDebug>
#include <QDir>
#include "imageprovider.h"
#include "models/albumlistmodel.h"
#include "models/albumbrowsemodel.h"
#include "quick/enums.h"
#include "quick/models.h"
#include "quick/quicktrackinfo.h"
#include "quick/quicksearch.h"
#include "quick/quickmosaicgenerator.h"
#include "../appkey.c"
namespace sp = Spotinetta;
namespace Sonetta {
namespace {
void deleteAudioOutputLater(AudioOutput * output) { output->deleteLater(); }
void deleteSettingsLater(Settings * settings) { settings->deleteLater(); }
}
Application::Application(int &argc, char **argv)
: QGuiApplication(argc, argv), m_view(new QQuickView), m_nav(new Navigation(this)),
m_output(new AudioOutput, deleteAudioOutputLater), m_settings(new Settings, deleteSettingsLater), m_exiting(false)
{
QGuiApplication::addLibraryPath(applicationDirPath() + QStringLiteral("/plugins"));
createSession();
m_player = new Player(m_session, m_output.data(), this);
m_ui = new UIStateCoordinator(this);
m_search = new SearchEngine(m_session, m_settings, this);
connect(m_session, &sp::Session::loggedOut, this, &Application::onLogout);
connect(m_session, &sp::Session::log, [] (const QString &msg) { qDebug() << msg; });
connect(m_settings.data(), &Settings::mouseEnabledChanged, this, &Application::updateCursor);
}
int Application::run()
{
registerQmlTypes();
if (m_session->error() == sp::Error::Ok)
{
setupQuickEnvironment();
showUi();
// Start event loop
return exec();
}
else
{
const QByteArray msg = QByteArray("Session creation failed. Error: ") + sp::errorMessage(m_session->error()).toUtf8();
qFatal(msg.constData());
return 1;
}
}
void Application::onExit()
{
m_exiting = true;
if (m_session->connectionState() == sp::Session::ConnectionState::LoggedIn
|| m_session->connectionState() == sp::Session::ConnectionState::Offline)
{
m_session->logout();
}
else
{
// Skip session logout
onLogout();
}
}
void Application::onLogout()
{
if (m_exiting)
{
quit();
}
}
void Application::updateCursor()
{
if (m_view.isNull())
return;
if (m_settings->mouseEnabled())
{
m_view->unsetCursor();
}
else
{
m_view->setCursor(QCursor(Qt::BlankCursor));
}
}
Application * Application::instance()
{
QCoreApplication * inst = QCoreApplication::instance();
return inst == nullptr ? nullptr : static_cast<Application *>(inst);
}
sp::Session * Application::session() const
{
return m_session;
}
bool Application::notify(QObject *receiver, QEvent *event)
{
switch (event->type())
{
case QEvent::MouseButtonDblClick:
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
if (!m_settings->mouseEnabled())
break;
case QEvent::KeyPress:
{
QKeyEvent * keyEvent = static_cast<QKeyEvent *>(event);
// Ignore Alt + Enter
if (!(keyEvent->key() == Qt::Key_Return && keyEvent->modifiers() & Qt::AltModifier))
{
if (Navigation::dispatchKeyEvent(keyEvent))
return true;
}
}
break;
default:
return QGuiApplication::notify(receiver, event);
}
return true;
}
void Application::registerQmlTypes()
{
qmlRegisterType<Navigation>("Sonetta", 0, 1, "Navigation");
qmlRegisterType<NavigationAttached>();
qmlRegisterUncreatableType<QuickNavEvent>("Sonetta", 0, 1, "NavEvent", "Cannot instantiate navigation event. ");
qmlRegisterType<QuickPlaylistContainerModel>("Sonetta", 0, 1, "PlaylistContainerModel");
qmlRegisterType<QuickPlaylistModel>("Sonetta", 0, 1, "PlaylistModel");
qmlRegisterType<QuickTrackInfo>("Sonetta", 0, 1, "TrackInfo");
qmlRegisterType<QuickSearch>("Sonetta", 0, 1, "SearchEngine");
qmlRegisterType<QuickMosaicGenerator>("Sonetta", 0, 1, "MosaicGenerator");
qmlRegisterUncreatableType<Spotinetta::Session>("Sonetta", 0, 1, "Session", "Cannot instantiate Session.");
// Enums
qmlRegisterUncreatableType<AlbumEnums>("Sonetta", 0, 1, "Album", "Cannot instantiate Album.");
qmlRegisterUncreatableType<TrackEnums>("Sonetta", 0, 1, "Track", "Cannot instantiate Track.");
}
void Application::setupQuickEnvironment()
{
connect(m_view->engine(), &QQmlEngine::quit, this, &Application::onExit);
QString applicationDir = applicationDirPath();
ImageProvider * provider = new ImageProvider(m_session, m_view.data());
m_view->engine()->addImageProvider(QLatin1String("sp"), provider);
m_view->engine()->addImportPath(applicationDir + QStringLiteral("/quick"));
m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/quick"));
m_view->engine()->addPluginPath(applicationDir + QStringLiteral("/plugins"));
m_view->engine()->rootContext()->setContextProperty("player", m_player);
m_view->engine()->rootContext()->setContextProperty("ui", m_ui);
m_view->engine()->rootContext()->setContextProperty("session", m_session);
m_view->engine()->rootContext()->setContextProperty("search", m_search);
m_view->engine()->addImportPath(applicationDir + QStringLiteral("/qml/modules"));
m_view->setSource(QUrl::fromLocalFile(applicationDir + QStringLiteral("/qml/rework2/main.qml")));
m_view->setResizeMode(QQuickView::SizeRootObjectToView);
}
void Application::showUi()
{
updateCursor();
// Center view
QScreen * screen = m_view->screen();
QPoint screenCenter = screen->availableGeometry().center();
QPoint windowCenter = m_view->geometry().center();
m_view->setPosition(screenCenter - windowCenter);
m_view->showFullScreen();
}
void Application::createSession()
{
sp::SessionConfig config;
config.applicationKey = sp::ApplicationKey(g_appkey, g_appkey_size);
config.userAgent = "Sonetta";
config.audioOutput = m_output;
config.settingsLocation = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/libspotify";
config.cacheLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation) + "/libspotify";
// Create directories if they don't exist
QDir dir;
dir.mkpath(config.settingsLocation);
dir.mkpath(config.cacheLocation);
m_session = new sp::Session(config, this);
}
}
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Open the mesh named in command line arguments,
// apply the named tests on every boundary side and normal vector,
// and give the specified boundary condition id to each side
// that passes the tests.
#include <limits>
#include <string>
#include "libmesh/libmesh.h"
#include "libmesh/boundary_info.h"
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/getpot.h"
#include "libmesh/mesh.h"
#include "libmesh/point.h"
#include "libmesh/quadrature_gauss.h"
using namespace libMesh;
void usage_error(const char * progname)
{
libMesh::out << "Usage: " << progname
<< " --dim d --input inputmesh --output outputmesh --newbcid idnum --tests --moretests"
<< std::endl;
exit(1);
}
int main(int argc, char ** argv)
{
LibMeshInit init(argc, argv);
GetPot cl(argc, argv);
unsigned char dim = -1;
if (!cl.search("--dim"))
{
libMesh::err << "No --dim argument found!" << std::endl;
usage_error(argv[0]);
}
dim = cl.next(dim);
Mesh mesh(init.comm(), dim);
if (!cl.search("--input"))
{
libMesh::err << "No --input argument found!" << std::endl;
usage_error(argv[0]);
}
const char * meshname = cl.next("mesh.xda");
mesh.read(meshname);
libMesh::out << "Loaded mesh " << meshname << std::endl;
if (!cl.search("--newbcid"))
{
libMesh::err << "No --bcid argument found!" << std::endl;
usage_error(argv[0]);
}
boundary_id_type bcid = 0;
bcid = cl.next(bcid);
Point minnormal(-std::numeric_limits<Real>::max(),
-std::numeric_limits<Real>::max(),
-std::numeric_limits<Real>::max());
Point maxnormal(std::numeric_limits<Real>::max(),
std::numeric_limits<Real>::max(),
std::numeric_limits<Real>::max());
Point minpoint(-std::numeric_limits<Real>::max(),
-std::numeric_limits<Real>::max(),
-std::numeric_limits<Real>::max());
Point maxpoint(std::numeric_limits<Real>::max(),
std::numeric_limits<Real>::max(),
std::numeric_limits<Real>::max());
if (cl.search("--minnormalx"))
minnormal(0) = cl.next(minnormal(0));
if (cl.search("--minnormalx"))
minnormal(0) = cl.next(minnormal(0));
if (cl.search("--maxnormalx"))
maxnormal(0) = cl.next(maxnormal(0));
if (cl.search("--minnormaly"))
minnormal(1) = cl.next(minnormal(1));
if (cl.search("--maxnormaly"))
maxnormal(1) = cl.next(maxnormal(1));
if (cl.search("--minnormalz"))
minnormal(2) = cl.next(minnormal(2));
if (cl.search("--maxnormalz"))
maxnormal(2) = cl.next(maxnormal(2));
if (cl.search("--minpointx"))
minpoint(0) = cl.next(minpoint(0));
if (cl.search("--maxpointx"))
maxpoint(0) = cl.next(maxpoint(0));
if (cl.search("--minpointy"))
minpoint(1) = cl.next(minpoint(1));
if (cl.search("--maxpointy"))
maxpoint(1) = cl.next(maxpoint(1));
if (cl.search("--minpointz"))
minpoint(2) = cl.next(minpoint(2));
if (cl.search("--maxpointz"))
maxpoint(2) = cl.next(maxpoint(2));
libMesh::out << "min point = " << minpoint << std::endl;
libMesh::out << "max point = " << maxpoint << std::endl;
libMesh::out << "min normal = " << minnormal << std::endl;
libMesh::out << "max normal = " << maxnormal << std::endl;
bool matcholdbcid = false;
boundary_id_type oldbcid = 0;
if (cl.search("--oldbcid"))
{
matcholdbcid = true;
oldbcid = cl.next(oldbcid);
if (oldbcid < 0)
oldbcid = BoundaryInfo::invalid_id;
}
std::unique_ptr<FEBase> fe = FEBase::build(dim, FEType(FIRST,LAGRANGE));
QGauss qface(dim-1, CONSTANT);
fe->attach_quadrature_rule(&qface);
const std::vector<Point> & face_points = fe->get_xyz();
const std::vector<Point> & face_normals = fe->get_normals();
for (auto & elem : mesh.element_ptr_range())
{
unsigned int n_sides = elem->n_sides();
// Container to catch ids handed back from BoundaryInfo
std::vector<boundary_id_type> ids;
for (unsigned short s=0; s != n_sides; ++s)
{
if (elem->neighbor_ptr(s))
continue;
fe->reinit(elem,s);
const Point & p = face_points[0];
const Point & n = face_normals[0];
//libMesh::out << "elem = " << elem->id() << std::endl;
//libMesh::out << "centroid = " << elem->centroid() << std::endl;
//libMesh::out << "p = " << p << std::endl;
//libMesh::out << "n = " << n << std::endl;
if (p(0) > minpoint(0) && p(0) < maxpoint(0) &&
p(1) > minpoint(1) && p(1) < maxpoint(1) &&
p(2) > minpoint(2) && p(2) < maxpoint(2) &&
n(0) > minnormal(0) && n(0) < maxnormal(0) &&
n(1) > minnormal(1) && n(1) < maxnormal(1) &&
n(2) > minnormal(2) && n(2) < maxnormal(2))
{
// Get the list of boundary ids for this side
mesh.get_boundary_info().boundary_ids(elem, s, ids);
// There should be at most one value present, otherwise the
// logic here won't work.
libmesh_assert(ids.size() <= 1);
// A convenient name for the side's ID.
boundary_id_type b_id = ids.empty() ? BoundaryInfo::invalid_id : ids[0];
if (matcholdbcid && b_id != oldbcid)
continue;
mesh.get_boundary_info().remove_side(elem, s);
mesh.get_boundary_info().add_side(elem, s, bcid);
//libMesh::out << "Set element " << elem->id() << " side " << s <<
// " to boundary " << bcid << std::endl;
}
}
}
// We might have removed *every* instance of a given id, and if that
// happened then we should make sure that file formats which write
// out id sets do not write out the removed id.
mesh.get_boundary_info().regenerate_id_sets();
std::string outputname;
if (cl.search("--output"))
{
outputname = cl.next("mesh.xda");
}
else
{
outputname = "new.";
outputname += meshname;
}
mesh.write(outputname.c_str());
libMesh::out << "Wrote mesh " << outputname << std::endl;
return 0;
}
<commit_msg>Use BoundingBox in meshbcid app<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2019 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Open the mesh named in command line arguments,
// apply the named tests on every boundary side and normal vector,
// and give the specified boundary condition id to each side
// that passes the tests.
#include <limits>
#include <string>
#include "libmesh/libmesh.h"
#include "libmesh/boundary_info.h"
#include "libmesh/bounding_box.h"
#include "libmesh/elem.h"
#include "libmesh/fe.h"
#include "libmesh/getpot.h"
#include "libmesh/mesh.h"
#include "libmesh/point.h"
#include "libmesh/quadrature_gauss.h"
using namespace libMesh;
void usage_error(const char * progname)
{
libMesh::out << "Usage: " << progname
<< " --dim d --input inputmesh --output outputmesh --newbcid idnum --tests --moretests"
<< std::endl;
exit(1);
}
int main(int argc, char ** argv)
{
LibMeshInit init(argc, argv);
GetPot cl(argc, argv);
unsigned char dim = -1;
if (!cl.search("--dim"))
{
libMesh::err << "No --dim argument found!" << std::endl;
usage_error(argv[0]);
}
dim = cl.next(dim);
Mesh mesh(init.comm(), dim);
if (!cl.search("--input"))
{
libMesh::err << "No --input argument found!" << std::endl;
usage_error(argv[0]);
}
const char * meshname = cl.next("mesh.xda");
mesh.read(meshname);
libMesh::out << "Loaded mesh " << meshname << std::endl;
if (!cl.search("--newbcid"))
{
libMesh::err << "No --bcid argument found!" << std::endl;
usage_error(argv[0]);
}
boundary_id_type bcid = 0;
bcid = cl.next(bcid);
Point minpt(-std::numeric_limits<Real>::max());
#if LIBMESH_DIM > 1
minpt(1) = -std::numeric_limits<Real>::max();
#endif
#if LIBMESH_DIM > 2
minpt(2) = -std::numeric_limits<Real>::max();
#endif
Point maxpt = -minpt;
BoundingBox normals(minpt, maxpt),
points(minpt, maxpt);
if (cl.search("--minnormalx"))
normals.min()(0) = cl.next(normals.min()(0));
if (cl.search("--maxnormalx"))
normals.max()(0) = cl.next(normals.max()(0));
if (cl.search("--minpointx"))
points.min()(0) = cl.next(points.min()(0));
if (cl.search("--maxpointx"))
points.max()(0) = cl.next(points.max()(0));
#if LIBMESH_DIM > 1
if (cl.search("--minnormaly"))
normals.min()(1) = cl.next(normals.min()(1));
if (cl.search("--maxnormaly"))
normals.max()(1) = cl.next(normals.max()(1));
if (cl.search("--minpointy"))
points.min()(1) = cl.next(points.min()(1));
if (cl.search("--maxpointy"))
points.max()(1) = cl.next(points.max()(1));
#endif
#if LIBMESH_DIM > 2
if (cl.search("--minnormalz"))
normals.min()(2) = cl.next(normals.min()(2));
if (cl.search("--maxnormalz"))
normals.max()(2) = cl.next(normals.max()(2));
if (cl.search("--minpointz"))
points.min()(2) = cl.next(points.min()(2));
if (cl.search("--maxpointz"))
points.max()(2) = cl.next(points.max()(2));
#endif
libMesh::out << "min point = " << points.min() << std::endl;
libMesh::out << "max point = " << points.max() << std::endl;
libMesh::out << "min normal = " << normals.min() << std::endl;
libMesh::out << "max normal = " << normals.max() << std::endl;
bool matcholdbcid = false;
boundary_id_type oldbcid = 0;
if (cl.search("--oldbcid"))
{
matcholdbcid = true;
oldbcid = cl.next(oldbcid);
if (oldbcid < 0)
oldbcid = BoundaryInfo::invalid_id;
}
std::unique_ptr<FEBase> fe = FEBase::build(dim, FEType(FIRST,LAGRANGE));
QGauss qface(dim-1, CONSTANT);
fe->attach_quadrature_rule(&qface);
const std::vector<Point> & face_points = fe->get_xyz();
const std::vector<Point> & face_normals = fe->get_normals();
for (auto & elem : mesh.element_ptr_range())
{
unsigned int n_sides = elem->n_sides();
// Container to catch ids handed back from BoundaryInfo
std::vector<boundary_id_type> ids;
for (unsigned short s=0; s != n_sides; ++s)
{
if (elem->neighbor_ptr(s))
continue;
fe->reinit(elem,s);
const Point & p = face_points[0];
const Point & n = face_normals[0];
//libMesh::out << "elem = " << elem->id() << std::endl;
//libMesh::out << "centroid = " << elem->centroid() << std::endl;
//libMesh::out << "p = " << p << std::endl;
//libMesh::out << "n = " << n << std::endl;
if (points.contains_point(p) &&
normals.contains_point(n))
{
// Get the list of boundary ids for this side
mesh.get_boundary_info().boundary_ids(elem, s, ids);
// There should be at most one value present, otherwise the
// logic here won't work.
libmesh_assert(ids.size() <= 1);
// A convenient name for the side's ID.
boundary_id_type b_id = ids.empty() ? BoundaryInfo::invalid_id : ids[0];
if (matcholdbcid && b_id != oldbcid)
continue;
mesh.get_boundary_info().remove_side(elem, s);
mesh.get_boundary_info().add_side(elem, s, bcid);
//libMesh::out << "Set element " << elem->id() << " side " << s <<
// " to boundary " << bcid << std::endl;
}
}
}
// We might have removed *every* instance of a given id, and if that
// happened then we should make sure that file formats which write
// out id sets do not write out the removed id.
mesh.get_boundary_info().regenerate_id_sets();
std::string outputname;
if (cl.search("--output"))
{
outputname = cl.next("mesh.xda");
}
else
{
outputname = "new.";
outputname += meshname;
}
mesh.write(outputname.c_str());
libMesh::out << "Wrote mesh " << outputname << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "ROOT/TDataFrame.hxx"
#include "ROOT/TSeq.hxx"
#include "ROOT/TTrivialDS.hxx"
#include "TH1F.h"
#include "TRandom.h"
#include "TSystem.h"
#include "TNonCopiableDS.hxx"
#include "gtest/gtest.h"
#include <algorithm>
using namespace ROOT::Experimental;
using namespace ROOT::Experimental::TDF;
TEST(Cache, FundType)
{
TDataFrame tdf(5);
int i = 1;
auto cached =
tdf.Define("c0", [&i]() { return i++; }).Define("c1", []() { return 1.; }).Cache<int, double>({"c0", "c1"});
auto c = cached.Count();
auto m = cached.Min<int>("c0");
auto v = *cached.Take<int>("c0");
EXPECT_EQ(1, *m);
EXPECT_EQ(5UL, *c);
for (auto j : ROOT::TSeqI(5)) {
EXPECT_EQ(j + 1, v[j]);
}
}
TEST(Cache, Contiguity)
{
TDataFrame tdf(2);
auto f = 0.f;
auto cached = tdf.Define("float", [&f]() { return f++; }).Cache<float>({"float"});
int counter = 0;
float *fPrec = nullptr;
auto count = [&counter, &fPrec](float &ff) {
if (1 == counter++) {
EXPECT_EQ(1U, std::distance(fPrec, &ff));
}
fPrec = &ff;
};
cached.Foreach(count, {"float"});
}
TEST(Cache, Class)
{
TH1F h("", "h", 64, 0, 1);
gRandom->SetSeed(1);
h.FillRandom("gaus", 10);
TDataFrame tdf(1);
auto cached = tdf.Define("c0", [&h]() { return h; }).Cache<TH1F>({"c0"});
auto c = cached.Count();
auto d = cached.Define("Mean", [](TH1F &hh) { return hh.GetMean(); }, {"c0"})
.Define("StdDev", [](TH1F &hh) { return hh.GetStdDev(); }, {"c0"});
auto m = d.Max<double>("Mean");
auto s = d.Max<double>("StdDev");
EXPECT_EQ(h.GetMean(), *m);
EXPECT_EQ(h.GetStdDev(), *s);
EXPECT_EQ(1UL, *c);
}
TEST(Cache, RunTwiceOnCached)
{
auto nevts = 10U;
TDataFrame tdf(nevts);
auto f = 0.f;
auto nCalls = 0U;
auto orig = tdf.Define("float", [&f, &nCalls]() {
nCalls++;
return f++;
});
auto cached = orig.Cache<float>({"float"});
EXPECT_EQ(nevts, nCalls);
auto m0 = cached.Mean<float>("float");
EXPECT_EQ(nevts, nCalls);
cached.Foreach([]() {}); // run the event loop
auto m1 = cached.Mean<float>("float"); // re-run the event loop
EXPECT_EQ(nevts, nCalls);
EXPECT_EQ(*m0, *m1);
}
// Broken - caching a cached tdf destroys the cache of the cached.
TEST(Cache, CacheFromCache)
{
auto nevts = 10U;
TDataFrame tdf(nevts);
auto f = 0.f;
auto orig = tdf.Define("float", [&f]() { return f++; });
auto cached = orig.Cache<float>({"float"});
f = 0.f;
auto recached = cached.Cache<float>({"float"});
auto ofloat = *orig.Take<float>("float");
auto cfloat = *cached.Take<float>("float");
auto rcfloat = *recached.Take<float>("float");
for (auto j : ROOT::TSeqU(nevts)) {
EXPECT_EQ(ofloat[j], cfloat[j]);
EXPECT_EQ(ofloat[j], rcfloat[j]);
}
}
TEST(Cache, InternalColumnsSnapshot)
{
TDataFrame tdf(2);
auto f = 0.f;
auto colName = "__TDF_MySecretCol_";
auto orig = tdf.Define(colName, [&f]() { return f++; });
auto cached = orig.Cache<float>({colName});
auto snapshot = cached.Snapshot("t", "InternalColumnsSnapshot.root", "", {"RECREATE", ROOT::kZLIB, 0, 0, 99});
int ret(1);
try {
testing::internal::CaptureStderr();
snapshot.Mean<ULong64_t>(colName);
} catch (const std::runtime_error &e) {
ret = 0;
}
EXPECT_EQ(0, ret) << "Internal column " << colName << " has been snapshotted!";
}
TEST(Cache, CollectionColumns)
{
TDataFrame tdf(3);
int i = 0;
auto d = tdf.Define("vector",
[&i]() {
std::vector<int> v(3);
v[0] = i;
v[1] = i + 1;
v[2] = i + 2;
return v;
})
.Define("list",
[&i]() {
std::list<int> v;
for (auto j : {0, 1, 2})
v.emplace_back(j + i);
return v;
})
.Define("deque",
[&i]() {
std::deque<int> v(3);
v[0] = i;
v[1] = i + 1;
v[2] = i + 2;
return v;
})
.Define("blob", [&i]() { return ++i; });
{
auto c = d.Cache<std::vector<int>, std::list<int>, std::deque<int>>({"vector", "list", "deque"});
auto hv = c.Histo1D("vector");
auto hl = c.Histo1D("list");
auto hd = c.Histo1D("deque");
EXPECT_EQ(1, hv->GetMean());
EXPECT_EQ(1, hl->GetMean());
EXPECT_EQ(1, hd->GetMean());
}
// same but jitted
auto c = d.Cache({"vector", "list", "deque"});
auto hv = c.Histo1D("vector");
auto hl = c.Histo1D("list");
auto hd = c.Histo1D("deque");
EXPECT_EQ(1, hv->GetMean());
EXPECT_EQ(1, hl->GetMean());
EXPECT_EQ(1, hd->GetMean());
}
TEST(Cache, Regex)
{
TDataFrame tdf(1);
auto d = tdf.Define("c0", []() { return 0; }).Define("c1", []() { return 1; }).Define("b0", []() { return 2; });
auto cachedAll = d.Cache();
auto cachedC = d.Cache("c[0,1].*");
auto sumAll = [](int c0, int c1, int b0) { return c0 + c1 + b0; };
auto mAll = cachedAll.Define("sum", sumAll, {"c0", "c1", "b0"}).Max<int>("sum");
EXPECT_EQ(3, *mAll);
auto sumC = [](int c0, int c1) { return c0 + c1; };
auto mC = cachedC.Define("sum", sumC, {"c0", "c1"}).Max<int>("sum");
EXPECT_EQ(1, *mC);
// Now from source
std::unique_ptr<TDataSource> tds(new TTrivialDS(4));
TDataFrame tdfs(std::move(tds));
auto cached = tdfs.Cache();
auto m = cached.Max<ULong64_t>("col0");
EXPECT_EQ(3UL, *m);
}
TEST(Cache, NonCopiable)
{
std::unique_ptr<TDataSource> tds(new NonCopiableDS());
TDataFrame tdf(std::move(tds));
int ret(1);
try {
tdf.Cache(NonCopiableDS::fgColumnName);
} catch (const std::runtime_error &e) {
ret = 0;
}
EXPECT_EQ(0, ret)
<< "The static assert was not triggered even if caching of columns of a non copiable type was requested";
}
TEST(Cache, Carrays)
{
auto treeName = "t";
auto fileName = "CacheCarrays.root";
{
TFile f(fileName, "RECREATE");
TTree t(treeName, treeName);
float arr[4];
t.Branch("arr", arr, "arr[4]/F");
for (auto i : ROOT::TSeqU(4)) {
for (auto j : ROOT::TSeqU(4)) {
arr[j] = i + j;
}
t.Fill();
}
t.Write();
}
TDataFrame tdf(treeName, fileName);
auto cache = tdf.Cache<std::array_view<float>>({"arr"});
int i = 0;
auto checkArr = [&i](std::vector<float> av) {
auto ifloat = float(i);
EXPECT_EQ(ifloat, av[0]);
EXPECT_EQ(ifloat + 1, av[1]);
EXPECT_EQ(ifloat + 2, av[2]);
EXPECT_EQ(ifloat + 3, av[3]);
i++;
};
cache.Foreach(checkArr, {"arr"});
// now jitted
auto cachej = tdf.Cache("arr");
i = 0;
cache.Foreach(checkArr, {"arr"});
gSystem->Unlink(fileName);
}
<commit_msg>[TDF] Avoid some jitting to save time in unit test<commit_after>#include "ROOT/TDataFrame.hxx"
#include "ROOT/TSeq.hxx"
#include "ROOT/TTrivialDS.hxx"
#include "TH1F.h"
#include "TRandom.h"
#include "TSystem.h"
#include "TNonCopiableDS.hxx"
#include "gtest/gtest.h"
#include <algorithm>
using namespace ROOT::Experimental;
using namespace ROOT::Experimental::TDF;
TEST(Cache, FundType)
{
TDataFrame tdf(5);
int i = 1;
auto cached =
tdf.Define("c0", [&i]() { return i++; }).Define("c1", []() { return 1.; }).Cache<int, double>({"c0", "c1"});
auto c = cached.Count();
auto m = cached.Min<int>("c0");
auto v = *cached.Take<int>("c0");
EXPECT_EQ(1, *m);
EXPECT_EQ(5UL, *c);
for (auto j : ROOT::TSeqI(5)) {
EXPECT_EQ(j + 1, v[j]);
}
}
TEST(Cache, Contiguity)
{
TDataFrame tdf(2);
auto f = 0.f;
auto cached = tdf.Define("float", [&f]() { return f++; }).Cache<float>({"float"});
int counter = 0;
float *fPrec = nullptr;
auto count = [&counter, &fPrec](float &ff) {
if (1 == counter++) {
EXPECT_EQ(1U, std::distance(fPrec, &ff));
}
fPrec = &ff;
};
cached.Foreach(count, {"float"});
}
TEST(Cache, Class)
{
TH1F h("", "h", 64, 0, 1);
gRandom->SetSeed(1);
h.FillRandom("gaus", 10);
TDataFrame tdf(1);
auto cached = tdf.Define("c0", [&h]() { return h; }).Cache<TH1F>({"c0"});
auto c = cached.Count();
auto d = cached.Define("Mean", [](TH1F &hh) { return hh.GetMean(); }, {"c0"})
.Define("StdDev", [](TH1F &hh) { return hh.GetStdDev(); }, {"c0"});
auto m = d.Max<double>("Mean");
auto s = d.Max<double>("StdDev");
EXPECT_EQ(h.GetMean(), *m);
EXPECT_EQ(h.GetStdDev(), *s);
EXPECT_EQ(1UL, *c);
}
TEST(Cache, RunTwiceOnCached)
{
auto nevts = 10U;
TDataFrame tdf(nevts);
auto f = 0.f;
auto nCalls = 0U;
auto orig = tdf.Define("float", [&f, &nCalls]() {
nCalls++;
return f++;
});
auto cached = orig.Cache<float>({"float"});
EXPECT_EQ(nevts, nCalls);
auto m0 = cached.Mean<float>("float");
EXPECT_EQ(nevts, nCalls);
cached.Foreach([]() {}); // run the event loop
auto m1 = cached.Mean<float>("float"); // re-run the event loop
EXPECT_EQ(nevts, nCalls);
EXPECT_EQ(*m0, *m1);
}
// Broken - caching a cached tdf destroys the cache of the cached.
TEST(Cache, CacheFromCache)
{
auto nevts = 10U;
TDataFrame tdf(nevts);
auto f = 0.f;
auto orig = tdf.Define("float", [&f]() { return f++; });
auto cached = orig.Cache<float>({"float"});
f = 0.f;
auto recached = cached.Cache<float>({"float"});
auto ofloat = *orig.Take<float>("float");
auto cfloat = *cached.Take<float>("float");
auto rcfloat = *recached.Take<float>("float");
for (auto j : ROOT::TSeqU(nevts)) {
EXPECT_EQ(ofloat[j], cfloat[j]);
EXPECT_EQ(ofloat[j], rcfloat[j]);
}
}
TEST(Cache, InternalColumnsSnapshot)
{
TDataFrame tdf(2);
auto f = 0.f;
auto colName = "__TDF_MySecretCol_";
auto orig = tdf.Define(colName, [&f]() { return f++; });
auto cached = orig.Cache<float>({colName});
auto snapshot = cached.Snapshot("t", "InternalColumnsSnapshot.root", "", {"RECREATE", ROOT::kZLIB, 0, 0, 99});
int ret(1);
try {
testing::internal::CaptureStderr();
snapshot.Mean<ULong64_t>(colName);
} catch (const std::runtime_error &e) {
ret = 0;
}
EXPECT_EQ(0, ret) << "Internal column " << colName << " has been snapshotted!";
}
TEST(Cache, CollectionColumns)
{
TDataFrame tdf(3);
int i = 0;
auto d = tdf.Define("vector",
[&i]() {
std::vector<int> v(3);
v[0] = i;
v[1] = i + 1;
v[2] = i + 2;
return v;
})
.Define("list",
[&i]() {
std::list<int> v;
for (auto j : {0, 1, 2})
v.emplace_back(j + i);
return v;
})
.Define("deque",
[&i]() {
std::deque<int> v(3);
v[0] = i;
v[1] = i + 1;
v[2] = i + 2;
return v;
})
.Define("blob", [&i]() { return ++i; });
{
auto c = d.Cache<std::vector<int>, std::list<int>, std::deque<int>>({"vector", "list", "deque"});
auto hv = c.Histo1D<std::vector<int>>("vector");
auto hl = c.Histo1D<std::list<int>>("list");
auto hd = c.Histo1D<std::deque<int>>("deque");
EXPECT_EQ(1, hv->GetMean());
EXPECT_EQ(1, hl->GetMean());
EXPECT_EQ(1, hd->GetMean());
}
// same but jitted
auto c = d.Cache({"vector", "list", "deque"});
auto hv = c.Histo1D("vector");
auto hl = c.Histo1D("list");
auto hd = c.Histo1D("deque");
EXPECT_EQ(1, hv->GetMean());
EXPECT_EQ(1, hl->GetMean());
EXPECT_EQ(1, hd->GetMean());
}
TEST(Cache, Regex)
{
TDataFrame tdf(1);
auto d = tdf.Define("c0", []() { return 0; }).Define("c1", []() { return 1; }).Define("b0", []() { return 2; });
auto cachedAll = d.Cache();
auto cachedC = d.Cache("c[0,1].*");
auto sumAll = [](int c0, int c1, int b0) { return c0 + c1 + b0; };
auto mAll = cachedAll.Define("sum", sumAll, {"c0", "c1", "b0"}).Max<int>("sum");
EXPECT_EQ(3, *mAll);
auto sumC = [](int c0, int c1) { return c0 + c1; };
auto mC = cachedC.Define("sum", sumC, {"c0", "c1"}).Max<int>("sum");
EXPECT_EQ(1, *mC);
// Now from source
std::unique_ptr<TDataSource> tds(new TTrivialDS(4));
TDataFrame tdfs(std::move(tds));
auto cached = tdfs.Cache();
auto m = cached.Max<ULong64_t>("col0");
EXPECT_EQ(3UL, *m);
}
TEST(Cache, NonCopiable)
{
std::unique_ptr<TDataSource> tds(new NonCopiableDS());
TDataFrame tdf(std::move(tds));
int ret(1);
try {
tdf.Cache(NonCopiableDS::fgColumnName);
} catch (const std::runtime_error &e) {
ret = 0;
}
EXPECT_EQ(0, ret)
<< "The static assert was not triggered even if caching of columns of a non copiable type was requested";
}
TEST(Cache, Carrays)
{
auto treeName = "t";
auto fileName = "CacheCarrays.root";
{
TFile f(fileName, "RECREATE");
TTree t(treeName, treeName);
float arr[4];
t.Branch("arr", arr, "arr[4]/F");
for (auto i : ROOT::TSeqU(4)) {
for (auto j : ROOT::TSeqU(4)) {
arr[j] = i + j;
}
t.Fill();
}
t.Write();
}
TDataFrame tdf(treeName, fileName);
auto cache = tdf.Cache<std::array_view<float>>({"arr"});
int i = 0;
auto checkArr = [&i](std::vector<float> av) {
auto ifloat = float(i);
EXPECT_EQ(ifloat, av[0]);
EXPECT_EQ(ifloat + 1, av[1]);
EXPECT_EQ(ifloat + 2, av[2]);
EXPECT_EQ(ifloat + 3, av[3]);
i++;
};
cache.Foreach(checkArr, {"arr"});
// now jitted
auto cachej = tdf.Cache("arr");
i = 0;
cache.Foreach(checkArr, {"arr"});
gSystem->Unlink(fileName);
}
<|endoftext|>
|
<commit_before>/*
:DV company (c) 1997-2016
*/
#include "../include/apps_starter.h"
#include "../include/isca_alpha.h"
#include "../include/desktop.h"
#include "../include/system_defines.h"
using namespace std;
int main(int argc, char *argv[]) {
setlocale(LC_ALL, "");
init_display();
init_color();
InitLOAD_T(loading_info); // ЧТО ЗДЕСЬ ТОБОЙ ДВИГАЛО???
string hos_ver = _HOS_VERSION;
add_to_load_screen(loading_info, 0, 0, "HOS version: " + hos_ver);
add_to_load_screen(loading_info, 0, 1, "WINDLG version: " + get_ver_windlg());
loading_title_start(&loading_info); // Вывод загрузочного экрана
init_signals();
apps_vect.clear();
usleep(2500000); // ВАЖНО!
kill_loading_title(); // Закрытие загрузочного экрана
if (!load_to_vector(MAIN_CONFIG, main_config_base)) { // АБСТРАКЦИИ, ПОЛИМОРФИЗМ, КОСВЕННЫЙ ДОСТУП... ЗААААЧЧЧЕЕЕЕМ?
DLGSTR failwin = {}; // Только так!!! ЭТО ФИЧА!
failwin.line = "Can't load main configuration file!!!";
failwin.style = RED_WIN;
msg_win(failwin);
endwin();
return 32;
}
get_normal_inv_color(conf("system_color", main_config_base), main_system_color, main_system_color_selection);
if (conf("alpha_warning_on_start", main_config_base) != "0") {
DLGSTR teststr = {}; // Только так!!!
teststr.title = "Pre pre pre ... Alpha"; // Aaa??
teststr.style = RED_WIN; // КРАСНЫЙ КАК КРОВЬ!!!
teststr.line = "Dear user, it's not full version of OS!/nThis is just an example of how might look this OS.";
msg_win(teststr);
}
if ((conf("start_boot_indexing", main_config_base) == "1") && (FileExists(MAIN_APPS_FILE))) {
if (!rm_file(MAIN_APPS_FILE)) {
DLGSTR failwin = {}; // Только так!!!
failwin.line = "Can't load main configuration file!!!";
failwin.style = RED_WIN;
msg_win(failwin); // ТЫ ЗАФЕЙЛИЛ, МУДИЛА
}
}
main_desktop("user_name"); // ВИНОВНИК ТОРЖЕСТВА
endwin(); // КОНЕЦ СТРАДАНИЯМ
return 0;
}
<commit_msg>Исправление запуска через make start<commit_after>/*
:DV company (c) 1997-2017
*/
#include "../include/apps_starter.h"
#include "../include/isca_alpha.h"
#include "../include/desktop.h"
#include "../include/system_defines.h"
using namespace std;
int start(int argc, char *argv[]) {
setlocale(LC_ALL, "");
init_display();
init_color();
InitLOAD_T(loading_info); // ЧТО ЗДЕСЬ ТОБОЙ ДВИГАЛО???
string hos_ver = _HOS_VERSION;
add_to_load_screen(loading_info, 0, 0, "HOS version: " + hos_ver);
add_to_load_screen(loading_info, 0, 1, "WINDLG version: " + get_ver_windlg());
loading_title_start(&loading_info); // Вывод загрузочного экрана
init_signals();
apps_vect.clear();
usleep(2500000); // ВАЖНО!
kill_loading_title(); // Закрытие загрузочного экрана
if (!load_to_vector(MAIN_CONFIG, main_config_base)) { // АБСТРАКЦИИ, ПОЛИМОРФИЗМ, КОСВЕННЫЙ ДОСТУП... ЗААААЧЧЧЕЕЕЕМ?
DLGSTR failwin = {}; // Только так!!! ЭТО ФИЧА!
failwin.line = "Can't load main configuration file!!!";
failwin.style = RED_WIN;
msg_win(failwin);
endwin();
return 32;
}
get_normal_inv_color(conf("system_color", main_config_base), main_system_color, main_system_color_selection);
if (conf("alpha_warning_on_start", main_config_base) != "0") {
DLGSTR teststr = {}; // Только так!!!
teststr.title = "Pre pre pre ... Alpha"; // Aaa??
teststr.style = RED_WIN; // КРАСНЫЙ КАК КРОВЬ!!!
teststr.line = "Dear user, it's not full version of OS!/nThis is just an example of how might look this OS.";
msg_win(teststr);
}
if ((conf("start_boot_indexing", main_config_base) == "1") && (FileExists(MAIN_APPS_FILE))) {
if (!rm_file(MAIN_APPS_FILE)) {
DLGSTR failwin = {}; // Только так!!!
failwin.line = "Can't load main configuration file!!!";
failwin.style = RED_WIN;
msg_win(failwin); // ТЫ ЗАФЕЙЛИЛ, МУДИЛА
}
}
add_to_filef("fail.log", "Start [ OK ]\n");
main_desktop("user_name"); // ВИНОВНИК ТОРЖЕСТВА
endwin(); // КОНЕЦ СТРАДАНИЯМ
return 0;
}
int main(int argc, char *argv[]) {
pid_t chpid = fork();
if (chpid == 0) {
signal(SIGTTIN, SIG_IGN);
signal(SIGTTOU, SIG_IGN);
tcsetpgrp(STDIN_FILENO, getpid());
// chdir(path_to_dir.c_str());
setpgid(getpid(), getpid()); // Создаём группу процессов
start(argc, argv); // Запуск оболочки
return 0;
} else {
waitpid(chpid, NULL, WUNTRACED);
}
return 0;
}<|endoftext|>
|
<commit_before>#include "taichi.h" // Note: You DO NOT have to install taichi or taichi_mpm.
using namespace taichi; // You only need [taichi.h] - see below for
// instructions.
const int n = 160 /*grid resolution (cells)*/, window_size = 800;
const real dt = 60e-4_f / n, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx;
auto particle_mass = 1.0_f, vol = 1.0_f;
auto hardening = 10.0_f, E = 1e4_f, nu = 0.2_f;
real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1 + nu) * (1 - 2 * nu));
using Vec = Vector2;
using Mat = Matrix2;
struct Particle {
Vec x, v;
Mat F, C;
real Jp;
int c /*color*/;
int type; // 0: elastic 1: plastic 2: liquid
Particle(Vec x, int c, int type, Vec v = Vec(0))
: x(x), v(v), F(1), C(0), Jp(1), c(c), type(type) {
}
};
std::vector<Particle> particles;
Vector3 grid[n + 1][n + 1]; // velocity + mass, node_res = cell_res + 1
void advance(real dt) {
std::memset(grid, 0, sizeof(grid)); // Reset grid
for (auto &p : particles) { // P2G
Vector2i base_coord =
(p.x * inv_dx - Vec(0.5_f)).cast<int>(); // element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast<real>();
// Quadratic kernels [http://mpm.graphics Eqn. 123, with x=fx, fx-1,fx-2]
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
auto e = std::exp(hardening * (1.0_f - p.Jp)), mu = mu_0 * e,
lambda = lambda_0 * e;
real J = determinant(p.F); // Current volume
Mat r, s;
polar_decomp(p.F, r, s); // Polar decomp. for fixed corotated model
Mat cauchy;
if (p.type == 2) {
cauchy = Mat(0.2_f * E * (pow<1>(p.Jp) - 1));
} else {
cauchy = 2 * mu * (p.F - r) * transposed(p.F) + lambda * (J - 1) * J;
}
auto stress = // Cauchy stress times dt and inv_dx
-4 * inv_dx * inv_dx * dt * vol * cauchy;
auto affine = stress + particle_mass * p.C;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) { // Scatter to grid
auto dpos = (Vec(i, j) - fx) * dx;
Vector3 mv(p.v * particle_mass,
particle_mass); // translational momentum
grid[base_coord.x + i][base_coord.y + j] +=
w[i].x * w[j].y * (mv + Vector3(affine * dpos, 0));
}
}
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++) { // For all grid nodes
auto &g = grid[i][j];
if (g[2] > 0) { // No need for epsilon here
g /= g[2]; // Normalize by mass
g += dt * Vector3(0, -200, 0); // Gravity
real boundary = 0.05, x = (real)i / n,
y = real(j) / n; // boundary thick.,node coord
if (x < boundary || x > 1 - boundary || y > 1 - boundary)
g = Vector3(0); // Sticky
if (y < boundary)
g[1] = std::max(0.0_f, g[1]); //"Separate"
}
}
for (auto &p : particles) { // Grid to particle
Vector2i base_coord =
(p.x * inv_dx - Vec(0.5_f)).cast<int>(); // element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast<real>();
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
p.C = Mat(0);
p.v = Vec(0);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
auto dpos = (Vec(i, j) - fx),
grid_v = Vec(grid[base_coord.x + i][base_coord.y + j]);
auto weight = w[i].x * w[j].y;
p.v += weight * grid_v; // Velocity
p.C +=
4 * inv_dx * Mat::outer_product(weight * grid_v, dpos); // APIC C
}
p.x += dt * p.v; // Advection
if (p.type <= 1) { // plastic
auto F = (Mat(1) + dt * p.C) * p.F; // MLS-MPM F-update
if (p.type == 1) {
Mat svd_u, sig, svd_v;
svd(F, svd_u, sig, svd_v);
for (int i = 0; i < 2; i++) // Snow Plasticity
sig[i][i] = clamp(sig[i][i], 1.0_f - 2.5e-2_f, 1.0_f + 7.5e-3_f);
real oldJ = determinant(F);
F = svd_u * sig * transposed(svd_v);
real Jp_new = clamp(p.Jp * oldJ / determinant(F), 0.6_f, 20.0_f);
p.Jp = Jp_new;
}
p.F = F;
} else { // liquid
p.Jp *= determinant(Mat(1) + dt * p.C);
}
}
}
void add_object(Vec center, int c, int type) {
for (int i = 0; i < 500 * pow<2>(n / 80.0); i++)
particles.push_back(
Particle((Vec::rand() * 2.0_f - Vec(1)) * 0.08_f + center, c, type));
}
int main() {
GUI gui("Real-time 2D MLS-MPM", window_size, window_size);
add_object(Vec(0.55, 0.45), 0xED553B, 0);
add_object(Vec(0.45, 0.65), 0xF2B134, 1);
add_object(Vec(0.55, 0.85), 0x068587, 2);
auto &canvas = gui.get_canvas();
int f = 0;
for (int i = 0;; i++) { // Main Loop
advance(dt); // Advance simulation
if (i % int(frame_dt / dt) == 0) { // Visualize frame
canvas.clear(0x112F41); // Clear background
canvas.rect(Vec(0.04), Vec(0.96))
.radius(2)
.color(0x4FB99F)
.close(); // Box
for (auto p : particles)
canvas.circle(p.x).radius(2).color(p.c); // Particles
gui.update(); // Update image
// canvas.img.write_as_image(fmt::format("tmp/{:05d}.png", f++));
}
}
} //----------------------------------------------------------------------------<commit_msg>tetris shape<commit_after>#include "taichi.h" // Note: You DO NOT have to install taichi or taichi_mpm.
using namespace taichi; // You only need [taichi.h] - see below for
// instructions.
const int n = 160 /*grid resolution (cells)*/, window_size = 800;
const real dt = 60e-4_f / n, frame_dt = 1e-3_f, dx = 1.0_f / n,
inv_dx = 1.0_f / dx;
auto particle_mass = 1.0_f, vol = 1.0_f;
auto hardening = 10.0_f, E = 1e4_f, nu = 0.2_f;
real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1 + nu) * (1 - 2 * nu));
using Vec = Vector2;
using Mat = Matrix2;
struct Particle {
Vec x, v;
Mat F, C;
real Jp;
int c /*color*/;
int type; // 0: elastic 1: plastic 2: liquid
Particle(Vec x, int c, int type, Vec v = Vec(0))
: x(x), v(v), F(1), C(0), Jp(1), c(c), type(type) {
}
};
std::vector<Particle> particles;
Vector3 grid[n + 1][n + 1]; // velocity + mass, node_res = cell_res + 1
// http://zetcode.com/tutorials/javaswingtutorial/thetetrisgame/
int tetris_offsets[7][3][2] = {
// excluding center
{{0, -1}, {-1, 0}, {-2, 0}}, {{0, 1}, {-1, 0}, {-2, 0}},
{{1, 0}, {-1, 0}, {1, 1}}, {{0, 1}, {1, 0}, {1, 1}},
{{0, 1}, {0, -1}, {0, 2}}, {{0, 1}, {0, -1}, {0, 2}},
};
void advance(real dt) {
std::memset(grid, 0, sizeof(grid)); // Reset grid
for (auto &p : particles) { // P2G
Vector2i base_coord =
(p.x * inv_dx - Vec(0.5_f)).cast<int>(); // element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast<real>();
// Quadratic kernels [http://mpm.graphics Eqn. 123, with x=fx, fx-1,fx-2]
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
auto e = std::exp(hardening * (1.0_f - p.Jp)), mu = mu_0 * e,
lambda = lambda_0 * e;
real J = determinant(p.F); // Current volume
Mat r, s;
polar_decomp(p.F, r, s); // Polar decomp. for fixed corotated model
Mat cauchy;
if (p.type == 2) {
cauchy = Mat(0.2_f * E * (pow<1>(p.Jp) - 1));
} else {
cauchy = 2 * mu * (p.F - r) * transposed(p.F) + lambda * (J - 1) * J;
}
auto stress = // Cauchy stress times dt and inv_dx
-4 * inv_dx * inv_dx * dt * vol * cauchy;
auto affine = stress + particle_mass * p.C;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) { // Scatter to grid
auto dpos = (Vec(i, j) - fx) * dx;
Vector3 mv(p.v * particle_mass,
particle_mass); // translational momentum
grid[base_coord.x + i][base_coord.y + j] +=
w[i].x * w[j].y * (mv + Vector3(affine * dpos, 0));
}
}
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++) { // For all grid nodes
auto &g = grid[i][j];
if (g[2] > 0) { // No need for epsilon here
g /= g[2]; // Normalize by mass
g += dt * Vector3(0, -200, 0); // Gravity
real boundary = 0.05, x = (real)i / n,
y = real(j) / n; // boundary thick.,node coord
if (x < boundary || x > 1 - boundary || y > 1 - boundary)
g = Vector3(0); // Sticky
if (y < boundary)
g[1] = std::max(0.0_f, g[1]); //"Separate"
}
}
for (auto &p : particles) { // Grid to particle
Vector2i base_coord =
(p.x * inv_dx - Vec(0.5_f)).cast<int>(); // element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast<real>();
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
p.C = Mat(0);
p.v = Vec(0);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
auto dpos = (Vec(i, j) - fx),
grid_v = Vec(grid[base_coord.x + i][base_coord.y + j]);
auto weight = w[i].x * w[j].y;
p.v += weight * grid_v; // Velocity
p.C +=
4 * inv_dx * Mat::outer_product(weight * grid_v, dpos); // APIC C
}
p.x += dt * p.v; // Advection
if (p.type <= 1) { // plastic
auto F = (Mat(1) + dt * p.C) * p.F; // MLS-MPM F-update
if (p.type == 1) {
Mat svd_u, sig, svd_v;
svd(F, svd_u, sig, svd_v);
for (int i = 0; i < 2; i++) // Snow Plasticity
sig[i][i] = clamp(sig[i][i], 1.0_f - 2.5e-2_f, 1.0_f + 7.5e-3_f);
real oldJ = determinant(F);
F = svd_u * sig * transposed(svd_v);
real Jp_new = clamp(p.Jp * oldJ / determinant(F), 0.6_f, 20.0_f);
p.Jp = Jp_new;
}
p.F = F;
} else { // liquid
p.Jp *= determinant(Mat(1) + dt * p.C);
}
}
}
void add_object(Vec center, int c, int type, int block) {
auto gen = [&](int k) {
Vector2 offset(0, 0);
if (k >= 0)
offset =
Vector2(tetris_offsets[block][k][0], tetris_offsets[block][k][1]);
for (int i = 0; i < 30 * pow<2>(n / 80.0); i++)
particles.push_back(
Particle((Vec::rand() + offset) * 0.05_f + center, c, type));
};
gen(-1);
gen(0);
gen(1);
gen(2);
}
int main() {
GUI gui("Real-time 2D MLS-MPM", window_size, window_size);
add_object(Vec(0.55, 0.45), 0xED553B, 0, 0);
add_object(Vec(0.45, 0.65), 0xF2B134, 1, 1);
add_object(Vec(0.55, 0.75), 0x068587, 2, 2);
auto &canvas = gui.get_canvas();
int f = 0;
for (int i = 0;; i++) { // Main Loop
advance(dt); // Advance simulation
if (i % int(frame_dt / dt) == 0) { // Visualize frame
canvas.clear(0x112F41); // Clear background
canvas.rect(Vec(0.04), Vec(0.96))
.radius(2)
.color(0x4FB99F)
.close(); // Box
for (auto p : particles)
canvas.circle(p.x).radius(2).color(p.c); // Particles
gui.update(); // Update image
// canvas.img.write_as_image(fmt::format("tmp/{:05d}.png", f++));
}
}
} //----------------------------------------------------------------------------<|endoftext|>
|
<commit_before>/******************************************
Author: Tiago Britto Lobão
tiago.blobao@gmail.com
*/
/*
Purpose: Control an integrated circuit
Cirrus Logic - CS5490
Used to measure electrical quantities
MIT License
******************************************/
#include "CS5490.h"
/******* Init CS5490 *******/
//For Arduino & ESP8622
#if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s)
CS5490::CS5490(float mclk, int rx, int tx){
this->MCLK = mclk;
this->cSerial = new SoftwareSerial(rx,tx);
}
//For ESP32 AND MEGA
#else
CS5490::CS5490(float mclk){
this->MCLK = mclk;
this->cSerial = &Serial2;
}
#endif
void CS5490::begin(int baudRate){
cSerial->begin(baudRate);
delay(10); //Avoid Bugs on Arduino UNO
}
/**************************************************************/
/* PRIVATE METHODS */
/**************************************************************/
/******* Write a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::write(int page, int address, long value){
uint8_t checksum = 0;
for(int i=0; i<3; i++)
checksum += 0xFF - checksum;
//Select page and address
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (writeByte | (uint8_t)address);
cSerial->write(buffer);
//Send information
for(int i=0; i<3 ; i++){
data[i] = value & 0x000000FF;
cSerial->write(this->data[i]);
value >>= 8;
}
//Calculate and send checksum
buffer = 0xFF - data[0] - data[1] - data[2];
cSerial->write(buffer);
}
/******* Read a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::read(int page, int address){
this->clearSerialBuffer();
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (readByte | (uint8_t)address);
cSerial->write(buffer);
//Wait for 3 bytes to arrive
while(cSerial->available() < 3);
for(int i=0; i<3; i++){
data[i] = cSerial->read();
}
}
/******* Give an instruction by the serial communication *******/
void CS5490::instruct(int value){
uint8_t buffer = (instructionByte | (uint8_t)value);
cSerial->write(buffer);
}
/******* Clears cSerial Buffer *******/
void CS5490::clearSerialBuffer(){
while (cSerial->available()) cSerial->read();
}
/*
Function: toDouble
Transforms a 24 bit number to a double number for easy processing data
Param:
data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490
LSBpow => Expoent specified from datasheet of the less significant bit
MSBoption => Information of most significant bit case. It can be only three values:
MSBnull (1) The MSB is a Don't Care bit
MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion
MSBunsigned (3) The MSB is a positive value, the default case.
*/
double CS5490::toDouble(int LSBpow, int MSBoption){
uint32_t buffer = 0;
double output = 0.0;
bool MSB;
//Concat bytes in a 32 bit word
buffer += this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
switch(MSBoption){
case MSBnull:
this->data[2] &= ~(1 << 7); //Clear MSB
buffer += this->data[2] << 16;
output = (double)buffer;
output /= pow(2,LSBpow);
break;
case MSBsigned:
MSB = data[2] & 0x80;
if(MSB){ //- (2 complement conversion)
buffer = ~buffer;
//Clearing the first 8 bits
for(int i=24; i<32; i++)
buffer &= ~(1 << i);
output = (double)buffer + 1.0;
output /= -pow(2,LSBpow);
}
else{ //+
output = (double)buffer;
output /= (pow(2,LSBpow)-1.0);
}
break;
default:
case MSBunsigned:
output = (double)buffer;
output /= pow(2,LSBpow);
break;
}
return output;
}
/**************************************************************/
/* PUBLIC METHODS - Instructions */
/**************************************************************/
void CS5490::reset(){
this->instruct(1);
}
void CS5490::standby(){
this->instruct(2);
}
void CS5490::wakeUp(){
this->instruct(3);
}
void CS5490::singConv(){
this->instruct(20);
}
void CS5490::contConv(){
this->instruct(21);
}
void CS5490::haltConv(){
this->instruct(24);
}
/**************************************************************/
/* PUBLIC METHODS - Calibration and Configuration */
/**************************************************************/
/* SET */
void CS5490::setBaudRate(long value){
//Calculate the correct binary value
uint32_t hexBR = ceil(value*0.5242880/MCLK);
if (hexBR > 65535) hexBR = 65535;
hexBR += 0x020000;
this->write(0x80,0x07,hexBR);
delay(100); //To avoid bugs from ESP32
//Reset Serial communication from controller
cSerial->end();
cSerial->begin(value);
return;
}
/* GET */
int CS5490::getGainI(){
//Page 16, Address 33
this->read(16,33);
return this->toDouble(22,MSBunsigned);
}
long CS5490::getBaudRate(){
this->read(0,7);
uint32_t buffer = this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
buffer -= 0x020000;
return ( (buffer/0.5242880)*MCLK );
}
/**************************************************************/
/* PUBLIC METHODS - Measurements */
/**************************************************************/
double CS5490::getPeakV(){
//Page 0, Address 36
this->read(0,36);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPeakI(){
//Page 0, Address 37
this->read(0,37);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstI(){
//Page 16, Address 2
this->read(16,2);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstV(){
//Page 16, Address 3
this->read(16,3);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstP(){
//Page 16, Address 4
this->read(16,4);
return this->toDouble(23, MSBsigned);
}
double CS5490::getRmsI(){
//Page 16, Address 6
this->read(16,6);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getRmsV(){
//Page 16, Address 7
this->read(16,7);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getAvgP(){
//Page 16, Address 5
this->read(16,5);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgQ(){
//Page 16, Address 14
this->read(16,14);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgS(){
//Page 16, Address 20
this->read(16,20);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstQ(){
//Page 16, Address 15
this->read(16,15);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPF(){
//Page 16, Address 21
this->read(16,21);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalP(){
//Page 16, Address 29
this->read(16,29);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalS(){
//Page 16, Address 30
this->read(16,30);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalQ(){
//Page 16, Address 31
this->read(16,31);
return this->toDouble(23, MSBsigned);
}
double CS5490::getFreq(){
//Page 16, Address 49
this->read(16,49);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTime(){
//Page 16, Address 49
this->read(16,61);
return this->toDouble(0, MSBunsigned);
}
/**************************************************************/
/* PUBLIC METHODS - Read Register */
/**************************************************************/
long CS5490::readReg(int page, int address){
long value = 0;
this->read(page, address);
for(int i=0; i<3; i++){
value += data[2-i];
value <<= 8;
}
return value;
}
<commit_msg>Bug Fix for Arduino MEGA<commit_after>/******************************************
Author: Tiago Britto Lobão
tiago.blobao@gmail.com
*/
/*
Purpose: Control an integrated circuit
Cirrus Logic - CS5490
Used to measure electrical quantities
MIT License
******************************************/
#include "CS5490.h"
/******* Init CS5490 *******/
//For Arduino & ESP8622
#if !(defined ARDUINO_NodeMCU_32S ) && !defined(__AVR_ATmega1280__) && !defined(__AVR_ATmega2560__) && !defined(ARDUINO_Node32s)
CS5490::CS5490(float mclk, int rx, int tx){
this->MCLK = mclk;
this->cSerial = new SoftwareSerial(rx,tx);
}
//For ESP32 AND MEGA
#else
CS5490::CS5490(float mclk){
this->MCLK = mclk;
this->cSerial = &Serial2;
}
#endif
void CS5490::begin(int baudRate){
cSerial->begin(baudRate);
delay(10); //Avoid Bugs on Arduino UNO
}
/**************************************************************/
/* PRIVATE METHODS */
/**************************************************************/
/******* Write a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::write(int page, int address, long value){
uint8_t checksum = 0;
for(int i=0; i<3; i++)
checksum += 0xFF - checksum;
//Select page and address
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (writeByte | (uint8_t)address);
cSerial->write(buffer);
//Send information
for(int i=0; i<3 ; i++){
data[i] = value & 0x000000FF;
cSerial->write(this->data[i]);
value >>= 8;
}
//Calculate and send checksum
buffer = 0xFF - data[0] - data[1] - data[2];
cSerial->write(buffer);
}
/******* Read a register by the serial communication *******/
/* data bytes pass by data variable from this class */
void CS5490::read(int page, int address){
this->clearSerialBuffer();
uint8_t buffer = (pageByte | (uint8_t)page);
cSerial->write(buffer);
buffer = (readByte | (uint8_t)address);
cSerial->write(buffer);
//Wait for 3 bytes to arrive
while(cSerial->available() < 3);
for(int i=0; i<3; i++){
data[i] = cSerial->read();
}
}
/******* Give an instruction by the serial communication *******/
void CS5490::instruct(int value){
uint8_t buffer = (instructionByte | (uint8_t)value);
cSerial->write(buffer);
}
/******* Clears cSerial Buffer *******/
void CS5490::clearSerialBuffer(){
while (cSerial->available()) cSerial->read();
}
/*
Function: toDouble
Transforms a 24 bit number to a double number for easy processing data
Param:
data[] => Array with size 3. Each uint8_t is an 8 byte number received from CS5490
LSBpow => Expoent specified from datasheet of the less significant bit
MSBoption => Information of most significant bit case. It can be only three values:
MSBnull (1) The MSB is a Don't Care bit
MSBsigned (2) the MSB is a negative value, requiring a 2 complement conversion
MSBunsigned (3) The MSB is a positive value, the default case.
*/
double CS5490::toDouble(int LSBpow, int MSBoption){
uint32_t buffer = 0;
double output = 0.0;
bool MSB;
//Concat bytes in a 32 bit word
buffer += this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
switch(MSBoption){
case MSBnull:
this->data[2] &= ~(1 << 7); //Clear MSB
buffer += this->data[2] << 16;
output = (double)buffer;
output /= pow(2,LSBpow);
break;
case MSBsigned:
MSB = data[2] & 0x80;
if(MSB){ //- (2 complement conversion)
buffer = ~buffer;
//Clearing the first 8 bits
for(int i=24; i<32; i++)
buffer &= ~(1 << i);
output = (double)buffer + 1.0;
output /= -pow(2,LSBpow);
}
else{ //+
output = (double)buffer;
output /= (pow(2,LSBpow)-1.0);
}
break;
default:
case MSBunsigned:
output = (double)buffer;
output /= pow(2,LSBpow);
break;
}
return output;
}
/**************************************************************/
/* PUBLIC METHODS - Instructions */
/**************************************************************/
void CS5490::reset(){
this->instruct(1);
}
void CS5490::standby(){
this->instruct(2);
}
void CS5490::wakeUp(){
this->instruct(3);
}
void CS5490::singConv(){
this->instruct(20);
}
void CS5490::contConv(){
this->instruct(21);
}
void CS5490::haltConv(){
this->instruct(24);
}
/**************************************************************/
/* PUBLIC METHODS - Calibration and Configuration */
/**************************************************************/
/* SET */
void CS5490::setBaudRate(long value){
//Calculate the correct binary value
uint32_t hexBR = ceil(value*0.5242880/MCLK);
if (hexBR > 65535) hexBR = 65535;
hexBR += 0x020000;
this->write(0x80,0x07,hexBR);
delay(100); //To avoid bugs from ESP32
//Reset Serial communication from controller
cSerial->end();
cSerial->begin(value);
delay(50); //Avoid bugs from Arduino MEGA
return;
}
/* GET */
int CS5490::getGainI(){
//Page 16, Address 33
this->read(16,33);
return this->toDouble(22,MSBunsigned);
}
long CS5490::getBaudRate(){
this->read(0,7);
uint32_t buffer = this->data[0];
buffer += this->data[1] << 8;
buffer += this->data[2] << 16;
buffer -= 0x020000;
return ( (buffer/0.5242880)*MCLK );
}
/**************************************************************/
/* PUBLIC METHODS - Measurements */
/**************************************************************/
double CS5490::getPeakV(){
//Page 0, Address 36
this->read(0,36);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPeakI(){
//Page 0, Address 37
this->read(0,37);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstI(){
//Page 16, Address 2
this->read(16,2);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstV(){
//Page 16, Address 3
this->read(16,3);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstP(){
//Page 16, Address 4
this->read(16,4);
return this->toDouble(23, MSBsigned);
}
double CS5490::getRmsI(){
//Page 16, Address 6
this->read(16,6);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getRmsV(){
//Page 16, Address 7
this->read(16,7);
return this->toDouble(23, MSBunsigned);
}
double CS5490::getAvgP(){
//Page 16, Address 5
this->read(16,5);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgQ(){
//Page 16, Address 14
this->read(16,14);
return this->toDouble(23, MSBsigned);
}
double CS5490::getAvgS(){
//Page 16, Address 20
this->read(16,20);
return this->toDouble(23, MSBsigned);
}
double CS5490::getInstQ(){
//Page 16, Address 15
this->read(16,15);
return this->toDouble(23, MSBsigned);
}
double CS5490::getPF(){
//Page 16, Address 21
this->read(16,21);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalP(){
//Page 16, Address 29
this->read(16,29);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalS(){
//Page 16, Address 30
this->read(16,30);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTotalQ(){
//Page 16, Address 31
this->read(16,31);
return this->toDouble(23, MSBsigned);
}
double CS5490::getFreq(){
//Page 16, Address 49
this->read(16,49);
return this->toDouble(23, MSBsigned);
}
double CS5490::getTime(){
//Page 16, Address 49
this->read(16,61);
return this->toDouble(0, MSBunsigned);
}
/**************************************************************/
/* PUBLIC METHODS - Read Register */
/**************************************************************/
long CS5490::readReg(int page, int address){
long value = 0;
this->read(page, address);
for(int i=0; i<3; i++){
value += data[2-i];
value <<= 8;
}
return value;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2012 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "table/filter_block.h"
#include "db/dbformat.h"
#include "rocksdb/filter_policy.h"
#include "util/coding.h"
namespace rocksdb {
// See doc/table_format.txt for an explanation of the filter block format.
// Generate new filter every 2KB of data
static const size_t kFilterBaseLg = 11;
static const size_t kFilterBase = 1 << kFilterBaseLg;
FilterBlockBuilder::FilterBlockBuilder(const Options& opt,
const Comparator* internal_comparator)
: policy_(opt.filter_policy),
prefix_extractor_(opt.prefix_extractor),
whole_key_filtering_(opt.whole_key_filtering),
comparator_(internal_comparator) {}
void FilterBlockBuilder::StartBlock(uint64_t block_offset) {
uint64_t filter_index = (block_offset / kFilterBase);
assert(filter_index >= filter_offsets_.size());
while (filter_index > filter_offsets_.size()) {
GenerateFilter();
}
}
bool FilterBlockBuilder::SamePrefix(const Slice &key1,
const Slice &key2) const {
if (!prefix_extractor_->InDomain(key1) &&
!prefix_extractor_->InDomain(key2)) {
return true;
} else if (!prefix_extractor_->InDomain(key1) ||
!prefix_extractor_->InDomain(key2)) {
return false;
} else {
return (prefix_extractor_->Transform(key1) ==
prefix_extractor_->Transform(key2));
}
}
void FilterBlockBuilder::AddKey(const Slice& key) {
// get slice for most recently added entry
Slice prev;
size_t added_to_start = 0;
// add key to filter if needed
if (whole_key_filtering_) {
start_.push_back(entries_.size());
++added_to_start;
entries_.append(key.data(), key.size());
}
if (start_.size() > added_to_start) {
size_t prev_start = start_[start_.size() - 1 - added_to_start];
const char* base = entries_.data() + prev_start;
size_t length = entries_.size() - prev_start;
prev = Slice(base, length);
}
// add prefix to filter if needed
if (prefix_extractor_ && prefix_extractor_->InDomain(ExtractUserKey(key))) {
// If prefix_extractor_, this filter_block layer assumes we only
// operate on internal keys.
Slice user_key = ExtractUserKey(key);
// this assumes prefix(prefix(key)) == prefix(key), as the last
// entry in entries_ may be either a key or prefix, and we use
// prefix(last entry) to get the prefix of the last key.
if (prev.size() == 0 ||
!SamePrefix(user_key, ExtractUserKey(prev))) {
Slice prefix = prefix_extractor_->Transform(user_key);
InternalKey internal_prefix_tmp(prefix, 0, kTypeValue);
Slice internal_prefix = internal_prefix_tmp.Encode();
assert(comparator_->Compare(internal_prefix, key) <= 0);
start_.push_back(entries_.size());
entries_.append(internal_prefix.data(), internal_prefix.size());
}
}
}
Slice FilterBlockBuilder::Finish() {
if (!start_.empty()) {
GenerateFilter();
}
// Append array of per-filter offsets
const uint32_t array_offset = result_.size();
for (size_t i = 0; i < filter_offsets_.size(); i++) {
PutFixed32(&result_, filter_offsets_[i]);
}
PutFixed32(&result_, array_offset);
result_.push_back(kFilterBaseLg); // Save encoding parameter in result
return Slice(result_);
}
void FilterBlockBuilder::GenerateFilter() {
const size_t num_entries = start_.size();
if (num_entries == 0) {
// Fast path if there are no keys for this filter
filter_offsets_.push_back(result_.size());
return;
}
// Make list of keys from flattened key structure
start_.push_back(entries_.size()); // Simplify length computation
tmp_entries_.resize(num_entries);
for (size_t i = 0; i < num_entries; i++) {
const char* base = entries_.data() + start_[i];
size_t length = start_[i+1] - start_[i];
tmp_entries_[i] = Slice(base, length);
}
// Generate filter for current set of keys and append to result_.
filter_offsets_.push_back(result_.size());
policy_->CreateFilter(&tmp_entries_[0], num_entries, &result_);
tmp_entries_.clear();
entries_.clear();
start_.clear();
}
FilterBlockReader::FilterBlockReader(
const Options& opt, const Slice& contents, bool delete_contents_after_use)
: policy_(opt.filter_policy),
prefix_extractor_(opt.prefix_extractor),
whole_key_filtering_(opt.whole_key_filtering),
data_(nullptr),
offset_(nullptr),
num_(0),
base_lg_(0) {
size_t n = contents.size();
if (n < 5) return; // 1 byte for base_lg_ and 4 for start of offset array
base_lg_ = contents[n-1];
uint32_t last_word = DecodeFixed32(contents.data() + n - 5);
if (last_word > n - 5) return;
data_ = contents.data();
offset_ = data_ + last_word;
num_ = (n - 5 - last_word) / 4;
if (delete_contents_after_use) {
filter_data.reset(contents.data());
}
}
bool FilterBlockReader::KeyMayMatch(uint64_t block_offset,
const Slice& key) {
if (!whole_key_filtering_) {
return true;
}
return MayMatch(block_offset, key);
}
bool FilterBlockReader::PrefixMayMatch(uint64_t block_offset,
const Slice& prefix) {
if (!prefix_extractor_) {
return true;
}
return MayMatch(block_offset, prefix);
}
bool FilterBlockReader::MayMatch(uint64_t block_offset, const Slice& entry) {
uint64_t index = block_offset >> base_lg_;
if (index < num_) {
uint32_t start = DecodeFixed32(offset_ + index*4);
uint32_t limit = DecodeFixed32(offset_ + index*4 + 4);
if (start <= limit && limit <= (uint32_t)(offset_ - data_)) {
Slice filter = Slice(data_ + start, limit - start);
return policy_->KeyMayMatch(entry, filter);
} else if (start == limit) {
// Empty filters do not match any entries
return false;
}
}
return true; // Errors are treated as potential matches
}
}
<commit_msg>Fix a buggy assert<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2012 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "table/filter_block.h"
#include "db/dbformat.h"
#include "rocksdb/filter_policy.h"
#include "util/coding.h"
namespace rocksdb {
// See doc/table_format.txt for an explanation of the filter block format.
// Generate new filter every 2KB of data
static const size_t kFilterBaseLg = 11;
static const size_t kFilterBase = 1 << kFilterBaseLg;
FilterBlockBuilder::FilterBlockBuilder(const Options& opt,
const Comparator* internal_comparator)
: policy_(opt.filter_policy),
prefix_extractor_(opt.prefix_extractor),
whole_key_filtering_(opt.whole_key_filtering),
comparator_(internal_comparator) {}
void FilterBlockBuilder::StartBlock(uint64_t block_offset) {
uint64_t filter_index = (block_offset / kFilterBase);
assert(filter_index >= filter_offsets_.size());
while (filter_index > filter_offsets_.size()) {
GenerateFilter();
}
}
bool FilterBlockBuilder::SamePrefix(const Slice &key1,
const Slice &key2) const {
if (!prefix_extractor_->InDomain(key1) &&
!prefix_extractor_->InDomain(key2)) {
return true;
} else if (!prefix_extractor_->InDomain(key1) ||
!prefix_extractor_->InDomain(key2)) {
return false;
} else {
return (prefix_extractor_->Transform(key1) ==
prefix_extractor_->Transform(key2));
}
}
void FilterBlockBuilder::AddKey(const Slice& key) {
// get slice for most recently added entry
Slice prev;
size_t added_to_start = 0;
// add key to filter if needed
if (whole_key_filtering_) {
start_.push_back(entries_.size());
++added_to_start;
entries_.append(key.data(), key.size());
}
if (start_.size() > added_to_start) {
size_t prev_start = start_[start_.size() - 1 - added_to_start];
const char* base = entries_.data() + prev_start;
size_t length = entries_.size() - prev_start;
prev = Slice(base, length);
}
// add prefix to filter if needed
if (prefix_extractor_ && prefix_extractor_->InDomain(ExtractUserKey(key))) {
// If prefix_extractor_, this filter_block layer assumes we only
// operate on internal keys.
Slice user_key = ExtractUserKey(key);
// this assumes prefix(prefix(key)) == prefix(key), as the last
// entry in entries_ may be either a key or prefix, and we use
// prefix(last entry) to get the prefix of the last key.
if (prev.size() == 0 ||
!SamePrefix(user_key, ExtractUserKey(prev))) {
Slice prefix = prefix_extractor_->Transform(user_key);
InternalKey internal_prefix_tmp(prefix, 0, kTypeValue);
Slice internal_prefix = internal_prefix_tmp.Encode();
start_.push_back(entries_.size());
entries_.append(internal_prefix.data(), internal_prefix.size());
}
}
}
Slice FilterBlockBuilder::Finish() {
if (!start_.empty()) {
GenerateFilter();
}
// Append array of per-filter offsets
const uint32_t array_offset = result_.size();
for (size_t i = 0; i < filter_offsets_.size(); i++) {
PutFixed32(&result_, filter_offsets_[i]);
}
PutFixed32(&result_, array_offset);
result_.push_back(kFilterBaseLg); // Save encoding parameter in result
return Slice(result_);
}
void FilterBlockBuilder::GenerateFilter() {
const size_t num_entries = start_.size();
if (num_entries == 0) {
// Fast path if there are no keys for this filter
filter_offsets_.push_back(result_.size());
return;
}
// Make list of keys from flattened key structure
start_.push_back(entries_.size()); // Simplify length computation
tmp_entries_.resize(num_entries);
for (size_t i = 0; i < num_entries; i++) {
const char* base = entries_.data() + start_[i];
size_t length = start_[i+1] - start_[i];
tmp_entries_[i] = Slice(base, length);
}
// Generate filter for current set of keys and append to result_.
filter_offsets_.push_back(result_.size());
policy_->CreateFilter(&tmp_entries_[0], num_entries, &result_);
tmp_entries_.clear();
entries_.clear();
start_.clear();
}
FilterBlockReader::FilterBlockReader(
const Options& opt, const Slice& contents, bool delete_contents_after_use)
: policy_(opt.filter_policy),
prefix_extractor_(opt.prefix_extractor),
whole_key_filtering_(opt.whole_key_filtering),
data_(nullptr),
offset_(nullptr),
num_(0),
base_lg_(0) {
size_t n = contents.size();
if (n < 5) return; // 1 byte for base_lg_ and 4 for start of offset array
base_lg_ = contents[n-1];
uint32_t last_word = DecodeFixed32(contents.data() + n - 5);
if (last_word > n - 5) return;
data_ = contents.data();
offset_ = data_ + last_word;
num_ = (n - 5 - last_word) / 4;
if (delete_contents_after_use) {
filter_data.reset(contents.data());
}
}
bool FilterBlockReader::KeyMayMatch(uint64_t block_offset,
const Slice& key) {
if (!whole_key_filtering_) {
return true;
}
return MayMatch(block_offset, key);
}
bool FilterBlockReader::PrefixMayMatch(uint64_t block_offset,
const Slice& prefix) {
if (!prefix_extractor_) {
return true;
}
return MayMatch(block_offset, prefix);
}
bool FilterBlockReader::MayMatch(uint64_t block_offset, const Slice& entry) {
uint64_t index = block_offset >> base_lg_;
if (index < num_) {
uint32_t start = DecodeFixed32(offset_ + index*4);
uint32_t limit = DecodeFixed32(offset_ + index*4 + 4);
if (start <= limit && limit <= (uint32_t)(offset_ - data_)) {
Slice filter = Slice(data_ + start, limit - start);
return policy_->KeyMayMatch(entry, filter);
} else if (start == limit) {
// Empty filters do not match any entries
return false;
}
}
return true; // Errors are treated as potential matches
}
}
<|endoftext|>
|
<commit_before>#include <unistd.h>
#include <vector>
#include "Export.h"
#include "Common.h"
#include "Client.h"
#include "Keywords.h"
namespace douban {
namespace mc {
Client::Client() {
}
Client::~Client() {
}
void Client::config(config_options_t opt, int val) {
switch (opt) {
case CFG_POLL_TIMEOUT:
setPollTimeout(val);
break;
case CFG_CONNECT_TIMEOUT:
setConnectTimeout(val);
break;
case CFG_RETRY_TIMEOUT:
setRetryTimeout(val);
break;
case CFG_HASH_FUNCTION:
ConnectionPool::setHashFunction(static_cast<hash_function_options_t>(val));
default:
break;
}
}
err_code_t Client::get(const char* const* keys, const size_t* keyLens, size_t nKeys,
retrieval_result_t*** results, size_t* nResults) {
dispatchRetrieval(GET_OP, keys, keyLens, nKeys);
err_code_t rv = waitPoll();
collectRetrievalResult(results, nResults);
return rv;
}
err_code_t Client::gets(const char* const* keys, const size_t* keyLens, size_t nKeys,
retrieval_result_t*** results, size_t* nResults) {
dispatchRetrieval(GETS_OP, keys, keyLens, nKeys);
err_code_t rv = waitPoll();
collectRetrievalResult(results, nResults);
return rv;
}
void Client::collectRetrievalResult(retrieval_result_t*** results, size_t* nResults) {
assert(m_outRetrievalResultPtrs.size() == 0);
ConnectionPool::collectRetrievalResult(m_outRetrievalResultPtrs);
*nResults = m_outRetrievalResultPtrs.size();
if (*nResults == 0) {
*results = NULL;
} else {
*results = &m_outRetrievalResultPtrs.front();
}
}
void Client::destroyRetrievalResult() {
ConnectionPool::reset();
m_outRetrievalResultPtrs.clear();
}
void Client::collectMessageResult(message_result_t*** results, size_t* nResults) {
assert(m_outMessageResultPtrs.size() == 0);
ConnectionPool::collectMessageResult(m_outMessageResultPtrs);
*nResults = m_outMessageResultPtrs.size();
if (*nResults == 0) {
*results = NULL;
} else {
*results = &m_outMessageResultPtrs.front();
}
}
void Client::destroyMessageResult() {
ConnectionPool::reset();
m_outMessageResultPtrs.clear();
}
#define IMPL_STORAGE_CMD(M, O) \
err_code_t Client::M(const char* const* keys, const size_t* key_lens, \
const flags_t* flags, const exptime_t exptime, \
const cas_unique_t* cas_uniques, const bool noreply, \
const char* const* vals, const size_t* val_lens, \
size_t nItems, message_result_t*** results, size_t* nResults) { \
dispatchStorage((O), keys, key_lens, flags, exptime, cas_uniques, noreply, vals, \
val_lens, nItems); \
err_code_t rv = waitPoll(); \
collectMessageResult(results, nResults); \
return rv;\
}
IMPL_STORAGE_CMD(set, SET_OP)
IMPL_STORAGE_CMD(add, ADD_OP)
IMPL_STORAGE_CMD(replace, REPLACE_OP)
IMPL_STORAGE_CMD(append, APPEND_OP)
IMPL_STORAGE_CMD(prepend, PREPEND_OP)
IMPL_STORAGE_CMD(cas, CAS_OP)
#undef IMPL_STORAGE_CMD
err_code_t Client::_delete(const char* const* keys, const size_t* key_lens,
const bool noreply, size_t nItems,
message_result_t*** results, size_t* nResults) {
dispatchDeletion(keys, key_lens, noreply, nItems);
err_code_t rv = waitPoll();
collectMessageResult(results, nResults);
return rv;
}
void Client::collectBroadcastResult(broadcast_result_t** results, size_t* nHosts) {
assert(m_outBroadcastResultPtrs.size() == 0);
*nHosts = m_nConns;
ConnectionPool::collectBroadcastResult(m_outBroadcastResultPtrs);
*results = &m_outBroadcastResultPtrs.front();
}
void Client::destroyBroadcastResult() {
ConnectionPool::reset();
for (std::vector<broadcast_result_t>::iterator it = m_outBroadcastResultPtrs.begin();
it != m_outBroadcastResultPtrs.end(); ++it) {
types::delete_broadcast_result(&(*it));
}
m_outBroadcastResultPtrs.clear();
}
err_code_t Client::version(broadcast_result_t** results, size_t* nHosts) {
broadcastCommand(keywords::kVERSION, 7);
err_code_t rv = waitPoll();
collectBroadcastResult(results, nHosts);
return rv;
}
err_code_t Client::quit() {
broadcastCommand(keywords::kQUIT, 4);
err_code_t rv = waitPoll();
return rv;
}
err_code_t Client::stats(broadcast_result_t** results, size_t* nHosts) {
broadcastCommand(keywords::kSTATS, 5);
err_code_t rv = waitPoll();
collectBroadcastResult(results, nHosts);
return rv;
}
err_code_t Client::touch(const char* const* keys, const size_t* keyLens,
const exptime_t exptime, const bool noreply, size_t nItems,
message_result_t*** results, size_t* nResults) {
dispatchTouch(keys, keyLens, exptime, noreply, nItems);
err_code_t rv = waitPoll();
collectMessageResult(results, nResults);
return rv;
}
void Client::collectUnsignedResult(unsigned_result_t** results, size_t* nResults) {
assert(m_outUnsignedResultPtrs.size() == 0);
ConnectionPool::collectUnsignedResult(m_outUnsignedResultPtrs);
*nResults = m_outUnsignedResultPtrs.size();
if (*nResults == 0) {
*results = NULL;
} else {
*results = m_outUnsignedResultPtrs.front();
}
}
err_code_t Client::incr(const char* key, const size_t keyLen, const uint64_t delta,
const bool noreply,
unsigned_result_t** results, size_t* nResults) {
dispatchIncrDecr(INCR_OP, key, keyLen, delta, noreply);
err_code_t rv = waitPoll();
collectUnsignedResult(results, nResults);
return rv;
}
err_code_t Client::decr(const char* key, const size_t keyLen, const uint64_t delta,
const bool noreply,
unsigned_result_t** results, size_t* nResults) {
dispatchIncrDecr(DECR_OP, key, keyLen, delta, noreply);
err_code_t rv = waitPoll();
collectUnsignedResult(results, nResults);
return rv;
}
void Client::destroyUnsignedResult() {
ConnectionPool::reset();
m_outUnsignedResultPtrs.clear();
}
void Client::_sleep(uint32_t seconds) {
usleep(seconds * 1000000);
}
} // namespace mc
} // namespace douban
<commit_msg>use vector empty instead of size() == 0<commit_after>#include <unistd.h>
#include <vector>
#include "Export.h"
#include "Common.h"
#include "Client.h"
#include "Keywords.h"
namespace douban {
namespace mc {
Client::Client() {
}
Client::~Client() {
}
void Client::config(config_options_t opt, int val) {
switch (opt) {
case CFG_POLL_TIMEOUT:
setPollTimeout(val);
break;
case CFG_CONNECT_TIMEOUT:
setConnectTimeout(val);
break;
case CFG_RETRY_TIMEOUT:
setRetryTimeout(val);
break;
case CFG_HASH_FUNCTION:
ConnectionPool::setHashFunction(static_cast<hash_function_options_t>(val));
default:
break;
}
}
err_code_t Client::get(const char* const* keys, const size_t* keyLens, size_t nKeys,
retrieval_result_t*** results, size_t* nResults) {
dispatchRetrieval(GET_OP, keys, keyLens, nKeys);
err_code_t rv = waitPoll();
collectRetrievalResult(results, nResults);
return rv;
}
err_code_t Client::gets(const char* const* keys, const size_t* keyLens, size_t nKeys,
retrieval_result_t*** results, size_t* nResults) {
dispatchRetrieval(GETS_OP, keys, keyLens, nKeys);
err_code_t rv = waitPoll();
collectRetrievalResult(results, nResults);
return rv;
}
void Client::collectRetrievalResult(retrieval_result_t*** results, size_t* nResults) {
assert(m_outRetrievalResultPtrs.empty());
ConnectionPool::collectRetrievalResult(m_outRetrievalResultPtrs);
*nResults = m_outRetrievalResultPtrs.size();
if (*nResults == 0) {
*results = NULL;
} else {
*results = &m_outRetrievalResultPtrs.front();
}
}
void Client::destroyRetrievalResult() {
ConnectionPool::reset();
m_outRetrievalResultPtrs.clear();
}
void Client::collectMessageResult(message_result_t*** results, size_t* nResults) {
assert(m_outMessageResultPtrs.empty());
ConnectionPool::collectMessageResult(m_outMessageResultPtrs);
*nResults = m_outMessageResultPtrs.size();
if (*nResults == 0) {
*results = NULL;
} else {
*results = &m_outMessageResultPtrs.front();
}
}
void Client::destroyMessageResult() {
ConnectionPool::reset();
m_outMessageResultPtrs.clear();
}
#define IMPL_STORAGE_CMD(M, O) \
err_code_t Client::M(const char* const* keys, const size_t* key_lens, \
const flags_t* flags, const exptime_t exptime, \
const cas_unique_t* cas_uniques, const bool noreply, \
const char* const* vals, const size_t* val_lens, \
size_t nItems, message_result_t*** results, size_t* nResults) { \
dispatchStorage((O), keys, key_lens, flags, exptime, cas_uniques, noreply, vals, \
val_lens, nItems); \
err_code_t rv = waitPoll(); \
collectMessageResult(results, nResults); \
return rv;\
}
IMPL_STORAGE_CMD(set, SET_OP)
IMPL_STORAGE_CMD(add, ADD_OP)
IMPL_STORAGE_CMD(replace, REPLACE_OP)
IMPL_STORAGE_CMD(append, APPEND_OP)
IMPL_STORAGE_CMD(prepend, PREPEND_OP)
IMPL_STORAGE_CMD(cas, CAS_OP)
#undef IMPL_STORAGE_CMD
err_code_t Client::_delete(const char* const* keys, const size_t* key_lens,
const bool noreply, size_t nItems,
message_result_t*** results, size_t* nResults) {
dispatchDeletion(keys, key_lens, noreply, nItems);
err_code_t rv = waitPoll();
collectMessageResult(results, nResults);
return rv;
}
void Client::collectBroadcastResult(broadcast_result_t** results, size_t* nHosts) {
assert(m_outBroadcastResultPtrs.empty());
*nHosts = m_nConns;
ConnectionPool::collectBroadcastResult(m_outBroadcastResultPtrs);
*results = &m_outBroadcastResultPtrs.front();
}
void Client::destroyBroadcastResult() {
ConnectionPool::reset();
for (std::vector<broadcast_result_t>::iterator it = m_outBroadcastResultPtrs.begin();
it != m_outBroadcastResultPtrs.end(); ++it) {
types::delete_broadcast_result(&(*it));
}
m_outBroadcastResultPtrs.clear();
}
err_code_t Client::version(broadcast_result_t** results, size_t* nHosts) {
broadcastCommand(keywords::kVERSION, 7);
err_code_t rv = waitPoll();
collectBroadcastResult(results, nHosts);
return rv;
}
err_code_t Client::quit() {
broadcastCommand(keywords::kQUIT, 4);
err_code_t rv = waitPoll();
return rv;
}
err_code_t Client::stats(broadcast_result_t** results, size_t* nHosts) {
broadcastCommand(keywords::kSTATS, 5);
err_code_t rv = waitPoll();
collectBroadcastResult(results, nHosts);
return rv;
}
err_code_t Client::touch(const char* const* keys, const size_t* keyLens,
const exptime_t exptime, const bool noreply, size_t nItems,
message_result_t*** results, size_t* nResults) {
dispatchTouch(keys, keyLens, exptime, noreply, nItems);
err_code_t rv = waitPoll();
collectMessageResult(results, nResults);
return rv;
}
void Client::collectUnsignedResult(unsigned_result_t** results, size_t* nResults) {
assert(m_outUnsignedResultPtrs.empty());
ConnectionPool::collectUnsignedResult(m_outUnsignedResultPtrs);
*nResults = m_outUnsignedResultPtrs.size();
if (*nResults == 0) {
*results = NULL;
} else {
*results = m_outUnsignedResultPtrs.front();
}
}
err_code_t Client::incr(const char* key, const size_t keyLen, const uint64_t delta,
const bool noreply,
unsigned_result_t** results, size_t* nResults) {
dispatchIncrDecr(INCR_OP, key, keyLen, delta, noreply);
err_code_t rv = waitPoll();
collectUnsignedResult(results, nResults);
return rv;
}
err_code_t Client::decr(const char* key, const size_t keyLen, const uint64_t delta,
const bool noreply,
unsigned_result_t** results, size_t* nResults) {
dispatchIncrDecr(DECR_OP, key, keyLen, delta, noreply);
err_code_t rv = waitPoll();
collectUnsignedResult(results, nResults);
return rv;
}
void Client::destroyUnsignedResult() {
ConnectionPool::reset();
m_outUnsignedResultPtrs.clear();
}
void Client::_sleep(uint32_t seconds) {
usleep(seconds * 1000000);
}
} // namespace mc
} // namespace douban
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "chainparamsbase.h"
#include "clientversion.h"
#include "fs.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include "support/events.h"
#include <univalue.h>
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
static const bool DEFAULT_NAMED=false;
static const int CONTINUE_EXECUTION=-1;
std::string HelpMessageCli()
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
std::string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoin-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] help " + _("List commands") + "\n" +
" bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
}
return CONTINUE_EXECUTION;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host = GetArg("-rpcconnect", DEFAULT_RPCCONNECT);
int port = GetArg("-rpcport", BaseParams().RPCPort());
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
else if (response.status == HTTP_UNAUTHORIZED)
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
if (GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
args.push_back(line);
}
if (args.size() < 1)
throw std::runtime_error("too few parameters (need at least command)");
std::string strMethod = args[0];
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
if(GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
return EXIT_FAILURE;
}
try {
int ret = AppInitRPC(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
}
return ret;
}
<commit_msg>[utils] allow square brackets for ipv6 addresses in bitcoin-cli<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "chainparamsbase.h"
#include "clientversion.h"
#include "fs.h"
#include "utilstrencodings.h"
#include "rpc/client.h"
#include "rpc/protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <event2/buffer.h>
#include <event2/keyvalq_struct.h>
#include "support/events.h"
#include <univalue.h>
static const char DEFAULT_RPCCONNECT[] = "127.0.0.1";
static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900;
static const bool DEFAULT_NAMED=false;
static const int CONTINUE_EXECUTION=-1;
std::string HelpMessageCli()
{
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
std::string strUsage;
strUsage += HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
AppendParamsHelpMessages(strUsage);
strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED));
strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort()));
strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT));
strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)"));
return strUsage;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
//
// Exception thrown on connection error. This error is used to determine
// when to wait if -rpcwait is given.
//
class CConnectionFailed : public std::runtime_error
{
public:
explicit inline CConnectionFailed(const std::string& msg) :
std::runtime_error(msg)
{}
};
//
// This function returns either one of EXIT_ codes when it's expected to stop the process or
// CONTINUE_EXECUTION when it's expected to continue further.
//
static int AppInitRPC(int argc, char* argv[])
{
//
// Parameters
//
ParseParameters(argc, argv);
if (argc<2 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) {
std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n";
if (!IsArgSet("-version")) {
strUsage += "\n" + _("Usage:") + "\n" +
" bitcoin-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" +
" bitcoin-cli [options] help " + _("List commands") + "\n" +
" bitcoin-cli [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessageCli();
}
fprintf(stdout, "%s", strUsage.c_str());
if (argc < 2) {
fprintf(stderr, "Error: too few parameters\n");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (!fs::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str());
return EXIT_FAILURE;
}
try {
ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME));
} catch (const std::exception& e) {
fprintf(stderr,"Error reading configuration file: %s\n", e.what());
return EXIT_FAILURE;
}
// Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause)
try {
SelectBaseParams(ChainNameFromCommandLine());
} catch (const std::exception& e) {
fprintf(stderr, "Error: %s\n", e.what());
return EXIT_FAILURE;
}
if (GetBoolArg("-rpcssl", false))
{
fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n");
return EXIT_FAILURE;
}
return CONTINUE_EXECUTION;
}
/** Reply structure for request_done to fill in */
struct HTTPReply
{
HTTPReply(): status(0), error(-1) {}
int status;
int error;
std::string body;
};
const char *http_errorstring(int code)
{
switch(code) {
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
case EVREQ_HTTP_TIMEOUT:
return "timeout reached";
case EVREQ_HTTP_EOF:
return "EOF reached";
case EVREQ_HTTP_INVALID_HEADER:
return "error while reading header, or invalid header";
case EVREQ_HTTP_BUFFER_ERROR:
return "error encountered while reading or writing";
case EVREQ_HTTP_REQUEST_CANCEL:
return "request was canceled";
case EVREQ_HTTP_DATA_TOO_LONG:
return "response body is larger than allowed";
#endif
default:
return "unknown";
}
}
static void http_request_done(struct evhttp_request *req, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
if (req == NULL) {
/* If req is NULL, it means an error occurred while connecting: the
* error code will have been passed to http_error_cb.
*/
reply->status = 0;
return;
}
reply->status = evhttp_request_get_response_code(req);
struct evbuffer *buf = evhttp_request_get_input_buffer(req);
if (buf)
{
size_t size = evbuffer_get_length(buf);
const char *data = (const char*)evbuffer_pullup(buf, size);
if (data)
reply->body = std::string(data, size);
evbuffer_drain(buf, size);
}
}
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
static void http_error_cb(enum evhttp_request_error err, void *ctx)
{
HTTPReply *reply = static_cast<HTTPReply*>(ctx);
reply->error = err;
}
#endif
UniValue CallRPC(const std::string& strMethod, const UniValue& params)
{
std::string host;
// In preference order, we choose the following for the port:
// 1. -rpcport
// 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6)
// 3. default port for chain
int port = BaseParams().RPCPort();
SplitHostPort(GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host);
port = GetArg("-rpcport", port);
// Obtain event base
raii_event_base base = obtain_event_base();
// Synchronously look up hostname
raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port);
evhttp_connection_set_timeout(evcon.get(), GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT));
HTTPReply response;
raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response);
if (req == NULL)
throw std::runtime_error("create http request failed");
#if LIBEVENT_VERSION_NUMBER >= 0x02010300
evhttp_request_set_error_cb(req.get(), http_error_cb);
#endif
// Get credentials
std::string strRPCUserColonPass;
if (GetArg("-rpcpassword", "") == "") {
// Try fall back to cookie-based authentication if no password is provided
if (!GetAuthCookie(&strRPCUserColonPass)) {
throw std::runtime_error(strprintf(
_("Could not locate RPC credentials. No authentication cookie could be found, and no rpcpassword is set in the configuration file (%s)"),
GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string().c_str()));
}
} else {
strRPCUserColonPass = GetArg("-rpcuser", "") + ":" + GetArg("-rpcpassword", "");
}
struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get());
assert(output_headers);
evhttp_add_header(output_headers, "Host", host.c_str());
evhttp_add_header(output_headers, "Connection", "close");
evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str());
// Attach request data
std::string strRequest = JSONRPCRequestObj(strMethod, params, 1).write() + "\n";
struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get());
assert(output_buffer);
evbuffer_add(output_buffer, strRequest.data(), strRequest.size());
int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, "/");
req.release(); // ownership moved to evcon in above call
if (r != 0) {
throw CConnectionFailed("send http request failed");
}
event_base_dispatch(base.get());
if (response.status == 0)
throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error));
else if (response.status == HTTP_UNAUTHORIZED)
throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR)
throw std::runtime_error(strprintf("server returned HTTP error %d", response.status));
else if (response.body.empty())
throw std::runtime_error("no response from server");
// Parse reply
UniValue valReply(UniValue::VSTR);
if (!valReply.read(response.body))
throw std::runtime_error("couldn't parse reply from server");
const UniValue& reply = valReply.get_obj();
if (reply.empty())
throw std::runtime_error("expected reply to have result, error and id properties");
return reply;
}
int CommandLineRPC(int argc, char *argv[])
{
std::string strPrint;
int nRet = 0;
try {
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0])) {
argc--;
argv++;
}
std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]);
if (GetBoolArg("-stdin", false)) {
// Read one arg per line from stdin and append
std::string line;
while (std::getline(std::cin,line))
args.push_back(line);
}
if (args.size() < 1)
throw std::runtime_error("too few parameters (need at least command)");
std::string strMethod = args[0];
args.erase(args.begin()); // Remove trailing method name from arguments vector
UniValue params;
if(GetBoolArg("-named", DEFAULT_NAMED)) {
params = RPCConvertNamedValues(strMethod, args);
} else {
params = RPCConvertValues(strMethod, args);
}
// Execute and handle connection failures with -rpcwait
const bool fWait = GetBoolArg("-rpcwait", false);
do {
try {
const UniValue reply = CallRPC(strMethod, params);
// Parse reply
const UniValue& result = find_value(reply, "result");
const UniValue& error = find_value(reply, "error");
if (!error.isNull()) {
// Error
int code = error["code"].get_int();
if (fWait && code == RPC_IN_WARMUP)
throw CConnectionFailed("server in warmup");
strPrint = "error: " + error.write();
nRet = abs(code);
if (error.isObject())
{
UniValue errCode = find_value(error, "code");
UniValue errMsg = find_value(error, "message");
strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n";
if (errMsg.isStr())
strPrint += "error message:\n"+errMsg.get_str();
}
} else {
// Result
if (result.isNull())
strPrint = "";
else if (result.isStr())
strPrint = result.get_str();
else
strPrint = result.write(2);
}
// Connection succeeded, no need to retry.
break;
}
catch (const CConnectionFailed&) {
if (fWait)
MilliSleep(1000);
else
throw;
}
} while (fWait);
}
catch (const boost::thread_interrupted&) {
throw;
}
catch (const std::exception& e) {
strPrint = std::string("error: ") + e.what();
nRet = EXIT_FAILURE;
}
catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
throw;
}
if (strPrint != "") {
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
if (!SetupNetworking()) {
fprintf(stderr, "Error: Initializing networking failed\n");
return EXIT_FAILURE;
}
try {
int ret = AppInitRPC(argc, argv);
if (ret != CONTINUE_EXECUTION)
return ret;
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "AppInitRPC()");
return EXIT_FAILURE;
} catch (...) {
PrintExceptionContinue(NULL, "AppInitRPC()");
return EXIT_FAILURE;
}
int ret = EXIT_FAILURE;
try {
ret = CommandLineRPC(argc, argv);
}
catch (const std::exception& e) {
PrintExceptionContinue(&e, "CommandLineRPC()");
} catch (...) {
PrintExceptionContinue(NULL, "CommandLineRPC()");
}
return ret;
}
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2017 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_BOOSTING_RF_H_
#define LIGHTGBM_BOOSTING_RF_H_
#include <LightGBM/boosting.h>
#include <LightGBM/metric.h>
#include <string>
#include <cstdio>
#include <fstream>
#include <memory>
#include <utility>
#include <vector>
#include "gbdt.h"
#include "score_updater.hpp"
namespace LightGBM {
/*!
* \brief Rondom Forest implementation
*/
class RF : public GBDT {
public:
RF() : GBDT() {
average_output_ = true;
}
~RF() {}
void Init(const Config* config, const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override {
CHECK(config->bagging_freq > 0 && config->bagging_fraction < 1.0f && config->bagging_fraction > 0.0f);
CHECK(config->feature_fraction <= 1.0f && config->feature_fraction > 0.0f);
GBDT::Init(config, train_data, objective_function, training_metrics);
if (num_init_iteration_ > 0) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
MultiplyScore(cur_tree_id, 1.0f / num_init_iteration_);
}
} else {
CHECK_EQ(train_data->metadata().init_score(), nullptr);
}
CHECK_EQ(num_tree_per_iteration_, num_class_);
// not shrinkage rate for the RF
shrinkage_rate_ = 1.0f;
// only boosting one time
Boosting();
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
tmp_grad_.resize(num_data_);
tmp_hess_.resize(num_data_);
}
}
void ResetConfig(const Config* config) override {
CHECK(config->bagging_freq > 0 && config->bagging_fraction < 1.0f && config->bagging_fraction > 0.0f);
CHECK(config->feature_fraction <= 1.0f && config->feature_fraction > 0.0f);
GBDT::ResetConfig(config);
// not shrinkage rate for the RF
shrinkage_rate_ = 1.0f;
}
void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override {
GBDT::ResetTrainingData(train_data, objective_function, training_metrics);
if (iter_ + num_init_iteration_ > 0) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
train_score_updater_->MultiplyScore(1.0f / (iter_ + num_init_iteration_), cur_tree_id);
}
}
CHECK_EQ(num_tree_per_iteration_, num_class_);
// only boosting one time
Boosting();
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
tmp_grad_.resize(num_data_);
tmp_hess_.resize(num_data_);
}
}
void Boosting() override {
if (objective_function_ == nullptr) {
Log::Fatal("RF mode do not support custom objective function, please use built-in objectives.");
}
init_scores_.resize(num_tree_per_iteration_, 0.0);
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
init_scores_[cur_tree_id] = BoostFromAverage(cur_tree_id, false);
}
size_t total_size = static_cast<size_t>(num_data_) * num_tree_per_iteration_;
std::vector<double> tmp_scores(total_size, 0.0f);
#pragma omp parallel for schedule(static)
for (int j = 0; j < num_tree_per_iteration_; ++j) {
size_t offset = static_cast<size_t>(j)* num_data_;
for (data_size_t i = 0; i < num_data_; ++i) {
tmp_scores[offset + i] = init_scores_[j];
}
}
objective_function_->
GetGradients(tmp_scores.data(), gradients_.data(), hessians_.data());
}
bool TrainOneIter(const score_t* gradients, const score_t* hessians) override {
// bagging logic
Bagging(iter_);
CHECK_EQ(gradients, nullptr);
CHECK_EQ(hessians, nullptr);
gradients = gradients_.data();
hessians = hessians_.data();
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
std::unique_ptr<Tree> new_tree(new Tree(2, false));
size_t offset = static_cast<size_t>(cur_tree_id)* num_data_;
if (class_need_train_[cur_tree_id]) {
auto grad = gradients + offset;
auto hess = hessians + offset;
// need to copy gradients for bagging subset.
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
for (int i = 0; i < bag_data_cnt_; ++i) {
tmp_grad_[i] = grad[bag_data_indices_[i]];
tmp_hess_[i] = hess[bag_data_indices_[i]];
}
grad = tmp_grad_.data();
hess = tmp_hess_.data();
}
new_tree.reset(tree_learner_->Train(grad, hess));
}
if (new_tree->num_leaves() > 1) {
double pred = init_scores_[cur_tree_id];
auto residual_getter = [pred](const label_t* label, int i) {return static_cast<double>(label[i]) - pred; };
tree_learner_->RenewTreeOutput(new_tree.get(), objective_function_, residual_getter,
num_data_, bag_data_indices_.data(), bag_data_cnt_);
if (std::fabs(init_scores_[cur_tree_id]) > kEpsilon) {
new_tree->AddBias(init_scores_[cur_tree_id]);
}
// update score
MultiplyScore(cur_tree_id, (iter_ + num_init_iteration_));
UpdateScore(new_tree.get(), cur_tree_id);
MultiplyScore(cur_tree_id, 1.0 / (iter_ + num_init_iteration_ + 1));
} else {
// only add default score one-time
if (models_.size() < static_cast<size_t>(num_tree_per_iteration_)) {
double output = 0.0;
if (!class_need_train_[cur_tree_id]) {
if (objective_function_ != nullptr) {
output = objective_function_->BoostFromScore(cur_tree_id);
} else {
output = init_scores_[cur_tree_id];
}
}
new_tree->AsConstantTree(output);
MultiplyScore(cur_tree_id, (iter_ + num_init_iteration_));
UpdateScore(new_tree.get(), cur_tree_id);
MultiplyScore(cur_tree_id, 1.0 / (iter_ + num_init_iteration_ + 1));
}
}
// add model
models_.push_back(std::move(new_tree));
}
++iter_;
return false;
}
void RollbackOneIter() override {
if (iter_ <= 0) { return; }
int cur_iter = iter_ + num_init_iteration_ - 1;
// reset score
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
auto curr_tree = cur_iter * num_tree_per_iteration_ + cur_tree_id;
models_[curr_tree]->Shrinkage(-1.0);
MultiplyScore(cur_tree_id, (iter_ + num_init_iteration_));
train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
for (auto& score_updater : valid_score_updater_) {
score_updater->AddScore(models_[curr_tree].get(), cur_tree_id);
}
MultiplyScore(cur_tree_id, 1.0f / (iter_ + num_init_iteration_ - 1));
}
// remove model
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
models_.pop_back();
}
--iter_;
}
void MultiplyScore(const int cur_tree_id, double val) {
train_score_updater_->MultiplyScore(val, cur_tree_id);
for (auto& score_updater : valid_score_updater_) {
score_updater->MultiplyScore(val, cur_tree_id);
}
}
void AddValidDataset(const Dataset* valid_data,
const std::vector<const Metric*>& valid_metrics) override {
GBDT::AddValidDataset(valid_data, valid_metrics);
if (iter_ + num_init_iteration_ > 0) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
valid_score_updater_.back()->MultiplyScore(1.0f / (iter_ + num_init_iteration_), cur_tree_id);
}
}
}
bool NeedAccuratePrediction() const override {
// No early stopping for prediction
return true;
};
private:
std::vector<score_t> tmp_grad_;
std::vector<score_t> tmp_hess_;
std::vector<double> init_scores_;
};
} // namespace LightGBM
#endif // LIGHTGBM_BOOSTING_RF_H_
<commit_msg>typo fix (#3174)<commit_after>/*!
* Copyright (c) 2017 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_BOOSTING_RF_H_
#define LIGHTGBM_BOOSTING_RF_H_
#include <LightGBM/boosting.h>
#include <LightGBM/metric.h>
#include <string>
#include <cstdio>
#include <fstream>
#include <memory>
#include <utility>
#include <vector>
#include "gbdt.h"
#include "score_updater.hpp"
namespace LightGBM {
/*!
* \brief Random Forest implementation
*/
class RF : public GBDT {
public:
RF() : GBDT() {
average_output_ = true;
}
~RF() {}
void Init(const Config* config, const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override {
CHECK(config->bagging_freq > 0 && config->bagging_fraction < 1.0f && config->bagging_fraction > 0.0f);
CHECK(config->feature_fraction <= 1.0f && config->feature_fraction > 0.0f);
GBDT::Init(config, train_data, objective_function, training_metrics);
if (num_init_iteration_ > 0) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
MultiplyScore(cur_tree_id, 1.0f / num_init_iteration_);
}
} else {
CHECK_EQ(train_data->metadata().init_score(), nullptr);
}
CHECK_EQ(num_tree_per_iteration_, num_class_);
// not shrinkage rate for the RF
shrinkage_rate_ = 1.0f;
// only boosting one time
Boosting();
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
tmp_grad_.resize(num_data_);
tmp_hess_.resize(num_data_);
}
}
void ResetConfig(const Config* config) override {
CHECK(config->bagging_freq > 0 && config->bagging_fraction < 1.0f && config->bagging_fraction > 0.0f);
CHECK(config->feature_fraction <= 1.0f && config->feature_fraction > 0.0f);
GBDT::ResetConfig(config);
// not shrinkage rate for the RF
shrinkage_rate_ = 1.0f;
}
void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function,
const std::vector<const Metric*>& training_metrics) override {
GBDT::ResetTrainingData(train_data, objective_function, training_metrics);
if (iter_ + num_init_iteration_ > 0) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
train_score_updater_->MultiplyScore(1.0f / (iter_ + num_init_iteration_), cur_tree_id);
}
}
CHECK_EQ(num_tree_per_iteration_, num_class_);
// only boosting one time
Boosting();
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
tmp_grad_.resize(num_data_);
tmp_hess_.resize(num_data_);
}
}
void Boosting() override {
if (objective_function_ == nullptr) {
Log::Fatal("RF mode do not support custom objective function, please use built-in objectives.");
}
init_scores_.resize(num_tree_per_iteration_, 0.0);
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
init_scores_[cur_tree_id] = BoostFromAverage(cur_tree_id, false);
}
size_t total_size = static_cast<size_t>(num_data_) * num_tree_per_iteration_;
std::vector<double> tmp_scores(total_size, 0.0f);
#pragma omp parallel for schedule(static)
for (int j = 0; j < num_tree_per_iteration_; ++j) {
size_t offset = static_cast<size_t>(j)* num_data_;
for (data_size_t i = 0; i < num_data_; ++i) {
tmp_scores[offset + i] = init_scores_[j];
}
}
objective_function_->
GetGradients(tmp_scores.data(), gradients_.data(), hessians_.data());
}
bool TrainOneIter(const score_t* gradients, const score_t* hessians) override {
// bagging logic
Bagging(iter_);
CHECK_EQ(gradients, nullptr);
CHECK_EQ(hessians, nullptr);
gradients = gradients_.data();
hessians = hessians_.data();
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
std::unique_ptr<Tree> new_tree(new Tree(2, false));
size_t offset = static_cast<size_t>(cur_tree_id)* num_data_;
if (class_need_train_[cur_tree_id]) {
auto grad = gradients + offset;
auto hess = hessians + offset;
// need to copy gradients for bagging subset.
if (is_use_subset_ && bag_data_cnt_ < num_data_) {
for (int i = 0; i < bag_data_cnt_; ++i) {
tmp_grad_[i] = grad[bag_data_indices_[i]];
tmp_hess_[i] = hess[bag_data_indices_[i]];
}
grad = tmp_grad_.data();
hess = tmp_hess_.data();
}
new_tree.reset(tree_learner_->Train(grad, hess));
}
if (new_tree->num_leaves() > 1) {
double pred = init_scores_[cur_tree_id];
auto residual_getter = [pred](const label_t* label, int i) {return static_cast<double>(label[i]) - pred; };
tree_learner_->RenewTreeOutput(new_tree.get(), objective_function_, residual_getter,
num_data_, bag_data_indices_.data(), bag_data_cnt_);
if (std::fabs(init_scores_[cur_tree_id]) > kEpsilon) {
new_tree->AddBias(init_scores_[cur_tree_id]);
}
// update score
MultiplyScore(cur_tree_id, (iter_ + num_init_iteration_));
UpdateScore(new_tree.get(), cur_tree_id);
MultiplyScore(cur_tree_id, 1.0 / (iter_ + num_init_iteration_ + 1));
} else {
// only add default score one-time
if (models_.size() < static_cast<size_t>(num_tree_per_iteration_)) {
double output = 0.0;
if (!class_need_train_[cur_tree_id]) {
if (objective_function_ != nullptr) {
output = objective_function_->BoostFromScore(cur_tree_id);
} else {
output = init_scores_[cur_tree_id];
}
}
new_tree->AsConstantTree(output);
MultiplyScore(cur_tree_id, (iter_ + num_init_iteration_));
UpdateScore(new_tree.get(), cur_tree_id);
MultiplyScore(cur_tree_id, 1.0 / (iter_ + num_init_iteration_ + 1));
}
}
// add model
models_.push_back(std::move(new_tree));
}
++iter_;
return false;
}
void RollbackOneIter() override {
if (iter_ <= 0) { return; }
int cur_iter = iter_ + num_init_iteration_ - 1;
// reset score
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
auto curr_tree = cur_iter * num_tree_per_iteration_ + cur_tree_id;
models_[curr_tree]->Shrinkage(-1.0);
MultiplyScore(cur_tree_id, (iter_ + num_init_iteration_));
train_score_updater_->AddScore(models_[curr_tree].get(), cur_tree_id);
for (auto& score_updater : valid_score_updater_) {
score_updater->AddScore(models_[curr_tree].get(), cur_tree_id);
}
MultiplyScore(cur_tree_id, 1.0f / (iter_ + num_init_iteration_ - 1));
}
// remove model
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
models_.pop_back();
}
--iter_;
}
void MultiplyScore(const int cur_tree_id, double val) {
train_score_updater_->MultiplyScore(val, cur_tree_id);
for (auto& score_updater : valid_score_updater_) {
score_updater->MultiplyScore(val, cur_tree_id);
}
}
void AddValidDataset(const Dataset* valid_data,
const std::vector<const Metric*>& valid_metrics) override {
GBDT::AddValidDataset(valid_data, valid_metrics);
if (iter_ + num_init_iteration_ > 0) {
for (int cur_tree_id = 0; cur_tree_id < num_tree_per_iteration_; ++cur_tree_id) {
valid_score_updater_.back()->MultiplyScore(1.0f / (iter_ + num_init_iteration_), cur_tree_id);
}
}
}
bool NeedAccuratePrediction() const override {
// No early stopping for prediction
return true;
};
private:
std::vector<score_t> tmp_grad_;
std::vector<score_t> tmp_hess_;
std::vector<double> init_scores_;
};
} // namespace LightGBM
#endif // LIGHTGBM_BOOSTING_RF_H_
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplicationFactory.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbGridResampleImageFilter.h"
#include "otbImportGeoInformationImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbPleiadesPToXSAffineTransformCalculator.h"
namespace otb
{
enum
{
Interpolator_BCO,
Interpolator_NNeighbor,
Interpolator_Linear
};
namespace Wrapper
{
class Superimpose : public Application
{
public:
/** Standard class typedefs. */
typedef Superimpose Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Superimpose, Application);
typedef unsigned short int PixelType;
typedef itk::LinearInterpolateImageFunction
<FloatVectorImageType,
double> LinInterpolatorType;
typedef itk::NearestNeighborInterpolateImageFunction
<FloatVectorImageType,
double> NNInterpolatorType;
typedef otb::BCOInterpolateImageFunction
<FloatVectorImageType> BCOInterpolatorType;
typedef otb::GenericRSResampleImageFilter<FloatVectorImageType,
FloatVectorImageType> ResamplerType;
typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,
FloatVectorImageType> ImportGeoInformationFilterType;
typedef itk::ScalableAffineTransform<double, 2> TransformType;
typedef otb::GridResampleImageFilter
<FloatVectorImageType,
FloatVectorImageType> BasicResamplerType;
private:
void DoInit() ITK_OVERRIDE
{
SetName("Superimpose");
SetDescription("Using available image metadata, project one image onto another one");
// Documentation
SetDocName("Superimpose sensor");
SetDocLongDescription("This application performs the projection of an image into the geometry of another one.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag("Superimposition");
AddParameter(ParameterType_InputImage, "inr", "Reference input");
SetParameterDescription("inr","The input reference image.");
AddParameter(ParameterType_InputImage, "inm", "The image to reproject");
SetParameterDescription("inm","The image to reproject into the geometry of the reference input.");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field");
SetParameterDescription("lms","Generate a coarser deformation field with the given spacing");
SetDefaultParameterFloat("lms", 4.);
MandatoryOff("lms");
AddParameter(ParameterType_OutputImage, "out", "Output image");
SetParameterDescription("out","Output reprojected image.");
// Superposition mode
AddParameter(ParameterType_Choice,"mode", "Mode");
SetParameterDescription("mode", "Superimposition mode");
AddChoice("mode.default", "Default mode");
SetParameterDescription("mode.default", "Default superimposition mode : "
"uses any projection reference or sensor model found in the images");
AddChoice("mode.phr", "Pleiades mode");
SetParameterDescription("mode.phr", "Pleiades superimposition mode, "
"designed for the case of a P+XS bundle in SENSOR geometry. It uses"
" a simple transform on the XS image : a scaling and a residual "
"translation.");
// Interpolators
AddParameter(ParameterType_Choice, "interpolator", "Interpolation");
SetParameterDescription("interpolator","This group of parameters allows defining how the input image will be interpolated during resampling.");
AddChoice("interpolator.bco", "Bicubic interpolation");
SetParameterDescription("interpolator.bco", "Bicubic interpolation leads to very good image quality but is slow.");
AddParameter(ParameterType_Radius, "interpolator.bco.radius", "Radius for bicubic interpolation");
SetParameterDescription("interpolator.bco.radius","This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.");
SetDefaultParameterInt("interpolator.bco.radius", 2);
AddChoice("interpolator.nn", "Nearest Neighbor interpolation");
SetParameterDescription("interpolator.nn","Nearest neighbor interpolation leads to poor image quality, but it is very fast.");
AddChoice("interpolator.linear", "Linear interpolation");
SetParameterDescription("interpolator.linear","Linear interpolation leads to average image quality but is quite fast");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif");
}
void DoUpdateParameters() ITK_OVERRIDE
{
if(!HasUserValue("mode") && HasValue("inr") && HasValue("inm") && otb::PleiadesPToXSAffineTransformCalculator::CanCompute(GetParameterImage("inr"),GetParameterImage("inm")))
{
otbAppLogWARNING("Forcing PHR mode with PHR data. You need to add \"-mode default\" to force the default mode with PHR images.");
SetParameterString("mode","phr");
}
}
void DoExecute() ITK_OVERRIDE
{
// Get the inputs
FloatVectorImageType* refImage = GetParameterImage("inr");
FloatVectorImageType* movingImage = GetParameterImage("inm");
// Resample filter
m_Resampler = ResamplerType::New();
m_BasicResampler = BasicResamplerType::New();
m_GeoImport = ImportGeoInformationFilterType::New();
// Get Interpolator
switch ( GetParameterInt("interpolator") )
{
case Interpolator_Linear:
{
LinInterpolatorType::Pointer interpolator = LinInterpolatorType::New();
m_Resampler->SetInterpolator(interpolator);
m_BasicResampler->SetInterpolator(interpolator);
}
break;
case Interpolator_NNeighbor:
{
NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New();
m_Resampler->SetInterpolator(interpolator);
m_BasicResampler->SetInterpolator(interpolator);
}
break;
case Interpolator_BCO:
{
BCOInterpolatorType::Pointer interpolator = BCOInterpolatorType::New();
interpolator->SetRadius(GetParameterInt("interpolator.bco.radius"));
m_Resampler->SetInterpolator(interpolator);
m_BasicResampler->SetInterpolator(interpolator);
}
break;
}
// Setup the DEM Handler
otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image information
FloatVectorImageType::SpacingType spacing = refImage->GetSpacing();
FloatVectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex();
FloatVectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize();
FloatVectorImageType::PointType origin = refImage->GetOrigin();
FloatVectorImageType::PixelType defaultValue;
itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, movingImage->GetNumberOfComponentsPerPixel());
if(GetParameterString("mode")=="default")
{
if(IsParameterEnabled("lms"))
{
float defScalarSpacing = vcl_abs(GetParameterFloat("lms"));
otbAppLogDEBUG("Generating coarse deformation field (spacing="<<defScalarSpacing<<")");
FloatVectorImageType::SpacingType defSpacing;
defSpacing[0] = defScalarSpacing;
defSpacing[1] = defScalarSpacing;
if (spacing[0]<0.0) defSpacing[0] *= -1.0;
if (spacing[1]<0.0) defSpacing[1] *= -1.0;
m_Resampler->SetDisplacementFieldSpacing(defSpacing);
}
// Setup transform through projRef and Keywordlist
m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist());
m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef());
m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());
m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());
m_Resampler->SetInput(movingImage);
m_Resampler->SetOutputOrigin(origin);
m_Resampler->SetOutputSpacing(spacing);
m_Resampler->SetOutputSize(size);
m_Resampler->SetOutputStartIndex(start);
m_Resampler->SetEdgePaddingValue(defaultValue);
// Set the output image
SetParameterOutputImage("out", m_Resampler->GetOutput());
}
else if(GetParameterString("mode")=="phr")
{
otbAppLogINFO("Using the PHR mode");
otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset
= otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(GetParameterImage("inr"),
GetParameterImage("inm"));
m_BasicResampler->SetInput(movingImage);
origin+=offset;
origin[0]=origin[0]/4;
origin[1]=origin[1]/4;
m_BasicResampler->SetOutputOrigin(origin);
FloatVectorImageType::SpacingType xsSpacing = GetParameterImage("inm")->GetSpacing();
xsSpacing*=0.25;
m_BasicResampler->SetOutputSpacing(xsSpacing);
m_BasicResampler->SetOutputSize(size);
m_Resampler->SetOutputStartIndex(start);
m_BasicResampler->SetEdgePaddingValue(defaultValue);
m_GeoImport->SetInput(m_BasicResampler->GetOutput());
m_GeoImport->SetSource(refImage);
// Set the output image
SetParameterOutputImage("out", m_GeoImport->GetOutput());
}
else
{
otbAppLogWARNING("Unknown mode");
}
}
ResamplerType::Pointer m_Resampler;
BasicResamplerType::Pointer m_BasicResampler;
ImportGeoInformationFilterType::Pointer m_GeoImport;
};
} // end namespace Wrapper
} // end namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)
<commit_msg>BUG: Mantis-1328: add fill value parameter in Superimpose<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplicationFactory.h"
#include "otbGenericRSResampleImageFilter.h"
#include "otbGridResampleImageFilter.h"
#include "otbImportGeoInformationImageFilter.h"
#include "otbBCOInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
// Elevation handler
#include "otbWrapperElevationParametersHandler.h"
#include "otbPleiadesPToXSAffineTransformCalculator.h"
namespace otb
{
enum
{
Interpolator_BCO,
Interpolator_NNeighbor,
Interpolator_Linear
};
namespace Wrapper
{
class Superimpose : public Application
{
public:
/** Standard class typedefs. */
typedef Superimpose Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Superimpose, Application);
typedef unsigned short int PixelType;
typedef itk::LinearInterpolateImageFunction
<FloatVectorImageType,
double> LinInterpolatorType;
typedef itk::NearestNeighborInterpolateImageFunction
<FloatVectorImageType,
double> NNInterpolatorType;
typedef otb::BCOInterpolateImageFunction
<FloatVectorImageType> BCOInterpolatorType;
typedef otb::GenericRSResampleImageFilter<FloatVectorImageType,
FloatVectorImageType> ResamplerType;
typedef otb::ImportGeoInformationImageFilter<FloatVectorImageType,
FloatVectorImageType> ImportGeoInformationFilterType;
typedef itk::ScalableAffineTransform<double, 2> TransformType;
typedef otb::GridResampleImageFilter
<FloatVectorImageType,
FloatVectorImageType> BasicResamplerType;
private:
void DoInit() ITK_OVERRIDE
{
SetName("Superimpose");
SetDescription("Using available image metadata, project one image onto another one");
// Documentation
SetDocName("Superimpose sensor");
SetDocLongDescription("This application performs the projection of an image into the geometry of another one.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag("Superimposition");
AddParameter(ParameterType_InputImage, "inr", "Reference input");
SetParameterDescription("inr","The input reference image.");
AddParameter(ParameterType_InputImage, "inm", "The image to reproject");
SetParameterDescription("inm","The image to reproject into the geometry of the reference input.");
// Elevation
ElevationParametersHandler::AddElevationParameters(this, "elev");
AddParameter(ParameterType_Float, "lms", "Spacing of the deformation field");
SetParameterDescription("lms","Generate a coarser deformation field with the given spacing");
SetDefaultParameterFloat("lms", 4.);
MandatoryOff("lms");
AddParameter(ParameterType_Float, "fv", "Fill Value");
SetParameterDescription("fv","Fill value for area outside the reprojected image");
SetDefaultParameterFloat("fv", 0.);
MandatoryOff("fv");
AddParameter(ParameterType_OutputImage, "out", "Output image");
SetParameterDescription("out","Output reprojected image.");
// Superposition mode
AddParameter(ParameterType_Choice,"mode", "Mode");
SetParameterDescription("mode", "Superimposition mode");
AddChoice("mode.default", "Default mode");
SetParameterDescription("mode.default", "Default superimposition mode : "
"uses any projection reference or sensor model found in the images");
AddChoice("mode.phr", "Pleiades mode");
SetParameterDescription("mode.phr", "Pleiades superimposition mode, "
"designed for the case of a P+XS bundle in SENSOR geometry. It uses"
" a simple transform on the XS image : a scaling and a residual "
"translation.");
// Interpolators
AddParameter(ParameterType_Choice, "interpolator", "Interpolation");
SetParameterDescription("interpolator","This group of parameters allows defining how the input image will be interpolated during resampling.");
AddChoice("interpolator.bco", "Bicubic interpolation");
SetParameterDescription("interpolator.bco", "Bicubic interpolation leads to very good image quality but is slow.");
AddParameter(ParameterType_Radius, "interpolator.bco.radius", "Radius for bicubic interpolation");
SetParameterDescription("interpolator.bco.radius","This parameter allows controlling the size of the bicubic interpolation filter. If the target pixel size is higher than the input pixel size, increasing this parameter will reduce aliasing artifacts.");
SetDefaultParameterInt("interpolator.bco.radius", 2);
AddChoice("interpolator.nn", "Nearest Neighbor interpolation");
SetParameterDescription("interpolator.nn","Nearest neighbor interpolation leads to poor image quality, but it is very fast.");
AddChoice("interpolator.linear", "Linear interpolation");
SetParameterDescription("interpolator.linear","Linear interpolation leads to average image quality but is quite fast");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("inr", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inm", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "SuperimposedXS_to_PAN.tif");
}
void DoUpdateParameters() ITK_OVERRIDE
{
if(!HasUserValue("mode") && HasValue("inr") && HasValue("inm") && otb::PleiadesPToXSAffineTransformCalculator::CanCompute(GetParameterImage("inr"),GetParameterImage("inm")))
{
otbAppLogWARNING("Forcing PHR mode with PHR data. You need to add \"-mode default\" to force the default mode with PHR images.");
SetParameterString("mode","phr");
}
}
void DoExecute() ITK_OVERRIDE
{
// Get the inputs
FloatVectorImageType* refImage = GetParameterImage("inr");
FloatVectorImageType* movingImage = GetParameterImage("inm");
// Resample filter
m_Resampler = ResamplerType::New();
m_BasicResampler = BasicResamplerType::New();
m_GeoImport = ImportGeoInformationFilterType::New();
// Get Interpolator
switch ( GetParameterInt("interpolator") )
{
case Interpolator_Linear:
{
LinInterpolatorType::Pointer interpolator = LinInterpolatorType::New();
m_Resampler->SetInterpolator(interpolator);
m_BasicResampler->SetInterpolator(interpolator);
}
break;
case Interpolator_NNeighbor:
{
NNInterpolatorType::Pointer interpolator = NNInterpolatorType::New();
m_Resampler->SetInterpolator(interpolator);
m_BasicResampler->SetInterpolator(interpolator);
}
break;
case Interpolator_BCO:
{
BCOInterpolatorType::Pointer interpolator = BCOInterpolatorType::New();
interpolator->SetRadius(GetParameterInt("interpolator.bco.radius"));
m_Resampler->SetInterpolator(interpolator);
m_BasicResampler->SetInterpolator(interpolator);
}
break;
}
// Setup the DEM Handler
otb::Wrapper::ElevationParametersHandler::SetupDEMHandlerFromElevationParameters(this,"elev");
// Set up output image information
FloatVectorImageType::SpacingType spacing = refImage->GetSpacing();
FloatVectorImageType::IndexType start = refImage->GetLargestPossibleRegion().GetIndex();
FloatVectorImageType::SizeType size = refImage->GetLargestPossibleRegion().GetSize();
FloatVectorImageType::PointType origin = refImage->GetOrigin();
FloatVectorImageType::PixelType defaultValue;
itk::NumericTraits<FloatVectorImageType::PixelType>::SetLength(defaultValue, movingImage->GetNumberOfComponentsPerPixel());
defaultValue.Fill(GetParameterFloat("fv"));
if(GetParameterString("mode")=="default")
{
if(IsParameterEnabled("lms"))
{
float defScalarSpacing = vcl_abs(GetParameterFloat("lms"));
otbAppLogDEBUG("Generating coarse deformation field (spacing="<<defScalarSpacing<<")");
FloatVectorImageType::SpacingType defSpacing;
defSpacing[0] = defScalarSpacing;
defSpacing[1] = defScalarSpacing;
if (spacing[0]<0.0) defSpacing[0] *= -1.0;
if (spacing[1]<0.0) defSpacing[1] *= -1.0;
m_Resampler->SetDisplacementFieldSpacing(defSpacing);
}
// Setup transform through projRef and Keywordlist
m_Resampler->SetInputKeywordList(movingImage->GetImageKeywordlist());
m_Resampler->SetInputProjectionRef(movingImage->GetProjectionRef());
m_Resampler->SetOutputKeywordList(refImage->GetImageKeywordlist());
m_Resampler->SetOutputProjectionRef(refImage->GetProjectionRef());
m_Resampler->SetInput(movingImage);
m_Resampler->SetOutputOrigin(origin);
m_Resampler->SetOutputSpacing(spacing);
m_Resampler->SetOutputSize(size);
m_Resampler->SetOutputStartIndex(start);
m_Resampler->SetEdgePaddingValue(defaultValue);
// Set the output image
SetParameterOutputImage("out", m_Resampler->GetOutput());
}
else if(GetParameterString("mode")=="phr")
{
otbAppLogINFO("Using the PHR mode");
otb::PleiadesPToXSAffineTransformCalculator::TransformType::OffsetType offset
= otb::PleiadesPToXSAffineTransformCalculator::ComputeOffset(GetParameterImage("inr"),
GetParameterImage("inm"));
m_BasicResampler->SetInput(movingImage);
origin+=offset;
origin[0]=origin[0]/4;
origin[1]=origin[1]/4;
m_BasicResampler->SetOutputOrigin(origin);
FloatVectorImageType::SpacingType xsSpacing = GetParameterImage("inm")->GetSpacing();
xsSpacing*=0.25;
m_BasicResampler->SetOutputSpacing(xsSpacing);
m_BasicResampler->SetOutputSize(size);
m_Resampler->SetOutputStartIndex(start);
m_BasicResampler->SetEdgePaddingValue(defaultValue);
m_GeoImport->SetInput(m_BasicResampler->GetOutput());
m_GeoImport->SetSource(refImage);
// Set the output image
SetParameterOutputImage("out", m_GeoImport->GetOutput());
}
else
{
otbAppLogWARNING("Unknown mode");
}
}
ResamplerType::Pointer m_Resampler;
BasicResamplerType::Pointer m_BasicResampler;
ImportGeoInformationFilterType::Pointer m_GeoImport;
};
} // end namespace Wrapper
} // end namespace otb
OTB_APPLICATION_EXPORT(otb::Wrapper::Superimpose)
<|endoftext|>
|
<commit_before>#include "Editor.h"
Editor::Editor() {
mode_ = MODE_NOTHING;
}
void Editor::DrawHandle(Vector pos) {
glPushMatrix();
glTranslatef(pos.i, pos.j, 0);
glBegin(GL_POLYGON);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.03 * cos(ang), 0.03 * sin(ang));
}
glEnd();
glBegin(GL_LINE_LOOP);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.2 * cos(ang), 0.2 * sin(ang));
}
glEnd();
glPopMatrix();
}
Vector Editor::AdjustedMousePos() {
if(Key::I().Pressed(GLFW_KEY_LSHIFT) ||
Key::I().Pressed(GLFW_KEY_RSHIFT)) {
Vector new_pos = Mouse::I().WorldPos();
new_pos.i = floor(new_pos.i + 0.5);
new_pos.j = floor(new_pos.j + 0.5);
return new_pos;
} else {
return Mouse::I().WorldPos();
}
}
void Editor::Update() {
if(mode_ == MODE_NOTHING) {
if(Mouse::I().Pressed(0)) {
for(size_t i=0; i<objects_.size()&&mode_==MODE_NOTHING; ++i) {
for(size_t p=0; p<objects_[i]->NumPoints(); ++p) {
if((objects_[i]->Point(p) - Mouse::I().WorldPos()).Len() < 0.2) {
held_obj = objects_[i];
held_pt = p;
mode_ = MODE_MOVE_POINT;
break;
}
}
}
} else if(Mouse::I().Pressed(1)) {
pan_start_ = Mouse::I().WorldPos();
mode_ = MODE_PAN;
} else if(Key::I().Pressed('F')) {
mode_ = MODE_ADD_FLOOR_1;
} else if(Key::I().Pressed('W')) {
mode_ = MODE_ADD_WALL_1;
}
} else if(mode_ == MODE_MOVE_POINT) {
if(!Mouse::I().Pressed(0)) {
mode_ = MODE_NOTHING;
} else {
held_obj->Point(held_pt) = AdjustedMousePos();
}
} else if(mode_ == MODE_PAN) {
if(!Mouse::I().Pressed(1)) {
mode_ = MODE_NOTHING;
} else {
cam_pos_ += pan_start_ - Mouse::I().WorldPos();
}
} else if(mode_ == MODE_ADD_FLOOR_1) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
store_pt_ = AdjustedMousePos();
mode_ = MODE_ADD_FLOOR_2;
}
} else if(mode_ == MODE_ADD_FLOOR_2) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
objects_.push_back(new Floor(store_pt_, AdjustedMousePos()));
mode_ = MODE_NOTHING;
}
} else if(mode_ == MODE_ADD_WALL_1) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
store_pt_ = AdjustedMousePos();
mode_ = MODE_ADD_WALL_2;
}
} else if(mode_ == MODE_ADD_WALL_2) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
objects_.push_back(new Wall(store_pt_, AdjustedMousePos()));
mode_ = MODE_NOTHING;
}
}
}
void Editor::Draw() {
Cam::I().SetPos(cam_pos_);
for(size_t i=0; i<objects_.size(); ++i) {
objects_[i]->Draw();
for(size_t p=0; p<objects_[i]->NumPoints(); ++p) {
DrawHandle(objects_[i]->Point(p));
}
}
glColor3f(0, 0, 0);
if(mode_ == MODE_ADD_FLOOR_1) {
DrawHandle(AdjustedMousePos());
} else if(mode_ == MODE_ADD_FLOOR_2) {
Floor(store_pt_, AdjustedMousePos()).Draw();
DrawHandle(AdjustedMousePos());
} else if(mode_ == MODE_ADD_WALL_1) {
DrawHandle(AdjustedMousePos());
} else if(mode_ == MODE_ADD_WALL_2) {
Wall(store_pt_, AdjustedMousePos()).Draw();
DrawHandle(AdjustedMousePos());
}
}
<commit_msg>Make objects update upon being placed and created<commit_after>#include "Editor.h"
Editor::Editor() {
mode_ = MODE_NOTHING;
}
void Editor::DrawHandle(Vector pos) {
glPushMatrix();
glTranslatef(pos.i, pos.j, 0);
glBegin(GL_POLYGON);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.03 * cos(ang), 0.03 * sin(ang));
}
glEnd();
glBegin(GL_LINE_LOOP);
for(float ang = 0; ang < 2*M_PI; ang += M_PI/8) {
glVertex2f(0.2 * cos(ang), 0.2 * sin(ang));
}
glEnd();
glPopMatrix();
}
Vector Editor::AdjustedMousePos() {
if(Key::I().Pressed(GLFW_KEY_LSHIFT) ||
Key::I().Pressed(GLFW_KEY_RSHIFT)) {
Vector new_pos = Mouse::I().WorldPos();
new_pos.i = floor(new_pos.i + 0.5);
new_pos.j = floor(new_pos.j + 0.5);
return new_pos;
} else {
return Mouse::I().WorldPos();
}
}
void Editor::Update() {
if(mode_ == MODE_NOTHING) {
if(Mouse::I().Pressed(0)) {
for(size_t i=0; i<objects_.size()&&mode_==MODE_NOTHING; ++i) {
for(size_t p=0; p<objects_[i]->NumPoints(); ++p) {
if((objects_[i]->Point(p) - Mouse::I().WorldPos()).Len() < 0.2) {
held_obj = objects_[i];
held_pt = p;
mode_ = MODE_MOVE_POINT;
break;
}
}
}
} else if(Mouse::I().Pressed(1)) {
pan_start_ = Mouse::I().WorldPos();
mode_ = MODE_PAN;
} else if(Key::I().Pressed('F')) {
mode_ = MODE_ADD_FLOOR_1;
} else if(Key::I().Pressed('W')) {
mode_ = MODE_ADD_WALL_1;
}
} else if(mode_ == MODE_MOVE_POINT) {
if(!Mouse::I().Pressed(0)) {
mode_ = MODE_NOTHING;
held_obj->Update();
} else {
held_obj->Point(held_pt) = AdjustedMousePos();
}
} else if(mode_ == MODE_PAN) {
if(!Mouse::I().Pressed(1)) {
mode_ = MODE_NOTHING;
} else {
cam_pos_ += pan_start_ - Mouse::I().WorldPos();
}
} else if(mode_ == MODE_ADD_FLOOR_1) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
store_pt_ = AdjustedMousePos();
mode_ = MODE_ADD_FLOOR_2;
}
} else if(mode_ == MODE_ADD_FLOOR_2) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
WorldObject* new_obj = new Floor(store_pt_, AdjustedMousePos());
new_obj->Update();
objects_.push_back(new_obj);
mode_ = MODE_NOTHING;
}
} else if(mode_ == MODE_ADD_WALL_1) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
store_pt_ = AdjustedMousePos();
mode_ = MODE_ADD_WALL_2;
}
} else if(mode_ == MODE_ADD_WALL_2) {
if(Mouse::I().Pressed(0, Mouse::PRESSED | Mouse::EDGE)) {
WorldObject* new_obj = new Wall(store_pt_, AdjustedMousePos());
new_obj->Update();
objects_.push_back(new_obj);
mode_ = MODE_NOTHING;
}
}
}
void Editor::Draw() {
Cam::I().SetPos(cam_pos_);
for(size_t i=0; i<objects_.size(); ++i) {
objects_[i]->Draw();
for(size_t p=0; p<objects_[i]->NumPoints(); ++p) {
DrawHandle(objects_[i]->Point(p));
}
}
glColor3f(0, 0, 0);
if(mode_ == MODE_ADD_FLOOR_1) {
DrawHandle(AdjustedMousePos());
} else if(mode_ == MODE_ADD_FLOOR_2) {
Floor(store_pt_, AdjustedMousePos()).Draw();
DrawHandle(AdjustedMousePos());
} else if(mode_ == MODE_ADD_WALL_1) {
DrawHandle(AdjustedMousePos());
} else if(mode_ == MODE_ADD_WALL_2) {
Wall(store_pt_, AdjustedMousePos()).Draw();
DrawHandle(AdjustedMousePos());
}
}
<|endoftext|>
|
<commit_before>#ifdef CAN_EMULATOR
#include "usbutil.h"
#include "canread.h"
#include "serialutil.h"
#include "log.h"
#include <stdlib.h>
#define NUMERICAL_SIGNAL_COUNT 11
#define BOOLEAN_SIGNAL_COUNT 5
#define STATE_SIGNAL_COUNT 2
#define EVENT_SIGNAL_COUNT 1
extern SerialDevice SERIAL_DEVICE;
extern UsbDevice USB_DEVICE;
extern Listener listener;
const char* NUMERICAL_SIGNALS[NUMERICAL_SIGNAL_COUNT] = {
"steering_wheel_angle",
"torque_at_transmission",
"engine_speed",
"vehicle_speed",
"accelerator_pedal_position",
"odometer",
"fine_odometer_since_restart",
"latitude",
"longitude",
"fuel_level",
"fuel_consumed_since_restart",
};
const char* BOOLEAN_SIGNALS[BOOLEAN_SIGNAL_COUNT] = {
"parking_brake_status",
"brake_pedal_status",
"headlamp_status",
"high_beam_status",
"windshield_wiper_status",
};
const char* STATE_SIGNALS[STATE_SIGNAL_COUNT] = {
"transmission_gear_position",
"ignition_status",
};
const char* SIGNAL_STATES[STATE_SIGNAL_COUNT][3] = {
{ "neutral", "first", "second" },
{ "off", "run", "accessory" },
};
const char* EVENT_SIGNALS[EVENT_SIGNAL_COUNT] = {
"door_status",
};
struct Event {
const char* value;
bool event;
};
Event EVENT_SIGNAL_STATES[EVENT_SIGNAL_COUNT][3] = {
{ {"driver", false}, {"passenger", true}, {"rear_right", true}},
};
void setup() {
srand(42);
initializeLogging();
initializeSerial(&SERIAL_DEVICE);
initializeUsb(&USB_DEVICE);
}
bool usbWriteStub(uint8_t* buffer) {
debug("Ignoring write request -- running an emulator\r\n");
return true;
}
void loop() {
while(1) {
sendNumericalMessage(
NUMERICAL_SIGNALS[rand() % NUMERICAL_SIGNAL_COUNT],
rand() % 50 + rand() % 100 * .1, &listener);
sendBooleanMessage(BOOLEAN_SIGNALS[rand() % BOOLEAN_SIGNAL_COUNT],
rand() % 2 == 1 ? true : false, &listener);
int stateSignalIndex = rand() % STATE_SIGNAL_COUNT;
sendStringMessage(STATE_SIGNALS[stateSignalIndex],
SIGNAL_STATES[stateSignalIndex][rand() % 3], &listener);
int eventSignalIndex = rand() % EVENT_SIGNAL_COUNT;
Event randomEvent = EVENT_SIGNAL_STATES[eventSignalIndex][rand() % 3];
sendEventedBooleanMessage(EVENT_SIGNALS[eventSignalIndex],
randomEvent.value, randomEvent.event, &listener);
processListenerQueues(&listener);
readFromHost(&USB_DEVICE, usbWriteStub);
readFromSerial(&SERIAL_DEVICE, usbWriteStub);
}
}
void reset() { }
const char* getMessageSet() {
return "emulator";
}
#endif // CAN_EMULATOR
<commit_msg>Don't initialize or read from serial in emualtor if NO_UART.<commit_after>#ifdef CAN_EMULATOR
#include "usbutil.h"
#include "canread.h"
#include "serialutil.h"
#include "log.h"
#include <stdlib.h>
#define NUMERICAL_SIGNAL_COUNT 11
#define BOOLEAN_SIGNAL_COUNT 5
#define STATE_SIGNAL_COUNT 2
#define EVENT_SIGNAL_COUNT 1
extern SerialDevice SERIAL_DEVICE;
extern UsbDevice USB_DEVICE;
extern Listener listener;
const char* NUMERICAL_SIGNALS[NUMERICAL_SIGNAL_COUNT] = {
"steering_wheel_angle",
"torque_at_transmission",
"engine_speed",
"vehicle_speed",
"accelerator_pedal_position",
"odometer",
"fine_odometer_since_restart",
"latitude",
"longitude",
"fuel_level",
"fuel_consumed_since_restart",
};
const char* BOOLEAN_SIGNALS[BOOLEAN_SIGNAL_COUNT] = {
"parking_brake_status",
"brake_pedal_status",
"headlamp_status",
"high_beam_status",
"windshield_wiper_status",
};
const char* STATE_SIGNALS[STATE_SIGNAL_COUNT] = {
"transmission_gear_position",
"ignition_status",
};
const char* SIGNAL_STATES[STATE_SIGNAL_COUNT][3] = {
{ "neutral", "first", "second" },
{ "off", "run", "accessory" },
};
const char* EVENT_SIGNALS[EVENT_SIGNAL_COUNT] = {
"door_status",
};
struct Event {
const char* value;
bool event;
};
Event EVENT_SIGNAL_STATES[EVENT_SIGNAL_COUNT][3] = {
{ {"driver", false}, {"passenger", true}, {"rear_right", true}},
};
void setup() {
srand(42);
initializeLogging();
#ifndef NO_UART
initializeSerial(&SERIAL_DEVICE);
#endif
initializeUsb(&USB_DEVICE);
}
bool usbWriteStub(uint8_t* buffer) {
debug("Ignoring write request -- running an emulator\r\n");
return true;
}
void loop() {
while(1) {
sendNumericalMessage(
NUMERICAL_SIGNALS[rand() % NUMERICAL_SIGNAL_COUNT],
rand() % 50 + rand() % 100 * .1, &listener);
sendBooleanMessage(BOOLEAN_SIGNALS[rand() % BOOLEAN_SIGNAL_COUNT],
rand() % 2 == 1 ? true : false, &listener);
int stateSignalIndex = rand() % STATE_SIGNAL_COUNT;
sendStringMessage(STATE_SIGNALS[stateSignalIndex],
SIGNAL_STATES[stateSignalIndex][rand() % 3], &listener);
int eventSignalIndex = rand() % EVENT_SIGNAL_COUNT;
Event randomEvent = EVENT_SIGNAL_STATES[eventSignalIndex][rand() % 3];
sendEventedBooleanMessage(EVENT_SIGNALS[eventSignalIndex],
randomEvent.value, randomEvent.event, &listener);
processListenerQueues(&listener);
readFromHost(&USB_DEVICE, usbWriteStub);
#ifndef NO_UART
readFromSerial(&SERIAL_DEVICE, usbWriteStub);
#endif
}
}
void reset() { }
const char* getMessageSet() {
return "emulator";
}
#endif // CAN_EMULATOR
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include "Entity.h"
#include "Log.h"
#include "Window.h"
Entity::Entity(Window* window, const std::string& textureName, int xPos, int yPos):
textureName(textureName)
{
this->window = window;
this->xPos = xPos;
this->yPos = yPos;
this->typeId = TYPEID_ENTITY;
this->texture = window->loadTexture(textureName);
// store the texture's width and height
SDL_QueryTexture(texture, NULL, NULL, &width, &height);
moveState = MOVE_NONE;
moveRate = 1;
active = true;
const std::string msg = "Created new entity with texture " + textureName + " at (" + std::to_string(xPos) + ", " + std::to_string(xPos) + ")";
Log::info(msg);
}
Entity::~Entity()
{
Log::info("Destroyed entity with texure " + textureName);
SDL_DestroyTexture(texture);
}
// function that updates the given entity
void Entity::update()
{
if (!isActive())
return;
if (isMoving(MOVE_UP))
yPos -= moveRate;
if (isMoving(MOVE_DOWN))
yPos += moveRate;
if (isMoving(MOVE_LEFT))
xPos -= moveRate;
if (isMoving(MOVE_RIGHT))
xPos += moveRate;
if (xPos < 0)
xPos = 0;
if (yPos < 0)
yPos = 0;
if (xPos > window->getWidth() - width)
xPos = window->getWidth() - width;
if (yPos > window->getHeight() - height)
yPos = window->getHeight() - height;
window->renderTexture(texture, xPos, yPos);
}
bool Entity::collidedWith(Entity* entity)
{
// if the given entity doesn't exist, we aren't colliding with it
if (!entity)
return false;
// can't collide with self
if (this == entity)
return false;
SDL_Rect rect;
rect.x = xPos;
rect.y = yPos;
rect.h = height;
rect.w = width;
SDL_Rect rectCol;
rectCol.x = entity->getX();
rectCol.y = entity->getY();
rectCol.h = entity->getHeight();
rectCol.w = entity->getWidth();
return SDL_HasIntersection(&rect, &rectCol) /* Prevent warning C4800 */!= 0;
}
//function for removing the specified texture
void Entity::remove()
{
if (!texture)
{
Log::error("Tried to delete non-existant texture!");
return;
}
SDL_DestroyTexture(texture);
active = false;
}
void Entity::setTexture(const std::string& textureName)
{
const std::string old = this->textureName;
this->texture = window->loadTexture(textureName);
// store the texture's width and height
SDL_QueryTexture(texture, NULL, NULL, &width, &height);
Log::info("Changed texture of entity from " + old + " to " + textureName);
}
void Entity::startMoving(int direction)
{
moveState |= direction;
}
void Entity::stopMoving(int direction)
{
moveState &= ~direction;
}
bool Entity::isMoving(int direction)
{
return (moveState & direction) != 0;
}
bool operator==(const Entity& left, const Entity& right)
{
return (left.xPos == right.xPos)
&& (left.yPos == right.yPos)
&& (left.textureName == right.textureName);
}
<commit_msg>Entities can only collide if they are both active<commit_after>#include <iostream>
#include <string>
#include "Entity.h"
#include "Log.h"
#include "Window.h"
Entity::Entity(Window* window, const std::string& textureName, int xPos, int yPos):
textureName(textureName)
{
this->window = window;
this->xPos = xPos;
this->yPos = yPos;
this->typeId = TYPEID_ENTITY;
this->texture = window->loadTexture(textureName);
// store the texture's width and height
SDL_QueryTexture(texture, NULL, NULL, &width, &height);
moveState = MOVE_NONE;
moveRate = 1;
active = true;
const std::string msg = "Created new entity with texture " + textureName + " at (" + std::to_string(xPos) + ", " + std::to_string(xPos) + ")";
Log::info(msg);
}
Entity::~Entity()
{
Log::info("Destroyed entity with texure " + textureName);
SDL_DestroyTexture(texture);
}
// function that updates the given entity
void Entity::update()
{
if (!isActive())
return;
if (isMoving(MOVE_UP))
yPos -= moveRate;
if (isMoving(MOVE_DOWN))
yPos += moveRate;
if (isMoving(MOVE_LEFT))
xPos -= moveRate;
if (isMoving(MOVE_RIGHT))
xPos += moveRate;
if (xPos < 0)
xPos = 0;
if (yPos < 0)
yPos = 0;
if (xPos > window->getWidth() - width)
xPos = window->getWidth() - width;
if (yPos > window->getHeight() - height)
yPos = window->getHeight() - height;
window->renderTexture(texture, xPos, yPos);
}
bool Entity::collidedWith(Entity* entity)
{
// if the given entity doesn't exist, we aren't colliding with it
if (!entity)
return false;
// can't collide with self
if (this == entity)
return false;
if (!entity->isActive())
return false;
SDL_Rect rect;
rect.x = xPos;
rect.y = yPos;
rect.h = height;
rect.w = width;
SDL_Rect rectCol;
rectCol.x = entity->getX();
rectCol.y = entity->getY();
rectCol.h = entity->getHeight();
rectCol.w = entity->getWidth();
return SDL_HasIntersection(&rect, &rectCol) /* Prevent warning C4800 */!= 0;
}
//function for removing the specified texture
void Entity::remove()
{
if (!texture)
{
Log::error("Tried to delete non-existant texture!");
return;
}
SDL_DestroyTexture(texture);
active = false;
}
void Entity::setTexture(const std::string& textureName)
{
const std::string old = this->textureName;
this->texture = window->loadTexture(textureName);
// store the texture's width and height
SDL_QueryTexture(texture, NULL, NULL, &width, &height);
Log::info("Changed texture of entity from " + old + " to " + textureName);
}
void Entity::startMoving(int direction)
{
moveState |= direction;
}
void Entity::stopMoving(int direction)
{
moveState &= ~direction;
}
bool Entity::isMoving(int direction)
{
return (moveState & direction) != 0;
}
bool operator==(const Entity& left, const Entity& right)
{
return (left.xPos == right.xPos)
&& (left.yPos == right.yPos)
&& (left.textureName == right.textureName);
}
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
osimModel.setAuthors("Matt DeMers");
double Pi = SimTK::Pi;
// Get the ground body
Ground& ground = osimModel.updGround();
ground.addMeshGeometry("checkered_floor.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
Vec3 linkageMassCenter(0,linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);
OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
Cylinder cyl;
//This cylinder.vtp geometry is 1 meter tall, 1 meter diameter. Scale and shift it to look pretty
cyl.set_scale_factors(linkageDimensions);
Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl1Frame->setName("Cyl1_frame");
osimModel.addFrame(cyl1Frame);
cyl.setFrameName("Cyl1_frame");
linkage1->addGeometry(cyl);
linkage1->addGeometry(Sphere(0.1));
//This sphere.vtp is 1 meter in diameter. Scale it.
// Creat a second linkage body
OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
linkage2->setName("linkage2");
Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl2Frame->setName("Cyl2_frame");
osimModel.addFrame(cyl2Frame);
(linkage2->upd_GeometrySet(0)).setFrameName("Cyl2_frame");
// Creat a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
Brick brick(SimTK::Vec3(0.05, 0.05, 0.05));
block->addGeometry(brick);
//This block.vtp is 0.1x0.1x0.1 meters. scale its appearance
//block->updDisplayer()->updGeometrySet()[0].setScaleFactors(Vec3(2.0));
// Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Add the joints to the model
osimModel.addJoint(ankle);
osimModel.addJoint(knee);
osimModel.addJoint(hip);
// Define contraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// create a controller to control the piston and spring actuators
// the prescribed controller sets the controls as functions of time
PrescribedController *legController = new PrescribedController();
// give the legController control over all (two) model actuators
legController->setActuators(osimModel.updActuators());
// specify some control nodes for spring stiffness control
double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};
double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};
// specify the control function for each actuator
legController->prescribeControlForActuator("piston", new Constant(0.1));
legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));
// add the controller to the model
osimModel.addController(legController);
// define the acceration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
osimModel.dumpPathName();
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
osimModel.printControlStorage("SpringActuatedLeg_controls.sto");
Storage statesDegrees(manager.getStateStorage());
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
//statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
statesDegrees.print("SpringActuatedLeg_states_degrees.mot");
forces->getForceStorage().print("actuator_forces.mot");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
<commit_msg>Fix one more compilation error on travis.<commit_after>/* -------------------------------------------------------------------------- *
* OpenSim: toyLeg_example.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Matt S. DeMers *
* *
* 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. *
* -------------------------------------------------------------------------- */
/*
* Below is an example of an OpenSim application that provides its own
* main() routine. This application acts as an example for utilizing the
* ControllabeSpring actuator.
*/
// Author: Matt DeMers
//==============================================================================
//==============================================================================
#include "PistonActuator.h"
#include "ControllableSpring.h"
#include <OpenSim/OpenSim.h>
using namespace OpenSim;
using namespace SimTK;
//______________________________________________________________________________
/**
* Run a simulation of block sliding with contact on by two muscles sliding with contact
*/
int main()
{
try {
// Create a new OpenSim model
Model osimModel;
osimModel.setName("osimModel");
osimModel.setAuthors("Matt DeMers");
double Pi = SimTK::Pi;
// Get the ground body
Ground& ground = osimModel.updGround();
ground.addMeshGeometry("checkered_floor.vtp");
// create linkage body
double linkageMass = 0.001, linkageLength = 0.5, linkageDiameter = 0.06;
Vec3 linkageDimensions(linkageDiameter, linkageLength, linkageDiameter);
Vec3 linkageMassCenter(0,linkageLength/2,0);
Inertia linkageInertia = Inertia::cylinderAlongY(linkageDiameter/2.0, linkageLength/2.0);
OpenSim::Body* linkage1 = new OpenSim::Body("linkage1", linkageMass, linkageMassCenter, linkageMass*linkageInertia);
// Graphical representation
Cylinder cyl;
//This cylinder.vtp geometry is 1 meter tall, 1 meter diameter. Scale and shift it to look pretty
cyl.set_scale_factors(linkageDimensions);
Frame* cyl1Frame = new PhysicalOffsetFrame(*linkage1, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl1Frame->setName("Cyl1_frame");
osimModel.addFrame(cyl1Frame);
cyl.setFrameName("Cyl1_frame");
linkage1->addGeometry(cyl);
Sphere sphere(0.1);
linkage1->addGeometry(sphere);
//This sphere.vtp is 1 meter in diameter. Scale it.
// Creat a second linkage body
OpenSim::Body* linkage2 = new OpenSim::Body(*linkage1);
linkage2->setName("linkage2");
Frame* cyl2Frame = new PhysicalOffsetFrame(*linkage2, Transform(Vec3(0.0, linkageLength / 2.0, 0.0)));
cyl2Frame->setName("Cyl2_frame");
osimModel.addFrame(cyl2Frame);
(linkage2->upd_GeometrySet(0)).setFrameName("Cyl2_frame");
// Creat a block to be the pelvis
double blockMass = 20.0, blockSideLength = 0.2;
Vec3 blockMassCenter(0);
Inertia blockInertia = blockMass*Inertia::brick(blockSideLength, blockSideLength, blockSideLength);
OpenSim::Body *block = new OpenSim::Body("block", blockMass, blockMassCenter, blockInertia);
Brick brick(SimTK::Vec3(0.05, 0.05, 0.05));
block->addGeometry(brick);
//This block.vtp is 0.1x0.1x0.1 meters. scale its appearance
//block->updDisplayer()->updGeometrySet()[0].setScaleFactors(Vec3(2.0));
// Create 1 degree-of-freedom pin joints between the bodies to creat a kinematic chain from ground through the block
Vec3 orientationInGround(0), locationInGround(0), locationInParent(0.0, linkageLength, 0.0), orientationInChild(0), locationInChild(0);
PinJoint *ankle = new PinJoint("ankle", ground, locationInGround, orientationInGround, *linkage1,
locationInChild, orientationInChild);
PinJoint *knee = new PinJoint("knee", *linkage1, locationInParent, orientationInChild, *linkage2,
locationInChild, orientationInChild);
PinJoint *hip = new PinJoint("hip", *linkage2, locationInParent, orientationInChild, *block,
locationInChild, orientationInChild);
double range[2] = {-SimTK::Pi*2, SimTK::Pi*2};
CoordinateSet& ankleCoordinateSet = ankle->upd_CoordinateSet();
ankleCoordinateSet[0].setName("q1");
ankleCoordinateSet[0].setRange(range);
CoordinateSet& kneeCoordinateSet = knee->upd_CoordinateSet();
kneeCoordinateSet[0].setName("q2");
kneeCoordinateSet[0].setRange(range);
CoordinateSet& hipCoordinateSet = hip->upd_CoordinateSet();
hipCoordinateSet[0].setName("q3");
hipCoordinateSet[0].setRange(range);
// Add the bodies to the model
osimModel.addBody(linkage1);
osimModel.addBody(linkage2);
osimModel.addBody(block);
// Add the joints to the model
osimModel.addJoint(ankle);
osimModel.addJoint(knee);
osimModel.addJoint(hip);
// Define contraints on the model
// Add a point on line constraint to limit the block to vertical motion
Vec3 lineDirection(0,1,0), pointOnLine(0,0,0), pointOnBlock(0);
PointOnLineConstraint *lineConstraint = new PointOnLineConstraint(ground, lineDirection, pointOnLine, *block, pointOnBlock);
osimModel.addConstraint(lineConstraint);
// Add PistonActuator between the first linkage and the block
Vec3 pointOnBodies(0);
PistonActuator *piston = new PistonActuator();
piston->setName("piston");
piston->setBodyA(linkage1);
piston->setBodyB(block);
piston->setPointA(pointOnBodies);
piston->setPointB(pointOnBodies);
piston->setOptimalForce(200.0);
piston->setPointsAreGlobal(false);
osimModel.addForce(piston);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Added ControllableSpring between the first linkage and the second block
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
ControllableSpring *spring = new ControllableSpring;
spring->setName("spring");
spring->setBodyA(block);
spring->setBodyB(linkage1);
spring->setPointA(pointOnBodies);
spring->setPointB(pointOnBodies);
spring->setOptimalForce(2000.0);
spring->setPointsAreGlobal(false);
spring->setRestLength(0.8);
osimModel.addForce(spring);
// define the simulation times
double t0(0.0), tf(15);
// create a controller to control the piston and spring actuators
// the prescribed controller sets the controls as functions of time
PrescribedController *legController = new PrescribedController();
// give the legController control over all (two) model actuators
legController->setActuators(osimModel.updActuators());
// specify some control nodes for spring stiffness control
double t[] = {0.0, 4.0, 7.0, 10.0, 15.0};
double x[] = {1.0, 1.0, 0.25, 0.25, 5.0};
// specify the control function for each actuator
legController->prescribeControlForActuator("piston", new Constant(0.1));
legController->prescribeControlForActuator("spring", new PiecewiseLinearFunction(5, t, x));
// add the controller to the model
osimModel.addController(legController);
// define the acceration due to gravity
osimModel.setGravity(Vec3(0, -9.80665, 0));
// enable the model visualizer see the model in action, which can be
// useful for debugging
osimModel.setUseVisualizer(false);
// Initialize system
SimTK::State& si = osimModel.initSystem();
// Pin joint initial states
double q1_i = -Pi/4;
double q2_i = - 2*q1_i;
CoordinateSet &coordinates = osimModel.updCoordinateSet();
coordinates[0].setValue(si, q1_i, true);
coordinates[1].setValue(si,q2_i, true);
// Setup integrator and manager
SimTK::RungeKuttaMersonIntegrator integrator(osimModel.getMultibodySystem());
integrator.setAccuracy(1.0e-3);
ForceReporter *forces = new ForceReporter(&osimModel);
osimModel.updAnalysisSet().adoptAndAppend(forces);
Manager manager(osimModel, integrator);
//Examine the model
osimModel.printDetailedInfo(si, std::cout);
// Save the model
osimModel.print("toyLeg.osim");
// Print out the initial position and velocity states
si.getQ().dump("Initial q's");
si.getU().dump("Initial u's");
std::cout << "Initial time: " << si.getTime() << std::endl;
osimModel.dumpPathName();
// Integrate
manager.setInitialTime(t0);
manager.setFinalTime(tf);
std::cout<<"\n\nIntegrating from " << t0 << " to " << tf << std::endl;
manager.integrate(si);
// Save results
osimModel.printControlStorage("SpringActuatedLeg_controls.sto");
Storage statesDegrees(manager.getStateStorage());
osimModel.updSimbodyEngine().convertRadiansToDegrees(statesDegrees);
//statesDegrees.print("PistonActuatedLeg_states_degrees.mot");
statesDegrees.print("SpringActuatedLeg_states_degrees.mot");
forces->getForceStorage().print("actuator_forces.mot");
}
catch (const std::exception& ex)
{
std::cout << "Exception in toyLeg_example: " << ex.what() << std::endl;
return 1;
}
std::cout << "Done." << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
//
// Main network
//
unsigned int pnSeed[] =
{
0x12345678
};
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
pchMessageStart[0] = 0x03;
pchMessageStart[1] = 0xd5;
pchMessageStart[2] = 0xb5;
pchMessageStart[3] = 0x03;
nDefaultPort = 65534;
nRPCPort = 65535;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
nSubsidyHalvingInterval = 100000;
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
const char* pszTimestamp = "San Francisco plaza evacuated after suspicious package is found";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 1 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1375548986;
genesis.nBits = 0x1e0fffff;
genesis.nNonce = 1211565;
//// debug print
hashGenesisBlock = genesis.GetHash();
//while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
// if (++genesis.nNonce==0) break;
// hashGenesisBlock = genesis.GetHash();
//}
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
printf("%x\n", bnProofOfWorkLimit.GetCompact());
genesis.print();
assert(hashGenesisBlock == uint256("0x000004c2fc5fffb810dccc197d603690099a68305232e552d96ccbe8e2c52b75"));
assert(genesis.hashMerkleRoot == uint256("0x36a192e90f70131a884fe541a1e8a5643a28ba4cb24cbb2924bd0ee483f7f484"));
vSeeds.push_back(CDNSSeedData("andarazoroflove.org", "andarazoroflove.org"));
vSeeds.push_back(CDNSSeedData("rockchain.info", "rockchain.info"));
base58Prefixes[PUBKEY_ADDRESS] = 130;
base58Prefixes[SCRIPT_ADDRESS] = 30;
base58Prefixes[SECRET_KEY] = 224;
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time'
const int64 nTwoDays = 2 * 24 * 60 * 60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
pchMessageStart[0] = 0x01;
pchMessageStart[1] = 0xfe;
pchMessageStart[2] = 0xfe;
pchMessageStart[3] = 0x05;
nDefaultPort = 55534;
nRPCPort = 55535;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1374901773;
genesis.nNonce = 1211565;
//// debug print
hashGenesisBlock = genesis.GetHash();
//while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
// if (++genesis.nNonce==0) break;
// hashGenesisBlock = genesis.GetHash();
//}
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
genesis.print();
vFixedSeeds.clear();
vSeeds.clear();
// vSeeds.push_back(CDNSSeedData("unobtanium.test", "test.unobtanium.org"));
base58Prefixes[PUBKEY_ADDRESS] = 130;
base58Prefixes[SCRIPT_ADDRESS] = 30;
base58Prefixes[SECRET_KEY] = 239;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xfa;
pchMessageStart[1] = 0x0f;
pchMessageStart[2] = 0xa5;
pchMessageStart[3] = 0x5a;
nSubsidyHalvingInterval = 150;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1296688602;
genesis.nBits = 0x207fffff;
genesis.nNonce = 3;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18444;
strDataDir = "regtest";
//// debug print
hashGenesisBlock = genesis.GetHash();
//while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
// if (++genesis.nNonce==0) break;
// hashGenesisBlock = genesis.GetHash();
//}
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
genesis.print();
// assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
base58Prefixes[PUBKEY_ADDRESS] = 0;
base58Prefixes[SCRIPT_ADDRESS] = 5;
base58Prefixes[SECRET_KEY] = 128;
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>Added iSpace.co.uk to seed nodes<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "core.h"
#include "protocol.h"
#include "util.h"
//
// Main network
//
unsigned int pnSeed[] =
{
0x12345678
};
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
pchMessageStart[0] = 0x03;
pchMessageStart[1] = 0xd5;
pchMessageStart[2] = 0xb5;
pchMessageStart[3] = 0x03;
nDefaultPort = 65534;
nRPCPort = 65535;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20);
nSubsidyHalvingInterval = 100000;
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
const char* pszTimestamp = "San Francisco plaza evacuated after suspicious package is found";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 1 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG;
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1375548986;
genesis.nBits = 0x1e0fffff;
genesis.nNonce = 1211565;
//// debug print
hashGenesisBlock = genesis.GetHash();
//while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
// if (++genesis.nNonce==0) break;
// hashGenesisBlock = genesis.GetHash();
//}
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
printf("%x\n", bnProofOfWorkLimit.GetCompact());
genesis.print();
assert(hashGenesisBlock == uint256("0x000004c2fc5fffb810dccc197d603690099a68305232e552d96ccbe8e2c52b75"));
assert(genesis.hashMerkleRoot == uint256("0x36a192e90f70131a884fe541a1e8a5643a28ba4cb24cbb2924bd0ee483f7f484"));
vSeeds.push_back(CDNSSeedData("108.61.10.90", "108.61.10.90"));
vSeeds.push_back(CDNSSeedData("107.170.63.157", "107.170.63.157"));
vSeeds.push_back(CDNSSeedData("192.241.254.222", "192.241.254.222"));
vSeeds.push_back(CDNSSeedData("198.199.97.43","198.199.97.43"));
vSeeds.push_back(CDNSSeedData("128.199.174.196","128.199.174.196"));
vSeeds.push_back(CDNSSeedData("rockchain.info", "rockchain.info"));
base58Prefixes[PUBKEY_ADDRESS] = 130;
base58Prefixes[SCRIPT_ADDRESS] = 30;
base58Prefixes[SECRET_KEY] = 224;
// Convert the pnSeeds array into usable address objects.
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time'
const int64 nTwoDays = 2 * 24 * 60 * 60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - GetRand(nTwoDays) - nTwoDays;
vFixedSeeds.push_back(addr);
}
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet (v3)
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
pchMessageStart[0] = 0x01;
pchMessageStart[1] = 0xfe;
pchMessageStart[2] = 0xfe;
pchMessageStart[3] = 0x05;
nDefaultPort = 55534;
nRPCPort = 55535;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nTime = 1374901773;
genesis.nNonce = 1211565;
//// debug print
hashGenesisBlock = genesis.GetHash();
//while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
// if (++genesis.nNonce==0) break;
// hashGenesisBlock = genesis.GetHash();
//}
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
genesis.print();
vFixedSeeds.clear();
vSeeds.clear();
// vSeeds.push_back(CDNSSeedData("unobtanium.test", "test.unobtanium.org"));
base58Prefixes[PUBKEY_ADDRESS] = 130;
base58Prefixes[SCRIPT_ADDRESS] = 30;
base58Prefixes[SECRET_KEY] = 239;
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xfa;
pchMessageStart[1] = 0x0f;
pchMessageStart[2] = 0xa5;
pchMessageStart[3] = 0x5a;
nSubsidyHalvingInterval = 150;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1296688602;
genesis.nBits = 0x207fffff;
genesis.nNonce = 3;
hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18444;
strDataDir = "regtest";
//// debug print
hashGenesisBlock = genesis.GetHash();
//while (hashGenesisBlock > bnProofOfWorkLimit.getuint256()){
// if (++genesis.nNonce==0) break;
// hashGenesisBlock = genesis.GetHash();
//}
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", genesis.hashMerkleRoot.ToString().c_str());
genesis.print();
// assert(hashGenesisBlock == uint256("0x13d8d31dde96874006da503dd2b63fa68c698dc823334359e417aa3a92f80433"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
base58Prefixes[PUBKEY_ADDRESS] = 0;
base58Prefixes[SCRIPT_ADDRESS] = 5;
base58Prefixes[SECRET_KEY] = 128;
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <Context.h>
#include <Eval.h>
#include <Variant.h>
#include <Dates.h>
#include <Filter.h>
#include <i18n.h>
#include <text.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Const iterator that can be derefenced into a Task by domSource.
static Task dummy;
Task& contextTask = dummy;
////////////////////////////////////////////////////////////////////////////////
bool domSource (const std::string& identifier, Variant& value)
{
if (context.dom.get (identifier, contextTask, value))
{
value.source (identifier);
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
Filter::Filter ()
: _startCount (0)
, _endCount (0)
{
}
////////////////////////////////////////////////////////////////////////////////
Filter::~Filter ()
{
}
////////////////////////////////////////////////////////////////////////////////
// Take an input set of tasks and filter into a subset.
void Filter::subset (const std::vector <Task>& input, std::vector <Task>& output)
{
context.timer_filter.start ();
_startCount = (int) input.size ();
if (context.config.getInteger ("debug.parser") >= 1)
{
context.debug (context.cli.dump ());
Tree* t = context.parser.tree ();
if (t)
context.debug (t->dump ());
}
std::string filterExpr = context.parser.getFilterExpression ();
if (filterExpr.length ())
{
Eval eval;
eval.ambiguity (false);
eval.addSource (namedDates);
eval.addSource (domSource);
// Debug output from Eval during compilation is useful. During evaluation
// it is mostly noise.
eval.debug (context.config.getInteger ("debug.parser") >= 1 ? true : false);
eval.compileExpression (filterExpr);
eval.debug (false);
std::vector <Task>::const_iterator task;
for (task = input.begin (); task != input.end (); ++task)
{
// Set up context for any DOM references.
contextTask = *task;
Variant var;
eval.evaluateCompiledExpression (var);
if (var.get_bool ())
output.push_back (*task);
}
}
else
output = input;
_endCount = (int) output.size ();
context.debug (format ("Filtered {1} tasks --> {2} tasks [list subset]", _startCount, _endCount));
context.timer_filter.stop ();
}
////////////////////////////////////////////////////////////////////////////////
// Take the set of all tasks and filter into a subset.
void Filter::subset (std::vector <Task>& output)
{
context.timer_filter.start ();
if (context.config.getInteger ("debug.parser") >= 1)
{
context.debug (context.cli.dump ());
Tree* t = context.parser.tree ();
if (t)
context.debug (t->dump ());
}
bool shortcut = false;
std::string filterExpr = context.parser.getFilterExpression ();
if (filterExpr.length ())
{
context.timer_filter.stop ();
const std::vector <Task>& pending = context.tdb2.pending.get_tasks ();
context.timer_filter.start ();
_startCount = (int) pending.size ();
Eval eval;
eval.ambiguity (false);
eval.addSource (namedDates);
eval.addSource (domSource);
// Debug output from Eval during compilation is useful. During evaluation
// it is mostly noise.
eval.debug (context.config.getInteger ("debug.parser") >= 1 ? true : false);
eval.compileExpression (filterExpr);
eval.debug (false);
output.clear ();
std::vector <Task>::const_iterator task;
for (task = pending.begin (); task != pending.end (); ++task)
{
// Set up context for any DOM references.
contextTask = *task;
Variant var;
eval.evaluateCompiledExpression (var);
if (var.get_bool ())
output.push_back (*task);
}
shortcut = pendingOnly ();
if (! shortcut)
{
context.timer_filter.stop ();
const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); // TODO Optional
context.timer_filter.start ();
_startCount += (int) completed.size ();
for (task = completed.begin (); task != completed.end (); ++task)
{
// Set up context for any DOM references.
contextTask = *task;
Variant var;
eval.evaluateCompiledExpression (var);
if (var.get_bool ())
output.push_back (*task);
}
}
}
else
{
safety ();
context.timer_filter.stop ();
const std::vector <Task>& pending = context.tdb2.pending.get_tasks ();
const std::vector <Task>& completed = context.tdb2.completed.get_tasks ();
context.timer_filter.start ();
std::vector <Task>::const_iterator task;
for (task = pending.begin (); task != pending.end (); ++task)
output.push_back (*task);
for (task = completed.begin (); task != completed.end (); ++task)
output.push_back (*task);
}
_endCount = (int) output.size ();
context.debug (format ("Filtered {1} tasks --> {2} tasks [{3}]", _startCount, _endCount, (shortcut ? "pending only" : "all tasks")));
context.timer_filter.stop ();
}
////////////////////////////////////////////////////////////////////////////////
// If the filter contains the restriction "status:pending", as the first filter
// term, then completed.data does not need to be loaded.
bool Filter::pendingOnly ()
{
Tree* tree = context.parser.tree ();
// To skip loading completed.data, there should be:
// - 'status' in filter
// - no 'completed'
// - no 'deleted'
// - no 'xor'
// - no 'or'
int countStatus = 0;
int countPending = 0;
int countId = 0;
int countOr = 0;
int countXor = 0;
std::vector <A>::iterator a;
for (a = context.cli._args.begin (); a != context.cli._args.end (); ++a)
{
if (a->hasTag ("FILTER"))
{
if (a->hasTag ("ID")) ++countId;
if (a->hasTag ("OP") && a->attribute ("raw") == "or") ++countOr;
if (a->hasTag ("OP") && a->attribute ("raw") == "xor") ++countXor;
if (a->hasTag ("ATTRIBUTE") && a->attribute ("name") == "status") ++countStatus;
if ( a->attribute ("raw") == "pending") ++countPending;
}
}
// Use of 'or' or 'xor' means the potential for alternation.
if (countOr || countXor)
return false;
// If the filter does not contain id or status terms, read both files.
if (countId == 0 && countStatus == 0)
return false;
// Only one 'status == pending' is allowed.
if (countStatus != 1 || countPending != 1)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Disaster avoidance mechanism. If a WRITECMD has no filter, then it can cause
// all tasks to be modified. This is usually not intended.
void Filter::safety ()
{
std::vector <A>::iterator a;
for (a = context.cli._args.begin (); a != context.cli._args.end (); ++a)
{
if (a->hasTag ("CMD"))
{
if (a->hasTag ("WRITECMD"))
{
if (context.cli.getFilter () == "")
{
if (! context.config.getBoolean ("allow.empty.filter"))
throw std::string (STRING_TASK_SAFETY_ALLOW);
// If user is willing to be asked, this can be avoided.
if (context.config.getBoolean ("confirmation") &&
confirm (STRING_TASK_SAFETY_VALVE))
return;
// Sounds the alarm.
throw std::string (STRING_TASK_SAFETY_FAIL);
}
}
// CMD was found.
return;
}
}
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Filter<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2014, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <Context.h>
#include <Eval.h>
#include <Variant.h>
#include <Dates.h>
#include <Filter.h>
#include <i18n.h>
#include <text.h>
#include <util.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
// Const iterator that can be derefenced into a Task by domSource.
static Task dummy;
Task& contextTask = dummy;
////////////////////////////////////////////////////////////////////////////////
bool domSource (const std::string& identifier, Variant& value)
{
if (context.dom.get (identifier, contextTask, value))
{
value.source (identifier);
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
Filter::Filter ()
: _startCount (0)
, _endCount (0)
{
}
////////////////////////////////////////////////////////////////////////////////
Filter::~Filter ()
{
}
////////////////////////////////////////////////////////////////////////////////
// Take an input set of tasks and filter into a subset.
void Filter::subset (const std::vector <Task>& input, std::vector <Task>& output)
{
context.timer_filter.start ();
_startCount = (int) input.size ();
if (context.config.getInteger ("debug.parser") >= 1)
{
context.debug (context.cli.dump ());
Tree* t = context.parser.tree ();
if (t)
context.debug (t->dump ());
}
std::string filterExpr = context.parser.getFilterExpression ();
if (filterExpr.length ())
{
Eval eval;
eval.ambiguity (false);
eval.addSource (namedDates);
eval.addSource (domSource);
// Debug output from Eval during compilation is useful. During evaluation
// it is mostly noise.
eval.debug (context.config.getInteger ("debug.parser") >= 1 ? true : false);
eval.compileExpression (filterExpr);
eval.debug (false);
std::vector <Task>::const_iterator task;
for (task = input.begin (); task != input.end (); ++task)
{
// Set up context for any DOM references.
contextTask = *task;
Variant var;
eval.evaluateCompiledExpression (var);
if (var.get_bool ())
output.push_back (*task);
}
}
else
output = input;
_endCount = (int) output.size ();
context.debug (format ("Filtered {1} tasks --> {2} tasks [list subset]", _startCount, _endCount));
context.timer_filter.stop ();
}
////////////////////////////////////////////////////////////////////////////////
// Take the set of all tasks and filter into a subset.
void Filter::subset (std::vector <Task>& output)
{
context.timer_filter.start ();
if (context.config.getInteger ("debug.parser") >= 1)
{
context.debug (context.cli.dump ());
Tree* t = context.parser.tree ();
if (t)
context.debug (t->dump ());
}
bool shortcut = false;
std::string filterExpr = context.parser.getFilterExpression ();
if (filterExpr.length ())
{
context.timer_filter.stop ();
const std::vector <Task>& pending = context.tdb2.pending.get_tasks ();
context.timer_filter.start ();
_startCount = (int) pending.size ();
Eval eval;
eval.ambiguity (false);
eval.addSource (namedDates);
eval.addSource (domSource);
// Debug output from Eval during compilation is useful. During evaluation
// it is mostly noise.
eval.debug (context.config.getInteger ("debug.parser") >= 2 ? true : false);
eval.compileExpression (filterExpr);
eval.debug (false);
output.clear ();
std::vector <Task>::const_iterator task;
for (task = pending.begin (); task != pending.end (); ++task)
{
// Set up context for any DOM references.
contextTask = *task;
Variant var;
eval.evaluateCompiledExpression (var);
if (var.get_bool ())
output.push_back (*task);
}
shortcut = pendingOnly ();
if (! shortcut)
{
context.timer_filter.stop ();
const std::vector <Task>& completed = context.tdb2.completed.get_tasks (); // TODO Optional
context.timer_filter.start ();
_startCount += (int) completed.size ();
for (task = completed.begin (); task != completed.end (); ++task)
{
// Set up context for any DOM references.
contextTask = *task;
Variant var;
eval.evaluateCompiledExpression (var);
if (var.get_bool ())
output.push_back (*task);
}
}
}
else
{
safety ();
context.timer_filter.stop ();
const std::vector <Task>& pending = context.tdb2.pending.get_tasks ();
const std::vector <Task>& completed = context.tdb2.completed.get_tasks ();
context.timer_filter.start ();
std::vector <Task>::const_iterator task;
for (task = pending.begin (); task != pending.end (); ++task)
output.push_back (*task);
for (task = completed.begin (); task != completed.end (); ++task)
output.push_back (*task);
}
_endCount = (int) output.size ();
context.debug (format ("Filtered {1} tasks --> {2} tasks [{3}]", _startCount, _endCount, (shortcut ? "pending only" : "all tasks")));
context.timer_filter.stop ();
}
////////////////////////////////////////////////////////////////////////////////
// If the filter contains the restriction "status:pending", as the first filter
// term, then completed.data does not need to be loaded.
bool Filter::pendingOnly ()
{
Tree* tree = context.parser.tree ();
// To skip loading completed.data, there should be:
// - 'status' in filter
// - no 'completed'
// - no 'deleted'
// - no 'xor'
// - no 'or'
int countStatus = 0;
int countPending = 0;
int countId = 0;
int countOr = 0;
int countXor = 0;
// TODO Use an int index, and ensure that 'status', '==' and 'pending/waiting'
// are consecutive.
std::vector <A>::iterator a;
for (a = context.cli._args.begin (); a != context.cli._args.end (); ++a)
{
if (a->hasTag ("FILTER"))
{
if (a->hasTag ("ID")) ++countId;
if (a->hasTag ("OP") && a->attribute ("raw") == "or") ++countOr;
if (a->hasTag ("OP") && a->attribute ("raw") == "xor") ++countXor;
if (a->hasTag ("ATTRIBUTE") && a->attribute ("name") == "status") ++countStatus;
if ( a->attribute ("raw") == "pending") ++countPending;
}
}
// Use of 'or' or 'xor' means the potential for alternation.
if (countOr || countXor)
return false;
// If the filter does not contain id or status terms, read both files.
if (countId == 0 && countStatus == 0)
return false;
// Only one 'status == pending' is allowed.
if (countStatus != 1 || countPending != 1)
return false;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Disaster avoidance mechanism. If a WRITECMD has no filter, then it can cause
// all tasks to be modified. This is usually not intended.
void Filter::safety ()
{
std::vector <A>::iterator a;
for (a = context.cli._args.begin (); a != context.cli._args.end (); ++a)
{
if (a->hasTag ("CMD"))
{
if (a->hasTag ("WRITECMD"))
{
if (context.cli.getFilter () == "")
{
if (! context.config.getBoolean ("allow.empty.filter"))
throw std::string (STRING_TASK_SAFETY_ALLOW);
// If user is willing to be asked, this can be avoided.
if (context.config.getBoolean ("confirmation") &&
confirm (STRING_TASK_SAFETY_VALVE))
return;
// Sounds the alarm.
throw std::string (STRING_TASK_SAFETY_FAIL);
}
}
// CMD was found.
return;
}
}
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xd5;
pchMessageStart[1] = 0x7a;
pchMessageStart[2] = 0xe4;
pchMessageStart[3] = 0x3d;
vAlertPubKey = ParseHex("040251669e27baf52584bfe5a757b61c8f5b0e43761250fadae6330c7ebac33835eaa89c1466547ed1f93283f68bc3bde7856a84debb0ac353e6a27430dad61c82");
nDefaultPort = 44321;
nRPCPort = 44122;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 15);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
//
const char* pszTimestamp = "24 9 2017 Start of Kurdish Block Chain";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1506250100, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1506250100;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 6488;
// uncomment to log genesis block info
// // start
// if (true && genesis.GetHash() != hashGenesisBlock)
// {
// printf("Searching for genesis block...\n");
// uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
// uint256 thash;
//
// while (true)
// {
// thash = genesis.GetHash();
// if (thash <= hashTarget)
// break;
// if ((genesis.nNonce & 0xFFF) == 0)
// {
// printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
// }
// ++genesis.nNonce;
// if (genesis.nNonce == 0)
// {
// printf("NONCE WRAPPED, incrementing time\n");
// ++genesis.nTime;
// }
// }
// printf("genesis.nTime = %u \n", genesis.nTime);
// printf("genesis.nNonce = %u \n", genesis.nNonce);
// printf("genesis.nVersion = %u \n", genesis.nVersion);
// printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under.
// printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root
//
// }
//
// //end
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x0000af8611f474e997efec4294d9144bca3cc93a370d3a3fbea6cb8ef156162e"));
assert(genesis.hashMerkleRoot == uint256("0x9a957fc4121962ed9ff30325a6c67856d1b94ef20d2fdef63d5e74d54e5a9620"));
vSeeds.push_back(CDNSSeedData("america", "america.kurdcoin.org"));
vSeeds.push_back(CDNSSeedData("europ", "europ.kurdcoin.org"));
vSeeds.push_back(CDNSSeedData("asia", "asia.kurdcoin.org"));
base58Prefixes[PUBKEY_ADDRESS] = list_of(45);
base58Prefixes[SCRIPT_ADDRESS] = list_of(63);
base58Prefixes[SECRET_KEY] = list_of(75);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x3d)(0xB2)(0x1E);
base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x3d)(0xAD)(0xE4);
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x3d;
pchMessageStart[1] = 0xa5;
pchMessageStart[2] = 0xd3;
pchMessageStart[3] = 0xa7;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 5);
vAlertPubKey = ParseHex("04c5e13ee9c47c6d9c898153552d61e86be9dfe3a7c944a17b204c0491da30c888d4d8ba1a913b72f0b43496fdc998c2e41d0a1690fefbe32fb6029ed5e6cb096e");
nDefaultPort = 55321;
nRPCPort = 55122;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 20;
// uncomment to log genesis block info
// // start
// if (true && genesis.GetHash() != hashGenesisBlock)
// {
// printf("Searching for genesis block...\n");
// uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
// uint256 thash;
//
// while (true)
// {
// thash = genesis.GetHash();
// if (thash <= hashTarget)
// break;
// if ((genesis.nNonce & 0xFFF) == 0)
// {
// printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
// }
// ++genesis.nNonce;
// if (genesis.nNonce == 0)
// {
// printf("NONCE WRAPPED, incrementing time\n");
// ++genesis.nTime;
// }
// }
// printf("genesis.nTime = %u \n", genesis.nTime);
// printf("genesis.nNonce = %u \n", genesis.nNonce);
// printf("genesis.nVersion = %u \n", genesis.nVersion);
// printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under.
// printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root
//
// }
//
// //end
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x013cd814a6ca2fcf87c7d1815e025cd5d542ab8732ba4afcd305cd0c904f7496"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = list_of(66);
base58Prefixes[SCRIPT_ADDRESS] = list_of(196);
base58Prefixes[SECRET_KEY] = list_of(81);
base58Prefixes[EXT_PUBLIC_KEY] = list_of(0xd3)(0x35)(0x87)(0xCF);
base58Prefixes[EXT_SECRET_KEY] = list_of(0xd3)(0x35)(0x83)(0x94);
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xf2;
pchMessageStart[1] = 0xa9;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xca;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1426450258;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 0;
//hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18445;
strDataDir = "regtest";
// if (true && genesis.GetHash() != hashGenesisBlock)
// {
// printf("Searching for genesis block...\n");
// uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
// uint256 thash;
//
// while (true)
// {
// thash = genesis.GetHash();
// if (thash <= hashTarget)
// break;
// if ((genesis.nNonce & 0xFFF) == 0)
// {
// printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
// }
// ++genesis.nNonce;
// if (genesis.nNonce == 0)
// {
// printf("NONCE WRAPPED, incrementing time\n");
// ++genesis.nTime;
// }
// }
// printf("genesis.nTime = %u \n", genesis.nTime);
// printf("genesis.nNonce = %u \n", genesis.nNonce);
// printf("genesis.nVersion = %u \n", genesis.nVersion);
// printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under.
// printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root
//
// }
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x6218936b0dd6b08e608830192a5da606af1c7fe03f583f046f18a9beeea39194"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<commit_msg>fix compilation using latest boost version<commit_after>// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "assert.h"
#include "chainparams.h"
#include "main.h"
#include "util.h"
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
struct SeedSpec6 {
uint8_t addr[16];
uint16_t port;
};
#include "chainparamsseeds.h"
//
// Main network
//
// Convert the pnSeeds6 array into usable address objects.
static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64_t nOneWeek = 7*24*60*60;
for (unsigned int i = 0; i < count; i++)
{
struct in6_addr ip;
memcpy(&ip, data[i].addr, sizeof(ip));
CAddress addr(CService(ip, data[i].port));
addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
vSeedsOut.push_back(addr);
}
}
class CMainParams : public CChainParams {
public:
CMainParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0xd5;
pchMessageStart[1] = 0x7a;
pchMessageStart[2] = 0xe4;
pchMessageStart[3] = 0x3d;
vAlertPubKey = ParseHex("040251669e27baf52584bfe5a757b61c8f5b0e43761250fadae6330c7ebac33835eaa89c1466547ed1f93283f68bc3bde7856a84debb0ac353e6a27430dad61c82");
nDefaultPort = 44321;
nRPCPort = 44122;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 15);
// Build the genesis block. Note that the output of the genesis coinbase cannot
// be spent as it did not originally exist in the database.
//
const char* pszTimestamp = "24 9 2017 Start of Kurdish Block Chain";
std::vector<CTxIn> vin;
vin.resize(1);
vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
std::vector<CTxOut> vout;
vout.resize(1);
vout[0].SetEmpty();
CTransaction txNew(1, 1506250100, vin, vout, 0);
genesis.vtx.push_back(txNew);
genesis.hashPrevBlock = 0;
genesis.hashMerkleRoot = genesis.BuildMerkleTree();
genesis.nVersion = 1;
genesis.nTime = 1506250100;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 6488;
// uncomment to log genesis block info
// // start
// if (true && genesis.GetHash() != hashGenesisBlock)
// {
// printf("Searching for genesis block...\n");
// uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
// uint256 thash;
//
// while (true)
// {
// thash = genesis.GetHash();
// if (thash <= hashTarget)
// break;
// if ((genesis.nNonce & 0xFFF) == 0)
// {
// printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
// }
// ++genesis.nNonce;
// if (genesis.nNonce == 0)
// {
// printf("NONCE WRAPPED, incrementing time\n");
// ++genesis.nTime;
// }
// }
// printf("genesis.nTime = %u \n", genesis.nTime);
// printf("genesis.nNonce = %u \n", genesis.nNonce);
// printf("genesis.nVersion = %u \n", genesis.nVersion);
// printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under.
// printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root
//
// }
//
// //end
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x0000af8611f474e997efec4294d9144bca3cc93a370d3a3fbea6cb8ef156162e"));
assert(genesis.hashMerkleRoot == uint256("0x9a957fc4121962ed9ff30325a6c67856d1b94ef20d2fdef63d5e74d54e5a9620"));
vSeeds.push_back(CDNSSeedData("america", "america.kurdcoin.org"));
vSeeds.push_back(CDNSSeedData("europ", "europ.kurdcoin.org"));
vSeeds.push_back(CDNSSeedData("asia", "asia.kurdcoin.org"));
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 45);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 63);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 75);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x3d)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x3d)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main));
}
virtual const CBlock& GenesisBlock() const { return genesis; }
virtual Network NetworkID() const { return CChainParams::MAIN; }
virtual const vector<CAddress>& FixedSeeds() const {
return vFixedSeeds;
}
protected:
CBlock genesis;
vector<CAddress> vFixedSeeds;
};
static CMainParams mainParams;
//
// Testnet
//
class CTestNetParams : public CMainParams {
public:
CTestNetParams() {
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ASCII, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
pchMessageStart[0] = 0x3d;
pchMessageStart[1] = 0xa5;
pchMessageStart[2] = 0xd3;
pchMessageStart[3] = 0xa7;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 5);
vAlertPubKey = ParseHex("04c5e13ee9c47c6d9c898153552d61e86be9dfe3a7c944a17b204c0491da30c888d4d8ba1a913b72f0b43496fdc998c2e41d0a1690fefbe32fb6029ed5e6cb096e");
nDefaultPort = 55321;
nRPCPort = 55122;
strDataDir = "testnet";
// Modify the testnet genesis block so the timestamp is valid for a later start.
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 20;
// uncomment to log genesis block info
// // start
// if (true && genesis.GetHash() != hashGenesisBlock)
// {
// printf("Searching for genesis block...\n");
// uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
// uint256 thash;
//
// while (true)
// {
// thash = genesis.GetHash();
// if (thash <= hashTarget)
// break;
// if ((genesis.nNonce & 0xFFF) == 0)
// {
// printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
// }
// ++genesis.nNonce;
// if (genesis.nNonce == 0)
// {
// printf("NONCE WRAPPED, incrementing time\n");
// ++genesis.nTime;
// }
// }
// printf("genesis.nTime = %u \n", genesis.nTime);
// printf("genesis.nNonce = %u \n", genesis.nNonce);
// printf("genesis.nVersion = %u \n", genesis.nVersion);
// printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under.
// printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root
//
// }
//
// //end
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x013cd814a6ca2fcf87c7d1815e025cd5d542ab8732ba4afcd305cd0c904f7496"));
vFixedSeeds.clear();
vSeeds.clear();
base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 66);
base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196);
base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 81);
base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0xd3)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >();
base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0xd3)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >();
convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test));
}
virtual Network NetworkID() const { return CChainParams::TESTNET; }
};
static CTestNetParams testNetParams;
//
// Regression test
//
class CRegTestParams : public CTestNetParams {
public:
CRegTestParams() {
pchMessageStart[0] = 0xf2;
pchMessageStart[1] = 0xa9;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xca;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 1);
genesis.nTime = 1426450258;
genesis.nBits = bnProofOfWorkLimit.GetCompact();
genesis.nNonce = 0;
//hashGenesisBlock = genesis.GetHash();
nDefaultPort = 18445;
strDataDir = "regtest";
// if (true && genesis.GetHash() != hashGenesisBlock)
// {
// printf("Searching for genesis block...\n");
// uint256 hashTarget = CBigNum().SetCompact(genesis.nBits).getuint256();
// uint256 thash;
//
// while (true)
// {
// thash = genesis.GetHash();
// if (thash <= hashTarget)
// break;
// if ((genesis.nNonce & 0xFFF) == 0)
// {
// printf("nonce %08X: hash = %s (target = %s)\n", genesis.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
// }
// ++genesis.nNonce;
// if (genesis.nNonce == 0)
// {
// printf("NONCE WRAPPED, incrementing time\n");
// ++genesis.nTime;
// }
// }
// printf("genesis.nTime = %u \n", genesis.nTime);
// printf("genesis.nNonce = %u \n", genesis.nNonce);
// printf("genesis.nVersion = %u \n", genesis.nVersion);
// printf("genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); //first this, then comment this line out and uncomment the one under.
// printf("genesis.hashMerkleRoot = %s \n", genesis.hashMerkleRoot.ToString().c_str()); //improvised. worked for me, to find merkle root
//
// }
hashGenesisBlock = genesis.GetHash();
assert(hashGenesisBlock == uint256("0x6218936b0dd6b08e608830192a5da606af1c7fe03f583f046f18a9beeea39194"));
vSeeds.clear(); // Regtest mode doesn't have any DNS seeds.
}
virtual bool RequireRPCPassword() const { return false; }
virtual Network NetworkID() const { return CChainParams::REGTEST; }
};
static CRegTestParams regTestParams;
static CChainParams *pCurrentParams = &mainParams;
const CChainParams &Params() {
return *pCurrentParams;
}
void SelectParams(CChainParams::Network network) {
switch (network) {
case CChainParams::MAIN:
pCurrentParams = &mainParams;
break;
case CChainParams::TESTNET:
pCurrentParams = &testNetParams;
break;
case CChainParams::REGTEST:
pCurrentParams = ®TestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
bool SelectParamsFromCommandLine() {
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest) {
return false;
}
if (fRegTest) {
SelectParams(CChainParams::REGTEST);
} else if (fTestNet) {
SelectParams(CChainParams::TESTNET);
} else {
SelectParams(CChainParams::MAIN);
}
return true;
}
<|endoftext|>
|
<commit_before>#include <Galaxy.h>
#include <numeric>
double Galaxy::get_mass() const
{
double unused;
return std::accumulate(stars.begin(), stars.end(), 1.0,
[](double mass , Star const& star) {
return mass + star.get_mass();
});
}
<commit_msg>bugfix sum must start at zero<commit_after>#include <Galaxy.h>
#include <numeric>
double Galaxy::get_mass() const
{
double unused;
return std::accumulate(stars.begin(), stars.end(), 0.0,
[](double mass , Star const& star) {
return mass + star.get_mass();
});
}
<|endoftext|>
|
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
*
* Slideshow 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.
*
* Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "argument_parser.h"
#include "module.h"
#include "module_loader.h"
#include "Kernel.h"
#include "Graphics.h"
#include "OS.h"
#include "path.h"
#include "Log.h"
#include "exception.h"
#include "Transition.h"
#include "state/VideoState.h" /* must be initialized */
// IPC
#ifdef HAVE_DBUS
# include "IPC/dbus.h"
#endif /* HAVE_DBUS */
// FSM
#include "state/State.h"
#include "state/InitialState.h"
#include "state/SwitchState.h"
#include "state/TransitionState.h"
#include "state/ViewState.h"
// Backend
#include "backend/platform.h"
// libportable
#include <portable/Time.h>
#include <portable/asprintf.h>
#include <portable/scandir.h>
#include <portable/cwd.h>
// libc
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cassert>
// Platform
#ifdef __GNUC__
# include <sys/wait.h>
#endif
#ifdef WIN32
# include "win32.h"
# include <direct.h>
# define getcwd _getcwd
# define PATH_MAX _MAX_PATH
#endif
static char* pidfile = NULL;
Kernel::Kernel(const argument_set_t& arg, PlatformBackend* backend)
: _arg(arg)
, _password(NULL)
, _state(NULL)
, _graphics(NULL)
, _browser(NULL)
, _ipc(NULL)
, _backend(backend)
, _running(false) {
verify(_backend);
create_pidpath();
_password = get_password();
}
Kernel::~Kernel(){
delete _backend;
free( _arg.connection_string );
free( _arg.transition_string );
}
void Kernel::init(){
Log::message(Log_Info, "Kernel: Starting slideshow\n");
init_backend();
init_graphics();
init_IPC();
init_browser();
init_fsm();
VideoState::init();
}
void Kernel::cleanup(){
VideoState::cleanup();
delete _state;
module_close(&_browser->module);
delete _graphics;
delete _ipc;
free(pidfile);
free(_password);
cleanup_backend();
_state = NULL;
_browser = NULL;
_graphics = NULL;
_ipc = NULL;
pidfile = NULL;
}
void Kernel::init_backend(){
_backend->init(Vector2ui(_arg.width, _arg.height), _arg.fullscreen > 0);
}
void Kernel::cleanup_backend(){
_backend->cleanup();
}
void Kernel::init_graphics(){
_graphics = new Graphics(_arg.width, _arg.height, _arg.fullscreen > 0);
load_transition( _arg.transition_string ? _arg.transition_string : "fade" );
}
void Kernel::init_IPC(){
#ifdef HAVE_DBUS
_ipc = new DBus(this, 50);
#endif /* HAVE_DBUS */
}
void Kernel::init_browser(){
/* no browser string */
if ( !_arg.connection_string){
Log::message(Log_Warning, "No browser selected, you will not see any slides\n");
return;
}
browser_context_t context = get_context(_arg.connection_string);
// If the contex doesn't contain a password and a password was passed from stdin (arg password)
// we set that as the password in the context.
if ( !context.pass && _password ){
context.pass = strdup(_password);
}
_browser = (struct browser_module_t*)module_open(context.provider, BROWSER_MODULE, MODULE_CALLER_INIT);
if ( !_browser ){
Log::message(Log_Warning, "Failed to load browser plugin '%s': %s\n", context.provider, module_error_string());
return;
}
_browser->context = context;
_browser->module.init((module_handle)_browser);
change_bin(_arg.queue_id);
}
char* Kernel::get_password(){
if ( !_arg.have_password ){
return NULL;
}
char* password = (char*)malloc(256);
verify( scanf("%256s", password) == 1 );
return password;
}
void Kernel::init_fsm(){
TransitionState::set_transition_time(_arg.transition_time);
ViewState::set_view_time(_arg.switch_time);
_state = new InitialState(_browser, _graphics, _ipc);
}
void Kernel::load_transition(const char* name){
_graphics->set_transition(name);
}
void Kernel::poll(){
_backend->poll(_running);
VideoState::poll();
}
void Kernel::action(){
if ( !_state ){
return;
}
bool flip = false;
try {
_state = _state->action(flip);
} catch ( exception& e ){
Log::message(Log_Warning, "State exception: %s\n", e.what());
_state = NULL;
}
if ( flip ){
_backend->swap_buffers();
}
}
void Kernel::print_config() const {
char* cwd = get_current_dir_name();
Log::message(Log_Info, "Slideshow configuration\n");
Log::message(Log_Info, " cwd: %s\n", cwd);
Log::message(Log_Info, " pidfile: %s\n", pidfile);
Log::message(Log_Info, " datapath: %s\n", datapath());
Log::message(Log_Info, " pluginpath: %s\n", pluginpath());
Log::message(Log_Info, " resolution: %dx%d (%s)\n", _arg.width, _arg.height, _arg.fullscreen ? "fullscreen" : "windowed");
Log::message(Log_Info, " transition time: %0.3fs\n", _arg.transition_time);
Log::message(Log_Info, " switch time: %0.3fs\n", _arg.switch_time);
Log::message(Log_Info, " connection string: %s\n", _arg.connection_string);
Log::message(Log_Info, " transition: %s\n", _arg.transition_string);
Log::message(Log_Info, "\n");
free(cwd);
}
void Kernel::print_licence_statement() const {
Log::message(Log_Info, "Slideshow Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>\n");
Log::message(Log_Info, "This program comes with ABSOLUTELY NO WARRANTY.\n");
Log::message(Log_Info, "This is free software, and you are welcome to redistribute it\n");
Log::message(Log_Info, "under certain conditions; see COPYING or <http://www.gnu.org/licenses/>\n");
Log::message(Log_Info, "for details.\n");
Log::message(Log_Info, "\n");
}
#ifdef WIN32
# define SO_SUFFIX ".dll"
#else
# define SO_SUFFIX ".la"
#endif
static int filter(const struct dirent* el){
return fnmatch("*" SO_SUFFIX , el->d_name, 0) == 0;
}
void Kernel::print_transitions(){
Log::message(Log_Info, "Available transitions: \n");
struct dirent **namelist;
int n;
char* path_list = strdup(pluginpath());
char* ctx;
char* path = strtok_r(path_list, ":", &ctx);
while ( path ){
n = scandir(path, &namelist, filter, NULL);
if (n < 0){
perror("scandir");
} else {
for ( int i = 0; i < n; i++ ){
module_handle context = module_open(namelist[i]->d_name, ANY_MODULE, MODULE_CALLEE_INIT);
free(namelist[i]);
if ( !context ){
continue;
}
if ( module_type(context) != TRANSITION_MODULE ){
continue;
}
Log::message(Log_Info, " * %s\n", module_get_name(context));
module_close(context);
}
free(namelist);
}
path = strtok_r(NULL, ":", &ctx);
}
free(path_list);
}
bool Kernel::parse_arguments(argument_set_t& arg, int argc, const char* argv[]){
option_set_t options;
option_initialize(&options, argc, argv);
option_set_description(&options, "Slideshow is an application for showing text and images in a loop on monitors and projectors.");
option_add_flag(&options, "verbose", 'v', "Include debugging messages in log.", &arg.loglevel, Log_Debug);
option_add_flag(&options, "quiet", 'q', "Show only warnings and errors in log.", &arg.loglevel, Log_Warning);
option_add_flag(&options, "fullscreen", 'f', "Start in fullscreen mode", &arg.fullscreen, true);
option_add_flag(&options, "window", 'w', "Start in windowed mode [default]", &arg.fullscreen, false);
option_add_flag(&options, "daemon", 'd', "Run in background mode", &arg.mode, DaemonMode);
option_add_flag(&options, "foreground", 'd', "Run in foreground mode", &arg.mode, ForegroundMode);
option_add_flag(&options, "list-transitions", 0, "List available transitions", &arg.mode, ListTransitionMode);
option_add_flag(&options, "stdin-password", 0, "Except the input (e.g database password) to come from stdin", &arg.have_password, true);
option_add_string(&options, "browser", 0, "Browser connection string. provider://user[:pass]@host[:port]/name", &arg.connection_string);
option_add_string(&options, "transition", 't', "Set slide transition plugin [fade]", &arg.transition_string);
option_add_int(&options, "collection-id", 'c', "ID of the queue to display (deprecated, use `--queue-id')", &arg.queue_id);
option_add_int(&options, "queue-id", 'c', "ID of the queue to display", &arg.queue_id);
option_add_format(&options, "resolution", 'r', "Resolution", "WIDTHxHEIGHT", "%dx%d", &arg.width, &arg.height);
/* logging options */
option_add_string(&options, "file-log", 0, "Log to regular file (appending)", &arg.log_file);
option_add_string(&options, "fifo-log", 0, "Log to a named pipe", &arg.log_fifo);
option_add_string(&options, "uds-log", 0, "Log to a unix domain socket", &arg.log_domain);
int n = option_parse(&options);
option_finalize(&options);
if ( n < 0 ){
return false;
}
if ( n != argc ){
printf("%d %d\n", n, argc);
printf("%s: unrecognized option '%s'\n", argv[0], argv[n+1]);
printf("Try `%s --help' for more information.\n", argv[0]);
return false;
}
return true;
}
void Kernel::play_video(const char* fullpath){
#ifndef WIN32
Log::message(Log_Info, "Kernel: Playing video \"%s\"\n", fullpath);
int status;
if ( fork() == 0 ){
execlp("mplayer", "", "-fs", "-really-quiet", fullpath, NULL);
exit(0);
}
::wait(&status);
#else /* WIN32 */
Log::message(Log_Warning, "Kernel: Video playback is not supported on this platform (skipping \"%s\")\n", fullpath);
#endif /* WIN32 */
}
void Kernel::start(){
_running = true;
}
void Kernel::quit(){
_running = false;
}
void Kernel::reload_browser(){
_browser->queue_reload(_browser);
}
void Kernel::change_bin(unsigned int id){
Log::message(Log_Verbose, "Kernel: Switching to queue %d\n", id);
_browser->queue_set(_browser, id);
_browser->queue_reload(_browser);
}
void Kernel::ipc_quit(){
delete _ipc;
_ipc = NULL;
}
void Kernel::debug_dumpqueue(){
_browser->queue_dump(_browser);
}
void Kernel::create_pidpath(){
char* cwd = get_current_dir_name();
verify( asprintf(&pidfile, "%s/slideshow.pid", cwd) >= 0 );
free(cwd);
}
const char* Kernel::pidpath(){
return pidfile;
}
<commit_msg>checking for null pointer<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>
*
* Slideshow 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.
*
* Slideshow 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 Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "argument_parser.h"
#include "module.h"
#include "module_loader.h"
#include "Kernel.h"
#include "Graphics.h"
#include "OS.h"
#include "path.h"
#include "Log.h"
#include "exception.h"
#include "Transition.h"
#include "state/VideoState.h" /* must be initialized */
// IPC
#ifdef HAVE_DBUS
# include "IPC/dbus.h"
#endif /* HAVE_DBUS */
// FSM
#include "state/State.h"
#include "state/InitialState.h"
#include "state/SwitchState.h"
#include "state/TransitionState.h"
#include "state/ViewState.h"
// Backend
#include "backend/platform.h"
// libportable
#include <portable/Time.h>
#include <portable/asprintf.h>
#include <portable/scandir.h>
#include <portable/cwd.h>
// libc
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cassert>
// Platform
#ifdef __GNUC__
# include <sys/wait.h>
#endif
#ifdef WIN32
# include "win32.h"
# include <direct.h>
# define getcwd _getcwd
# define PATH_MAX _MAX_PATH
#endif
static char* pidfile = NULL;
Kernel::Kernel(const argument_set_t& arg, PlatformBackend* backend)
: _arg(arg)
, _password(NULL)
, _state(NULL)
, _graphics(NULL)
, _browser(NULL)
, _ipc(NULL)
, _backend(backend)
, _running(false) {
verify(_backend);
create_pidpath();
_password = get_password();
}
Kernel::~Kernel(){
delete _backend;
free( _arg.connection_string );
free( _arg.transition_string );
}
void Kernel::init(){
Log::message(Log_Info, "Kernel: Starting slideshow\n");
init_backend();
init_graphics();
init_IPC();
init_browser();
init_fsm();
VideoState::init();
}
void Kernel::cleanup(){
VideoState::cleanup();
delete _state;
module_close(&_browser->module);
delete _graphics;
delete _ipc;
free(pidfile);
free(_password);
cleanup_backend();
_state = NULL;
_browser = NULL;
_graphics = NULL;
_ipc = NULL;
pidfile = NULL;
}
void Kernel::init_backend(){
_backend->init(Vector2ui(_arg.width, _arg.height), _arg.fullscreen > 0);
}
void Kernel::cleanup_backend(){
_backend->cleanup();
}
void Kernel::init_graphics(){
_graphics = new Graphics(_arg.width, _arg.height, _arg.fullscreen > 0);
load_transition( _arg.transition_string ? _arg.transition_string : "fade" );
}
void Kernel::init_IPC(){
#ifdef HAVE_DBUS
_ipc = new DBus(this, 50);
#endif /* HAVE_DBUS */
}
void Kernel::init_browser(){
/* no browser string */
if ( !_arg.connection_string){
Log::message(Log_Warning, "No browser selected, you will not see any slides\n");
return;
}
browser_context_t context = get_context(_arg.connection_string);
// If the contex doesn't contain a password and a password was passed from stdin (arg password)
// we set that as the password in the context.
if ( !context.pass && _password ){
context.pass = strdup(_password);
}
_browser = (struct browser_module_t*)module_open(context.provider, BROWSER_MODULE, MODULE_CALLER_INIT);
if ( !_browser ){
Log::message(Log_Warning, "Failed to load browser plugin '%s': %s\n", context.provider, module_error_string());
return;
}
_browser->context = context;
_browser->module.init((module_handle)_browser);
change_bin(_arg.queue_id);
}
char* Kernel::get_password(){
if ( !_arg.have_password ){
return NULL;
}
char* password = (char*)malloc(256);
verify( scanf("%256s", password) == 1 );
return password;
}
void Kernel::init_fsm(){
TransitionState::set_transition_time(_arg.transition_time);
ViewState::set_view_time(_arg.switch_time);
_state = new InitialState(_browser, _graphics, _ipc);
}
void Kernel::load_transition(const char* name){
_graphics->set_transition(name);
}
void Kernel::poll(){
_backend->poll(_running);
VideoState::poll();
}
void Kernel::action(){
if ( !_state ){
return;
}
bool flip = false;
try {
_state = _state->action(flip);
} catch ( exception& e ){
Log::message(Log_Warning, "State exception: %s\n", e.what());
_state = NULL;
}
if ( flip ){
_backend->swap_buffers();
}
}
void Kernel::print_config() const {
char* cwd = get_current_dir_name();
Log::message(Log_Info, "Slideshow configuration\n");
Log::message(Log_Info, " cwd: %s\n", cwd);
Log::message(Log_Info, " pidfile: %s\n", pidfile);
Log::message(Log_Info, " datapath: %s\n", datapath());
Log::message(Log_Info, " pluginpath: %s\n", pluginpath());
Log::message(Log_Info, " resolution: %dx%d (%s)\n", _arg.width, _arg.height, _arg.fullscreen ? "fullscreen" : "windowed");
Log::message(Log_Info, " transition time: %0.3fs\n", _arg.transition_time);
Log::message(Log_Info, " switch time: %0.3fs\n", _arg.switch_time);
Log::message(Log_Info, " connection string: %s\n", _arg.connection_string);
Log::message(Log_Info, " transition: %s\n", _arg.transition_string);
Log::message(Log_Info, "\n");
free(cwd);
}
void Kernel::print_licence_statement() const {
Log::message(Log_Info, "Slideshow Copyright (C) 2008-2010 David Sveningsson <ext@sidvind.com>\n");
Log::message(Log_Info, "This program comes with ABSOLUTELY NO WARRANTY.\n");
Log::message(Log_Info, "This is free software, and you are welcome to redistribute it\n");
Log::message(Log_Info, "under certain conditions; see COPYING or <http://www.gnu.org/licenses/>\n");
Log::message(Log_Info, "for details.\n");
Log::message(Log_Info, "\n");
}
#ifdef WIN32
# define SO_SUFFIX ".dll"
#else
# define SO_SUFFIX ".la"
#endif
static int filter(const struct dirent* el){
return fnmatch("*" SO_SUFFIX , el->d_name, 0) == 0;
}
void Kernel::print_transitions(){
Log::message(Log_Info, "Available transitions: \n");
struct dirent **namelist;
int n;
char* path_list = strdup(pluginpath());
char* ctx;
char* path = strtok_r(path_list, ":", &ctx);
while ( path ){
n = scandir(path, &namelist, filter, NULL);
if (n < 0){
perror("scandir");
} else {
for ( int i = 0; i < n; i++ ){
module_handle context = module_open(namelist[i]->d_name, ANY_MODULE, MODULE_CALLEE_INIT);
free(namelist[i]);
if ( !context ){
continue;
}
if ( module_type(context) != TRANSITION_MODULE ){
continue;
}
Log::message(Log_Info, " * %s\n", module_get_name(context));
module_close(context);
}
free(namelist);
}
path = strtok_r(NULL, ":", &ctx);
}
free(path_list);
}
bool Kernel::parse_arguments(argument_set_t& arg, int argc, const char* argv[]){
option_set_t options;
option_initialize(&options, argc, argv);
option_set_description(&options, "Slideshow is an application for showing text and images in a loop on monitors and projectors.");
option_add_flag(&options, "verbose", 'v', "Include debugging messages in log.", &arg.loglevel, Log_Debug);
option_add_flag(&options, "quiet", 'q', "Show only warnings and errors in log.", &arg.loglevel, Log_Warning);
option_add_flag(&options, "fullscreen", 'f', "Start in fullscreen mode", &arg.fullscreen, true);
option_add_flag(&options, "window", 'w', "Start in windowed mode [default]", &arg.fullscreen, false);
option_add_flag(&options, "daemon", 'd', "Run in background mode", &arg.mode, DaemonMode);
option_add_flag(&options, "foreground", 'd', "Run in foreground mode", &arg.mode, ForegroundMode);
option_add_flag(&options, "list-transitions", 0, "List available transitions", &arg.mode, ListTransitionMode);
option_add_flag(&options, "stdin-password", 0, "Except the input (e.g database password) to come from stdin", &arg.have_password, true);
option_add_string(&options, "browser", 0, "Browser connection string. provider://user[:pass]@host[:port]/name", &arg.connection_string);
option_add_string(&options, "transition", 't', "Set slide transition plugin [fade]", &arg.transition_string);
option_add_int(&options, "collection-id", 'c', "ID of the queue to display (deprecated, use `--queue-id')", &arg.queue_id);
option_add_int(&options, "queue-id", 'c', "ID of the queue to display", &arg.queue_id);
option_add_format(&options, "resolution", 'r', "Resolution", "WIDTHxHEIGHT", "%dx%d", &arg.width, &arg.height);
/* logging options */
option_add_string(&options, "file-log", 0, "Log to regular file (appending)", &arg.log_file);
option_add_string(&options, "fifo-log", 0, "Log to a named pipe", &arg.log_fifo);
option_add_string(&options, "uds-log", 0, "Log to a unix domain socket", &arg.log_domain);
int n = option_parse(&options);
option_finalize(&options);
if ( n < 0 ){
return false;
}
if ( n != argc ){
printf("%d %d\n", n, argc);
printf("%s: unrecognized option '%s'\n", argv[0], argv[n+1]);
printf("Try `%s --help' for more information.\n", argv[0]);
return false;
}
return true;
}
void Kernel::play_video(const char* fullpath){
#ifndef WIN32
Log::message(Log_Info, "Kernel: Playing video \"%s\"\n", fullpath);
int status;
if ( fork() == 0 ){
execlp("mplayer", "", "-fs", "-really-quiet", fullpath, NULL);
exit(0);
}
::wait(&status);
#else /* WIN32 */
Log::message(Log_Warning, "Kernel: Video playback is not supported on this platform (skipping \"%s\")\n", fullpath);
#endif /* WIN32 */
}
void Kernel::start(){
_running = true;
}
void Kernel::quit(){
_running = false;
}
void Kernel::reload_browser(){
if ( _browser ){
_browser->queue_reload(_browser);
}
}
void Kernel::change_bin(unsigned int id){
Log::message(Log_Verbose, "Kernel: Switching to queue %d\n", id);
if ( _browser ){
_browser->queue_set(_browser, id);
_browser->queue_reload(_browser);
}
}
void Kernel::ipc_quit(){
delete _ipc;
_ipc = NULL;
}
void Kernel::debug_dumpqueue(){
if ( _browser ){
_browser->queue_dump(_browser);
}
}
void Kernel::create_pidpath(){
char* cwd = get_current_dir_name();
verify( asprintf(&pidfile, "%s/slideshow.pid", cwd) >= 0 );
free(cwd);
}
const char* Kernel::pidpath(){
return pidfile;
}
<|endoftext|>
|
<commit_before><commit_msg>Update AliFemtoCutMonitorPairBetaT.cxx<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include "Message.h"
#include "Ladder.h"
#include "SearchBoard.h"
#include "Point.h"
using namespace std;
#define ALIVE true
#define DEAD false
// シチョウ探索
static bool IsLadderCaptured( const int depth, search_game_info_t *game, const int ren_xy, const int turn_color );
////////////////////////////////
// 現在の局面のシチョウ探索 //
////////////////////////////////
void
LadderExtension( game_info_t *game, int color, bool *ladder_pos )
{
const string_t *string = game->string;
search_game_info_t ladder_game;
bool checked[BOARD_MAX] = { false };
int neighbor, ladder = PASS;
bool flag;
CopyGameForSearch(&ladder_game, game);
for (int i = 0; i < MAX_STRING; i++) {
if (!string[i].flag ||
string[i].color != color) {
continue;
}
// アタリから逃げる着手箇所
ladder = string[i].lib[0];
flag = false;
// アタリを逃げる手で未探索のものを確認
if (!checked[ladder] && string[i].libs == 1) {
// 隣接する敵連を取って助かるかを確認
neighbor = string[i].neighbor[0];
while (neighbor != NEIGHBOR_END && !flag) {
if (string[neighbor].libs == 1) {
if (IsLegal(game, string[neighbor].lib[0], color)) {
PutStoneForSearch(&ladder_game, string[neighbor].lib[0], color);
if (IsLadderCaptured(0, &ladder_game, string[i].origin, FLIP_COLOR(color)) == DEAD) {
if (string[i].size >= 2) {
ladder_pos[string[neighbor].lib[0]] = true;
}
} else {
flag = true;
}
Undo(&ladder_game);
}
}
neighbor = string[i].neighbor[neighbor];
}
// 取って助からない時は逃げてみる
if (!flag) {
if (IsLegal(game, ladder, color)) {
PutStoneForSearch(&ladder_game, ladder, color);
if (string[i].size >= 2 &&
IsLadderCaptured(0, &ladder_game, ladder, FLIP_COLOR(color)) == DEAD) {
ladder_pos[ladder] = true;
}
Undo(&ladder_game);
}
}
checked[ladder] = true;
}
}
}
////////////////////
// シチョウ探索 //
////////////////////
static bool
IsLadderCaptured( const int depth, search_game_info_t *game, const int ren_xy, const int turn_color )
{
const char *board = game->board;
const string_t *string = game->string;
const int str = game->string_id[ren_xy];
int escape_color, capture_color;
int escape_xy, capture_xy;
int neighbor;
if (depth >= 100) {
return ALIVE;
}
if (board[ren_xy] == S_EMPTY) {
return DEAD;
} else if (string[str].libs >= 3) {
return ALIVE;
}
escape_color = board[ren_xy];
capture_color = FLIP_COLOR(escape_color);
if (turn_color == escape_color) {
// 周囲の敵連が取れるか確認し,
// 取れるなら取って探索を続ける
neighbor = string[str].neighbor[0];
while (neighbor != NEIGHBOR_END) {
if (string[neighbor].libs == 1) {
if (IsLegalForSearch(game, string[neighbor].lib[0], escape_color)) {
PutStoneForSearch(game, string[neighbor].lib[0], escape_color);
if (IsLadderCaptured(depth + 1, game, ren_xy, FLIP_COLOR(turn_color)) == ALIVE) {
Undo(game);
return ALIVE;
}
Undo(game);
}
}
neighbor = string[str].neighbor[neighbor];
}
// 逃げる手を打ってみて探索を続ける
escape_xy = string[str].lib[0];
while (escape_xy != LIBERTY_END) {
if (IsLegalForSearch(game, escape_xy, escape_color)) {
PutStoneForSearch(game, escape_xy, escape_color);
if (IsLadderCaptured(depth + 1, game, ren_xy, FLIP_COLOR(turn_color)) == ALIVE) {
Undo(game);
return ALIVE;
}
Undo(game);
}
escape_xy = string[str].lib[escape_xy];
}
return DEAD;
} else {
if (string[str].libs == 1) {
return DEAD;
}
// 追いかける側なのでアタリにする手を打ってみる
capture_xy = string[str].lib[0];
while (capture_xy != LIBERTY_END) {
if (IsLegalForSearch(game, capture_xy, capture_color)) {
PutStoneForSearch(game, capture_xy, capture_color);
if (IsLadderCaptured(depth + 1, game, ren_xy, FLIP_COLOR(turn_color)) == DEAD) {
Undo(game);
return DEAD;
}
Undo(game);
}
capture_xy = string[str].lib[capture_xy];
}
}
return ALIVE;
}
//////////////////////////////////////////
// 助からないシチョウを逃げる手か判定 //
//////////////////////////////////////////
bool
CheckLadderExtension( game_info_t *game, int color, int pos )
{
char *board = game->board;
string_t *string = game->string;
int *string_id = game->string_id;
int ladder = PASS;
search_game_info_t ladder_game;
bool flag = false;
int id;
if (board[pos] != color){
return false;
}
id = string_id[pos];
ladder = string[id].lib[0];
if (string[id].libs == 1 &&
IsLegal(game, ladder, color)) {
CopyGameForSearch(&ladder_game, game);
PutStoneForSearch(&ladder_game, ladder, color);
if (IsLadderCaptured(0, &ladder_game, ladder, FLIP_COLOR(color)) == DEAD) {
flag = true;
} else {
flag = false;
}
}
return flag;
}
<commit_msg>Modify ladder search<commit_after>#include <iostream>
#include "Message.h"
#include "Ladder.h"
#include "SearchBoard.h"
#include "Point.h"
using namespace std;
#define ALIVE true
#define DEAD false
// シチョウ探索
static bool IsLadderCaptured( const int depth, search_game_info_t *game, const int ren_xy, const int turn_color );
////////////////////////////////
// 現在の局面のシチョウ探索 //
////////////////////////////////
void
LadderExtension( game_info_t *game, int color, bool *ladder_pos )
{
const string_t *string = game->string;
search_game_info_t ladder_game;
bool checked[BOARD_MAX] = { false };
int neighbor, ladder = PASS;
bool flag;
CopyGameForSearch(&ladder_game, game);
for (int i = 0; i < MAX_STRING; i++) {
if (!string[i].flag ||
string[i].color != color) {
continue;
}
// アタリから逃げる着手箇所
ladder = string[i].lib[0];
flag = false;
// アタリを逃げる手で未探索のものを確認
if (!checked[ladder] && string[i].libs == 1) {
// 隣接する敵連を取って助かるかを確認
neighbor = string[i].neighbor[0];
while (neighbor != NEIGHBOR_END && !flag) {
if (string[neighbor].libs == 1) {
if (IsLegal(game, string[neighbor].lib[0], color)) {
PutStoneForSearch(&ladder_game, string[neighbor].lib[0], color);
if (IsLadderCaptured(0, &ladder_game, string[i].origin, FLIP_COLOR(color)) == DEAD) {
if (string[i].size >= 2) {
ladder_pos[string[neighbor].lib[0]] = true;
}
} else {
flag = true;
}
Undo(&ladder_game);
}
}
neighbor = string[i].neighbor[neighbor];
}
// 取って助からない時は逃げてみる
if (!flag) {
if (IsLegal(game, ladder, color)) {
PutStoneForSearch(&ladder_game, ladder, color);
if (string[i].size >= 2 &&
IsLadderCaptured(0, &ladder_game, ladder, FLIP_COLOR(color)) == DEAD) {
ladder_pos[ladder] = true;
}
Undo(&ladder_game);
}
}
checked[ladder] = true;
}
}
}
////////////////////
// シチョウ探索 //
////////////////////
static bool
IsLadderCaptured( const int depth, search_game_info_t *game, const int ren_xy, const int turn_color )
{
const char *board = game->board;
const string_t *string = game->string;
const int str = game->string_id[ren_xy];
int escape_color, capture_color;
int escape_xy, capture_xy;
int neighbor;
bool result;
if (depth >= 100) {
return ALIVE;
}
if (board[ren_xy] == S_EMPTY) {
return DEAD;
} else if (string[str].libs >= 3) {
return ALIVE;
}
escape_color = board[ren_xy];
capture_color = FLIP_COLOR(escape_color);
if (turn_color == escape_color) {
// 周囲の敵連が取れるか確認し,
// 取れるなら取って探索を続ける
neighbor = string[str].neighbor[0];
while (neighbor != NEIGHBOR_END) {
if (string[neighbor].libs == 1) {
if (IsLegalForSearch(game, string[neighbor].lib[0], escape_color)) {
PutStoneForSearch(game, string[neighbor].lib[0], escape_color);
result = IsLadderCaptured(depth + 1, game, ren_xy, FLIP_COLOR(turn_color));
Undo(game);
if (result == ALIVE) {
return ALIVE;
}
}
}
neighbor = string[str].neighbor[neighbor];
}
// 逃げる手を打ってみて探索を続ける
escape_xy = string[str].lib[0];
while (escape_xy != LIBERTY_END) {
if (IsLegalForSearch(game, escape_xy, escape_color)) {
PutStoneForSearch(game, escape_xy, escape_color);
result = IsLadderCaptured(depth + 1, game, ren_xy, FLIP_COLOR(turn_color));
Undo(game);
if (result == ALIVE) {
return ALIVE;
}
}
escape_xy = string[str].lib[escape_xy];
}
return DEAD;
} else {
if (string[str].libs == 1) {
return DEAD;
}
// 追いかける側なのでアタリにする手を打ってみる
capture_xy = string[str].lib[0];
while (capture_xy != LIBERTY_END) {
if (IsLegalForSearch(game, capture_xy, capture_color)) {
PutStoneForSearch(game, capture_xy, capture_color);
result = IsLadderCaptured(depth + 1, game, ren_xy, FLIP_COLOR(turn_color));
Undo(game);
if (result == DEAD) {
return DEAD;
}
}
capture_xy = string[str].lib[capture_xy];
}
}
return ALIVE;
}
//////////////////////////////////////////
// 助からないシチョウを逃げる手か判定 //
//////////////////////////////////////////
bool
CheckLadderExtension( game_info_t *game, int color, int pos )
{
char *board = game->board;
string_t *string = game->string;
int *string_id = game->string_id;
int ladder = PASS;
search_game_info_t ladder_game;
bool flag = false;
int id;
if (board[pos] != color){
return false;
}
id = string_id[pos];
ladder = string[id].lib[0];
if (string[id].libs == 1 &&
IsLegal(game, ladder, color)) {
CopyGameForSearch(&ladder_game, game);
PutStoneForSearch(&ladder_game, ladder, color);
if (IsLadderCaptured(0, &ladder_game, ladder, FLIP_COLOR(color)) == DEAD) {
flag = true;
} else {
flag = false;
}
}
return flag;
}
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexAsm.cxx
** Lexer for Assembler, just for the Masm Syntax
** Written by The Black Horus
**/
// Copyright 1998-2002 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 "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_' || ch =='\\');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.');
}
inline bool isAsmOperator(char ch) {
if (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 == ':')
return true;
return false;
}
static void ColouriseAsmDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &cpuInstruction = *keywordlists[0];
WordList &mathInstruction = *keywordlists[1];
WordList ®isters = *keywordlists[2];
WordList &directive = *keywordlists[3];
WordList &directiveOperand = *keywordlists[4];
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward())
{
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_ASM_OPERATOR) {
sc.SetState(SCE_ASM_DEFAULT);
}else if (sc.state == SCE_ASM_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_ASM_DEFAULT);
}
} else if (sc.state == SCE_ASM_IDENTIFIER) {
if (!IsAWordChar(sc.ch) ) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (cpuInstruction.InList(s)) {
sc.ChangeState(SCE_ASM_CPUINSTRUCTION);
} else if (mathInstruction.InList(s)) {
sc.ChangeState(SCE_ASM_MATHINSTRUCTION);
} else if (registers.InList(s)) {
sc.ChangeState(SCE_ASM_REGISTER);
} else if (directive.InList(s)) {
sc.ChangeState(SCE_ASM_DIRECTIVE);
} else if (directiveOperand.InList(s)) {
sc.ChangeState(SCE_ASM_DIRECTIVEOPERAND);
}
sc.SetState(SCE_ASM_DEFAULT);
}
}
else if (sc.state == SCE_ASM_COMMENT ) {
if (sc.atLineEnd) {
sc.SetState(SCE_ASM_DEFAULT);
}
} else if (sc.state == SCE_ASM_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_ASM_DEFAULT);
} else if (sc.atLineEnd) {
sc.ForwardSetState(SCE_ASM_DEFAULT);
}
}
// Determine if a new state should be entered.
else if (sc.state == SCE_ASM_DEFAULT) {
if (sc.ch == ';'){
sc.SetState(SCE_ASM_COMMENT);
} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {
sc.SetState(SCE_ASM_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_ASM_IDENTIFIER);
} else if (sc.Match('\"')) {
sc.SetState(SCE_ASM_STRING);
}
}
}
sc.Complete();
}
static const char * const asmWordListDesc[] = {
"CPU instructions",
"FPU instructions",
"Registers",
"Directives",
"Directive operands",
0
};
LexerModule lmAsm(SCLEX_ASM, ColouriseAsmDoc, "asm", 0, asmWordListDesc);
<commit_msg>Enhancements to Asm lexer by Kein-Hong Man.<commit_after>// Scintilla source code edit control
/** @file LexAsm.cxx
** Lexer for Assembler, just for the MASM syntax
** Written by The Black Horus
** Enhancements and NASM stuff by Kein-Hong Man, 2003-10
** SCE_ASM_COMMENTBLOCK and SCE_ASM_CHARACTER are for future GNU as colouring
**/
// Copyright 1998-2003 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 "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' ||
ch == '_' || ch == '?');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_' || ch == '.' ||
ch == '%' || ch == '@' || ch == '$' || ch == '?');
}
static inline bool IsAsmOperator(char ch) {
if (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 == ':')
return true;
return false;
}
static void ColouriseAsmDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &cpuInstruction = *keywordlists[0];
WordList &mathInstruction = *keywordlists[1];
WordList ®isters = *keywordlists[2];
WordList &directive = *keywordlists[3];
WordList &directiveOperand = *keywordlists[4];
WordList &extInstruction = *keywordlists[5];
// Do not leak onto next line
if (initStyle == SCE_ASM_STRINGEOL)
initStyle = SCE_ASM_DEFAULT;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward())
{
// Prevent SCE_ASM_STRINGEOL from leaking back to previous line
if (sc.atLineStart && (sc.state == SCE_ASM_STRING)) {
sc.SetState(SCE_ASM_STRING);
} else if (sc.atLineStart && (sc.state == SCE_ASM_CHARACTER)) {
sc.SetState(SCE_ASM_CHARACTER);
}
// Handle line continuation generically.
if (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_ASM_OPERATOR) {
if (!IsAsmOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_ASM_DEFAULT);
}
}else if (sc.state == SCE_ASM_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_ASM_DEFAULT);
}
} else if (sc.state == SCE_ASM_IDENTIFIER) {
if (!IsAWordChar(sc.ch) ) {
char s[100];
sc.GetCurrentLowered(s, sizeof(s));
if (cpuInstruction.InList(s)) {
sc.ChangeState(SCE_ASM_CPUINSTRUCTION);
} else if (mathInstruction.InList(s)) {
sc.ChangeState(SCE_ASM_MATHINSTRUCTION);
} else if (registers.InList(s)) {
sc.ChangeState(SCE_ASM_REGISTER);
} else if (directive.InList(s)) {
sc.ChangeState(SCE_ASM_DIRECTIVE);
} else if (directiveOperand.InList(s)) {
sc.ChangeState(SCE_ASM_DIRECTIVEOPERAND);
} else if (extInstruction.InList(s)) {
sc.ChangeState(SCE_ASM_EXTINSTRUCTION);
}
sc.SetState(SCE_ASM_DEFAULT);
}
}
else if (sc.state == SCE_ASM_COMMENT ) {
if (sc.atLineEnd) {
sc.SetState(SCE_ASM_DEFAULT);
}
} else if (sc.state == SCE_ASM_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_ASM_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_ASM_STRINGEOL);
sc.ForwardSetState(SCE_ASM_DEFAULT);
}
} else if (sc.state == SCE_ASM_CHARACTER) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_ASM_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_ASM_STRINGEOL);
sc.ForwardSetState(SCE_ASM_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_ASM_DEFAULT) {
if (sc.ch == ';'){
sc.SetState(SCE_ASM_COMMENT);
} else if (isdigit(sc.ch) || (sc.ch == '.' && isdigit(sc.chNext))) {
sc.SetState(SCE_ASM_NUMBER);
} else if (IsAWordStart(sc.ch)) {
sc.SetState(SCE_ASM_IDENTIFIER);
} else if (sc.ch == '\"') {
sc.SetState(SCE_ASM_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_ASM_CHARACTER);
} else if (IsAsmOperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_ASM_OPERATOR);
}
}
}
sc.Complete();
}
static const char * const asmWordListDesc[] = {
"CPU instructions",
"FPU instructions",
"Registers",
"Directives",
"Directive operands",
"Extended instructions",
0
};
LexerModule lmAsm(SCLEX_ASM, ColouriseAsmDoc, "asm", 0, asmWordListDesc);
<|endoftext|>
|
<commit_before>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 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 "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (style == SCE_C_OPERATOR) {
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 cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<commit_msg>Folding implemented for fold comments //{..//} and C# #region..#endregion.<commit_after>// Scintilla source code edit control
/** @file LexCPP.cxx
** Lexer for C++, C, Java, and Javascript.
**/
// Copyright 1998-2002 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 "StyleContext.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
static bool IsOKBeforeRE(const int ch) {
return (ch == '(') || (ch == '=') || (ch == ',');
}
static inline bool IsAWordChar(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '.' || ch == '_');
}
static inline bool IsAWordStart(const int ch) {
return (ch < 0x80) && (isalnum(ch) || ch == '_');
}
static inline bool IsASpaceOrTab(const int ch) {
return (ch == ' ') || (ch == '\t');
}
static inline bool IsADoxygenChar(const int ch) {
return (islower(ch) || ch == '$' || ch == '@' ||
ch == '\\' || ch == '&' || ch == '<' ||
ch == '>' || ch == '#' || ch == '{' ||
ch == '}' || ch == '[' || ch == ']');
}
static inline bool IsStateComment(const int state) {
return ((state == SCE_C_COMMENT) ||
(state == SCE_C_COMMENTLINE) ||
(state == SCE_C_COMMENTDOC) ||
(state == SCE_C_COMMENTDOCKEYWORD) ||
(state == SCE_C_COMMENTDOCKEYWORDERROR));
}
static inline bool IsStateString(const int state) {
return ((state == SCE_C_STRING) || (state == SCE_C_VERBATIM));
}
static void ColouriseCppDoc(unsigned int startPos, int length, int initStyle, WordList *keywordlists[],
Accessor &styler) {
WordList &keywords = *keywordlists[0];
WordList &keywords2 = *keywordlists[1];
WordList &keywords3 = *keywordlists[2];
bool stylingWithinPreprocessor = styler.GetPropertyInt("styling.within.preprocessor") != 0;
// Do not leak onto next line
if (initStyle == SCE_C_STRINGEOL)
initStyle = SCE_C_DEFAULT;
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
StyleContext sc(startPos, length, initStyle, styler);
for (; sc.More(); sc.Forward()) {
if (sc.atLineStart && (sc.state == SCE_C_STRING)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line
sc.SetState(SCE_C_STRING);
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if (sc.Match("\\\n")) {
sc.Forward();
continue;
}
if (sc.Match("\\\r\n")) {
sc.Forward();
sc.Forward();
continue;
}
}
// Determine if the current state should terminate.
if (sc.state == SCE_C_OPERATOR) {
sc.SetState(SCE_C_DEFAULT);
} else if (sc.state == SCE_C_NUMBER) {
if (!IsAWordChar(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_IDENTIFIER) {
if (!IsAWordChar(sc.ch) || (sc.ch == '.')) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (keywords.InList(s)) {
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD);
} else if (keywords2.InList(s)) {
sc.ChangeState(SCE_C_WORD2);
}
sc.SetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_PREPROCESSOR) {
if (stylingWithinPreprocessor) {
if (IsASpace(sc.ch)) {
sc.SetState(SCE_C_DEFAULT);
}
} else {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_COMMENT) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_COMMENTDOC) {
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '@' || sc.ch == '\\') {
sc.SetState(SCE_C_COMMENTDOCKEYWORD);
}
} else if (sc.state == SCE_C_COMMENTLINE || sc.state == SCE_C_COMMENTLINEDOC) {
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_COMMENTDOCKEYWORD) {
if (sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (!IsADoxygenChar(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if (!isspace(sc.ch) || !keywords3.InList(s+1)) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
}
sc.SetState(SCE_C_COMMENTDOC);
}
} else if (sc.state == SCE_C_STRING) {
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
}
} else if (sc.state == SCE_C_CHARACTER) {
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL);
sc.ForwardSetState(SCE_C_DEFAULT);
visibleChars = 0;
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
sc.ForwardSetState(SCE_C_DEFAULT);
}
} else if (sc.state == SCE_C_REGEX) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == '/') {
sc.ForwardSetState(SCE_C_DEFAULT);
} else if (sc.ch == '\\') {
// Gobble up the quoted character
if (sc.chNext == '\\' || sc.chNext == '/') {
sc.Forward();
}
}
} else if (sc.state == SCE_C_VERBATIM) {
if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT);
}
}
} else if (sc.state == SCE_C_UUID) {
if (sc.ch == '\r' || sc.ch == '\n' || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT);
}
}
// Determine if a new state should be entered.
if (sc.state == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM);
sc.Forward();
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER);
}
} else if (IsAWordStart(sc.ch) || (sc.ch == '@')) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC);
} else {
sc.SetState(SCE_C_COMMENT);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if (sc.Match("///") || sc.Match("//!")) // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC);
else
sc.SetState(SCE_C_COMMENTLINE);
} else if (sc.ch == '/' && IsOKBeforeRE(chPrevNonWhite)) {
sc.SetState(SCE_C_REGEX);
} else if (sc.ch == '\"') {
sc.SetState(SCE_C_STRING);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ') && (sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT);
}
} else if (isoperator(static_cast<char>(sc.ch))) {
sc.SetState(SCE_C_OPERATOR);
}
}
if (sc.atLineEnd) {
// Reset states to begining of colourise so no surprises
// if different sets of lines lexed.
chPrevNonWhite = ' ';
visibleChars = 0;
lastWordWasUUID = false;
}
if (!IsASpace(sc.ch)) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
}
sc.Complete();
}
static bool IsStreamCommentStyle(int style) {
return style == SCE_C_COMMENT ||
style == SCE_C_COMMENTDOC ||
style == SCE_C_COMMENTDOCKEYWORD ||
style == SCE_C_COMMENTDOCKEYWORDERROR;
}
static bool MatchString(Accessor &styler, int pos, const char *s) {
for (int i=0; *s; i++) {
if (*s != styler.SafeGetCharAt(pos+i))
return false;
s++;
}
return true;
}
static void FoldCppDoc(unsigned int startPos, int length, int initStyle, WordList *[],
Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
int styleNext = styler.StyleAt(startPos);
int style = initStyle;
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int stylePrev = style;
style = styleNext;
styleNext = styler.StyleAt(i + 1);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
if (foldComment && IsStreamCommentStyle(style)) {
if (!IsStreamCommentStyle(stylePrev)) {
levelCurrent++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelCurrent--;
}
}
if (foldComment && (style == SCE_C_COMMENTLINE)) {
if ((ch == '/') && (chNext == '/')) {
char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelCurrent++;
} else if (chNext2 == '}') {
levelCurrent--;
}
}
}
if (style == SCE_C_PREPROCESSOR) {
if (ch == '#') {
unsigned int j=i+1;
while ((j<endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
j++;
}
if (MatchString(styler, j, "region")) {
levelCurrent++;
} else if (MatchString(styler, j, "endregion")) {
levelCurrent--;
}
}
}
if (style == SCE_C_OPERATOR) {
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 cppWordLists[] = {
"Primary keywords and identifiers",
"Secondary keywords and identifiers",
"Documentation comment keywords",
0,
};
LexerModule lmCPP(SCLEX_CPP, ColouriseCppDoc, "cpp", FoldCppDoc, cppWordLists);
LexerModule lmTCL(SCLEX_TCL, ColouriseCppDoc, "tcl", FoldCppDoc, cppWordLists);
<|endoftext|>
|
<commit_before><?hh //strict
/**
* This file is part of hhpack\typechecker package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\typechecker\check;
use hhpack\typechecker\Node;
use hhpack\typechecker\JSONResult;
final class Result implements JSONResult<ResultOptions>, Node<ResultOptions>
{
private ImmutableErrors $errors;
public function __construct
(
private bool $passed,
private Version $version,
Errors $errors
)
{
$this->errors = new ImmVector($errors);
}
public function isPassed() : bool
{
return $this->passed;
}
public function getVersion() : Version
{
return $this->version;
}
public function getErrors() : Iterable<Error>
{
return $this->errors->items();
}
public function hasErrors() : bool
{
return $this->errors->isEmpty() === false;
}
public static function fromOptions(ResultOptions $options) : this
{
$errors = Vector {};
foreach ($options['errors'] as $errorOptions) {
$error = Error::fromOptions($errorOptions);
$errors->add($error);
}
return new static(
$options['passed'],
$options['version'],
$errors->items()
);
}
public static function fromString(string $result) : this
{
$json = preg_replace('/^([^\{]+)|([^\}]+)$/', "", $result);
$values = json_decode(trim($json), true);
return static::fromOptions($values);
}
}
<commit_msg><commit_after><?hh //strict
/**
* This file is part of hhpack\typechecker package.
*
* (c) Noritaka Horio <holy.shared.design@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace hhpack\typechecker\check;
use hhpack\typechecker\Node;
use hhpack\typechecker\JSONResult;
final class Result implements JSONResult<ResultOptions>, Node<ResultOptions>
{
private ImmutableErrors $errors;
public function __construct
(
private bool $passed,
private Version $version,
Errors $errors
)
{
$this->errors = new ImmVector($errors);
}
public function isPassed() : bool
{
return $this->passed;
}
public function getVersion() : Version
{
return $this->version;
}
public function getErrors() : KeyedIterator<int, Error>
{
return $this->errors->lazy()->getIterator();
}
public function hasErrors() : bool
{
return $this->errors->isEmpty() === false;
}
public static function fromOptions(ResultOptions $options) : this
{
$errors = Vector {};
foreach ($options['errors'] as $errorOptions) {
$error = Error::fromOptions($errorOptions);
$errors->add($error);
}
return new static(
$options['passed'],
$options['version'],
$errors->items()
);
}
public static function fromString(string $result) : this
{
$json = preg_replace('/^([^\{]+)|([^\}]+)$/', "", $result);
$values = json_decode(trim($json), true);
return static::fromOptions($values);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x3d9e5080e63c65fb2dd117ea0330892e450c15b5a59c1a6c4e3fb2a01f16d0db"))
( 1, uint256("0xaf7f1e670b61d341202dec0e873b079eeabd0b745c91d64a799108e61a4c97c9"))
( 100, unit256("0x2518c68fb48de031618aef649b969efa4adcadaa6d1673ae0153b657b2b1f14b"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Update checkpoints.cpp<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x3d9e5080e63c65fb2dd117ea0330892e450c15b5a59c1a6c4e3fb2a01f16d0db"))
( 1, uint256("0xaf7f1e670b61d341202dec0e873b079eeabd0b745c91d64a799108e61a4c97c9"))
( 100, uint256("0x2518c68fb48de031618aef649b969efa4adcadaa6d1673ae0153b657b2b1f14b"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
( 68555, uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a"))
( 70567, uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a"))
( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
(105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
(118000, uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553"))
(134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
(140700, uint256("0x000000000000033b512028abb90e1626d8b346fd0ed598ac0a3c371138dce2bd"))
(168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Add a testnet checkpoint at block 546<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 11111, uint256("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d"))
( 33333, uint256("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6"))
( 68555, uint256("0x00000000001e1b4903550a0b96e9a9405c8a95f387162e4944e8d9fbe501cd6a"))
( 70567, uint256("0x00000000006a49b14bcf27462068f1264c961f11fa2e0eddd2be0791e1d4124a"))
( 74000, uint256("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20"))
(105000, uint256("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97"))
(118000, uint256("0x000000000000774a7f8a7a12dc906ddb9e17e75d684f15e00f8767f9e8f36553"))
(134444, uint256("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe"))
(140700, uint256("0x000000000000033b512028abb90e1626d8b346fd0ed598ac0a3c371138dce2bd"))
(168000, uint256("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763"))
;
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 546, uint256("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
MapCheckpoints& checkpoints = (fTestNet ? mapCheckpointsTestnet : mapCheckpoints);
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x72fe5181ea60b91497de2458c7aeea3103c70df19dd0425b43f6cdc2ac8022fa"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1392960907, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
720.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1392960907,
0,
720.0
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Check fern<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("2eaf880120c4948146a4676a00bd1b95e7232f566dfd63c239eed22f2dd4b2a4"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1392960907, // * UNIX timestamp of last checkpoint block
0, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
720.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1392960907,
0,
720.0
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL; // Testnet has no checkpoints
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Limecoinx developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
// limxdev limecoinx 2015-04
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0000012e1b8843ac9ce8c18603658eaf8895f99d3f5e7e1b7b1686f35e3c087a")) //limxdev 04-2015
( 10000, uint256("0x0000000006c1a1573ca82ad24789c10a36535cf085f201122f1d112a88841271"))
( 15790, uint256("0x000000004151f93a4012545309d4bbcac5f2977dea643a178c4bec1310e6c086"))
( 21190, uint256("0x000000002a798fd88d0ce270cad1c217aceea236b573c68cfd02b086f5745921"))
( 26000, uint256("0x00000002bace42e673000616ed8dbf16a49e3a7aec6bf59774fed081f6deac5f"))
( 29999, uint256("0x00000000ede644fcbdf8f8ce8c53bb15de5dfd5c32384c751fa4ef409992aa07"))
( 36222, uint256("0x0000000047c4338861a6b191570f07a23bd30c75c03a81ac5e5978053d946408"))
( 40599, uint256("0x00000000c2596d6bd49b08ab9d233cd7de97a01a7cde19d0e1a136a1f3904f3c"))
( 45512, uint256("0x00000000e2448d27f6360461739bcd25bf41d3767fc7c0e8c5e53a2db90eaf06"))
( 49478, uint256("0x00000000dbb3d6386ed45e335316a4f018e451bf60b12fdebbef680969a90acb"))
( 74910, uint256("0x000000002409374bcab8006f171b8c3eb4485220d94ae555b041ee24eb4d8434"))
( 84579, uint256("0x00000000372eebd8b26d135798ac04549dc32fdfb584710ed9edf2dcb1be6941"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1429705032, // * UNIX timestamp of last checkpoint block
102428, // * total number of transactions between genesis and last checkpoint //
// (the tx=... number in the SetBestChain debug.log lines)
350 // * estimated number of transactions per day after checkpoint //800
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0 , uint256("0x000008030a1e9a647ecc6119e0782166552e49dadfa8353afa26f3a6c2179845")) //limxdev 04-2015
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1402095180,
3000,
30
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET)
return dataTestnet;
else if (Params().NetworkID() == CChainParams::MAIN)
return data;
else
return dataRegtest;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex==NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Add new Checkpoint<commit_after>// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Limecoinx developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
// limxdev limecoinx 2015-04
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0000012e1b8843ac9ce8c18603658eaf8895f99d3f5e7e1b7b1686f35e3c087a")) //limxdev 04-2015
( 10000, uint256("0x0000000006c1a1573ca82ad24789c10a36535cf085f201122f1d112a88841271"))
( 15790, uint256("0x000000004151f93a4012545309d4bbcac5f2977dea643a178c4bec1310e6c086"))
( 21190, uint256("0x000000002a798fd88d0ce270cad1c217aceea236b573c68cfd02b086f5745921"))
( 26000, uint256("0x00000002bace42e673000616ed8dbf16a49e3a7aec6bf59774fed081f6deac5f"))
( 29999, uint256("0x00000000ede644fcbdf8f8ce8c53bb15de5dfd5c32384c751fa4ef409992aa07"))
( 36222, uint256("0x0000000047c4338861a6b191570f07a23bd30c75c03a81ac5e5978053d946408"))
( 40599, uint256("0x00000000c2596d6bd49b08ab9d233cd7de97a01a7cde19d0e1a136a1f3904f3c"))
( 45512, uint256("0x00000000e2448d27f6360461739bcd25bf41d3767fc7c0e8c5e53a2db90eaf06"))
( 49478, uint256("0x00000000dbb3d6386ed45e335316a4f018e451bf60b12fdebbef680969a90acb"))
( 74910, uint256("0x000000002409374bcab8006f171b8c3eb4485220d94ae555b041ee24eb4d8434"))
( 84579, uint256("0x00000000372eebd8b26d135798ac04549dc32fdfb584710ed9edf2dcb1be6941"))
( 140602, uint256("0x0000000000b86fa0891a7241c71a0969439896b61abaf07e856eb0f49115b741"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1447088155, // * UNIX timestamp of last checkpoint block
176968, // * total number of transactions between genesis and last checkpoint //
// (the tx=... number in the SetBestChain debug.log lines)
350 // * estimated number of transactions per day after checkpoint //800
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0 , uint256("0x000008030a1e9a647ecc6119e0782166552e49dadfa8353afa26f3a6c2179845")) //limxdev 04-2015
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1402095180,
3000,
30
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256("0x000008ca1832a4baf228eb1553c03d3a2c8e02399550dd6ea8d65cec3ef23d2e"))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET)
return dataTestnet;
else if (Params().NetworkID() == CChainParams::MAIN)
return data;
else
return dataRegtest;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex==NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x59e32f1ba2fe0625099198bd1b5fbb10a3a8d4c2bb9be8fd9f298575e90b9c7c"))
( 20, uint256("0xb0aade3d58abf55e974633d2dc992be00baba00a91df3ae07e7bd700dbbdc07e"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1473995494, // * UNIX timestamp of last checkpoint block
21, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
1000 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0xc35f0dddb80479c9ed48a3889b46b55d5fa4fed3a808b4002402849cfc269b3e"))
( 100, uint256("0xe7822a6374fd745ae50b545320cf5fc1b1cfb9b760759557e77d86a340ea1862"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1474062651,
101,
1000
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>Updated checkpoints to block 15000<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double fSigcheckVerificationFactor = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64 nTimeLastCheckpoint;
int64 nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
( 0, uint256("0x59e32f1ba2fe0625099198bd1b5fbb10a3a8d4c2bb9be8fd9f298575e90b9c7c"))
( 20, uint256("0xb0aade3d58abf55e974633d2dc992be00baba00a91df3ae07e7bd700dbbdc07e"))
( 15000, uint256("0x456eafa35e61affaadf77d61ee2b55f71f35eee2e95581598f85cf97c4c6704c"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1476455803,, // * UNIX timestamp of last checkpoint block
16146, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
1500 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0xc35f0dddb80479c9ed48a3889b46b55d5fa4fed3a808b4002402849cfc269b3e"))
( 100, uint256("0xe7822a6374fd745ae50b545320cf5fc1b1cfb9b760759557e77d86a340ea1862"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1474062651,
101,
1000
};
const CCheckpointData &Checkpoints() {
if (fTestNet)
return dataTestnet;
else
return data;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!GetBoolArg("-checkpoints", true))
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex) {
if (pindex==NULL)
return 0.0;
int64 nNow = time(NULL);
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!GetBoolArg("-checkpoints", true))
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!GetBoolArg("-checkpoints", true))
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of // TODO: needs to adjusted for checkpoint checks, also see main.cpp
( 1, uint256("0x512a9c69d87cc0bfb04a4d274f1e60262dd244d3c9b0aa2c236a2cfc13c19f12"))
( 2, uint256("0x43682e5929c9234209db6592953347aa8b4c8e233692369a61b4780b80835c42"))
( 34336, uint256("0xfc6a3ee59b9f2429114178ff7a4792a7af102688156d26a3edbb90c243850dcd"))
( 50000, uint256("0x5fa3d8bb008a55a1b6e301b435be3a68985083435748b913ef8572bf1282303c"))
( 70000, uint256("0x7ee7864ffec5a23f526e01a1388a6e988d2773365522e04dd51d3c71c19b459f"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<commit_msg>changes<commit_after>// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
//
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
//
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of // TODO: needs to adjusted for checkpoint checks, also see main.cpp
( 0, uint256("0x512a9c69d87cc0bfb04a4d274f1e60262dd244d3c9b0aa2c236a2cfc13c19f12"))
;
bool CheckBlock(int nHeight, const uint256& hash)
{
if (fTestNet) return true; // Testnet has no checkpoints
MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight);
if (i == mapCheckpoints.end()) return true;
return hash == i->second;
}
int GetTotalBlocksEstimate()
{
if (fTestNet) return 0;
return mapCheckpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (fTestNet) return NULL;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
#include "GitSourceControlPrivatePCH.h"
#include "GitSourceControlUtils.h"
#include "GitSourceControlState.h"
#include "GitSourceControlModule.h"
#include "GitSourceControlCommand.h"
namespace GitSourceControlConstants
{
/** The maximum number of files we submit in a single Git command */
const int32 MaxFilesPerBatch = 20;
}
namespace GitSourceControlUtils
{
static bool RunCommandInternal(const FString& InGitBinaryPath, const FString& InRepositoryRoot, const FString& InCommand, const TArray<FString>& InParameters, const TArray<FString>& InFiles, FString& OutResults, FString& OutErrors)
{
int32 ReturnCode = 0;
FString FullCommand;
FString LogableCommand; // short version of the command for logging purpose
if (!InRepositoryRoot.IsEmpty())
{
// Specify the working copy (the root) of the git repository (before the command itself)
FullCommand = TEXT("--work-tree=\"");
FullCommand += InRepositoryRoot;
// and the ".git" subdirectory in it (before the command itself)
FullCommand += TEXT("\" --git-dir=\"");
FullCommand += InRepositoryRoot;
FullCommand += TEXT(".git\" ");
}
// then the git command itself ("status", "log", "commit"...)
LogableCommand += InCommand;
// Append to the command all parameters, and then finally the files
for(const auto& Parameter : InParameters)
{
LogableCommand += TEXT(" ");
LogableCommand += Parameter;
}
for(const auto& File : InFiles)
{
LogableCommand += TEXT(" \"");
LogableCommand += File;
LogableCommand += TEXT("\"");
}
// Also, Git does not have a "--non-interactive" option, as it auto-detects when there are no connected standard input/output streams
FullCommand += LogableCommand;
// @todo: temporary debug logs
UE_LOG(LogSourceControl, Log, TEXT("RunCommandInternal: Attempting 'git %s'"), *LogableCommand);
FPlatformProcess::ExecProcess(*InGitBinaryPath, *FullCommand, &ReturnCode, &OutResults, &OutErrors);
UE_LOG(LogSourceControl, Log, TEXT("RunCommandInternal: ExecProcess ReturnCode=%d OutResults='%s'"), ReturnCode, *OutResults);
if(!OutErrors.IsEmpty())
{
UE_LOG(LogSourceControl, Error, TEXT("RunCommandInternal: ExecProcess ReturnCode=%d OutErrors='%s'"), ReturnCode, *OutErrors);
}
return ReturnCode == 0;
}
FString FindGitBinaryPath()
{
bool bFound = false;
#if PLATFORM_WINDOWS
// 1) First of all, check for the ThirdParty directory as it may contain a specific version of Git for this plugin to work
// NOTE using only "git" (or "git.exe") relying on the "PATH" envvar does not always work as expected, depending on the installation:
// If the PATH is set with "git/cmd" instead of "git/bin",
// "git.exe" launch "git/cmd/git.exe" that redirect to "git/bin/git.exe" and ExecProcess() is unable to catch its outputs streams.
// Under Windows, we can use the third party "msysgit PortableGit" https://code.google.com/p/msysgit/downloads/list?can=1&q=PortableGit
// NOTE: Win32 platform subdirectory as there is no Git 64bit build available
FString GitBinaryPath(FPaths::EngineDir() / TEXT("Binaries/ThirdParty/git/Win32/bin") / TEXT("git.exe"));
bFound = CheckGitAvailability(GitBinaryPath);
#endif
// 2) If Git is not found in ThirdParty directory, look into standard install directory
if(!bFound)
{
#if PLATFORM_WINDOWS
// @todo use the Windows registry to find Git
GitBinaryPath = TEXT("C:/Program Files (x86)/Git/bin/git.exe");
#else
GitBinaryPath = TEXT("/usr/bin/git");
#endif
}
return GitBinaryPath;
}
bool CheckGitAvailability(const FString& InGitBinaryPath)
{
bool bGitAvailable = false;
FString InfoMessages;
FString ErrorMessages;
bGitAvailable = RunCommandInternal(InGitBinaryPath, FString(), TEXT("version"), TArray<FString>(), TArray<FString>(), InfoMessages, ErrorMessages);
if(bGitAvailable)
{
if(InfoMessages.Contains("git"))
{
bGitAvailable = true;
}
else
{
bGitAvailable = false;
}
}
// @todo also check Git config user.name & user.email
return bGitAvailable;
}
bool RunCommand(const FString& InGitBinaryPath, const FString& InRepositoryRoot, const FString& InCommand, const TArray<FString>& InParameters, const TArray<FString>& InFiles, TArray<FString>& OutResults, TArray<FString>& OutErrorMessages)
{
bool bResult = true;
if(InFiles.Num() > GitSourceControlConstants::MaxFilesPerBatch)
{
// Batch files up so we dont exceed command-line limits
int32 FileCount = 0;
while(FileCount < InFiles.Num())
{
TArray<FString> FilesInBatch;
for(int32 FileIndex = 0; FileIndex < InFiles.Num() && FileIndex < GitSourceControlConstants::MaxFilesPerBatch; FileIndex++, FileCount++)
{
FilesInBatch.Add(InFiles[FileIndex]);
}
FString Results;
FString Errors;
bResult &= RunCommandInternal(InGitBinaryPath, InRepositoryRoot, InCommand, InParameters, FilesInBatch, Results, Errors);
Results.ParseIntoArray(&OutResults, TEXT("\n"), true);
Errors.ParseIntoArray(&OutErrorMessages, TEXT("\n"), true);
}
}
else
{
FString Results;
FString Errors;
bResult &= RunCommandInternal(InGitBinaryPath, InRepositoryRoot, InCommand, InParameters, InFiles, Results, Errors);
Results.ParseIntoArray(&OutResults, TEXT("\n"), true);
Errors.ParseIntoArray(&OutErrorMessages, TEXT("\n"), true);
}
return bResult;
}
/** Example git log results:
commit 97a4e7626681895e073aaefd68b8ac087db81b0b
Author: Sébastien Rombauts <sebastien.rombauts@gmail.com>
Date: 2014-05-15 21:32:27 +0200
Another commit used to test History
- with many lines
- some <xml>
- and strange characteres $*+
M Content/Blueprints/Blueprint_CeilingLight.uasset
commit 355f0df26ebd3888adbb558fd42bb8bd3e565000
Author: Sébastien Rombauts <sebastien.rombauts@gmail.com>
Date: 2014-05-12 11:28:14 +0200
Testing git status, edit, and revert
A Content/Blueprints/Blueprint_CeilingLight.uasset
*/
void ParseLogResults(const TArray<FString>& InResults, TGitSourceControlHistory& OutHistory)
{
TSharedRef<FGitSourceControlRevision, ESPMode::ThreadSafe> SourceControlRevision = MakeShareable(new FGitSourceControlRevision);
for(int32 IdxResult = 0; IdxResult < InResults.Num(); IdxResult++)
{
const FString& Result = InResults[IdxResult];
if(Result.StartsWith(TEXT("commit ")))
{
// End of the previous commit
if(SourceControlRevision->RevisionNumber != 0)
{
SourceControlRevision->Description += TEXT("\nCommit Id: ");
SourceControlRevision->Description += SourceControlRevision->CommitId;
OutHistory.Add(SourceControlRevision);
SourceControlRevision = MakeShareable(new FGitSourceControlRevision);
}
SourceControlRevision->CommitId = Result.RightChop(7);
FString ShortCommitId = SourceControlRevision->CommitId.Right(8); // Short revision ; first 8 hex characters (max that can hold a 32 bit integer)
SourceControlRevision->RevisionNumber = FParse::HexNumber(*ShortCommitId);
}
else if(Result.StartsWith(TEXT("Author: ")))
{
SourceControlRevision->UserName = Result.RightChop(8);
}
else if(Result.StartsWith(TEXT("Date: ")))
{
FString Date = Result.RightChop(8);
SourceControlRevision->Date = FDateTime::FromUnixTimestamp(FCString::Atoi(*Date));
}
// else if(Result.IsEmpty()) // empty line before/after commit message has already been taken care by FString::ParseIntoArray()
else if(Result.StartsWith(TEXT(" ")))
{
SourceControlRevision->Description += Result.RightChop(4);
SourceControlRevision->Description += TEXT("\n");
}
else
{
SourceControlRevision->Action = Result.Left(1); // @todo Readable string state
SourceControlRevision->Filename = Result.RightChop(8); // relative filename
}
}
// End of the last commit
if(SourceControlRevision->RevisionNumber != 0)
{
SourceControlRevision->Description += TEXT("\nCommit Id: ");
SourceControlRevision->Description += SourceControlRevision->CommitId;
OutHistory.Add(SourceControlRevision);
}
}
/** Match the relative filename of a Git status result with a provided absolute filename */
class FGitStatusFileMatcher
{
public:
FGitStatusFileMatcher(const FString& InAbsoluteFilename)
: AbsoluteFilename(InAbsoluteFilename)
{
}
bool Matches(const FString& InResult) const
{
// Extract the relative filename from the Git status result
// @todo this can not work in case of a rename from -> to
FString RelativeFilename = InResult.RightChop(3);
return AbsoluteFilename.Contains(RelativeFilename);
}
private:
const FString& AbsoluteFilename;
};
/**
* Extract and interpret the file state from the given Git status result.
* @see file:///C:/Program%20Files%20(x86)/Git/doc/git/html/git-status.html
* ' ' = unmodified
* 'M' = modified
* 'A' = added
* 'D' = deleted
* 'R' = renamed
* 'C' = copied
* 'U' = updated but unmerged
* '?' = unknown/untracked
* '!' = ignored
*/
class FGitStatusParser
{
public:
FGitStatusParser(const FString& InResult)
{
// @todo Get the second part of a rename "from -> to"
//FString Filename = InResult.RightChop(3);
TCHAR IndexState = InResult[0];
TCHAR WCopyState = InResult[1];
if( (IndexState == 'U' || WCopyState == 'U')
|| (IndexState == 'A' && WCopyState == 'A')
|| (IndexState == 'D' && WCopyState == 'D'))
{
// "Unmerged" conflict cases are generally marked with a "U",
// but there are also the special cases of both "A"dded, or both "D"eleted
State = EWorkingCopyState::Conflicted;
}
else if(IndexState == 'A')
{
State = EWorkingCopyState::Added;
}
else if(IndexState == 'D')
{
State = EWorkingCopyState::Deleted;
}
else if(WCopyState == 'D')
{
State = EWorkingCopyState::Missing;
}
else if(IndexState == 'M' || WCopyState == 'M')
{
State = EWorkingCopyState::Modified;
}
else if(IndexState == 'R')
{
State = EWorkingCopyState::Renamed;
}
else if(IndexState == 'C')
{
State = EWorkingCopyState::Copied;
}
else if(IndexState == '?' || WCopyState == '?')
{
State = EWorkingCopyState::NotControlled;
}
else if(IndexState == '!' || WCopyState == '!')
{
State = EWorkingCopyState::Ignored;
}
else
{
// Unmodified never yield a status
State = EWorkingCopyState::Unknown;
}
}
EWorkingCopyState::Type State;
};
void ParseStatusResults(const TArray<FString>& InFiles, const TArray<FString>& InResults, TArray<FGitSourceControlState>& OutStates)
{
for(const auto& File : InFiles)
{
FGitSourceControlState FileState(File);
FGitStatusFileMatcher FileMatcher(File);
int32 IdxResult = InResults.FindMatch(FileMatcher);
if(IdxResult != INDEX_NONE)
{
// File found in status results; only the case for "changed" files
FGitStatusParser StatusParser(InResults[IdxResult]);
FileState.WorkingCopyState = StatusParser.State;
}
else
{
// File not found in status
if(FPaths::FileExists(File))
{
// usually means the file is unchanged,
FileState.WorkingCopyState = EWorkingCopyState::Unchanged;
}
else
{
// but also the case for newly created content: there is no file on disk until the content is saved for the first time
FileState.WorkingCopyState = EWorkingCopyState::NotControlled;
}
}
FileState.TimeStamp.Now();
OutStates.Add(FileState);
}
}
bool UpdateCachedStates(const TArray<FGitSourceControlState>& InStates)
{
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>( "GitSourceControl" );
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
int NbStatesUpdated = 0;
for(const auto& InState : InStates)
{
TSharedRef<FGitSourceControlState, ESPMode::ThreadSafe> State = Provider.GetStateInternal(InState.LocalFilename);
if(State->WorkingCopyState != InState.WorkingCopyState)
{
State->WorkingCopyState = InState.WorkingCopyState;
// State->TimeStamp = InState.TimeStamp; // @todo Workaround a bug with the Source Control Module not updating file state after a "Save"
NbStatesUpdated++;
}
}
return (NbStatesUpdated > 0);
}
}
<commit_msg>History: Remove the 'email' part from the end of the UserName<commit_after>// Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)
#include "GitSourceControlPrivatePCH.h"
#include "GitSourceControlUtils.h"
#include "GitSourceControlState.h"
#include "GitSourceControlModule.h"
#include "GitSourceControlCommand.h"
namespace GitSourceControlConstants
{
/** The maximum number of files we submit in a single Git command */
const int32 MaxFilesPerBatch = 20;
}
namespace GitSourceControlUtils
{
static bool RunCommandInternal(const FString& InGitBinaryPath, const FString& InRepositoryRoot, const FString& InCommand, const TArray<FString>& InParameters, const TArray<FString>& InFiles, FString& OutResults, FString& OutErrors)
{
int32 ReturnCode = 0;
FString FullCommand;
FString LogableCommand; // short version of the command for logging purpose
if (!InRepositoryRoot.IsEmpty())
{
// Specify the working copy (the root) of the git repository (before the command itself)
FullCommand = TEXT("--work-tree=\"");
FullCommand += InRepositoryRoot;
// and the ".git" subdirectory in it (before the command itself)
FullCommand += TEXT("\" --git-dir=\"");
FullCommand += InRepositoryRoot;
FullCommand += TEXT(".git\" ");
}
// then the git command itself ("status", "log", "commit"...)
LogableCommand += InCommand;
// Append to the command all parameters, and then finally the files
for(const auto& Parameter : InParameters)
{
LogableCommand += TEXT(" ");
LogableCommand += Parameter;
}
for(const auto& File : InFiles)
{
LogableCommand += TEXT(" \"");
LogableCommand += File;
LogableCommand += TEXT("\"");
}
// Also, Git does not have a "--non-interactive" option, as it auto-detects when there are no connected standard input/output streams
FullCommand += LogableCommand;
// @todo: temporary debug logs
UE_LOG(LogSourceControl, Log, TEXT("RunCommandInternal: Attempting 'git %s'"), *LogableCommand);
FPlatformProcess::ExecProcess(*InGitBinaryPath, *FullCommand, &ReturnCode, &OutResults, &OutErrors);
UE_LOG(LogSourceControl, Log, TEXT("RunCommandInternal: ExecProcess ReturnCode=%d OutResults='%s'"), ReturnCode, *OutResults);
if(!OutErrors.IsEmpty())
{
UE_LOG(LogSourceControl, Error, TEXT("RunCommandInternal: ExecProcess ReturnCode=%d OutErrors='%s'"), ReturnCode, *OutErrors);
}
return ReturnCode == 0;
}
FString FindGitBinaryPath()
{
bool bFound = false;
#if PLATFORM_WINDOWS
// 1) First of all, check for the ThirdParty directory as it may contain a specific version of Git for this plugin to work
// NOTE using only "git" (or "git.exe") relying on the "PATH" envvar does not always work as expected, depending on the installation:
// If the PATH is set with "git/cmd" instead of "git/bin",
// "git.exe" launch "git/cmd/git.exe" that redirect to "git/bin/git.exe" and ExecProcess() is unable to catch its outputs streams.
// Under Windows, we can use the third party "msysgit PortableGit" https://code.google.com/p/msysgit/downloads/list?can=1&q=PortableGit
// NOTE: Win32 platform subdirectory as there is no Git 64bit build available
FString GitBinaryPath(FPaths::EngineDir() / TEXT("Binaries/ThirdParty/git/Win32/bin") / TEXT("git.exe"));
bFound = CheckGitAvailability(GitBinaryPath);
#endif
// 2) If Git is not found in ThirdParty directory, look into standard install directory
if(!bFound)
{
#if PLATFORM_WINDOWS
// @todo use the Windows registry to find Git
GitBinaryPath = TEXT("C:/Program Files (x86)/Git/bin/git.exe");
#else
GitBinaryPath = TEXT("/usr/bin/git");
#endif
}
return GitBinaryPath;
}
bool CheckGitAvailability(const FString& InGitBinaryPath)
{
bool bGitAvailable = false;
FString InfoMessages;
FString ErrorMessages;
bGitAvailable = RunCommandInternal(InGitBinaryPath, FString(), TEXT("version"), TArray<FString>(), TArray<FString>(), InfoMessages, ErrorMessages);
if(bGitAvailable)
{
if(InfoMessages.Contains("git"))
{
bGitAvailable = true;
}
else
{
bGitAvailable = false;
}
}
// @todo also check Git config user.name & user.email
return bGitAvailable;
}
bool RunCommand(const FString& InGitBinaryPath, const FString& InRepositoryRoot, const FString& InCommand, const TArray<FString>& InParameters, const TArray<FString>& InFiles, TArray<FString>& OutResults, TArray<FString>& OutErrorMessages)
{
bool bResult = true;
if(InFiles.Num() > GitSourceControlConstants::MaxFilesPerBatch)
{
// Batch files up so we dont exceed command-line limits
int32 FileCount = 0;
while(FileCount < InFiles.Num())
{
TArray<FString> FilesInBatch;
for(int32 FileIndex = 0; FileIndex < InFiles.Num() && FileIndex < GitSourceControlConstants::MaxFilesPerBatch; FileIndex++, FileCount++)
{
FilesInBatch.Add(InFiles[FileIndex]);
}
FString Results;
FString Errors;
bResult &= RunCommandInternal(InGitBinaryPath, InRepositoryRoot, InCommand, InParameters, FilesInBatch, Results, Errors);
Results.ParseIntoArray(&OutResults, TEXT("\n"), true);
Errors.ParseIntoArray(&OutErrorMessages, TEXT("\n"), true);
}
}
else
{
FString Results;
FString Errors;
bResult &= RunCommandInternal(InGitBinaryPath, InRepositoryRoot, InCommand, InParameters, InFiles, Results, Errors);
Results.ParseIntoArray(&OutResults, TEXT("\n"), true);
Errors.ParseIntoArray(&OutErrorMessages, TEXT("\n"), true);
}
return bResult;
}
/** Example git log results:
commit 97a4e7626681895e073aaefd68b8ac087db81b0b
Author: Sébastien Rombauts <sebastien.rombauts@gmail.com>
Date: 2014-05-15 21:32:27 +0200
Another commit used to test History
- with many lines
- some <xml>
- and strange characteres $*+
M Content/Blueprints/Blueprint_CeilingLight.uasset
commit 355f0df26ebd3888adbb558fd42bb8bd3e565000
Author: Sébastien Rombauts <sebastien.rombauts@gmail.com>
Date: 2014-05-12 11:28:14 +0200
Testing git status, edit, and revert
A Content/Blueprints/Blueprint_CeilingLight.uasset
*/
void ParseLogResults(const TArray<FString>& InResults, TGitSourceControlHistory& OutHistory)
{
TSharedRef<FGitSourceControlRevision, ESPMode::ThreadSafe> SourceControlRevision = MakeShareable(new FGitSourceControlRevision);
for(int32 IdxResult = 0; IdxResult < InResults.Num(); IdxResult++)
{
const FString& Result = InResults[IdxResult];
if(Result.StartsWith(TEXT("commit ")))
{
// End of the previous commit
if(SourceControlRevision->RevisionNumber != 0)
{
SourceControlRevision->Description += TEXT("\nCommit Id: ");
SourceControlRevision->Description += SourceControlRevision->CommitId;
OutHistory.Add(SourceControlRevision);
SourceControlRevision = MakeShareable(new FGitSourceControlRevision);
}
SourceControlRevision->CommitId = Result.RightChop(7);
FString ShortCommitId = SourceControlRevision->CommitId.Right(8); // Short revision ; first 8 hex characters (max that can hold a 32 bit integer)
SourceControlRevision->RevisionNumber = FParse::HexNumber(*ShortCommitId);
}
else if(Result.StartsWith(TEXT("Author: ")))
{
// Remove the 'email' part of the UserName
FString UserNameEmail = Result.RightChop(8);
int32 EmailIndex = 0;
if(UserNameEmail.FindLastChar('<', EmailIndex))
{
SourceControlRevision->UserName = UserNameEmail.Left(EmailIndex - 1);
}
}
else if(Result.StartsWith(TEXT("Date: ")))
{
FString Date = Result.RightChop(8);
SourceControlRevision->Date = FDateTime::FromUnixTimestamp(FCString::Atoi(*Date));
}
// else if(Result.IsEmpty()) // empty line before/after commit message has already been taken care by FString::ParseIntoArray()
else if(Result.StartsWith(TEXT(" ")))
{
SourceControlRevision->Description += Result.RightChop(4);
SourceControlRevision->Description += TEXT("\n");
}
else
{
SourceControlRevision->Action = Result.Left(1); // @todo Readable string state
SourceControlRevision->Filename = Result.RightChop(8); // relative filename
}
}
// End of the last commit
if(SourceControlRevision->RevisionNumber != 0)
{
SourceControlRevision->Description += TEXT("\nCommit Id: ");
SourceControlRevision->Description += SourceControlRevision->CommitId;
OutHistory.Add(SourceControlRevision);
}
}
/** Match the relative filename of a Git status result with a provided absolute filename */
class FGitStatusFileMatcher
{
public:
FGitStatusFileMatcher(const FString& InAbsoluteFilename)
: AbsoluteFilename(InAbsoluteFilename)
{
}
bool Matches(const FString& InResult) const
{
// Extract the relative filename from the Git status result
// @todo this can not work in case of a rename from -> to
FString RelativeFilename = InResult.RightChop(3);
return AbsoluteFilename.Contains(RelativeFilename);
}
private:
const FString& AbsoluteFilename;
};
/**
* Extract and interpret the file state from the given Git status result.
* @see file:///C:/Program%20Files%20(x86)/Git/doc/git/html/git-status.html
* ' ' = unmodified
* 'M' = modified
* 'A' = added
* 'D' = deleted
* 'R' = renamed
* 'C' = copied
* 'U' = updated but unmerged
* '?' = unknown/untracked
* '!' = ignored
*/
class FGitStatusParser
{
public:
FGitStatusParser(const FString& InResult)
{
// @todo Get the second part of a rename "from -> to"
//FString Filename = InResult.RightChop(3);
TCHAR IndexState = InResult[0];
TCHAR WCopyState = InResult[1];
if( (IndexState == 'U' || WCopyState == 'U')
|| (IndexState == 'A' && WCopyState == 'A')
|| (IndexState == 'D' && WCopyState == 'D'))
{
// "Unmerged" conflict cases are generally marked with a "U",
// but there are also the special cases of both "A"dded, or both "D"eleted
State = EWorkingCopyState::Conflicted;
}
else if(IndexState == 'A')
{
State = EWorkingCopyState::Added;
}
else if(IndexState == 'D')
{
State = EWorkingCopyState::Deleted;
}
else if(WCopyState == 'D')
{
State = EWorkingCopyState::Missing;
}
else if(IndexState == 'M' || WCopyState == 'M')
{
State = EWorkingCopyState::Modified;
}
else if(IndexState == 'R')
{
State = EWorkingCopyState::Renamed;
}
else if(IndexState == 'C')
{
State = EWorkingCopyState::Copied;
}
else if(IndexState == '?' || WCopyState == '?')
{
State = EWorkingCopyState::NotControlled;
}
else if(IndexState == '!' || WCopyState == '!')
{
State = EWorkingCopyState::Ignored;
}
else
{
// Unmodified never yield a status
State = EWorkingCopyState::Unknown;
}
}
EWorkingCopyState::Type State;
};
void ParseStatusResults(const TArray<FString>& InFiles, const TArray<FString>& InResults, TArray<FGitSourceControlState>& OutStates)
{
for(const auto& File : InFiles)
{
FGitSourceControlState FileState(File);
FGitStatusFileMatcher FileMatcher(File);
int32 IdxResult = InResults.FindMatch(FileMatcher);
if(IdxResult != INDEX_NONE)
{
// File found in status results; only the case for "changed" files
FGitStatusParser StatusParser(InResults[IdxResult]);
FileState.WorkingCopyState = StatusParser.State;
}
else
{
// File not found in status
if(FPaths::FileExists(File))
{
// usually means the file is unchanged,
FileState.WorkingCopyState = EWorkingCopyState::Unchanged;
}
else
{
// but also the case for newly created content: there is no file on disk until the content is saved for the first time
FileState.WorkingCopyState = EWorkingCopyState::NotControlled;
}
}
FileState.TimeStamp.Now();
OutStates.Add(FileState);
}
}
bool UpdateCachedStates(const TArray<FGitSourceControlState>& InStates)
{
FGitSourceControlModule& GitSourceControl = FModuleManager::LoadModuleChecked<FGitSourceControlModule>( "GitSourceControl" );
FGitSourceControlProvider& Provider = GitSourceControl.GetProvider();
int NbStatesUpdated = 0;
for(const auto& InState : InStates)
{
TSharedRef<FGitSourceControlState, ESPMode::ThreadSafe> State = Provider.GetStateInternal(InState.LocalFilename);
if(State->WorkingCopyState != InState.WorkingCopyState)
{
State->WorkingCopyState = InState.WorkingCopyState;
// State->TimeStamp = InState.TimeStamp; // @todo Workaround a bug with the Source Control Module not updating file state after a "Save"
NbStatesUpdated++;
}
}
return (NbStatesUpdated > 0);
}
}
<|endoftext|>
|
<commit_before>#include "ship.h"
#include "../classes/weapon.h"
#include "../engines/physics/projectile.h"
Ship::Ship(int id, float mass, float max_tolerance, std::vector<float> d, float size, float preset_a, float preset_p_dot, float preset_r_dot) : Projectile(id, 1, mass, max_tolerance, d, { 0, 0, 0 }, size, { 1, 0, 0 }, { 0, 1, 0 }, 0, 0, preset_a, preset_p_dot, preset_r_dot, -1) {
this->type = ObjType::SHIP;
}
int Ship::get_weapon_index() {
return this->weapon_index;
}
void Ship::fire(Environment *e) {
this->weapons.at(this->weapon_index)->fire(this->get_d(), this->get_r(), this->get_v(), this->get_size(), e);
}
void Ship::add_weapon(Weapon *weapon) {}
void Ship::sel_weapon(int index) {}
<commit_msg>weapon_index set in ship.init<commit_after>#include "ship.h"
#include "../classes/weapon.h"
#include "../engines/physics/projectile.h"
Ship::Ship(int id, float mass, float max_tolerance, std::vector<float> d, float size, float preset_a, float preset_p_dot, float preset_r_dot) : Projectile(id, 1, mass, max_tolerance, d, { 0, 0, 0 }, size, { 1, 0, 0 }, { 0, 1, 0 }, 0, 0, preset_a, preset_p_dot, preset_r_dot, -1) {
this->type = ObjType::SHIP;
this->weapon_index = 0;
}
int Ship::get_weapon_index() {
return this->weapon_index;
}
void Ship::fire(Environment *e) {
this->weapons.at(this->weapon_index)->fire(this->get_d(), this->get_r(), this->get_v(), this->get_size(), e);
}
void Ship::add_weapon(Weapon *weapon) {}
void Ship::sel_weapon(int index) {}
<|endoftext|>
|
<commit_before>#include "CodeGen_C.h"
#include "StmtToHtml.h"
#include "Output.h"
#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include <fstream>
namespace Halide {
void compile_module_to_object(const Module &module, std::string filename) {
if (filename.empty()) {
if (module.target().os == Target::Windows) {
filename = module.name() + ".obj";
} else {
filename = module.name() + ".o";
}
}
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_object(llvm, filename);
delete llvm;
}
void compile_module_to_assembly(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".s";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_assembly(llvm, filename);
delete llvm;
}
void compile_module_to_native(const Module &module,
std::string object_filename,
std::string assembly_filename) {
if (object_filename.empty()) {
if (module.target().os == Target::Windows) {
object_filename = module.name() + ".obj";
} else {
object_filename = module.name() + ".o";
}
}
if (assembly_filename.empty()) {
assembly_filename = module.name() + ".s";
}
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_object(llvm, object_filename);
compile_llvm_module_to_assembly(llvm, assembly_filename);
delete llvm;
}
void compile_module_to_llvm_bitcode(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".bc";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_llvm_bitcode(llvm, filename);
delete llvm;
}
void compile_module_to_llvm_assembly(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".ll";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_llvm_assembly(llvm, filename);
delete llvm;
}
void compile_module_to_llvm(const Module &module,
std::string bitcode_filename,
std::string llvm_assembly_filename) {
if (bitcode_filename.empty()) bitcode_filename = module.name() + ".bc";
if (llvm_assembly_filename.empty()) llvm_assembly_filename = module.name() + ".ll";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_llvm_bitcode(llvm, bitcode_filename);
compile_llvm_module_to_llvm_assembly(llvm, llvm_assembly_filename);
delete llvm;
}
void compile_module_to_html(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".html";
Internal::print_to_html(filename, module);
}
void compile_module_to_text(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".stmt";
std::ofstream file(filename.c_str());
file << module;
}
void compile_module_to_c_header(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".h";
std::ofstream file(filename.c_str());
Internal::CodeGen_C cg(file, true, filename);
cg.compile(module);
}
void compile_module_to_c_source(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".c";
std::ofstream file(filename.c_str());
Internal::CodeGen_C cg(file, false);
cg.compile(module);
}
void compile_module_to_c(const Module &module,
std::string h_filename,
std::string c_filename) {
compile_module_to_c_header(module, h_filename);
compile_module_to_c_source(module, c_filename);
}
void compile_standalone_runtime(std::string object_filename, Target t) {
Module empty("standalone_runtime", t.without_feature(Target::NoRuntime));
compile_module_to_object(empty, object_filename);
}
} // namespace Halide
<commit_msg>Strip JIT when compiling standalone runtime<commit_after>#include "CodeGen_C.h"
#include "StmtToHtml.h"
#include "Output.h"
#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include <fstream>
namespace Halide {
void compile_module_to_object(const Module &module, std::string filename) {
if (filename.empty()) {
if (module.target().os == Target::Windows) {
filename = module.name() + ".obj";
} else {
filename = module.name() + ".o";
}
}
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_object(llvm, filename);
delete llvm;
}
void compile_module_to_assembly(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".s";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_assembly(llvm, filename);
delete llvm;
}
void compile_module_to_native(const Module &module,
std::string object_filename,
std::string assembly_filename) {
if (object_filename.empty()) {
if (module.target().os == Target::Windows) {
object_filename = module.name() + ".obj";
} else {
object_filename = module.name() + ".o";
}
}
if (assembly_filename.empty()) {
assembly_filename = module.name() + ".s";
}
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_object(llvm, object_filename);
compile_llvm_module_to_assembly(llvm, assembly_filename);
delete llvm;
}
void compile_module_to_llvm_bitcode(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".bc";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_llvm_bitcode(llvm, filename);
delete llvm;
}
void compile_module_to_llvm_assembly(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".ll";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_llvm_assembly(llvm, filename);
delete llvm;
}
void compile_module_to_llvm(const Module &module,
std::string bitcode_filename,
std::string llvm_assembly_filename) {
if (bitcode_filename.empty()) bitcode_filename = module.name() + ".bc";
if (llvm_assembly_filename.empty()) llvm_assembly_filename = module.name() + ".ll";
llvm::LLVMContext context;
llvm::Module *llvm = compile_module_to_llvm_module(module, context);
compile_llvm_module_to_llvm_bitcode(llvm, bitcode_filename);
compile_llvm_module_to_llvm_assembly(llvm, llvm_assembly_filename);
delete llvm;
}
void compile_module_to_html(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".html";
Internal::print_to_html(filename, module);
}
void compile_module_to_text(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".stmt";
std::ofstream file(filename.c_str());
file << module;
}
void compile_module_to_c_header(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".h";
std::ofstream file(filename.c_str());
Internal::CodeGen_C cg(file, true, filename);
cg.compile(module);
}
void compile_module_to_c_source(const Module &module, std::string filename) {
if (filename.empty()) filename = module.name() + ".c";
std::ofstream file(filename.c_str());
Internal::CodeGen_C cg(file, false);
cg.compile(module);
}
void compile_module_to_c(const Module &module,
std::string h_filename,
std::string c_filename) {
compile_module_to_c_header(module, h_filename);
compile_module_to_c_source(module, c_filename);
}
void compile_standalone_runtime(std::string object_filename, Target t) {
t.set_feature(Target::NoRuntime, false);
t.set_feature(Target::JIT, false);
Module empty("standalone_runtime", t);
compile_module_to_object(empty, object_filename);
}
} // namespace Halide
<|endoftext|>
|
<commit_before>#include "Player.hpp"
Player::Player() {
m_x = 0.0f;
m_y = 0.0f;
m_velocity = 0.0f;
for (int i = 0; i < 2; i++)
m_animations[i] = nullptr;
}
Player::Player(float x, float y) {
m_x = x;
m_y = y;
m_velocity = 0.0f;
for (int i = 0; i < 2; i++)
m_animations[i] = nullptr;
}
Player::~Player() {
for (int i = 0; i < 2; i++)
m_animations[i] = nullptr;
}
void Player::handleInput(SDL_Event e) {
if (e.key.repeat == 0) {
switch (e.key.keysym.sym) {
case SDLK_LEFT:
m_currentAnimation = PLAYER_RUNNING_LEFT;
m_x -= 10;
break;
case SDLK_RIGHT:
m_currentAnimation = PLAYER_RUNNING_RIGHT;
m_x += 10;
break;
}
}
}
void Player::update(float deltaTime) {
m_animations[m_currentAnimation]->run();
}
void Player::render(SDL_Renderer* renderer) {
m_animations[m_currentAnimation]->render(m_x, m_y, renderer);
}<commit_msg>put space between last two functions in Player.cpp<commit_after>#include "Player.hpp"
Player::Player() {
m_x = 0.0f;
m_y = 0.0f;
m_velocity = 0.0f;
for (int i = 0; i < 2; i++)
m_animations[i] = nullptr;
}
Player::Player(float x, float y) {
m_x = x;
m_y = y;
m_velocity = 0.0f;
for (int i = 0; i < 2; i++)
m_animations[i] = nullptr;
}
Player::~Player() {
for (int i = 0; i < 2; i++)
m_animations[i] = nullptr;
}
void Player::handleInput(SDL_Event e) {
if (e.key.repeat == 0) {
switch (e.key.keysym.sym) {
case SDLK_LEFT:
m_currentAnimation = PLAYER_RUNNING_LEFT;
m_x -= 10;
break;
case SDLK_RIGHT:
m_currentAnimation = PLAYER_RUNNING_RIGHT;
m_x += 10;
break;
}
}
}
void Player::update(float deltaTime) {
m_animations[m_currentAnimation]->run();
}
void Player::render(SDL_Renderer* renderer) {
m_animations[m_currentAnimation]->render(m_x, m_y, renderer);
}<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#include "Team.h"
#include "Pack.h"
float Team::tankColor[NumTeams][3] = {
{ 0.0f, 0.0f, 0.0f }, // rogue
{ 1.0f, 0.0f, 0.0f }, // red
{ 0.0f, 1.0f, 0.0f }, // green
{ 0.2f, 0.2f, 1.0f }, // blue
{ 1.0f, 0.0f, 1.0f }, // purple
{ 0.0f, 0.0f, 0.0f }, // observer
{ 1.0f, 1.0f, 1.0f } // rabbit
};
float Team::radarColor[NumTeams][3] = {
{ 1.0f, 1.0f, 0.0f }, // rogue
{ 1.0f, 0.15f, 0.15f }, // red
{ 0.2f, 0.9f, 0.2f }, // green
{ 0.08f, 0.25, 1.0f }, // blue
{ 1.0f, 0.4f, 1.0f }, // purple
{ 0.0f, 0.0f, 0.0f }, // observer
{ 1.0f, 1.0f, 1.0f } // rabbit
};
Team::Team()
{
size = 0;
won = 0;
lost = 0;
}
void* Team::pack(void* buf) const
{
buf = nboPackUShort(buf, uint16_t(size));
buf = nboPackUShort(buf, uint16_t(won));
buf = nboPackUShort(buf, uint16_t(lost));
return buf;
}
void* Team::unpack(void* buf)
{
uint16_t inSize, inWon, inLost;
buf = nboUnpackUShort(buf, inSize);
buf = nboUnpackUShort(buf, inWon);
buf = nboUnpackUShort(buf, inLost);
size = (unsigned short)inSize;
won = (unsigned short)inWon;
lost = (unsigned short)inLost;
return buf;
}
const char* Team::getName(TeamColor team) // const
{
switch (team) {
case RogueTeam: return "Rogue";
case RedTeam: return "Red Team";
case GreenTeam: return "Green Team";
case BlueTeam: return "Blue Team";
case PurpleTeam: return "Purple Team";
case ObserverTeam: return "Observer";
case RabbitTeam: return "Rabbit";
default: return "Invalid team";
}
}
const float* Team::getTankColor(TeamColor team) // const
{
return tankColor[int(team)];
}
const float* Team::getRadarColor(TeamColor team) // const
{
return radarColor[int(team)];
}
const bool Team::isColorTeam(TeamColor team) // const
{
return team >= RedTeam && team <= PurpleTeam;
}
void Team::setColors(TeamColor team,
const float* tank,
const float* radar)
{
tankColor[int(team)][0] = tank[0];
tankColor[int(team)][1] = tank[1];
tankColor[int(team)][2] = tank[2];
radarColor[int(team)][0] = radar[0];
radarColor[int(team)][1] = radar[1];
radarColor[int(team)][2] = radar[2];
}
// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>added automatic team label and invalid index protection in accessors<commit_after>/* bzflag
* Copyright (c) 1993 - 2003 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "common.h"
#include "Team.h"
#include "Pack.h"
float Team::tankColor[NumTeams][3] = {
{ 0.0f, 0.0f, 0.0f }, // rogue
{ 1.0f, 0.0f, 0.0f }, // red
{ 0.0f, 1.0f, 0.0f }, // green
{ 0.2f, 0.2f, 1.0f }, // blue
{ 1.0f, 0.0f, 1.0f }, // purple
{ 0.0f, 0.0f, 0.0f }, // observer
{ 1.0f, 1.0f, 1.0f } // rabbit
};
float Team::radarColor[NumTeams][3] = {
{ 1.0f, 1.0f, 0.0f }, // rogue
{ 1.0f, 0.15f, 0.15f }, // red
{ 0.2f, 0.9f, 0.2f }, // green
{ 0.08f, 0.25, 1.0f }, // blue
{ 1.0f, 0.4f, 1.0f }, // purple
{ 0.0f, 0.0f, 0.0f }, // observer
{ 1.0f, 1.0f, 1.0f } // rabbit
};
Team::Team()
{
size = 0;
won = 0;
lost = 0;
}
void* Team::pack(void* buf) const
{
buf = nboPackUShort(buf, uint16_t(size));
buf = nboPackUShort(buf, uint16_t(won));
buf = nboPackUShort(buf, uint16_t(lost));
return buf;
}
void* Team::unpack(void* buf)
{
uint16_t inSize, inWon, inLost;
buf = nboUnpackUShort(buf, inSize);
buf = nboUnpackUShort(buf, inWon);
buf = nboUnpackUShort(buf, inLost);
size = (unsigned short)inSize;
won = (unsigned short)inWon;
lost = (unsigned short)inLost;
return buf;
}
const char* Team::getName(TeamColor team) // const
{
switch (team) {
case AutomaticTeam: return "Automatic";
case RogueTeam: return "Rogue";
case RedTeam: return "Red Team";
case GreenTeam: return "Green Team";
case BlueTeam: return "Blue Team";
case PurpleTeam: return "Purple Team";
case ObserverTeam: return "Observer";
case RabbitTeam: return "Rabbit";
case NoTeam: return "No Team??";
default: return "Invalid team";
}
}
const float* Team::getTankColor(TeamColor team) // const
{
if (int(team) < 0) {
return tankColor[0];
}
return tankColor[int(team)];
}
const float* Team::getRadarColor(TeamColor team) // const
{
if (int(team) < 0) {
return radarColor[0];
}
return radarColor[int(team)];
}
const bool Team::isColorTeam(TeamColor team) // const
{
return team >= RedTeam && team <= PurpleTeam;
}
void Team::setColors(TeamColor team,
const float* tank,
const float* radar)
{
if (int(team) < 0) {
team = 0;
}
tankColor[int(team)][0] = tank[0];
tankColor[int(team)][1] = tank[1];
tankColor[int(team)][2] = tank[2];
radarColor[int(team)][0] = radar[0];
radarColor[int(team)][1] = radar[1];
radarColor[int(team)][2] = radar[2];
}
// Local variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>#define PY_SSIZE_T_CLEAN
#include <Python.h>
// Numpy array interface
struct PyArrayInterface {
int two; // contains the integer 2 -- simple sanity check
int nd; // number of dimensions
char typekind; // kind in array --- character code of typestr
int itemsize; // size of each element
int flags; // flags indicating how the data should be interpreted, must set ARR_HAS_DESCR bit to validate descr
Py_intptr_t * shape; // A length-nd array of shape information
Py_intptr_t * strides; // A length-nd array of stride information
void * data; // A pointer to the first element of the array
PyObject * descr; // NULL or data-description (same as descr key of __array_interface__) -- must set ARR_HAS_DESCR flag or this will be ignored.
};
<commit_msg>redefined<commit_after>#pragma once
#define PY_SSIZE_T_CLEAN
#include <Python.h>
// Numpy array interface
struct PyArrayInterface {
int two; // contains the integer 2 -- simple sanity check
int nd; // number of dimensions
char typekind; // kind in array --- character code of typestr
int itemsize; // size of each element
int flags; // flags indicating how the data should be interpreted, must set ARR_HAS_DESCR bit to validate descr
Py_intptr_t * shape; // A length-nd array of shape information
Py_intptr_t * strides; // A length-nd array of stride information
void * data; // A pointer to the first element of the array
PyObject * descr; // NULL or data-description (same as descr key of __array_interface__) -- must set ARR_HAS_DESCR flag or this will be ignored.
};
<|endoftext|>
|
<commit_before>// Kernel.cpp (Oclgrind)
// Copyright (c) 2013-2016, James Price and Simon McIntosh-Smith,
// University of Bristol. All rights reserved.
//
// This program is provided under a three-clause BSD license. For full
// license terms please see the LICENSE file distributed with this
// source code.
#include "config.h"
#include "common.h"
#include <sstream>
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_os_ostream.h"
#include "Kernel.h"
#include "Program.h"
#include "Memory.h"
using namespace oclgrind;
using namespace std;
Kernel::Kernel(const Program *program,
const llvm::Function *function, const llvm::Module *module)
: m_program(program), m_function(function), m_name(function->getName())
{
// Set-up global variables
llvm::Module::const_global_iterator itr;
for (itr = module->global_begin(); itr != module->global_end(); itr++)
{
llvm::PointerType *type = itr->getType();
switch (type->getPointerAddressSpace())
{
case AddrSpacePrivate:
{
// Get initializer data
const llvm::Constant *init = itr->getInitializer();
unsigned size = getTypeSize(init->getType());
TypedValue value = {size, 1, new uint8_t[size]};
getConstantData(value.data, init);
m_values[&*itr] = value;
break;
}
case AddrSpaceConstant:
m_constants.push_back(&*itr);
break;
case AddrSpaceLocal:
{
// Get size of allocation
TypedValue allocSize = {
getTypeSize(itr->getInitializer()->getType()), 1, NULL
};
m_values[&*itr] = allocSize;
break;
}
default:
FATAL_ERROR("Unsupported GlobalVariable address space: %d",
type->getPointerAddressSpace());
}
}
// Get metadata node containing kernel arg info
m_metadata = NULL;
llvm::NamedMDNode *md = module->getNamedMetadata("opencl.kernels");
if (md)
{
for (unsigned i = 0; i < md->getNumOperands(); i++)
{
llvm::MDNode *node = md->getOperand(i);
llvm::ConstantAsMetadata *cam =
llvm::dyn_cast<llvm::ConstantAsMetadata>(node->getOperand(0).get());
if (!cam)
continue;
llvm::Function *function = ((llvm::Function*)cam->getValue());
if (function->getName() == m_name)
{
m_metadata = node;
break;
}
}
}
}
Kernel::Kernel(const Kernel& kernel)
: m_program(kernel.m_program)
{
m_function = kernel.m_function;
m_constants = kernel.m_constants;
m_constantBuffers = kernel.m_constantBuffers;
m_name = kernel.m_name;
m_metadata = kernel.m_metadata;
for (auto itr = kernel.m_values.begin(); itr != kernel.m_values.end(); itr++)
{
m_values[itr->first] = itr->second.clone();
}
}
Kernel::~Kernel()
{
TypedValueMap::iterator itr;
for (itr = m_values.begin(); itr != m_values.end(); itr++)
{
delete[] itr->second.data;
}
}
bool Kernel::allArgumentsSet() const
{
llvm::Function::const_arg_iterator itr;
for (itr = m_function->arg_begin(); itr != m_function->arg_end(); itr++)
{
if (!m_values.count(&*itr))
{
return false;
}
}
return true;
}
void Kernel::allocateConstants(Memory *memory)
{
list<const llvm::GlobalVariable*>::const_iterator itr;
for (itr = m_constants.begin(); itr != m_constants.end(); itr++)
{
const llvm::Constant *initializer = (*itr)->getInitializer();
const llvm::Type *type = initializer->getType();
// Deallocate existing pointer
if (m_values.count(*itr))
{
delete[] m_values[*itr].data;
}
// Get initializer data
unsigned size = getTypeSize(type);
unsigned char *data = new unsigned char[size];
getConstantData(data, (const llvm::Constant*)initializer);
// Allocate buffer
TypedValue address = {
sizeof(size_t),
1,
new unsigned char[sizeof(size_t)]
};
size_t ptr = memory->allocateBuffer(size, 0, data);
address.setPointer(ptr);
m_values[*itr] = address;
m_constantBuffers.push_back(ptr);
delete[] data;
}
}
void Kernel::deallocateConstants(Memory *memory)
{
list<size_t>::const_iterator itr;
for (itr = m_constantBuffers.begin(); itr != m_constantBuffers.end(); itr++)
{
memory->deallocateBuffer(*itr);
}
m_constantBuffers.clear();
}
const llvm::Argument* Kernel::getArgument(unsigned int index) const
{
assert(index < getNumArguments());
llvm::Function::const_arg_iterator argItr = m_function->arg_begin();
for (unsigned i = 0; i < index; i++)
{
argItr++;
}
return &*argItr;
}
unsigned int Kernel::getArgumentAccessQualifier(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md =
getArgumentMetadata("kernel_arg_access_qual", index);
if (!md)
{
return -1;
}
// Get qualifier string
const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
string access = str->getString();
if (access == "read_only")
{
return CL_KERNEL_ARG_ACCESS_READ_ONLY;
}
else if (access == "write_only")
{
return CL_KERNEL_ARG_ACCESS_WRITE_ONLY;
}
else if (access == "read_write")
{
return CL_KERNEL_ARG_ACCESS_READ_WRITE;
}
return CL_KERNEL_ARG_ACCESS_NONE;
}
unsigned int Kernel::getArgumentAddressQualifier(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md =
getArgumentMetadata("kernel_arg_addr_space", index);
if (!md)
{
return -1;
}
switch(getMDAsConstInt(md)->getZExtValue())
{
case AddrSpacePrivate:
return CL_KERNEL_ARG_ADDRESS_PRIVATE;
case AddrSpaceGlobal:
return CL_KERNEL_ARG_ADDRESS_GLOBAL;
case AddrSpaceConstant:
return CL_KERNEL_ARG_ADDRESS_CONSTANT;
case AddrSpaceLocal:
return CL_KERNEL_ARG_ADDRESS_LOCAL;
default:
return -1;
}
}
const llvm::Metadata* Kernel::getArgumentMetadata(string name,
unsigned int index) const
{
#if LLVM_VERSION < 39
if (!m_metadata)
{
return NULL;
}
// Loop over all metadata nodes for this kernel
for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
{
const llvm::MDOperand& op = m_metadata->getOperand(i);
if (llvm::MDNode *node = llvm::dyn_cast<llvm::MDNode>(op.get()))
{
// Check if node matches target name
if (node->getNumOperands() > 0 &&
((llvm::MDString*)(node->getOperand(0).get()))->getString() == name)
{
return node->getOperand(index+1).get();
}
}
}
return NULL;
#else
llvm::MDNode *node = m_function->getMetadata(name);
if (!node)
return NULL;
return node->getOperand(index);
#endif
}
const llvm::StringRef Kernel::getArgumentName(unsigned int index) const
{
return getArgument(index)->getName();
}
const llvm::StringRef Kernel::getArgumentTypeName(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type", index);
if (!md)
{
return "";
}
return llvm::dyn_cast<llvm::MDString>(md)->getString();
}
unsigned int Kernel::getArgumentTypeQualifier(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type_qual", index);
if (!md)
{
return -1;
}
// Get qualifiers
const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
istringstream iss(str->getString().str());
unsigned int result = CL_KERNEL_ARG_TYPE_NONE;
while (!iss.eof())
{
string tok;
iss >> tok;
if (tok == "const")
{
result |= CL_KERNEL_ARG_TYPE_CONST;
}
else if (tok == "restrict")
{
result |= CL_KERNEL_ARG_TYPE_RESTRICT;
}
else if (tok == "volatile")
{
result |= CL_KERNEL_ARG_TYPE_VOLATILE;
}
}
return result;
}
size_t Kernel::getArgumentSize(unsigned int index) const
{
const llvm::Argument *argument = getArgument(index);
const llvm::Type *type = argument->getType();
// Check if pointer argument
if (type->isPointerTy() && argument->hasByValAttr())
{
return getTypeSize(type->getPointerElementType());
}
return getTypeSize(type);
}
string Kernel::getAttributes() const
{
ostringstream attributes("");
for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
{
llvm::MDNode *op = llvm::dyn_cast<llvm::MDNode>(m_metadata->getOperand(i));
if (op)
{
llvm::MDNode *val = ((llvm::MDNode*)op);
llvm::MDString *str =
llvm::dyn_cast<llvm::MDString>(val->getOperand(0).get());
string name = str->getString().str();
if (name == "reqd_work_group_size" ||
name == "work_group_size_hint")
{
attributes << name << "("
<< getMDAsConstInt(val->getOperand(1))->getZExtValue()
<< "," << getMDAsConstInt(val->getOperand(2))->getZExtValue()
<< "," << getMDAsConstInt(val->getOperand(3))->getZExtValue()
<< ") ";
}
else if (name == "vec_type_hint")
{
// Get type hint
size_t n = 1;
llvm::Metadata *md = val->getOperand(1).get();
llvm::ValueAsMetadata *vam = llvm::dyn_cast<llvm::ValueAsMetadata>(md);
const llvm::Type *type = vam->getType();
if (type->isVectorTy())
{
n = type->getVectorNumElements();
type = type->getVectorElementType();
}
// Generate attribute string
attributes << name << "(" << flush;
llvm::raw_os_ostream out(attributes);
type->print(out);
out.flush();
attributes << n << ") ";
}
}
}
return attributes.str();
}
const llvm::Function* Kernel::getFunction() const
{
return m_function;
}
size_t Kernel::getLocalMemorySize() const
{
size_t sz = 0;
for (auto value = m_values.begin(); value != m_values.end(); value++)
{
const llvm::Type *type = value->first->getType();
if (type->isPointerTy() && type->getPointerAddressSpace() == AddrSpaceLocal)
{
sz += value->second.size;
}
}
return sz;
}
const std::string& Kernel::getName() const
{
return m_name;
}
unsigned int Kernel::getNumArguments() const
{
return m_function->arg_size();
}
const Program* Kernel::getProgram() const
{
return m_program;
}
void Kernel::getRequiredWorkGroupSize(size_t reqdWorkGroupSize[3]) const
{
memset(reqdWorkGroupSize, 0, 3*sizeof(size_t));
for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
{
const llvm::MDOperand& op = m_metadata->getOperand(i);
if (llvm::MDNode *val = llvm::dyn_cast<llvm::MDNode>(op.get()))
{
llvm::MDString *str =
llvm::dyn_cast<llvm::MDString>(val->getOperand(0).get());
if (str->getString() == "reqd_work_group_size")
{
for (int j = 0; j < 3; j++)
{
reqdWorkGroupSize[j] =
getMDAsConstInt(val->getOperand(j+1))->getZExtValue();
}
}
}
}
}
void Kernel::setArgument(unsigned int index, TypedValue value)
{
assert(index < m_function->arg_size());
const llvm::Value *argument = getArgument(index);
// Deallocate existing argument
if (m_values.count(argument))
{
delete[] m_values[argument].data;
}
m_values[argument] = value.clone();
}
TypedValueMap::const_iterator Kernel::values_begin() const
{
return m_values.begin();
}
TypedValueMap::const_iterator Kernel::values_end() const
{
return m_values.end();
}
<commit_msg>Use getArgumentMetadata for reqd_work_group_size<commit_after>// Kernel.cpp (Oclgrind)
// Copyright (c) 2013-2016, James Price and Simon McIntosh-Smith,
// University of Bristol. All rights reserved.
//
// This program is provided under a three-clause BSD license. For full
// license terms please see the LICENSE file distributed with this
// source code.
#include "config.h"
#include "common.h"
#include <sstream>
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_os_ostream.h"
#include "Kernel.h"
#include "Program.h"
#include "Memory.h"
using namespace oclgrind;
using namespace std;
Kernel::Kernel(const Program *program,
const llvm::Function *function, const llvm::Module *module)
: m_program(program), m_function(function), m_name(function->getName())
{
// Set-up global variables
llvm::Module::const_global_iterator itr;
for (itr = module->global_begin(); itr != module->global_end(); itr++)
{
llvm::PointerType *type = itr->getType();
switch (type->getPointerAddressSpace())
{
case AddrSpacePrivate:
{
// Get initializer data
const llvm::Constant *init = itr->getInitializer();
unsigned size = getTypeSize(init->getType());
TypedValue value = {size, 1, new uint8_t[size]};
getConstantData(value.data, init);
m_values[&*itr] = value;
break;
}
case AddrSpaceConstant:
m_constants.push_back(&*itr);
break;
case AddrSpaceLocal:
{
// Get size of allocation
TypedValue allocSize = {
getTypeSize(itr->getInitializer()->getType()), 1, NULL
};
m_values[&*itr] = allocSize;
break;
}
default:
FATAL_ERROR("Unsupported GlobalVariable address space: %d",
type->getPointerAddressSpace());
}
}
// Get metadata node containing kernel arg info
m_metadata = NULL;
llvm::NamedMDNode *md = module->getNamedMetadata("opencl.kernels");
if (md)
{
for (unsigned i = 0; i < md->getNumOperands(); i++)
{
llvm::MDNode *node = md->getOperand(i);
llvm::ConstantAsMetadata *cam =
llvm::dyn_cast<llvm::ConstantAsMetadata>(node->getOperand(0).get());
if (!cam)
continue;
llvm::Function *function = ((llvm::Function*)cam->getValue());
if (function->getName() == m_name)
{
m_metadata = node;
break;
}
}
}
}
Kernel::Kernel(const Kernel& kernel)
: m_program(kernel.m_program)
{
m_function = kernel.m_function;
m_constants = kernel.m_constants;
m_constantBuffers = kernel.m_constantBuffers;
m_name = kernel.m_name;
m_metadata = kernel.m_metadata;
for (auto itr = kernel.m_values.begin(); itr != kernel.m_values.end(); itr++)
{
m_values[itr->first] = itr->second.clone();
}
}
Kernel::~Kernel()
{
TypedValueMap::iterator itr;
for (itr = m_values.begin(); itr != m_values.end(); itr++)
{
delete[] itr->second.data;
}
}
bool Kernel::allArgumentsSet() const
{
llvm::Function::const_arg_iterator itr;
for (itr = m_function->arg_begin(); itr != m_function->arg_end(); itr++)
{
if (!m_values.count(&*itr))
{
return false;
}
}
return true;
}
void Kernel::allocateConstants(Memory *memory)
{
list<const llvm::GlobalVariable*>::const_iterator itr;
for (itr = m_constants.begin(); itr != m_constants.end(); itr++)
{
const llvm::Constant *initializer = (*itr)->getInitializer();
const llvm::Type *type = initializer->getType();
// Deallocate existing pointer
if (m_values.count(*itr))
{
delete[] m_values[*itr].data;
}
// Get initializer data
unsigned size = getTypeSize(type);
unsigned char *data = new unsigned char[size];
getConstantData(data, (const llvm::Constant*)initializer);
// Allocate buffer
TypedValue address = {
sizeof(size_t),
1,
new unsigned char[sizeof(size_t)]
};
size_t ptr = memory->allocateBuffer(size, 0, data);
address.setPointer(ptr);
m_values[*itr] = address;
m_constantBuffers.push_back(ptr);
delete[] data;
}
}
void Kernel::deallocateConstants(Memory *memory)
{
list<size_t>::const_iterator itr;
for (itr = m_constantBuffers.begin(); itr != m_constantBuffers.end(); itr++)
{
memory->deallocateBuffer(*itr);
}
m_constantBuffers.clear();
}
const llvm::Argument* Kernel::getArgument(unsigned int index) const
{
assert(index < getNumArguments());
llvm::Function::const_arg_iterator argItr = m_function->arg_begin();
for (unsigned i = 0; i < index; i++)
{
argItr++;
}
return &*argItr;
}
unsigned int Kernel::getArgumentAccessQualifier(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md =
getArgumentMetadata("kernel_arg_access_qual", index);
if (!md)
{
return -1;
}
// Get qualifier string
const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
string access = str->getString();
if (access == "read_only")
{
return CL_KERNEL_ARG_ACCESS_READ_ONLY;
}
else if (access == "write_only")
{
return CL_KERNEL_ARG_ACCESS_WRITE_ONLY;
}
else if (access == "read_write")
{
return CL_KERNEL_ARG_ACCESS_READ_WRITE;
}
return CL_KERNEL_ARG_ACCESS_NONE;
}
unsigned int Kernel::getArgumentAddressQualifier(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md =
getArgumentMetadata("kernel_arg_addr_space", index);
if (!md)
{
return -1;
}
switch(getMDAsConstInt(md)->getZExtValue())
{
case AddrSpacePrivate:
return CL_KERNEL_ARG_ADDRESS_PRIVATE;
case AddrSpaceGlobal:
return CL_KERNEL_ARG_ADDRESS_GLOBAL;
case AddrSpaceConstant:
return CL_KERNEL_ARG_ADDRESS_CONSTANT;
case AddrSpaceLocal:
return CL_KERNEL_ARG_ADDRESS_LOCAL;
default:
return -1;
}
}
const llvm::Metadata* Kernel::getArgumentMetadata(string name,
unsigned int index) const
{
#if LLVM_VERSION < 39
if (!m_metadata)
{
return NULL;
}
// Loop over all metadata nodes for this kernel
for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
{
const llvm::MDOperand& op = m_metadata->getOperand(i);
if (llvm::MDNode *node = llvm::dyn_cast<llvm::MDNode>(op.get()))
{
// Check if node matches target name
if (node->getNumOperands() > 0 &&
((llvm::MDString*)(node->getOperand(0).get()))->getString() == name)
{
return node->getOperand(index+1).get();
}
}
}
return NULL;
#else
llvm::MDNode *node = m_function->getMetadata(name);
if (!node)
return NULL;
return node->getOperand(index);
#endif
}
const llvm::StringRef Kernel::getArgumentName(unsigned int index) const
{
return getArgument(index)->getName();
}
const llvm::StringRef Kernel::getArgumentTypeName(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type", index);
if (!md)
{
return "";
}
return llvm::dyn_cast<llvm::MDString>(md)->getString();
}
unsigned int Kernel::getArgumentTypeQualifier(unsigned int index) const
{
assert(index < getNumArguments());
// Get metadata
const llvm::Metadata *md = getArgumentMetadata("kernel_arg_type_qual", index);
if (!md)
{
return -1;
}
// Get qualifiers
const llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(md);
istringstream iss(str->getString().str());
unsigned int result = CL_KERNEL_ARG_TYPE_NONE;
while (!iss.eof())
{
string tok;
iss >> tok;
if (tok == "const")
{
result |= CL_KERNEL_ARG_TYPE_CONST;
}
else if (tok == "restrict")
{
result |= CL_KERNEL_ARG_TYPE_RESTRICT;
}
else if (tok == "volatile")
{
result |= CL_KERNEL_ARG_TYPE_VOLATILE;
}
}
return result;
}
size_t Kernel::getArgumentSize(unsigned int index) const
{
const llvm::Argument *argument = getArgument(index);
const llvm::Type *type = argument->getType();
// Check if pointer argument
if (type->isPointerTy() && argument->hasByValAttr())
{
return getTypeSize(type->getPointerElementType());
}
return getTypeSize(type);
}
string Kernel::getAttributes() const
{
ostringstream attributes("");
for (unsigned i = 0; i < m_metadata->getNumOperands(); i++)
{
llvm::MDNode *op = llvm::dyn_cast<llvm::MDNode>(m_metadata->getOperand(i));
if (op)
{
llvm::MDNode *val = ((llvm::MDNode*)op);
llvm::MDString *str =
llvm::dyn_cast<llvm::MDString>(val->getOperand(0).get());
string name = str->getString().str();
if (name == "reqd_work_group_size" ||
name == "work_group_size_hint")
{
attributes << name << "("
<< getMDAsConstInt(val->getOperand(1))->getZExtValue()
<< "," << getMDAsConstInt(val->getOperand(2))->getZExtValue()
<< "," << getMDAsConstInt(val->getOperand(3))->getZExtValue()
<< ") ";
}
else if (name == "vec_type_hint")
{
// Get type hint
size_t n = 1;
llvm::Metadata *md = val->getOperand(1).get();
llvm::ValueAsMetadata *vam = llvm::dyn_cast<llvm::ValueAsMetadata>(md);
const llvm::Type *type = vam->getType();
if (type->isVectorTy())
{
n = type->getVectorNumElements();
type = type->getVectorElementType();
}
// Generate attribute string
attributes << name << "(" << flush;
llvm::raw_os_ostream out(attributes);
type->print(out);
out.flush();
attributes << n << ") ";
}
}
}
return attributes.str();
}
const llvm::Function* Kernel::getFunction() const
{
return m_function;
}
size_t Kernel::getLocalMemorySize() const
{
size_t sz = 0;
for (auto value = m_values.begin(); value != m_values.end(); value++)
{
const llvm::Type *type = value->first->getType();
if (type->isPointerTy() && type->getPointerAddressSpace() == AddrSpaceLocal)
{
sz += value->second.size;
}
}
return sz;
}
const std::string& Kernel::getName() const
{
return m_name;
}
unsigned int Kernel::getNumArguments() const
{
return m_function->arg_size();
}
const Program* Kernel::getProgram() const
{
return m_program;
}
void Kernel::getRequiredWorkGroupSize(size_t reqdWorkGroupSize[3]) const
{
memset(reqdWorkGroupSize, 0, 3*sizeof(size_t));
for (int j = 0; j < 3; j++)
{
const llvm::Metadata *md = getArgumentMetadata("reqd_work_group_size", j);
if (md)
reqdWorkGroupSize[j] = getMDAsConstInt(md)->getZExtValue();
}
}
void Kernel::setArgument(unsigned int index, TypedValue value)
{
assert(index < m_function->arg_size());
const llvm::Value *argument = getArgument(index);
// Deallocate existing argument
if (m_values.count(argument))
{
delete[] m_values[argument].data;
}
m_values[argument] = value.clone();
}
TypedValueMap::const_iterator Kernel::values_begin() const
{
return m_values.begin();
}
TypedValueMap::const_iterator Kernel::values_end() const
{
return m_values.end();
}
<|endoftext|>
|
<commit_before>#include <time.h>
#include <iostream>
#include <fstream>
#include "logger.h"
Logger::Logger(std::string log_name)
{
m_output = new std::ofstream(log_name.c_str());
}
Logger::Logger()
{
m_output = &std::cerr;
}
std::ostream &Logger::log(LogSeverity sev)
{
const char *sevtext;
switch(sev) {
case LSEVERITY_SPAM:
sevtext = "SPAM";
break;
case LSEVERITY_DEBUG:
sevtext = "DEBUG";
break;
case LSEVERITY_INFO:
sevtext = "INFO";
break;
case LSEVERITY_WARNING:
sevtext = "WARNING";
break;
case LSEVERITY_SECURITY:
sevtext = "SECURITY";
break;
case LSEVERITY_ERROR:
sevtext = "ERROR";
break;
case LSEVERITY_FATAL:
sevtext = "FATAL";
break;
}
time_t rawtime;
time(&rawtime);
char timetext[1024];
strftime(timetext, 1024, "%Y-%m-%d %H:%M:%S", localtime(&rawtime));
*m_output << "[" << timetext << "] " << sevtext << ": ";
return *m_output;
}
#define LOG_LEVEL(name, severity) \
std::ostream &Logger::name() \
{ \
return log(severity); \
}
LOG_LEVEL(spam, LSEVERITY_SPAM)
LOG_LEVEL(debug, LSEVERITY_DEBUG)
LOG_LEVEL(info, LSEVERITY_INFO)
LOG_LEVEL(warning, LSEVERITY_WARNING)
LOG_LEVEL(security, LSEVERITY_SECURITY)
LOG_LEVEL(error, LSEVERITY_ERROR)
LOG_LEVEL(fatal, LSEVERITY_FATAL)
<commit_msg>Logger: Move variable initializations to initializer lists where they blong. Output on std::cout rather than cerr, because not all of our output is error<commit_after>#include <time.h>
#include <iostream>
#include <fstream>
#include "logger.h"
Logger::Logger(std::string log_name) : m_output(new std::ofstream(log_name))
{
}
Logger::Logger() : m_output(&std::cout)
{
}
std::ostream &Logger::log(LogSeverity sev)
{
const char *sevtext;
switch(sev) {
case LSEVERITY_SPAM:
sevtext = "SPAM";
break;
case LSEVERITY_DEBUG:
sevtext = "DEBUG";
break;
case LSEVERITY_INFO:
sevtext = "INFO";
break;
case LSEVERITY_WARNING:
sevtext = "WARNING";
break;
case LSEVERITY_SECURITY:
sevtext = "SECURITY";
break;
case LSEVERITY_ERROR:
sevtext = "ERROR";
break;
case LSEVERITY_FATAL:
sevtext = "FATAL";
break;
}
time_t rawtime;
time(&rawtime);
char timetext[1024];
strftime(timetext, 1024, "%Y-%m-%d %H:%M:%S", localtime(&rawtime));
*m_output << "[" << timetext << "] " << sevtext << ": ";
return *m_output;
}
#define LOG_LEVEL(name, severity) \
std::ostream &Logger::name() \
{ \
return log(severity); \
}
LOG_LEVEL(spam, LSEVERITY_SPAM)
LOG_LEVEL(debug, LSEVERITY_DEBUG)
LOG_LEVEL(info, LSEVERITY_INFO)
LOG_LEVEL(warning, LSEVERITY_WARNING)
LOG_LEVEL(security, LSEVERITY_SECURITY)
LOG_LEVEL(error, LSEVERITY_ERROR)
LOG_LEVEL(fatal, LSEVERITY_FATAL)
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "defragmenter.h"
#include <phosphor/phosphor.h>
#include "defragmenter_visitor.h"
#include "ep_engine.h"
#include "stored-value.h"
DefragmenterTask::DefragmenterTask(EventuallyPersistentEngine* e,
EPStats& stats_)
: GlobalTask(e, TaskId::DefragmenterTask, false),
stats(stats_),
epstore_position(engine->getKVBucket()->startPosition()),
visitor(NULL) {
}
DefragmenterTask::~DefragmenterTask() {
delete visitor;
}
bool DefragmenterTask::run(void) {
TRACE_EVENT0("ep-engine/task", "DefragmenterTask");
if (engine->getConfiguration().isDefragmenterEnabled()) {
// Get our visitor. If we didn't finish the previous pass,
// then resume from where we last were, otherwise create a new visitor and
// reset the position.
if (visitor == NULL) {
visitor = new DefragmentVisitor(getAgeThreshold());
epstore_position = engine->getKVBucket()->startPosition();
}
// Print start status.
std::stringstream ss;
ss << to_string(getDescription()) << " for bucket '"
<< engine->getName() << "'";
if (epstore_position == engine->getKVBucket()->startPosition()) {
ss << " starting. ";
} else {
ss << " resuming from " << epstore_position << ", ";
ss << visitor->getHashtablePosition() << ".";
}
ss << " Using chunk_duration=" << getChunkDurationMS() << " ms."
<< " mem_used=" << stats.getTotalMemoryUsed()
<< ", mapped_bytes=" << getMappedBytes();
LOG(EXTENSION_LOG_INFO, "%s", ss.str().c_str());
// Disable thread-caching (as we are about to defragment, and hence don't
// want any of the new Blobs in tcache).
ALLOCATOR_HOOKS_API* alloc_hooks = engine->getServerApi()->alloc_hooks;
bool old_tcache = alloc_hooks->enable_thread_cache(false);
// Prepare the visitor.
hrtime_t start = gethrtime();
hrtime_t deadline = start + (getChunkDurationMS() * 1000 * 1000);
visitor->setDeadline(deadline);
visitor->clearStats();
// Do it - set off the visitor.
epstore_position = engine->getKVBucket()->pauseResumeVisit(
*visitor,
epstore_position);
hrtime_t end = gethrtime();
// Defrag complete. Restore thread caching.
alloc_hooks->enable_thread_cache(old_tcache);
// Update stats
stats.defragNumMoved.fetch_add(visitor->getDefragCount());
stats.defragNumVisited.fetch_add(visitor->getVisitedCount());
// Release any free memory we now have in the allocator back to the OS.
// TODO: Benchmark this - is it necessary? How much of a slowdown does it
// add? How much memory does it return?
alloc_hooks->release_free_memory();
// Check if the visitor completed a full pass.
bool completed = (epstore_position ==
engine->getKVBucket()->endPosition());
// Print status.
ss.str("");
ss << to_string(getDescription()) << " for bucket '"
<< engine->getName() << "'";
if (completed) {
ss << " finished.";
} else {
ss << " paused at position " << epstore_position << ".";
}
ss << " Took " << (end - start) / 1024 << " us."
<< " moved " << visitor->getDefragCount() << "/"
<< visitor->getVisitedCount() << " visited documents."
<< " mem_used=" << stats.getTotalMemoryUsed()
<< ", mapped_bytes=" << getMappedBytes()
<< ". Sleeping for " << getSleepTime() << " seconds.";
LOG(EXTENSION_LOG_INFO, "%s", ss.str().c_str());
// Delete visitor if it finished.
if (completed) {
delete visitor;
visitor = NULL;
}
}
snooze(getSleepTime());
if (engine->getEpStats().isShutdown) {
return false;
}
return true;
}
void DefragmenterTask::stop(void) {
if (uid) {
ExecutorPool::get()->cancel(uid);
}
}
cb::const_char_buffer DefragmenterTask::getDescription() {
return "Memory defragmenter";
}
size_t DefragmenterTask::getSleepTime() const {
return engine->getConfiguration().getDefragmenterInterval();
}
size_t DefragmenterTask::getAgeThreshold() const {
return engine->getConfiguration().getDefragmenterAgeThreshold();
}
size_t DefragmenterTask::getChunkDurationMS() const {
return engine->getConfiguration().getDefragmenterChunkDuration();
}
size_t DefragmenterTask::getMappedBytes() {
ALLOCATOR_HOOKS_API* alloc_hooks = engine->getServerApi()->alloc_hooks;
allocator_stats stats = {0};
stats.ext_stats_size = alloc_hooks->get_extra_stats_size();
stats.ext_stats = new allocator_ext_stat[stats.ext_stats_size];
alloc_hooks->get_allocator_stats(&stats);
size_t mapped_bytes = stats.heap_size - stats.free_mapped_size -
stats.free_unmapped_size;
delete[] stats.ext_stats;
return mapped_bytes;
}
<commit_msg>DefragmenterTask: Don't wait task to complete before shutdown<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2014 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "defragmenter.h"
#include <phosphor/phosphor.h>
#include "defragmenter_visitor.h"
#include "ep_engine.h"
#include "stored-value.h"
DefragmenterTask::DefragmenterTask(EventuallyPersistentEngine* e,
EPStats& stats_)
: GlobalTask(e, TaskId::DefragmenterTask, 0, false),
stats(stats_),
epstore_position(engine->getKVBucket()->startPosition()),
visitor(NULL) {
}
DefragmenterTask::~DefragmenterTask() {
delete visitor;
}
bool DefragmenterTask::run(void) {
TRACE_EVENT0("ep-engine/task", "DefragmenterTask");
if (engine->getConfiguration().isDefragmenterEnabled()) {
// Get our visitor. If we didn't finish the previous pass,
// then resume from where we last were, otherwise create a new visitor and
// reset the position.
if (visitor == NULL) {
visitor = new DefragmentVisitor(getAgeThreshold());
epstore_position = engine->getKVBucket()->startPosition();
}
// Print start status.
std::stringstream ss;
ss << to_string(getDescription()) << " for bucket '"
<< engine->getName() << "'";
if (epstore_position == engine->getKVBucket()->startPosition()) {
ss << " starting. ";
} else {
ss << " resuming from " << epstore_position << ", ";
ss << visitor->getHashtablePosition() << ".";
}
ss << " Using chunk_duration=" << getChunkDurationMS() << " ms."
<< " mem_used=" << stats.getTotalMemoryUsed()
<< ", mapped_bytes=" << getMappedBytes();
LOG(EXTENSION_LOG_INFO, "%s", ss.str().c_str());
// Disable thread-caching (as we are about to defragment, and hence don't
// want any of the new Blobs in tcache).
ALLOCATOR_HOOKS_API* alloc_hooks = engine->getServerApi()->alloc_hooks;
bool old_tcache = alloc_hooks->enable_thread_cache(false);
// Prepare the visitor.
hrtime_t start = gethrtime();
hrtime_t deadline = start + (getChunkDurationMS() * 1000 * 1000);
visitor->setDeadline(deadline);
visitor->clearStats();
// Do it - set off the visitor.
epstore_position = engine->getKVBucket()->pauseResumeVisit(
*visitor,
epstore_position);
hrtime_t end = gethrtime();
// Defrag complete. Restore thread caching.
alloc_hooks->enable_thread_cache(old_tcache);
// Update stats
stats.defragNumMoved.fetch_add(visitor->getDefragCount());
stats.defragNumVisited.fetch_add(visitor->getVisitedCount());
// Release any free memory we now have in the allocator back to the OS.
// TODO: Benchmark this - is it necessary? How much of a slowdown does it
// add? How much memory does it return?
alloc_hooks->release_free_memory();
// Check if the visitor completed a full pass.
bool completed = (epstore_position ==
engine->getKVBucket()->endPosition());
// Print status.
ss.str("");
ss << to_string(getDescription()) << " for bucket '"
<< engine->getName() << "'";
if (completed) {
ss << " finished.";
} else {
ss << " paused at position " << epstore_position << ".";
}
ss << " Took " << (end - start) / 1024 << " us."
<< " moved " << visitor->getDefragCount() << "/"
<< visitor->getVisitedCount() << " visited documents."
<< " mem_used=" << stats.getTotalMemoryUsed()
<< ", mapped_bytes=" << getMappedBytes()
<< ". Sleeping for " << getSleepTime() << " seconds.";
LOG(EXTENSION_LOG_INFO, "%s", ss.str().c_str());
// Delete visitor if it finished.
if (completed) {
delete visitor;
visitor = NULL;
}
}
snooze(getSleepTime());
if (engine->getEpStats().isShutdown) {
return false;
}
return true;
}
void DefragmenterTask::stop(void) {
if (uid) {
ExecutorPool::get()->cancel(uid);
}
}
cb::const_char_buffer DefragmenterTask::getDescription() {
return "Memory defragmenter";
}
size_t DefragmenterTask::getSleepTime() const {
return engine->getConfiguration().getDefragmenterInterval();
}
size_t DefragmenterTask::getAgeThreshold() const {
return engine->getConfiguration().getDefragmenterAgeThreshold();
}
size_t DefragmenterTask::getChunkDurationMS() const {
return engine->getConfiguration().getDefragmenterChunkDuration();
}
size_t DefragmenterTask::getMappedBytes() {
ALLOCATOR_HOOKS_API* alloc_hooks = engine->getServerApi()->alloc_hooks;
allocator_stats stats = {0};
stats.ext_stats_size = alloc_hooks->get_extra_stats_size();
stats.ext_stats = new allocator_ext_stat[stats.ext_stats_size];
alloc_hooks->get_allocator_stats(&stats);
size_t mapped_bytes = stats.heap_size - stats.free_mapped_size -
stats.free_unmapped_size;
delete[] stats.ext_stats;
return mapped_bytes;
}
<|endoftext|>
|
<commit_before>#include <vector>
#include <map>
#include <sys/queue.h>
#include <evhttp.h>
#include <mecab.h>
#include "Kana.h"
#include "Server.h"
#define PARSE_URI(request, params) { \
char const *uri = evhttp_request_uri(request); \
evhttp_parse_query(uri, ¶ms); \
}
#define PARAM_GET_STR(var, params, name, mendatory) { \
var = evhttp_find_header(¶ms_get, name); \
if (!var && mendatory) { \
http_send(request, "<err message=\"field '" name "' is mendatory\"/>\n"); \
return; \
} \
}
inline static void output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
evbuffer_add_printf(buffer, "<root>\n");
}
inline static void output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</root>\n");
}
inline static void kana_output_xml(const char *kana, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<kana><![CDATA[");
evbuffer_add_printf(buffer, "%s", kana);
evbuffer_add_printf(buffer, "]]></kana>\n");
}
inline static void parse_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<parse>");
}
inline static void parse_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</parse>\n");
}
inline static void furigana_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<furigana>");
}
inline static void furigana_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</furigana>\n");
}
inline static void token_output_xml(const char *token, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<token><![CDATA[");
evbuffer_add_printf(buffer, "%s",token);
evbuffer_add_printf(buffer, "]]></token>\n");
}
/**
*
*/
static void http_send(struct evhttp_request *request, const char *fmt, ...) {
struct evbuffer *buffer = evbuffer_new();
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
va_list ap;
va_start(ap, fmt);
evbuffer_add_vprintf(buffer, fmt, ap);
va_end(ap);
evhttp_send_reply(request, HTTP_OK, "", buffer);
evbuffer_free(buffer);
}
/**** uri: *
*
*/
static void http_callback_default(struct evhttp_request *request, void *data) {
evhttp_send_error(request, HTTP_NOTFOUND, "Service not found");
}
/**** uri: /kana?str=*
*
*/
static void http_kana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *kana = server->yomiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
std::string enforcedHiranagas = server->kana.katakana_to_hiragana(kana);
kana_output_xml(enforcedHiranagas.c_str(), buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**** uri: /parse?str=*
*
*/
static void http_parse_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
std::vector<std::string> tokens;
const MeCab::Node* node = server->tagger->parseToNode(str);
for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
tokens.push_back(std::string(node->surface, node->length));
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& oneToken : tokens) {
token_output_xml(oneToken.c_str(), buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**** uri: /furigana?str=*
*
*/
static void http_furigana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into furigana => token+kana
Server* server = (Server*) data;
std::vector<std::pair<std::string, std::string> > furiganas;
const MeCab::Node* node = server->tagger->parseToNode(str); for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
std::string token(node->surface, node->length);
std::string kana(server->yomiTagger->parse(token.c_str()));
furiganas.push_back(std::pair<std::string, std::string>(
token,
kana
));
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& oneFurigana : furiganas) {
furigana_output_xml_header(buffer);
token_output_xml(oneFurigana.first.c_str(), buffer);
std::string enforcedHiranagas = server->kana.katakana_to_hiragana(oneFurigana.second);
kana_output_xml(enforcedHiranagas.c_str(), buffer);
furigana_output_xml_footer(buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**
*
*/
Server::Server(std::string address, int port) {
struct event_base *base = event_init();
struct evhttp *server = evhttp_new(base);
int res = evhttp_bind_socket(server, address.c_str(), port);
wakatiTagger = MeCab::createTagger("-Owakati");
yomiTagger = MeCab::createTagger("-Oyomi");
tagger = MeCab::createTagger("");
if (res != 0) {
std::cout << "[ERROR] Could not start http server!" << std::endl;
return;
}
evhttp_set_gencb(server, http_callback_default, this);
evhttp_set_cb(server, "/kana", http_kana_callback, this);
evhttp_set_cb(server, "/parse", http_parse_callback, this);
evhttp_set_cb(server, "/furigana", http_furigana_callback, this);
event_base_dispatch(base);
}
/**
*
*
*/
Server::~Server() {
delete wakatiTagger;
delete yomiTagger;
delete tagger;
}
<commit_msg>Avoid producing useless furiganas.<commit_after>#include <algorithm>
#include <vector>
#include <map>
#include <sys/queue.h>
#include <evhttp.h>
#include <mecab.h>
#include "Kana.h"
#include "Server.h"
#define PARSE_URI(request, params) { \
char const *uri = evhttp_request_uri(request); \
evhttp_parse_query(uri, ¶ms); \
}
#define PARAM_GET_STR(var, params, name, mendatory) { \
var = evhttp_find_header(¶ms_get, name); \
if (!var && mendatory) { \
http_send(request, "<err message=\"field '" name "' is mendatory\"/>\n"); \
return; \
} \
}
inline static void output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
evbuffer_add_printf(buffer, "<root>\n");
}
inline static void output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</root>\n");
}
inline static void kana_output_xml(const char *kana, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<kana><![CDATA[");
evbuffer_add_printf(buffer, "%s", kana);
evbuffer_add_printf(buffer, "]]></kana>\n");
}
inline static void parse_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<parse>");
}
inline static void parse_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</parse>\n");
}
inline static void furigana_output_xml_header(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<furigana>");
}
inline static void furigana_output_xml_footer(struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "</furigana>\n");
}
inline static void token_output_xml(const char *token, struct evbuffer *buffer) {
evbuffer_add_printf(buffer, "<token><![CDATA[");
evbuffer_add_printf(buffer, "%s",token);
evbuffer_add_printf(buffer, "]]></token>\n");
}
/**
*
*/
static void http_send(struct evhttp_request *request, const char *fmt, ...) {
struct evbuffer *buffer = evbuffer_new();
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
va_list ap;
va_start(ap, fmt);
evbuffer_add_vprintf(buffer, fmt, ap);
va_end(ap);
evhttp_send_reply(request, HTTP_OK, "", buffer);
evbuffer_free(buffer);
}
/**** uri: *
*
*/
static void http_callback_default(struct evhttp_request *request, void *data) {
evhttp_send_error(request, HTTP_NOTFOUND, "Service not found");
}
/**** uri: /kana?str=*
*
*/
static void http_kana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
const char *kana = server->yomiTagger->parse(str);
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
std::string enforcedHiranagas = server->kana.katakana_to_hiragana(kana);
kana_output_xml(enforcedHiranagas.c_str(), buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**** uri: /parse?str=*
*
*/
static void http_parse_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into kana
Server* server = (Server*) data;
std::vector<std::string> tokens;
const MeCab::Node* node = server->tagger->parseToNode(str);
for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
tokens.push_back(std::string(node->surface, node->length));
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& oneToken : tokens) {
token_output_xml(oneToken.c_str(), buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
static inline void remove_spaces(std::string &str) {
str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))std::isspace), str.end());
}
static void clean_furigana(Kana *kana, std::string token, std::string &furigana) {
remove_spaces(furigana);
furigana = kana->katakana_to_hiragana(furigana);
if (kana->katakana_to_hiragana(token) == furigana) {
furigana = "";
}
}
/**** uri: /furigana?str=*
*
*/
static void http_furigana_callback(struct evhttp_request *request, void *data) {
//parse uri
struct evkeyvalq params_get;
PARSE_URI(request, params_get);
//get "str"
char const *str;
PARAM_GET_STR(str, ¶ms_get, "str", true);
//we parse into furigana => token+kana
Server* server = (Server*) data;
std::vector<std::pair<std::string, std::string> > furiganas;
const MeCab::Node* node = server->tagger->parseToNode(str); for (; node; node = node->next) {
if (node->stat != MECAB_BOS_NODE && node->stat != MECAB_EOS_NODE) {
std::string token(node->surface, node->length);
std::string kana(server->yomiTagger->parse(token.c_str()));
clean_furigana(&server->kana, token, kana);
furiganas.push_back(std::pair<std::string, std::string>(
token,
kana
));
}
}
//TODO add error handling
//prepare output
struct evbuffer *buffer = evbuffer_new();
output_xml_header(buffer);
parse_output_xml_header(buffer);
for (auto& oneFurigana : furiganas) {
furigana_output_xml_header(buffer);
token_output_xml(oneFurigana.first.c_str(), buffer);
kana_output_xml(oneFurigana.second.c_str(), buffer);
furigana_output_xml_footer(buffer);
}
parse_output_xml_footer(buffer);
output_xml_footer(buffer);
//send
evhttp_add_header(request->output_headers, "Content-Type", "TEXT/XML; charset=UTF8");
evhttp_send_reply(request, HTTP_OK, "", buffer);
}
/**
*
*/
Server::Server(std::string address, int port) {
struct event_base *base = event_init();
struct evhttp *server = evhttp_new(base);
int res = evhttp_bind_socket(server, address.c_str(), port);
wakatiTagger = MeCab::createTagger("-Owakati");
yomiTagger = MeCab::createTagger("-Oyomi");
tagger = MeCab::createTagger("");
if (res != 0) {
std::cout << "[ERROR] Could not start http server!" << std::endl;
return;
}
evhttp_set_gencb(server, http_callback_default, this);
evhttp_set_cb(server, "/kana", http_kana_callback, this);
evhttp_set_cb(server, "/parse", http_parse_callback, this);
evhttp_set_cb(server, "/furigana", http_furigana_callback, this);
event_base_dispatch(base);
}
/**
*
*
*/
Server::~Server() {
delete wakatiTagger;
delete yomiTagger;
delete tagger;
}
<|endoftext|>
|
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>
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 "Shader.h"
#include <fstream>
#include <Utility/Assert.h>
/* libgles-omap3-dev_4.03.00.02-r15.6 on BeagleBoard/Ångström linux 2011.3 doesn't have GLchar */
#ifdef MAGNUM_TARGET_GLES
typedef char GLchar;
#endif
namespace Magnum {
namespace {
std::string shaderName(const Shader::Type type) {
switch(type) {
case Shader::Type::Vertex: return "vertex";
#ifndef MAGNUM_TARGET_GLES
case Shader::Type::Geometry: return "geometry";
case Shader::Type::TessellationControl: return "tessellation control";
case Shader::Type::TessellationEvaluation: return "tessellation evaluation";
case Shader::Type::Compute: return "compute";
#endif
case Shader::Type::Fragment: return "fragment";
}
CORRADE_ASSERT_UNREACHABLE();
}
}
Shader::Shader(const Version version, const Type type): _type(type), _id(0) {
_id = glCreateShader(static_cast<GLenum>(_type));
switch(version) {
#ifndef MAGNUM_TARGET_GLES
case Version::GL210: addSource("#version 120\n"); return;
case Version::GL300: addSource("#version 130\n"); return;
case Version::GL310: addSource("#version 140\n"); return;
case Version::GL320: addSource("#version 150\n"); return;
case Version::GL330: addSource("#version 330\n"); return;
case Version::GL400: addSource("#version 400\n"); return;
case Version::GL410: addSource("#version 410\n"); return;
case Version::GL420: addSource("#version 420\n"); return;
case Version::GL430: addSource("#version 430\n"); return;
#else
case Version::GLES200: addSource("#version 100\n"); return;
case Version::GLES300: addSource("#version 300\n"); return;
#endif
case Version::None:
CORRADE_ASSERT(false, "Shader::Shader(): unsupported version" << version, );
}
CORRADE_ASSERT_UNREACHABLE();
}
Shader::Shader(Shader&& other): _type(other._type), _id(other._id), sources(std::move(other.sources)) {
other._id = 0;
}
Shader::~Shader() {
if(_id) glDeleteShader(_id);
}
Shader& Shader::operator=(Shader&& other) {
glDeleteShader(_id);
_type = other._type;
sources = std::move(other.sources);
_id = other._id;
other._id = 0;
return *this;
}
Shader& Shader::addSource(std::string source) {
if(!source.empty()) {
/* Fix line numbers, so line 41 of third added file is marked as 3(41).
Source 0 is the #version string added in constructor. */
sources.push_back("#line 1 " + std::to_string(sources.size()) + '\n');
sources.push_back(std::move(source));
}
return *this;
}
Shader& Shader::addFile(const std::string& filename) {
/* Open file */
std::ifstream file(filename.c_str());
CORRADE_ASSERT(file.good(), "Shader file " << '\'' + filename + '\'' << " cannot be opened.", *this);
/* Get size of shader and initialize buffer */
file.seekg(0, std::ios::end);
std::string source(file.tellg(), '\0');
/* Read data, close */
file.seekg(0, std::ios::beg);
file.read(&source[0], source.size());
file.close();
/* Move to sources */
addSource(std::move(source));
return *this;
}
bool Shader::compile() {
CORRADE_ASSERT(sources.size() > 1, "Shader::compile(): no files added", false);
/* Array of sources */
const GLchar** _sources = new const GLchar*[sources.size()];
for(std::size_t i = 0; i != sources.size(); ++i)
_sources[i] = static_cast<const GLchar*>(sources[i].c_str());
/* Create shader and set its source */
glShaderSource(_id, sources.size(), _sources, nullptr);
/* Compile shader */
glCompileShader(_id);
delete _sources;
/* Check compilation status */
GLint success, logLength;
glGetShaderiv(_id, GL_COMPILE_STATUS, &success);
glGetShaderiv(_id, GL_INFO_LOG_LENGTH, &logLength);
/* Error or warning message. The string is returned null-terminated, scrap
the \0 at the end afterwards */
std::string message(logLength, '\0');
if(!message.empty()) {
glGetShaderInfoLog(_id, message.size(), nullptr, &message[0]);
message.resize(logLength-1);
}
/* Show error log */
if(!success) {
Error out;
out.setFlag(Debug::NewLineAtTheEnd, false);
out.setFlag(Debug::SpaceAfterEachValue, false);
out << "Shader:" << shaderName(_type)
<< " shader failed to compile with the following message:\n"
<< message;
/* Or just message, if any */
} else if(!message.empty()) {
Error out;
out.setFlag(Debug::NewLineAtTheEnd, false);
out.setFlag(Debug::SpaceAfterEachValue, false);
out << "Shader:" << shaderName(_type)
<< " shader was successfully compiled with the following message:\n"
<< message;
}
return success;
}
}
<commit_msg>Missing space in shader compiler output message.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013 Vladimír Vondruš <mosra@centrum.cz>
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 "Shader.h"
#include <fstream>
#include <Utility/Assert.h>
/* libgles-omap3-dev_4.03.00.02-r15.6 on BeagleBoard/Ångström linux 2011.3 doesn't have GLchar */
#ifdef MAGNUM_TARGET_GLES
typedef char GLchar;
#endif
namespace Magnum {
namespace {
std::string shaderName(const Shader::Type type) {
switch(type) {
case Shader::Type::Vertex: return "vertex";
#ifndef MAGNUM_TARGET_GLES
case Shader::Type::Geometry: return "geometry";
case Shader::Type::TessellationControl: return "tessellation control";
case Shader::Type::TessellationEvaluation: return "tessellation evaluation";
case Shader::Type::Compute: return "compute";
#endif
case Shader::Type::Fragment: return "fragment";
}
CORRADE_ASSERT_UNREACHABLE();
}
}
Shader::Shader(const Version version, const Type type): _type(type), _id(0) {
_id = glCreateShader(static_cast<GLenum>(_type));
switch(version) {
#ifndef MAGNUM_TARGET_GLES
case Version::GL210: addSource("#version 120\n"); return;
case Version::GL300: addSource("#version 130\n"); return;
case Version::GL310: addSource("#version 140\n"); return;
case Version::GL320: addSource("#version 150\n"); return;
case Version::GL330: addSource("#version 330\n"); return;
case Version::GL400: addSource("#version 400\n"); return;
case Version::GL410: addSource("#version 410\n"); return;
case Version::GL420: addSource("#version 420\n"); return;
case Version::GL430: addSource("#version 430\n"); return;
#else
case Version::GLES200: addSource("#version 100\n"); return;
case Version::GLES300: addSource("#version 300\n"); return;
#endif
case Version::None:
CORRADE_ASSERT(false, "Shader::Shader(): unsupported version" << version, );
}
CORRADE_ASSERT_UNREACHABLE();
}
Shader::Shader(Shader&& other): _type(other._type), _id(other._id), sources(std::move(other.sources)) {
other._id = 0;
}
Shader::~Shader() {
if(_id) glDeleteShader(_id);
}
Shader& Shader::operator=(Shader&& other) {
glDeleteShader(_id);
_type = other._type;
sources = std::move(other.sources);
_id = other._id;
other._id = 0;
return *this;
}
Shader& Shader::addSource(std::string source) {
if(!source.empty()) {
/* Fix line numbers, so line 41 of third added file is marked as 3(41).
Source 0 is the #version string added in constructor. */
sources.push_back("#line 1 " + std::to_string(sources.size()) + '\n');
sources.push_back(std::move(source));
}
return *this;
}
Shader& Shader::addFile(const std::string& filename) {
/* Open file */
std::ifstream file(filename.c_str());
CORRADE_ASSERT(file.good(), "Shader file " << '\'' + filename + '\'' << " cannot be opened.", *this);
/* Get size of shader and initialize buffer */
file.seekg(0, std::ios::end);
std::string source(file.tellg(), '\0');
/* Read data, close */
file.seekg(0, std::ios::beg);
file.read(&source[0], source.size());
file.close();
/* Move to sources */
addSource(std::move(source));
return *this;
}
bool Shader::compile() {
CORRADE_ASSERT(sources.size() > 1, "Shader::compile(): no files added", false);
/* Array of sources */
const GLchar** _sources = new const GLchar*[sources.size()];
for(std::size_t i = 0; i != sources.size(); ++i)
_sources[i] = static_cast<const GLchar*>(sources[i].c_str());
/* Create shader and set its source */
glShaderSource(_id, sources.size(), _sources, nullptr);
/* Compile shader */
glCompileShader(_id);
delete _sources;
/* Check compilation status */
GLint success, logLength;
glGetShaderiv(_id, GL_COMPILE_STATUS, &success);
glGetShaderiv(_id, GL_INFO_LOG_LENGTH, &logLength);
/* Error or warning message. The string is returned null-terminated, scrap
the \0 at the end afterwards */
std::string message(logLength, '\0');
if(!message.empty()) {
glGetShaderInfoLog(_id, message.size(), nullptr, &message[0]);
message.resize(logLength-1);
}
/* Show error log */
if(!success) {
Error out;
out.setFlag(Debug::NewLineAtTheEnd, false);
out.setFlag(Debug::SpaceAfterEachValue, false);
out << "Shader: " << shaderName(_type)
<< " shader failed to compile with the following message:\n"
<< message;
/* Or just message, if any */
} else if(!message.empty()) {
Error out;
out.setFlag(Debug::NewLineAtTheEnd, false);
out.setFlag(Debug::SpaceAfterEachValue, false);
out << "Shader: " << shaderName(_type)
<< " shader was successfully compiled with the following message:\n"
<< message;
}
return success;
}
}
<|endoftext|>
|
<commit_before>#ifndef SYSTEM_H
#define SYSTEM_H
#include <memory>
#include <atomic>
#include <thread>
#include "Assembler.hpp"
#include "Bus.hpp"
#include "Processor.hpp"
#include "VGA.hpp"
#include "Memory.hpp"
#include "Coprocessor.hpp"
#include "Options.hpp"
class System {
public:
System(Options opt);
System(): System(Options()) {};
private:
std::shared_ptr<Bus> bus;
std::shared_ptr<Coprocessor> cp0;
std::shared_ptr<Processor> cpu;
std::shared_ptr<VGA> vga;
std::shared_ptr<Memory> memory;
std::thread *process;
std::atomic<bool> systemShouldQuit;
Options options;
};
#endif<commit_msg>Add system shouldQuit init to false<commit_after>#ifndef SYSTEM_H
#define SYSTEM_H
#include <memory>
#include <atomic>
#include <thread>
#include "Assembler.hpp"
#include "Bus.hpp"
#include "Processor.hpp"
#include "VGA.hpp"
#include "Memory.hpp"
#include "Coprocessor.hpp"
#include "Options.hpp"
class System {
public:
System(Options opt);
System(): System(Options()) {};
private:
std::shared_ptr<Bus> bus;
std::shared_ptr<Coprocessor> cp0;
std::shared_ptr<Processor> cpu;
std::shared_ptr<VGA> vga;
std::shared_ptr<Memory> memory;
std::thread *process;
std::atomic<bool> systemShouldQuit {false};
Options options;
};
#endif<|endoftext|>
|
<commit_before>#include "Vector.h"
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
template <typename T>
Vector<T>::Vector(int size) :
m_capacity(size),
m_size(size)
{
m_items = new T[m_capacity];
}
template <typename T>
Vector<T>::Vector(const Vector& rhs) :
m_capacity(rhs.m_capacity),
m_size(rhs.m_size)
{
m_items = new T[m_capacity];
for (auto i = 0; i < rhs.m_size; ++i)
{
m_items[i] = rhs.m_items[i];
}
}
template <typename T>
Vector<T>& Vector<T>::operator=(const Vector& rhs)
{
Vector<T> copy = rhs;
swap(*this, copy);
return *this;
}
template <typename T>
Vector<T>::Vector(Vector&& rhs) noexcept :
m_capacity(rhs.m_capacity),
m_size(rhs.m_size),
m_items(m_items)
{
rhs.m_size = 0;
rhs.m_capacity = 0;
rhs.m_items = nullptr;
}
template <typename T>
Vector<T>& Vector<T>::operator=(Vector&& rhs) noexcept
{
using std::swap;
swap(m_size, rhs.m_size);
swap(m_capacity, rhs.m_capacity);
swap(m_items, rhs.m_items);
return *this;
}
template <typename T>
Vector<T>::~Vector()
{
delete[] m_items;
}
/************************************************************************/
/* Public Members */
/************************************************************************/
template <typename T>
int Vector<T>::capacity() const
{
return m_capacity;
}
template <typename T>
int Vector<T>::size() const
{
return m_size;
}
template <typename T>
bool Vector<T>::empty() const
{
return size() == 0;
}
template <typename T>
T& Vector<T>::operator[](int idx)
{
return at(idx);
}
template <typename T>
T& Vector<T>::at(int idx)
{
if (idx < size())
{
return m_items[idx];
}
else
{
throw std::out_of_range("Index is out of range.");
}
}
template <typename T>
void Vector<T>::push_back(T x)
{
}
template <typename T>
void Vector<T>::pop_back()
{
}
template <typename T>
const T& Vector<T>::back() const
{
}
template <typename T>
const T& Vector<T>::front() const
{
}
template <typename T>
void Vector<T>::assign()
{
}
template <typename T>
void Vector<T>::clear()
{
}
template <typename T>
void Vector<T>::reserve(int capacity)
{
// TODO
}
<commit_msg>Fixed typo bugs.<commit_after>#include "Vector.h"
/************************************************************************/
/* Constructors and Destructor */
/************************************************************************/
template <typename T>
Vector<T>::Vector(int size) :
m_capacity(size),
m_size(size)
{
m_items = new T[m_capacity];
}
template <typename T>
Vector<T>::Vector(const Vector& rhs) :
m_capacity(rhs.m_capacity),
m_size(rhs.m_size)
{
m_items = new T[m_capacity];
for (auto i = 0; i < rhs.m_size; ++i)
{
m_items[i] = rhs.m_items[i];
}
}
template <typename T>
Vector<T>& Vector<T>::operator=(const Vector& rhs)
{
Vector<T> copy = rhs;
swap(*this, copy);
return *this;
}
template <typename T>
Vector<T>::Vector(Vector&& rhs) noexcept :
m_capacity(rhs.m_capacity),
m_size(rhs.m_size),
m_items(rhs.m_items)
{
rhs.m_size = 0;
rhs.m_capacity = 0;
rhs.m_items = nullptr;
}
template <typename T>
Vector<T>& Vector<T>::operator=(Vector&& rhs) noexcept
{
using std::swap;
swap(m_size, rhs.m_size);
swap(m_capacity, rhs.m_capacity);
swap(m_items, rhs.m_items);
return *this;
}
template <typename T>
Vector<T>::~Vector()
{
delete[] m_items;
}
/************************************************************************/
/* Public Members */
/************************************************************************/
template <typename T>
int Vector<T>::capacity() const
{
return m_capacity;
}
template <typename T>
int Vector<T>::size() const
{
return m_size;
}
template <typename T>
bool Vector<T>::empty() const
{
return size() == 0;
}
template <typename T>
T& Vector<T>::operator[](int idx)
{
return at(idx);
}
template <typename T>
T& Vector<T>::at(int idx)
{
if (idx < size())
{
return m_items[idx];
}
else
{
throw std::out_of_range("Index is out of range.");
}
}
template <typename T>
void Vector<T>::push_back(T x)
{
// TODO
}
template <typename T>
void Vector<T>::pop_back()
{
// TODO
}
template <typename T>
const T& Vector<T>::back() const
{
// TODO
}
template <typename T>
const T& Vector<T>::front() const
{
// TODO
}
template <typename T>
void Vector<T>::assign()
{
// TODO
}
template <typename T>
void Vector<T>::clear()
{
// TODO
}
template <typename T>
void Vector<T>::reserve(int capacity)
{
// TODO
}
<|endoftext|>
|
<commit_before>#include <QtGui>
#include "Window.h"
#include "ui_Window.h"
#include "ui_SettingsWidget.h"
#include "ui_LogWidget.h"
#include "ui_AboutWidget.h"
#include "Tracker.h"
#include "Updater.h"
extern Updater *gUpdater;
SettingsTab::SettingsTab( QWidget *parent )
: QWidget( parent ), mUI( new Ui::SettingsWidget )
{
mUI->setupUi( this );
connect( mUI->exportAccountButton, SIGNAL( clicked() ), this, SLOT( ExportAccount() ) );
connect( mUI->importAccountButton, SIGNAL( clicked() ), this, SLOT( ImportAccount() ) );
connect( mUI->checkForUpdatesNowButton, SIGNAL( clicked()), this, SLOT( CheckForUpdatesNow() ) );
connect( mUI->startAtLogin, SIGNAL( clicked(bool) ), this, SLOT( UpdateAutostart() ) );
connect( mUI->checkForUpdates, SIGNAL( clicked(bool) ), this, SLOT( UpdateUpdateCheck() ) );
connect( Tracker::Instance(), SIGNAL( AccountCreated() ), this, SLOT( LoadSettings() ) );
LoadSettings();
}
SettingsTab::~SettingsTab() {
delete mUI;
}
void SettingsTab::ExportAccount() {
QString fileName = QFileDialog::getSaveFileName( this,
tr( "Export Track-o-Bot Account Data" ), "",
tr( "Account Data (*.track-o-bot);; All Files (*)" ) );
if( fileName.isEmpty() ) {
return;
} else {
QFile file( fileName );
if( !file.open( QIODevice::WriteOnly ) ) {
QMessageBox::information( this, tr( "Unable to open file" ), file.errorString() );
return;
}
QDataStream out( &file );
out.setVersion( QDataStream::Qt_4_8 );
out << Tracker::Instance()->Username();
out << Tracker::Instance()->Password();
out << Tracker::Instance()->WebserviceURL();
LOG( "Account %s exported in %s", Tracker::Instance()->Username().toStdString().c_str(), fileName.toStdString().c_str() );
}
}
void SettingsTab::CheckForUpdatesNow() {
if( gUpdater ) {
gUpdater->CheckForUpdatesNow();
}
}
void SettingsTab::ImportAccount() {
QString fileName = QFileDialog::getOpenFileName( this,
tr( "Import Track-o-Bot Account Data" ), "",
tr( "Account Data (*.track-o-bot);; All Files (*)" ) );
if( fileName.isEmpty() ) {
return;
} else {
QFile file( fileName );
if( !file.open( QIODevice::ReadOnly ) ) {
QMessageBox::information( this, tr( "Unable to open file" ), file.errorString() );
return;
}
QDataStream in( &file );
QString username, password, webserviceUrl;
in.setVersion( QDataStream::Qt_4_8 );
in >> username;
in >> password;
in >> webserviceUrl;
if( !username.isEmpty() && !password.isEmpty() && !webserviceUrl.isEmpty() ) {
Tracker::Instance()->SetUsername( username );
Tracker::Instance()->SetPassword( password );
Tracker::Instance()->SetWebserviceURL( webserviceUrl );
LOG( "Account %s imported from %s", username.toStdString().c_str(), fileName.toStdString().c_str() );
LoadSettings();
} else {
LOG( "Import failed" );
}
}
}
void SettingsTab::UpdateAutostart() {
Autostart autostart;
autostart.SetActive( mUI->startAtLogin->isChecked() );
}
void SettingsTab::UpdateUpdateCheck() {
if( gUpdater ) {
gUpdater->SetAutomaticallyChecksForUpdates( mUI->checkForUpdates->isChecked() );
}
}
void SettingsTab::LoadSettings() {
Autostart autostart;
mUI->startAtLogin->setChecked( autostart.Active() );
if( gUpdater ) {
mUI->checkForUpdates->setChecked( gUpdater->AutomaticallyChecksForUpdates() );
}
bool accountSetUp = Tracker::Instance()->IsAccountSetUp();
if( accountSetUp ) {
mUI->account->setText( Tracker::Instance()->Username() );
}
mUI->importAccountButton->setEnabled( accountSetUp );
mUI->exportAccountButton->setEnabled( accountSetUp );
}
LogTab::LogTab( QWidget *parent )
: QWidget( parent ), mUI( new Ui::LogWidget )
{
mUI->setupUi( this );
QFont font( "Monospace" );
font.setStyleHint( QFont::TypeWriter );
mUI->logText->setFont( font );
connect( Logger::Instance(), SIGNAL( NewMessage(const string&) ), this, SLOT( AddLogEntry(const string&) ) );
}
LogTab::~LogTab() {
delete mUI;
}
void LogTab::AddLogEntry( const string& msg ) {
mUI->logText->moveCursor( QTextCursor::End );
mUI->logText->insertPlainText( msg.c_str() );
mUI->logText->moveCursor( QTextCursor::End );
}
AboutTab::AboutTab( QWidget *parent )
: QWidget( parent ), mUI( new Ui::AboutWidget )
{
mUI->setupUi( this );
QPixmap logoImage( ":/icons/logo.png" );
mUI->logo->setPixmap( logoImage.scaled( 64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation ) );
mUI->version->setText( VERSION );
}
AboutTab::~AboutTab() {
delete mUI;
}
Window::Window()
: mUI( new Ui::Window )
{
mUI->setupUi( this );
setWindowTitle( qApp->applicationName() );
CreateActions();
CreateTrayIcon();
connect( mTrayIcon, SIGNAL( activated(QSystemTrayIcon::ActivationReason) ), this, SLOT( TrayIconActivated(QSystemTrayIcon::ActivationReason) ) );
connect( &mCore, SIGNAL( HandleGameClientRestartRequired(bool) ), this, SLOT( HandleGameClientRestartRequired(bool) ) );
#ifdef Q_WS_WIN
// Notify user the first time that the app runs in the taskbar
QSettings settings;
if( !settings.contains("taskbarHint") ) {
settings.setValue( "taskbarHint", true );
mTrayIcon->showMessage( tr( "Heads up!" ), "Track-o-Bot runs in your taskbar! Right click the icon for more options." );
}
#endif
}
Window::~Window() {
delete mUI;
}
void Window::TrayIconActivated( QSystemTrayIcon::ActivationReason reason ) {
#ifdef Q_WS_WIN
if( reason == QSystemTrayIcon::ActivationReason::DoubleClick ) {
Tracker::Instance()->OpenProfile();
}
#endif
}
void Window::showEvent( QShowEvent *event ) {
QDialog::showEvent( event );
mUI->settingsTab->LoadSettings();
}
void Window::closeEvent( QCloseEvent *event ) {
if( mTrayIcon->isVisible() ) {
hide();
event->ignore();
}
}
// prevent esc from closing the app
void Window::reject() {
if( mTrayIcon->isVisible() ) {
hide();
} else {
QDialog::reject();
}
}
void Window::CreateActions() {
mOpenProfileAction = new QAction( tr( "Open Profile..." ), this );
connect( mOpenProfileAction, SIGNAL( triggered() ), this, SLOT( OpenProfile() ) );
mShowAction = new QAction( tr( "Settings..." ), this );
connect( mShowAction, SIGNAL( triggered() ), this, SLOT( RiseAndShine() ) );
mQuitAction = new QAction( tr("Quit"), this );
connect( mQuitAction, SIGNAL( triggered() ), qApp, SLOT( quit() ) );
mGameClientRestartRequiredAction = new QAction( tr("Please restart Hearthstone!" ), this );
mGameClientRestartRequiredAction->setEnabled( false );
}
void Window::CreateTrayIcon() {
mTrayIconMenu = new QMenu( this);
mTrayIconMenu->addAction( mOpenProfileAction );
mTrayIconMenu->addSeparator();
mTrayIconMenu->addAction( mShowAction );
mTrayIconMenu->addSeparator();
mTrayIconMenu->addAction( mQuitAction );
mTrayIcon = new QSystemTrayIcon( this );
mTrayIcon->setContextMenu (mTrayIconMenu );
#if defined Q_WS_MAC
QIcon icon = QIcon( ":/icons/mac.png" );
icon.addFile( ":/icons/mac_selected.png", QSize(), QIcon::Selected );
#elif defined Q_WS_WIN
QIcon icon = QIcon( ":/icons/win.ico" );
#endif
mTrayIcon->setIcon( icon );
mTrayIcon->show();
}
void Window::RiseAndShine() {
show();
raise();
}
void Window::OpenProfile() {
Tracker::Instance()->OpenProfile();
}
void Window::HandleGameClientRestartRequired( bool restartRequired ) {
static QAction *separator = NULL;
if( restartRequired ) {
separator = mTrayIconMenu->insertSeparator( mOpenProfileAction );
mTrayIconMenu->insertAction( separator, mGameClientRestartRequiredAction );
#ifdef Q_WS_WIN
mTrayIcon->showMessage( tr( "Action required" ), "Please restart Hearthstone!" );
#endif
} else {
mTrayIconMenu->removeAction( mGameClientRestartRequiredAction );
if( separator ) {
mTrayIconMenu->removeAction( separator );
}
}
}
<commit_msg>clarify<commit_after>#include <QtGui>
#include "Window.h"
#include "ui_Window.h"
#include "ui_SettingsWidget.h"
#include "ui_LogWidget.h"
#include "ui_AboutWidget.h"
#include "Tracker.h"
#include "Updater.h"
extern Updater *gUpdater;
SettingsTab::SettingsTab( QWidget *parent )
: QWidget( parent ), mUI( new Ui::SettingsWidget )
{
mUI->setupUi( this );
connect( mUI->exportAccountButton, SIGNAL( clicked() ), this, SLOT( ExportAccount() ) );
connect( mUI->importAccountButton, SIGNAL( clicked() ), this, SLOT( ImportAccount() ) );
connect( mUI->checkForUpdatesNowButton, SIGNAL( clicked()), this, SLOT( CheckForUpdatesNow() ) );
connect( mUI->startAtLogin, SIGNAL( clicked(bool) ), this, SLOT( UpdateAutostart() ) );
connect( mUI->checkForUpdates, SIGNAL( clicked(bool) ), this, SLOT( UpdateUpdateCheck() ) );
connect( Tracker::Instance(), SIGNAL( AccountCreated() ), this, SLOT( LoadSettings() ) );
LoadSettings();
}
SettingsTab::~SettingsTab() {
delete mUI;
}
void SettingsTab::ExportAccount() {
QString fileName = QFileDialog::getSaveFileName( this,
tr( "Export Track-o-Bot Account Data" ), "",
tr( "Account Data (*.track-o-bot);; All Files (*)" ) );
if( fileName.isEmpty() ) {
return;
} else {
QFile file( fileName );
if( !file.open( QIODevice::WriteOnly ) ) {
QMessageBox::information( this, tr( "Unable to open file" ), file.errorString() );
return;
}
QDataStream out( &file );
out.setVersion( QDataStream::Qt_4_8 );
out << Tracker::Instance()->Username();
out << Tracker::Instance()->Password();
out << Tracker::Instance()->WebserviceURL();
LOG( "Account %s exported in %s", Tracker::Instance()->Username().toStdString().c_str(), fileName.toStdString().c_str() );
}
}
void SettingsTab::CheckForUpdatesNow() {
if( gUpdater ) {
gUpdater->CheckForUpdatesNow();
}
}
void SettingsTab::ImportAccount() {
QString fileName = QFileDialog::getOpenFileName( this,
tr( "Import Track-o-Bot Account Data" ), "",
tr( "Account Data (*.track-o-bot);; All Files (*)" ) );
if( fileName.isEmpty() ) {
return;
} else {
QFile file( fileName );
if( !file.open( QIODevice::ReadOnly ) ) {
QMessageBox::information( this, tr( "Unable to open file" ), file.errorString() );
return;
}
QDataStream in( &file );
QString username, password, webserviceUrl;
in.setVersion( QDataStream::Qt_4_8 );
in >> username;
in >> password;
in >> webserviceUrl;
if( !username.isEmpty() && !password.isEmpty() && !webserviceUrl.isEmpty() ) {
Tracker::Instance()->SetUsername( username );
Tracker::Instance()->SetPassword( password );
Tracker::Instance()->SetWebserviceURL( webserviceUrl );
LOG( "Account %s imported from %s", username.toStdString().c_str(), fileName.toStdString().c_str() );
LoadSettings();
} else {
LOG( "Import failed" );
}
}
}
void SettingsTab::UpdateAutostart() {
Autostart autostart;
autostart.SetActive( mUI->startAtLogin->isChecked() );
}
void SettingsTab::UpdateUpdateCheck() {
if( gUpdater ) {
gUpdater->SetAutomaticallyChecksForUpdates( mUI->checkForUpdates->isChecked() );
}
}
void SettingsTab::LoadSettings() {
Autostart autostart;
mUI->startAtLogin->setChecked( autostart.Active() );
if( gUpdater ) {
mUI->checkForUpdates->setChecked( gUpdater->AutomaticallyChecksForUpdates() );
}
bool accountSetUp = Tracker::Instance()->IsAccountSetUp();
if( accountSetUp ) {
mUI->account->setText( Tracker::Instance()->Username() );
}
mUI->importAccountButton->setEnabled( accountSetUp );
mUI->exportAccountButton->setEnabled( accountSetUp );
}
LogTab::LogTab( QWidget *parent )
: QWidget( parent ), mUI( new Ui::LogWidget )
{
mUI->setupUi( this );
QFont font( "Monospace" );
font.setStyleHint( QFont::TypeWriter );
mUI->logText->setFont( font );
connect( Logger::Instance(), SIGNAL( NewMessage(const string&) ), this, SLOT( AddLogEntry(const string&) ) );
}
LogTab::~LogTab() {
delete mUI;
}
void LogTab::AddLogEntry( const string& msg ) {
mUI->logText->moveCursor( QTextCursor::End );
mUI->logText->insertPlainText( msg.c_str() );
mUI->logText->moveCursor( QTextCursor::End );
}
AboutTab::AboutTab( QWidget *parent )
: QWidget( parent ), mUI( new Ui::AboutWidget )
{
mUI->setupUi( this );
QPixmap logoImage( ":/icons/logo.png" );
mUI->logo->setPixmap( logoImage.scaled( 64, 64, Qt::KeepAspectRatio, Qt::SmoothTransformation ) );
mUI->version->setText( VERSION );
}
AboutTab::~AboutTab() {
delete mUI;
}
Window::Window()
: mUI( new Ui::Window )
{
mUI->setupUi( this );
setWindowTitle( qApp->applicationName() );
CreateActions();
CreateTrayIcon();
connect( mTrayIcon, SIGNAL( activated(QSystemTrayIcon::ActivationReason) ), this, SLOT( TrayIconActivated(QSystemTrayIcon::ActivationReason) ) );
connect( &mCore, SIGNAL( HandleGameClientRestartRequired(bool) ), this, SLOT( HandleGameClientRestartRequired(bool) ) );
#ifdef Q_WS_WIN
// Notify user the first time that the app runs in the taskbar
QSettings settings;
if( !settings.contains("taskbarHint") ) {
settings.setValue( "taskbarHint", true );
mTrayIcon->showMessage( tr( "Heads up!" ), "Track-o-Bot runs in your taskbar! Right click the icon for more options." );
}
#endif
}
Window::~Window() {
delete mUI;
}
void Window::TrayIconActivated( QSystemTrayIcon::ActivationReason reason ) {
#ifdef Q_WS_WIN
if( reason == QSystemTrayIcon::ActivationReason::DoubleClick ) {
Tracker::Instance()->OpenProfile();
}
#endif
}
void Window::showEvent( QShowEvent *event ) {
QDialog::showEvent( event );
mUI->settingsTab->LoadSettings();
}
void Window::closeEvent( QCloseEvent *event ) {
if( mTrayIcon->isVisible() ) {
hide();
event->ignore();
}
}
// prevent esc from closing the app
void Window::reject() {
if( mTrayIcon->isVisible() ) {
hide();
} else {
QDialog::reject();
}
}
void Window::CreateActions() {
mOpenProfileAction = new QAction( tr( "Open Profile..." ), this );
connect( mOpenProfileAction, SIGNAL( triggered() ), this, SLOT( OpenProfile() ) );
mShowAction = new QAction( tr( "Settings..." ), this );
connect( mShowAction, SIGNAL( triggered() ), this, SLOT( RiseAndShine() ) );
mQuitAction = new QAction( tr("Quit"), this );
connect( mQuitAction, SIGNAL( triggered() ), qApp, SLOT( quit() ) );
mGameClientRestartRequiredAction = new QAction( tr("Please restart Hearthstone!" ), this );
mGameClientRestartRequiredAction->setEnabled( false );
}
void Window::CreateTrayIcon() {
mTrayIconMenu = new QMenu( this);
mTrayIconMenu->addAction( mOpenProfileAction );
mTrayIconMenu->addSeparator();
mTrayIconMenu->addAction( mShowAction );
mTrayIconMenu->addSeparator();
mTrayIconMenu->addAction( mQuitAction );
mTrayIcon = new QSystemTrayIcon( this );
mTrayIcon->setContextMenu (mTrayIconMenu );
#if defined Q_WS_MAC
QIcon icon = QIcon( ":/icons/mac.png" );
icon.addFile( ":/icons/mac_selected.png", QSize(), QIcon::Selected );
#elif defined Q_WS_WIN
QIcon icon = QIcon( ":/icons/win.ico" );
#endif
mTrayIcon->setIcon( icon );
mTrayIcon->show();
}
void Window::RiseAndShine() {
show();
raise();
}
void Window::OpenProfile() {
Tracker::Instance()->OpenProfile();
}
void Window::HandleGameClientRestartRequired( bool restartRequired ) {
static QAction *separator = NULL;
if( restartRequired ) {
separator = mTrayIconMenu->insertSeparator( mOpenProfileAction );
mTrayIconMenu->insertAction( separator, mGameClientRestartRequiredAction );
#ifdef Q_WS_WIN
mTrayIcon->showMessage( tr( "Game log enabled" ), "Please restart Hearthstone for changes to take effect!" );
#endif
} else {
mTrayIconMenu->removeAction( mGameClientRestartRequiredAction );
if( separator ) {
mTrayIconMenu->removeAction( separator );
}
}
}
<|endoftext|>
|
<commit_before>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "adapter.hh"
#include "helper.hh"
#include <cstdio>
#include "log.hh"
struct timeval Adapter::current_time;
int Adapter::sleeptime = 0;
FACTORY_IMPLEMENTATION(Adapter)
Adapter::Adapter(Log& l, std::string params) :
log(l), actions(NULL), parent(NULL)
{
}
Adapter::~Adapter()
{
}
void Adapter::set_actions(std::vector<std::string>* _actions)
{
actions = _actions;
unames.resize(actions->size()+1);
}
bool Adapter::init()
{
return true;
}
Adapter* Adapter::up()
{
return parent;
}
Adapter* Adapter::down(unsigned int a)
{
printf("adapter_base %i\n",a);
return NULL;
}
std::vector<std::string>& Adapter::getAdapterNames()
{
return adapter_names;
}
std::vector<std::string>& Adapter::getAllActions()
{
return *actions;
}
std::string& Adapter::getActionName(int action) {
return (*actions)[action];
}
int Adapter::getActionNumber(std::string& name)
{
for(size_t i=0;i<actions->size();i++) {
if ((*actions)[i]==name) {
return i;
}
}
return -1;
}
int Adapter::getActionNumber(const char *name)
{
std::string _name(name);
return getActionNumber(_name);
}
void Adapter::setparent(Adapter* a)
{
parent = a;
}
const char* Adapter::getUActionName(int action)
{
switch (action) {
case -1: return "OUTPUTONLY";
case -2: return "DEADLOCK";
case -3: return "SILENCE";
default:
if (action<0) {
return "";
}
}
if (!unames[action]) {
unames[action]=escape_string((*actions)[action].c_str());
}
return unames[action];
}
<commit_msg>Adapter: Free encoded names on desturctor<commit_after>/*
* fMBT, free Model Based Testing tool
* Copyright (c) 2011, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU Lesser General Public License,
* version 2.1, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include "adapter.hh"
#include "helper.hh"
#include <cstdio>
#include "log.hh"
struct timeval Adapter::current_time;
int Adapter::sleeptime = 0;
FACTORY_IMPLEMENTATION(Adapter)
Adapter::Adapter(Log& l, std::string params) :
log(l), actions(NULL), parent(NULL)
{
}
Adapter::~Adapter()
{
for(unsigned i=0;i<unames.size();i++) {
if (unames[i]) {
escape_free(unames[i]);
unames[i]=NULL;
}
}
}
void Adapter::set_actions(std::vector<std::string>* _actions)
{
actions = _actions;
unames.resize(actions->size()+1);
}
bool Adapter::init()
{
return true;
}
Adapter* Adapter::up()
{
return parent;
}
Adapter* Adapter::down(unsigned int a)
{
printf("adapter_base %i\n",a);
return NULL;
}
std::vector<std::string>& Adapter::getAdapterNames()
{
return adapter_names;
}
std::vector<std::string>& Adapter::getAllActions()
{
return *actions;
}
std::string& Adapter::getActionName(int action) {
return (*actions)[action];
}
int Adapter::getActionNumber(std::string& name)
{
for(size_t i=0;i<actions->size();i++) {
if ((*actions)[i]==name) {
return i;
}
}
return -1;
}
int Adapter::getActionNumber(const char *name)
{
std::string _name(name);
return getActionNumber(_name);
}
void Adapter::setparent(Adapter* a)
{
parent = a;
}
const char* Adapter::getUActionName(int action)
{
switch (action) {
case -1: return "OUTPUTONLY";
case -2: return "DEADLOCK";
case -3: return "SILENCE";
default:
if (action<0) {
return "";
}
}
if (!unames[action]) {
unames[action]=escape_string((*actions)[action].c_str());
}
return unames[action];
}
<|endoftext|>
|
<commit_before>/*
============================================================================
Alfred: BAM alignment statistics
============================================================================
Copyright (C) 2017 Tobias Rausch
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
============================================================================
Contact: Tobias Rausch (rausch@embl.de)
============================================================================
*/
#define _SECURE_SCL 0
#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <fstream>
#define BOOST_DISABLE_ASSERTS
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <htslib/sam.h>
#include <htslib/faidx.h>
#ifdef PROFILE
#include "gperftools/profiler.h"
#endif
#include "bamstats.h"
#include "util.h"
#include "version.h"
using namespace bamstats;
struct Config {
bool hasRegionFile;
std::string sampleName;
std::string outprefix;
boost::filesystem::path genome;
boost::filesystem::path regionFile;
boost::filesystem::path bamFile;
};
int main(int argc, char **argv) {
#ifdef PROFILE
ProfilerStart("pbBamStats.prof");
#endif
Config c;
// Parameter
boost::program_options::options_description generic("Generic options");
generic.add_options()
("help,?", "show help message")
("reference,r", boost::program_options::value<boost::filesystem::path>(&c.genome), "reference fasta file (required)")
("bed,b", boost::program_options::value<boost::filesystem::path>(&c.regionFile), "bed file with regions to analyze (optional)")
("outprefix,o", boost::program_options::value<std::string>(&c.outprefix)->default_value("stats"), "output file prefix")
;
boost::program_options::options_description hidden("Hidden options");
hidden.add_options()
("input-file", boost::program_options::value<boost::filesystem::path>(&c.bamFile), "input bam file")
;
boost::program_options::positional_options_description pos_args;
pos_args.add("input-file", -1);
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(hidden);
boost::program_options::options_description visible_options;
visible_options.add(generic);
// Only help/license/warranty/version information
if ((argc < 2) || (std::string(argv[1]) == "help") || (std::string(argv[1]) == "--help") || (std::string(argv[1]) == "-h") || (std::string(argv[1]) == "-?")) {
printTitle("Alfred");
std::cout << "Usage: " << argv[0] << " [OPTIONS] -r <ref.fa> <aligned.bam>" << std::endl;
std::cout << visible_options << "\n";
return 0;
} else if ((std::string(argv[1]) == "version") || (std::string(argv[1]) == "--version") || (std::string(argv[1]) == "--version-only") || (std::string(argv[1]) == "-v")) {
std::cout << "Alfred version: v" << alfredVersionNumber << std::endl;
return 0;
} else if ((std::string(argv[1]) == "warranty") || (std::string(argv[1]) == "--warranty") || (std::string(argv[1]) == "-w")) {
displayWarranty();
return 0;
} else if ((std::string(argv[1]) == "license") || (std::string(argv[1]) == "--license") || (std::string(argv[1]) == "-l")) {
gplV3();
return 0;
}
// Parse command-line
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
boost::program_options::notify(vm);
// Check command line arguments
if ((!vm.count("input-file")) || (!vm.count("reference"))) {
printTitle("Alfred");
std::cout << "Usage: " << argv[0] << " [OPTIONS] -r <ref.fa> <aligned.bam>" << std::endl;
std::cout << visible_options << "\n";
return 1;
}
// Check genome
if (!(boost::filesystem::exists(c.genome) && boost::filesystem::is_regular_file(c.genome) && boost::filesystem::file_size(c.genome))) {
std::cerr << "Input reference file is missing: " << c.genome.string() << std::endl;
return 1;
} else {
faidx_t* fai = fai_load(c.genome.string().c_str());
if (fai == NULL) {
if (fai_build(c.genome.string().c_str()) == -1) {
std::cerr << "Fail to open genome fai index for " << c.genome.string() << std::endl;
return 1;
} else fai = fai_load(c.genome.string().c_str());
}
fai_destroy(fai);
}
// Check bam file
if (!(boost::filesystem::exists(c.bamFile) && boost::filesystem::is_regular_file(c.bamFile) && boost::filesystem::file_size(c.bamFile))) {
std::cerr << "Alignment file is missing: " << c.bamFile.string() << std::endl;
return 1;
}
samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
if (samfile == NULL) {
std::cerr << "Fail to open file " << c.bamFile.string() << std::endl;
return 1;
}
hts_idx_t* idx = sam_index_load(samfile, c.bamFile.string().c_str());
if (idx == NULL) {
std::cerr << "Fail to open index for " << c.bamFile.string() << std::endl;
return 1;
}
bam_hdr_t* hdr = sam_hdr_read(samfile);
faidx_t* fai = fai_load(c.genome.string().c_str());
for(int32_t refIndex=0; refIndex < hdr->n_targets; ++refIndex) {
std::string tname(hdr->target_name[refIndex]);
if (!faidx_has_seq(fai, tname.c_str())) {
std::cerr << "BAM file chromosome " << hdr->target_name[refIndex] << " is NOT present in your reference file " << c.genome.string() << std::endl;
return 1;
}
}
fai_destroy(fai);
std::string sampleName;
if (!getSMTag(std::string(hdr->text), c.bamFile.stem().string(), sampleName)) {
std::cerr << "Only one sample (@RG:SM) is allowed per input BAM file " << c.bamFile.string() << std::endl;
return 1;
} else c.sampleName = sampleName;
bam_hdr_destroy(hdr);
hts_idx_destroy(idx);
sam_close(samfile);
// Check region file
if (vm.count("bed")) {
if (!(boost::filesystem::exists(c.regionFile) && boost::filesystem::is_regular_file(c.regionFile) && boost::filesystem::file_size(c.regionFile))) {
std::cerr << "Input region file in bed format is missing: " << c.regionFile.string() << std::endl;
return 1;
}
std::string oldChr;
faidx_t* fai = fai_load(c.genome.string().c_str());
std::ifstream interval_file(c.regionFile.string().c_str(), std::ifstream::in);
if (interval_file.is_open()) {
while (interval_file.good()) {
std::string intervalLine;
getline(interval_file, intervalLine);
typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
boost::char_separator<char> sep(" \t,;");
Tokenizer tokens(intervalLine, sep);
Tokenizer::iterator tokIter = tokens.begin();
if (tokIter!=tokens.end()) {
std::string chrName=*tokIter++;
if (chrName.compare(oldChr) != 0) {
oldChr = chrName;
if (!faidx_has_seq(fai, chrName.c_str())) {
std::cerr << "Chromosome from bed file " << chrName << " is NOT present in your reference file " << c.genome.string() << std::endl;
return 1;
}
}
}
}
interval_file.close();
}
fai_destroy(fai);
c.hasRegionFile = true;
} else c.hasRegionFile = false;
// Show cmd
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] ";
for(int i=0; i<argc; ++i) { std::cout << argv[i] << ' '; }
std::cout << std::endl;
return bamStatsRun(c);
}
<commit_msg>build bam idx<commit_after>/*
============================================================================
Alfred: BAM alignment statistics
============================================================================
Copyright (C) 2017 Tobias Rausch
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
============================================================================
Contact: Tobias Rausch (rausch@embl.de)
============================================================================
*/
#define _SECURE_SCL 0
#define _SCL_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <fstream>
#define BOOST_DISABLE_ASSERTS
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/tokenizer.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <htslib/sam.h>
#include <htslib/faidx.h>
#ifdef PROFILE
#include "gperftools/profiler.h"
#endif
#include "bamstats.h"
#include "util.h"
#include "version.h"
using namespace bamstats;
struct Config {
bool hasRegionFile;
std::string sampleName;
std::string outprefix;
boost::filesystem::path genome;
boost::filesystem::path regionFile;
boost::filesystem::path bamFile;
};
int main(int argc, char **argv) {
#ifdef PROFILE
ProfilerStart("pbBamStats.prof");
#endif
Config c;
// Parameter
boost::program_options::options_description generic("Generic options");
generic.add_options()
("help,?", "show help message")
("reference,r", boost::program_options::value<boost::filesystem::path>(&c.genome), "reference fasta file (required)")
("bed,b", boost::program_options::value<boost::filesystem::path>(&c.regionFile), "bed file with regions to analyze (optional)")
("outprefix,o", boost::program_options::value<std::string>(&c.outprefix)->default_value("stats"), "output file prefix")
;
boost::program_options::options_description hidden("Hidden options");
hidden.add_options()
("input-file", boost::program_options::value<boost::filesystem::path>(&c.bamFile), "input bam file")
;
boost::program_options::positional_options_description pos_args;
pos_args.add("input-file", -1);
boost::program_options::options_description cmdline_options;
cmdline_options.add(generic).add(hidden);
boost::program_options::options_description visible_options;
visible_options.add(generic);
// Only help/license/warranty/version information
if ((argc < 2) || (std::string(argv[1]) == "help") || (std::string(argv[1]) == "--help") || (std::string(argv[1]) == "-h") || (std::string(argv[1]) == "-?")) {
printTitle("Alfred");
std::cout << "Usage: " << argv[0] << " [OPTIONS] -r <ref.fa> <aligned.bam>" << std::endl;
std::cout << visible_options << "\n";
return 0;
} else if ((std::string(argv[1]) == "version") || (std::string(argv[1]) == "--version") || (std::string(argv[1]) == "--version-only") || (std::string(argv[1]) == "-v")) {
std::cout << "Alfred version: v" << alfredVersionNumber << std::endl;
return 0;
} else if ((std::string(argv[1]) == "warranty") || (std::string(argv[1]) == "--warranty") || (std::string(argv[1]) == "-w")) {
displayWarranty();
return 0;
} else if ((std::string(argv[1]) == "license") || (std::string(argv[1]) == "--license") || (std::string(argv[1]) == "-l")) {
gplV3();
return 0;
}
// Parse command-line
boost::program_options::variables_map vm;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm);
boost::program_options::notify(vm);
// Check command line arguments
if ((!vm.count("input-file")) || (!vm.count("reference"))) {
printTitle("Alfred");
std::cout << "Usage: " << argv[0] << " [OPTIONS] -r <ref.fa> <aligned.bam>" << std::endl;
std::cout << visible_options << "\n";
return 1;
}
// Check genome
if (!(boost::filesystem::exists(c.genome) && boost::filesystem::is_regular_file(c.genome) && boost::filesystem::file_size(c.genome))) {
std::cerr << "Input reference file is missing: " << c.genome.string() << std::endl;
return 1;
} else {
faidx_t* fai = fai_load(c.genome.string().c_str());
if (fai == NULL) {
if (fai_build(c.genome.string().c_str()) == -1) {
std::cerr << "Fail to open genome fai index for " << c.genome.string() << std::endl;
return 1;
} else fai = fai_load(c.genome.string().c_str());
}
fai_destroy(fai);
}
// Check bam file
if (!(boost::filesystem::exists(c.bamFile) && boost::filesystem::is_regular_file(c.bamFile) && boost::filesystem::file_size(c.bamFile))) {
std::cerr << "Alignment file is missing: " << c.bamFile.string() << std::endl;
return 1;
}
samFile* samfile = sam_open(c.bamFile.string().c_str(), "r");
if (samfile == NULL) {
std::cerr << "Fail to open file " << c.bamFile.string() << std::endl;
return 1;
}
hts_idx_t* idx = sam_index_load(samfile, c.bamFile.string().c_str());
if (idx == NULL) {
if (bam_index_build(c.bamFile.string().c_str(), 0) != 0) {
std::cerr << "Fail to open index for " << c.bamFile.string() << std::endl;
return 1;
}
}
bam_hdr_t* hdr = sam_hdr_read(samfile);
faidx_t* fai = fai_load(c.genome.string().c_str());
for(int32_t refIndex=0; refIndex < hdr->n_targets; ++refIndex) {
std::string tname(hdr->target_name[refIndex]);
if (!faidx_has_seq(fai, tname.c_str())) {
std::cerr << "BAM file chromosome " << hdr->target_name[refIndex] << " is NOT present in your reference file " << c.genome.string() << std::endl;
return 1;
}
}
fai_destroy(fai);
std::string sampleName;
if (!getSMTag(std::string(hdr->text), c.bamFile.stem().string(), sampleName)) {
std::cerr << "Only one sample (@RG:SM) is allowed per input BAM file " << c.bamFile.string() << std::endl;
return 1;
} else c.sampleName = sampleName;
bam_hdr_destroy(hdr);
hts_idx_destroy(idx);
sam_close(samfile);
// Check region file
if (vm.count("bed")) {
if (!(boost::filesystem::exists(c.regionFile) && boost::filesystem::is_regular_file(c.regionFile) && boost::filesystem::file_size(c.regionFile))) {
std::cerr << "Input region file in bed format is missing: " << c.regionFile.string() << std::endl;
return 1;
}
std::string oldChr;
faidx_t* fai = fai_load(c.genome.string().c_str());
std::ifstream interval_file(c.regionFile.string().c_str(), std::ifstream::in);
if (interval_file.is_open()) {
while (interval_file.good()) {
std::string intervalLine;
getline(interval_file, intervalLine);
typedef boost::tokenizer< boost::char_separator<char> > Tokenizer;
boost::char_separator<char> sep(" \t,;");
Tokenizer tokens(intervalLine, sep);
Tokenizer::iterator tokIter = tokens.begin();
if (tokIter!=tokens.end()) {
std::string chrName=*tokIter++;
if (chrName.compare(oldChr) != 0) {
oldChr = chrName;
if (!faidx_has_seq(fai, chrName.c_str())) {
std::cerr << "Chromosome from bed file " << chrName << " is NOT present in your reference file " << c.genome.string() << std::endl;
return 1;
}
}
}
}
interval_file.close();
}
fai_destroy(fai);
c.hasRegionFile = true;
} else c.hasRegionFile = false;
// Show cmd
boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
std::cout << '[' << boost::posix_time::to_simple_string(now) << "] ";
for(int i=0; i<argc; ++i) { std::cout << argv[i] << ' '; }
std::cout << std::endl;
return bamStatsRun(c);
}
<|endoftext|>
|
<commit_before>/*
* base64.cxx
*
* Created on: 2015.4.24
* Author: Fifi Lyu
*/
#include "base64.h"
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
/*
计算密文对应明文的长度
Base64:http://zh.wikipedia.org/zh/Base64
将 3 byte 的数据,放入一个24bit的缓冲区中。
数据不足 3 byte 的话,缓冲区剩下的bit用0补足(Base64中的等号)。
然后,每次取出 6 个 bit。不断进行,直到全部输入数据转换完成。
//
补0说明:
如果要编码的字节数不能被3整除,最后会多出1个或2个字节, 那么可以使用下面的方法进行处理:
先使用0字节值在末尾补足,使其能够被3整除,然后再进行base64的编码。
在编码后的base64文本后加上一个或两个'='号,代表补足的字节数。也就是说,
如果最后剩余一个八位字节(1个byte)时,最后一个6位的base64字节块有四位是0值,最后附加上2个等号;
如果最后剩余两个八位字节(2个byte)时,最后一个6位的base字节块有两位是0值,最后附加1个等号
//
也就是
1 byte = 8 bit
1 base64 = 6 bit(可能含末尾补足的0)
//
明文长度 = (密文长度 * 6) / 8 - 等号数量
明文长度 = (密文长度 * 3) / 4 - 等号数量
*/
size_t plaintext_size(const string &cipher) {
const size_t size_ = cipher.size();
size_t padding_ = 0;
if (cipher[size_ - 1] == '=' && cipher[size_ - 2] == '=')
padding_ = 2;
else if (cipher[size_ - 1] == '=')
padding_ = 1;
else
padding_ = 0;
return (size_ * 3) / 4 - padding_;
}
string base64_encode(const string &plaintext) {
BIO *bio_ = NULL;
BIO *b64_ = NULL;
BUF_MEM *bufferPtr_ = NULL;
b64_ = BIO_new(BIO_f_base64());
bio_ = BIO_new(BIO_s_mem());
bio_ = BIO_push(b64_, bio_);
//Ignore newlines - write everything in one line
BIO_set_flags(bio_, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio_, plaintext.c_str(), plaintext.size());
BIO_flush(bio_);
BIO_get_mem_ptr(bio_, &bufferPtr_);
BIO_set_close(bio_, BIO_NOCLOSE);
BIO_free_all(bio_);
return string(bufferPtr_->data, bufferPtr_->length);
}
string base64_decode(const string &cipher) {
BIO *bio_ = NULL;
BIO *b64_ = NULL;
const int p_size_ = plaintext_size(cipher.c_str());
char buffer[p_size_ + 1];
bio_ = BIO_new_mem_buf((void*)cipher.c_str(), -1);
b64_ = BIO_new(BIO_f_base64());
bio_ = BIO_push(b64_, bio_);
//Do not use newlines to flush buffer
BIO_set_flags(bio_, BIO_FLAGS_BASE64_NO_NL);
const size_t read_size_ = BIO_read(bio_, buffer, p_size_);
BIO_free_all(bio_);
if (read_size_ == p_size_) {
buffer[p_size_] = '\0';
return string(buffer);
}
return "";
}
<commit_msg>[Bugfix] 内存泄漏<commit_after>/*
* base64.cxx
*
* Created on: 2015.4.24
* Author: Fifi Lyu
*/
#include "base64.h"
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/buffer.h>
/*
计算密文对应明文的长度
Base64:http://zh.wikipedia.org/zh/Base64
将 3 byte 的数据,放入一个24bit的缓冲区中。
数据不足 3 byte 的话,缓冲区剩下的bit用0补足(Base64中的等号)。
然后,每次取出 6 个 bit。不断进行,直到全部输入数据转换完成。
//
补0说明:
如果要编码的字节数不能被3整除,最后会多出1个或2个字节, 那么可以使用下面的方法进行处理:
先使用0字节值在末尾补足,使其能够被3整除,然后再进行base64的编码。
在编码后的base64文本后加上一个或两个'='号,代表补足的字节数。也就是说,
如果最后剩余一个八位字节(1个byte)时,最后一个6位的base64字节块有四位是0值,最后附加上2个等号;
如果最后剩余两个八位字节(2个byte)时,最后一个6位的base字节块有两位是0值,最后附加1个等号
//
也就是
1 byte = 8 bit
1 base64 = 6 bit(可能含末尾补足的0)
//
明文长度 = (密文长度 * 6) / 8 - 等号数量
明文长度 = (密文长度 * 3) / 4 - 等号数量
*/
size_t plaintext_size(const string &cipher) {
const size_t size_ = cipher.size();
size_t padding_ = 0;
if (cipher[size_ - 1] == '=' && cipher[size_ - 2] == '=')
padding_ = 2;
else if (cipher[size_ - 1] == '=')
padding_ = 1;
else
padding_ = 0;
return (size_ * 3) / 4 - padding_;
}
string base64_encode(const string &plaintext) {
BIO *bio_ = NULL;
BIO *b64_ = NULL;
BUF_MEM *bufferPtr_ = NULL;
b64_ = BIO_new(BIO_f_base64());
bio_ = BIO_new(BIO_s_mem());
bio_ = BIO_push(b64_, bio_);
//Ignore newlines - write everything in one line
BIO_set_flags(bio_, BIO_FLAGS_BASE64_NO_NL);
BIO_write(bio_, plaintext.c_str(), plaintext.size());
BIO_flush(bio_);
BIO_get_mem_ptr(bio_, &bufferPtr_);
const string tmp_(bufferPtr_->data, bufferPtr_->length);
BIO_free_all(bio_);
// 仅仅使用 BIO_free_all 无法释放所有内存
CRYPTO_cleanup_all_ex_data();
return tmp_;
}
string base64_decode(const string &cipher) {
BIO *bio_ = NULL;
BIO *b64_ = NULL;
const int p_size_ = plaintext_size(cipher.c_str());
char buffer[p_size_ + 1];
bio_ = BIO_new_mem_buf((void*)cipher.c_str(), -1);
b64_ = BIO_new(BIO_f_base64());
bio_ = BIO_push(b64_, bio_);
//Do not use newlines to flush buffer
BIO_set_flags(bio_, BIO_FLAGS_BASE64_NO_NL);
const size_t read_size_ = BIO_read(bio_, buffer, p_size_);
BIO_free_all(bio_);
// 仅仅使用 BIO_free_all 无法释放所有内存
CRYPTO_cleanup_all_ex_data();
if (read_size_ == p_size_) {
buffer[p_size_] = '\0';
return string(buffer);
}
return "";
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2013-2014 gtalent2@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WOMBAT_CORE_MODELIO_HPP
#define WOMBAT_CORE_MODELIO_HPP
#include <map>
#include <string>
#include <functional>
#include "models/enginemodels.hpp"
namespace wombat {
namespace core {
using std::map;
using std::string;
using std::function;
/**
* Prepends to the path to load models from.
* Unless another path is prepended to the path, this will be the first
* directory that files are looked for in.
* @param path the new path
*/
void prependPath(std::string h);
/**
* Adds to the path to load models from.
* This will be the last directory the files are looked for in.
* @param path the new path
*/
void appendPath(std::string path);
/**
* Returns the given path with the wombat_home path prepended to it.
* @param path the of the file to refer to within wombat_home
* @return the given path with the wombat_home path prepended to it.
*/
std::string path(std::string path);
/**
* Reads the file at the given path within the path into the given model.
* @param model the model to load the file into
* @prarm path the path within the path to read from
*/
int read(models::cyborgbear::Model &model, std::string path);
/**
* Manages Model IO, preventing redundancies in memory.
*/
template <class Model>
class Flyweight {
public:
class Value {
friend class Flyweight;
protected:
int dependents;
public:
virtual ~Value() {};
virtual string key() = 0;
};
class GenericValue: public Value {
friend class Flyweight;
protected:
string m_key;
public:
virtual ~GenericValue() {};
virtual string key() {
return m_key;
};
};
typedef function<Value*(Model&)> FlyweightNodeBuilder;
private:
map<string, Value*> m_cache;
FlyweightNodeBuilder m_build;
public:
Flyweight(FlyweightNodeBuilder build) {
m_build = build;
}
/**
* Takes a Model's path as the key.
* @param modelPath the path to the model
* @return the value associated with the given key
*/
Value* checkout(std::string modelPath) {
Value *v = m_cache[modelPath];
if (!v) {
Model key;
read(key, modelPath);
m_cache[modelPath] = v = m_build(key);
}
if (v) {
v->dependents++;
}
return v;
}
Value* checkout(Model &key) {
string keyStr = key.toJson();
Value *v = m_cache[keyStr];
if (!v) {
m_cache[keyStr] = v = m_build(key);
}
if (v) {
v->dependents++;
}
return v;
}
void checkin(string key) {
Value *v = m_cache[key];
checkin(v);
}
void checkin(Value *v) {
v->dependents--;
if (!v->dependents) {
m_cache.erase(v->key());
delete v;
}
}
};
}
}
#endif
<commit_msg>Added thread synchronization Flyweight.<commit_after>/*
* Copyright 2013-2014 gtalent2@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef WOMBAT_CORE_MODELIO_HPP
#define WOMBAT_CORE_MODELIO_HPP
#include <map>
#include <string>
#include <functional>
#include "threads.hpp"
#include "models/enginemodels.hpp"
namespace wombat {
namespace core {
using std::map;
using std::string;
using std::function;
/**
* Prepends to the path to load models from.
* Unless another path is prepended to the path, this will be the first
* directory that files are looked for in.
* @param path the new path
*/
void prependPath(std::string h);
/**
* Adds to the path to load models from.
* This will be the last directory the files are looked for in.
* @param path the new path
*/
void appendPath(std::string path);
/**
* Returns the given path with the wombat_home path prepended to it.
* @param path the of the file to refer to within wombat_home
* @return the given path with the wombat_home path prepended to it.
*/
std::string path(std::string path);
/**
* Reads the file at the given path within the path into the given model.
* @param model the model to load the file into
* @prarm path the path within the path to read from
*/
int read(models::cyborgbear::Model &model, std::string path);
/**
* Manages Model IO, preventing redundancies in memory.
*/
template <class Model>
class Flyweight {
public:
class Value {
friend class Flyweight;
protected:
int dependents;
public:
virtual ~Value() {};
virtual string key() = 0;
};
class GenericValue: public Value {
friend class Flyweight;
protected:
string m_key;
public:
virtual ~GenericValue() {};
virtual string key() {
return m_key;
};
};
typedef function<Value*(Model&)> FlyweightNodeBuilder;
private:
map<string, Value*> m_cache;
FlyweightNodeBuilder m_build;
core::Mutex m_lock;
public:
Flyweight(FlyweightNodeBuilder build) {
m_build = build;
}
/**
* Takes a Model's path as the key.
* @param modelPath the path to the model
* @return the value associated with the given key
*/
Value* checkout(std::string modelPath) {
m_lock.lock();
Value *v = m_cache[modelPath];
if (!v) {
Model key;
read(key, modelPath);
m_cache[modelPath] = v = m_build(key);
}
if (v) {
v->dependents++;
}
m_lock.unlock();
return v;
}
Value* checkout(Model &key) {
m_lock.lock();
string keyStr = key.toJson();
Value *v = m_cache[keyStr];
if (!v) {
m_cache[keyStr] = v = m_build(key);
}
if (v) {
v->dependents++;
}
m_lock.unlock();
return v;
}
void checkin(string key) {
m_lock.lock();
Value *v = m_cache[key];
checkin(v);
m_lock.unlock();
}
void checkin(Value *v) {
m_lock.lock();
v->dependents--;
if (!v->dependents) {
m_cache.erase(v->key());
delete v;
}
m_lock.unlock();
}
};
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Battle implementation
*/
#include "battle.h"
/* Initializes the Battle object with information about the given line.
* Calls a traceBack function to construct a response line.
*/
Battle::Battle(std::string given, Model* m, Nouncer* nouncer, Denouncer* denouncer) {
updateLineStats(given, nouncer);
std::cout<<"Number of syls on given line: "<<numSyls<<std::endl;
int numWords = getNumWords();
Rhymer* rhymer = new Rhymer(nouncer, denouncer);
Word* rhyme = new Word(rhymer->rhyme(lastGiven));
fire = traceBack_syls(rhyme, numWords, m, nouncer);
delete rhymer;
delete rhyme;
}
void Battle::spit() {
std::cout << fire << std::endl;
}
Battle::~Battle(){}
/* Builds a response to the given line with the same number of words.*/
std::string Battle::traceBack_words(Word* base, int numWords, Model* m) {
Word* _NULL_ = new Word("_NULL_");
std::string response = base->getVal();
//construct response by traversing the adjacency-list
for (int addedWords = 1; addedWords < numWords; addedWords++) {
// find word in model
WordList* leadersList = m->find(base);
Word* leader = leadersList->pickLeader();
// if _NULL_
if (leader->getVal() == "_NULL_") {
leadersList = m->find(_NULL_);
leader = leadersList->pickLeader();
}
// add it to the response
response = leader->getVal() + " " + response;
// set leader as new base
base = leader;
}
delete _NULL_;
return response;
}
/* Builds a response to the given line with the same number of syllables.*/
std::string Battle::traceBack_syls(Word* base, int numWords, Model* m, Nouncer* n) {
Word* _NULL_ = new Word("_NULL_");
std::string response = base->getVal();
//get number of syls in base word
int addedSyls = n->getSylCount(base->getVal());
//construct response by traversing the adjacency-list
while (addedSyls < numSyls) {
// find word in model
WordList* leadersList = m->find(base);
Word* leader = leadersList->pickLeader();
// if _NULL_
if (leader->getVal() == "_NULL_") {
leadersList = m->find(_NULL_);
leader = leadersList->pickLeader();
}
// add it to the response
response = leader->getVal() + " " + response;
// set leader as new base
base = leader;
//update addedSyls
addedSyls += n->getSylCount(base->getVal());
}
delete _NULL_;
std::cout<<"Number of syls in response: "<<addedSyls<<std::endl;
return response;
}
/* Parses the input line and updates member variables with
* relevant characteristics:
* - word count
* - syllable count
* - last word of line (for rhyming)
*/
void Battle::updateLineStats(std::string given, Nouncer* n) {
std::istringstream ss(given);
std::string last;
int words = 0;
int syls = 0;
while (ss >> last) {
words++;
syls += n->getSylCount(last);
}
lastGiven = last;
numWords = words;
numSyls = syls;
}
std::string Battle::getLast() {
return lastGiven;
}
int Battle::getNumWords() {
return numWords;
}
<commit_msg>update indentation<commit_after>/*
* Battle implementation
*/
#include "battle.h"
/* Initializes the Battle object with information about the given line.
* Calls a traceBack function to construct a response line.
*/
Battle::Battle(std::string given, Model* m, Nouncer* nouncer, Denouncer* denouncer) {
updateLineStats(given, nouncer);
std::cout<<"Number of syls on given line: "<<numSyls<<std::endl;
int numWords = getNumWords();
Rhymer* rhymer = new Rhymer(nouncer, denouncer);
Word* rhyme = new Word(rhymer->rhyme(lastGiven));
fire = traceBack_syls(rhyme, numWords, m, nouncer);
delete rhymer;
delete rhyme;
}
void Battle::spit() {
std::cout << fire << std::endl;
}
Battle::~Battle(){}
/* Builds a response to the given line with the same number of words.*/
std::string Battle::traceBack_words(Word* base, int numWords, Model* m) {
Word* _NULL_ = new Word("_NULL_");
std::string response = base->getVal();
//construct response by traversing the adjacency-list
for (int addedWords = 1; addedWords < numWords; addedWords++) {
// find word in model
WordList* leadersList = m->find(base);
Word* leader = leadersList->pickLeader();
// if _NULL_
if (leader->getVal() == "_NULL_") {
leadersList = m->find(_NULL_);
leader = leadersList->pickLeader();
}
// add it to the response
response = leader->getVal() + " " + response;
// set leader as new base
base = leader;
}
delete _NULL_;
return response;
}
/* Builds a response to the given line with the same number of syllables.*/
std::string Battle::traceBack_syls(Word* base, int numWords, Model* m, Nouncer* n) {
Word* _NULL_ = new Word("_NULL_");
std::string response = base->getVal();
//get number of syls in base word
int addedSyls = n->getSylCount(base->getVal());
//construct response by traversing the adjacency-list
while (addedSyls < numSyls) {
// find word in model
WordList* leadersList = m->find(base);
Word* leader = leadersList->pickLeader();
// if _NULL_
if (leader->getVal() == "_NULL_") {
leadersList = m->find(_NULL_);
leader = leadersList->pickLeader();
}
// add it to the response
response = leader->getVal() + " " + response;
// set leader as new base
base = leader;
//update addedSyls
addedSyls += n->getSylCount(base->getVal());
}
delete _NULL_;
std::cout<<"Number of syls in response: "<<addedSyls<<std::endl;
return response;
}
/*
* Parses the input line and updates member variables with
* relevant characteristics:
* - word count
* - syllable count
* - last word of line (for rhyming)
*/
void Battle::updateLineStats(std::string given, Nouncer* n) {
std::istringstream ss(given);
std::string last;
int words = 0;
int syls = 0;
while (ss >> last) {
words++;
syls += n->getSylCount(last);
}
lastGiven = last;
numWords = words;
numSyls = syls;
}
std::string Battle::getLast() {
return lastGiven;
}
int Battle::getNumWords() {
return numWords;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2010-2015, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "txn.h"
#include "engine.h"
#include "box.h" /* global recovery */
#include "tuple.h"
#include "recovery.h"
#include <fiber.h>
#include "request.h" /* for request_name */
#include "xrow.h"
double too_long_threshold;
static inline void
fiber_set_txn(struct fiber *fiber, struct txn *txn)
{
fiber_set_key(fiber, FIBER_KEY_TXN, (void *) txn);
}
static void
txn_add_redo(struct txn_stmt *stmt, struct request *request)
{
stmt->row = request->header;
if (request->header != NULL)
return;
/* Create a redo log row for Lua requests */
struct xrow_header *row =
region_alloc_object_xc(&fiber()->gc, struct xrow_header);
/* Initialize members explicitly to save time on memset() */
row->type = request->type;
row->server_id = 0;
row->lsn = 0;
row->sync = 0;
row->tm = 0;
row->bodycnt = request_encode(request, row->body);
stmt->row = row;
}
/** Initialize a new stmt object within txn. */
static struct txn_stmt *
txn_stmt_new(struct txn *txn)
{
assert(txn->in_stmt == false);
assert(stailq_empty(&txn->stmts) || !txn->is_autocommit);
struct txn_stmt *stmt =
region_alloc_object_xc(&fiber()->gc, struct txn_stmt);
/* Initialize members explicitly to save time on memset() */
stmt->space = NULL;
stmt->old_tuple = NULL;
stmt->new_tuple = NULL;
stmt->row = NULL;
stailq_add_tail_entry(&txn->stmts, stmt, next);
txn->in_stmt = true;
return stmt;
}
struct txn *
txn_begin(bool is_autocommit)
{
assert(! in_txn());
struct txn *txn = (struct txn *)
region_alloc_object_xc(&fiber()->gc, struct txn);
/* Initialize members explicitly to save time on memset() */
stailq_create(&txn->stmts);
txn->n_rows = 0;
txn->is_autocommit = is_autocommit;
txn->has_triggers = false;
txn->in_stmt = false;
txn->engine = NULL;
txn->engine_tx = NULL;
/* fiber_on_yield/fiber_on_stop initialized by engine on demand */
fiber_set_txn(fiber(), txn);
return txn;
}
void
txn_begin_in_engine(struct txn *txn, struct space *space)
{
Engine *engine = space->handler->engine;
if (txn->engine == NULL) {
assert(stailq_empty(&txn->stmts));
txn->engine = engine;
engine->begin(txn);
} else if (txn->engine != engine) {
/**
* Only one engine can be used in
* a multi-statement transaction currently.
*/
tnt_raise(ClientError, ER_CROSS_ENGINE_TRANSACTION);
}
}
struct txn *
txn_begin_stmt(struct space *space)
{
struct txn *txn = in_txn();
if (txn == NULL)
txn = txn_begin(true);
txn_begin_in_engine(txn, space);
struct txn_stmt *stmt = txn_stmt_new(txn);
stmt->space = space;
return txn;
}
/**
* End a statement. In autocommit mode, end
* the current transaction as well.
*/
void
txn_commit_stmt(struct txn *txn, struct request *request)
{
assert(txn->in_stmt);
/*
* Run on_replace triggers. For now, disallow mutation
* of tuples in the trigger.
*/
struct txn_stmt *stmt = stailq_last_entry(&txn->stmts,
struct txn_stmt, next);
/* Create WAL record for the write requests in non-temporary spaces */
if (!space_is_temporary(stmt->space)) {
txn_add_redo(stmt, request);
++txn->n_rows;
}
/*
* If there are triggers, and they are not disabled, and
* the statement found any rows, run triggers.
* XXX:
* - sophia doesn't set old/new tuple, so triggers don't
* work for it
* - perhaps we should run triggers even for deletes which
* doesn't find any rows
*/
if (!rlist_empty(&stmt->space->on_replace) &&
stmt->space->run_triggers && (stmt->old_tuple || stmt->new_tuple)) {
trigger_run(&stmt->space->on_replace, txn);
}
txn->in_stmt = false;
if (txn->is_autocommit)
txn_commit(txn);
}
static int64_t
txn_write_to_wal(struct txn *txn)
{
assert(txn->n_rows > 0);
struct wal_request *req;
req = (struct wal_request *)region_aligned_alloc_xc(
&fiber()->gc,
sizeof(struct wal_request) +
sizeof(req->rows[0]) * txn->n_rows,
alignof(struct wal_request));
/*
* Note: offsetof(struct wal_request, rows) is more appropriate,
* but compiler warns.
*/
req->n_rows = 0;
struct txn_stmt *stmt;
stailq_foreach_entry(stmt, &txn->stmts, next) {
if (stmt->row == NULL)
continue; /* A read (e.g. select) request */
/*
* Bump current LSN even if wal_mode = NONE, so that
* snapshots still works with WAL turned off.
*/
recovery_fill_lsn(recovery, stmt->row);
stmt->row->tm = ev_now(loop());
req->rows[req->n_rows++] = stmt->row;
}
assert(req->n_rows == txn->n_rows);
ev_tstamp start = ev_now(loop()), stop;
int64_t res;
if (wal == NULL) {
/** wal_mode = NONE or initial recovery. */
res = vclock_sum(&recovery->vclock);
} else {
res = wal_write(wal, req);
}
stop = ev_now(loop());
if (stop - start > too_long_threshold)
say_warn("too long WAL write: %.3f sec", stop - start);
if (res < 0)
tnt_raise(LoggedError, ER_WAL_IO);
/*
* Use vclock_sum() from WAL writer as transaction signature.
*/
return res;
}
void
txn_commit(struct txn *txn)
{
assert(txn == in_txn());
assert(stailq_empty(&txn->stmts) || txn->engine);
/* Do transaction conflict resolving */
if (txn->engine) {
int64_t signature = -1;
txn->engine->prepare(txn);
if (txn->n_rows > 0)
signature = txn_write_to_wal(txn);
/*
* The transaction is in the binary log. No action below
* may throw. In case an error has happened, there is
* no other option but terminate.
*/
if (txn->has_triggers)
trigger_run(&txn->on_commit, txn);
txn->engine->commit(txn, signature);
}
TRASH(txn);
/** Free volatile txn memory. */
fiber_gc();
fiber_set_txn(fiber(), NULL);
}
/**
* Void all effects of the statement, but
* keep it in the list - to maintain
* limit on the number of statements in a
* transaction.
*/
void
txn_rollback_stmt()
{
struct txn *txn = in_txn();
if (txn == NULL)
return;
if (txn->is_autocommit)
return txn_rollback();
if (txn->in_stmt == false)
return;
struct txn_stmt *stmt = stailq_last_entry(&txn->stmts, struct txn_stmt,
next);
txn->engine->rollbackStatement(stmt);
if (stmt->row != NULL) {
stmt->row = NULL;
--txn->n_rows;
assert(txn->n_rows >= 0);
}
txn->in_stmt = false;
}
void
txn_rollback()
{
struct txn *txn = in_txn();
if (txn == NULL)
return;
if (txn->has_triggers)
trigger_run(&txn->on_rollback, txn); /* must not throw. */
if (txn->engine)
txn->engine->rollback(txn);
TRASH(txn);
/** Free volatile txn memory. */
fiber_gc();
fiber_set_txn(fiber(), NULL);
/*
* Move fiber to end of event loop to avoid execution of
* any new requests before all pending rollbacks will processed
*/
fiber_reschedule();
}
void
txn_check_autocommit(struct txn *txn, const char *where)
{
if (txn->is_autocommit == false) {
tnt_raise(ClientError, ER_UNSUPPORTED,
where, "multi-statement transactions");
}
}
extern "C" {
bool
box_txn()
{
return in_txn() != NULL;
}
int
box_txn_begin()
{
try {
if (in_txn())
tnt_raise(ClientError, ER_ACTIVE_TRANSACTION);
(void) txn_begin(false);
} catch (Exception *e) {
return -1; /* pass exception through FFI */
}
return 0;
}
int
box_txn_commit()
{
struct txn *txn = in_txn();
/**
* COMMIT is like BEGIN or ROLLBACK
* a "transaction-initiating statement".
* Do nothing if transaction is not started,
* it's the same as BEGIN + COMMIT.
*/
if (! txn)
return 0;
try {
txn_commit(txn);
} catch (Exception *e) {
txn_rollback();
return -1;
}
return 0;
}
void
box_txn_rollback()
{
txn_rollback(); /* doesn't throw */
}
void *
box_txn_alloc(size_t size)
{
union natural_align {
void *p;
double lf;
long l;
};
return region_aligned_alloc(&fiber()->gc, size,
alignof(union natural_align));
}
} /* extern "C" */
<commit_msg>txn: remove unnecessary casts<commit_after>/*
* Copyright 2010-2015, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "txn.h"
#include "engine.h"
#include "box.h" /* global recovery */
#include "tuple.h"
#include "recovery.h"
#include <fiber.h>
#include "request.h" /* for request_name */
#include "xrow.h"
double too_long_threshold;
static inline void
fiber_set_txn(struct fiber *fiber, struct txn *txn)
{
fiber_set_key(fiber, FIBER_KEY_TXN, (void *) txn);
}
static void
txn_add_redo(struct txn_stmt *stmt, struct request *request)
{
stmt->row = request->header;
if (request->header != NULL)
return;
/* Create a redo log row for Lua requests */
struct xrow_header *row;
row = region_alloc_object_xc(&fiber()->gc, struct xrow_header);
/* Initialize members explicitly to save time on memset() */
row->type = request->type;
row->server_id = 0;
row->lsn = 0;
row->sync = 0;
row->tm = 0;
row->bodycnt = request_encode(request, row->body);
stmt->row = row;
}
/** Initialize a new stmt object within txn. */
static struct txn_stmt *
txn_stmt_new(struct txn *txn)
{
assert(txn->in_stmt == false);
assert(stailq_empty(&txn->stmts) || !txn->is_autocommit);
struct txn_stmt *stmt;
stmt = region_alloc_object_xc(&fiber()->gc, struct txn_stmt);
/* Initialize members explicitly to save time on memset() */
stmt->space = NULL;
stmt->old_tuple = NULL;
stmt->new_tuple = NULL;
stmt->row = NULL;
stailq_add_tail_entry(&txn->stmts, stmt, next);
txn->in_stmt = true;
return stmt;
}
struct txn *
txn_begin(bool is_autocommit)
{
assert(! in_txn());
struct txn *txn = region_alloc_object_xc(&fiber()->gc, struct txn);
/* Initialize members explicitly to save time on memset() */
stailq_create(&txn->stmts);
txn->n_rows = 0;
txn->is_autocommit = is_autocommit;
txn->has_triggers = false;
txn->in_stmt = false;
txn->engine = NULL;
txn->engine_tx = NULL;
/* fiber_on_yield/fiber_on_stop initialized by engine on demand */
fiber_set_txn(fiber(), txn);
return txn;
}
void
txn_begin_in_engine(struct txn *txn, struct space *space)
{
Engine *engine = space->handler->engine;
if (txn->engine == NULL) {
assert(stailq_empty(&txn->stmts));
txn->engine = engine;
engine->begin(txn);
} else if (txn->engine != engine) {
/**
* Only one engine can be used in
* a multi-statement transaction currently.
*/
tnt_raise(ClientError, ER_CROSS_ENGINE_TRANSACTION);
}
}
struct txn *
txn_begin_stmt(struct space *space)
{
struct txn *txn = in_txn();
if (txn == NULL)
txn = txn_begin(true);
txn_begin_in_engine(txn, space);
struct txn_stmt *stmt = txn_stmt_new(txn);
stmt->space = space;
return txn;
}
/**
* End a statement. In autocommit mode, end
* the current transaction as well.
*/
void
txn_commit_stmt(struct txn *txn, struct request *request)
{
assert(txn->in_stmt);
/*
* Run on_replace triggers. For now, disallow mutation
* of tuples in the trigger.
*/
struct txn_stmt *stmt = stailq_last_entry(&txn->stmts,
struct txn_stmt, next);
/* Create WAL record for the write requests in non-temporary spaces */
if (!space_is_temporary(stmt->space)) {
txn_add_redo(stmt, request);
++txn->n_rows;
}
/*
* If there are triggers, and they are not disabled, and
* the statement found any rows, run triggers.
* XXX:
* - sophia doesn't set old/new tuple, so triggers don't
* work for it
* - perhaps we should run triggers even for deletes which
* doesn't find any rows
*/
if (!rlist_empty(&stmt->space->on_replace) &&
stmt->space->run_triggers && (stmt->old_tuple || stmt->new_tuple)) {
trigger_run(&stmt->space->on_replace, txn);
}
txn->in_stmt = false;
if (txn->is_autocommit)
txn_commit(txn);
}
static int64_t
txn_write_to_wal(struct txn *txn)
{
assert(txn->n_rows > 0);
struct wal_request *req;
req = (struct wal_request *)region_aligned_alloc_xc(
&fiber()->gc,
sizeof(struct wal_request) +
sizeof(req->rows[0]) * txn->n_rows,
alignof(struct wal_request));
/*
* Note: offsetof(struct wal_request, rows) is more appropriate,
* but compiler warns.
*/
req->n_rows = 0;
struct txn_stmt *stmt;
stailq_foreach_entry(stmt, &txn->stmts, next) {
if (stmt->row == NULL)
continue; /* A read (e.g. select) request */
/*
* Bump current LSN even if wal_mode = NONE, so that
* snapshots still works with WAL turned off.
*/
recovery_fill_lsn(recovery, stmt->row);
stmt->row->tm = ev_now(loop());
req->rows[req->n_rows++] = stmt->row;
}
assert(req->n_rows == txn->n_rows);
ev_tstamp start = ev_now(loop()), stop;
int64_t res;
if (wal == NULL) {
/** wal_mode = NONE or initial recovery. */
res = vclock_sum(&recovery->vclock);
} else {
res = wal_write(wal, req);
}
stop = ev_now(loop());
if (stop - start > too_long_threshold)
say_warn("too long WAL write: %.3f sec", stop - start);
if (res < 0)
tnt_raise(LoggedError, ER_WAL_IO);
/*
* Use vclock_sum() from WAL writer as transaction signature.
*/
return res;
}
void
txn_commit(struct txn *txn)
{
assert(txn == in_txn());
assert(stailq_empty(&txn->stmts) || txn->engine);
/* Do transaction conflict resolving */
if (txn->engine) {
int64_t signature = -1;
txn->engine->prepare(txn);
if (txn->n_rows > 0)
signature = txn_write_to_wal(txn);
/*
* The transaction is in the binary log. No action below
* may throw. In case an error has happened, there is
* no other option but terminate.
*/
if (txn->has_triggers)
trigger_run(&txn->on_commit, txn);
txn->engine->commit(txn, signature);
}
TRASH(txn);
/** Free volatile txn memory. */
fiber_gc();
fiber_set_txn(fiber(), NULL);
}
/**
* Void all effects of the statement, but
* keep it in the list - to maintain
* limit on the number of statements in a
* transaction.
*/
void
txn_rollback_stmt()
{
struct txn *txn = in_txn();
if (txn == NULL)
return;
if (txn->is_autocommit)
return txn_rollback();
if (txn->in_stmt == false)
return;
struct txn_stmt *stmt = stailq_last_entry(&txn->stmts, struct txn_stmt,
next);
txn->engine->rollbackStatement(stmt);
if (stmt->row != NULL) {
stmt->row = NULL;
--txn->n_rows;
assert(txn->n_rows >= 0);
}
txn->in_stmt = false;
}
void
txn_rollback()
{
struct txn *txn = in_txn();
if (txn == NULL)
return;
if (txn->has_triggers)
trigger_run(&txn->on_rollback, txn); /* must not throw. */
if (txn->engine)
txn->engine->rollback(txn);
TRASH(txn);
/** Free volatile txn memory. */
fiber_gc();
fiber_set_txn(fiber(), NULL);
/*
* Move fiber to end of event loop to avoid execution of
* any new requests before all pending rollbacks will processed
*/
fiber_reschedule();
}
void
txn_check_autocommit(struct txn *txn, const char *where)
{
if (txn->is_autocommit == false) {
tnt_raise(ClientError, ER_UNSUPPORTED,
where, "multi-statement transactions");
}
}
extern "C" {
bool
box_txn()
{
return in_txn() != NULL;
}
int
box_txn_begin()
{
try {
if (in_txn())
tnt_raise(ClientError, ER_ACTIVE_TRANSACTION);
(void) txn_begin(false);
} catch (Exception *e) {
return -1; /* pass exception through FFI */
}
return 0;
}
int
box_txn_commit()
{
struct txn *txn = in_txn();
/**
* COMMIT is like BEGIN or ROLLBACK
* a "transaction-initiating statement".
* Do nothing if transaction is not started,
* it's the same as BEGIN + COMMIT.
*/
if (! txn)
return 0;
try {
txn_commit(txn);
} catch (Exception *e) {
txn_rollback();
return -1;
}
return 0;
}
void
box_txn_rollback()
{
txn_rollback(); /* doesn't throw */
}
void *
box_txn_alloc(size_t size)
{
union natural_align {
void *p;
double lf;
long l;
};
return region_aligned_alloc(&fiber()->gc, size,
alignof(union natural_align));
}
} /* extern "C" */
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.