text
stringlengths 54
60.6k
|
|---|
<commit_before><commit_msg>Cleanup temporary files created by the extension updater unit test.<commit_after><|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCamera.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkActor.h"
#include "vtkCellArray.h"
#include "vtkPointData.h"
#include "vtkPolyDataMapper.h"
#include "vtkPLYReader.h"
#include "vtkNew.h"
#include "vtkProperty.h"
#include "vtkLightKit.h"
#include "vtkPolyDataNormals.h"
#include "vtkTimerLog.h"
#include "vtkRegressionTestImage.h"
#include "vtkTestUtilities.h"
#include "vtkRenderWindowInteractor.h"
//----------------------------------------------------------------------------
int TestVBOPLYMapper(int argc, char *argv[])
{
vtkNew<vtkActor> actor;
vtkNew<vtkRenderer> renderer;
vtkNew<vtkPolyDataMapper> mapper;
renderer->SetBackground(0.0, 0.0, 0.0);
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->SetSize(900, 900);
renderWindow->AddRenderer(renderer.Get());
renderer->AddActor(actor.Get());
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renderWindow.Get());
vtkNew<vtkLightKit> lightKit;
lightKit->AddLightsToRenderer(renderer.Get());
const char* fileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/dragon.ply");
vtkNew<vtkPLYReader> reader;
reader->SetFileName(fileName);
reader->Update();
// vtkNew<vtkPolyDataNormals> norms;
// norms->SetInputConnection(reader->GetOutputPort());
// norms->Update();
mapper->SetInputConnection(reader->GetOutputPort());
//mapper->SetInputConnection(norms->GetOutputPort());
actor->SetMapper(mapper.Get());
actor->GetProperty()->SetAmbientColor(0.2, 0.2, 1.0);
actor->GetProperty()->SetDiffuseColor(1.0, 0.65, 0.7);
actor->GetProperty()->SetSpecularColor(1.0, 1.0, 1.0);
actor->GetProperty()->SetSpecular(0.5);
actor->GetProperty()->SetDiffuse(0.7);
actor->GetProperty()->SetAmbient(0.5);
actor->GetProperty()->SetSpecularPower(20.0);
actor->GetProperty()->SetOpacity(1.0);
//actor->GetProperty()->SetRepresentationToWireframe();
renderWindow->SetMultiSamples(0);
vtkNew<vtkTimerLog> timer;
timer->StartTimer();
renderWindow->Render();
timer->StopTimer();
double firstRender = timer->GetElapsedTime();
cerr << "first render time: " << firstRender << endl;
timer->StartTimer();
int numRenders = 8;
for (int i = 0; i < numRenders; ++i)
{
renderer->GetActiveCamera()->Azimuth(10);
renderer->GetActiveCamera()->Elevation(10);
renderWindow->Render();
}
timer->StopTimer();
double elapsed = timer->GetElapsedTime();
cerr << "interactive render time: " << elapsed / numRenders << endl;
unsigned int numTris = reader->GetOutput()->GetPolys()->GetNumberOfCells();
cerr << "number of triangles: " << numTris << endl;
cerr << "triangles per second: " << numTris*(numRenders/elapsed) << endl;
renderer->GetActiveCamera()->SetPosition(0,0,1);
renderer->GetActiveCamera()->SetFocalPoint(0,0,0);
renderer->GetActiveCamera()->SetViewUp(0,1,0);
renderer->ResetCamera();
renderWindow->SetSize(300, 300);
// render a few times to get the resize to flush out
renderWindow->Render();
renderWindow->Render();
renderWindow->Render();
int retVal = vtkRegressionTestImage( renderWindow.Get() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<commit_msg>Update test to not resize<commit_after>/*=========================================================================
Program: Visualization Toolkit
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkCamera.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkActor.h"
#include "vtkCellArray.h"
#include "vtkPointData.h"
#include "vtkPolyDataMapper.h"
#include "vtkPLYReader.h"
#include "vtkNew.h"
#include "vtkProperty.h"
#include "vtkLightKit.h"
#include "vtkPolyDataNormals.h"
#include "vtkTimerLog.h"
#include "vtkRegressionTestImage.h"
#include "vtkTestUtilities.h"
#include "vtkRenderWindowInteractor.h"
//----------------------------------------------------------------------------
int TestVBOPLYMapper(int argc, char *argv[])
{
vtkNew<vtkActor> actor;
vtkNew<vtkRenderer> renderer;
vtkNew<vtkPolyDataMapper> mapper;
renderer->SetBackground(0.0, 0.0, 0.0);
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->SetSize(300, 300);
renderWindow->AddRenderer(renderer.Get());
renderer->AddActor(actor.Get());
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renderWindow.Get());
vtkNew<vtkLightKit> lightKit;
lightKit->AddLightsToRenderer(renderer.Get());
const char* fileName = vtkTestUtilities::ExpandDataFileName(argc, argv,
"Data/dragon.ply");
vtkNew<vtkPLYReader> reader;
reader->SetFileName(fileName);
reader->Update();
// vtkNew<vtkPolyDataNormals> norms;
// norms->SetInputConnection(reader->GetOutputPort());
// norms->Update();
mapper->SetInputConnection(reader->GetOutputPort());
//mapper->SetInputConnection(norms->GetOutputPort());
actor->SetMapper(mapper.Get());
actor->GetProperty()->SetAmbientColor(0.2, 0.2, 1.0);
actor->GetProperty()->SetDiffuseColor(1.0, 0.65, 0.7);
actor->GetProperty()->SetSpecularColor(1.0, 1.0, 1.0);
actor->GetProperty()->SetSpecular(0.5);
actor->GetProperty()->SetDiffuse(0.7);
actor->GetProperty()->SetAmbient(0.5);
actor->GetProperty()->SetSpecularPower(20.0);
actor->GetProperty()->SetOpacity(1.0);
//actor->GetProperty()->SetRepresentationToWireframe();
renderWindow->SetMultiSamples(0);
vtkNew<vtkTimerLog> timer;
timer->StartTimer();
renderWindow->Render();
timer->StopTimer();
double firstRender = timer->GetElapsedTime();
cerr << "first render time: " << firstRender << endl;
timer->StartTimer();
int numRenders = 8;
for (int i = 0; i < numRenders; ++i)
{
renderer->GetActiveCamera()->Azimuth(10);
renderer->GetActiveCamera()->Elevation(10);
renderWindow->Render();
}
timer->StopTimer();
double elapsed = timer->GetElapsedTime();
cerr << "interactive render time: " << elapsed / numRenders << endl;
unsigned int numTris = reader->GetOutput()->GetPolys()->GetNumberOfCells();
cerr << "number of triangles: " << numTris << endl;
cerr << "triangles per second: " << numTris*(numRenders/elapsed) << endl;
renderer->GetActiveCamera()->SetPosition(0,0,1);
renderer->GetActiveCamera()->SetFocalPoint(0,0,0);
renderer->GetActiveCamera()->SetViewUp(0,1,0);
renderer->ResetCamera();
renderWindow->Render();
renderWindow->Render();
int retVal = vtkRegressionTestImage( renderWindow.Get() );
if ( retVal == vtkRegressionTester::DO_INTERACTOR)
{
iren->Start();
}
return !retVal;
}
<|endoftext|>
|
<commit_before>#include <pthread.h>
#include <time.h>
#include "t_zset.h"
#include "ttl.h"
#define EXPIRATION_LIST_KEY "\xff\xff\xff\xff\xff|EXPIRE_LIST|KV"
ExpirationHandler::ExpirationHandler(SSDB *ssdb){
this->ssdb = ssdb;
this->thread_quit = false;
this->list_name = EXPIRATION_LIST_KEY;
this->start();
}
ExpirationHandler::~ExpirationHandler(){
this->stop();
ssdb = NULL;
thread_quit = true;
}
void ExpirationHandler::start(){
int count = 0;
ZIterator *it;
it = ssdb->zscan(this->list_name, "", "", "", 999999999);
while(it->next()){
int64_t score = str_to_int64(it->score);
expiration_keys.add(it->key, score);
count ++;
}
delete it;
log_debug("loaded %d expiration key(s)", count);
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &ExpirationHandler::thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
void ExpirationHandler::stop(){
thread_quit = true;
for(int i=0; i<100; i++){
if(!thread_quit){
break;
}
usleep(10 * 1000);
}
}
int ExpirationHandler::set_ttl(const Bytes &key, int ttl){
int64_t expired = time_ms() + ttl * 1000;
char data[30];
int size = snprintf(data, sizeof(data), "%" PRId64, expired);
if(size <= 0){
log_error("snprintf return error!");
return -1;
}
Locking l(&mutex);
int ret = ssdb->zset(this->list_name, key, Bytes(data, size));
if(ret == -1){
return -1;
}
expiration_keys.add(key.String(), expired);
return 0;
}
void* ExpirationHandler::thread_func(void *arg){
log_debug("ExpirationHandler started");
ExpirationHandler *handler = (ExpirationHandler *)arg;
while(!handler->thread_quit){
SSDB *ssdb = handler->ssdb;
if(!ssdb){
break;
}
const std::string *key;
int64_t score;
{
Locking l(&handler->mutex);
if(handler->expiration_keys.front(&key, &score)){
int64_t now = time_ms();
if(score <= now){
log_debug("%s expired", key->c_str());
ssdb->del(*key);
ssdb->zdel(handler->list_name, *key);
handler->expiration_keys.pop_front();
continue;
}
}
}
usleep(50 * 1000);
}
log_debug("ExpirationHandler thread_func quit");
handler->thread_quit = false;
return (void *)NULL;
}
<commit_msg>update<commit_after>#include <pthread.h>
#include <time.h>
#include "t_zset.h"
#include "ttl.h"
#define EXPIRATION_LIST_KEY "\xff\xff\xff\xff\xff|EXPIRE_LIST|KV"
ExpirationHandler::ExpirationHandler(SSDB *ssdb){
this->ssdb = ssdb;
this->thread_quit = false;
this->list_name = EXPIRATION_LIST_KEY;
this->start();
}
ExpirationHandler::~ExpirationHandler(){
this->stop();
ssdb = NULL;
thread_quit = true;
}
void ExpirationHandler::start(){
int count = 0;
ZIterator *it;
it = ssdb->zscan(this->list_name, "", "", "", 999999999);
while(it->next()){
int64_t score = str_to_int64(it->score);
if(score < 2000000000){
// older version compatible
score *= 1000;
}
expiration_keys.add(it->key, score);
count ++;
}
delete it;
log_debug("loaded %d expiration key(s)", count);
thread_quit = false;
pthread_t tid;
int err = pthread_create(&tid, NULL, &ExpirationHandler::thread_func, this);
if(err != 0){
log_fatal("can't create thread: %s", strerror(err));
exit(0);
}
}
void ExpirationHandler::stop(){
thread_quit = true;
for(int i=0; i<100; i++){
if(!thread_quit){
break;
}
usleep(10 * 1000);
}
}
int ExpirationHandler::set_ttl(const Bytes &key, int ttl){
int64_t expired = time_ms() + ttl * 1000;
char data[30];
int size = snprintf(data, sizeof(data), "%" PRId64, expired);
if(size <= 0){
log_error("snprintf return error!");
return -1;
}
Locking l(&mutex);
int ret = ssdb->zset(this->list_name, key, Bytes(data, size));
if(ret == -1){
return -1;
}
expiration_keys.add(key.String(), expired);
return 0;
}
void* ExpirationHandler::thread_func(void *arg){
log_debug("ExpirationHandler started");
ExpirationHandler *handler = (ExpirationHandler *)arg;
while(!handler->thread_quit){
SSDB *ssdb = handler->ssdb;
if(!ssdb){
break;
}
const std::string *key;
int64_t score;
{
Locking l(&handler->mutex);
if(handler->expiration_keys.front(&key, &score)){
int64_t now = time_ms();
if(score <= now){
log_debug("expired %s", key->c_str());
ssdb->del(*key);
ssdb->zdel(handler->list_name, *key);
handler->expiration_keys.pop_front();
continue;
}
}
}
usleep(50 * 1000);
}
log_debug("ExpirationHandler thread_func quit");
handler->thread_quit = false;
return (void *)NULL;
}
<|endoftext|>
|
<commit_before><commit_msg>begin uin.cpp base code<commit_after>#include <iostream>
#include <string>
using namespace std;
string userin(string &);
void print(const string);
string userin(string &s)
{
getline(s);
}
void print(const string s)
{
}
int main()
{
string uin;
userin(uin);
print(uin);
return 0;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File FilterElectrogram.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Outputs values at specific points during time-stepping.
//
///////////////////////////////////////////////////////////////////////////////
#include <LibUtilities/Memory/NekMemoryManager.hpp>
#include <iomanip>
#include <CardiacEPSolver/Filters/FilterElectrogram.h>
namespace Nektar
{
std::string FilterElectrogram::className = GetFilterFactory().RegisterCreatorFunction("Electrogram", FilterElectrogram::create);
/**
*
*/
FilterElectrogram::FilterElectrogram(
const LibUtilities::SessionReaderSharedPtr &pSession,
const std::map<std::string, std::string> &pParams) :
Filter(pSession)
{
if (pParams.find("OutputFile") == pParams.end())
{
m_outputFile = m_session->GetSessionName();
}
else
{
ASSERTL0(!(pParams.find("OutputFile")->second.empty()),
"Missing parameter 'OutputFile'.");
m_outputFile = pParams.find("OutputFile")->second;
}
if (!(m_outputFile.length() >= 4
&& m_outputFile.substr(m_outputFile.length() - 4) == ".ecg"))
{
m_outputFile += ".ecg";
}
if (pParams.find("OutputFrequency") == pParams.end())
{
m_outputFrequency = 1;
}
else
{
m_outputFrequency = atoi(pParams.find("OutputFrequency")->second.c_str());
}
ASSERTL0(pParams.find("Points") != pParams.end(),
"Missing parameter 'Points'.");
m_electrogramStream.str(pParams.find("Points")->second);
m_index = 0;
}
/**
*
*/
FilterElectrogram::~FilterElectrogram()
{
}
/**
*
*/
void FilterElectrogram::v_Initialise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
ASSERTL0(!m_electrogramStream.fail(),
"No history points in stream.");
m_index = 0;
m_electrogramList.clear();
Array<OneD, NekDouble> gloCoord(3,0.0);
LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();
// Read electrogram points
// Always use dim = 3 to allow electrode to be above surface
int dim = 3;
int i = 0;
while (!m_electrogramStream.fail())
{
m_electrogramStream >> gloCoord[0] >> gloCoord[1] >> gloCoord[2];
if (!m_electrogramStream.fail())
{
SpatialDomains::VertexComponentSharedPtr vert
= MemoryManager<SpatialDomains::VertexComponent>
::AllocateSharedPtr(dim, i, gloCoord[0],
gloCoord[1], gloCoord[2]);
m_electrogramPoints.push_back(vert);
++i;
}
}
if (vComm->GetRank() == 0)
{
// Open output stream
m_outputStream.open(m_outputFile.c_str());
m_outputStream << "# Electrogram data for variables (:";
for (i = 0; i < pFields.num_elements(); ++i)
{
m_outputStream << m_session->GetVariable(i) <<",";
}
m_outputStream << ") at points:" << endl;
for (i = 0; i < m_electrogramPoints.size(); ++i)
{
m_electrogramPoints[i]->GetCoords( gloCoord[0],
gloCoord[1],
gloCoord[2]);
m_outputStream << "# \t" << i;
m_outputStream.width(8);
m_outputStream << gloCoord[0];
m_outputStream.width(8);
m_outputStream << gloCoord[1];
m_outputStream.width(8);
m_outputStream << gloCoord[2];
m_outputStream << endl;
}
}
// Compute the distance function for each electrogram point
const unsigned int nq = pFields[0]->GetNpoints();
NekDouble px, py, pz;
m_grad_R_x = Array<OneD, Array<OneD, NekDouble> >(m_electrogramPoints.size());
m_grad_R_y = Array<OneD, Array<OneD, NekDouble> >(m_electrogramPoints.size());
m_grad_R_z = Array<OneD, Array<OneD, NekDouble> >(m_electrogramPoints.size());
Array<OneD, NekDouble> x(nq);
Array<OneD, NekDouble> y(nq);
Array<OneD, NekDouble> z(nq);
pFields[0]->GetCoords(x,y,z);
Array<OneD, NekDouble> oneOverR(nq);
for (unsigned int i = 0; i < m_electrogramPoints.size(); ++i)
{
m_grad_R_x[i] = Array<OneD, NekDouble>(nq);
m_grad_R_y[i] = Array<OneD, NekDouble>(nq);
m_grad_R_z[i] = Array<OneD, NekDouble>(nq);
// Compute 1/R
m_electrogramPoints[i]->GetCoords(px,py,pz);
Vmath::Sadd (nq, -px, x, 1, x, 1);
Vmath::Sadd (nq, -py, y, 1, y, 1);
Vmath::Sadd (nq, -pz, z, 1, z, 1);
Vmath::Vvtvvtp(nq, x, 1, x, 1, y, 1, y, 1, oneOverR, 1);
Vmath::Vvtvp (nq, z, 1, z, 1, oneOverR, 1, oneOverR, 1);
Vmath::Vsqrt (nq, oneOverR, 1, oneOverR, 1);
Vmath::Sdiv (nq, 1.0, oneOverR, 1, oneOverR, 1);
// Compute grad 1/R
pFields[0]->PhysDeriv(oneOverR, m_grad_R_x[i], m_grad_R_y[i], m_grad_R_z[i]);
}
// Compute electrogram point for initial condition
v_Update(pFields, time);
}
/**
*
*/
void FilterElectrogram::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
// Only output every m_outputFrequency.
if ((m_index++) % m_outputFrequency)
{
return;
}
const unsigned int nq = pFields[0]->GetNpoints();
const unsigned int npoints = m_electrogramPoints.size();
LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();
unsigned int i = 0;
Array<OneD, NekDouble> e(npoints);
// Compute grad V
Array<OneD, NekDouble> grad_V_x(nq), grad_V_y(nq), grad_V_z(nq);
pFields[0]->PhysDeriv(pFields[0]->GetPhys(), grad_V_x, grad_V_y, grad_V_z);
for (i = 0; i < npoints; ++i)
{
// Multiply together
Array<OneD, NekDouble> output(nq);
Vmath::Vvtvvtp(nq, m_grad_R_x[i], 1, grad_V_x, 1, m_grad_R_y[i], 1, grad_V_y, 1, output, 1);
Vmath::Vvtvp (nq, m_grad_R_z[i], 1, grad_V_z, 1, output, 1, output, 1);
e[i] = pFields[0]->Integral(output);
}
// Exchange history data
// This could be improved to reduce communication but works for now
vComm->AllReduce(e, LibUtilities::ReduceSum);
// Only the root process writes out electrogram data
if (vComm->GetRank() == 0)
{
m_outputStream.width(8);
m_outputStream << setprecision(6) << time;
// Write data values point by point
for (i = 0; i < m_electrogramPoints.size(); ++i)
{
m_outputStream.width(25);
m_outputStream << setprecision(16) << e[i];
}
m_outputStream << endl;
}
}
/**
*
*/
void FilterElectrogram::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
if (pFields[0]->GetComm()->GetRank() == 0)
{
m_outputStream.close();
}
}
/**
*
*/
bool FilterElectrogram::v_IsTimeDependent()
{
return true;
}
}
<commit_msg>Fixed bug in electrogram filter.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File FilterElectrogram.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Outputs values at specific points during time-stepping.
//
///////////////////////////////////////////////////////////////////////////////
#include <LibUtilities/Memory/NekMemoryManager.hpp>
#include <iomanip>
#include <CardiacEPSolver/Filters/FilterElectrogram.h>
namespace Nektar
{
std::string FilterElectrogram::className = GetFilterFactory().RegisterCreatorFunction("Electrogram", FilterElectrogram::create);
/**
*
*/
FilterElectrogram::FilterElectrogram(
const LibUtilities::SessionReaderSharedPtr &pSession,
const std::map<std::string, std::string> &pParams) :
Filter(pSession)
{
if (pParams.find("OutputFile") == pParams.end())
{
m_outputFile = m_session->GetSessionName();
}
else
{
ASSERTL0(!(pParams.find("OutputFile")->second.empty()),
"Missing parameter 'OutputFile'.");
m_outputFile = pParams.find("OutputFile")->second;
}
if (!(m_outputFile.length() >= 4
&& m_outputFile.substr(m_outputFile.length() - 4) == ".ecg"))
{
m_outputFile += ".ecg";
}
if (pParams.find("OutputFrequency") == pParams.end())
{
m_outputFrequency = 1;
}
else
{
m_outputFrequency = atoi(pParams.find("OutputFrequency")->second.c_str());
}
ASSERTL0(pParams.find("Points") != pParams.end(),
"Missing parameter 'Points'.");
m_electrogramStream.str(pParams.find("Points")->second);
m_index = 0;
}
/**
*
*/
FilterElectrogram::~FilterElectrogram()
{
}
/**
*
*/
void FilterElectrogram::v_Initialise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
ASSERTL0(!m_electrogramStream.fail(),
"No history points in stream.");
m_index = 0;
m_electrogramList.clear();
Array<OneD, NekDouble> gloCoord(3,0.0);
LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();
// Read electrogram points
// Always use dim = 3 to allow electrode to be above surface
int dim = 3;
int i = 0;
while (!m_electrogramStream.fail())
{
m_electrogramStream >> gloCoord[0] >> gloCoord[1] >> gloCoord[2];
if (!m_electrogramStream.fail())
{
SpatialDomains::VertexComponentSharedPtr vert
= MemoryManager<SpatialDomains::VertexComponent>
::AllocateSharedPtr(dim, i, gloCoord[0],
gloCoord[1], gloCoord[2]);
m_electrogramPoints.push_back(vert);
++i;
}
}
if (vComm->GetRank() == 0)
{
// Open output stream
m_outputStream.open(m_outputFile.c_str());
m_outputStream << "# Electrogram data for variables (:";
for (i = 0; i < pFields.num_elements(); ++i)
{
m_outputStream << m_session->GetVariable(i) <<",";
}
m_outputStream << ") at points:" << endl;
for (i = 0; i < m_electrogramPoints.size(); ++i)
{
m_electrogramPoints[i]->GetCoords( gloCoord[0],
gloCoord[1],
gloCoord[2]);
m_outputStream << "# \t" << i;
m_outputStream.width(8);
m_outputStream << gloCoord[0];
m_outputStream.width(8);
m_outputStream << gloCoord[1];
m_outputStream.width(8);
m_outputStream << gloCoord[2];
m_outputStream << endl;
}
}
// Compute the distance function for each electrogram point
const unsigned int nq = pFields[0]->GetNpoints();
NekDouble px, py, pz;
m_grad_R_x = Array<OneD, Array<OneD, NekDouble> >(m_electrogramPoints.size());
m_grad_R_y = Array<OneD, Array<OneD, NekDouble> >(m_electrogramPoints.size());
m_grad_R_z = Array<OneD, Array<OneD, NekDouble> >(m_electrogramPoints.size());
Array<OneD, NekDouble> x(nq);
Array<OneD, NekDouble> y(nq);
Array<OneD, NekDouble> z(nq);
Array<OneD, NekDouble> oneOverR(nq);
for (unsigned int i = 0; i < m_electrogramPoints.size(); ++i)
{
m_grad_R_x[i] = Array<OneD, NekDouble>(nq);
m_grad_R_y[i] = Array<OneD, NekDouble>(nq);
m_grad_R_z[i] = Array<OneD, NekDouble>(nq);
// Compute 1/R
m_electrogramPoints[i]->GetCoords(px,py,pz);
pFields[0]->GetCoords(x,y,z);
Vmath::Sadd (nq, -px, x, 1, x, 1);
Vmath::Sadd (nq, -py, y, 1, y, 1);
Vmath::Sadd (nq, -pz, z, 1, z, 1);
Vmath::Vvtvvtp(nq, x, 1, x, 1, y, 1, y, 1, oneOverR, 1);
Vmath::Vvtvp (nq, z, 1, z, 1, oneOverR, 1, oneOverR, 1);
Vmath::Vsqrt (nq, oneOverR, 1, oneOverR, 1);
Vmath::Sdiv (nq, 1.0, oneOverR, 1, oneOverR, 1);
// Compute grad 1/R
pFields[0]->PhysDeriv(oneOverR, m_grad_R_x[i], m_grad_R_y[i], m_grad_R_z[i]);
}
// Compute electrogram point for initial condition
v_Update(pFields, time);
}
/**
*
*/
void FilterElectrogram::v_Update(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
// Only output every m_outputFrequency.
if ((m_index++) % m_outputFrequency)
{
return;
}
const unsigned int nq = pFields[0]->GetNpoints();
const unsigned int npoints = m_electrogramPoints.size();
LibUtilities::CommSharedPtr vComm = pFields[0]->GetComm();
unsigned int i = 0;
Array<OneD, NekDouble> e(npoints);
// Compute grad V
Array<OneD, NekDouble> grad_V_x(nq), grad_V_y(nq), grad_V_z(nq);
pFields[0]->PhysDeriv(pFields[0]->GetPhys(), grad_V_x, grad_V_y, grad_V_z);
for (i = 0; i < npoints; ++i)
{
// Multiply together
Array<OneD, NekDouble> output(nq);
Vmath::Vvtvvtp(nq, m_grad_R_x[i], 1, grad_V_x, 1, m_grad_R_y[i], 1, grad_V_y, 1, output, 1);
Vmath::Vvtvp (nq, m_grad_R_z[i], 1, grad_V_z, 1, output, 1, output, 1);
e[i] = pFields[0]->Integral(output);
}
// Exchange history data
// This could be improved to reduce communication but works for now
vComm->AllReduce(e, LibUtilities::ReduceSum);
// Only the root process writes out electrogram data
if (vComm->GetRank() == 0)
{
m_outputStream.width(8);
m_outputStream << setprecision(6) << time;
// Write data values point by point
for (i = 0; i < m_electrogramPoints.size(); ++i)
{
m_outputStream.width(25);
m_outputStream << setprecision(16) << e[i];
}
m_outputStream << endl;
}
}
/**
*
*/
void FilterElectrogram::v_Finalise(const Array<OneD, const MultiRegions::ExpListSharedPtr> &pFields, const NekDouble &time)
{
if (pFields[0]->GetComm()->GetRank() == 0)
{
m_outputStream.close();
}
}
/**
*
*/
bool FilterElectrogram::v_IsTimeDependent()
{
return true;
}
}
<|endoftext|>
|
<commit_before>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Dan Petrie <dpetrie AT SIPez DOT com>
// SYSTEM INCLUDES
#include <assert.h>
#include <math.h>
// APPLICATION INCLUDES
#include <mp/MpInputDeviceManager.h>
#include <mp/MpSineWaveGeneratorDeviceDriver.h>
#include <os/OsServerTask.h>
#include <os/OsTimer.h>
#include <os/OsEventMsg.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
// 0 is the Highest priority
#define SINE_WAVE_DEVICE_PRIORITY 0
// STATIC VARIABLE INITIALIZATIONS
// PRIVATE CLASSES
class MpSineWaveGeneratorServer : public OsServerTask
{
public:
MpSineWaveGeneratorServer(unsigned int startFrameTime,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond,
unsigned int magnitude,
unsigned int periodMicroseconds,
int underOverRunTime,
MpInputDeviceHandle deviceId,
MpInputDeviceManager& inputDeviceManager)
: OsServerTask("MpSineWaveGeneratorServer-%d", NULL, DEF_MAX_MSGS, SINE_WAVE_DEVICE_PRIORITY),
mNextFrameTime(startFrameTime),
mSamplesPerFrame(samplesPerFrame),
mSamplesPerSecond(samplesPerSecond),
mMagnatude(magnitude),
mSinePeriodMicroseconds(periodMicroseconds),
mUnderOverRunTime(underOverRunTime),
mDeviceId(deviceId),
mpInputDeviceManager(&inputDeviceManager),
mpFrameData(NULL),
mTimer(getMessageQueue(), 0)
{
mpFrameData = new MpAudioSample[mSamplesPerFrame];
};
virtual ~MpSineWaveGeneratorServer()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer start");
// Do not continue until the task is safely shutdown
waitUntilShutDown();
assert(isShutDown());
if(mpFrameData)
{
delete[] mpFrameData;
mpFrameData = NULL;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer end");
};
virtual UtlBoolean start(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start start");
// start the task
UtlBoolean result = OsServerTask::start();
OsTime noDelay(0, 0);
int microSecondsPerFrame =
(mSamplesPerFrame * 1000000 / mSamplesPerSecond) -
mUnderOverRunTime;
assert(microSecondsPerFrame > 0);
OsTime framePeriod(0, microSecondsPerFrame);
// Start re-occurring timer which causes handleMessage to be called
// periodically
mTimer.periodicEvery(noDelay, framePeriod);
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start end");
return(result);
};
virtual void requestShutdown(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown start");
// Stop the timer first so it stops queuing messages
mTimer.stop();
// Then stop the server task
OsServerTask::requestShutdown();
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown end");
};
UtlBoolean handleMessage(OsMsg& rMsg)
{
#ifdef RTL_ENABLED
RTL_BLOCK("MpSineWaveGeneratorServer.handleMessage");
#endif
// Build a frame of signal and push it to the device manager
assert(mpFrameData);
// Check that we've got expected message type.
assert(rMsg.getMsgType() == OsMsg::OS_EVENT);
assert(rMsg.getMsgSubType() == OsEventMsg::NOTIFY);
for(unsigned int frameIndex = 0; frameIndex < mSamplesPerFrame; frameIndex++)
{
mpFrameData[frameIndex] =
MpSineWaveGeneratorDeviceDriver::calculateSample(mNextFrameTime,
mMagnatude,
mSinePeriodMicroseconds,
frameIndex,
mSamplesPerFrame,
mSamplesPerSecond);
}
mpInputDeviceManager->pushFrame(mDeviceId,
mSamplesPerFrame,
mpFrameData,
mNextFrameTime);
mNextFrameTime += mSamplesPerFrame * 1000 / mSamplesPerSecond;
return(TRUE);
}
// This is intended to be called from other threads when this task is not
// started -- either not yet started, suspended, or stopped,
// as there is no concurrency locks.
void setNewTone(unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
{
mMagnatude = magnitude;
mSinePeriodMicroseconds = periodInMicroseconds;
mUnderOverRunTime = underOverRunTime;
}
private:
MpFrameTime mNextFrameTime;
unsigned int mSamplesPerFrame;
unsigned int mSamplesPerSecond;
unsigned int mMagnatude;
unsigned int mSinePeriodMicroseconds;
int mUnderOverRunTime;
MpInputDeviceHandle mDeviceId;
MpInputDeviceManager* mpInputDeviceManager;
MpAudioSample* mpFrameData;
OsTimer mTimer;
};
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
MpSineWaveGeneratorDeviceDriver::MpSineWaveGeneratorDeviceDriver(const UtlString& name,
MpInputDeviceManager& deviceManager,
unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
: MpInputDeviceDriver(name, deviceManager),
mMagnitude(magnitude),
mPeriodInMicroseconds(periodInMicroseconds),
mUnderOverRunTime(underOverRunTime),
mpReaderTask(NULL)
{
}
// Destructor
MpSineWaveGeneratorDeviceDriver::~MpSineWaveGeneratorDeviceDriver()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver start");
if(mpReaderTask)
{
OsStatus stat = disableDevice();
assert(stat == OS_SUCCESS);
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver end");
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpSineWaveGeneratorDeviceDriver::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice start");
OsStatus result = OS_INVALID;
assert(mpReaderTask == NULL);
if(mpReaderTask == NULL)
{
mpReaderTask =
new MpSineWaveGeneratorServer(currentFrameTime,
samplesPerFrame,
samplesPerSec,
mMagnitude,
mPeriodInMicroseconds,
mUnderOverRunTime,
getDeviceId(),
*mpInputDeviceManager);
if(mpReaderTask->start())
{
result = OS_SUCCESS;
mIsEnabled = TRUE;
}
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice end");
return(result);
}
OsStatus MpSineWaveGeneratorDeviceDriver::disableDevice()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice start");
OsStatus result = OS_TASK_NOT_STARTED;
//assert(mpReaderTask);
if(mpReaderTask)
{
mpReaderTask->requestShutdown();
delete mpReaderTask;
mpReaderTask = NULL;
result = OS_SUCCESS;
mIsEnabled = FALSE;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice end");
return(result);
}
OsStatus MpSineWaveGeneratorDeviceDriver::setNewTone(unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
{
if(!mpReaderTask)
{
return OS_TASK_NOT_STARTED;
}
// Pause the thread so we can set a new tone.
OsStatus stat = mpReaderTask->suspend();
if(stat != OS_SUCCESS)
return stat;
// Set the new tone values.
mMagnitude = magnitude;
mPeriodInMicroseconds = periodInMicroseconds;
mUnderOverRunTime;
((MpSineWaveGeneratorServer*)mpReaderTask)->setNewTone(mMagnitude,
mPeriodInMicroseconds,
mUnderOverRunTime);
// Resume the thread.
return mpReaderTask->resume();
}
/* ============================ ACCESSORS ================================= */
MpAudioSample
MpSineWaveGeneratorDeviceDriver::calculateSample(MpFrameTime frameStartTime,
unsigned int magnitude,
unsigned int periodInMicroseconds,
unsigned int frameSampleIndex,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond)
{
double time = ((frameStartTime + frameSampleIndex * 1000.0 / (double) samplesPerSecond)
/ ((double) periodInMicroseconds) * 1000.0 ) * 2.0 * M_PI;
MpAudioSample sample = (MpAudioSample)(cos(time) * (double)magnitude);
return(sample);
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<commit_msg>Make constructor parameter for setting speed of tone generation (faster than normal, slower than normal) more clear in it's name.<commit_after>//
// Copyright (C) 2007 SIPez LLC.
// Licensed to SIPfoundry under a Contributor Agreement.
//
// Copyright (C) 2007 SIPfoundry Inc.
// Licensed by SIPfoundry under the LGPL license.
//
// $$
///////////////////////////////////////////////////////////////////////////////
// Author: Dan Petrie <dpetrie AT SIPez DOT com>
// SYSTEM INCLUDES
#include <assert.h>
#include <math.h>
// APPLICATION INCLUDES
#include <mp/MpInputDeviceManager.h>
#include <mp/MpSineWaveGeneratorDeviceDriver.h>
#include <os/OsServerTask.h>
#include <os/OsTimer.h>
#include <os/OsEventMsg.h>
#ifdef RTL_ENABLED
# include <rtl_macro.h>
#endif
// EXTERNAL FUNCTIONS
// EXTERNAL VARIABLES
// CONSTANTS
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
// 0 is the Highest priority
#define SINE_WAVE_DEVICE_PRIORITY 0
// STATIC VARIABLE INITIALIZATIONS
// PRIVATE CLASSES
class MpSineWaveGeneratorServer : public OsServerTask
{
public:
MpSineWaveGeneratorServer(unsigned int startFrameTime,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond,
unsigned int magnitude,
unsigned int periodMicroseconds,
int relativeSpeed,
MpInputDeviceHandle deviceId,
MpInputDeviceManager& inputDeviceManager)
: OsServerTask("MpSineWaveGeneratorServer-%d", NULL, DEF_MAX_MSGS, SINE_WAVE_DEVICE_PRIORITY),
mNextFrameTime(startFrameTime),
mSamplesPerFrame(samplesPerFrame),
mSamplesPerSecond(samplesPerSecond),
mMagnatude(magnitude),
mSinePeriodMicroseconds(periodMicroseconds),
relativeSpeed(relativeSpeed),
mDeviceId(deviceId),
mpInputDeviceManager(&inputDeviceManager),
mpFrameData(NULL),
mTimer(getMessageQueue(), 0)
{
mpFrameData = new MpAudioSample[mSamplesPerFrame];
};
virtual ~MpSineWaveGeneratorServer()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer start");
// Do not continue until the task is safely shutdown
waitUntilShutDown();
assert(isShutDown());
if(mpFrameData)
{
delete[] mpFrameData;
mpFrameData = NULL;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorServer end");
};
virtual UtlBoolean start(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start start");
// start the task
UtlBoolean result = OsServerTask::start();
OsTime noDelay(0, 0);
int microSecondsPerFrame =
(mSamplesPerFrame * 1000000 / mSamplesPerSecond) -
relativeSpeed;
assert(microSecondsPerFrame > 0);
OsTime framePeriod(0, microSecondsPerFrame);
// Start re-occurring timer which causes handleMessage to be called
// periodically
mTimer.periodicEvery(noDelay, framePeriod);
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::start end");
return(result);
};
virtual void requestShutdown(void)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown start");
// Stop the timer first so it stops queuing messages
mTimer.stop();
// Then stop the server task
OsServerTask::requestShutdown();
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorServer::requestShutdown end");
};
UtlBoolean handleMessage(OsMsg& rMsg)
{
#ifdef RTL_ENABLED
RTL_BLOCK("MpSineWaveGeneratorServer.handleMessage");
#endif
// Build a frame of signal and push it to the device manager
assert(mpFrameData);
// Check that we've got expected message type.
assert(rMsg.getMsgType() == OsMsg::OS_EVENT);
assert(rMsg.getMsgSubType() == OsEventMsg::NOTIFY);
for(unsigned int frameIndex = 0; frameIndex < mSamplesPerFrame; frameIndex++)
{
mpFrameData[frameIndex] =
MpSineWaveGeneratorDeviceDriver::calculateSample(mNextFrameTime,
mMagnatude,
mSinePeriodMicroseconds,
frameIndex,
mSamplesPerFrame,
mSamplesPerSecond);
}
mpInputDeviceManager->pushFrame(mDeviceId,
mSamplesPerFrame,
mpFrameData,
mNextFrameTime);
mNextFrameTime += mSamplesPerFrame * 1000 / mSamplesPerSecond;
return(TRUE);
}
// This is intended to be called from other threads when this task is not
// started -- either not yet started, suspended, or stopped,
// as there is no concurrency locks.
void setNewTone(unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
{
mMagnatude = magnitude;
mSinePeriodMicroseconds = periodInMicroseconds;
relativeSpeed = underOverRunTime;
}
private:
MpFrameTime mNextFrameTime;
unsigned int mSamplesPerFrame;
unsigned int mSamplesPerSecond;
unsigned int mMagnatude;
unsigned int mSinePeriodMicroseconds;
int relativeSpeed;
MpInputDeviceHandle mDeviceId;
MpInputDeviceManager* mpInputDeviceManager;
MpAudioSample* mpFrameData;
OsTimer mTimer;
};
/* //////////////////////////// PUBLIC //////////////////////////////////// */
/* ============================ CREATORS ================================== */
// Constructor
MpSineWaveGeneratorDeviceDriver::MpSineWaveGeneratorDeviceDriver(const UtlString& name,
MpInputDeviceManager& deviceManager,
unsigned int magnitude,
unsigned int periodInMicroseconds,
int relativeSpeed)
: MpInputDeviceDriver(name, deviceManager),
mMagnitude(magnitude),
mPeriodInMicroseconds(periodInMicroseconds),
relativeSpeed(relativeSpeed),
mpReaderTask(NULL)
{
}
// Destructor
MpSineWaveGeneratorDeviceDriver::~MpSineWaveGeneratorDeviceDriver()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver start");
if(mpReaderTask)
{
OsStatus stat = disableDevice();
assert(stat == OS_SUCCESS);
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"~MpSineWaveGeneratorDeviceDriver end");
}
/* ============================ MANIPULATORS ============================== */
OsStatus MpSineWaveGeneratorDeviceDriver::enableDevice(unsigned samplesPerFrame,
unsigned samplesPerSec,
MpFrameTime currentFrameTime)
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice start");
OsStatus result = OS_INVALID;
assert(mpReaderTask == NULL);
if(mpReaderTask == NULL)
{
mpReaderTask =
new MpSineWaveGeneratorServer(currentFrameTime,
samplesPerFrame,
samplesPerSec,
mMagnitude,
mPeriodInMicroseconds,
relativeSpeed,
getDeviceId(),
*mpInputDeviceManager);
if(mpReaderTask->start())
{
result = OS_SUCCESS;
mIsEnabled = TRUE;
}
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::enableDevice end");
return(result);
}
OsStatus MpSineWaveGeneratorDeviceDriver::disableDevice()
{
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice start");
OsStatus result = OS_TASK_NOT_STARTED;
//assert(mpReaderTask);
if(mpReaderTask)
{
mpReaderTask->requestShutdown();
delete mpReaderTask;
mpReaderTask = NULL;
result = OS_SUCCESS;
mIsEnabled = FALSE;
}
OsSysLog::add(FAC_MP, PRI_DEBUG,"MpSineWaveGeneratorDeviceDriver::disableDevice end");
return(result);
}
OsStatus MpSineWaveGeneratorDeviceDriver::setNewTone(unsigned int magnitude,
unsigned int periodInMicroseconds,
int underOverRunTime)
{
if(!mpReaderTask)
{
return OS_TASK_NOT_STARTED;
}
// Pause the thread so we can set a new tone.
OsStatus stat = mpReaderTask->suspend();
if(stat != OS_SUCCESS)
return stat;
// Set the new tone values.
mMagnitude = magnitude;
mPeriodInMicroseconds = periodInMicroseconds;
relativeSpeed;
((MpSineWaveGeneratorServer*)mpReaderTask)->setNewTone(mMagnitude,
mPeriodInMicroseconds,
relativeSpeed);
// Resume the thread.
return mpReaderTask->resume();
}
/* ============================ ACCESSORS ================================= */
MpAudioSample
MpSineWaveGeneratorDeviceDriver::calculateSample(MpFrameTime frameStartTime,
unsigned int magnitude,
unsigned int periodInMicroseconds,
unsigned int frameSampleIndex,
unsigned int samplesPerFrame,
unsigned int samplesPerSecond)
{
double time = ((frameStartTime + frameSampleIndex * 1000.0 / (double) samplesPerSecond)
/ ((double) periodInMicroseconds) * 1000.0 ) * 2.0 * M_PI;
MpAudioSample sample = (MpAudioSample)(cos(time) * (double)magnitude);
return(sample);
}
/* ============================ INQUIRY =================================== */
/* //////////////////////////// PROTECTED ///////////////////////////////// */
/* //////////////////////////// PRIVATE /////////////////////////////////// */
/* ============================ FUNCTIONS ================================= */
<|endoftext|>
|
<commit_before>#include "game/tileview/tileview.h"
#include "game/tileview/tile.h"
#include "framework/includes.h"
#include "framework/framework.h"
#include "framework/image.h"
#include "game/resources/gamecore.h"
namespace OpenApoc {
TileView::TileView(Framework &fw, TileMap &map, Vec3<int> tileSize)
: Stage(fw), map(map), tileSize(tileSize), maxZDraw(10), offsetX(0), offsetY(0),
cameraScrollX(0), cameraScrollY(0), selectedTilePosition(0,0,0),
selectedTileImageBack(fw.data->load_image("CITY/SELECTED-CITYTILE-BACK.PNG")),
selectedTileImageFront(fw.data->load_image("CITY/SELECTED-CITYTILE-FRONT.PNG")),
pal(fw.data->load_palette("xcom3/ufodata/PAL_01.DAT"))
{
}
TileView::~TileView()
{
}
void TileView::Begin()
{
}
void TileView::Pause()
{
}
void TileView::Resume()
{
}
void TileView::Finish()
{
}
void TileView::EventOccurred(Event *e)
{
bool selectionChanged = false;
if( e->Type == EVENT_KEY_DOWN )
{
if( e->Data.Keyboard.KeyCode == ALLEGRO_KEY_ESCAPE )
{
stageCmd.cmd = StageCmd::Command::POP;
return;
}
switch (e->Data.Keyboard.KeyCode)
{
case ALLEGRO_KEY_UP:
//offsetY += tileSize.y;
cameraScrollY = tileSize.y / 8;
break;
case ALLEGRO_KEY_DOWN:
//offsetY -= tileSize.y;
cameraScrollY = -tileSize.y / 8;
break;
case ALLEGRO_KEY_LEFT:
//offsetX += tileSize.x;
cameraScrollX = tileSize.x / 8;
break;
case ALLEGRO_KEY_RIGHT:
//offsetX -= tileSize.x;
cameraScrollX = -tileSize.x / 8;
break;
case ALLEGRO_KEY_PGDN:
if( fw.gamecore->DebugModeEnabled && maxZDraw > 1)
{
maxZDraw--;
}
break;
case ALLEGRO_KEY_PGUP:
if( fw.gamecore->DebugModeEnabled && maxZDraw < map.size.z)
{
maxZDraw++;
}
break;
case ALLEGRO_KEY_S:
selectionChanged = true;
if (selectedTilePosition.y < (map.size.y-1))
selectedTilePosition.y++;
break;
case ALLEGRO_KEY_W:
selectionChanged = true;
if (selectedTilePosition.y > 0)
selectedTilePosition.y--;
break;
case ALLEGRO_KEY_A:
selectionChanged = true;
if (selectedTilePosition.x > 0)
selectedTilePosition.x--;
break;
case ALLEGRO_KEY_D:
selectionChanged = true;
if (selectedTilePosition.x < (map.size.x-1))
selectedTilePosition.x++;
break;
case ALLEGRO_KEY_R:
selectionChanged = true;
if (selectedTilePosition.z < (map.size.z-1))
selectedTilePosition.z++;
break;
case ALLEGRO_KEY_F:
selectionChanged = true;
if (selectedTilePosition.z > 0)
selectedTilePosition.z--;
break;
case ALLEGRO_KEY_1:
pal = fw.data->load_palette("xcom3/ufodata/PAL_01.DAT");
break;
case ALLEGRO_KEY_2:
pal = fw.data->load_palette("xcom3/ufodata/PAL_02.DAT");
break;
case ALLEGRO_KEY_3:
pal = fw.data->load_palette("xcom3/ufodata/PAL_03.DAT");
break;
}
}
else if (e->Type == EVENT_MOUSE_DOWN)
{
auto &ev = e->Data.Mouse;
auto selected = screenToTileCoords(Vec2<float>{(float)ev.X - offsetX, (float)ev.Y - offsetY}, (float)maxZDraw-1);
if (selected.x < 0) selected.x = 0;
if (selected.y < 0) selected.y = 0;
if (selected.x > 99) selected.x = 99;
if (selected.y > 99) selected.y = 99;
selectedTilePosition = Vec3<int>{(int)selected.x, (int)selected.y, (int)selected.z};
selectionChanged = true;
} else if( e->Type == EVENT_KEY_UP )
{
switch (e->Data.Keyboard.KeyCode)
{
case ALLEGRO_KEY_UP:
case ALLEGRO_KEY_DOWN:
cameraScrollY = 0;
break;
case ALLEGRO_KEY_LEFT:
case ALLEGRO_KEY_RIGHT:
cameraScrollX = 0;
break;
}
}
if (fw.gamecore->DebugModeEnabled &&
selectionChanged)
{
LogInfo("Selected tile {%d,%d,%d}", selectedTilePosition.x, selectedTilePosition.y, selectedTilePosition.z);
}
}
void TileView::Update(StageCmd * const cmd)
{
*cmd = stageCmd;
stageCmd = StageCmd();
offsetX += cameraScrollX;
offsetY += cameraScrollY;
//TODO: Map wall-time to ticks?
this->map.update(1);
}
void TileView::Render()
{
int dpyWidth = fw.Display_GetWidth();
int dpyHeight = fw.Display_GetHeight();
Renderer &r = *fw.renderer;
r.clear();
r.setPalette(this->pal);
// offsetX/offsetY is the 'amount added to the tile coords' - so we want
// the inverse to tell which tiles are at the screen bounds
auto topLeft = screenToTileCoords(Vec2<int>{-offsetX, -offsetY}, 0);
auto topRight = screenToTileCoords(Vec2<int>{-offsetX + dpyWidth, -offsetY}, 0);
auto bottomLeft = screenToTileCoords(Vec2<int>{-offsetX, -offsetY + dpyHeight}, map.size.z);
auto bottomRight = screenToTileCoords(Vec2<int>{-offsetX + dpyWidth, -offsetY + dpyHeight}, map.size.z);
int minX = std::max(0, topLeft.x);
int maxX = std::min(map.size.x, bottomRight.x);
int minY = std::max(0, topRight.y);
int maxY = std::min(map.size.y, bottomLeft.y);
for (int z = 0; z < maxZDraw; z++)
{
for (int y = minY; y < maxY; y++)
{
for (int x = minX; x < maxX; x++)
{
bool showOrigin = fw.gamecore->DebugModeEnabled;
bool showSelected =
(fw.gamecore->DebugModeEnabled &&
z == selectedTilePosition.z &&
y == selectedTilePosition.y &&
x == selectedTilePosition.x);
auto tile = map.getTile(x, y, z);
// Skip over transparent (missing) tiles
auto screenPos = tileToScreenCoords(Vec3<float>{(float)x,(float)y,(float)z});
screenPos.x += offsetX;
screenPos.y += offsetY;
//Skip over tiles that would be outside the window
if (screenPos.x + tileSize.x < 0 || screenPos.y + tileSize.y < 0
|| screenPos.x - tileSize.x > dpyWidth || screenPos.y - tileSize.y > dpyHeight)
continue;
if (showSelected)
r.draw(selectedTileImageBack, screenPos);
for (auto obj : tile->visibleObjects)
{
assert(obj->isVisible());
auto img = obj->getSprite();
auto pos = obj->getDrawPosition();
auto objScreenPos = tileToScreenCoords(pos);
objScreenPos.x += offsetX;
objScreenPos.y += offsetY;
r.draw(img, objScreenPos);
if (showOrigin)
{
Vec2<float> offset{offsetX, offsetY};
objScreenPos = tileToScreenCoords(obj->getPosition());
objScreenPos.x += offsetX;
objScreenPos.y += offsetY;
auto linePos0 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,0,0.5});
auto linePos1 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,0,-0.5});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,0,0,255});
linePos0 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,0.5,0});
linePos1 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,-0.5,0});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,0,0,255});
linePos0 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0.5,0,0});
linePos1 = tileToScreenCoords(obj->getPosition() + Vec3<float>{-0.5,0,0});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,0,0,255});
}
}
if (showSelected)
r.draw(selectedTileImageFront, screenPos);
}
}
}
}
bool TileView::IsTransition()
{
return false;
}
}; //namespace OpenApoc
<commit_msg>Show object owning tile in yellow with debug mode enabled<commit_after>#include "game/tileview/tileview.h"
#include "game/tileview/tile.h"
#include "framework/includes.h"
#include "framework/framework.h"
#include "framework/image.h"
#include "game/resources/gamecore.h"
namespace OpenApoc {
TileView::TileView(Framework &fw, TileMap &map, Vec3<int> tileSize)
: Stage(fw), map(map), tileSize(tileSize), maxZDraw(10), offsetX(0), offsetY(0),
cameraScrollX(0), cameraScrollY(0), selectedTilePosition(0,0,0),
selectedTileImageBack(fw.data->load_image("CITY/SELECTED-CITYTILE-BACK.PNG")),
selectedTileImageFront(fw.data->load_image("CITY/SELECTED-CITYTILE-FRONT.PNG")),
pal(fw.data->load_palette("xcom3/ufodata/PAL_01.DAT"))
{
}
TileView::~TileView()
{
}
void TileView::Begin()
{
}
void TileView::Pause()
{
}
void TileView::Resume()
{
}
void TileView::Finish()
{
}
void TileView::EventOccurred(Event *e)
{
bool selectionChanged = false;
if( e->Type == EVENT_KEY_DOWN )
{
if( e->Data.Keyboard.KeyCode == ALLEGRO_KEY_ESCAPE )
{
stageCmd.cmd = StageCmd::Command::POP;
return;
}
switch (e->Data.Keyboard.KeyCode)
{
case ALLEGRO_KEY_UP:
//offsetY += tileSize.y;
cameraScrollY = tileSize.y / 8;
break;
case ALLEGRO_KEY_DOWN:
//offsetY -= tileSize.y;
cameraScrollY = -tileSize.y / 8;
break;
case ALLEGRO_KEY_LEFT:
//offsetX += tileSize.x;
cameraScrollX = tileSize.x / 8;
break;
case ALLEGRO_KEY_RIGHT:
//offsetX -= tileSize.x;
cameraScrollX = -tileSize.x / 8;
break;
case ALLEGRO_KEY_PGDN:
if( fw.gamecore->DebugModeEnabled && maxZDraw > 1)
{
maxZDraw--;
}
break;
case ALLEGRO_KEY_PGUP:
if( fw.gamecore->DebugModeEnabled && maxZDraw < map.size.z)
{
maxZDraw++;
}
break;
case ALLEGRO_KEY_S:
selectionChanged = true;
if (selectedTilePosition.y < (map.size.y-1))
selectedTilePosition.y++;
break;
case ALLEGRO_KEY_W:
selectionChanged = true;
if (selectedTilePosition.y > 0)
selectedTilePosition.y--;
break;
case ALLEGRO_KEY_A:
selectionChanged = true;
if (selectedTilePosition.x > 0)
selectedTilePosition.x--;
break;
case ALLEGRO_KEY_D:
selectionChanged = true;
if (selectedTilePosition.x < (map.size.x-1))
selectedTilePosition.x++;
break;
case ALLEGRO_KEY_R:
selectionChanged = true;
if (selectedTilePosition.z < (map.size.z-1))
selectedTilePosition.z++;
break;
case ALLEGRO_KEY_F:
selectionChanged = true;
if (selectedTilePosition.z > 0)
selectedTilePosition.z--;
break;
case ALLEGRO_KEY_1:
pal = fw.data->load_palette("xcom3/ufodata/PAL_01.DAT");
break;
case ALLEGRO_KEY_2:
pal = fw.data->load_palette("xcom3/ufodata/PAL_02.DAT");
break;
case ALLEGRO_KEY_3:
pal = fw.data->load_palette("xcom3/ufodata/PAL_03.DAT");
break;
}
}
else if (e->Type == EVENT_MOUSE_DOWN)
{
auto &ev = e->Data.Mouse;
auto selected = screenToTileCoords(Vec2<float>{(float)ev.X - offsetX, (float)ev.Y - offsetY}, (float)maxZDraw-1);
if (selected.x < 0) selected.x = 0;
if (selected.y < 0) selected.y = 0;
if (selected.x > 99) selected.x = 99;
if (selected.y > 99) selected.y = 99;
selectedTilePosition = Vec3<int>{(int)selected.x, (int)selected.y, (int)selected.z};
selectionChanged = true;
} else if( e->Type == EVENT_KEY_UP )
{
switch (e->Data.Keyboard.KeyCode)
{
case ALLEGRO_KEY_UP:
case ALLEGRO_KEY_DOWN:
cameraScrollY = 0;
break;
case ALLEGRO_KEY_LEFT:
case ALLEGRO_KEY_RIGHT:
cameraScrollX = 0;
break;
}
}
if (fw.gamecore->DebugModeEnabled &&
selectionChanged)
{
LogInfo("Selected tile {%d,%d,%d}", selectedTilePosition.x, selectedTilePosition.y, selectedTilePosition.z);
}
}
void TileView::Update(StageCmd * const cmd)
{
*cmd = stageCmd;
stageCmd = StageCmd();
offsetX += cameraScrollX;
offsetY += cameraScrollY;
//TODO: Map wall-time to ticks?
this->map.update(1);
}
void TileView::Render()
{
int dpyWidth = fw.Display_GetWidth();
int dpyHeight = fw.Display_GetHeight();
Renderer &r = *fw.renderer;
r.clear();
r.setPalette(this->pal);
// offsetX/offsetY is the 'amount added to the tile coords' - so we want
// the inverse to tell which tiles are at the screen bounds
auto topLeft = screenToTileCoords(Vec2<int>{-offsetX, -offsetY}, 0);
auto topRight = screenToTileCoords(Vec2<int>{-offsetX + dpyWidth, -offsetY}, 0);
auto bottomLeft = screenToTileCoords(Vec2<int>{-offsetX, -offsetY + dpyHeight}, map.size.z);
auto bottomRight = screenToTileCoords(Vec2<int>{-offsetX + dpyWidth, -offsetY + dpyHeight}, map.size.z);
int minX = std::max(0, topLeft.x);
int maxX = std::min(map.size.x, bottomRight.x);
int minY = std::max(0, topRight.y);
int maxY = std::min(map.size.y, bottomLeft.y);
for (int z = 0; z < maxZDraw; z++)
{
for (int y = minY; y < maxY; y++)
{
for (int x = minX; x < maxX; x++)
{
bool showOrigin = fw.gamecore->DebugModeEnabled;
bool showSelected =
(fw.gamecore->DebugModeEnabled &&
z == selectedTilePosition.z &&
y == selectedTilePosition.y &&
x == selectedTilePosition.x);
auto tile = map.getTile(x, y, z);
// Skip over transparent (missing) tiles
auto screenPos = tileToScreenCoords(Vec3<float>{(float)x,(float)y,(float)z});
screenPos.x += offsetX;
screenPos.y += offsetY;
//Skip over tiles that would be outside the window
if (screenPos.x + tileSize.x < 0 || screenPos.y + tileSize.y < 0
|| screenPos.x - tileSize.x > dpyWidth || screenPos.y - tileSize.y > dpyHeight)
continue;
if (showSelected)
r.draw(selectedTileImageBack, screenPos);
for (auto obj : tile->visibleObjects)
{
assert(obj->isVisible());
auto img = obj->getSprite();
auto pos = obj->getDrawPosition();
auto objScreenPos = tileToScreenCoords(pos);
objScreenPos.x += offsetX;
objScreenPos.y += offsetY;
r.draw(img, objScreenPos);
if (showOrigin)
{
Vec2<float> offset{offsetX, offsetY};
auto linePos0 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,0,0.5});
auto linePos1 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,0,-0.5});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,0,0,255});
linePos0 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,0.5,0});
linePos1 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0,-0.5,0});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,0,0,255});
linePos0 = tileToScreenCoords(obj->getPosition() + Vec3<float>{0.5,0,0});
linePos1 = tileToScreenCoords(obj->getPosition() + Vec3<float>{-0.5,0,0});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,0,0,255});
linePos0 = tileToScreenCoords(Vec3<float>{obj->getOwningTile()->position} + Vec3<float>{0,0,0.5});
linePos1 = tileToScreenCoords(Vec3<float>{obj->getOwningTile()->position} + Vec3<float>{0,0,-0.5});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,255,0,255});
linePos0 = tileToScreenCoords(Vec3<float>{obj->getOwningTile()->position} + Vec3<float>{0,0.5,0});
linePos1 = tileToScreenCoords(Vec3<float>{obj->getOwningTile()->position} + Vec3<float>{0,-0.5,0});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,255,0,255});
linePos0 = tileToScreenCoords(Vec3<float>{obj->getOwningTile()->position} + Vec3<float>{0.5,0,0});
linePos1 = tileToScreenCoords(Vec3<float>{obj->getOwningTile()->position} + Vec3<float>{-0.5,0,0});
linePos1 += offset;
linePos0 += offset;
r.drawLine(linePos0, linePos1, Colour{255,255,0,255});
}
}
if (showSelected)
r.draw(selectedTileImageFront, screenPos);
}
}
}
}
bool TileView::IsTransition()
{
return false;
}
}; //namespace OpenApoc
<|endoftext|>
|
<commit_before>#include "benchmarktarget_writer.h"
#include "common_writer.h"
#include "precomp.h"
void BenchmarktargetWriter::WriteBenchmarkTarget(
std::string dir_name,
std::map<std::string, RepoSearcher::directory> &targets,
std::map<std::string, RepoSearcher::library> &libraries) {
std::string proj_name =
dir_name.substr(dir_name.find_last_of('/') + 1, dir_name.size());
proj_name = dir_name.substr(dir_name.find_first_of('_') + 1, dir_name.size());
std::set<std::string> include_dirs;
std::vector<std::string> ext = {"cc", "cpp"};
std::set<std::string> added;
std::map<int, std::string> all_includes;
for (auto &target : targets) {
if (target.first.find("test_") != std::string::npos) continue;
for (auto &file : target.second.include_files) {
if (added.find(file.first) == added.end()) {
all_includes[file.second] = file.first;
added.insert(file.first);
}
}
}
std::string precomp_includes = "";
if (std::filesystem::exists("./source_shared")) {
include_dirs.insert("../source_shared");
for (auto &p : std::filesystem::directory_iterator("./source_shared")) {
if (std::filesystem::is_regular_file(p)) {
std::stringstream path_stream;
path_stream << p;
std::string path = path_stream.str();
while (path.back() == '\"') path.pop_back();
precomp_includes +=
"#include \"" +
path.substr(path.find_last_of('/') + 1, path.size()) + "\"\n";
}
}
}
precomp_includes += "\n";
for (auto &include : all_includes) {
while (include.second.back() == '\"') include.second.pop_back();
precomp_includes += "#include " + include.second + "\n";
}
precomp_includes += "\n";
std::string expected_precomp_h =
"#include <benchmark/benchmark.h>\n\n" + precomp_includes;
CommonWriter::UpdateIfDifferent(dir_name + "/precomp.h", expected_precomp_h);
std::string expected_precomp_cc = "#include \"precomp.h\"\n\n";
CommonWriter::UpdateIfDifferent(dir_name + "/precomp.cc",
expected_precomp_cc);
std::string expected_benchmark_main = "#include \"precomp.h\"\n\n";
for (auto &dir : targets)
for (auto &obj_dir : dir.second.files["h"].fmap)
for (auto &obj : obj_dir.second)
if (obj.find("benchmark_") != std::string::npos) {
while (obj.back() == '\"') obj.pop_back();
expected_benchmark_main +=
"#include \"" +
obj.substr(obj.find_last_of('/') + 1, obj.size()) + "\"\n";
}
expected_benchmark_main += "\nBENCHMARK_MAIN();";
CommonWriter::UpdateIfDifferent(dir_name + "/benchmark_main.cc",
expected_benchmark_main);
std::string expected = CommonWriter::cmake_header_ + "\n";
std::map<std::string, std::set<std::string>> all_finds;
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
for (auto &lib : dir.second.libraries) {
auto &lib_info = libraries[lib];
if (!lib_info.find_command.empty()) {
auto &ref = all_finds[lib_info.find_command];
for (auto &comp : lib_info.components) ref.insert(comp);
}
}
}
for (auto &find : all_finds) {
expected += "find_package(" + find.first;
if (!find.second.empty()) {
expected += " COMPONENTS\n";
for (auto &mod : find.second) expected += " " + mod + "\n";
}
expected += ")\n";
}
expected +=
"\nset(cpp_files\n"
" benchmark_main.cc\n"
" precomp.h\n"
" precomp.cc\n"
")\n\n"
"add_msvc_precompiled_header(\"precomp.h\" \"precomp.cc\" cpp_files)\n"
"add_executable(" +
proj_name + " ${cpp_files})\n\n";
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
for (auto &d : dir.second.directories)
if (!d.empty())
include_dirs.insert("." + dir.first + d.substr(1, d.size()));
for (auto &d : dir.second.include_dirs)
if (!d.empty()) include_dirs.insert(d);
for (auto &lib : dir.second.libraries)
for (auto &inc : libraries[lib].includes) include_dirs.insert(inc);
}
#ifdef WindowsBuild
include_dirs.insert("D:/API/GoogleBenchmark/include");
#endif
expected += "include_directories(" + proj_name + "\n";
for (auto &include : include_dirs) expected += " " + include + "\n";
expected += ")\n\n";
std::set<std::string> link_libraries;
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
if (dir.first.find("shared_") != std::string::npos) continue;
if (dir.first.find("benchmark_") != std::string::npos) continue;
std::string dir_n =
dir.first.substr(dir.first.find_last_of('/') + 1, dir.first.size());
for (auto &lib : dir.second.libraries)
for (auto &l : libraries[lib].libs) link_libraries.insert(l);
for (auto &ext : ext) {
for (auto &obj_dir : dir.second.files[ext].fmap) {
for (auto &obj : obj_dir.second) {
if (obj.find("main.") != std::string::npos) continue;
#ifdef WindowsBuild
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) +
".dir/";
for (auto &conf : CommonWriter::configs_)
obj_file_str += "$<$<CONFIG:" + conf + ">:" + conf + ">";
obj_file_str +=
"/" +
obj.substr(obj.find_last_of('/') + 1,
obj.find_last_of('.') - obj.find_last_of('/')) +
"obj";
#else
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/CMakeFiles/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) +
".dir/";
obj_file_str += obj + ".o";
#endif
link_libraries.insert(obj_file_str);
}
}
}
for (auto &obj : dir.second.moc_files) {
if (obj.find("main.") != std::string::npos) continue;
#ifdef WindowsBuild
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) + ".dir/";
for (auto &conf : CommonWriter::configs_)
obj_file_str += "$<$<CONFIG:" + conf + ">:" + conf + ">";
obj_file_str +=
"/moc_" +
obj.substr(obj.find_last_of('/') + 1,
obj.find_last_of('.') - obj.find_last_of('/')) +
"obj";
#else
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/CMakeFiles/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) + ".dir/";
obj_file_str += obj.substr(0, obj.find_last_of('/')) + "moc_" +
obj.substr(obj.find_last_of('/') + 1, obj.size()) + ".o";
#endif
link_libraries.insert(obj_file_str);
}
}
#ifdef WindowsBuild
link_libraries.insert("Shlwapi.lib");
link_libraries.insert("optimized D:/API/GoogleBenchmark/lib/benchmark.lib");
link_libraries.insert("debug D:/API/GoogleBenchmark/lib/benchmarkd.lib");
#else
link_libraries.insert("libbenchmark.so");
link_libraries.insert("libpthread.so");
#endif
expected += "target_link_libraries(" + proj_name + "\n";
for (auto &lib : link_libraries) expected += " " + lib + "\n";
expected += ")\n\n";
#ifdef WindowsBuild
std::string shared_ext = ".dll";
std::string shared_prefix = "";
#else
std::string shared_ext = ".so";
std::string shared_prefix = "lib";
#endif
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
std::set<std::string> libs;
for (auto &dep : dir.second.dependencies)
for (auto &lib : targets["./" + dep].libraries)
if (!libraries[lib].dlls.empty()) libs.insert(lib);
for (auto &lib : dir.second.libraries)
if (!libraries[lib].dlls.empty()) libs.insert(lib);
if (!libs.empty())
expected += "add_custom_command(TARGET " + proj_name + " POST_BUILD\n";
for (auto &lib : libs) {
for (int i = 0; i < libraries[lib].dlls.size(); ++i) {
auto &dll = libraries[lib].dlls[i];
auto &debug_dll = libraries[lib].debug_dlls.size() > i
? libraries[lib].debug_dlls[i]
: dll;
expected +=
" COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different\n \"";
for (auto &conf : CommonWriter::configs_) {
if (!conf.empty()) expected += "$<$<CONFIG:" + conf + ">:";
expected += shared_prefix +
(conf.compare("Debug") == 0
? debug_dll + libraries[lib].debug_suffix
: dll) +
shared_ext;
if (!conf.empty()) expected += ">";
}
expected += "\"\n \"";
for (auto &conf : CommonWriter::configs_) {
if (!conf.empty()) expected += "$<$<CONFIG:" + conf + ">:";
expected += "${CMAKE_CURRENT_BINARY_DIR}/Build_Output/bin/";
if (!conf.empty()) expected += conf + "/";
expected +=
shared_prefix +
(conf.compare("Debug") == 0
? debug_dll.substr(debug_dll.find_last_of('/') + 1,
debug_dll.size()) +
libraries[lib].debug_suffix
: dll.substr(dll.find_last_of('/') + 1, dll.size())) +
shared_ext;
if (!conf.empty()) expected += ">";
}
expected += "\"\n";
}
}
if (!libs.empty()) expected += ")\n\n";
}
expected += "add_dependencies(" + proj_name;
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
std::string dir_n =
dir.first.substr(dir.first.find_last_of('/') + 1, dir.first.size());
dir_n = dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size());
expected += " " + dir_n;
}
expected += " ALL_PRE_BUILD)";
CommonWriter::UpdateIfDifferent(dir_name + "/CMakeLists.txt", expected);
}
bool BenchmarktargetWriter::MainUpdateNeeded(
std::string dir_name,
std::map<std::string, RepoSearcher::directory> &targets) {
if (!std::filesystem::exists(dir_name + "/benchmark_main.cc")) return true;
std::ifstream bench_main(dir_name + "/benchmark_main.cc");
std::set<std::string> bench_files, check_set;
for (auto &dir : targets)
for (auto &obj_dir : dir.second.files["h"].fmap)
for (auto &obj : obj_dir.second)
if (obj.find("benchmark_") != std::string::npos)
bench_files.insert(obj.substr(obj.find_last_of('/') + 1, obj.size()));
std::string line;
while (!bench_main.eof()) {
std::getline(bench_main, line);
if (line.find("#include") != std::string::npos) {
auto it = bench_files.find(
line.substr(line.find_first_of('\"') + 1,
line.find_last_of('\"') - line.find_first_of('\"') - 1));
if (it != bench_files.end()) check_set.insert(*it);
}
}
bench_main.close();
return check_set.size() != bench_files.size();
}
<commit_msg>fix benchmark writer bug<commit_after>#include "benchmarktarget_writer.h"
#include "common_writer.h"
#include "precomp.h"
void BenchmarktargetWriter::WriteBenchmarkTarget(
std::string dir_name,
std::map<std::string, RepoSearcher::directory> &targets,
std::map<std::string, RepoSearcher::library> &libraries) {
std::string proj_name =
dir_name.substr(dir_name.find_last_of('/') + 1, dir_name.size());
proj_name = dir_name.substr(dir_name.find_first_of('_') + 1, dir_name.size());
std::set<std::string> include_dirs;
std::vector<std::string> ext = {"cc", "cpp"};
std::set<std::string> added;
std::map<int, std::string> all_includes;
for (auto &target : targets) {
if (target.first.find("test_") != std::string::npos) continue;
for (auto &file : target.second.include_files) {
if (added.find(file.first) == added.end()) {
all_includes[file.second] = file.first;
added.insert(file.first);
}
}
}
std::string precomp_includes = "";
if (std::filesystem::exists("./source_shared")) {
include_dirs.insert("../source_shared");
for (auto &p : std::filesystem::directory_iterator("./source_shared")) {
if (std::filesystem::is_regular_file(p)) {
std::stringstream path_stream;
path_stream << p;
std::string path = path_stream.str();
while (path.back() == '\"') path.pop_back();
precomp_includes +=
"#include \"" +
path.substr(path.find_last_of('/') + 1, path.size()) + "\"\n";
}
}
}
precomp_includes += "\n";
for (auto &include : all_includes) {
while (include.second.back() == '\"') include.second.pop_back();
precomp_includes += "#include " + include.second;
if (!include.second.empty() && include.second.back() != '>')
precomp_includes += "\"";
precomp_includes += "\n";
}
precomp_includes += "\n";
std::string expected_precomp_h =
"#include <benchmark/benchmark.h>\n\n" + precomp_includes;
CommonWriter::UpdateIfDifferent(dir_name + "/precomp.h", expected_precomp_h);
std::string expected_precomp_cc = "#include \"precomp.h\"\n\n";
CommonWriter::UpdateIfDifferent(dir_name + "/precomp.cc",
expected_precomp_cc);
std::string expected_benchmark_main = "#include \"precomp.h\"\n\n";
for (auto &dir : targets)
for (auto &obj_dir : dir.second.files["h"].fmap)
for (auto &obj : obj_dir.second)
if (obj.find("benchmark_") != std::string::npos) {
while (obj.back() == '\"') obj.pop_back();
expected_benchmark_main +=
"#include \"" +
obj.substr(obj.find_last_of('/') + 1, obj.size()) + "\"\n";
}
expected_benchmark_main += "\nBENCHMARK_MAIN();";
CommonWriter::UpdateIfDifferent(dir_name + "/benchmark_main.cc",
expected_benchmark_main);
std::string expected = CommonWriter::cmake_header_ + "\n";
std::map<std::string, std::set<std::string>> all_finds;
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
for (auto &lib : dir.second.libraries) {
auto &lib_info = libraries[lib];
if (!lib_info.find_command.empty()) {
auto &ref = all_finds[lib_info.find_command];
for (auto &comp : lib_info.components) ref.insert(comp);
}
}
}
for (auto &find : all_finds) {
expected += "find_package(" + find.first;
if (!find.second.empty()) {
expected += " COMPONENTS\n";
for (auto &mod : find.second) expected += " " + mod + "\n";
}
expected += ")\n";
}
expected +=
"\nset(cpp_files\n"
" benchmark_main.cc\n"
" precomp.h\n"
" precomp.cc\n"
")\n\n"
"add_msvc_precompiled_header(\"precomp.h\" \"precomp.cc\" cpp_files)\n"
"add_executable(" +
proj_name + " ${cpp_files})\n\n";
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
for (auto &d : dir.second.directories)
if (!d.empty())
include_dirs.insert("." + dir.first + d.substr(1, d.size()));
for (auto &d : dir.second.include_dirs)
if (!d.empty()) include_dirs.insert(d);
for (auto &lib : dir.second.libraries)
for (auto &inc : libraries[lib].includes) include_dirs.insert(inc);
}
#ifdef WindowsBuild
include_dirs.insert("D:/API/GoogleBenchmark/include");
#endif
expected += "include_directories(" + proj_name + "\n";
for (auto &include : include_dirs) expected += " " + include + "\n";
expected += ")\n\n";
std::set<std::string> link_libraries;
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
if (dir.first.find("shared_") != std::string::npos) continue;
if (dir.first.find("benchmark_") != std::string::npos) continue;
std::string dir_n =
dir.first.substr(dir.first.find_last_of('/') + 1, dir.first.size());
for (auto &lib : dir.second.libraries)
for (auto &l : libraries[lib].libs) link_libraries.insert(l);
for (auto &ext : ext) {
for (auto &obj_dir : dir.second.files[ext].fmap) {
for (auto &obj : obj_dir.second) {
if (obj.find("main.") != std::string::npos) continue;
#ifdef WindowsBuild
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) +
".dir/";
for (auto &conf : CommonWriter::configs_)
obj_file_str += "$<$<CONFIG:" + conf + ">:" + conf + ">";
obj_file_str +=
"/" +
obj.substr(obj.find_last_of('/') + 1,
obj.find_last_of('.') - obj.find_last_of('/')) +
"obj";
#else
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/CMakeFiles/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) +
".dir/";
obj_file_str += obj + ".o";
#endif
link_libraries.insert(obj_file_str);
}
}
}
for (auto &obj : dir.second.moc_files) {
if (obj.find("main.") != std::string::npos) continue;
#ifdef WindowsBuild
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) + ".dir/";
for (auto &conf : CommonWriter::configs_)
obj_file_str += "$<$<CONFIG:" + conf + ">:" + conf + ">";
obj_file_str +=
"/moc_" +
obj.substr(obj.find_last_of('/') + 1,
obj.find_last_of('.') - obj.find_last_of('/')) +
"obj";
#else
std::string obj_file_str =
"${CMAKE_CURRENT_BINARY_DIR}/../" + dir_n + "/CMakeFiles/" +
dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size()) + ".dir/";
obj_file_str += obj.substr(0, obj.find_last_of('/')) + "moc_" +
obj.substr(obj.find_last_of('/') + 1, obj.size()) + ".o";
#endif
link_libraries.insert(obj_file_str);
}
}
#ifdef WindowsBuild
link_libraries.insert("Shlwapi.lib");
link_libraries.insert("optimized D:/API/GoogleBenchmark/lib/benchmark.lib");
link_libraries.insert("debug D:/API/GoogleBenchmark/lib/benchmarkd.lib");
#else
link_libraries.insert("libbenchmark.so");
link_libraries.insert("libpthread.so");
#endif
expected += "target_link_libraries(" + proj_name + "\n";
for (auto &lib : link_libraries) expected += " " + lib + "\n";
expected += ")\n\n";
#ifdef WindowsBuild
std::string shared_ext = ".dll";
std::string shared_prefix = "";
#else
std::string shared_ext = ".so";
std::string shared_prefix = "lib";
#endif
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
std::set<std::string> libs;
for (auto &dep : dir.second.dependencies)
for (auto &lib : targets["./" + dep].libraries)
if (!libraries[lib].dlls.empty()) libs.insert(lib);
for (auto &lib : dir.second.libraries)
if (!libraries[lib].dlls.empty()) libs.insert(lib);
if (!libs.empty())
expected += "add_custom_command(TARGET " + proj_name + " POST_BUILD\n";
for (auto &lib : libs) {
for (int i = 0; i < libraries[lib].dlls.size(); ++i) {
auto &dll = libraries[lib].dlls[i];
auto &debug_dll = libraries[lib].debug_dlls.size() > i
? libraries[lib].debug_dlls[i]
: dll;
expected +=
" COMMAND ${CMAKE_COMMAND} ARGS -E copy_if_different\n \"";
for (auto &conf : CommonWriter::configs_) {
if (!conf.empty()) expected += "$<$<CONFIG:" + conf + ">:";
expected += shared_prefix +
(conf.compare("Debug") == 0
? debug_dll + libraries[lib].debug_suffix
: dll) +
shared_ext;
if (!conf.empty()) expected += ">";
}
expected += "\"\n \"";
for (auto &conf : CommonWriter::configs_) {
if (!conf.empty()) expected += "$<$<CONFIG:" + conf + ">:";
expected += "${CMAKE_CURRENT_BINARY_DIR}/Build_Output/bin/";
if (!conf.empty()) expected += conf + "/";
expected +=
shared_prefix +
(conf.compare("Debug") == 0
? debug_dll.substr(debug_dll.find_last_of('/') + 1,
debug_dll.size()) +
libraries[lib].debug_suffix
: dll.substr(dll.find_last_of('/') + 1, dll.size())) +
shared_ext;
if (!conf.empty()) expected += ">";
}
expected += "\"\n";
}
}
if (!libs.empty()) expected += ")\n\n";
}
expected += "add_dependencies(" + proj_name;
for (auto &dir : targets) {
if (dir.first.find("test_") != std::string::npos) continue;
std::string dir_n =
dir.first.substr(dir.first.find_last_of('/') + 1, dir.first.size());
dir_n = dir_n.substr(dir_n.find_first_of('_') + 1, dir_n.size());
expected += " " + dir_n;
}
expected += " ALL_PRE_BUILD)";
CommonWriter::UpdateIfDifferent(dir_name + "/CMakeLists.txt", expected);
}
bool BenchmarktargetWriter::MainUpdateNeeded(
std::string dir_name,
std::map<std::string, RepoSearcher::directory> &targets) {
if (!std::filesystem::exists(dir_name + "/benchmark_main.cc")) return true;
std::ifstream bench_main(dir_name + "/benchmark_main.cc");
std::set<std::string> bench_files, check_set;
for (auto &dir : targets)
for (auto &obj_dir : dir.second.files["h"].fmap)
for (auto &obj : obj_dir.second)
if (obj.find("benchmark_") != std::string::npos)
bench_files.insert(obj.substr(obj.find_last_of('/') + 1, obj.size()));
std::string line;
while (!bench_main.eof()) {
std::getline(bench_main, line);
if (line.find("#include") != std::string::npos) {
auto it = bench_files.find(
line.substr(line.find_first_of('\"') + 1,
line.find_last_of('\"') - line.find_first_of('\"') - 1));
if (it != bench_files.end()) check_set.insert(*it);
}
}
bench_main.close();
return check_set.size() != bench_files.size();
}
<|endoftext|>
|
<commit_before><commit_msg>More tests for `yli::linear_algebra::Tensor3`.<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: gcach_vdev.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hdu $ $Date: 2000-11-17 09:40:08 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <gcach_vdev.hxx>
#include <svapp.hxx>
#include <bitmap.hxx>
#include <outfont.hxx>
#include <virdev.hxx>
#include <metric.hxx>
// =======================================================================
// VirtDevServerFont
// =======================================================================
// -----------------------------------------------------------------------
long VirtDevServerFont::FetchFontList( ImplDevFontList* pToAdd )
{
long nCount = 0;
// TODO: add fonts on server but not on client to the list
return nCount;
}
// -----------------------------------------------------------------------
void VirtDevServerFont::ClearFontList()
{
// TODO
}
// -----------------------------------------------------------------------
VirtDevServerFont* VirtDevServerFont::CreateFont( const ImplFontSelectData& rFSD )
{
VirtDevServerFont* pServerFont = NULL;
// TODO: search list of VirtDevServerFonts, return NULL if not found
// pServerFont = new VirtDevServerFont( rFSD );
return pServerFont;
}
// -----------------------------------------------------------------------
VirtDevServerFont::VirtDevServerFont( const ImplFontSelectData& rFSD )
: ServerFont( rFSD)
{}
// -----------------------------------------------------------------------
void VirtDevServerFont::FetchFontMetric( ImplFontMetricData& rTo, long& rFactor ) const
{
const ImplFontSelectData& aFSD = GetFontSelData();
Font aFont;
aFont.SetName ( aFSD.maName );
aFont.SetStyleName ( aFSD.maStyleName );
aFont.SetHeight ( aFSD.mnHeight );
aFont.SetWidth ( aFSD.mnWidth );
aFont.SetOrientation( aFSD.mnOrientation );
VirtualDevice vdev( 1 );
FontMetric aMetric( vdev.GetFontMetric( aFont ) );
rFactor = 1;
rTo.mnWidth = aFSD.mnWidth;
rTo.mnAscent = aMetric.GetAscent();
rTo.mnDescent = aMetric.GetDescent();
rTo.mnLeading = aMetric.GetLeading();
rTo.mnSlant = aMetric.GetSlant();
rTo.meType = aMetric.GetType();
rTo.mnFirstChar = 0x0020; // TODO: where to get this info
rTo.mnLastChar = 0xFFFE; // TODO: where to get this info
rTo.maName = aFSD.maName;
rTo.maStyleName = aFSD.maStyleName;
rTo.mnOrientation = aFSD.mnOrientation;
rTo.meFamily = aFSD.meFamily;
rTo.meCharSet = aFSD.meCharSet;
rTo.meWeight = aFSD.meWeight;
rTo.meItalic = aFSD.meItalic;
rTo.mePitch = aFSD.mePitch;
rTo.mbDevice = FALSE;
}
// -----------------------------------------------------------------------
int VirtDevServerFont::GetGlyphIndex( sal_Unicode aChar ) const
{
return aChar;
}
// -----------------------------------------------------------------------
void VirtDevServerFont::SetGlyphData( int nGlyphIndex, bool bWithBitmap, GlyphData& rGD ) const
{
Font aFont;
aFont.SetName ( GetFontSelData().maName );
aFont.SetStyleName ( GetFontSelData().maStyleName );
aFont.SetHeight ( GetFontSelData().mnHeight );
aFont.SetWidth ( GetFontSelData().mnWidth );
aFont.SetOrientation( GetFontSelData().mnOrientation );
VirtualDevice vdev( 1 );
vdev.SetFont( aFont );
// get glyph metrics
long nCharWidth;
vdev.GetCharWidth( nGlyphIndex, nGlyphIndex, &nCharWidth );
rGD.SetCharWidth( nCharWidth );
const Rectangle aRect = vdev.GetTextRect( aRect, nGlyphIndex );
rGD.SetOffset( aRect.Top(), aRect.Left() );
rGD.SetDelta( vdev.GetTextWidth( nGlyphIndex ), 0 );
const Size aSize( aRect.GetSize() );
rGD.SetSize( aSize );
if( bWithBitmap && !rGD.GetBitmap() )
{
// draw bitmap
vdev.SetOutputSizePixel( aSize, TRUE );
vdev.DrawText( Point(0,0)-rGD.GetMetric().GetOffset(), nGlyphIndex );
// create new glyph item
const Bitmap& rBitmap = vdev.GetBitmap( Point(0,0), aSize );
rGD.SetBitmap( new Bitmap( rBitmap ) );
}
}
// -----------------------------------------------------------------------
ULONG VirtDevServerFont::GetKernPairs( ImplKernPairData** ppImplKernPairs ) const
{
Font aFont;
aFont.SetName ( GetFontSelData().maName );
aFont.SetStyleName ( GetFontSelData().maStyleName );
aFont.SetHeight ( GetFontSelData().mnHeight );
aFont.SetWidth ( GetFontSelData().mnWidth );
aFont.SetOrientation( GetFontSelData().mnOrientation );
VirtualDevice vdev( 1 );
vdev.SetFont( aFont );
ULONG nPairs = vdev.GetKerningPairCount();
if( nPairs > 0 )
{
KerningPair* pKernPairs = new KerningPair[ nPairs ];
vdev.GetKerningPairs( nPairs, pKernPairs );
*ppImplKernPairs = new ImplKernPairData[ nPairs ];
ImplKernPairData* pImplKernPair = *ppImplKernPairs;
for ( ULONG n = 0; n < nPairs; n++ )
{
pImplKernPair->mnChar1 = pKernPairs->nChar1;
pImplKernPair->mnChar2 = pKernPairs->nChar2;
pImplKernPair->mnKern = pKernPairs->nKern;
++pImplKernPair;
++pKernPairs;
}
}
return nPairs;
}
// -----------------------------------------------------------------------
bool VirtDevServerFont::GetGlyphOutline( int nGlyphIndex, bool bOptimize, PolyPolygon& rPolyPoly ) const
{
Font aFont;
aFont.SetName ( GetFontSelData().maName );
aFont.SetStyleName ( GetFontSelData().maStyleName );
aFont.SetHeight ( GetFontSelData().mnHeight );
aFont.SetWidth ( GetFontSelData().mnWidth );
aFont.SetOrientation( GetFontSelData().mnOrientation );
VirtualDevice vdev( 1 );
vdev.SetFont( aFont );
return vdev.GetGlyphOutline( nGlyphIndex, rPolyPoly, bOptimize);
}
// =======================================================================
<commit_msg>fix memory leak<commit_after>/*************************************************************************
*
* $RCSfile: gcach_vdev.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hdu $ $Date: 2000-11-17 10:41:29 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <gcach_vdev.hxx>
#include <svapp.hxx>
#include <bitmap.hxx>
#include <outfont.hxx>
#include <virdev.hxx>
#include <metric.hxx>
// =======================================================================
// VirtDevServerFont
// =======================================================================
// -----------------------------------------------------------------------
long VirtDevServerFont::FetchFontList( ImplDevFontList* pToAdd )
{
long nCount = 0;
// TODO: add fonts on server but not on client to the list
return nCount;
}
// -----------------------------------------------------------------------
void VirtDevServerFont::ClearFontList()
{
// TODO
}
// -----------------------------------------------------------------------
VirtDevServerFont* VirtDevServerFont::CreateFont( const ImplFontSelectData& rFSD )
{
VirtDevServerFont* pServerFont = NULL;
// TODO: search list of VirtDevServerFonts, return NULL if not found
// pServerFont = new VirtDevServerFont( rFSD );
return pServerFont;
}
// -----------------------------------------------------------------------
VirtDevServerFont::VirtDevServerFont( const ImplFontSelectData& rFSD )
: ServerFont( rFSD)
{}
// -----------------------------------------------------------------------
void VirtDevServerFont::FetchFontMetric( ImplFontMetricData& rTo, long& rFactor ) const
{
const ImplFontSelectData& aFSD = GetFontSelData();
Font aFont;
aFont.SetName ( aFSD.maName );
aFont.SetStyleName ( aFSD.maStyleName );
aFont.SetHeight ( aFSD.mnHeight );
aFont.SetWidth ( aFSD.mnWidth );
aFont.SetOrientation( aFSD.mnOrientation );
VirtualDevice vdev( 1 );
FontMetric aMetric( vdev.GetFontMetric( aFont ) );
rFactor = 1;
rTo.mnAscent = aMetric.GetAscent();
rTo.mnDescent = aMetric.GetDescent();
rTo.mnLeading = aMetric.GetLeading();
rTo.mnSlant = aMetric.GetSlant();
rTo.meType = aMetric.GetType();
rTo.mnFirstChar = 0x0020; // TODO: where to get this info?
rTo.mnLastChar = 0xFFFE; // TODO: where to get this info?
rTo.mnWidth = aFSD.mnWidth;
rTo.maName = aFSD.maName;
rTo.maStyleName = aFSD.maStyleName;
rTo.mnOrientation = aFSD.mnOrientation;
rTo.meFamily = aFSD.meFamily;
rTo.meCharSet = aFSD.meCharSet;
rTo.meWeight = aFSD.meWeight;
rTo.meItalic = aFSD.meItalic;
rTo.mePitch = aFSD.mePitch;
rTo.mbDevice = FALSE;
}
// -----------------------------------------------------------------------
int VirtDevServerFont::GetGlyphIndex( sal_Unicode aChar ) const
{
return aChar;
}
// -----------------------------------------------------------------------
void VirtDevServerFont::SetGlyphData( int nGlyphIndex, bool bWithBitmap, GlyphData& rGD ) const
{
Font aFont;
aFont.SetName ( GetFontSelData().maName );
aFont.SetStyleName ( GetFontSelData().maStyleName );
aFont.SetHeight ( GetFontSelData().mnHeight );
aFont.SetWidth ( GetFontSelData().mnWidth );
aFont.SetOrientation( GetFontSelData().mnOrientation );
VirtualDevice vdev( 1 );
vdev.SetFont( aFont );
// get glyph metrics
long nCharWidth;
vdev.GetCharWidth( nGlyphIndex, nGlyphIndex, &nCharWidth );
rGD.SetCharWidth( nCharWidth );
const Rectangle aRect = vdev.GetTextRect( aRect, nGlyphIndex );
rGD.SetOffset( aRect.Top(), aRect.Left() );
rGD.SetDelta( vdev.GetTextWidth( nGlyphIndex ), 0 );
const Size aSize( aRect.GetSize() );
rGD.SetSize( aSize );
if( bWithBitmap && !rGD.GetBitmap() )
{
// draw bitmap
vdev.SetOutputSizePixel( aSize, TRUE );
vdev.DrawText( Point(0,0)-rGD.GetMetric().GetOffset(), nGlyphIndex );
// create new glyph item
const Bitmap& rBitmap = vdev.GetBitmap( Point(0,0), aSize );
rGD.SetBitmap( new Bitmap( rBitmap ) );
}
}
// -----------------------------------------------------------------------
ULONG VirtDevServerFont::GetKernPairs( ImplKernPairData** ppImplKernPairs ) const
{
Font aFont;
aFont.SetName ( GetFontSelData().maName );
aFont.SetStyleName ( GetFontSelData().maStyleName );
aFont.SetHeight ( GetFontSelData().mnHeight );
aFont.SetWidth ( GetFontSelData().mnWidth );
aFont.SetOrientation( GetFontSelData().mnOrientation );
VirtualDevice vdev( 1 );
vdev.SetFont( aFont );
ULONG nPairs = vdev.GetKerningPairCount();
if( nPairs > 0 )
{
KerningPair* const pKernPairs = new KerningPair[ nPairs ];
vdev.GetKerningPairs( nPairs, pKernPairs );
*ppImplKernPairs = new ImplKernPairData[ nPairs ];
ImplKernPairData* pTo = *ppImplKernPairs;
KerningPair* pFrom = pKernPairs;
for ( ULONG n = 0; n < nPairs; n++ )
{
pTo->mnChar1 = pFrom->nChar1;
pTo->mnChar2 = pFrom->nChar2;
pTo->mnKern = pFrom->nKern;
++pFrom;
++pTo;
}
delete[] pKernPairs;
}
return nPairs;
}
// -----------------------------------------------------------------------
bool VirtDevServerFont::GetGlyphOutline( int nGlyphIndex, bool bOptimize, PolyPolygon& rPolyPoly ) const
{
Font aFont;
aFont.SetName ( GetFontSelData().maName );
aFont.SetStyleName ( GetFontSelData().maStyleName );
aFont.SetHeight ( GetFontSelData().mnHeight );
aFont.SetWidth ( GetFontSelData().mnWidth );
aFont.SetOrientation( GetFontSelData().mnOrientation );
VirtualDevice vdev( 1 );
vdev.SetFont( aFont );
return vdev.GetGlyphOutline( nGlyphIndex, rPolyPoly, bOptimize);
}
// =======================================================================
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gtkobject.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2006-08-11 17:46:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <plugins/gtk/gtkobject.hxx>
#include <plugins/gtk/gtkframe.hxx>
#include <plugins/gtk/gtkdata.hxx>
#include <plugins/gtk/gtkinst.hxx>
GtkSalObject::GtkSalObject( GtkSalFrame* pParent )
: m_pSocket( NULL ),
m_pRegion( NULL )
{
if( pParent )
{
// our plug window
m_pSocket = gtk_drawing_area_new();
// insert into container
gtk_fixed_put( pParent->getFixedContainer(),
m_pSocket,
0, 0 );
// realize so we can get a window id
gtk_widget_realize( m_pSocket );
// make it transparent; some plugins may not insert
// their own window here but use the socket window itself
gtk_widget_set_app_paintable( m_pSocket, TRUE );
//system data
SalDisplay* pDisp = GetX11SalData()->GetDisplay();
m_aSystemData.pDisplay = pDisp->GetDisplay();
m_aSystemData.aWindow = GDK_WINDOW_XWINDOW(m_pSocket->window);
m_aSystemData.pSalFrame = NULL;
m_aSystemData.pWidget = m_pSocket;
m_aSystemData.pVisual = pDisp->GetVisual()->GetVisual();
m_aSystemData.nDepth = pDisp->GetVisual()->GetDepth();
m_aSystemData.aColormap = pDisp->GetColormap().GetXColormap();
m_aSystemData.pAppContext = NULL;
m_aSystemData.aShellWindow = GDK_WINDOW_XWINDOW(GTK_WIDGET(pParent->getWindow())->window);
m_aSystemData.pShellWidget = GTK_WIDGET(pParent->getWindow());
g_signal_connect( G_OBJECT(m_pSocket), "button-press-event", G_CALLBACK(signalButton), this );
g_signal_connect( G_OBJECT(m_pSocket), "button-release-event", G_CALLBACK(signalButton), this );
g_signal_connect( G_OBJECT(m_pSocket), "focus-in-event", G_CALLBACK(signalFocus), this );
g_signal_connect( G_OBJECT(m_pSocket), "focus-out-event", G_CALLBACK(signalFocus), this );
g_signal_connect( G_OBJECT(m_pSocket), "destroy", G_CALLBACK(signalDestroy), this );
// #i59255# necessary due to sync effects with java child windows
pParent->Sync();
}
}
GtkSalObject::~GtkSalObject()
{
if( m_pRegion )
gdk_region_destroy( m_pRegion );
if( m_pSocket )
{
// remove socket from parent frame's fixed container
gtk_container_remove( GTK_CONTAINER(gtk_widget_get_parent(m_pSocket)),
m_pSocket );
// get rid of the socket
// actually the gtk_container_remove should let the ref count
// of the socket sink to 0 and destroy it (see signalDestroy)
// this is just a sanity check
if( m_pSocket )
gtk_widget_destroy( m_pSocket );
}
}
void GtkSalObject::ResetClipRegion()
{
if( m_pSocket )
gdk_window_shape_combine_region( m_pSocket->window, NULL, 0, 0 );
}
USHORT GtkSalObject::GetClipRegionType()
{
return SAL_OBJECT_CLIP_INCLUDERECTS;
}
void GtkSalObject::BeginSetClipRegion( ULONG )
{
if( m_pRegion )
gdk_region_destroy( m_pRegion );
m_pRegion = gdk_region_new();
}
void GtkSalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight )
{
GdkRectangle aRect;
aRect.x = nX;
aRect.y = nY;
aRect.width = nWidth;
aRect.height = nHeight;
gdk_region_union_with_rect( m_pRegion, &aRect );
}
void GtkSalObject::EndSetClipRegion()
{
if( m_pSocket )
gdk_window_shape_combine_region( m_pSocket->window, m_pRegion, 0, 0 );
}
void GtkSalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight )
{
if( m_pSocket )
{
GtkFixed* pContainer = GTK_FIXED(gtk_widget_get_parent(m_pSocket));
gtk_fixed_move( pContainer, m_pSocket, nX, nY );
gtk_widget_set_size_request( m_pSocket, nWidth, nHeight );
gtk_container_resize_children( GTK_CONTAINER(pContainer) );
}
}
void GtkSalObject::Show( BOOL bVisible )
{
if( m_pSocket )
{
if( bVisible )
gtk_widget_show( m_pSocket );
else
gtk_widget_hide( m_pSocket );
}
}
void GtkSalObject::Enable( BOOL )
{
}
void GtkSalObject::GrabFocus()
{
}
void GtkSalObject::SetBackground()
{
}
void GtkSalObject::SetBackground( SalColor )
{
}
const SystemEnvData* GtkSalObject::GetSystemData() const
{
return &m_aSystemData;
}
gboolean GtkSalObject::signalButton( GtkWidget*, GdkEventButton* pEvent, gpointer object )
{
GtkSalObject* pThis = (GtkSalObject*)object;
if( pEvent->type == GDK_BUTTON_PRESS )
{
GTK_YIELD_GRAB();
pThis->CallCallback( SALOBJ_EVENT_TOTOP, NULL );
}
return FALSE;
}
gboolean GtkSalObject::signalFocus( GtkWidget*, GdkEventFocus* pEvent, gpointer object )
{
GtkSalObject* pThis = (GtkSalObject*)object;
GTK_YIELD_GRAB();
pThis->CallCallback( pEvent->in ? SALOBJ_EVENT_GETFOCUS : SALOBJ_EVENT_LOSEFOCUS, NULL );
return FALSE;
}
void GtkSalObject::signalDestroy( GtkObject* pObj, gpointer object )
{
GtkSalObject* pThis = (GtkSalObject*)object;
if( GTK_WIDGET(pObj) == pThis->m_pSocket )
{
pThis->m_pSocket = NULL;
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.4); FILE MERGED 2006/09/01 17:58:02 kaib 1.9.4.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: gtkobject.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:30:31 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <plugins/gtk/gtkobject.hxx>
#include <plugins/gtk/gtkframe.hxx>
#include <plugins/gtk/gtkdata.hxx>
#include <plugins/gtk/gtkinst.hxx>
GtkSalObject::GtkSalObject( GtkSalFrame* pParent )
: m_pSocket( NULL ),
m_pRegion( NULL )
{
if( pParent )
{
// our plug window
m_pSocket = gtk_drawing_area_new();
// insert into container
gtk_fixed_put( pParent->getFixedContainer(),
m_pSocket,
0, 0 );
// realize so we can get a window id
gtk_widget_realize( m_pSocket );
// make it transparent; some plugins may not insert
// their own window here but use the socket window itself
gtk_widget_set_app_paintable( m_pSocket, TRUE );
//system data
SalDisplay* pDisp = GetX11SalData()->GetDisplay();
m_aSystemData.pDisplay = pDisp->GetDisplay();
m_aSystemData.aWindow = GDK_WINDOW_XWINDOW(m_pSocket->window);
m_aSystemData.pSalFrame = NULL;
m_aSystemData.pWidget = m_pSocket;
m_aSystemData.pVisual = pDisp->GetVisual()->GetVisual();
m_aSystemData.nDepth = pDisp->GetVisual()->GetDepth();
m_aSystemData.aColormap = pDisp->GetColormap().GetXColormap();
m_aSystemData.pAppContext = NULL;
m_aSystemData.aShellWindow = GDK_WINDOW_XWINDOW(GTK_WIDGET(pParent->getWindow())->window);
m_aSystemData.pShellWidget = GTK_WIDGET(pParent->getWindow());
g_signal_connect( G_OBJECT(m_pSocket), "button-press-event", G_CALLBACK(signalButton), this );
g_signal_connect( G_OBJECT(m_pSocket), "button-release-event", G_CALLBACK(signalButton), this );
g_signal_connect( G_OBJECT(m_pSocket), "focus-in-event", G_CALLBACK(signalFocus), this );
g_signal_connect( G_OBJECT(m_pSocket), "focus-out-event", G_CALLBACK(signalFocus), this );
g_signal_connect( G_OBJECT(m_pSocket), "destroy", G_CALLBACK(signalDestroy), this );
// #i59255# necessary due to sync effects with java child windows
pParent->Sync();
}
}
GtkSalObject::~GtkSalObject()
{
if( m_pRegion )
gdk_region_destroy( m_pRegion );
if( m_pSocket )
{
// remove socket from parent frame's fixed container
gtk_container_remove( GTK_CONTAINER(gtk_widget_get_parent(m_pSocket)),
m_pSocket );
// get rid of the socket
// actually the gtk_container_remove should let the ref count
// of the socket sink to 0 and destroy it (see signalDestroy)
// this is just a sanity check
if( m_pSocket )
gtk_widget_destroy( m_pSocket );
}
}
void GtkSalObject::ResetClipRegion()
{
if( m_pSocket )
gdk_window_shape_combine_region( m_pSocket->window, NULL, 0, 0 );
}
USHORT GtkSalObject::GetClipRegionType()
{
return SAL_OBJECT_CLIP_INCLUDERECTS;
}
void GtkSalObject::BeginSetClipRegion( ULONG )
{
if( m_pRegion )
gdk_region_destroy( m_pRegion );
m_pRegion = gdk_region_new();
}
void GtkSalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight )
{
GdkRectangle aRect;
aRect.x = nX;
aRect.y = nY;
aRect.width = nWidth;
aRect.height = nHeight;
gdk_region_union_with_rect( m_pRegion, &aRect );
}
void GtkSalObject::EndSetClipRegion()
{
if( m_pSocket )
gdk_window_shape_combine_region( m_pSocket->window, m_pRegion, 0, 0 );
}
void GtkSalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight )
{
if( m_pSocket )
{
GtkFixed* pContainer = GTK_FIXED(gtk_widget_get_parent(m_pSocket));
gtk_fixed_move( pContainer, m_pSocket, nX, nY );
gtk_widget_set_size_request( m_pSocket, nWidth, nHeight );
gtk_container_resize_children( GTK_CONTAINER(pContainer) );
}
}
void GtkSalObject::Show( BOOL bVisible )
{
if( m_pSocket )
{
if( bVisible )
gtk_widget_show( m_pSocket );
else
gtk_widget_hide( m_pSocket );
}
}
void GtkSalObject::Enable( BOOL )
{
}
void GtkSalObject::GrabFocus()
{
}
void GtkSalObject::SetBackground()
{
}
void GtkSalObject::SetBackground( SalColor )
{
}
const SystemEnvData* GtkSalObject::GetSystemData() const
{
return &m_aSystemData;
}
gboolean GtkSalObject::signalButton( GtkWidget*, GdkEventButton* pEvent, gpointer object )
{
GtkSalObject* pThis = (GtkSalObject*)object;
if( pEvent->type == GDK_BUTTON_PRESS )
{
GTK_YIELD_GRAB();
pThis->CallCallback( SALOBJ_EVENT_TOTOP, NULL );
}
return FALSE;
}
gboolean GtkSalObject::signalFocus( GtkWidget*, GdkEventFocus* pEvent, gpointer object )
{
GtkSalObject* pThis = (GtkSalObject*)object;
GTK_YIELD_GRAB();
pThis->CallCallback( pEvent->in ? SALOBJ_EVENT_GETFOCUS : SALOBJ_EVENT_LOSEFOCUS, NULL );
return FALSE;
}
void GtkSalObject::signalDestroy( GtkObject* pObj, gpointer object )
{
GtkSalObject* pThis = (GtkSalObject*)object;
if( GTK_WIDGET(pObj) == pThis->m_pSocket )
{
pThis->m_pSocket = NULL;
}
}
<|endoftext|>
|
<commit_before>#ifndef ITER_STARMAP_H_
#define ITER_STARMAP_H_
#include "iterbase.hpp"
#include <utility>
#include <type_traits>
#include <array>
#include <cassert>
#include <memory>
namespace iter {
// starmap with a container<T> where T is one of tuple, pair, array
template <typename Func, typename Container>
class StarMapper {
private:
Func func;
Container container;
public:
StarMapper(Func f, Container c)
: func(f),
container(std::forward<Container>(c))
{ }
class Iterator {
private:
Func func;
iterator_type<Container> sub_iter;
public:
Iterator(Func f, iterator_type<Container> iter)
: func(f),
sub_iter(iter)
{ }
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
Iterator operator++() {
++this->sub_iter;
return *this;
}
decltype(auto) operator*() {
return call_with_tuple(this->func, *this->sub_iter);
}
};
Iterator begin() {
return {this->func, std::begin(this->container)};
}
Iterator end() {
return {this->func, std::end(this->container)};
}
};
template <typename Func, typename Container>
StarMapper<Func, Container> starmap_helper(
Func func, Container&& container, std::false_type) {
return {func, std::forward<Container>(container)};
}
// starmap for a tuple or pair of tuples or pairs
template <typename Func, typename TupleType,
std::size_t Size =std::tuple_size<std::decay_t<TupleType>>::value>
class TupleStarMapper {
private:
class TupleExpanderBase {
protected:
// deduced return type to return of Func when called with
// one of TupleType
using ResultType =
decltype(call_with_tuple(
std::declval<Func&>(),
std::get<0>(std::declval<TupleType&>())));
public:
virtual ResultType call() = 0;
virtual ~TupleExpanderBase() { }
};
template <std::size_t Idx>
class TupleExpander : public TupleExpanderBase {
private:
Func func;
TupleType& tup;
public:
TupleExpander(Func f, TupleType& t)
: func(f),
tup(t)
{ }
typename TupleExpanderBase::ResultType call() override {
return call_with_tuple(
this->func, std::get<Idx>(this->tup));
}
};
private:
Func func;
TupleType tup;
std::array<std::unique_ptr<TupleExpanderBase>, Size> tuple_getters;
template <std::size_t... Is>
TupleStarMapper(Func f, TupleType t, std::index_sequence<Is...>)
: func(f),
tup(std::forward<TupleType>(t)),
tuple_getters(
{std::make_unique<TupleExpander<Is>>(func, tup)...})
{ }
public:
TupleStarMapper(Func f, TupleType t)
: TupleStarMapper(f, std::forward<TupleType>(t),
std::make_index_sequence<Size>{})
{ }
class Iterator {
private:
std::array<std::unique_ptr<TupleExpanderBase>, Size>&
tuple_getters;
std::size_t index;
public:
Iterator(std::array<
std::unique_ptr<TupleExpanderBase>, Size>& tg,
std::size_t i)
: tuple_getters(tg),
index{i}
{ }
decltype(auto) operator*() {
return this->tuple_getters[this->index]->call();
}
Iterator operator++() {
++this->index;
return *this;
}
bool operator!=(const Iterator& other) const {
return this->index != other.index;
}
};
Iterator begin() {
return {this->tuple_getters, 0};
}
Iterator end() {
return {this->tuple_getters, Size};
}
};
template <typename Func, typename TupleType>
TupleStarMapper<Func, TupleType> starmap_helper(
Func func, TupleType&& tup, std::true_type) {
return {func, std::forward<TupleType>(tup)};
}
// "tag dispatch" to differentiate between normal containers and
// tuple-like containers, things that work with std::get
template <typename T, typename U =void>
struct is_tuple_like : public std::false_type { };
template <typename T>
struct is_tuple_like<T, decltype(std::get<0>(std::declval<T>()), void())>
: public std::true_type { };
template <typename Func, typename Seq>
auto starmap(Func func, Seq&& sequence) {
return starmap_helper(
func, std::forward<Seq>(sequence),
is_tuple_like<Seq>{});
}
}
#endif // #ifndef ITER_STARMAP_H_
<commit_msg>uses anonymous template parm in is_tuple_like<commit_after>#ifndef ITER_STARMAP_H_
#define ITER_STARMAP_H_
#include "iterbase.hpp"
#include <utility>
#include <type_traits>
#include <array>
#include <cassert>
#include <memory>
namespace iter {
// starmap with a container<T> where T is one of tuple, pair, array
template <typename Func, typename Container>
class StarMapper {
private:
Func func;
Container container;
public:
StarMapper(Func f, Container c)
: func(f),
container(std::forward<Container>(c))
{ }
class Iterator {
private:
Func func;
iterator_type<Container> sub_iter;
public:
Iterator(Func f, iterator_type<Container> iter)
: func(f),
sub_iter(iter)
{ }
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
Iterator operator++() {
++this->sub_iter;
return *this;
}
decltype(auto) operator*() {
return call_with_tuple(this->func, *this->sub_iter);
}
};
Iterator begin() {
return {this->func, std::begin(this->container)};
}
Iterator end() {
return {this->func, std::end(this->container)};
}
};
template <typename Func, typename Container>
StarMapper<Func, Container> starmap_helper(
Func func, Container&& container, std::false_type) {
return {func, std::forward<Container>(container)};
}
// starmap for a tuple or pair of tuples or pairs
template <typename Func, typename TupleType,
std::size_t Size =std::tuple_size<std::decay_t<TupleType>>::value>
class TupleStarMapper {
private:
class TupleExpanderBase {
protected:
// deduced return type to return of Func when called with
// one of TupleType
using ResultType =
decltype(call_with_tuple(
std::declval<Func&>(),
std::get<0>(std::declval<TupleType&>())));
public:
virtual ResultType call() = 0;
virtual ~TupleExpanderBase() { }
};
template <std::size_t Idx>
class TupleExpander : public TupleExpanderBase {
private:
Func func;
TupleType& tup;
public:
TupleExpander(Func f, TupleType& t)
: func(f),
tup(t)
{ }
typename TupleExpanderBase::ResultType call() override {
return call_with_tuple(
this->func, std::get<Idx>(this->tup));
}
};
private:
Func func;
TupleType tup;
std::array<std::unique_ptr<TupleExpanderBase>, Size> tuple_getters;
template <std::size_t... Is>
TupleStarMapper(Func f, TupleType t, std::index_sequence<Is...>)
: func(f),
tup(std::forward<TupleType>(t)),
tuple_getters(
{std::make_unique<TupleExpander<Is>>(func, tup)...})
{ }
public:
TupleStarMapper(Func f, TupleType t)
: TupleStarMapper(f, std::forward<TupleType>(t),
std::make_index_sequence<Size>{})
{ }
class Iterator {
private:
std::array<std::unique_ptr<TupleExpanderBase>, Size>&
tuple_getters;
std::size_t index;
public:
Iterator(std::array<
std::unique_ptr<TupleExpanderBase>, Size>& tg,
std::size_t i)
: tuple_getters(tg),
index{i}
{ }
decltype(auto) operator*() {
return this->tuple_getters[this->index]->call();
}
Iterator operator++() {
++this->index;
return *this;
}
bool operator!=(const Iterator& other) const {
return this->index != other.index;
}
};
Iterator begin() {
return {this->tuple_getters, 0};
}
Iterator end() {
return {this->tuple_getters, Size};
}
};
template <typename Func, typename TupleType>
TupleStarMapper<Func, TupleType> starmap_helper(
Func func, TupleType&& tup, std::true_type) {
return {func, std::forward<TupleType>(tup)};
}
// "tag dispatch" to differentiate between normal containers and
// tuple-like containers, things that work with std::get
template <typename T, typename =void>
struct is_tuple_like : public std::false_type { };
template <typename T>
struct is_tuple_like<T, decltype(std::get<0>(std::declval<T>()), void())>
: public std::true_type { };
template <typename Func, typename Seq>
auto starmap(Func func, Seq&& sequence) {
return starmap_helper(
func, std::forward<Seq>(sequence),
is_tuple_like<Seq>{});
}
}
#endif // #ifndef ITER_STARMAP_H_
<|endoftext|>
|
<commit_before>#include <archie/fused/tuple.hpp>
#include <archie/fused/algorithm.hpp>
#include <memory>
#include <catch.hpp>
namespace {
namespace fused = archie::fused;
TEST_CASE("canUseFusedCompose", "[fused::algo]") {
{
auto x = fused::compose(fused::make_tuple, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
}
{
auto a = 1;
auto b = 2u;
auto c = '3';
auto const& x = fused::compose(fused::make_tuple(fused::front, fused::tie), a, b, c);
REQUIRE(&a == &x);
}
{
auto a = 1;
auto b = 2u;
auto c = '3';
auto opt = fused::make_tuple(fused::front, fused::tie);
auto const& x = fused::compose(opt, a, b, c);
REQUIRE(&a == &x);
}
}
TEST_CASE("canComposeFusedMakeTuple", "[fused::algo]") {
auto x = fused::apply(fused::make_tuple, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
}
TEST_CASE("canComposeFusedTie", "[fused::algo]") {
auto a = 1;
auto b = 2u;
auto c = '3';
auto x = fused::apply(fused::tie, a, b, c);
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(&a == &fused::get<0>(x));
REQUIRE(&b == &fused::get<1>(x));
REQUIRE(&c == &fused::get<2>(x));
}
TEST_CASE("canComposeFusedFront", "[fused::algo]") {
{
auto a = fused::apply(fused::front, fused::make_tuple(1, 2u, '3'));
REQUIRE(1 == a);
auto const& b = fused::apply(fused::front, a, 2u, '3');
REQUIRE(1 == b);
REQUIRE(&a == &b);
}
#if 0
{
auto x = fused::compose(fused::make_tuple(fused::front, fused::make_tuple), 1, 2u, '3');
REQUIRE(1 == x);
}
#endif
}
TEST_CASE("canComposeFusedBack", "[fused::algo]") {
auto a = fused::apply(fused::back, fused::make_tuple(1, 2u, '3'));
REQUIRE('3' == a);
auto const& b = fused::apply(fused::back, 1, 2u, a);
REQUIRE('3' == b);
REQUIRE(&a == &b);
}
TEST_CASE("canComposeFusedForEach", "[fused::algo]") {
{
auto i = 0u;
auto f = [&i](auto&&) { ++i; };
fused::apply(fused::for_each, fused::make_tuple(f, 2u, '3'));
fused::apply(fused::for_each, f, 2u, '3');
REQUIRE(4 == i);
}
{
auto i = 0u;
auto f = [&i](auto&&) { ++i; };
auto opt = fused::make_tuple(fused::for_each, fused::make_tuple);
fused::compose(opt, f, 1, 2u, '3', 4.0);
REQUIRE(4 == i);
}
}
TEST_CASE("canComposeFusedForEachOrder", "[fused::algo]") {
auto i = 0u;
auto f = [&i](auto&& x) {
i *= 10;
i += x;
};
fused::for_each_forward(f, 1u, 2u, 3u);
REQUIRE(123u == i);
i = 0u;
fused::for_each_backward(f, 1u, 2u, 3u);
REQUIRE(321u == i);
}
TEST_CASE("canComposeFusedTransform", "[fused::algo]") {
{
auto f = [](auto&& x) { return ++x; };
auto x = fused::apply(fused::transform, f, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(2 == fused::get<0>(x));
REQUIRE(3u == fused::get<1>(x));
REQUIRE('4' == fused::get<2>(x));
}
{
auto f = [](auto&& x) { return std::make_unique<std::remove_reference_t<decltype(x)>>(x); };
auto opt = fused::make_tuple(fused::transform, fused::make_tuple);
auto x = fused::compose(opt, f, 1, 2u, '3', 4.0);
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 4u, "");
REQUIRE(fused::get<0>(x) != nullptr);
REQUIRE(1 == *fused::get<0>(x));
}
}
TEST_CASE("canComposeFusedConcat", "[fused::algo]") {
auto x = fused::apply(fused::concat, fused::make_tuple(1, 2u, '3'), 4.0);
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 4u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
REQUIRE(4.0 == fused::get<3>(x));
auto y =
fused::apply(fused::concat, fused::make_tuple(1, 2u, '3'), fused::make_tuple(4.0, 5, 6u));
static_assert(fused::tuple_size(fused::id<decltype(y)>) == 6u, "");
REQUIRE(1 == fused::get<0>(y));
REQUIRE(2u == fused::get<1>(y));
REQUIRE('3' == fused::get<2>(y));
REQUIRE(4.0 == fused::get<3>(y));
REQUIRE(5 == fused::get<4>(y));
REQUIRE(6u == fused::get<5>(y));
}
TEST_CASE("canComposeFusedZip", "[fused::algo]") {
auto x =
fused::apply(fused::concat, fused::make_tuple(1, 2u, '3'), fused::make_tuple(4.0, 5, 6u));
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 6u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
REQUIRE(4.0 == fused::get<3>(x));
REQUIRE(5 == fused::get<4>(x));
REQUIRE(6u == fused::get<5>(x));
}
TEST_CASE("canComposeFusedTail", "[fused::algo]") {
auto x = fused::tail(fused::make_tuple(1, 2u, '3'));
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 2u, "");
REQUIRE(2u == fused::get<0>(x));
REQUIRE('3' == fused::get<1>(x));
}
TEST_CASE("canComposeFusedFind", "[fused::algo]") {
auto x = fused::apply(fused::find<unsigned>, 1, 2u, '3', 4u);
REQUIRE(2u == x);
auto y = fused::apply(fused::find<char>, 1, 2u, '3', 4u);
REQUIRE('3' == y);
}
TEST_CASE("canComposeFusedFindIf", "[fused::algo]") {
auto x = fused::apply(fused::find_if<std::is_unsigned>, 1, 2u, '3', 4u);
REQUIRE(2u == x);
auto y = fused::apply(fused::find_if<std::is_signed>, 1, 2u, '3', 4u);
REQUIRE(1 == y);
}
TEST_CASE("canComposeFusedTake", "[fused::algo]") {
auto x = fused::apply(fused::take<2>, fused::make_tuple(1, 2u, '3'));
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 2u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
auto y = fused::apply(fused::take<3>, 4.0, '3', 2u, 1);
static_assert(fused::tuple_size(fused::id<decltype(y)>) == 3u, "");
REQUIRE(4.0 == fused::get<0>(y));
REQUIRE('3' == fused::get<1>(y));
REQUIRE(2u == fused::get<2>(y));
}
TEST_CASE("canComposeFusedNth", "[fused::algo]") {
auto x = fused::apply(fused::nth<0>, 1, 2u, '3');
auto y = fused::apply(fused::nth<1>, 1, 2u, '3');
auto z = fused::apply(fused::nth<2>, 1, 2u, '3');
REQUIRE(1 == x);
REQUIRE(2u == y);
REQUIRE('3' == z);
}
TEST_CASE("canComposeFusedConstruct", "[fused::algo]") {
using tuple_type = fused::tuple<int, unsigned, char>;
constexpr auto& ctor = fused::id<tuple_type>;
auto x = fused::apply(ctor, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
}
TEST_CASE("canComposeIndexOf", "[fused::algo]") {
{
auto x = fused::apply(fused::index_of<int>, 1, 2u, '3');
auto y = fused::apply(fused::index_of<unsigned>, 1, 2u, '3');
auto z = fused::apply(fused::index_of<char>, 1, 2u, '3');
REQUIRE(0 == x);
REQUIRE(1 == y);
REQUIRE(2 == z);
}
{
auto x = fused::apply(fused::index_of<int>, 1);
REQUIRE(0 == x);
}
{
auto x = fused::apply(fused::index_of<int>, fused::type_list<int, unsigned, char>);
auto y = fused::apply(fused::index_of<unsigned>, fused::type_list<int, unsigned, char>);
auto z = fused::apply(fused::index_of<char>, fused::type_list<int, unsigned, char>);
REQUIRE(0 == x);
REQUIRE(1 == y);
REQUIRE(2 == z);
}
}
}
<commit_msg>disable failing code<commit_after>#include <archie/fused/tuple.hpp>
#include <archie/fused/algorithm.hpp>
#include <memory>
#include <catch.hpp>
namespace {
namespace fused = archie::fused;
TEST_CASE("canUseFusedCompose", "[fused::algo]") {
{
auto x = fused::compose(fused::make_tuple, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
}
#if 0
{
auto a = 1;
auto b = 2u;
auto c = '3';
auto const& x = fused::compose(fused::make_tuple(fused::front, fused::tie), a, b, c);
REQUIRE(&a == &x);
}
{
auto a = 1;
auto b = 2u;
auto c = '3';
auto opt = fused::make_tuple(fused::front, fused::tie);
auto const& x = fused::compose(opt, a, b, c);
REQUIRE(&a == &x);
}
#endif
}
TEST_CASE("canComposeFusedMakeTuple", "[fused::algo]") {
auto x = fused::apply(fused::make_tuple, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
}
TEST_CASE("canComposeFusedTie", "[fused::algo]") {
auto a = 1;
auto b = 2u;
auto c = '3';
auto x = fused::apply(fused::tie, a, b, c);
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(&a == &fused::get<0>(x));
REQUIRE(&b == &fused::get<1>(x));
REQUIRE(&c == &fused::get<2>(x));
}
TEST_CASE("canComposeFusedFront", "[fused::algo]") {
{
auto a = fused::apply(fused::front, fused::make_tuple(1, 2u, '3'));
REQUIRE(1 == a);
auto const& b = fused::apply(fused::front, a, 2u, '3');
REQUIRE(1 == b);
REQUIRE(&a == &b);
}
#if 0
{
auto x = fused::compose(fused::make_tuple(fused::front, fused::make_tuple), 1, 2u, '3');
REQUIRE(1 == x);
}
#endif
}
TEST_CASE("canComposeFusedBack", "[fused::algo]") {
auto a = fused::apply(fused::back, fused::make_tuple(1, 2u, '3'));
REQUIRE('3' == a);
auto const& b = fused::apply(fused::back, 1, 2u, a);
REQUIRE('3' == b);
REQUIRE(&a == &b);
}
TEST_CASE("canComposeFusedForEach", "[fused::algo]") {
{
auto i = 0u;
auto f = [&i](auto&&) { ++i; };
fused::apply(fused::for_each, fused::make_tuple(f, 2u, '3'));
fused::apply(fused::for_each, f, 2u, '3');
REQUIRE(4 == i);
}
{
auto i = 0u;
auto f = [&i](auto&&) { ++i; };
auto opt = fused::make_tuple(fused::for_each, fused::make_tuple);
fused::compose(opt, f, 1, 2u, '3', 4.0);
REQUIRE(4 == i);
}
}
TEST_CASE("canComposeFusedForEachOrder", "[fused::algo]") {
auto i = 0u;
auto f = [&i](auto&& x) {
i *= 10;
i += x;
};
fused::for_each_forward(f, 1u, 2u, 3u);
REQUIRE(123u == i);
i = 0u;
fused::for_each_backward(f, 1u, 2u, 3u);
REQUIRE(321u == i);
}
TEST_CASE("canComposeFusedTransform", "[fused::algo]") {
{
auto f = [](auto&& x) { return ++x; };
auto x = fused::apply(fused::transform, f, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(2 == fused::get<0>(x));
REQUIRE(3u == fused::get<1>(x));
REQUIRE('4' == fused::get<2>(x));
}
{
auto f = [](auto&& x) { return std::make_unique<std::remove_reference_t<decltype(x)>>(x); };
auto opt = fused::make_tuple(fused::transform, fused::make_tuple);
auto x = fused::compose(opt, f, 1, 2u, '3', 4.0);
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 4u, "");
REQUIRE(fused::get<0>(x) != nullptr);
REQUIRE(1 == *fused::get<0>(x));
}
}
TEST_CASE("canComposeFusedConcat", "[fused::algo]") {
auto x = fused::apply(fused::concat, fused::make_tuple(1, 2u, '3'), 4.0);
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 4u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
REQUIRE(4.0 == fused::get<3>(x));
auto y =
fused::apply(fused::concat, fused::make_tuple(1, 2u, '3'), fused::make_tuple(4.0, 5, 6u));
static_assert(fused::tuple_size(fused::id<decltype(y)>) == 6u, "");
REQUIRE(1 == fused::get<0>(y));
REQUIRE(2u == fused::get<1>(y));
REQUIRE('3' == fused::get<2>(y));
REQUIRE(4.0 == fused::get<3>(y));
REQUIRE(5 == fused::get<4>(y));
REQUIRE(6u == fused::get<5>(y));
}
TEST_CASE("canComposeFusedZip", "[fused::algo]") {
auto x =
fused::apply(fused::concat, fused::make_tuple(1, 2u, '3'), fused::make_tuple(4.0, 5, 6u));
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 6u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
REQUIRE(4.0 == fused::get<3>(x));
REQUIRE(5 == fused::get<4>(x));
REQUIRE(6u == fused::get<5>(x));
}
TEST_CASE("canComposeFusedTail", "[fused::algo]") {
auto x = fused::tail(fused::make_tuple(1, 2u, '3'));
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 2u, "");
REQUIRE(2u == fused::get<0>(x));
REQUIRE('3' == fused::get<1>(x));
}
TEST_CASE("canComposeFusedFind", "[fused::algo]") {
auto x = fused::apply(fused::find<unsigned>, 1, 2u, '3', 4u);
REQUIRE(2u == x);
auto y = fused::apply(fused::find<char>, 1, 2u, '3', 4u);
REQUIRE('3' == y);
}
TEST_CASE("canComposeFusedFindIf", "[fused::algo]") {
auto x = fused::apply(fused::find_if<std::is_unsigned>, 1, 2u, '3', 4u);
REQUIRE(2u == x);
auto y = fused::apply(fused::find_if<std::is_signed>, 1, 2u, '3', 4u);
REQUIRE(1 == y);
}
TEST_CASE("canComposeFusedTake", "[fused::algo]") {
auto x = fused::apply(fused::take<2>, fused::make_tuple(1, 2u, '3'));
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 2u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
auto y = fused::apply(fused::take<3>, 4.0, '3', 2u, 1);
static_assert(fused::tuple_size(fused::id<decltype(y)>) == 3u, "");
REQUIRE(4.0 == fused::get<0>(y));
REQUIRE('3' == fused::get<1>(y));
REQUIRE(2u == fused::get<2>(y));
}
TEST_CASE("canComposeFusedNth", "[fused::algo]") {
auto x = fused::apply(fused::nth<0>, 1, 2u, '3');
auto y = fused::apply(fused::nth<1>, 1, 2u, '3');
auto z = fused::apply(fused::nth<2>, 1, 2u, '3');
REQUIRE(1 == x);
REQUIRE(2u == y);
REQUIRE('3' == z);
}
TEST_CASE("canComposeFusedConstruct", "[fused::algo]") {
using tuple_type = fused::tuple<int, unsigned, char>;
constexpr auto& ctor = fused::id<tuple_type>;
auto x = fused::apply(ctor, 1, 2u, '3');
static_assert(fused::tuple_size(fused::id<decltype(x)>) == 3u, "");
REQUIRE(1 == fused::get<0>(x));
REQUIRE(2u == fused::get<1>(x));
REQUIRE('3' == fused::get<2>(x));
}
TEST_CASE("canComposeIndexOf", "[fused::algo]") {
{
auto x = fused::apply(fused::index_of<int>, 1, 2u, '3');
auto y = fused::apply(fused::index_of<unsigned>, 1, 2u, '3');
auto z = fused::apply(fused::index_of<char>, 1, 2u, '3');
REQUIRE(0 == x);
REQUIRE(1 == y);
REQUIRE(2 == z);
}
{
auto x = fused::apply(fused::index_of<int>, 1);
REQUIRE(0 == x);
}
{
auto x = fused::apply(fused::index_of<int>, fused::type_list<int, unsigned, char>);
auto y = fused::apply(fused::index_of<unsigned>, fused::type_list<int, unsigned, char>);
auto z = fused::apply(fused::index_of<char>, fused::type_list<int, unsigned, char>);
REQUIRE(0 == x);
REQUIRE(1 == y);
REQUIRE(2 == z);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <thrift/lib/cpp/concurrency/Mutex-impl.h>
#include <gtest/gtest.h>
#include "common/concurrency/Timeout.h"
#include "common/time/TimeConstants.h"
#include <thrift/lib/cpp/concurrency/Util.h>
#include <thread>
#include <vector>
using namespace std;
using namespace facebook;
using namespace apache::thrift::concurrency;
const int kTimeoutUsec = 10*kUsecPerMs; // 10ms
const int kTimeoutMs = kTimeoutUsec / kUsecPerMs;
const int kMaxReaders = 10;
const int kMicroSecInMilliSec = 1000;
// user operation time on the lock in milliseconds
const int kOpTimeInMs = 100;
TEST(RWMutexTest, Max_Readers ) {
ReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
TEST(RWMutexTest, Writer_Wait_Readers ) {
ReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
}
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
l.release();
// Testing timeout
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
threads_.push_back(std::thread([this, &l] {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
}));
}
// make sure reader lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread thread1 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread thread2 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
for (auto& t : threads_) {
t.join();
}
thread1.join();
thread2.join();
}
TEST(RWMutexTest, Readers_Wait_Writer) {
ReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
l.release();
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
l.release();
}
// Testing Timeout
std::thread wrThread = std::thread([&l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
// wait shorter than the operation time will timeout
threads_.push_back(std::thread([&l] {
EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));
}));
// wait longer than the operation time will success
threads_.push_back(std::thread([&l] {
EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));
l.release();
}));
}
for (auto& t : threads_) {
t.join();
}
wrThread.join();
}
TEST(RWMutexTest, Writer_Wait_Writer) {
ReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
// Testing Timeout
std::thread wrThread1 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread wrThread2 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread wrThread3 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
wrThread1.join();
wrThread2.join();
wrThread3.join();
}
TEST(RWMutexTest, Read_Holders) {
ReadWriteMutex l;
RWGuard guard(l, false);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_TRUE(l.timedRead(kTimeoutMs));
l.release();
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
TEST(RWMutexTest, Write_Holders) {
ReadWriteMutex l;
RWGuard guard(l, true);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
TEST(MutexTest, Recursive_Holders) {
Mutex mutex(Mutex::RECURSIVE_INITIALIZER);
Guard g1(mutex);
{
Guard g2(mutex);
}
Guard g2(mutex);
}
TEST(NoStarveRWMutexTest, Max_Readers ) {
NoStarveReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
TEST(NoStarveRWMutexTest, Writer_Wait_Readers ) {
NoStarveReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
}
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
l.release();
// Testing timeout
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
threads_.push_back(std::thread([this, &l] {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
}));
}
// make sure reader lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread thread1 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread thread2 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
for (auto& t : threads_) {
t.join();
}
thread1.join();
thread2.join();
}
TEST(NoStarveRWMutexTest, Readers_Wait_Writer) {
NoStarveReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
l.release();
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
l.release();
}
// Testing Timeout
std::thread wrThread = std::thread([&l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
// wait shorter than the operation time will timeout
threads_.push_back(std::thread([&l] {
EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));
}));
// wait longer than the operation time will success
threads_.push_back(std::thread([&l] {
EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));
l.release();
}));
}
for (auto& t : threads_) {
t.join();
}
wrThread.join();
}
TEST(NoStarveRWMutexTest, Writer_Wait_Writer) {
NoStarveReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
// Testing Timeout
std::thread wrThread1 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread wrThread2 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread wrThread3 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
wrThread1.join();
wrThread2.join();
wrThread3.join();
}
TEST(NoStarveRWMutexTest, Read_Holders) {
NoStarveReadWriteMutex l;
RWGuard guard(l, false);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_TRUE(l.timedRead(kTimeoutMs));
l.release();
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
TEST(NoStarveRWMutexTest, Write_Holders) {
NoStarveReadWriteMutex l;
RWGuard guard(l, true);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
<commit_msg>Fix NoStarveRWMutexTest.Writer_Wait_Readers<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 <thrift/lib/cpp/concurrency/Mutex-impl.h>
#include <gtest/gtest.h>
#include "common/concurrency/Timeout.h"
#include "common/time/TimeConstants.h"
#include <thrift/lib/cpp/concurrency/Util.h>
#include <thread>
#include <condition_variable>
#include <vector>
using namespace std;
using namespace facebook;
using namespace apache::thrift::concurrency;
const int kTimeoutUsec = 10*kUsecPerMs; // 10ms
const int kTimeoutMs = kTimeoutUsec / kUsecPerMs;
const int kMaxReaders = 10;
const int kMicroSecInMilliSec = 1000;
// user operation time on the lock in milliseconds
const int kOpTimeInMs = 100;
TEST(RWMutexTest, Max_Readers ) {
ReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
TEST(RWMutexTest, Writer_Wait_Readers ) {
ReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
}
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
l.release();
// Testing timeout
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
threads_.push_back(std::thread([this, &l] {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
}));
}
// make sure reader lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread thread1 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread thread2 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
for (auto& t : threads_) {
t.join();
}
thread1.join();
thread2.join();
}
TEST(RWMutexTest, Readers_Wait_Writer) {
ReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
l.release();
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
l.release();
}
// Testing Timeout
std::thread wrThread = std::thread([&l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
// wait shorter than the operation time will timeout
threads_.push_back(std::thread([&l] {
EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));
}));
// wait longer than the operation time will success
threads_.push_back(std::thread([&l] {
EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));
l.release();
}));
}
for (auto& t : threads_) {
t.join();
}
wrThread.join();
}
TEST(RWMutexTest, Writer_Wait_Writer) {
ReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
// Testing Timeout
std::thread wrThread1 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread wrThread2 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread wrThread3 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
wrThread1.join();
wrThread2.join();
wrThread3.join();
}
TEST(RWMutexTest, Read_Holders) {
ReadWriteMutex l;
RWGuard guard(l, false);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_TRUE(l.timedRead(kTimeoutMs));
l.release();
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
TEST(RWMutexTest, Write_Holders) {
ReadWriteMutex l;
RWGuard guard(l, true);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
TEST(MutexTest, Recursive_Holders) {
Mutex mutex(Mutex::RECURSIVE_INITIALIZER);
Guard g1(mutex);
{
Guard g2(mutex);
}
Guard g2(mutex);
}
TEST(NoStarveRWMutexTest, Max_Readers ) {
NoStarveReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
TEST(NoStarveRWMutexTest, Writer_Wait_Readers ) {
NoStarveReadWriteMutex l;
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
}
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
l.release();
std::condition_variable cv;
std::mutex cv_m;
int readers = 0;
// Testing timeout
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
threads_.push_back(std::thread([&, this] {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
{
std::lock_guard<std::mutex> lk(cv_m);
readers++;
cv.notify_one();
}
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
}));
}
{
std::unique_lock<std::mutex> lk(cv_m);
cv.wait(lk, [&] {return readers == kMaxReaders;});
}
// wait shorter than the operation time will timeout
std::thread thread1 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread thread2 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
for (auto& t : threads_) {
t.join();
}
thread1.join();
thread2.join();
}
TEST(NoStarveRWMutexTest, Readers_Wait_Writer) {
NoStarveReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
l.release();
for (int i = 0; i < kMaxReaders; ++i) {
EXPECT_TRUE(l.timedRead(kTimeoutMs));
}
for (int i = 0; i < kMaxReaders; ++i) {
l.release();
}
// Testing Timeout
std::thread wrThread = std::thread([&l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
vector<std::thread> threads_;
for (int i = 0; i < kMaxReaders; ++i) {
// wait shorter than the operation time will timeout
threads_.push_back(std::thread([&l] {
EXPECT_FALSE(l.timedRead(0.5 * kOpTimeInMs));
}));
// wait longer than the operation time will success
threads_.push_back(std::thread([&l] {
EXPECT_TRUE(l.timedRead(1.5 * kOpTimeInMs));
l.release();
}));
}
for (auto& t : threads_) {
t.join();
}
wrThread.join();
}
TEST(NoStarveRWMutexTest, Writer_Wait_Writer) {
NoStarveReadWriteMutex l;
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
l.release();
// Testing Timeout
std::thread wrThread1 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(kTimeoutMs));
usleep(kOpTimeInMs * kMicroSecInMilliSec);
l.release();
});
// make sure wrThread lock the lock first
usleep(1000);
// wait shorter than the operation time will timeout
std::thread wrThread2 = std::thread([this, &l] {
EXPECT_FALSE(l.timedWrite(0.5 * kOpTimeInMs));
});
// wait longer than the operation time will success
std::thread wrThread3 = std::thread([this, &l] {
EXPECT_TRUE(l.timedWrite(1.5 * kOpTimeInMs));
l.release();
});
wrThread1.join();
wrThread2.join();
wrThread3.join();
}
TEST(NoStarveRWMutexTest, Read_Holders) {
NoStarveReadWriteMutex l;
RWGuard guard(l, false);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_TRUE(l.timedRead(kTimeoutMs));
l.release();
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
}
TEST(NoStarveRWMutexTest, Write_Holders) {
NoStarveReadWriteMutex l;
RWGuard guard(l, true);
EXPECT_FALSE(l.timedWrite(kTimeoutMs));
EXPECT_FALSE(l.timedRead(kTimeoutMs));
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (C) 2012 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file Block.h
*
* Controller library code
*/
#pragma once
#include <stdint.h>
#include <inttypes.h>
#include <containers/List.hpp>
#include <uORB/Publication.hpp>
#include <uORB/Subscription.hpp>
#include <controllib/block/BlockParam.hpp>
namespace control
{
static const uint16_t maxChildrenPerBlock = 100;
static const uint16_t maxParamsPerBlock = 100;
static const uint16_t maxSubscriptionsPerBlock = 100;
static const uint16_t maxPublicationsPerBlock = 100;
static const uint8_t blockNameLengthMax = 80;
// forward declaration
class BlockParamBase;
class SuperBlock;
/**
*/
class __EXPORT Block :
public ListNode<Block *>
{
public:
friend class BlockParamBase;
// methods
Block(SuperBlock *parent, const char *name);
void getName(char *name, size_t n);
virtual ~Block() {};
virtual void updateParams();
virtual void updateSubscriptions();
virtual void updatePublications();
virtual void setDt(float dt) { _dt = dt; }
// accessors
float getDt() { return _dt; }
protected:
// accessors
SuperBlock *getParent() { return _parent; }
List<uORB::SubscriptionNode *> &getSubscriptions() { return _subscriptions; }
List<uORB::PublicationNode *> &getPublications() { return _publications; }
List<BlockParamBase *> &getParams() { return _params; }
// attributes
const char *_name;
SuperBlock *_parent;
float _dt;
List<uORB::SubscriptionNode *> _subscriptions;
List<uORB::PublicationNode *> _publications;
List<BlockParamBase *> _params;
private:
/* this class has pointer data members and should not be copied (private constructor) */
Block(const control::Block &);
Block operator=(const control::Block &);
};
class __EXPORT SuperBlock :
public Block
{
public:
friend class Block;
// methods
SuperBlock(SuperBlock *parent, const char *name) :
Block(parent, name),
_children()
{
}
virtual ~SuperBlock() {};
virtual void setDt(float dt);
virtual void updateParams()
{
Block::updateParams();
if (getChildren().getHead() != NULL) { updateChildParams(); }
}
virtual void updateSubscriptions()
{
Block::updateSubscriptions();
if (getChildren().getHead() != NULL) { updateChildSubscriptions(); }
}
virtual void updatePublications()
{
Block::updatePublications();
if (getChildren().getHead() != NULL) { updateChildPublications(); }
}
protected:
// methods
List<Block *> &getChildren() { return _children; }
void updateChildParams();
void updateChildSubscriptions();
void updateChildPublications();
// attributes
List<Block *> _children;
};
} // namespace control
<commit_msg>controllib decrease blockNameLengthMax to 40<commit_after>/****************************************************************************
*
* Copyright (C) 2012 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file Block.h
*
* Controller library code
*/
#pragma once
#include <stdint.h>
#include <inttypes.h>
#include <containers/List.hpp>
#include <uORB/Publication.hpp>
#include <uORB/Subscription.hpp>
#include <controllib/block/BlockParam.hpp>
namespace control
{
static const uint16_t maxChildrenPerBlock = 100;
static const uint16_t maxParamsPerBlock = 100;
static const uint16_t maxSubscriptionsPerBlock = 100;
static const uint16_t maxPublicationsPerBlock = 100;
static const uint8_t blockNameLengthMax = 40;
// forward declaration
class BlockParamBase;
class SuperBlock;
/**
*/
class __EXPORT Block :
public ListNode<Block *>
{
public:
friend class BlockParamBase;
// methods
Block(SuperBlock *parent, const char *name);
void getName(char *name, size_t n);
virtual ~Block() {};
virtual void updateParams();
virtual void updateSubscriptions();
virtual void updatePublications();
virtual void setDt(float dt) { _dt = dt; }
// accessors
float getDt() { return _dt; }
protected:
// accessors
SuperBlock *getParent() { return _parent; }
List<uORB::SubscriptionNode *> &getSubscriptions() { return _subscriptions; }
List<uORB::PublicationNode *> &getPublications() { return _publications; }
List<BlockParamBase *> &getParams() { return _params; }
// attributes
const char *_name;
SuperBlock *_parent;
float _dt;
List<uORB::SubscriptionNode *> _subscriptions;
List<uORB::PublicationNode *> _publications;
List<BlockParamBase *> _params;
private:
/* this class has pointer data members and should not be copied (private constructor) */
Block(const control::Block &);
Block operator=(const control::Block &);
};
class __EXPORT SuperBlock :
public Block
{
public:
friend class Block;
// methods
SuperBlock(SuperBlock *parent, const char *name) :
Block(parent, name),
_children()
{
}
virtual ~SuperBlock() {};
virtual void setDt(float dt);
virtual void updateParams()
{
Block::updateParams();
if (getChildren().getHead() != NULL) { updateChildParams(); }
}
virtual void updateSubscriptions()
{
Block::updateSubscriptions();
if (getChildren().getHead() != NULL) { updateChildSubscriptions(); }
}
virtual void updatePublications()
{
Block::updatePublications();
if (getChildren().getHead() != NULL) { updateChildPublications(); }
}
protected:
// methods
List<Block *> &getChildren() { return _children; }
void updateChildParams();
void updateChildSubscriptions();
void updateChildPublications();
// attributes
List<Block *> _children;
};
} // namespace control
<|endoftext|>
|
<commit_before>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "DiscovererWorker.h"
#include "logging/Logger.h"
#include "Folder.h"
#include "Media.h"
#include "MediaLibrary.h"
#include "Device.h"
#include "utils/Filename.h"
#include "medialibrary/filesystem/Errors.h"
#include <cassert>
namespace medialibrary
{
DiscovererWorker::DiscovererWorker(MediaLibrary* ml )
: m_run( false )
, m_ml( ml )
{
}
DiscovererWorker::~DiscovererWorker()
{
stop();
}
void DiscovererWorker::addDiscoverer( std::unique_ptr<IDiscoverer> discoverer )
{
m_discoverers.push_back( std::move( discoverer ) );
}
void DiscovererWorker::stop()
{
bool running = true;
if ( m_run.compare_exchange_strong( running, false ) )
{
{
std::unique_lock<compat::Mutex> lock( m_mutex );
while ( m_tasks.empty() == false )
m_tasks.pop();
}
m_cond.notify_all();
m_thread.join();
}
}
bool DiscovererWorker::discover( const std::string& entryPoint )
{
if ( entryPoint.length() == 0 )
return false;
LOG_INFO( "Adding ", entryPoint, " to the folder discovery list" );
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Discover );
return true;
}
void DiscovererWorker::remove( const std::string& entryPoint )
{
enqueue( entryPoint, Task::Type::Remove );
}
void DiscovererWorker::reload()
{
enqueue( "", Task::Type::Reload );
}
void DiscovererWorker::reload( const std::string& entryPoint )
{
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Reload );
}
void DiscovererWorker::ban( const std::string& entryPoint )
{
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Ban );
}
void DiscovererWorker::unban( const std::string& entryPoint )
{
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Unban );
}
void DiscovererWorker::reloadDevice(int64_t deviceId)
{
enqueue( deviceId, Task::Type::ReloadDevice );
}
void DiscovererWorker::enqueue( const std::string& entryPoint, Task::Type type )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
if ( entryPoint.empty() == false )
{
LOG_INFO( "Queuing entrypoint ", entryPoint, " of type ",
static_cast<typename std::underlying_type<Task::Type>::type>( type ) );
}
else
{
assert( type == Task::Type::Reload );
LOG_INFO( "Queuing global reload request" );
}
m_tasks.emplace( entryPoint, type );
notify();
}
void DiscovererWorker::enqueue( int64_t entityId, Task::Type type )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
LOG_INFO( "Queuing entity ", entityId, " of type ",
static_cast<typename std::underlying_type<Task::Type>::type>( type ) );
m_tasks.emplace( entityId, type );
notify();
}
void DiscovererWorker::notify()
{
if ( m_thread.get_id() == compat::Thread::id{} )
{
m_run = true;
m_thread = compat::Thread( &DiscovererWorker::run, this );
}
// Since we just added an element, let's not check for size == 0 :)
else if ( m_tasks.size() == 1 )
m_cond.notify_all();
}
void DiscovererWorker::run()
{
LOG_INFO( "Entering DiscovererWorker thread" );
m_ml->onDiscovererIdleChanged( false );
while ( m_run == true )
{
ML_UNHANDLED_EXCEPTION_INIT
{
Task task;
{
std::unique_lock<compat::Mutex> lock( m_mutex );
if ( m_tasks.size() == 0 )
{
m_ml->onDiscovererIdleChanged( true );
m_cond.wait( lock, [this]() { return m_tasks.size() > 0 || m_run == false; } );
if ( m_run == false )
break;
m_ml->onDiscovererIdleChanged( false );
}
task = m_tasks.front();
m_tasks.pop();
}
switch ( task.type )
{
case Task::Type::Discover:
runDiscover( task.entryPoint );
break;
case Task::Type::Reload:
runReload( task.entryPoint );
break;
case Task::Type::Remove:
runRemove( task.entryPoint );
break;
case Task::Type::Ban:
runBan( task.entryPoint );
break;
case Task::Type::Unban:
runUnban( task.entryPoint );
break;
case Task::Type::ReloadDevice:
runReloadDevice( task.entityId );
break;
default:
assert(false);
}
}
ML_UNHANDLED_EXCEPTION_BODY( "DiscovererWorker" )
}
LOG_INFO( "Exiting DiscovererWorker thread" );
m_ml->onDiscovererIdleChanged( true );
}
void DiscovererWorker::runReload( const std::string& entryPoint )
{
for ( auto& d : m_discoverers )
{
try
{
if ( entryPoint.empty() == true )
{
// Let the discoverer invoke the callbacks for all its known folders
d->reload( *this );
}
else
{
m_ml->getCb()->onReloadStarted( entryPoint );
LOG_INFO( "Reloading folder ", entryPoint );
auto res = d->reload( entryPoint, *this );
m_ml->getCb()->onReloadCompleted( entryPoint, res );
}
}
catch(std::exception& ex)
{
LOG_ERROR( "Fatal error while reloading: ", ex.what() );
}
if ( m_run == false )
break;
}
}
void DiscovererWorker::runRemove( const std::string& ep )
{
auto entryPoint = utils::file::toFolderPath( ep );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_WARN( "Can't remove unknown entrypoint: ", entryPoint );
m_ml->getCb()->onEntryPointRemoved( ep, false );
return;
}
// The easy case is that this folder was directly discovered. In which case, we just
// have to delete it and it won't be discovered again.
// If it isn't, we also have to ban it to prevent it from reappearing. The Folder::banFolder
// method already handles the prior deletion
bool res;
if ( folder->isRootFolder() == false )
res = Folder::ban( m_ml, entryPoint );
else
res = m_ml->deleteFolder( *folder );
if ( res == false )
{
m_ml->getCb()->onEntryPointRemoved( ep, false );
return;
}
m_ml->getCb()->onEntryPointRemoved( ep, true );
}
void DiscovererWorker::runBan( const std::string& entryPoint )
{
auto res = Folder::ban( m_ml, entryPoint );
m_ml->getCb()->onEntryPointBanned( entryPoint, res );
}
void DiscovererWorker::runUnban( const std::string& entryPoint )
{
auto folder = Folder::bannedFolder( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_WARN( "Can't unban ", entryPoint, " as it wasn't banned" );
m_ml->getCb()->onEntryPointUnbanned( entryPoint, false );
return;
}
auto res = m_ml->deleteFolder( *folder );
m_ml->getCb()->onEntryPointUnbanned( entryPoint, res );
auto parentPath = utils::file::parentDirectory( entryPoint );
// If the parent folder was never added to the media library, the discoverer will reject it.
// We could check it from here, but that would mean fetching the folder twice, which would be a waste.
runReload( parentPath );
}
void DiscovererWorker::runReloadDevice( int64_t deviceId )
{
auto device = Device::fetch( m_ml, deviceId );
if ( device == nullptr )
{
LOG_ERROR( "Can't fetch device ", deviceId, " to reload it" );
return;
}
auto entryPoints = Folder::entryPoints( m_ml, false, device->id() );
if ( entryPoints == nullptr )
return;
for ( const auto& ep : entryPoints->all() )
{
try
{
auto mrl = ep->mrl();
LOG_INFO( "Reloading entrypoint on mounted device: ", mrl );
runReload( mrl );
}
catch ( const fs::errors::DeviceRemoved& )
{
LOG_INFO( "Can't reload device ", device->uuid(), " as it was removed" );
}
}
}
bool DiscovererWorker::isInterrupted() const
{
return m_run.load() == false;
}
void DiscovererWorker::runDiscover( const std::string& entryPoint )
{
m_ml->getCb()->onDiscoveryStarted( entryPoint );
auto discovered = false;
LOG_INFO( "Running discover on: ", entryPoint );
for ( auto& d : m_discoverers )
{
// Assume only one discoverer can handle an entrypoint.
try
{
auto chrono = std::chrono::steady_clock::now();
if ( d->discover( entryPoint, *this ) == true )
{
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_VERBOSE( "Discovered ", entryPoint, " in ",
std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(), "µs" );
discovered = true;
break;
}
}
catch(std::exception& ex)
{
LOG_ERROR( "Fatal error while discovering ", entryPoint, ": ", ex.what() );
}
if ( m_run == false )
break;
}
if ( discovered == false )
LOG_WARN( "No IDiscoverer found to discover ", entryPoint );
m_ml->getCb()->onDiscoveryCompleted( entryPoint, discovered );
}
}
<commit_msg>DiscovererWorker: Remove unneeded include<commit_after>/*****************************************************************************
* Media Library
*****************************************************************************
* Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
*
* Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#if HAVE_CONFIG_H
# include "config.h"
#endif
#include "DiscovererWorker.h"
#include "logging/Logger.h"
#include "Folder.h"
#include "MediaLibrary.h"
#include "Device.h"
#include "utils/Filename.h"
#include "medialibrary/filesystem/Errors.h"
#include <cassert>
namespace medialibrary
{
DiscovererWorker::DiscovererWorker(MediaLibrary* ml )
: m_run( false )
, m_ml( ml )
{
}
DiscovererWorker::~DiscovererWorker()
{
stop();
}
void DiscovererWorker::addDiscoverer( std::unique_ptr<IDiscoverer> discoverer )
{
m_discoverers.push_back( std::move( discoverer ) );
}
void DiscovererWorker::stop()
{
bool running = true;
if ( m_run.compare_exchange_strong( running, false ) )
{
{
std::unique_lock<compat::Mutex> lock( m_mutex );
while ( m_tasks.empty() == false )
m_tasks.pop();
}
m_cond.notify_all();
m_thread.join();
}
}
bool DiscovererWorker::discover( const std::string& entryPoint )
{
if ( entryPoint.length() == 0 )
return false;
LOG_INFO( "Adding ", entryPoint, " to the folder discovery list" );
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Discover );
return true;
}
void DiscovererWorker::remove( const std::string& entryPoint )
{
enqueue( entryPoint, Task::Type::Remove );
}
void DiscovererWorker::reload()
{
enqueue( "", Task::Type::Reload );
}
void DiscovererWorker::reload( const std::string& entryPoint )
{
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Reload );
}
void DiscovererWorker::ban( const std::string& entryPoint )
{
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Ban );
}
void DiscovererWorker::unban( const std::string& entryPoint )
{
enqueue( utils::file::toFolderPath( entryPoint ), Task::Type::Unban );
}
void DiscovererWorker::reloadDevice(int64_t deviceId)
{
enqueue( deviceId, Task::Type::ReloadDevice );
}
void DiscovererWorker::enqueue( const std::string& entryPoint, Task::Type type )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
if ( entryPoint.empty() == false )
{
LOG_INFO( "Queuing entrypoint ", entryPoint, " of type ",
static_cast<typename std::underlying_type<Task::Type>::type>( type ) );
}
else
{
assert( type == Task::Type::Reload );
LOG_INFO( "Queuing global reload request" );
}
m_tasks.emplace( entryPoint, type );
notify();
}
void DiscovererWorker::enqueue( int64_t entityId, Task::Type type )
{
std::unique_lock<compat::Mutex> lock( m_mutex );
LOG_INFO( "Queuing entity ", entityId, " of type ",
static_cast<typename std::underlying_type<Task::Type>::type>( type ) );
m_tasks.emplace( entityId, type );
notify();
}
void DiscovererWorker::notify()
{
if ( m_thread.get_id() == compat::Thread::id{} )
{
m_run = true;
m_thread = compat::Thread( &DiscovererWorker::run, this );
}
// Since we just added an element, let's not check for size == 0 :)
else if ( m_tasks.size() == 1 )
m_cond.notify_all();
}
void DiscovererWorker::run()
{
LOG_INFO( "Entering DiscovererWorker thread" );
m_ml->onDiscovererIdleChanged( false );
while ( m_run == true )
{
ML_UNHANDLED_EXCEPTION_INIT
{
Task task;
{
std::unique_lock<compat::Mutex> lock( m_mutex );
if ( m_tasks.size() == 0 )
{
m_ml->onDiscovererIdleChanged( true );
m_cond.wait( lock, [this]() { return m_tasks.size() > 0 || m_run == false; } );
if ( m_run == false )
break;
m_ml->onDiscovererIdleChanged( false );
}
task = m_tasks.front();
m_tasks.pop();
}
switch ( task.type )
{
case Task::Type::Discover:
runDiscover( task.entryPoint );
break;
case Task::Type::Reload:
runReload( task.entryPoint );
break;
case Task::Type::Remove:
runRemove( task.entryPoint );
break;
case Task::Type::Ban:
runBan( task.entryPoint );
break;
case Task::Type::Unban:
runUnban( task.entryPoint );
break;
case Task::Type::ReloadDevice:
runReloadDevice( task.entityId );
break;
default:
assert(false);
}
}
ML_UNHANDLED_EXCEPTION_BODY( "DiscovererWorker" )
}
LOG_INFO( "Exiting DiscovererWorker thread" );
m_ml->onDiscovererIdleChanged( true );
}
void DiscovererWorker::runReload( const std::string& entryPoint )
{
for ( auto& d : m_discoverers )
{
try
{
if ( entryPoint.empty() == true )
{
// Let the discoverer invoke the callbacks for all its known folders
d->reload( *this );
}
else
{
m_ml->getCb()->onReloadStarted( entryPoint );
LOG_INFO( "Reloading folder ", entryPoint );
auto res = d->reload( entryPoint, *this );
m_ml->getCb()->onReloadCompleted( entryPoint, res );
}
}
catch(std::exception& ex)
{
LOG_ERROR( "Fatal error while reloading: ", ex.what() );
}
if ( m_run == false )
break;
}
}
void DiscovererWorker::runRemove( const std::string& ep )
{
auto entryPoint = utils::file::toFolderPath( ep );
auto folder = Folder::fromMrl( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_WARN( "Can't remove unknown entrypoint: ", entryPoint );
m_ml->getCb()->onEntryPointRemoved( ep, false );
return;
}
// The easy case is that this folder was directly discovered. In which case, we just
// have to delete it and it won't be discovered again.
// If it isn't, we also have to ban it to prevent it from reappearing. The Folder::banFolder
// method already handles the prior deletion
bool res;
if ( folder->isRootFolder() == false )
res = Folder::ban( m_ml, entryPoint );
else
res = m_ml->deleteFolder( *folder );
if ( res == false )
{
m_ml->getCb()->onEntryPointRemoved( ep, false );
return;
}
m_ml->getCb()->onEntryPointRemoved( ep, true );
}
void DiscovererWorker::runBan( const std::string& entryPoint )
{
auto res = Folder::ban( m_ml, entryPoint );
m_ml->getCb()->onEntryPointBanned( entryPoint, res );
}
void DiscovererWorker::runUnban( const std::string& entryPoint )
{
auto folder = Folder::bannedFolder( m_ml, entryPoint );
if ( folder == nullptr )
{
LOG_WARN( "Can't unban ", entryPoint, " as it wasn't banned" );
m_ml->getCb()->onEntryPointUnbanned( entryPoint, false );
return;
}
auto res = m_ml->deleteFolder( *folder );
m_ml->getCb()->onEntryPointUnbanned( entryPoint, res );
auto parentPath = utils::file::parentDirectory( entryPoint );
// If the parent folder was never added to the media library, the discoverer will reject it.
// We could check it from here, but that would mean fetching the folder twice, which would be a waste.
runReload( parentPath );
}
void DiscovererWorker::runReloadDevice( int64_t deviceId )
{
auto device = Device::fetch( m_ml, deviceId );
if ( device == nullptr )
{
LOG_ERROR( "Can't fetch device ", deviceId, " to reload it" );
return;
}
auto entryPoints = Folder::entryPoints( m_ml, false, device->id() );
if ( entryPoints == nullptr )
return;
for ( const auto& ep : entryPoints->all() )
{
try
{
auto mrl = ep->mrl();
LOG_INFO( "Reloading entrypoint on mounted device: ", mrl );
runReload( mrl );
}
catch ( const fs::errors::DeviceRemoved& )
{
LOG_INFO( "Can't reload device ", device->uuid(), " as it was removed" );
}
}
}
bool DiscovererWorker::isInterrupted() const
{
return m_run.load() == false;
}
void DiscovererWorker::runDiscover( const std::string& entryPoint )
{
m_ml->getCb()->onDiscoveryStarted( entryPoint );
auto discovered = false;
LOG_INFO( "Running discover on: ", entryPoint );
for ( auto& d : m_discoverers )
{
// Assume only one discoverer can handle an entrypoint.
try
{
auto chrono = std::chrono::steady_clock::now();
if ( d->discover( entryPoint, *this ) == true )
{
auto duration = std::chrono::steady_clock::now() - chrono;
LOG_VERBOSE( "Discovered ", entryPoint, " in ",
std::chrono::duration_cast<std::chrono::microseconds>( duration ).count(), "µs" );
discovered = true;
break;
}
}
catch(std::exception& ex)
{
LOG_ERROR( "Fatal error while discovering ", entryPoint, ": ", ex.what() );
}
if ( m_run == false )
break;
}
if ( discovered == false )
LOG_WARN( "No IDiscoverer found to discover ", entryPoint );
m_ml->getCb()->onDiscoveryCompleted( entryPoint, discovered );
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2017-present Facebook, 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 <thrift/lib/cpp2/transport/core/ThriftClient.h>
#include <folly/Baton.h>
#include <glog/logging.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <thrift/lib/cpp2/async/ResponseChannel.h>
#include <thrift/lib/cpp2/transport/core/ThriftChannelIf.h>
#include <thrift/lib/cpp2/transport/core/ThriftClientCallback.h>
namespace apache {
namespace thrift {
using std::map;
using std::string;
using apache::thrift::async::TAsyncTransport;
using apache::thrift::protocol::PROTOCOL_TYPES;
using apache::thrift::transport::THeader;
using apache::thrift::transport::TTransportException;
using folly::EventBase;
using folly::IOBuf;
using folly::RequestContext;
namespace {
/**
* Used as the callback for sendRequestSync. It delegates to the
* wrapped callback and posts on the baton object to allow the
* synchronous call to continue.
*/
class WaitableRequestCallback final : public RequestCallback {
public:
WaitableRequestCallback(
std::unique_ptr<RequestCallback> cb,
folly::Baton<>& baton)
: cb_(std::move(cb)), baton_(baton) {}
void requestSent() override {
cb_->requestSent();
}
void replyReceived(ClientReceiveState&& rs) override {
cb_->replyReceived(std::move(rs));
baton_.post();
}
void requestError(ClientReceiveState&& rs) override {
DCHECK(rs.isException());
cb_->requestError(std::move(rs));
baton_.post();
}
private:
std::unique_ptr<RequestCallback> cb_;
folly::Baton<>& baton_;
};
} // namespace
ThriftClient::ThriftClient(
std::shared_ptr<ClientConnectionIf> connection,
folly::EventBase* callbackEvb)
: connection_(connection), callbackEvb_(callbackEvb) {}
ThriftClient::ThriftClient(std::shared_ptr<ClientConnectionIf> connection)
: ThriftClient(connection, connection->getEventBase()) {}
void ThriftClient::setProtocolId(uint16_t protocolId) {
protocolId_ = protocolId;
}
uint32_t ThriftClient::sendRequestSync(
RpcOptions& rpcOptions,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header) {
// Synchronous calls may be made from any thread except the one used
// by the underlying connection. That thread is used to handle the
// callback and to release this thread that will be waiting on
// "baton".
EventBase* connectionEvb = connection_->getEventBase();
DCHECK(!connectionEvb->inRunningEventBaseThread());
folly::Baton<> baton;
DCHECK(typeid(ClientSyncCallback) == typeid(*cb));
bool oneway = static_cast<ClientSyncCallback&>(*cb).isOneway();
auto scb = std::make_unique<WaitableRequestCallback>(std::move(cb), baton);
int result;
if (oneway) {
result = sendRequestHelper(
rpcOptions,
true,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header),
connectionEvb);
} else {
result = sendRequestHelper(
rpcOptions,
false,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header),
connectionEvb);
}
baton.wait();
return result;
}
uint32_t ThriftClient::sendRequest(
RpcOptions& rpcOptions,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header) {
return sendRequestHelper(
rpcOptions,
false,
std::move(cb),
std::move(ctx),
std::move(buf),
std::move(header),
callbackEvb_);
}
uint32_t ThriftClient::sendOnewayRequest(
RpcOptions& rpcOptions,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header) {
sendRequestHelper(
rpcOptions,
true,
std::move(cb),
std::move(ctx),
std::move(buf),
std::move(header),
callbackEvb_);
return ResponseChannel::ONEWAY_REQUEST_ID;
}
uint32_t ThriftClient::sendRequestHelper(
RpcOptions& rpcOptions,
bool oneway,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header,
EventBase* callbackEvb) {
// TODO: We'll deal with properties such as timeouts later. Timeouts
// are of multiple kinds and can be set in different ways - so need to
// understand this first.
DestructorGuard dg(this); //// understand what this and
//// RequestContextScopeGuard are doing!!!!
cb->context_ = RequestContext::saveContext();
std::shared_ptr<ThriftChannelIf> channel;
try {
channel = connection_->getChannel();
} catch (TTransportException& te) {
folly::RequestContextScopeGuard rctx(cb->context_);
cb->requestError(ClientReceiveState(
folly::make_exception_wrapper<TTransportException>(std::move(te)),
std::move(ctx),
isSecurityActive()));
return 0;
}
std::unique_ptr<FunctionInfo> finfo = std::make_unique<FunctionInfo>();
// TODO: add function name. We don't use it right now. The payload
// already contains the function name - so that's where the name is
// obtained right now.
finfo->name = "";
if (oneway) {
finfo->kind = SINGLE_REQUEST_NO_RESPONSE;
} else {
finfo->kind = SINGLE_REQUEST_SINGLE_RESPONSE;
}
finfo->seqId = 0; // not used.
finfo->protocol = static_cast<PROTOCOL_TYPES>(protocolId_);
std::unique_ptr<map<string, string>> headers;
if (channel->supportsHeaders()) {
headers = buildHeaders(header.get(), rpcOptions);
}
std::unique_ptr<ThriftClientCallback> callback;
if (!oneway) {
callback = std::make_unique<ThriftClientCallback>(
callbackEvb,
std::move(cb),
std::move(ctx),
isSecurityActive(),
protocolId_);
}
connection_->getEventBase()->runInEventBaseThread([
evbChannel = channel,
evbFinfo = std::move(finfo),
evbHeaders = std::move(headers),
evbBuf = std::move(buf),
evbCallback = std::move(callback),
oneway,
evbCb = std::move(cb)
]() mutable {
evbChannel->sendThriftRequest(
std::move(evbFinfo),
std::move(evbHeaders),
std::move(evbBuf),
std::move(evbCallback));
if (oneway) {
// TODO: We only invoke requestSent for oneway calls. I don't think it
// use used for any other kind of call. Verify.
evbCb->requestSent();
}
});
return 0;
}
std::unique_ptr<map<string, string>> ThriftClient::buildHeaders(
THeader* header,
RpcOptions& rpcOptions) {
header->setClientType(THRIFT_HTTP_CLIENT_TYPE);
header->forceClientType(THRIFT_HTTP_CLIENT_TYPE);
addRpcOptionHeaders(header, rpcOptions);
auto headers = std::make_unique<map<string, string>>();
auto pwh = getPersistentWriteHeaders();
headers->insert(pwh.begin(), pwh.end());
{
auto wh = header->releaseWriteHeaders();
headers->insert(wh.begin(), wh.end());
}
auto eh = header->getExtraWriteHeaders();
if (eh) {
headers->insert(eh->begin(), eh->end());
}
return headers;
}
EventBase* ThriftClient::getEventBase() const {
return callbackEvb_;
}
uint16_t ThriftClient::getProtocolId() {
return protocolId_;
}
void ThriftClient::setCloseCallback(CloseCallback* /*cb*/) {
// TBD
}
TAsyncTransport* ThriftClient::getTransport() {
return connection_->getTransport();
}
bool ThriftClient::good() {
return connection_->good();
}
ClientChannel::SaturationStatus ThriftClient::getSaturationStatus() {
return connection_->getSaturationStatus();
}
void ThriftClient::attachEventBase(folly::EventBase* eventBase) {
connection_->attachEventBase(eventBase);
}
void ThriftClient::detachEventBase() {
connection_->detachEventBase();
}
bool ThriftClient::isDetachable() {
return connection_->isDetachable();
}
bool ThriftClient::isSecurityActive() {
return connection_->isSecurityActive();
}
uint32_t ThriftClient::getTimeout() {
return connection_->getTimeout();
}
void ThriftClient::setTimeout(uint32_t ms) {
return connection_->setTimeout(ms);
}
void ThriftClient::closeNow() {
connection_->closeNow();
}
CLIENT_TYPE ThriftClient::getClientType() {
return connection_->getClientType();
}
} // namespace thrift
} // namespace apache
<commit_msg>Minor refactor<commit_after>/*
* Copyright 2017-present Facebook, 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 <thrift/lib/cpp2/transport/core/ThriftClient.h>
#include <folly/Baton.h>
#include <glog/logging.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <thrift/lib/cpp2/async/ResponseChannel.h>
#include <thrift/lib/cpp2/transport/core/ThriftChannelIf.h>
#include <thrift/lib/cpp2/transport/core/ThriftClientCallback.h>
namespace apache {
namespace thrift {
using std::map;
using std::string;
using apache::thrift::async::TAsyncTransport;
using apache::thrift::protocol::PROTOCOL_TYPES;
using apache::thrift::transport::THeader;
using apache::thrift::transport::TTransportException;
using folly::EventBase;
using folly::IOBuf;
using folly::RequestContext;
namespace {
/**
* Used as the callback for sendRequestSync. It delegates to the
* wrapped callback and posts on the baton object to allow the
* synchronous call to continue.
*/
class WaitableRequestCallback final : public RequestCallback {
public:
WaitableRequestCallback(
std::unique_ptr<RequestCallback> cb,
folly::Baton<>& baton)
: cb_(std::move(cb)), baton_(baton) {}
void requestSent() override {
cb_->requestSent();
}
void replyReceived(ClientReceiveState&& rs) override {
cb_->replyReceived(std::move(rs));
baton_.post();
}
void requestError(ClientReceiveState&& rs) override {
DCHECK(rs.isException());
cb_->requestError(std::move(rs));
baton_.post();
}
private:
std::unique_ptr<RequestCallback> cb_;
folly::Baton<>& baton_;
};
} // namespace
ThriftClient::ThriftClient(
std::shared_ptr<ClientConnectionIf> connection,
folly::EventBase* callbackEvb)
: connection_(connection), callbackEvb_(callbackEvb) {}
ThriftClient::ThriftClient(std::shared_ptr<ClientConnectionIf> connection)
: ThriftClient(connection, connection->getEventBase()) {}
void ThriftClient::setProtocolId(uint16_t protocolId) {
protocolId_ = protocolId;
}
uint32_t ThriftClient::sendRequestSync(
RpcOptions& rpcOptions,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header) {
// Synchronous calls may be made from any thread except the one used
// by the underlying connection. That thread is used to handle the
// callback and to release this thread that will be waiting on
// "baton".
EventBase* connectionEvb = connection_->getEventBase();
DCHECK(!connectionEvb->inRunningEventBaseThread());
folly::Baton<> baton;
DCHECK(typeid(ClientSyncCallback) == typeid(*cb));
bool oneway = static_cast<ClientSyncCallback&>(*cb).isOneway();
auto scb = std::make_unique<WaitableRequestCallback>(std::move(cb), baton);
int result = sendRequestHelper(
rpcOptions,
oneway,
std::move(scb),
std::move(ctx),
std::move(buf),
std::move(header),
connectionEvb);
baton.wait();
return result;
}
uint32_t ThriftClient::sendRequest(
RpcOptions& rpcOptions,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header) {
return sendRequestHelper(
rpcOptions,
false,
std::move(cb),
std::move(ctx),
std::move(buf),
std::move(header),
callbackEvb_);
}
uint32_t ThriftClient::sendOnewayRequest(
RpcOptions& rpcOptions,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header) {
sendRequestHelper(
rpcOptions,
true,
std::move(cb),
std::move(ctx),
std::move(buf),
std::move(header),
callbackEvb_);
return ResponseChannel::ONEWAY_REQUEST_ID;
}
uint32_t ThriftClient::sendRequestHelper(
RpcOptions& rpcOptions,
bool oneway,
std::unique_ptr<RequestCallback> cb,
std::unique_ptr<ContextStack> ctx,
std::unique_ptr<IOBuf> buf,
std::shared_ptr<THeader> header,
EventBase* callbackEvb) {
// TODO: We'll deal with properties such as timeouts later. Timeouts
// are of multiple kinds and can be set in different ways - so need to
// understand this first.
DestructorGuard dg(this); //// understand what this and
//// RequestContextScopeGuard are doing!!!!
cb->context_ = RequestContext::saveContext();
std::shared_ptr<ThriftChannelIf> channel;
try {
channel = connection_->getChannel();
} catch (TTransportException& te) {
folly::RequestContextScopeGuard rctx(cb->context_);
cb->requestError(ClientReceiveState(
folly::make_exception_wrapper<TTransportException>(std::move(te)),
std::move(ctx),
isSecurityActive()));
return 0;
}
std::unique_ptr<FunctionInfo> finfo = std::make_unique<FunctionInfo>();
// TODO: add function name. We don't use it right now. The payload
// already contains the function name - so that's where the name is
// obtained right now.
finfo->name = "";
if (oneway) {
finfo->kind = SINGLE_REQUEST_NO_RESPONSE;
} else {
finfo->kind = SINGLE_REQUEST_SINGLE_RESPONSE;
}
finfo->seqId = 0; // not used.
finfo->protocol = static_cast<PROTOCOL_TYPES>(protocolId_);
std::unique_ptr<map<string, string>> headers;
if (channel->supportsHeaders()) {
headers = buildHeaders(header.get(), rpcOptions);
}
std::unique_ptr<ThriftClientCallback> callback;
if (!oneway) {
callback = std::make_unique<ThriftClientCallback>(
callbackEvb,
std::move(cb),
std::move(ctx),
isSecurityActive(),
protocolId_);
}
connection_->getEventBase()->runInEventBaseThread([
evbChannel = channel,
evbFinfo = std::move(finfo),
evbHeaders = std::move(headers),
evbBuf = std::move(buf),
evbCallback = std::move(callback),
oneway,
evbCb = std::move(cb)
]() mutable {
evbChannel->sendThriftRequest(
std::move(evbFinfo),
std::move(evbHeaders),
std::move(evbBuf),
std::move(evbCallback));
if (oneway) {
// TODO: We only invoke requestSent for oneway calls. I don't think it
// use used for any other kind of call. Verify.
evbCb->requestSent();
}
});
return 0;
}
std::unique_ptr<map<string, string>> ThriftClient::buildHeaders(
THeader* header,
RpcOptions& rpcOptions) {
header->setClientType(THRIFT_HTTP_CLIENT_TYPE);
header->forceClientType(THRIFT_HTTP_CLIENT_TYPE);
addRpcOptionHeaders(header, rpcOptions);
auto headers = std::make_unique<map<string, string>>();
auto pwh = getPersistentWriteHeaders();
headers->insert(pwh.begin(), pwh.end());
{
auto wh = header->releaseWriteHeaders();
headers->insert(wh.begin(), wh.end());
}
auto eh = header->getExtraWriteHeaders();
if (eh) {
headers->insert(eh->begin(), eh->end());
}
return headers;
}
EventBase* ThriftClient::getEventBase() const {
return callbackEvb_;
}
uint16_t ThriftClient::getProtocolId() {
return protocolId_;
}
void ThriftClient::setCloseCallback(CloseCallback* /*cb*/) {
// TBD
}
TAsyncTransport* ThriftClient::getTransport() {
return connection_->getTransport();
}
bool ThriftClient::good() {
return connection_->good();
}
ClientChannel::SaturationStatus ThriftClient::getSaturationStatus() {
return connection_->getSaturationStatus();
}
void ThriftClient::attachEventBase(folly::EventBase* eventBase) {
connection_->attachEventBase(eventBase);
}
void ThriftClient::detachEventBase() {
connection_->detachEventBase();
}
bool ThriftClient::isDetachable() {
return connection_->isDetachable();
}
bool ThriftClient::isSecurityActive() {
return connection_->isSecurityActive();
}
uint32_t ThriftClient::getTimeout() {
return connection_->getTimeout();
}
void ThriftClient::setTimeout(uint32_t ms) {
return connection_->setTimeout(ms);
}
void ThriftClient::closeNow() {
connection_->closeNow();
}
CLIENT_TYPE ThriftClient::getClientType() {
return connection_->getClientType();
}
} // namespace thrift
} // namespace apache
<|endoftext|>
|
<commit_before>#include "handler_unittest.hpp"
#include "fake_sys_file.hpp"
#include <google/protobuf/message_lite.h>
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <boost/endian/arithmetic.hpp>
#include <memory>
#include <string>
#include <vector>
#include "binaryblob.pb.h"
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::AtLeast;
using ::testing::ElementsAreArray;
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::StrEq;
using ::testing::StrNe;
using ::testing::UnorderedElementsAreArray;
using namespace std::string_literals;
using namespace binstore;
namespace blobs
{
class BinaryStoreBlobHandlerBasicTest : public BinaryStoreBlobHandlerTest
{
protected:
static inline std::string basicTestBaseId = "/test/"s;
static inline std::string basicTestBlobId = "/test/blob0"s;
static const std::vector<std::string> basicTestBaseIdList;
static inline std::string basicTestInvalidBlobId = "/invalid/blob0"s;
void addAllBaseIds()
{
for (size_t i = 0; i < basicTestBaseIdList.size(); ++i)
{
auto store = defaultMockStore(basicTestBaseIdList[i]);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
}
}
};
const std::vector<std::string>
BinaryStoreBlobHandlerBasicTest::basicTestBaseIdList = {
BinaryStoreBlobHandlerBasicTest::basicTestBaseId, "/another/"s,
"/null\0/"s};
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobZeroStoreFail)
{
// Cannot handle since there is no store. Shouldn't crash.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobChecksName)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
// Verify canHandleBlob checks and returns false on an invalid name.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, GetBlobIdEqualsConcatenationsOfBaseIds)
{
addAllBaseIds();
// When there is no other blob id, ids are just base ids (might be
// re-ordered).
EXPECT_THAT(handler.getBlobIds(),
UnorderedElementsAreArray(basicTestBaseIdList));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobInvalidNames)
{
addAllBaseIds();
const std::vector<std::string> invalidNames = {
basicTestInvalidBlobId,
"/"s,
"//"s,
"/test"s, // Cannot handle the base path
"/test/"s,
"/test/this/blob"s, // Cannot handle nested path
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
EXPECT_TRUE(
std::none_of(invalidNames.cbegin(), invalidNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobValidNames)
{
addAllBaseIds();
const std::vector<std::string> validNames = {
basicTestBlobId, "/test/test"s, "/test/xyz.abc"s,
"/another/blob"s, "/null\0/\0\0zer\0\0"s,
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob can handle a valid blob under the path.
EXPECT_TRUE(std::all_of(validNames.cbegin(), validNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, DeleteReturnsWhatStoreReturns)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
EXPECT_CALL(*store, deleteBlob(StrEq(basicTestBlobId)))
.WillOnce(Return(false))
.WillOnce(Return(true));
handler.addNewBinaryStore(std::move(store));
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_FALSE(canHandle(basicTestInvalidBlobId));
EXPECT_TRUE(canHandle(basicTestBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestInvalidBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestBlobId));
EXPECT_TRUE(handler.deleteBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, StaleDataIsClearedDuringCreation)
{
using namespace google::protobuf;
auto basicTestStaleBlobStr =
R"(blob_base_id: "/stale/"
blobs {
blob_id: "/stale/blob"
})";
// Create sysfile containing a valid but stale blob
const std::string staleBaseId = "/stale/"s;
const std::string staleBlobId = "/stale/blob"s;
binaryblobproto::BinaryBlobBase staleBlob;
EXPECT_TRUE(TextFormat::ParseFromString(basicTestStaleBlobStr, &staleBlob));
// Serialize to string stored in the fakeSysFile
auto staleBlobData = staleBlob.SerializeAsString();
boost::endian::little_uint64_t sizeLE = staleBlobData.size();
std::string commitData(sizeLE.data(), sizeof(sizeLE));
commitData += staleBlobData;
std::vector<std::string> expectedIdList = {basicTestBaseId};
handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(commitData), 0));
EXPECT_FALSE(handler.canHandleBlob(staleBlobId));
EXPECT_EQ(handler.getBlobIds(), expectedIdList);
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromEmptySysfile)
{
const std::string emptyData;
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(emptyData), 0)));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromJunkData)
{
boost::endian::little_uint64_t tooLarge = 0xffffffffffffffffull;
const std::string junkDataWithLargeSize(tooLarge.data(), sizeof(tooLarge));
EXPECT_GE(tooLarge, junkDataWithLargeSize.max_size());
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(junkDataWithLargeSize),
0)));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
} // namespace blobs
<commit_msg>test: fixup boost endian change<commit_after>#include "handler_unittest.hpp"
#include "fake_sys_file.hpp"
#include <google/protobuf/message_lite.h>
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <boost/endian/arithmetic.hpp>
#include <memory>
#include <string>
#include <vector>
#include "binaryblob.pb.h"
#include <gtest/gtest.h>
using ::testing::_;
using ::testing::AtLeast;
using ::testing::ElementsAreArray;
using ::testing::IsEmpty;
using ::testing::Return;
using ::testing::StrEq;
using ::testing::StrNe;
using ::testing::UnorderedElementsAreArray;
using namespace std::string_literals;
using namespace binstore;
namespace blobs
{
class BinaryStoreBlobHandlerBasicTest : public BinaryStoreBlobHandlerTest
{
protected:
static inline std::string basicTestBaseId = "/test/"s;
static inline std::string basicTestBlobId = "/test/blob0"s;
static const std::vector<std::string> basicTestBaseIdList;
static inline std::string basicTestInvalidBlobId = "/invalid/blob0"s;
void addAllBaseIds()
{
for (size_t i = 0; i < basicTestBaseIdList.size(); ++i)
{
auto store = defaultMockStore(basicTestBaseIdList[i]);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
}
}
};
const std::vector<std::string>
BinaryStoreBlobHandlerBasicTest::basicTestBaseIdList = {
BinaryStoreBlobHandlerBasicTest::basicTestBaseId, "/another/"s,
"/null\0/"s};
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobZeroStoreFail)
{
// Cannot handle since there is no store. Shouldn't crash.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobChecksName)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
handler.addNewBinaryStore(std::move(store));
// Verify canHandleBlob checks and returns false on an invalid name.
EXPECT_FALSE(handler.canHandleBlob(basicTestInvalidBlobId));
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, GetBlobIdEqualsConcatenationsOfBaseIds)
{
addAllBaseIds();
// When there is no other blob id, ids are just base ids (might be
// re-ordered).
EXPECT_THAT(handler.getBlobIds(),
UnorderedElementsAreArray(basicTestBaseIdList));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobInvalidNames)
{
addAllBaseIds();
const std::vector<std::string> invalidNames = {
basicTestInvalidBlobId,
"/"s,
"//"s,
"/test"s, // Cannot handle the base path
"/test/"s,
"/test/this/blob"s, // Cannot handle nested path
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
EXPECT_TRUE(
std::none_of(invalidNames.cbegin(), invalidNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CanHandleBlobValidNames)
{
addAllBaseIds();
const std::vector<std::string> validNames = {
basicTestBlobId, "/test/test"s, "/test/xyz.abc"s,
"/another/blob"s, "/null\0/\0\0zer\0\0"s,
};
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob can handle a valid blob under the path.
EXPECT_TRUE(std::all_of(validNames.cbegin(), validNames.cend(), canHandle));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, DeleteReturnsWhatStoreReturns)
{
auto store = defaultMockStore(basicTestBaseId);
EXPECT_CALL(*store, getBaseBlobId()).Times(AtLeast(1));
EXPECT_CALL(*store, deleteBlob(StrEq(basicTestBlobId)))
.WillOnce(Return(false))
.WillOnce(Return(true));
handler.addNewBinaryStore(std::move(store));
// Unary helper for algorithm
auto canHandle = [this](const std::string& blobId) {
return handler.canHandleBlob(blobId);
};
// Verify canHandleBlob return true for a blob id that it can handle
EXPECT_FALSE(canHandle(basicTestInvalidBlobId));
EXPECT_TRUE(canHandle(basicTestBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestInvalidBlobId));
EXPECT_FALSE(handler.deleteBlob(basicTestBlobId));
EXPECT_TRUE(handler.deleteBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, StaleDataIsClearedDuringCreation)
{
using namespace google::protobuf;
auto basicTestStaleBlobStr =
R"(blob_base_id: "/stale/"
blobs {
blob_id: "/stale/blob"
})";
// Create sysfile containing a valid but stale blob
const std::string staleBaseId = "/stale/"s;
const std::string staleBlobId = "/stale/blob"s;
binaryblobproto::BinaryBlobBase staleBlob;
EXPECT_TRUE(TextFormat::ParseFromString(basicTestStaleBlobStr, &staleBlob));
// Serialize to string stored in the fakeSysFile
auto staleBlobData = staleBlob.SerializeAsString();
boost::endian::little_uint64_t sizeLE = staleBlobData.size();
std::string commitData(reinterpret_cast<const char*>(sizeLE.data()),
sizeof(sizeLE));
commitData += staleBlobData;
std::vector<std::string> expectedIdList = {basicTestBaseId};
handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(commitData), 0));
EXPECT_FALSE(handler.canHandleBlob(staleBlobId));
EXPECT_EQ(handler.getBlobIds(), expectedIdList);
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromEmptySysfile)
{
const std::string emptyData;
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(emptyData), 0)));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
TEST_F(BinaryStoreBlobHandlerBasicTest, CreatingFromJunkData)
{
boost::endian::little_uint64_t tooLarge = 0xffffffffffffffffull;
const std::string junkDataWithLargeSize(
reinterpret_cast<const char*>(tooLarge.data()), sizeof(tooLarge));
EXPECT_GE(tooLarge, junkDataWithLargeSize.max_size());
EXPECT_NO_THROW(handler.addNewBinaryStore(BinaryStore::createFromConfig(
basicTestBaseId, std::make_unique<FakeSysFile>(junkDataWithLargeSize),
0)));
EXPECT_TRUE(handler.canHandleBlob(basicTestBlobId));
}
} // namespace blobs
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/i2c/i2cTargetPres.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <devicefw/driverif.H>
#include <fsi/fsiif.H>
#include <vpd/vpd_if.H>
#include <i2c/i2cif.H>
#include <i2c/i2creasoncodes.H>
#include <initservice/initserviceif.H>
#include <errl/errlmanager.H>
#include "i2c_common.H"
extern trace_desc_t* g_trac_i2c;
//#define TRACSSCOMP(args...) TRACFCOMP(args)
#define TRACSSCOMP(args...)
namespace I2C
{
/**
* @brief Performs a presence detect operation on a Target that has the
* ATTR_FAPI_I2C_CONTROL_INFO and can be detected via that device
*
* Currently used to detect I2C_MUTEX and OCMB_CHIP targets
*
* @param[in] i_target Presence detect target
* @param[in] i_buflen lengh of operation requested
* @param[in] o_present Present = 1, NOT Present = 0
* @
* @return errlHndl_t
*/
errlHndl_t genericI2CTargetPresenceDetect(TARGETING::Target* i_target,
size_t i_buflen,
bool & o_present)
{
errlHndl_t l_errl = nullptr;
bool l_target_present = false;
bool l_i2cMaster_exists = false;
TARGETING::Target * l_i2cMasterTarget = nullptr;
TARGETING::Target* l_masterProcTarget = nullptr;
TARGETING::ATTR_FAPI_I2C_CONTROL_INFO_type l_i2cInfo;
TRACSSCOMP( g_trac_i2c, ENTER_MRK"genericI2CTargetPresenceDetect() "
"Target HUID 0x%.08X ENTER", TARGETING::get_huid(i_target));
do{
if (unlikely(i_buflen != sizeof(bool)))
{
TRACFCOMP(g_trac_i2c,
ERR_MRK "I2C::ddimmPresenceDetect> Invalid data length: %d",
i_buflen);
/*@
* @errortype
* @moduleid I2C::I2C_GENERIC_PRES_DETECT
* @reasoncode I2C::I2C_INVALID_LENGTH
* @userdata1 Data Length
* @userdata2 HUID of target being detected
* @devdesc ddimmPresenceDetect> Invalid data length (!= 1 bytes)
* @custdesc Firmware error during boot
*/
l_errl =
new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
I2C::I2C_GENERIC_PRES_DETECT,
I2C::I2C_INVALID_LENGTH,
TO_UINT64(i_buflen),
TARGETING::get_huid(i_target),
ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
break;
}
// Get a ptr to the target service which we will use later on
TARGETING::TargetService& l_targetService = TARGETING::targetService();
// Read Attributes needed to complete the operation
l_i2cInfo = i_target->getAttr<TARGETING::ATTR_FAPI_I2C_CONTROL_INFO>();
// Check if the target set as the i2cMasterPath actually exists
l_targetService.exists(l_i2cInfo.i2cMasterPath, l_i2cMaster_exists);
// if the i2c master listed doesn't exist then bail out -- this target is not present
if(!l_i2cMaster_exists)
{
TRACFCOMP(g_trac_i2c,
ERR_MRK"I2C::genericI2CTargetPresenceDetect> I2C Master in FAPI_I2C_CONTROL_INFO for Target 0x.08%X does not exist, target not present",
TARGETING::get_huid(i_target));
/*@
* @errortype
* @moduleid I2C::I2C_GENERIC_PRES_DETECT
* @reasoncode VPD::VPD_INVALID_MASTER_I2C_PATH
* @userdata1 HUID of target being detected
* @userdata2 Unused
* @devdesc ocmbPresenceDetect> Invalid master i2c path
* @custdesc Firmware error during boot
*/
l_errl =
new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
I2C::I2C_GENERIC_PRES_DETECT,
I2C::INVALID_MASTER_TARGET,
TARGETING::get_huid(i_target),
0,
ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
break;
}
// if we think it exists then lookup the master path with the target service
l_i2cMasterTarget = l_targetService.toTarget(l_i2cInfo.i2cMasterPath);
// if target service returns a null ptr for the path something is wrong and we should
// mark the target not present
if(l_i2cMasterTarget == nullptr)
{
TRACFCOMP(g_trac_i2c,
ERR_MRK"I2C::genericI2CTargetPresenceDetect> I2C Master in FAPI_I2C_CONTROL_INFO for Target 0x.08%X returned a nullptr, target not present",
TARGETING::get_huid(i_target));
/*@
* @errortype
* @moduleid I2C::I2C_GENERIC_PRES_DETECT
* @reasoncode I2C::I2C_NULL_MASTER_TARGET
* @userdata1 HUID of target being detected
* @userdata2 Unused
* @devdesc ocmbPresenceDetect> Master i2c path returned nullptr
* @custdesc Firmware error during boot
*/
l_errl =
new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
I2C::I2C_GENERIC_PRES_DETECT,
I2C::I2C_NULL_MASTER_TARGET,
TARGETING::get_huid(i_target),
0,
ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
break;
}
TRACSSCOMP( g_trac_i2c, "I2C::genericI2CTargetPresenceDetect> i2c master for target 0x%.08X is HUID 0x%.08X",
TARGETING::get_huid(i_target), TARGETING::get_huid(l_i2cMasterTarget));
// Master proc is taken as always present. Validate other targets.
TARGETING::targetService().masterProcChipTargetHandle(l_masterProcTarget );
if (l_i2cMasterTarget != l_masterProcTarget)
{
// Use the FSI slave presence detection to see if master i2c can be found
if( ! FSI::isSlavePresent(l_i2cMasterTarget) )
{
TRACFCOMP( g_trac_i2c,
ERR_MRK"genericI2CTargetPresenceDetect> isSlavePresent returned false for I2C Master Target %.08X",
TARGETING::get_huid(l_i2cMasterTarget));
break;
}
}
//***********************************************************************************
//* If we make it through all of the checks then we have verified master is present *
//***********************************************************************************
//Check for the target at the I2C level
l_target_present = I2C::i2cPresence(l_i2cMasterTarget,
l_i2cInfo.port,
l_i2cInfo.engine,
l_i2cInfo.devAddr,
l_i2cInfo.i2cMuxBusSelector,
l_i2cInfo.i2cMuxPath );
}while(0);
o_present = l_target_present;
TRACSSCOMP( g_trac_i2c, EXIT_MRK"genericI2CTargetPresenceDetect() "
"Target HUID 0x%.08X found to be %s present EXIT", TARGETING::get_huid(i_target), o_present ? "" : "NOT" );
return l_errl;
}
/**
* @brief Performs a presence detect operation on a OCMB Target
*
* @param[in] i_opType Operation type, see DeviceFW::OperationType
* in driverif.H
* @param[in] i_target Presence detect target
* @param[in/out] io_buffer Read: Pointer to output data storage
* Write: Pointer to input data storage
* @param[in/out] io_buflen Input: size of io_buffer (in bytes, always 1)
* Output: Success = 1, Failure = 0
* @param[in] i_accessType DeviceFW::AccessType enum (userif.H)
* @param[in] i_args This is an argument list for DD framework.
* In this function, there are no arguments.
* @return errlHndl_t
*/
errlHndl_t ocmbI2CPresencePerformOp(DeviceFW::OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer,
size_t& io_buflen,
int64_t i_accessType,
va_list i_args)
{
bool l_ocmbPresent = 0;
// Error log which will eventually be returned
errlHndl_t l_returnedError = nullptr;
// Useful if two errors occur, but we still want to return first one
// from this function
errlHndl_t l_invalidateErrl = nullptr;
l_returnedError = genericI2CTargetPresenceDetect(i_target,
io_buflen,
l_ocmbPresent);
if (l_returnedError)
{
TRACFCOMP( g_trac_i2c, ERR_MRK"ocmbI2CTargetPresenceDetect() "
"Error detecting OCMB target 0x%.08X, io_buffer will not be set.",
" Invalidating SPD cache for target in pnor. ",
TARGETING::get_huid(i_target));
}
else
{
// Copy variable describing if target is present or not to i/o buffer param
memcpy(io_buffer, &l_ocmbPresent, sizeof(l_ocmbPresent));
io_buflen = sizeof(l_ocmbPresent);
}
// If OCMB was found to not be present, or an error occurred
// while checking presence, invalidate the pnor cache of this
// SPD data
if(!l_ocmbPresent || l_returnedError)
{
// Invalidate the SPD in PNOR
l_invalidateErrl = VPD::invalidatePnorCache(i_target);
if (l_invalidateErrl)
{
TRACFCOMP( g_trac_i2c, ERR_MRK"ocmbI2CTargetPresenceDetect() "
"Error invalidating SPD in PNOR for target 0x%.08X",
TARGETING::get_huid(i_target));
// If there was an error found while running genericI2CTargetPresenceDetect
// then we want return that error and just link the error we found from
// invalidatePnorCache and commit it right away. If this is the first error
// we encounter then we will just return the error from invalidatePnorCache
if(l_returnedError)
{
l_invalidateErrl->plid(l_returnedError->plid());
errlCommit(l_invalidateErrl, I2C_COMP_ID);
}
else
{
l_returnedError = l_invalidateErrl;
l_invalidateErrl = nullptr;
}
}
}
return l_returnedError;
}
/**
* @brief Performs a presence detect operation on a Target that has the
* ATTR_FAPI_I2C_CONTROL_INFO and can be detected via that device
*
* Currently used to detect I2C_MUTEX targets
*
* @param[in] i_opType Operation type, see DeviceFW::OperationType
* in driverif.H
* @param[in] i_target Presence detect target
* @param[in/out] io_buffer Read: Pointer to output data storage
* Write: Pointer to input data storage
* @param[in/out] io_buflen Input: size of io_buffer (in bytes, always 1)
* Output: Success = 1, Failure = 0
* @param[in] i_accessType DeviceFW::AccessType enum (userif.H)
* @param[in] i_args This is an argument list for DD framework.
* In this function, there are no arguments.
* @return errlHndl_t
*/
errlHndl_t basicI2CPresencePerformOp(DeviceFW::OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer,
size_t& io_buflen,
int64_t i_accessType,
va_list i_args)
{
bool l_muxPresent = 0;
errlHndl_t l_returnedError = nullptr;
l_returnedError = genericI2CTargetPresenceDetect(i_target,
io_buflen,
l_muxPresent);
if (l_returnedError)
{
TRACFCOMP( g_trac_i2c, ERR_MRK"basicI2CTargetPresenceDetect() "
"Error detecting target 0x%.08X, io_buffer will not be set",
TARGETING::get_huid(i_target));
}
else
{
// Copy variable describing if target is present or not to i/o buffer param
memcpy(io_buffer, &l_muxPresent, sizeof(l_muxPresent));
io_buflen = sizeof(l_muxPresent);
}
return l_returnedError;
}
// Register the ocmb presence detect function with the device framework
DEVICE_REGISTER_ROUTE(DeviceFW::READ,
DeviceFW::PRESENT,
TARGETING::TYPE_OCMB_CHIP,
ocmbI2CPresencePerformOp);
// Register the i2c mux presence detect function with the device framework
DEVICE_REGISTER_ROUTE( DeviceFW::READ,
DeviceFW::PRESENT,
TARGETING::TYPE_I2C_MUX,
basicI2CPresencePerformOp );
// Register the pmic vrm presence detect function with the device framework
DEVICE_REGISTER_ROUTE( DeviceFW::READ,
DeviceFW::PRESENT,
TARGETING::TYPE_PMIC,
basicI2CPresencePerformOp );
}
<commit_msg>Infer presense detection of Explorer chip from VPD EEPROM<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/usr/i2c/i2cTargetPres.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
#include <devicefw/driverif.H>
#include <fsi/fsiif.H>
#include <vpd/vpd_if.H>
#include <i2c/i2cif.H>
#include <i2c/i2creasoncodes.H>
#include <i2c/eepromif.H>
#include <initservice/initserviceif.H>
#include <errl/errlmanager.H>
#include "i2c_common.H"
extern trace_desc_t* g_trac_i2c;
//#define TRACSSCOMP(args...) TRACFCOMP(args)
#define TRACSSCOMP(args...)
namespace I2C
{
/**
* @brief Performs a presence detect operation on a Target that has the
* ATTR_FAPI_I2C_CONTROL_INFO and can be detected via that device
*
* Currently used to detect I2C_MUTEX and OCMB_CHIP targets
*
* @param[in] i_target Presence detect target
* @param[in] i_buflen lengh of operation requested
* @param[in] o_present Present = 1, NOT Present = 0
* @
* @return errlHndl_t
*/
errlHndl_t genericI2CTargetPresenceDetect(TARGETING::Target* i_target,
size_t i_buflen,
bool & o_present)
{
errlHndl_t l_errl = nullptr;
bool l_target_present = false;
bool l_i2cMaster_exists = false;
TARGETING::Target * l_i2cMasterTarget = nullptr;
TARGETING::Target* l_masterProcTarget = nullptr;
TARGETING::ATTR_FAPI_I2C_CONTROL_INFO_type l_i2cInfo;
TRACSSCOMP( g_trac_i2c, ENTER_MRK"genericI2CTargetPresenceDetect() "
"Target HUID 0x%.08X ENTER", TARGETING::get_huid(i_target));
do{
if (unlikely(i_buflen != sizeof(bool)))
{
TRACFCOMP(g_trac_i2c,
ERR_MRK "I2C::ddimmPresenceDetect> Invalid data length: %d",
i_buflen);
/*@
* @errortype
* @moduleid I2C::I2C_GENERIC_PRES_DETECT
* @reasoncode I2C::I2C_INVALID_LENGTH
* @userdata1 Data Length
* @userdata2 HUID of target being detected
* @devdesc ddimmPresenceDetect> Invalid data length (!= 1 bytes)
* @custdesc Firmware error during boot
*/
l_errl =
new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
I2C::I2C_GENERIC_PRES_DETECT,
I2C::I2C_INVALID_LENGTH,
TO_UINT64(i_buflen),
TARGETING::get_huid(i_target),
ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
break;
}
// Get a ptr to the target service which we will use later on
TARGETING::TargetService& l_targetService = TARGETING::targetService();
// Read Attributes needed to complete the operation
l_i2cInfo = i_target->getAttr<TARGETING::ATTR_FAPI_I2C_CONTROL_INFO>();
// Check if the target set as the i2cMasterPath actually exists
l_targetService.exists(l_i2cInfo.i2cMasterPath, l_i2cMaster_exists);
// if the i2c master listed doesn't exist then bail out -- this target is not present
if(!l_i2cMaster_exists)
{
TRACFCOMP(g_trac_i2c,
ERR_MRK"I2C::genericI2CTargetPresenceDetect> I2C Master in FAPI_I2C_CONTROL_INFO for Target 0x.08%X does not exist, target not present",
TARGETING::get_huid(i_target));
/*@
* @errortype
* @moduleid I2C::I2C_GENERIC_PRES_DETECT
* @reasoncode VPD::VPD_INVALID_MASTER_I2C_PATH
* @userdata1 HUID of target being detected
* @userdata2 Unused
* @devdesc ocmbPresenceDetect> Invalid master i2c path
* @custdesc Firmware error during boot
*/
l_errl =
new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
I2C::I2C_GENERIC_PRES_DETECT,
I2C::INVALID_MASTER_TARGET,
TARGETING::get_huid(i_target),
0,
ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
break;
}
// if we think it exists then lookup the master path with the target service
l_i2cMasterTarget = l_targetService.toTarget(l_i2cInfo.i2cMasterPath);
// if target service returns a null ptr for the path something is wrong and we should
// mark the target not present
if(l_i2cMasterTarget == nullptr)
{
TRACFCOMP(g_trac_i2c,
ERR_MRK"I2C::genericI2CTargetPresenceDetect> I2C Master in FAPI_I2C_CONTROL_INFO for Target 0x.08%X returned a nullptr, target not present",
TARGETING::get_huid(i_target));
/*@
* @errortype
* @moduleid I2C::I2C_GENERIC_PRES_DETECT
* @reasoncode I2C::I2C_NULL_MASTER_TARGET
* @userdata1 HUID of target being detected
* @userdata2 Unused
* @devdesc ocmbPresenceDetect> Master i2c path returned nullptr
* @custdesc Firmware error during boot
*/
l_errl =
new ERRORLOG::ErrlEntry(ERRORLOG::ERRL_SEV_UNRECOVERABLE,
I2C::I2C_GENERIC_PRES_DETECT,
I2C::I2C_NULL_MASTER_TARGET,
TARGETING::get_huid(i_target),
0,
ERRORLOG::ErrlEntry::ADD_SW_CALLOUT);
break;
}
TRACSSCOMP( g_trac_i2c, "I2C::genericI2CTargetPresenceDetect> i2c master for target 0x%.08X is HUID 0x%.08X",
TARGETING::get_huid(i_target), TARGETING::get_huid(l_i2cMasterTarget));
// Master proc is taken as always present. Validate other targets.
TARGETING::targetService().masterProcChipTargetHandle(l_masterProcTarget );
if (l_i2cMasterTarget != l_masterProcTarget)
{
// Use the FSI slave presence detection to see if master i2c can be found
if( ! FSI::isSlavePresent(l_i2cMasterTarget) )
{
TRACFCOMP( g_trac_i2c,
ERR_MRK"genericI2CTargetPresenceDetect> isSlavePresent returned false for I2C Master Target %.08X",
TARGETING::get_huid(l_i2cMasterTarget));
break;
}
}
//***********************************************************************************
//* If we make it through all of the checks then we have verified master is present *
//***********************************************************************************
//Check for the target at the I2C level
l_target_present = I2C::i2cPresence(l_i2cMasterTarget,
l_i2cInfo.port,
l_i2cInfo.engine,
l_i2cInfo.devAddr,
l_i2cInfo.i2cMuxBusSelector,
l_i2cInfo.i2cMuxPath );
}while(0);
o_present = l_target_present;
TRACSSCOMP( g_trac_i2c, EXIT_MRK"genericI2CTargetPresenceDetect() "
"Target HUID 0x%.08X found to be %s present EXIT", TARGETING::get_huid(i_target), o_present ? "" : "NOT" );
return l_errl;
}
/**
* @brief Performs a presence detect operation on a OCMB Target
*
* @param[in] i_opType Operation type, see DeviceFW::OperationType
* in driverif.H
* @param[in] i_target Presence detect target
* @param[in/out] io_buffer Read: Pointer to output data storage
* Write: Pointer to input data storage
* @param[in/out] io_buflen Input: size of io_buffer (in bytes, always 1)
* Output: Success = 1, Failure = 0
* @param[in] i_accessType DeviceFW::AccessType enum (userif.H)
* @param[in] i_args This is an argument list for DD framework.
* In this function, there are no arguments.
* @return errlHndl_t
*/
errlHndl_t ocmbI2CPresencePerformOp(DeviceFW::OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer,
size_t& io_buflen,
int64_t i_accessType,
va_list i_args)
{
errlHndl_t l_invalidateErrl = nullptr;
// @TODO RTC 208696: Gemini vs Explorer Presence Detection via SPD
// This function will be updated to differentiate between Explorer and
// Gemini OCMB chips. For now, presense of an OCMB chip is inferred by
// the presense of the eeprom.
bool l_ocmbPresent = EEPROM::eepromPresence(i_target);
memcpy(io_buffer, &l_ocmbPresent, sizeof(l_ocmbPresent));
io_buflen = sizeof(l_ocmbPresent);
return l_invalidateErrl;
}
/**
* @brief Performs a presence detect operation on a Target that has the
* ATTR_FAPI_I2C_CONTROL_INFO and can be detected via that device
*
* Currently used to detect I2C_MUTEX targets
*
* @param[in] i_opType Operation type, see DeviceFW::OperationType
* in driverif.H
* @param[in] i_target Presence detect target
* @param[in/out] io_buffer Read: Pointer to output data storage
* Write: Pointer to input data storage
* @param[in/out] io_buflen Input: size of io_buffer (in bytes, always 1)
* Output: Success = 1, Failure = 0
* @param[in] i_accessType DeviceFW::AccessType enum (userif.H)
* @param[in] i_args This is an argument list for DD framework.
* In this function, there are no arguments.
* @return errlHndl_t
*/
errlHndl_t basicI2CPresencePerformOp(DeviceFW::OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer,
size_t& io_buflen,
int64_t i_accessType,
va_list i_args)
{
bool l_muxPresent = 0;
errlHndl_t l_returnedError = nullptr;
l_returnedError = genericI2CTargetPresenceDetect(i_target,
io_buflen,
l_muxPresent);
if (l_returnedError)
{
TRACFCOMP( g_trac_i2c, ERR_MRK"basicI2CTargetPresenceDetect() "
"Error detecting target 0x%.08X, io_buffer will not be set",
TARGETING::get_huid(i_target));
}
else
{
// Copy variable describing if target is present or not to i/o buffer param
memcpy(io_buffer, &l_muxPresent, sizeof(l_muxPresent));
io_buflen = sizeof(l_muxPresent);
}
return l_returnedError;
}
// Register the ocmb presence detect function with the device framework
DEVICE_REGISTER_ROUTE(DeviceFW::READ,
DeviceFW::PRESENT,
TARGETING::TYPE_OCMB_CHIP,
ocmbI2CPresencePerformOp);
// Register the i2c mux presence detect function with the device framework
DEVICE_REGISTER_ROUTE( DeviceFW::READ,
DeviceFW::PRESENT,
TARGETING::TYPE_I2C_MUX,
basicI2CPresencePerformOp );
// Register the pmic vrm presence detect function with the device framework
DEVICE_REGISTER_ROUTE( DeviceFW::READ,
DeviceFW::PRESENT,
TARGETING::TYPE_PMIC,
basicI2CPresencePerformOp );
}
<|endoftext|>
|
<commit_before>/*
======================================================
Copyright 2016 Liang Ma
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
======================================================
*
* Author: Liang Ma (liang-ma@polito.it)
*
* Top function is defined here with interface specified as axi4.
* It creates an object of blackScholes and launches the simulation.
*
*----------------------------------------------------------------------------
*/
#include "../common/defTypes.h"
#include "../common/stockData.h"
#include "../common/blackScholes.h"
void blackAsian(data_t *call, data_t *put, // call price and put price
data_t timeT, // time period of options
data_t freeRate, // interest rate of the riskless asset
data_t volatility, // volatility of the risky asset
data_t initPrice, // stock price at time 0
data_t strikePrice) // strike price
{
#pragma HLS INTERFACE m_axi port=call bundle=gmem
#pragma HLS INTERFACE s_axilite port=call bundle=control
#pragma HLS INTERFACE m_axi port=put bundle=gmem
#pragma HLS INTERFACE s_axilite port=put bundle=control
#pragma HLS INTERFACE s_axilite port=timeT bundle=gmem
#pragma HLS INTERFACE s_axilite port=timeT bundle=control
#pragma HLS INTERFACE s_axilite port=freeRate bundle=gmem
#pragma HLS INTERFACE s_axilite port=freeRate bundle=control
#pragma HLS INTERFACE s_axilite port=volatility bundle=gmem
#pragma HLS INTERFACE s_axilite port=volatility bundle=control
#pragma HLS INTERFACE s_axilite port=initPrice bundle=gmem
#pragma HLS INTERFACE s_axilite port=initPrice bundle=control
#pragma HLS INTERFACE s_axilite port=strikePrice bundle=gmem
#pragma HLS INTERFACE s_axilite port=strikePrice bundle=control
#pragma HLS INTERFACE s_axilite port=return bundle=control
stockData sd(timeT,freeRate,volatility,initPrice,strikePrice);
blackScholes bs(sd);
data_t callPrice,putPrice;
bs.simulation(&callPrice,&putPrice);
*call=callPrice;
*put=putPrice;
return;
}
<commit_msg>add support for SDAccel2016.2<commit_after>/*
======================================================
Copyright 2016 Liang Ma
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
======================================================
*
* Author: Liang Ma (liang-ma@polito.it)
*
* Top function is defined here with interface specified as axi4.
* It creates an object of blackScholes and launches the simulation.
*
*----------------------------------------------------------------------------
*/
#include "../common/defTypes.h"
#include "../common/stockData.h"
#include "../common/blackScholes.h"
extern "C"
void blackAsian(data_t *call, data_t *put, // call price and put price
data_t timeT, // time period of options
data_t freeRate, // interest rate of the riskless asset
data_t volatility, // volatility of the risky asset
data_t initPrice, // stock price at time 0
data_t strikePrice) // strike price
{
#pragma HLS INTERFACE m_axi port=call bundle=gmem
#pragma HLS INTERFACE s_axilite port=call bundle=control
#pragma HLS INTERFACE m_axi port=put bundle=gmem
#pragma HLS INTERFACE s_axilite port=put bundle=control
#pragma HLS INTERFACE s_axilite port=timeT bundle=gmem
#pragma HLS INTERFACE s_axilite port=timeT bundle=control
#pragma HLS INTERFACE s_axilite port=freeRate bundle=gmem
#pragma HLS INTERFACE s_axilite port=freeRate bundle=control
#pragma HLS INTERFACE s_axilite port=volatility bundle=gmem
#pragma HLS INTERFACE s_axilite port=volatility bundle=control
#pragma HLS INTERFACE s_axilite port=initPrice bundle=gmem
#pragma HLS INTERFACE s_axilite port=initPrice bundle=control
#pragma HLS INTERFACE s_axilite port=strikePrice bundle=gmem
#pragma HLS INTERFACE s_axilite port=strikePrice bundle=control
#pragma HLS INTERFACE s_axilite port=return bundle=control
stockData sd(timeT,freeRate,volatility,initPrice,strikePrice);
blackScholes bs(sd);
data_t callPrice,putPrice;
bs.simulation(&callPrice,&putPrice);
*call=callPrice;
*put=putPrice;
return;
}
<|endoftext|>
|
<commit_before>#include <cassert>
#include <iostream> // std::cerr
#include <string> // std::string
#include <sstream> // std::ostringstream
#include <random> /* mt19937 */
#include "calc_hsv_rgb.h"
#include "util_stop_watch.h" /* util::stop_watch */
#include "iip_trace_by_hsv.h"
/*
template
TINN,TOUTについて
unsigned char
unsigned short
unsigned long
unsigned int (= unsigned)
のみサポート
float
double
は処理できない
*/
template <class TINN , class TOUT>
std::string iip_trace_by_hsv_tplt_(
int width
,int channels
,TINN* image_inn_top
,int area_xpos
,int area_ypos
,int area_xsize
,int area_ysize
,const std::vector<calc::trace_by_hsv_params>& hsv_params
,TOUT* image_out_top
,const bool white_out_of_area_sw
,const bool random_position_sw
,opengl::vertex_buffer_object& vbo
)
{
/* 初期パラメータ設定 */
const int scan_size = width * channels;
const int start_pos = area_ypos * scan_size + area_xpos * channels;
const auto max_val_inn = (std::numeric_limits<TINN>::max)();
/* 注意:windows.hのmax()マクロを回避するためカッコで囲う */
const auto max_glub_out = (std::numeric_limits<GLubyte>::max)();
const int shift_bit = std::numeric_limits<TINN>::digits -
std::numeric_limits<GLubyte>::digits;
util::stop_watch stwa; stwa.start();
/* ----- hsv3d表示のxyz値セット ----- */
if ( vbo.get_hsv_view_start_sw() ) {
opengl::vertex_buffer_object::vbo_float* xyz = vbo.start_vertex();
if (xyz == nullptr) { /* vboがopen出来ていればここはこないはず */
assert(!"Error:vbo.start_vertex() return null");
}
std::mt19937 engine;
std::uniform_real_distribution<> dist( -0.5 ,0.499999 );
TINN *image_inn = image_inn_top + start_pos;
for (int yy = 0; yy < area_ysize ; ++yy ,image_inn += scan_size) {
TINN* inn_x = image_inn;
for (int xx = 0; xx < area_xsize ;++xx ,inn_x+=channels ,xyz+=3) {
double hh=0., ss=0., vv=0.;
if ( !random_position_sw ) {
calc::rgb_to_hsv(
static_cast<double>(inn_x[CH_RED])/max_val_inn
,static_cast<double>(inn_x[CH_GRE])/max_val_inn
,static_cast<double>(inn_x[CH_BLU])/max_val_inn
,hh,ss,vv );
}
if ( random_position_sw ) {
/* RGB256段階で幾何学的並び気持ち悪いためランダムにずらす */
calc::rgb_to_hsv(
(static_cast<double>(inn_x[CH_RED])+dist(engine))/max_val_inn
,(static_cast<double>(inn_x[CH_GRE])+dist(engine))/max_val_inn
,(static_cast<double>(inn_x[CH_BLU])+dist(engine))/max_val_inn
,hh,ss,vv );
}
/* hsvからxyz座標値を生成 */
vbo.hsv_to_xyzarray( hh ,ss ,vv ,xyz );
}
}
vbo.end_vertex();
}
std::cout << "xyz:" << stwa.stop_ms().count() << "milisec\n";
stwa.start();
/* ----- 画像のpixel値と、hsv3d表示のrgb値セット(要高速化) ----- */
const double max_val_out_f = (std::numeric_limits<TOUT>::max)() + 0.999999;
GLubyte* rgb = nullptr;
if ( vbo.get_hsv_view_start_sw() ) {
rgb = vbo.start_color();
if (rgb == nullptr) { /* open出来ていればここはこないはず */
assert(!"Error:vbo.start_color() return null");
}
}
{
TINN *image_inn = image_inn_top + start_pos;
TOUT *image_out = image_out_top + start_pos;
for (int yy = 0; yy < area_ysize ; ++yy
,image_inn += scan_size ,image_out += scan_size) {
TINN* inn_x = image_inn;
TOUT* out_x = image_out;
for (int xx = 0; xx < area_xsize ;++xx
,inn_x+=channels ,out_x+=channels ,rgb+=3) {
double hh=0., ss=0., vv=0.;
calc::rgb_to_hsv(
static_cast<double>(inn_x[CH_RED])/max_val_inn
,static_cast<double>(inn_x[CH_GRE])/max_val_inn
,static_cast<double>(inn_x[CH_BLU])/max_val_inn
,hh,ss,vv );
/* 2値化 */
double rr=0., gg=0., bb=0.;
const bool trace_sw = calc::trace_by_hsv_to_rgb(
hh,ss,vv, hsv_params ,rr,gg,bb );
/* 出力 */
out_x[CH_RED] = static_cast<TOUT>(rr * max_val_out_f);
out_x[CH_GRE] = static_cast<TOUT>(gg * max_val_out_f);
out_x[CH_BLU] = static_cast<TOUT>(bb * max_val_out_f);
if ( vbo.get_hsv_view_start_sw() ) {
rgb[CH_RED] = inn_x[CH_RED] >> shift_bit;
rgb[CH_GRE] = inn_x[CH_GRE] >> shift_bit;
rgb[CH_BLU] = inn_x[CH_BLU] >> shift_bit;
if ( white_out_of_area_sw ) {
/* 2値化するかどうか判断より */
if (!trace_sw) {
/* 2値化しないpixelは白表示 */
rgb[CH_RED] = max_glub_out;
rgb[CH_GRE] = max_glub_out;
rgb[CH_BLU] = max_glub_out;
}
}
}
}
}
if ( vbo.get_hsv_view_start_sw() ) {
vbo.end_color();
}
}
std::cout << "rgb:" << stwa.stop_ms().count() << "milisec\n";
return std::string();
}
//--------------------------------------------------
/* 親のカンバスも自分のカンバスも必要、また同じ大きさであること */
std::string iip_trace_by_hsv::exec(
const std::vector<calc::trace_by_hsv_params>& hsv_params
,const bool white_out_of_area_sw
,const bool random_position_sw
,opengl::vertex_buffer_object& vbo
)
{
/*
* 処理のためのデータチェック
*/
iip_canvas* pare = this->get_clp_parent();
assert(NULL != pare); /* 親が必要 */
assert(NULL != pare->get_vp_canvas());/* 親が画像をもっていること */
/* 自分が独立したカンバスメモリをもっていること */
assert(ON == this->get_i_must_be_free_self_sw());
/* 親と同じサイズであること */
assert(this->get_l_width() == pare->get_l_width());
assert(this->get_l_height() == pare->get_l_height());
assert(this->get_l_channels() == pare->get_l_channels());
assert( this->cl_ch_info.get_l_bytes() ==
pare->cl_ch_info.get_l_bytes());
/* channel数は3(RGB)か4(RGBA) */
assert(SZ_RGB <= this->get_l_channels());
/* channel毎のサイズは(uchar,ushrt,ulong,double)のみ */
assert(E_CH_NUM_BITBW != this->cl_ch_info.get_e_ch_num_type());
/* 処理エリアの確認、実際の画像をはみだしたらだめ */
assert( 0 <= this->area_xpos_ );
assert( 0 <= this->area_ypos_ );
/* areaが画像範囲をはみ出していたときの対処
ホントはあってはならないエラー */
if ( this->get_l_width() <
(this->area_xpos_ + this->area_xsize_)
) {
// for debug
std::string str;
str += "this->area_xpos_<";
{ std::ostringstream ost; ost<<this->area_xpos_; str+=ost.str(); }
str += "> + this->area_xsize_<";
{ std::ostringstream ost; ost<<this->area_xsize_; str+=ost.str(); }
str += "> <= this->get_l_width()<";
{ std::ostringstream ost; ost<<this->get_l_width(); str+=ost.str(); }
str += ">";
std::cerr << str << std::endl;
this->area_xsize_ =
this->get_l_width() - this->area_xpos_;
}
if ( this->get_l_height() <
(this->area_ypos_ + this->area_ysize_)
) {
// for debug
std::string str;
str += "this->area_ypos_<";
{ std::ostringstream ost; ost<<this->area_ypos_; str+=ost.str(); }
str += "> + this->area_ysize_<";
{ std::ostringstream ost; ost<<this->area_ysize_; str+=ost.str(); }
str += "> <= this->get_l_height()<";
{ std::ostringstream ost; ost<<this->get_l_height(); str+=ost.str(); }
str += ">";
std::cerr << str << std::endl;
this->area_ysize_ =
this->get_l_height() - this->area_ypos_;
}
/*
* 処理
*/
if ( vbo.get_hsv_view_start_sw() ) {
/* vboを使うにはOpenGL初期化済であること */
/* vbo初期化あるいは再設定 */
std::string err_msg( vbo.open_or_reopen(
this->area_xsize_ * this->area_ysize_
) );
if (!err_msg.empty()) {
return err_msg;
}
}
switch (this->cl_ch_info.get_e_ch_num_type()) {
case E_CH_NUM_UCHAR:
return iip_trace_by_hsv_tplt_<unsigned char,unsigned char>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned char*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,hsv_params
,static_cast<unsigned char*>(this->get_vp_canvas())
,white_out_of_area_sw
,random_position_sw
,vbo
);
case E_CH_NUM_USHRT:
return iip_trace_by_hsv_tplt_<unsigned short,unsigned short>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned short*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,hsv_params
,static_cast<unsigned short*>(this->get_vp_canvas())
,white_out_of_area_sw
,random_position_sw
,vbo
);
case E_CH_NUM_ULONG:
return iip_trace_by_hsv_tplt_<unsigned long,unsigned long>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned long*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,hsv_params
,static_cast<unsigned long*>(this->get_vp_canvas())
,white_out_of_area_sw
,random_position_sw
,vbo
);
case E_CH_NUM_DOUBL: break; /* Not support */
case E_CH_NUM_BITBW: break; /* for no warning */
case E_CH_NUM_EMPTY: break; /* for no warning */
}
return std::string();
}
<commit_msg>refactoring iip_trace_by_hsv for multithread<commit_after>#include <cassert>
#include <iostream> // std::cerr
#include <string> // std::string
#include <sstream> // std::ostringstream
#include <random> /* mt19937 */
#include "calc_hsv_rgb.h"
#include "util_stop_watch.h" /* util::stop_watch */
#include "iip_trace_by_hsv.h"
/*
template
TINN,TOUTについて
unsigned char
unsigned short
unsigned long
unsigned int (= unsigned)
のみサポート
float
double
は処理できない
*/
template <class TINN , class TOUT>
std::string trace_xyz_(
int width
,int channels
,TINN* image_inn_top
,int area_xpos
,int area_ypos
,int area_xsize
,int area_ysize
,const bool random_position_sw
,opengl::vertex_buffer_object& vbo
)
{
util::stop_watch stwa; stwa.start();
if ( vbo.get_hsv_view_start_sw() ) {
/* 初期パラメータ設定 */
const int scan_size = width * channels;
const int start_pos = area_ypos * scan_size + area_xpos * channels;
const auto max_val_inn = (std::numeric_limits<TINN>::max)();
/* 注意:windows.hのmax()マクロを回避するためカッコで囲う */
/* hsv3d表示のxyz値セット(要高速化) */
opengl::vertex_buffer_object::vbo_float* xyz = vbo.start_vertex();
if (xyz == nullptr) { /* vboがopen出来ていればここはこないはず */
return "Error:vbo.start_vertex() return null";
}
std::mt19937 engine;
std::uniform_real_distribution<> dist( -0.5 ,0.499999 );
TINN *image_inn = image_inn_top + start_pos;
for (int yy = 0; yy < area_ysize ; ++yy ,image_inn += scan_size) {
TINN* inn_x = image_inn;
for (int xx = 0; xx < area_xsize ;++xx ,inn_x+=channels ,xyz+=3) {
double hh=0., ss=0., vv=0.;
if ( !random_position_sw ) {
calc::rgb_to_hsv(
static_cast<double>(inn_x[CH_RED])/max_val_inn
,static_cast<double>(inn_x[CH_GRE])/max_val_inn
,static_cast<double>(inn_x[CH_BLU])/max_val_inn
,hh,ss,vv );
} else {
/* RGB256段階で幾何学的並び気持ち悪いためランダムにずらす */
calc::rgb_to_hsv(
(static_cast<double>(inn_x[CH_RED])+dist(engine))/max_val_inn
,(static_cast<double>(inn_x[CH_GRE])+dist(engine))/max_val_inn
,(static_cast<double>(inn_x[CH_BLU])+dist(engine))/max_val_inn
,hh,ss,vv );
}
/* hsvからxyz座標値を生成 */
vbo.hsv_to_xyzarray( hh ,ss ,vv ,xyz );
}
}
vbo.end_vertex();
}
std::cout << "xyz:" << stwa.stop_ms().count() << "milisec\n";
return std::string();
}
template <class TINN , class TOUT>
std::string trace_out_and_rgb_(
int width
,int channels
,TINN* image_inn_top
,int area_xpos
,int area_ypos
,int area_xsize
,int area_ysize
,const std::vector<calc::trace_by_hsv_params>& hsv_params
,TOUT* image_out_top
,const bool white_out_of_area_sw
,opengl::vertex_buffer_object& vbo
)
{
util::stop_watch stwa; stwa.start();
/* 初期パラメータ設定 */
const int scan_size = width * channels;
const int start_pos = area_ypos * scan_size + area_xpos * channels;
const auto max_val_inn = (std::numeric_limits<TINN>::max)();
/* 注意:windows.hのmax()マクロを回避するためカッコで囲う */
const double max_val_out_f = (std::numeric_limits<TOUT>::max)() + 0.999999;
const int shift_bit = std::numeric_limits<TINN>::digits -
std::numeric_limits<GLubyte>::digits;
const auto max_glub_out = (std::numeric_limits<GLubyte>::max)();
/* 画像のpixel値と、hsv3d表示のrgb値セット(要高速化) */
GLubyte* rgb = nullptr;
if ( vbo.get_hsv_view_start_sw() ) {
rgb = vbo.start_color();
if (rgb == nullptr) { /* open出来ていればここはこないはず */
return "Error:vbo.start_color() return null";
}
}
TINN *image_inn = image_inn_top + start_pos;
TOUT *image_out = image_out_top + start_pos;
for (int yy = 0; yy < area_ysize ; ++yy
,image_inn += scan_size ,image_out += scan_size) {
TINN* inn_x = image_inn;
TOUT* out_x = image_out;
for (int xx = 0; xx < area_xsize ;++xx
,inn_x+=channels ,out_x+=channels) {
double hh=0., ss=0., vv=0.;
calc::rgb_to_hsv(
static_cast<double>(inn_x[CH_RED])/max_val_inn
,static_cast<double>(inn_x[CH_GRE])/max_val_inn
,static_cast<double>(inn_x[CH_BLU])/max_val_inn
,hh,ss,vv );
/* 2値化 */
double rr=0., gg=0., bb=0.;
const bool trace_sw = calc::trace_by_hsv_to_rgb(
hh,ss,vv, hsv_params ,rr,gg,bb );
/* 出力 */
out_x[CH_RED] = static_cast<TOUT>(rr * max_val_out_f);
out_x[CH_GRE] = static_cast<TOUT>(gg * max_val_out_f);
out_x[CH_BLU] = static_cast<TOUT>(bb * max_val_out_f);
if ( vbo.get_hsv_view_start_sw() ) {
if ( trace_sw || !white_out_of_area_sw ) {
rgb[CH_RED] = inn_x[CH_RED] >> shift_bit;
rgb[CH_GRE] = inn_x[CH_GRE] >> shift_bit;
rgb[CH_BLU] = inn_x[CH_BLU] >> shift_bit;
} else {
/* 2値化しない、かつ、範囲外を白表示モードのとき
pixelは白表示 */
rgb[CH_RED] = max_glub_out;
rgb[CH_GRE] = max_glub_out;
rgb[CH_BLU] = max_glub_out;
}
rgb+=3;
}
}
}
if ( vbo.get_hsv_view_start_sw() ) {
vbo.end_color();
}
std::cout << "rgb:" << stwa.stop_ms().count() << "milisec\n";
return std::string();
}
//--------------------------------------------------
/* 親のカンバスも自分のカンバスも必要、また同じ大きさであること */
std::string iip_trace_by_hsv::exec(
const std::vector<calc::trace_by_hsv_params>& hsv_params
,const bool white_out_of_area_sw
,const bool random_position_sw
,opengl::vertex_buffer_object& vbo
)
{
/*
* 処理のためのデータチェック
*/
iip_canvas* pare = this->get_clp_parent();
assert(NULL != pare); /* 親が必要 */
assert(NULL != pare->get_vp_canvas());/* 親が画像をもっていること */
/* 自分が独立したカンバスメモリをもっていること */
assert(ON == this->get_i_must_be_free_self_sw());
/* 親と同じサイズであること */
assert(this->get_l_width() == pare->get_l_width());
assert(this->get_l_height() == pare->get_l_height());
assert(this->get_l_channels() == pare->get_l_channels());
assert( this->cl_ch_info.get_l_bytes() ==
pare->cl_ch_info.get_l_bytes());
/* channel数は3(RGB)か4(RGBA) */
assert(SZ_RGB <= this->get_l_channels());
/* channel毎のサイズは(uchar,ushrt,ulong,double)のみ */
assert(E_CH_NUM_BITBW != this->cl_ch_info.get_e_ch_num_type());
/* 処理エリアの確認、実際の画像をはみだしたらだめ */
assert( 0 <= this->area_xpos_ );
assert( 0 <= this->area_ypos_ );
/* areaが画像範囲をはみ出していたときの対処
ホントはあってはならないエラー */
if ( this->get_l_width() <
(this->area_xpos_ + this->area_xsize_)
) {
// for debug
std::string str;
str += "this->area_xpos_<";
{ std::ostringstream ost; ost<<this->area_xpos_; str+=ost.str(); }
str += "> + this->area_xsize_<";
{ std::ostringstream ost; ost<<this->area_xsize_; str+=ost.str(); }
str += "> <= this->get_l_width()<";
{ std::ostringstream ost; ost<<this->get_l_width(); str+=ost.str(); }
str += ">";
std::cerr << str << std::endl;
this->area_xsize_ =
this->get_l_width() - this->area_xpos_;
}
if ( this->get_l_height() <
(this->area_ypos_ + this->area_ysize_)
) {
// for debug
std::string str;
str += "this->area_ypos_<";
{ std::ostringstream ost; ost<<this->area_ypos_; str+=ost.str(); }
str += "> + this->area_ysize_<";
{ std::ostringstream ost; ost<<this->area_ysize_; str+=ost.str(); }
str += "> <= this->get_l_height()<";
{ std::ostringstream ost; ost<<this->get_l_height(); str+=ost.str(); }
str += ">";
std::cerr << str << std::endl;
this->area_ysize_ =
this->get_l_height() - this->area_ypos_;
}
/*
* 処理
*/
if ( vbo.get_hsv_view_start_sw() ) {
/* vboを使うにはOpenGL初期化済であること */
/* vbo初期化あるいは再設定 */
std::string err_msg( vbo.open_or_reopen(
this->area_xsize_ * this->area_ysize_
) );
if (!err_msg.empty()) {
return err_msg;
}
}
std::string err_msg;
switch (this->cl_ch_info.get_e_ch_num_type()) {
case E_CH_NUM_UCHAR:
err_msg = trace_xyz_<unsigned char,unsigned char>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned char*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,random_position_sw
,vbo
);
if (!err_msg.empty()) { return err_msg; }
err_msg = trace_out_and_rgb_<unsigned char,unsigned char>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned char*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,hsv_params
,static_cast<unsigned char*>(this->get_vp_canvas())
,white_out_of_area_sw
,vbo
);
return err_msg;
case E_CH_NUM_USHRT:
err_msg = trace_xyz_<unsigned short,unsigned short>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned short*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,random_position_sw
,vbo
);
if (!err_msg.empty()) { return err_msg; }
err_msg = trace_out_and_rgb_<unsigned short,unsigned short>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned short*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,hsv_params
,static_cast<unsigned short*>(this->get_vp_canvas())
,white_out_of_area_sw
,vbo
);
return err_msg;
case E_CH_NUM_ULONG:
err_msg = trace_xyz_<unsigned long,unsigned long>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned long*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,random_position_sw
,vbo
);
if (!err_msg.empty()) { return err_msg; }
err_msg = trace_out_and_rgb_<unsigned long,unsigned long>(
this->get_l_width()
,this->get_l_channels()
,static_cast<unsigned long*>(pare->get_vp_canvas())
,this->area_xpos_
,this->area_ypos_
,this->area_xsize_
,this->area_ysize_
,hsv_params
,static_cast<unsigned long*>(this->get_vp_canvas())
,white_out_of_area_sw
,vbo
);
return err_msg;
case E_CH_NUM_DOUBL: break; /* Not support */
case E_CH_NUM_BITBW: break; /* for no warning */
case E_CH_NUM_EMPTY: break; /* for no warning */
}
return std::string();
}
<|endoftext|>
|
<commit_before>/****************************************************************************
*
* Copyright (c) 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file att_estimator.cpp
*
* @author Thomas Gubler <thomasgubler@gmail.com>
* @author Roman Bapst <romanbapst@yahoo.de>
*/
#include "attitude_estimator.h"
#include <px4/vehicle_attitude.h>
#include <mathlib/mathlib.h>
#include <platforms/px4_defines.h>
AttitudeEstimator::AttitudeEstimator() :
_n(),
// _sub_modelstates(_n.subscribe("/gazebo/model_states", 1, &AttitudeEstimator::ModelStatesCallback, this)),
_sub_imu(_n.subscribe("/px4_multicopter/imu", 1, &AttitudeEstimator::ImuCallback, this)),
_vehicle_attitude_pub(_n.advertise<px4::vehicle_attitude>("vehicle_attitude", 1))
{
}
void AttitudeEstimator::ModelStatesCallback(const gazebo_msgs::ModelStatesConstPtr &msg)
{
px4::vehicle_attitude msg_v_att;
/* Fill px4 attitude topic with contents from modelstates topic */
/* Convert quaternion to rotation matrix */
math::Quaternion quat;
//XXX: search for ardrone or other (other than 'plane') vehicle here
int index = 1;
quat(0) = (float)msg->pose[index].orientation.w;
quat(1) = (float)msg->pose[index].orientation.x;
quat(2) = (float) - msg->pose[index].orientation.y;
quat(3) = (float) - msg->pose[index].orientation.z;
msg_v_att.q[0] = quat(0);
msg_v_att.q[1] = quat(1);
msg_v_att.q[2] = quat(2);
msg_v_att.q[3] = quat(3);
math::Matrix<3, 3> rot = quat.to_dcm();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
PX4_R(msg_v_att.R, i, j) = rot(i, j);
}
}
msg_v_att.R_valid = true;
math::Vector<3> euler = rot.to_euler();
msg_v_att.roll = euler(0);
msg_v_att.pitch = euler(1);
msg_v_att.yaw = euler(2);
//XXX this is in inertial frame
// msg_v_att.rollspeed = (float)msg->twist[index].angular.x;
// msg_v_att.pitchspeed = -(float)msg->twist[index].angular.y;
// msg_v_att.yawspeed = -(float)msg->twist[index].angular.z;
_vehicle_attitude_pub.publish(msg_v_att);
}
void AttitudeEstimator::ImuCallback(const sensor_msgs::ImuConstPtr &msg)
{
px4::vehicle_attitude msg_v_att;
/* Fill px4 attitude topic with contents from modelstates topic */
/* Convert quaternion to rotation matrix */
math::Quaternion quat;
//XXX: search for ardrone or other (other than 'plane') vehicle here
int index = 1;
quat(0) = (float)msg->orientation.w;
quat(1) = (float)msg->orientation.x;
quat(2) = (float) - msg->orientation.y;
quat(3) = (float) - msg->orientation.z;
msg_v_att.q[0] = quat(0);
msg_v_att.q[1] = quat(1);
msg_v_att.q[2] = quat(2);
msg_v_att.q[3] = quat(3);
math::Matrix<3, 3> rot = quat.to_dcm();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
PX4_R(msg_v_att.R, i, j) = rot(i, j);
}
}
msg_v_att.R_valid = true;
math::Vector<3> euler = rot.to_euler();
msg_v_att.roll = euler(0);
msg_v_att.pitch = euler(1);
msg_v_att.yaw = euler(2);
msg_v_att.rollspeed = (float)msg->angular_velocity.x;
msg_v_att.pitchspeed = -(float)msg->angular_velocity.y;
msg_v_att.yawspeed = -(float)msg->angular_velocity.z;
_vehicle_attitude_pub.publish(msg_v_att);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "attitude_estimator");
AttitudeEstimator m;
ros::spin();
return 0;
}
<commit_msg>attitude estimator dummy node: add timestamp<commit_after>/****************************************************************************
*
* Copyright (c) 2014 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file att_estimator.cpp
*
* @author Thomas Gubler <thomasgubler@gmail.com>
* @author Roman Bapst <romanbapst@yahoo.de>
*/
#include "attitude_estimator.h"
#include <px4/vehicle_attitude.h>
#include <mathlib/mathlib.h>
#include <platforms/px4_defines.h>
#include <platforms/px4_middleware.h>
AttitudeEstimator::AttitudeEstimator() :
_n(),
// _sub_modelstates(_n.subscribe("/gazebo/model_states", 1, &AttitudeEstimator::ModelStatesCallback, this)),
_sub_imu(_n.subscribe("/px4_multicopter/imu", 1, &AttitudeEstimator::ImuCallback, this)),
_vehicle_attitude_pub(_n.advertise<px4::vehicle_attitude>("vehicle_attitude", 1))
{
}
void AttitudeEstimator::ModelStatesCallback(const gazebo_msgs::ModelStatesConstPtr &msg)
{
px4::vehicle_attitude msg_v_att;
/* Fill px4 attitude topic with contents from modelstates topic */
/* Convert quaternion to rotation matrix */
math::Quaternion quat;
//XXX: search for ardrone or other (other than 'plane') vehicle here
int index = 1;
quat(0) = (float)msg->pose[index].orientation.w;
quat(1) = (float)msg->pose[index].orientation.x;
quat(2) = (float) - msg->pose[index].orientation.y;
quat(3) = (float) - msg->pose[index].orientation.z;
msg_v_att.q[0] = quat(0);
msg_v_att.q[1] = quat(1);
msg_v_att.q[2] = quat(2);
msg_v_att.q[3] = quat(3);
math::Matrix<3, 3> rot = quat.to_dcm();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
PX4_R(msg_v_att.R, i, j) = rot(i, j);
}
}
msg_v_att.R_valid = true;
math::Vector<3> euler = rot.to_euler();
msg_v_att.roll = euler(0);
msg_v_att.pitch = euler(1);
msg_v_att.yaw = euler(2);
//XXX this is in inertial frame
// msg_v_att.rollspeed = (float)msg->twist[index].angular.x;
// msg_v_att.pitchspeed = -(float)msg->twist[index].angular.y;
// msg_v_att.yawspeed = -(float)msg->twist[index].angular.z;
msg_v_att.timestamp = px4::get_time_micros();
_vehicle_attitude_pub.publish(msg_v_att);
}
void AttitudeEstimator::ImuCallback(const sensor_msgs::ImuConstPtr &msg)
{
px4::vehicle_attitude msg_v_att;
/* Fill px4 attitude topic with contents from modelstates topic */
/* Convert quaternion to rotation matrix */
math::Quaternion quat;
//XXX: search for ardrone or other (other than 'plane') vehicle here
int index = 1;
quat(0) = (float)msg->orientation.w;
quat(1) = (float)msg->orientation.x;
quat(2) = (float) - msg->orientation.y;
quat(3) = (float) - msg->orientation.z;
msg_v_att.q[0] = quat(0);
msg_v_att.q[1] = quat(1);
msg_v_att.q[2] = quat(2);
msg_v_att.q[3] = quat(3);
math::Matrix<3, 3> rot = quat.to_dcm();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
PX4_R(msg_v_att.R, i, j) = rot(i, j);
}
}
msg_v_att.R_valid = true;
math::Vector<3> euler = rot.to_euler();
msg_v_att.roll = euler(0);
msg_v_att.pitch = euler(1);
msg_v_att.yaw = euler(2);
msg_v_att.rollspeed = (float)msg->angular_velocity.x;
msg_v_att.pitchspeed = -(float)msg->angular_velocity.y;
msg_v_att.yawspeed = -(float)msg->angular_velocity.z;
_vehicle_attitude_pub.publish(msg_v_att);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "attitude_estimator");
AttitudeEstimator m;
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2014, Nicolas Mansard, LAAS-CNRS
*
* This file is part of eigenpy.
* eigenpy is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __eigenpy_details_hpp__
#define __eigenpy_details_hpp__
#include <boost/python.hpp>
#include <Eigen/Core>
#include <numpy/arrayobject.h>
#include <iostream>
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/exception.hpp"
#include "eigenpy/map.hpp"
namespace eigenpy
{
template <typename SCALAR> struct NumpyEquivalentType {};
template <> struct NumpyEquivalentType<double> { enum { type_code = NPY_DOUBLE };};
template <> struct NumpyEquivalentType<int> { enum { type_code = NPY_INT };};
template <> struct NumpyEquivalentType<float> { enum { type_code = NPY_FLOAT };};
struct PyMatrixType
{
boost::python::object pyMatrixType;
boost::python::object pyModule;
PyMatrixType()
{
pyModule = boost::python::import("numpy");
pyMatrixType = pyModule.attr("matrix");
}
operator boost::python::object () { return pyMatrixType; }
boost::python::object make(PyArrayObject* pyArray, bool copy = false)
{ return make((PyObject*)pyArray,copy); }
boost::python::object make(PyObject* pyObj, bool copy = false)
{
boost::python::object m
= pyMatrixType( boost::python::object(boost::python::handle<>(pyObj)),
boost::python::object(), copy );
Py_INCREF(m.ptr());
return m;
}
};
extern PyMatrixType pyMatrixType;
/* --- TO PYTHON -------------------------------------------------------------- */
template< typename MatType,typename EquivalentEigenType >
struct EigenToPy
{
static PyObject* convert(MatType const& mat)
{
typedef typename MatType::Scalar T;
assert( (mat.rows()<INT_MAX) && (mat.cols()<INT_MAX)
&& "Matrix range larger than int ... should never happen." );
const int R = (int)mat.rows(), C = (int)mat.cols();
npy_intp shape[2] = { R,C };
PyArrayObject* pyArray = (PyArrayObject*)
PyArray_SimpleNew(2, shape, NumpyEquivalentType<T>::type_code);
MapNumpy<EquivalentEigenType>::map(pyArray) = mat;
return pyMatrixType.make(pyArray).ptr();
}
};
/* --- FROM PYTHON ------------------------------------------------------------ */
namespace bp = boost::python;
template<typename MatType, int ROWS,int COLS>
struct TraitsMatrixConstructor
{
static MatType & construct(void*storage,int /*r*/,int /*c*/)
{
return * new(storage) MatType();
}
};
template<typename MatType>
struct TraitsMatrixConstructor<MatType,Eigen::Dynamic,Eigen::Dynamic>
{
static MatType & construct(void*storage,int r,int c)
{
return * new(storage) MatType(r,c);
}
};
template<typename MatType,int R>
struct TraitsMatrixConstructor<MatType,R,Eigen::Dynamic>
{
static MatType & construct(void*storage,int /*r*/,int c)
{
return * new(storage) MatType(R,c);
}
};
template<typename MatType,int C>
struct TraitsMatrixConstructor<MatType,Eigen::Dynamic,C>
{
static MatType & construct(void*storage,int r,int /*c*/)
{
return * new(storage) MatType(r,C);
}
};
template<typename MatType,typename EquivalentEigenType>
struct EigenFromPy
{
EigenFromPy()
{
bp::converter::registry::push_back
(&convertible,&construct,bp::type_id<MatType>());
}
// Determine if obj_ptr can be converted in a Eigenvec
static void* convertible(PyObject* obj_ptr)
{
typedef typename MatType::Scalar T;
if (!PyArray_Check(obj_ptr))
{
std::cerr << "The python object is not a numpy array." << std::endl;
return 0;
}
if (PyArray_NDIM(obj_ptr) != 2)
if ( (PyArray_NDIM(obj_ptr) !=1) || (! MatType::IsVectorAtCompileTime) )
{
std::cerr << "The number of dimension of the object is not correct." << std::endl;
return 0;
}
if ((PyArray_ObjectType(obj_ptr, 0)) != NumpyEquivalentType<T>::type_code)
{
std::cerr << "The internal type as no Eigen equivalent." << std::endl;
return 0;
}
if (!(PyArray_FLAGS(obj_ptr) & NPY_ALIGNED))
{
std::cerr << "NPY non-aligned matrices are not implemented." << std::endl;
return 0;
}
return obj_ptr;
}
// Convert obj_ptr into a Eigenvec
static void construct(PyObject* pyObj,
bp::converter::rvalue_from_python_stage1_data* memory)
{
typedef typename MatType::Scalar T;
using namespace Eigen;
PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);
typename MapNumpy<EquivalentEigenType>::EigenMap numpyMap = MapNumpy<EquivalentEigenType>::map(pyArray);
void* storage = ((bp::converter::rvalue_from_python_storage<MatType>*)
(memory))->storage.bytes;
assert( (numpyMap.rows()<INT_MAX) && (numpyMap.cols()<INT_MAX)
&& "Map range larger than int ... can never happen." );
int r=(int)numpyMap.rows(),c=(int)numpyMap.cols();
EquivalentEigenType & eigenMatrix = //* new(storage) MatType(numpyMap.rows(),numpyMap.cols());
TraitsMatrixConstructor<MatType,MatType::RowsAtCompileTime,MatType::ColsAtCompileTime>::construct (storage,r,c);
memory->convertible = storage;
eigenMatrix = numpyMap;
}
};
template<typename MatType,typename EigenEquivalentType>
void enableEigenPySpecific()
{
import_array();
#ifdef EIGEN_DONT_VECTORIZE
boost::python::to_python_converter<MatType,
eigenpy::EigenToPy<MatType,MatType> >();
eigenpy::EigenFromPy<MatType,MatType>();
#else
typedef typename eigenpy::UnalignedEquivalent<MatType>::type MatTypeDontAlign;
boost::python::to_python_converter<MatType,
eigenpy::EigenToPy<MatType,MatType> >();
boost::python::to_python_converter<MatTypeDontAlign,
eigenpy::EigenToPy<MatTypeDontAlign,MatTypeDontAlign> >();
eigenpy::EigenFromPy<MatTypeDontAlign,MatTypeDontAlign>();
#endif
}
} // namespace eigenpy
#endif // ifndef __eigenpy_details_hpp__
<commit_msg>[C++] Remove useless typedef leading to warnings<commit_after>/*
* Copyright 2014, Nicolas Mansard, LAAS-CNRS
*
* This file is part of eigenpy.
* eigenpy is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
* eigenpy 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 eigenpy. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __eigenpy_details_hpp__
#define __eigenpy_details_hpp__
#include <boost/python.hpp>
#include <Eigen/Core>
#include <numpy/arrayobject.h>
#include <iostream>
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/exception.hpp"
#include "eigenpy/map.hpp"
namespace eigenpy
{
template <typename SCALAR> struct NumpyEquivalentType {};
template <> struct NumpyEquivalentType<double> { enum { type_code = NPY_DOUBLE };};
template <> struct NumpyEquivalentType<int> { enum { type_code = NPY_INT };};
template <> struct NumpyEquivalentType<float> { enum { type_code = NPY_FLOAT };};
struct PyMatrixType
{
boost::python::object pyMatrixType;
boost::python::object pyModule;
PyMatrixType()
{
pyModule = boost::python::import("numpy");
pyMatrixType = pyModule.attr("matrix");
}
operator boost::python::object () { return pyMatrixType; }
boost::python::object make(PyArrayObject* pyArray, bool copy = false)
{ return make((PyObject*)pyArray,copy); }
boost::python::object make(PyObject* pyObj, bool copy = false)
{
boost::python::object m
= pyMatrixType( boost::python::object(boost::python::handle<>(pyObj)),
boost::python::object(), copy );
Py_INCREF(m.ptr());
return m;
}
};
extern PyMatrixType pyMatrixType;
/* --- TO PYTHON -------------------------------------------------------------- */
template< typename MatType,typename EquivalentEigenType >
struct EigenToPy
{
static PyObject* convert(MatType const& mat)
{
typedef typename MatType::Scalar T;
assert( (mat.rows()<INT_MAX) && (mat.cols()<INT_MAX)
&& "Matrix range larger than int ... should never happen." );
const int R = (int)mat.rows(), C = (int)mat.cols();
npy_intp shape[2] = { R,C };
PyArrayObject* pyArray = (PyArrayObject*)
PyArray_SimpleNew(2, shape, NumpyEquivalentType<T>::type_code);
MapNumpy<EquivalentEigenType>::map(pyArray) = mat;
return pyMatrixType.make(pyArray).ptr();
}
};
/* --- FROM PYTHON ------------------------------------------------------------ */
namespace bp = boost::python;
template<typename MatType, int ROWS,int COLS>
struct TraitsMatrixConstructor
{
static MatType & construct(void*storage,int /*r*/,int /*c*/)
{
return * new(storage) MatType();
}
};
template<typename MatType>
struct TraitsMatrixConstructor<MatType,Eigen::Dynamic,Eigen::Dynamic>
{
static MatType & construct(void*storage,int r,int c)
{
return * new(storage) MatType(r,c);
}
};
template<typename MatType,int R>
struct TraitsMatrixConstructor<MatType,R,Eigen::Dynamic>
{
static MatType & construct(void*storage,int /*r*/,int c)
{
return * new(storage) MatType(R,c);
}
};
template<typename MatType,int C>
struct TraitsMatrixConstructor<MatType,Eigen::Dynamic,C>
{
static MatType & construct(void*storage,int r,int /*c*/)
{
return * new(storage) MatType(r,C);
}
};
template<typename MatType,typename EquivalentEigenType>
struct EigenFromPy
{
EigenFromPy()
{
bp::converter::registry::push_back
(&convertible,&construct,bp::type_id<MatType>());
}
// Determine if obj_ptr can be converted in a Eigenvec
static void* convertible(PyObject* obj_ptr)
{
typedef typename MatType::Scalar T;
if (!PyArray_Check(obj_ptr))
{
std::cerr << "The python object is not a numpy array." << std::endl;
return 0;
}
if (PyArray_NDIM(obj_ptr) != 2)
if ( (PyArray_NDIM(obj_ptr) !=1) || (! MatType::IsVectorAtCompileTime) )
{
std::cerr << "The number of dimension of the object is not correct." << std::endl;
return 0;
}
if ((PyArray_ObjectType(obj_ptr, 0)) != NumpyEquivalentType<T>::type_code)
{
std::cerr << "The internal type as no Eigen equivalent." << std::endl;
return 0;
}
if (!(PyArray_FLAGS(obj_ptr) & NPY_ALIGNED))
{
std::cerr << "NPY non-aligned matrices are not implemented." << std::endl;
return 0;
}
return obj_ptr;
}
// Convert obj_ptr into a Eigenvec
static void construct(PyObject* pyObj,
bp::converter::rvalue_from_python_stage1_data* memory)
{
using namespace Eigen;
PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);
typename MapNumpy<EquivalentEigenType>::EigenMap numpyMap = MapNumpy<EquivalentEigenType>::map(pyArray);
void* storage = ((bp::converter::rvalue_from_python_storage<MatType>*)
(memory))->storage.bytes;
assert( (numpyMap.rows()<INT_MAX) && (numpyMap.cols()<INT_MAX)
&& "Map range larger than int ... can never happen." );
int r=(int)numpyMap.rows(),c=(int)numpyMap.cols();
EquivalentEigenType & eigenMatrix = //* new(storage) MatType(numpyMap.rows(),numpyMap.cols());
TraitsMatrixConstructor<MatType,MatType::RowsAtCompileTime,MatType::ColsAtCompileTime>::construct (storage,r,c);
memory->convertible = storage;
eigenMatrix = numpyMap;
}
};
template<typename MatType,typename EigenEquivalentType>
void enableEigenPySpecific()
{
import_array();
#ifdef EIGEN_DONT_VECTORIZE
boost::python::to_python_converter<MatType,
eigenpy::EigenToPy<MatType,MatType> >();
eigenpy::EigenFromPy<MatType,MatType>();
#else
typedef typename eigenpy::UnalignedEquivalent<MatType>::type MatTypeDontAlign;
boost::python::to_python_converter<MatType,
eigenpy::EigenToPy<MatType,MatType> >();
boost::python::to_python_converter<MatTypeDontAlign,
eigenpy::EigenToPy<MatTypeDontAlign,MatTypeDontAlign> >();
eigenpy::EigenFromPy<MatTypeDontAlign,MatTypeDontAlign>();
#endif
}
} // namespace eigenpy
#endif // ifndef __eigenpy_details_hpp__
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/
#include "maemoqemuruntimeparser.h"
#include "maemoglobal.h"
#include <qt4projectmanager/qtversionmanager.h>
#include <QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>
namespace Qt4ProjectManager {
namespace Internal {
class MaemoQemuRuntimeParserV1 : public MaemoQemuRuntimeParser
{
public:
MaemoQemuRuntimeParserV1(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot);
MaemoQemuRuntime parseRuntime();
private:
void fillRuntimeInformation(MaemoQemuRuntime *runtime) const;
void setEnvironment(MaemoQemuRuntime *runTime, const QString &envSpec) const;
};
class MaemoQemuRuntimeParserV2 : public MaemoQemuRuntimeParser
{
public:
MaemoQemuRuntimeParserV2(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot);
MaemoQemuRuntime parseRuntime();
private:
void handleTargetTag(QString &runtimeName);
MaemoQemuRuntime handleRuntimeTag();
QProcessEnvironment handleEnvironmentTag();
QPair<QString, QString> handleVariableTag();
MaemoPortList handleTcpPortListTag();
int handlePortTag();
};
MaemoQemuRuntimeParser::MaemoQemuRuntimeParser(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot)
: m_targetName(targetName),
m_maddeRoot(maddeRoot),
m_madInfoReader(madInfoOutput)
{
}
MaemoQemuRuntime MaemoQemuRuntimeParser::parseRuntime(const QtVersion *qtVersion)
{
MaemoQemuRuntime runtime;
const QString maddeRootPath
= MaemoGlobal::maddeRoot(qtVersion->qmakeCommand());
const QString madCommand = maddeRootPath + QLatin1String("/bin/mad");
if (!QFileInfo(madCommand).exists())
return runtime;
QProcess madProc;
MaemoGlobal::callMaddeShellScript(madProc, maddeRootPath, madCommand,
QStringList() << QLatin1String("info"));
if (!madProc.waitForStarted() || !madProc.waitForFinished())
return runtime;
const QByteArray &madInfoOutput = madProc.readAllStandardOutput();
const QString &targetName
= MaemoGlobal::targetName(qtVersion->qmakeCommand());
runtime = MaemoQemuRuntimeParserV2(madInfoOutput, targetName, maddeRootPath)
.parseRuntime();
if (!runtime.m_name.isEmpty()) {
runtime.m_root = maddeRootPath + QLatin1String("/runtimes/")
+ runtime.m_name;
// TODO: Workaround for missing ssh tag. Fix once MADDE is ready.
runtime.m_sshPort = QLatin1String("6666");
} else {
runtime = MaemoQemuRuntimeParserV1(madInfoOutput, targetName,
maddeRootPath).parseRuntime();
}
runtime.m_watchPath = runtime.m_root
.left(runtime.m_root.lastIndexOf(QLatin1Char('/')));
return runtime;
}
MaemoQemuRuntimeParserV1::MaemoQemuRuntimeParserV1(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot)
: MaemoQemuRuntimeParser(madInfoOutput, targetName, maddeRoot)
{
}
MaemoQemuRuntime MaemoQemuRuntimeParserV1::parseRuntime()
{
QStringList installedRuntimes;
QString targetRuntime;
while (!m_madInfoReader.atEnd() && !installedRuntimes.contains(targetRuntime)) {
if (m_madInfoReader.readNext() == QXmlStreamReader::StartElement) {
if (targetRuntime.isEmpty()
&& m_madInfoReader.name() == QLatin1String("target")) {
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (attrs.value(QLatin1String("target_id")) == m_targetName)
targetRuntime = attrs.value("runtime_id").toString();
} else if (m_madInfoReader.name() == QLatin1String("runtime")) {
const QXmlStreamAttributes attrs = m_madInfoReader.attributes();
while (!m_madInfoReader.atEnd()) {
if (m_madInfoReader.readNext() == QXmlStreamReader::EndElement
&& m_madInfoReader.name() == QLatin1String("runtime"))
break;
if (m_madInfoReader.tokenType() == QXmlStreamReader::StartElement
&& m_madInfoReader.name() == QLatin1String("installed")) {
if (m_madInfoReader.readNext() == QXmlStreamReader::Characters
&& m_madInfoReader.text() == QLatin1String("true")) {
if (attrs.hasAttribute(QLatin1String("runtime_id")))
installedRuntimes << attrs.value(QLatin1String("runtime_id")).toString();
else if (attrs.hasAttribute(QLatin1String("id"))) {
// older MADDE seems to use only id
installedRuntimes << attrs.value(QLatin1String("id")).toString();
}
}
break;
}
}
}
}
}
MaemoQemuRuntime runtime;
if (installedRuntimes.contains(targetRuntime)) {
runtime.m_name = targetRuntime;
runtime.m_root = m_maddeRoot + QLatin1String("/runtimes/")
+ targetRuntime;
fillRuntimeInformation(&runtime);
}
return runtime;
}
void MaemoQemuRuntimeParserV1::fillRuntimeInformation(MaemoQemuRuntime *runtime) const
{
const QStringList files = QDir(runtime->m_root).entryList(QDir::Files
| QDir::NoSymLinks | QDir::NoDotAndDotDot);
const QLatin1String infoFile("information");
if (files.contains(infoFile)) {
QFile file(runtime->m_root + QLatin1Char('/') + infoFile);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMap<QString, QString> map;
QTextStream stream(&file);
while (!stream.atEnd()) {
const QString &line = stream.readLine().trimmed();
const int index = line.indexOf(QLatin1Char('='));
map.insert(line.mid(0, index).remove(QLatin1Char('\'')),
line.mid(index + 1).remove(QLatin1Char('\'')));
}
runtime->m_bin = map.value(QLatin1String("qemu"));
runtime->m_args = map.value(QLatin1String("qemu_args"));
setEnvironment(runtime, map.value(QLatin1String("libpath")));
runtime->m_sshPort = map.value(QLatin1String("sshport"));
runtime->m_freePorts = MaemoPortList();
int i = 2;
while (true) {
const QString port = map.value(QLatin1String("redirport")
+ QString::number(i++));
if (port.isEmpty())
break;
runtime->m_freePorts.addPort(port.toInt());
}
// This is complex because of extreme MADDE weirdness.
const QString root = m_maddeRoot + QLatin1Char('/');
const bool pathIsRelative = QFileInfo(runtime->m_bin).isRelative();
runtime->m_bin =
#ifdef Q_OS_WIN
root + (pathIsRelative
? QLatin1String("madlib/") + runtime->m_bin // Fremantle.
: runtime->m_bin) // Harmattan.
+ QLatin1String(".exe");
#else
pathIsRelative
? root + QLatin1String("madlib/") + runtime->m_bin // Fremantle.
: runtime->m_bin; // Harmattan.
#endif
}
}
}
void MaemoQemuRuntimeParserV1::setEnvironment(MaemoQemuRuntime *runTime,
const QString &envSpec) const
{
QString remainingEnvSpec = envSpec;
QString currentKey;
runTime->m_environment = QProcessEnvironment::systemEnvironment();
while (true) {
const int nextEqualsSignPos
= remainingEnvSpec.indexOf(QLatin1Char('='));
if (nextEqualsSignPos == -1) {
if (!currentKey.isEmpty())
runTime->m_environment.insert(currentKey, remainingEnvSpec);
break;
}
const int keyStartPos
= remainingEnvSpec.lastIndexOf(QRegExp(QLatin1String("\\s")),
nextEqualsSignPos) + 1;
if (!currentKey.isEmpty()) {
const int valueEndPos
= remainingEnvSpec.lastIndexOf(QRegExp(QLatin1String("\\S")),
qMax(0, keyStartPos - 1)) + 1;
runTime->m_environment.insert(currentKey,
remainingEnvSpec.left(valueEndPos));
}
currentKey = remainingEnvSpec.mid(keyStartPos,
nextEqualsSignPos - keyStartPos);
remainingEnvSpec.remove(0, nextEqualsSignPos + 1);
}
}
MaemoQemuRuntimeParserV2::MaemoQemuRuntimeParserV2(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot)
: MaemoQemuRuntimeParser(madInfoOutput, targetName, maddeRoot)
{
}
MaemoQemuRuntime MaemoQemuRuntimeParserV2::parseRuntime()
{
QString runtimeName;
QList<MaemoQemuRuntime> runtimes;
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("madde")) {
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("targets")) {
while (m_madInfoReader.readNextStartElement())
handleTargetTag(runtimeName);
} else if (m_madInfoReader.name() == QLatin1String("runtimes")) {
while (m_madInfoReader.readNextStartElement()) {
const MaemoQemuRuntime &rt = handleRuntimeTag();
if (!rt.m_name.isEmpty() && !rt.m_bin.isEmpty()
&& !rt.m_args.isEmpty()) {
runtimes << rt;
}
}
} else {
m_madInfoReader.skipCurrentElement();
}
}
}
}
foreach (const MaemoQemuRuntime &rt, runtimes) {
if (rt.m_name == runtimeName)
return rt;
}
return MaemoQemuRuntime();
}
void MaemoQemuRuntimeParserV2::handleTargetTag(QString &runtimeName)
{
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (m_madInfoReader.name() == QLatin1String("target") && runtimeName.isEmpty()
&& attrs.value(QLatin1String("name")) == m_targetName
&& attrs.value(QLatin1String("installed")) == QLatin1String("true")) {
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("runtime"))
runtimeName = m_madInfoReader.readElementText();
else
m_madInfoReader.skipCurrentElement();
}
} else {
m_madInfoReader.skipCurrentElement();
}
}
MaemoQemuRuntime MaemoQemuRuntimeParserV2::handleRuntimeTag()
{
MaemoQemuRuntime runtime;
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (m_madInfoReader.name() != QLatin1String("runtime")
|| attrs.value(QLatin1String("installed")) != QLatin1String("true")) {
m_madInfoReader.skipCurrentElement();
return runtime;
}
runtime.m_name = attrs.value(QLatin1String("name")).toString();
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("exec-path")) {
runtime.m_bin = m_madInfoReader.readElementText();
} else if (m_madInfoReader.name() == QLatin1String("args")) {
runtime.m_args = m_madInfoReader.readElementText();
} else if (m_madInfoReader.name() == QLatin1String("environment")) {
runtime.m_environment = handleEnvironmentTag();
} else if (m_madInfoReader.name() == QLatin1String("tcpportmap")) {
runtime.m_freePorts = handleTcpPortListTag();
} else {
m_madInfoReader.skipCurrentElement();
}
}
return runtime;
}
QProcessEnvironment MaemoQemuRuntimeParserV2::handleEnvironmentTag()
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
while (m_madInfoReader.readNextStartElement()) {
const QPair<QString, QString> &var = handleVariableTag();
if (!var.first.isEmpty())
env.insert(var.first, var.second);
}
#ifdef Q_OS_WIN
const QString root = QDir::toNativeSeparators(m_maddeRoot)
+ QLatin1Char('/');
const QLatin1Char colon(';');
const QLatin1String key("PATH");
env.insert(key, root + QLatin1String("bin") + colon + env.value(key));
env.insert(key, root + QLatin1String("madlib") + colon + env.value(key));
#endif
return env;
}
QPair<QString, QString> MaemoQemuRuntimeParserV2::handleVariableTag()
{
QPair<QString, QString> var;
if (m_madInfoReader.name() != QLatin1String("variable")) {
m_madInfoReader.skipCurrentElement();
return var;
}
// TODO: Check for "purpose" attribute and handle "glbackend" in a special way
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("name"))
var.first = m_madInfoReader.readElementText();
else if (m_madInfoReader.name() == QLatin1String("value"))
var.second = m_madInfoReader.readElementText();
else
m_madInfoReader.skipCurrentElement();
}
return var;
}
MaemoPortList MaemoQemuRuntimeParserV2::handleTcpPortListTag()
{
MaemoPortList ports;
while (m_madInfoReader.readNextStartElement()) {
const int port = handlePortTag();
if (port != -1 && port != 6666) // TODO: Remove second condition once MADDE has ssh tag
ports.addPort(port);
}
return ports;
}
int MaemoQemuRuntimeParserV2::handlePortTag()
{
int port = -1;
if (m_madInfoReader.name() == QLatin1String("port")) {
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("host"))
port = m_madInfoReader.readElementText().toInt();
else
m_madInfoReader.skipCurrentElement();
}
}
return port;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>Maemo: Fix "mad info" parsing for Qemu, part 1.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
**************************************************************************/
#include "maemoqemuruntimeparser.h"
#include "maemoglobal.h"
#include <qt4projectmanager/qtversionmanager.h>
#include <QtCore/QDir>
#include <QtCore/QProcess>
#include <QtCore/QStringList>
#include <QtCore/QTextStream>
namespace Qt4ProjectManager {
namespace Internal {
class MaemoQemuRuntimeParserV1 : public MaemoQemuRuntimeParser
{
public:
MaemoQemuRuntimeParserV1(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot);
MaemoQemuRuntime parseRuntime();
private:
void fillRuntimeInformation(MaemoQemuRuntime *runtime) const;
void setEnvironment(MaemoQemuRuntime *runTime, const QString &envSpec) const;
};
class MaemoQemuRuntimeParserV2 : public MaemoQemuRuntimeParser
{
public:
MaemoQemuRuntimeParserV2(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot);
MaemoQemuRuntime parseRuntime();
private:
struct Port {
Port() : port(-1) {}
int port;
bool ssh;
};
void handleTargetTag(QString &runtimeName);
MaemoQemuRuntime handleRuntimeTag();
QProcessEnvironment handleEnvironmentTag();
QPair<QString, QString> handleVariableTag();
QList<Port> handleTcpPortListTag();
Port handlePortTag();
};
MaemoQemuRuntimeParser::MaemoQemuRuntimeParser(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot)
: m_targetName(targetName),
m_maddeRoot(maddeRoot),
m_madInfoReader(madInfoOutput)
{
}
MaemoQemuRuntime MaemoQemuRuntimeParser::parseRuntime(const QtVersion *qtVersion)
{
MaemoQemuRuntime runtime;
const QString maddeRootPath
= MaemoGlobal::maddeRoot(qtVersion->qmakeCommand());
const QString madCommand = maddeRootPath + QLatin1String("/bin/mad");
if (!QFileInfo(madCommand).exists())
return runtime;
QProcess madProc;
MaemoGlobal::callMaddeShellScript(madProc, maddeRootPath, madCommand,
QStringList() << QLatin1String("info"));
if (!madProc.waitForStarted() || !madProc.waitForFinished())
return runtime;
const QByteArray &madInfoOutput = madProc.readAllStandardOutput();
const QString &targetName
= MaemoGlobal::targetName(qtVersion->qmakeCommand());
runtime = MaemoQemuRuntimeParserV2(madInfoOutput, targetName, maddeRootPath)
.parseRuntime();
if (!runtime.m_name.isEmpty()) {
runtime.m_root = maddeRootPath + QLatin1String("/runtimes/")
+ runtime.m_name;
} else {
runtime = MaemoQemuRuntimeParserV1(madInfoOutput, targetName,
maddeRootPath).parseRuntime();
}
runtime.m_watchPath = runtime.m_root
.left(runtime.m_root.lastIndexOf(QLatin1Char('/')));
return runtime;
}
MaemoQemuRuntimeParserV1::MaemoQemuRuntimeParserV1(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot)
: MaemoQemuRuntimeParser(madInfoOutput, targetName, maddeRoot)
{
}
MaemoQemuRuntime MaemoQemuRuntimeParserV1::parseRuntime()
{
QStringList installedRuntimes;
QString targetRuntime;
while (!m_madInfoReader.atEnd() && !installedRuntimes.contains(targetRuntime)) {
if (m_madInfoReader.readNext() == QXmlStreamReader::StartElement) {
if (targetRuntime.isEmpty()
&& m_madInfoReader.name() == QLatin1String("target")) {
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (attrs.value(QLatin1String("target_id")) == m_targetName)
targetRuntime = attrs.value("runtime_id").toString();
} else if (m_madInfoReader.name() == QLatin1String("runtime")) {
const QXmlStreamAttributes attrs = m_madInfoReader.attributes();
while (!m_madInfoReader.atEnd()) {
if (m_madInfoReader.readNext() == QXmlStreamReader::EndElement
&& m_madInfoReader.name() == QLatin1String("runtime"))
break;
if (m_madInfoReader.tokenType() == QXmlStreamReader::StartElement
&& m_madInfoReader.name() == QLatin1String("installed")) {
if (m_madInfoReader.readNext() == QXmlStreamReader::Characters
&& m_madInfoReader.text() == QLatin1String("true")) {
if (attrs.hasAttribute(QLatin1String("runtime_id")))
installedRuntimes << attrs.value(QLatin1String("runtime_id")).toString();
else if (attrs.hasAttribute(QLatin1String("id"))) {
// older MADDE seems to use only id
installedRuntimes << attrs.value(QLatin1String("id")).toString();
}
}
break;
}
}
}
}
}
MaemoQemuRuntime runtime;
if (installedRuntimes.contains(targetRuntime)) {
runtime.m_name = targetRuntime;
runtime.m_root = m_maddeRoot + QLatin1String("/runtimes/")
+ targetRuntime;
fillRuntimeInformation(&runtime);
}
return runtime;
}
void MaemoQemuRuntimeParserV1::fillRuntimeInformation(MaemoQemuRuntime *runtime) const
{
const QStringList files = QDir(runtime->m_root).entryList(QDir::Files
| QDir::NoSymLinks | QDir::NoDotAndDotDot);
const QLatin1String infoFile("information");
if (files.contains(infoFile)) {
QFile file(runtime->m_root + QLatin1Char('/') + infoFile);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QMap<QString, QString> map;
QTextStream stream(&file);
while (!stream.atEnd()) {
const QString &line = stream.readLine().trimmed();
const int index = line.indexOf(QLatin1Char('='));
map.insert(line.mid(0, index).remove(QLatin1Char('\'')),
line.mid(index + 1).remove(QLatin1Char('\'')));
}
runtime->m_bin = map.value(QLatin1String("qemu"));
runtime->m_args = map.value(QLatin1String("qemu_args"));
setEnvironment(runtime, map.value(QLatin1String("libpath")));
runtime->m_sshPort = map.value(QLatin1String("sshport"));
runtime->m_freePorts = MaemoPortList();
int i = 2;
while (true) {
const QString port = map.value(QLatin1String("redirport")
+ QString::number(i++));
if (port.isEmpty())
break;
runtime->m_freePorts.addPort(port.toInt());
}
// This is complex because of extreme MADDE weirdness.
const QString root = m_maddeRoot + QLatin1Char('/');
const bool pathIsRelative = QFileInfo(runtime->m_bin).isRelative();
runtime->m_bin =
#ifdef Q_OS_WIN
root + (pathIsRelative
? QLatin1String("madlib/") + runtime->m_bin // Fremantle.
: runtime->m_bin) // Harmattan.
+ QLatin1String(".exe");
#else
pathIsRelative
? root + QLatin1String("madlib/") + runtime->m_bin // Fremantle.
: runtime->m_bin; // Harmattan.
#endif
}
}
}
void MaemoQemuRuntimeParserV1::setEnvironment(MaemoQemuRuntime *runTime,
const QString &envSpec) const
{
QString remainingEnvSpec = envSpec;
QString currentKey;
runTime->m_environment = QProcessEnvironment::systemEnvironment();
while (true) {
const int nextEqualsSignPos
= remainingEnvSpec.indexOf(QLatin1Char('='));
if (nextEqualsSignPos == -1) {
if (!currentKey.isEmpty())
runTime->m_environment.insert(currentKey, remainingEnvSpec);
break;
}
const int keyStartPos
= remainingEnvSpec.lastIndexOf(QRegExp(QLatin1String("\\s")),
nextEqualsSignPos) + 1;
if (!currentKey.isEmpty()) {
const int valueEndPos
= remainingEnvSpec.lastIndexOf(QRegExp(QLatin1String("\\S")),
qMax(0, keyStartPos - 1)) + 1;
runTime->m_environment.insert(currentKey,
remainingEnvSpec.left(valueEndPos));
}
currentKey = remainingEnvSpec.mid(keyStartPos,
nextEqualsSignPos - keyStartPos);
remainingEnvSpec.remove(0, nextEqualsSignPos + 1);
}
}
MaemoQemuRuntimeParserV2::MaemoQemuRuntimeParserV2(const QString &madInfoOutput,
const QString &targetName, const QString &maddeRoot)
: MaemoQemuRuntimeParser(madInfoOutput, targetName, maddeRoot)
{
}
MaemoQemuRuntime MaemoQemuRuntimeParserV2::parseRuntime()
{
QString runtimeName;
QList<MaemoQemuRuntime> runtimes;
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("madde")) {
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("targets")) {
while (m_madInfoReader.readNextStartElement())
handleTargetTag(runtimeName);
} else if (m_madInfoReader.name() == QLatin1String("runtimes")) {
while (m_madInfoReader.readNextStartElement()) {
const MaemoQemuRuntime &rt = handleRuntimeTag();
if (!rt.m_name.isEmpty() && !rt.m_bin.isEmpty()
&& !rt.m_args.isEmpty()) {
runtimes << rt;
}
}
} else {
m_madInfoReader.skipCurrentElement();
}
}
}
}
foreach (const MaemoQemuRuntime &rt, runtimes) {
if (rt.m_name == runtimeName)
return rt;
}
return MaemoQemuRuntime();
}
void MaemoQemuRuntimeParserV2::handleTargetTag(QString &runtimeName)
{
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (m_madInfoReader.name() == QLatin1String("target") && runtimeName.isEmpty()
&& attrs.value(QLatin1String("name")) == m_targetName
&& attrs.value(QLatin1String("installed")) == QLatin1String("true")) {
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("runtime"))
runtimeName = m_madInfoReader.readElementText();
else
m_madInfoReader.skipCurrentElement();
}
} else {
m_madInfoReader.skipCurrentElement();
}
}
MaemoQemuRuntime MaemoQemuRuntimeParserV2::handleRuntimeTag()
{
MaemoQemuRuntime runtime;
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
if (m_madInfoReader.name() != QLatin1String("runtime")
|| attrs.value(QLatin1String("installed")) != QLatin1String("true")) {
m_madInfoReader.skipCurrentElement();
return runtime;
}
runtime.m_name = attrs.value(QLatin1String("name")).toString();
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("exec-path")) {
runtime.m_bin = m_madInfoReader.readElementText();
} else if (m_madInfoReader.name() == QLatin1String("args")) {
runtime.m_args = m_madInfoReader.readElementText();
} else if (m_madInfoReader.name() == QLatin1String("environment")) {
runtime.m_environment = handleEnvironmentTag();
} else if (m_madInfoReader.name() == QLatin1String("tcpportmap")) {
const QList<Port> &ports = handleTcpPortListTag();
foreach (const Port &port, ports) {
if (port.ssh)
runtime.m_sshPort = QString::number(port.port);
else
runtime.m_freePorts.addPort(port.port);
}
} else {
m_madInfoReader.skipCurrentElement();
}
}
return runtime;
}
QProcessEnvironment MaemoQemuRuntimeParserV2::handleEnvironmentTag()
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
while (m_madInfoReader.readNextStartElement()) {
const QPair<QString, QString> &var = handleVariableTag();
if (!var.first.isEmpty())
env.insert(var.first, var.second);
}
#ifdef Q_OS_WIN
const QString root = QDir::toNativeSeparators(m_maddeRoot)
+ QLatin1Char('/');
const QLatin1Char colon(';');
const QLatin1String key("PATH");
env.insert(key, root + QLatin1String("bin") + colon + env.value(key));
env.insert(key, root + QLatin1String("madlib") + colon + env.value(key));
#endif
return env;
}
QPair<QString, QString> MaemoQemuRuntimeParserV2::handleVariableTag()
{
QPair<QString, QString> var;
if (m_madInfoReader.name() != QLatin1String("variable")) {
m_madInfoReader.skipCurrentElement();
return var;
}
// TODO: Check for "purpose" attribute and handle "glbackend" in a special way
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("name"))
var.first = m_madInfoReader.readElementText();
else if (m_madInfoReader.name() == QLatin1String("value"))
var.second = m_madInfoReader.readElementText();
else
m_madInfoReader.skipCurrentElement();
}
return var;
}
QList<MaemoQemuRuntimeParserV2::Port> MaemoQemuRuntimeParserV2::handleTcpPortListTag()
{
QList<Port> ports;
while (m_madInfoReader.readNextStartElement()) {
const Port &port = handlePortTag();
if (port.port != -1)
ports << port;
}
return ports;
}
MaemoQemuRuntimeParserV2::Port MaemoQemuRuntimeParserV2::handlePortTag()
{
Port port;
if (m_madInfoReader.name() == QLatin1String("port")) {
const QXmlStreamAttributes &attrs = m_madInfoReader.attributes();
port.ssh = attrs.value(QLatin1String("service")) == QLatin1String("ssh");
while (m_madInfoReader.readNextStartElement()) {
if (m_madInfoReader.name() == QLatin1String("host"))
port.port = m_madInfoReader.readElementText().toInt();
else
m_madInfoReader.skipCurrentElement();
}
}
return port;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|>
|
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen, Daniel Melanz
// =============================================================================
//
// Front and Rear HMMWV suspension subsystems (double A-arm).
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChDoubleWishbone) and origins at the midpoint between the
// lower control arms' connection points to the chassis.
//
// All point locations are provided for the left half of the supspension.
//
// =============================================================================
#include "HMMWV_DoubleWishbone.h"
using namespace chrono;
namespace hmmwv {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
static const double in2m = 0.0254;
static const double lb2kg = 0.453592;
static const double lbf2N = 4.44822162;
static const double lbfpin2Npm = 175.12677;
const double HMMWV_DoubleWishboneFront::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneFront::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneFront::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneFront::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneFront::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneFront::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneFront::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneFront::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneFront::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneFront::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneFront::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneFront::m_springCoefficient = 167062.000;
const double HMMWV_DoubleWishboneFront::m_springRestLength = 0.339;
// -----------------------------------------------------------------------------
const double HMMWV_DoubleWishboneRear::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneRear::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneRear::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneRear::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneRear::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneRear::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneRear::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneRear::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneRear::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneRear::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneRear::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneRear::m_springCoefficient = 369149.000;
const double HMMWV_DoubleWishboneRear::m_springRestLength = 0.382;
// -----------------------------------------------------------------------------
// HMMWV shock functor class - implements a nonlinear damper
// -----------------------------------------------------------------------------
class HMMWV_ShockForce : public ChSpringForceCallback
{
public:
HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound);
virtual double operator()(double time,
double rest_length,
double length,
double vel);
private:
double m_ms_compr;
double m_ms_rebound;
double m_bs_compr;
double m_bs_rebound;
double m_F0;
double m_min_length;
double m_max_length;
};
HMMWV_ShockForce::HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound)
: m_ms_compr(midstroke_compression_slope),
m_ms_rebound(midstroke_rebound_slope),
m_bs_compr(bumpstop_compression_slope),
m_bs_rebound(bumpstop_rebound_slope),
m_F0(min_bumpstop_compression_force),
m_min_length(midstroke_lower_bound),
m_max_length(midstroke_upper_bound)
{
}
double HMMWV_ShockForce::operator()(double time,
double rest_length,
double length,
double vel)
{
/*
// On midstroke curve
if (length >= m_min_length && length <= m_max_length)
return (vel >= 0) ? -m_ms_rebound * vel : -m_ms_compr * vel;
// Hydraulic bump engaged
return (vel >= 0) ? -m_bs_rebound * vel : -m_bs_compr * vel + m_F0;
*/
return -m_bs_rebound * vel;
}
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::HMMWV_DoubleWishboneFront(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 71.50, // midstroke_compression_slope
lbfpin2Npm * 128.25, // midstroke_rebound_slope
lbfpin2Npm * 33.67, // bumpstop_compression_slope
lbfpin2Npm * 343.00, // bumpstop_rebound_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85 // midstroke_upper_bound
);
}
HMMWV_DoubleWishboneRear::HMMWV_DoubleWishboneRear(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 83.00, // midstroke_compression_slope
lbfpin2Npm * 200.00, // midstroke_rebound_slope
lbfpin2Npm * 48.75, // bumpstop_compression_slope
lbfpin2Npm * 365.00, // bumpstop_rebound_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85 // midstroke_upper_bound
);
}
// -----------------------------------------------------------------------------
// Destructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::~HMMWV_DoubleWishboneFront()
{
delete m_shockForceCB;
}
HMMWV_DoubleWishboneRear::~HMMWV_DoubleWishboneRear()
{
delete m_shockForceCB;
}
// -----------------------------------------------------------------------------
// Implementations of the getLocation() virtual methods.
// -----------------------------------------------------------------------------
const ChVector<> HMMWV_DoubleWishboneFront::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(-1.59, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(-1.59, 29.5675, -1.0350);
case UCA_F: return in2m * ChVector<>(-1.8864, 17.5575, 9.6308);
case UCA_B: return in2m * ChVector<>(-10.5596, 18.8085, 7.6992);
case UCA_U: return in2m * ChVector<>(-2.088, 28.17, 8.484);
case UCA_CM: return in2m * ChVector<>(-4.155, 23.176, 8.575);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(-1.40, 30.965, -4.65);
case LCA_CM: return in2m * ChVector<>(0, 21.528, -2.325);
case SHOCK_C: return in2m * ChVector<>(4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case SPRING_C: return in2m * ChVector<>(4.095, 20.07, 7.775);
case SPRING_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(-9.855, 17.655, 2.135);
case TIEROD_U: return in2m * ChVector<>(-6.922, 32.327, -0.643);
default: return ChVector<>(0, 0, 0);
}
}
const ChVector<> HMMWV_DoubleWishboneRear::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(1.40, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(1.40, 29.5675, -1.035);
case UCA_F: return in2m * ChVector<>(13.7445, 18.1991, 8.9604);
case UCA_B: return in2m * ChVector<>(3.0355, 18.1909, 8.8096);
case UCA_U: return in2m * ChVector<>(1.40, 28.17, 8.5);
case UCA_CM: return in2m * ChVector<>(4.895, 23.183, 8.692);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(1.40, 30.965, -4.650);
case LCA_CM: return in2m * ChVector<>(0, 21.527, -2.325);
case SHOCK_C: return in2m * ChVector<>(-4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(-3.827, 21.415, -1.511);
case SPRING_C: return in2m * ChVector<>(-4.095, 19.747, 10.098);
case SPRING_A: return in2m * ChVector<>(-3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(8.790, 16.38, 2.310);
case TIEROD_U: return in2m * ChVector<>(6.704, 32.327, -0.365);
default: return ChVector<>(0, 0, 0);
}
}
} // end namespace hmmwv
<commit_msg>Updated HMMWV Double Wishbone shock model to include hard contact<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Radu Serban, Justin Madsen, Daniel Melanz
// =============================================================================
//
// Front and Rear HMMWV suspension subsystems (double A-arm).
//
// These concrete suspension subsystems are defined with respect to right-handed
// frames with X pointing towards the front, Y to the left, and Z up (as imposed
// by the base class ChDoubleWishbone) and origins at the midpoint between the
// lower control arms' connection points to the chassis.
//
// All point locations are provided for the left half of the supspension.
//
// =============================================================================
#include "HMMWV_DoubleWishbone.h"
using namespace chrono;
namespace hmmwv {
// -----------------------------------------------------------------------------
// Static variables
// -----------------------------------------------------------------------------
static const double in2m = 0.0254;
static const double lb2kg = 0.453592;
static const double lbf2N = 4.44822162;
static const double lbfpin2Npm = 175.12677;
const double HMMWV_DoubleWishboneFront::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneFront::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneFront::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneFront::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneFront::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneFront::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneFront::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneFront::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneFront::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneFront::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneFront::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneFront::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneFront::m_springCoefficient = 167062.000;
const double HMMWV_DoubleWishboneFront::m_springRestLength = 0.339;
// -----------------------------------------------------------------------------
const double HMMWV_DoubleWishboneRear::m_UCAMass = 5.813;
const double HMMWV_DoubleWishboneRear::m_LCAMass = 23.965;
const double HMMWV_DoubleWishboneRear::m_uprightMass = 19.450;
const double HMMWV_DoubleWishboneRear::m_spindleMass = 14.705;
const double HMMWV_DoubleWishboneRear::m_spindleRadius = 0.10;
const double HMMWV_DoubleWishboneRear::m_spindleWidth = 0.06;
const double HMMWV_DoubleWishboneRear::m_LCARadius = 0.03;
const double HMMWV_DoubleWishboneRear::m_UCARadius = 0.02;
const double HMMWV_DoubleWishboneRear::m_uprightRadius = 0.04;
const ChVector<> HMMWV_DoubleWishboneRear::m_spindleInertia(0.04117, 0.07352, 0.04117); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_UCAInertia(0.03, 0.03, 0.06276); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_LCAInertia(0.4, 0.4, 0.8938); // TODO: This is not the correct value
const ChVector<> HMMWV_DoubleWishboneRear::m_uprightInertia(0.1656, 0.1934, 0.04367); // TODO: This is not the correct value
const double HMMWV_DoubleWishboneRear::m_axleInertia = 0.4;
const double HMMWV_DoubleWishboneRear::m_springCoefficient = 369149.000;
const double HMMWV_DoubleWishboneRear::m_springRestLength = 0.382;
// -----------------------------------------------------------------------------
// HMMWV shock functor class - implements a nonlinear damper
// -----------------------------------------------------------------------------
class HMMWV_ShockForce : public ChSpringForceCallback
{
public:
HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double metalmetal_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound,
double metalmetal_lower_bound,
double metalmetal_upper_bound);
virtual double operator()(double time,
double rest_length,
double length,
double vel);
private:
double m_ms_compr;
double m_ms_rebound;
double m_bs_compr;
double m_bs_rebound;
double m_metal_K;
double m_F0;
double m_ms_min_length;
double m_ms_max_length;
double m_min_length;
double m_max_length;
};
HMMWV_ShockForce::HMMWV_ShockForce(double midstroke_compression_slope,
double midstroke_rebound_slope,
double bumpstop_compression_slope,
double bumpstop_rebound_slope,
double metalmetal_slope,
double min_bumpstop_compression_force,
double midstroke_lower_bound,
double midstroke_upper_bound,
double metalmetal_lower_bound,
double metalmetal_upper_bound)
: m_ms_compr(midstroke_compression_slope),
m_ms_rebound(midstroke_rebound_slope),
m_bs_compr(bumpstop_compression_slope),
m_bs_rebound(bumpstop_rebound_slope),
m_metal_K(metalmetal_slope),
m_F0(min_bumpstop_compression_force),
m_ms_min_length(midstroke_lower_bound),
m_ms_max_length(midstroke_upper_bound),
m_min_length(metalmetal_lower_bound),
m_max_length(metalmetal_upper_bound)
{
}
double HMMWV_ShockForce::operator()(double time,
double rest_length,
double length,
double vel)
{
/*
// On midstroke curve
if (length >= m_min_length && length <= m_max_length)
return (vel >= 0) ? -m_ms_rebound * vel : -m_ms_compr * vel;
// Hydraulic bump engaged
return (vel >= 0) ? -m_bs_rebound * vel : -m_bs_compr * vel + m_F0;
*/
double force = 0;
//Calculate Damping Force
if(vel >= 0)
{
force = (length >= m_ms_max_length) ? -m_bs_rebound * vel : -m_ms_rebound * vel;
}
else
{
force = (length <= m_ms_min_length) ? -m_bs_compr * vel : -m_ms_compr * vel;
}
//Add in Shock metal to metal contact force
if(length <= m_min_length)
{
force = m_metal_K*(m_min_length-length);
}
else if(length >= m_max_length)
{
force = -m_metal_K*(length-m_max_length);
}
return force;
}
// -----------------------------------------------------------------------------
// Constructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::HMMWV_DoubleWishboneFront(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 71.50, // midstroke_compression_slope
lbfpin2Npm * 128.25, // midstroke_rebound_slope
lbfpin2Npm * 33.67, // bumpstop_compression_slope
lbfpin2Npm * 343.00, // bumpstop_rebound_slope
lbfpin2Npm * 150000, // metalmetal_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85, // midstroke_upper_bound
in2m * 12.76, // metalmetal_lower_bound
in2m * 16.48 // metalmetal_upper_boun
);
}
HMMWV_DoubleWishboneRear::HMMWV_DoubleWishboneRear(const std::string& name)
: ChDoubleWishbone(name)
{
m_shockForceCB = new HMMWV_ShockForce(
lbfpin2Npm * 83.00, // midstroke_compression_slope
lbfpin2Npm * 200.00, // midstroke_rebound_slope
lbfpin2Npm * 48.75, // bumpstop_compression_slope
lbfpin2Npm * 365.00, // bumpstop_rebound_slope
lbfpin2Npm * 150000, // metalmetal_slope
lbf2N * 3350, // min_bumpstop_compression_force
in2m * 13.76, // midstroke_lower_bound
in2m * 15.85, // midstroke_upper_bound
in2m * 12.76, // metalmetal_lower_bound
in2m * 16.48 // metalmetal_upper_bound
);
}
// -----------------------------------------------------------------------------
// Destructors
// -----------------------------------------------------------------------------
HMMWV_DoubleWishboneFront::~HMMWV_DoubleWishboneFront()
{
delete m_shockForceCB;
}
HMMWV_DoubleWishboneRear::~HMMWV_DoubleWishboneRear()
{
delete m_shockForceCB;
}
// -----------------------------------------------------------------------------
// Implementations of the getLocation() virtual methods.
// -----------------------------------------------------------------------------
const ChVector<> HMMWV_DoubleWishboneFront::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(-1.59, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(-1.59, 29.5675, -1.0350);
case UCA_F: return in2m * ChVector<>(-1.8864, 17.5575, 9.6308);
case UCA_B: return in2m * ChVector<>(-10.5596, 18.8085, 7.6992);
case UCA_U: return in2m * ChVector<>(-2.088, 28.17, 8.484);
case UCA_CM: return in2m * ChVector<>(-4.155, 23.176, 8.575);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(-1.40, 30.965, -4.65);
case LCA_CM: return in2m * ChVector<>(0, 21.528, -2.325);
case SHOCK_C: return in2m * ChVector<>(4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case SPRING_C: return in2m * ChVector<>(4.095, 20.07, 7.775);
case SPRING_A: return in2m * ChVector<>(3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(-9.855, 17.655, 2.135);
case TIEROD_U: return in2m * ChVector<>(-6.922, 32.327, -0.643);
default: return ChVector<>(0, 0, 0);
}
}
const ChVector<> HMMWV_DoubleWishboneRear::getLocation(PointId which)
{
switch (which) {
case SPINDLE: return in2m * ChVector<>(1.40, 35.815, -1.035);
case UPRIGHT: return in2m * ChVector<>(1.40, 29.5675, -1.035);
case UCA_F: return in2m * ChVector<>(13.7445, 18.1991, 8.9604);
case UCA_B: return in2m * ChVector<>(3.0355, 18.1909, 8.8096);
case UCA_U: return in2m * ChVector<>(1.40, 28.17, 8.5);
case UCA_CM: return in2m * ChVector<>(4.895, 23.183, 8.692);
case LCA_F: return in2m * ChVector<>(8.7900, 12.09, 0);
case LCA_B: return in2m * ChVector<>(-8.7900, 12.09, 0);
case LCA_U: return in2m * ChVector<>(1.40, 30.965, -4.650);
case LCA_CM: return in2m * ChVector<>(0, 21.527, -2.325);
case SHOCK_C: return in2m * ChVector<>(-4.095, 19.598, 12.722);
case SHOCK_A: return in2m * ChVector<>(-3.827, 21.415, -1.511);
case SPRING_C: return in2m * ChVector<>(-4.095, 19.747, 10.098);
case SPRING_A: return in2m * ChVector<>(-3.827, 21.385, -1.835);
case TIEROD_C: return in2m * ChVector<>(8.790, 16.38, 2.310);
case TIEROD_U: return in2m * ChVector<>(6.704, 32.327, -0.365);
default: return ChVector<>(0, 0, 0);
}
}
} // end namespace hmmwv
<|endoftext|>
|
<commit_before>
/*++
Copyright (c) 2015 Microsoft Corporation
--*/
#include<iostream>
#include<stdlib.h>
#include<limits.h>
#include"trace.h"
#include"memory_manager.h"
#include"error_codes.h"
#include"z3_omp.h"
// The following two function are automatically generated by the mk_make.py script.
// The script collects ADD_INITIALIZER and ADD_FINALIZER commands in the .h files.
// For example, rational.h contains
// ADD_INITIALIZER('rational::initialize();')
// ADD_FINALIZER('rational::finalize();')
// Thus, any executable or shared object (DLL) that depends on rational.h
// will have an automalically generated file mem_initializer.cpp containing
// mem_initialize()
// mem_finalize()
// and these functions will include the statements:
// rational::initialize();
//
// rational::finalize();
void mem_initialize();
void mem_finalize();
// If PROFILE_MEMORY is defined, Z3 will display the amount of memory used, and the number of synchronization steps during finalization
// #define PROFILE_MEMORY
out_of_memory_error::out_of_memory_error():z3_error(ERR_MEMOUT) {
}
exceeded_memory_allocations::exceeded_memory_allocations():z3_error(ERR_ALLOC_EXCEEDED) {
}
static volatile bool g_memory_out_of_memory = false;
static bool g_memory_initialized = false;
static long long g_memory_alloc_size = 0;
static long long g_memory_max_size = 0;
static long long g_memory_max_used_size = 0;
static long long g_memory_watermark = 0;
static long long g_memory_alloc_count = 0;
static long long g_memory_max_alloc_count = 0;
static bool g_exit_when_out_of_memory = false;
static char const * g_out_of_memory_msg = "ERROR: out of memory";
static volatile bool g_memory_fully_initialized = false;
void memory::exit_when_out_of_memory(bool flag, char const * msg) {
g_exit_when_out_of_memory = flag;
if (flag && msg)
g_out_of_memory_msg = msg;
}
static void throw_out_of_memory() {
#pragma omp critical (z3_memory_manager)
{
g_memory_out_of_memory = true;
}
if (g_exit_when_out_of_memory) {
std::cerr << g_out_of_memory_msg << "\n";
exit(ERR_MEMOUT);
}
else {
throw out_of_memory_error();
}
}
static void throw_alloc_counts_exceeded() {
#pragma omp critical (z3_memory_manager)
{
// reset the count to avoid re-throwing while
// the exception is being thrown.
g_memory_alloc_count = 0;
}
throw exceeded_memory_allocations();
}
#ifdef PROFILE_MEMORY
static unsigned g_synch_counter = 0;
class mem_usage_report {
public:
~mem_usage_report() {
std::cerr << "(memory :max " << g_memory_max_used_size
<< " :allocs " << g_memory_alloc_count
<< " :final " << g_memory_alloc_size
<< " :synch " << g_synch_counter << ")" << std::endl;
}
};
mem_usage_report g_info;
#endif
void memory::initialize(size_t max_size) {
bool initialize = false;
#pragma omp critical (z3_memory_manager)
{
// only update the maximum size if max_size != UINT_MAX
if (max_size != UINT_MAX)
g_memory_max_size = max_size;
if (!g_memory_initialized) {
g_memory_initialized = true;
initialize = true;
}
}
if (initialize) {
g_memory_out_of_memory = false;
mem_initialize();
g_memory_fully_initialized = true;
}
else {
// Delay the current thread until the DLL is fully initialized
// Without this, multiple threads can start to call API functions
// before memory::initialize(...) finishes.
while (!g_memory_fully_initialized)
/* wait */ ;
}
}
bool memory::is_out_of_memory() {
bool r = false;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_out_of_memory;
}
return r;
}
void memory::set_high_watermark(size_t watermark) {
// This method is only safe to invoke at initialization time, that is, before the threads are created.
g_memory_watermark = watermark;
}
bool memory::above_high_watermark() {
if (g_memory_watermark == 0)
return false;
bool r;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_watermark < g_memory_alloc_size;
}
return r;
}
// The following methods are only safe to invoke at
// initialization time, that is, before threads are created.
void memory::set_max_size(size_t max_size) {
g_memory_max_size = max_size;
}
void memory::set_max_alloc_count(size_t max_count) {
g_memory_max_alloc_count = max_count;
}
static bool g_finalizing = false;
void memory::finalize() {
if (g_memory_initialized) {
g_finalizing = true;
mem_finalize();
g_memory_initialized = false;
g_finalizing = false;
}
}
unsigned long long memory::get_allocation_size() {
long long r;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_alloc_size;
}
if (r < 0)
r = 0;
return r;
}
unsigned long long memory::get_max_used_memory() {
unsigned long long r;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_max_used_size;
}
return r;
}
unsigned long long memory::get_allocation_count() {
return g_memory_alloc_count;
}
void memory::display_max_usage(std::ostream & os) {
unsigned long long mem = get_max_used_memory();
os << "max. heap size: "
<< static_cast<double>(mem)/static_cast<double>(1024*1024)
<< " Mbytes\n";
}
void memory::display_i_max_usage(std::ostream & os) {
unsigned long long mem = get_max_used_memory();
std::cout << "MEMORY "
<< static_cast<double>(mem)/static_cast<double>(1024*1024)
<< "\n";
}
#if _DEBUG
void memory::deallocate(char const * file, int line, void * p) {
deallocate(p);
TRACE_CODE(if (!g_finalizing) TRACE("memory", tout << "dealloc " << std::hex << p << std::dec << " " << file << ":" << line << "\n";););
}
void * memory::allocate(char const* file, int line, char const* obj, size_t s) {
void * r = allocate(s);
TRACE("memory", tout << "alloc " << std::hex << r << std::dec << " " << file << ":" << line << " " << obj << " " << s << "\n";);
return r;
}
#endif
#if defined(_WINDOWS) || defined(_USE_THREAD_LOCAL)
// ==================================
// ==================================
// THREAD LOCAL VERSION
// ==================================
// ==================================
// We only integrate the local thread counters with the global one
// when the local counter > SYNCH_THRESHOLD
#define SYNCH_THRESHOLD 100000
#ifdef _WINDOWS
// Actually this is VS specific instead of Windows specific.
__declspec(thread) long long g_memory_thread_alloc_size = 0;
__declspec(thread) long long g_memory_thread_alloc_count = 0;
#else
// GCC style
__thread long long g_memory_thread_alloc_size = 0;
__thread long long g_memory_thread_alloc_count = 0;
#endif
static void synchronize_counters(bool allocating) {
#ifdef PROFILE_MEMORY
g_synch_counter++;
#endif
bool out_of_mem = false;
bool counts_exceeded = false;
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size += g_memory_thread_alloc_size;
g_memory_alloc_count += g_memory_thread_alloc_count;
if (g_memory_alloc_size > g_memory_max_used_size)
g_memory_max_used_size = g_memory_alloc_size;
if (g_memory_max_size != 0 && g_memory_alloc_size > g_memory_max_size)
out_of_mem = true;
if (g_memory_max_alloc_count != 0 && g_memory_alloc_count > g_memory_max_alloc_count)
counts_exceeded = true;
}
g_memory_thread_alloc_size = 0;
if (out_of_mem && allocating) {
throw_out_of_memory();
}
if (counts_exceeded && allocating) {
throw_alloc_counts_exceeded();
}
}
void memory::deallocate(void * p) {
size_t * sz_p = reinterpret_cast<size_t*>(p) - 1;
size_t sz = *sz_p;
void * real_p = reinterpret_cast<void*>(sz_p);
g_memory_thread_alloc_size -= sz;
free(real_p);
if (g_memory_thread_alloc_size < -SYNCH_THRESHOLD) {
synchronize_counters(false);
}
}
void * memory::allocate(size_t s) {
if (s == 0)
return 0;
s = s + sizeof(size_t); // we allocate an extra field!
void * r = malloc(s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
g_memory_thread_alloc_size += s;
g_memory_thread_alloc_count += 1;
if (g_memory_thread_alloc_size > SYNCH_THRESHOLD) {
synchronize_counters(true);
}
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
void* memory::reallocate(void *p, size_t s) {
size_t *sz_p = reinterpret_cast<size_t*>(p)-1;
size_t sz = *sz_p;
void *real_p = reinterpret_cast<void*>(sz_p);
s = s + sizeof(size_t); // we allocate an extra field!
g_memory_thread_alloc_size += s - sz;
g_memory_thread_alloc_count += 1;
if (g_memory_thread_alloc_size > SYNCH_THRESHOLD) {
synchronize_counters(true);
}
void *r = realloc(real_p, s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
#else
// ==================================
// ==================================
// NO THREAD LOCAL VERSION
// ==================================
// ==================================
// allocate & deallocate without using thread local storage
void memory::deallocate(void * p) {
size_t * sz_p = reinterpret_cast<size_t*>(p) - 1;
size_t sz = *sz_p;
void * real_p = reinterpret_cast<void*>(sz_p);
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size -= sz;
}
free(real_p);
}
void * memory::allocate(size_t s) {
if (s == 0)
return 0;
s = s + sizeof(size_t); // we allocate an extra field!
bool out_of_mem = false, counts_exceeded = false;
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size += s;
g_memory_alloc_count += 1;
if (g_memory_alloc_size > g_memory_max_used_size)
g_memory_max_used_size = g_memory_alloc_size;
if (g_memory_max_size != 0 && g_memory_alloc_size > g_memory_max_size)
out_of_mem = true;
if (g_memory_max_alloc_count != 0 && g_memory_alloc_count > g_memory_max_alloc_count)
counts_exceeded = true;
}
if (out_of_mem)
throw_out_of_memory();
if (counts_exceeded)
throw_alloc_counts_exceeded();
void * r = malloc(s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
void* memory::reallocate(void *p, size_t s) {
size_t * sz_p = reinterpret_cast<size_t*>(p) - 1;
size_t sz = *sz_p;
void * real_p = reinterpret_cast<void*>(sz_p);
s = s + sizeof(size_t); // we allocate an extra field!
bool out_of_mem = false, counts_exceeded = false;
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size += s - sz;
g_memory_alloc_count += 1;
if (g_memory_alloc_size > g_memory_max_used_size)
g_memory_max_used_size = g_memory_alloc_size;
if (g_memory_max_size != 0 && g_memory_alloc_size > g_memory_max_size)
out_of_mem = true;
if (g_memory_max_alloc_count != 0 && g_memory_alloc_count > g_memory_max_alloc_count)
counts_exceeded = true;
}
if (out_of_mem)
throw_out_of_memory();
if (counts_exceeded)
throw_alloc_counts_exceeded();
void *r = realloc(real_p, s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
#endif
<commit_msg>remove the optimization for 0-byte allocations I wasn't able to trigger with any SMT or API benchmark Removing it ensures the function never returns null and enables further optimizations. I get an amazing avg speedup of 0.9%<commit_after>
/*++
Copyright (c) 2015 Microsoft Corporation
--*/
#include<iostream>
#include<stdlib.h>
#include<limits.h>
#include"trace.h"
#include"memory_manager.h"
#include"error_codes.h"
#include"z3_omp.h"
// The following two function are automatically generated by the mk_make.py script.
// The script collects ADD_INITIALIZER and ADD_FINALIZER commands in the .h files.
// For example, rational.h contains
// ADD_INITIALIZER('rational::initialize();')
// ADD_FINALIZER('rational::finalize();')
// Thus, any executable or shared object (DLL) that depends on rational.h
// will have an automalically generated file mem_initializer.cpp containing
// mem_initialize()
// mem_finalize()
// and these functions will include the statements:
// rational::initialize();
//
// rational::finalize();
void mem_initialize();
void mem_finalize();
// If PROFILE_MEMORY is defined, Z3 will display the amount of memory used, and the number of synchronization steps during finalization
// #define PROFILE_MEMORY
out_of_memory_error::out_of_memory_error():z3_error(ERR_MEMOUT) {
}
exceeded_memory_allocations::exceeded_memory_allocations():z3_error(ERR_ALLOC_EXCEEDED) {
}
static volatile bool g_memory_out_of_memory = false;
static bool g_memory_initialized = false;
static long long g_memory_alloc_size = 0;
static long long g_memory_max_size = 0;
static long long g_memory_max_used_size = 0;
static long long g_memory_watermark = 0;
static long long g_memory_alloc_count = 0;
static long long g_memory_max_alloc_count = 0;
static bool g_exit_when_out_of_memory = false;
static char const * g_out_of_memory_msg = "ERROR: out of memory";
static volatile bool g_memory_fully_initialized = false;
void memory::exit_when_out_of_memory(bool flag, char const * msg) {
g_exit_when_out_of_memory = flag;
if (flag && msg)
g_out_of_memory_msg = msg;
}
static void throw_out_of_memory() {
#pragma omp critical (z3_memory_manager)
{
g_memory_out_of_memory = true;
}
if (g_exit_when_out_of_memory) {
std::cerr << g_out_of_memory_msg << "\n";
exit(ERR_MEMOUT);
}
else {
throw out_of_memory_error();
}
}
static void throw_alloc_counts_exceeded() {
#pragma omp critical (z3_memory_manager)
{
// reset the count to avoid re-throwing while
// the exception is being thrown.
g_memory_alloc_count = 0;
}
throw exceeded_memory_allocations();
}
#ifdef PROFILE_MEMORY
static unsigned g_synch_counter = 0;
class mem_usage_report {
public:
~mem_usage_report() {
std::cerr << "(memory :max " << g_memory_max_used_size
<< " :allocs " << g_memory_alloc_count
<< " :final " << g_memory_alloc_size
<< " :synch " << g_synch_counter << ")" << std::endl;
}
};
mem_usage_report g_info;
#endif
void memory::initialize(size_t max_size) {
bool initialize = false;
#pragma omp critical (z3_memory_manager)
{
// only update the maximum size if max_size != UINT_MAX
if (max_size != UINT_MAX)
g_memory_max_size = max_size;
if (!g_memory_initialized) {
g_memory_initialized = true;
initialize = true;
}
}
if (initialize) {
g_memory_out_of_memory = false;
mem_initialize();
g_memory_fully_initialized = true;
}
else {
// Delay the current thread until the DLL is fully initialized
// Without this, multiple threads can start to call API functions
// before memory::initialize(...) finishes.
while (!g_memory_fully_initialized)
/* wait */ ;
}
}
bool memory::is_out_of_memory() {
bool r = false;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_out_of_memory;
}
return r;
}
void memory::set_high_watermark(size_t watermark) {
// This method is only safe to invoke at initialization time, that is, before the threads are created.
g_memory_watermark = watermark;
}
bool memory::above_high_watermark() {
if (g_memory_watermark == 0)
return false;
bool r;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_watermark < g_memory_alloc_size;
}
return r;
}
// The following methods are only safe to invoke at
// initialization time, that is, before threads are created.
void memory::set_max_size(size_t max_size) {
g_memory_max_size = max_size;
}
void memory::set_max_alloc_count(size_t max_count) {
g_memory_max_alloc_count = max_count;
}
static bool g_finalizing = false;
void memory::finalize() {
if (g_memory_initialized) {
g_finalizing = true;
mem_finalize();
g_memory_initialized = false;
g_finalizing = false;
}
}
unsigned long long memory::get_allocation_size() {
long long r;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_alloc_size;
}
if (r < 0)
r = 0;
return r;
}
unsigned long long memory::get_max_used_memory() {
unsigned long long r;
#pragma omp critical (z3_memory_manager)
{
r = g_memory_max_used_size;
}
return r;
}
unsigned long long memory::get_allocation_count() {
return g_memory_alloc_count;
}
void memory::display_max_usage(std::ostream & os) {
unsigned long long mem = get_max_used_memory();
os << "max. heap size: "
<< static_cast<double>(mem)/static_cast<double>(1024*1024)
<< " Mbytes\n";
}
void memory::display_i_max_usage(std::ostream & os) {
unsigned long long mem = get_max_used_memory();
std::cout << "MEMORY "
<< static_cast<double>(mem)/static_cast<double>(1024*1024)
<< "\n";
}
#if _DEBUG
void memory::deallocate(char const * file, int line, void * p) {
deallocate(p);
TRACE_CODE(if (!g_finalizing) TRACE("memory", tout << "dealloc " << std::hex << p << std::dec << " " << file << ":" << line << "\n";););
}
void * memory::allocate(char const* file, int line, char const* obj, size_t s) {
void * r = allocate(s);
TRACE("memory", tout << "alloc " << std::hex << r << std::dec << " " << file << ":" << line << " " << obj << " " << s << "\n";);
return r;
}
#endif
#if defined(_WINDOWS) || defined(_USE_THREAD_LOCAL)
// ==================================
// ==================================
// THREAD LOCAL VERSION
// ==================================
// ==================================
// We only integrate the local thread counters with the global one
// when the local counter > SYNCH_THRESHOLD
#define SYNCH_THRESHOLD 100000
#ifdef _WINDOWS
// Actually this is VS specific instead of Windows specific.
__declspec(thread) long long g_memory_thread_alloc_size = 0;
__declspec(thread) long long g_memory_thread_alloc_count = 0;
#else
// GCC style
__thread long long g_memory_thread_alloc_size = 0;
__thread long long g_memory_thread_alloc_count = 0;
#endif
static void synchronize_counters(bool allocating) {
#ifdef PROFILE_MEMORY
g_synch_counter++;
#endif
bool out_of_mem = false;
bool counts_exceeded = false;
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size += g_memory_thread_alloc_size;
g_memory_alloc_count += g_memory_thread_alloc_count;
if (g_memory_alloc_size > g_memory_max_used_size)
g_memory_max_used_size = g_memory_alloc_size;
if (g_memory_max_size != 0 && g_memory_alloc_size > g_memory_max_size)
out_of_mem = true;
if (g_memory_max_alloc_count != 0 && g_memory_alloc_count > g_memory_max_alloc_count)
counts_exceeded = true;
}
g_memory_thread_alloc_size = 0;
if (out_of_mem && allocating) {
throw_out_of_memory();
}
if (counts_exceeded && allocating) {
throw_alloc_counts_exceeded();
}
}
void memory::deallocate(void * p) {
size_t * sz_p = reinterpret_cast<size_t*>(p) - 1;
size_t sz = *sz_p;
void * real_p = reinterpret_cast<void*>(sz_p);
g_memory_thread_alloc_size -= sz;
free(real_p);
if (g_memory_thread_alloc_size < -SYNCH_THRESHOLD) {
synchronize_counters(false);
}
}
void * memory::allocate(size_t s) {
s = s + sizeof(size_t); // we allocate an extra field!
void * r = malloc(s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
g_memory_thread_alloc_size += s;
g_memory_thread_alloc_count += 1;
if (g_memory_thread_alloc_size > SYNCH_THRESHOLD) {
synchronize_counters(true);
}
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
void* memory::reallocate(void *p, size_t s) {
size_t *sz_p = reinterpret_cast<size_t*>(p)-1;
size_t sz = *sz_p;
void *real_p = reinterpret_cast<void*>(sz_p);
s = s + sizeof(size_t); // we allocate an extra field!
g_memory_thread_alloc_size += s - sz;
g_memory_thread_alloc_count += 1;
if (g_memory_thread_alloc_size > SYNCH_THRESHOLD) {
synchronize_counters(true);
}
void *r = realloc(real_p, s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
#else
// ==================================
// ==================================
// NO THREAD LOCAL VERSION
// ==================================
// ==================================
// allocate & deallocate without using thread local storage
void memory::deallocate(void * p) {
size_t * sz_p = reinterpret_cast<size_t*>(p) - 1;
size_t sz = *sz_p;
void * real_p = reinterpret_cast<void*>(sz_p);
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size -= sz;
}
free(real_p);
}
void * memory::allocate(size_t s) {
s = s + sizeof(size_t); // we allocate an extra field!
bool out_of_mem = false, counts_exceeded = false;
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size += s;
g_memory_alloc_count += 1;
if (g_memory_alloc_size > g_memory_max_used_size)
g_memory_max_used_size = g_memory_alloc_size;
if (g_memory_max_size != 0 && g_memory_alloc_size > g_memory_max_size)
out_of_mem = true;
if (g_memory_max_alloc_count != 0 && g_memory_alloc_count > g_memory_max_alloc_count)
counts_exceeded = true;
}
if (out_of_mem)
throw_out_of_memory();
if (counts_exceeded)
throw_alloc_counts_exceeded();
void * r = malloc(s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
void* memory::reallocate(void *p, size_t s) {
size_t * sz_p = reinterpret_cast<size_t*>(p) - 1;
size_t sz = *sz_p;
void * real_p = reinterpret_cast<void*>(sz_p);
s = s + sizeof(size_t); // we allocate an extra field!
bool out_of_mem = false, counts_exceeded = false;
#pragma omp critical (z3_memory_manager)
{
g_memory_alloc_size += s - sz;
g_memory_alloc_count += 1;
if (g_memory_alloc_size > g_memory_max_used_size)
g_memory_max_used_size = g_memory_alloc_size;
if (g_memory_max_size != 0 && g_memory_alloc_size > g_memory_max_size)
out_of_mem = true;
if (g_memory_max_alloc_count != 0 && g_memory_alloc_count > g_memory_max_alloc_count)
counts_exceeded = true;
}
if (out_of_mem)
throw_out_of_memory();
if (counts_exceeded)
throw_alloc_counts_exceeded();
void *r = realloc(real_p, s);
if (r == 0)
throw_out_of_memory();
*(static_cast<size_t*>(r)) = s;
return static_cast<size_t*>(r) + 1; // we return a pointer to the location after the extra field
}
#endif
<|endoftext|>
|
<commit_before>/*
* AnimDataModule.cpp
*
* Copyright (C) 2008 - 2009 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/view/AnimDataModule.h"
#include "vislib/assert.h"
#include "vislib/sys/Log.h"
using namespace megamol::core;
#define MM_ADM_COUNT_LOCKED_FRAMES
/*
* view::AnimDataModule::AnimDataModule
*/
view::AnimDataModule::AnimDataModule(void) : Module(), frameCnt(0),
loader(loaderFunction), frameCache(NULL), cacheSize(0),
stateLock(), lastRequested(0) {
this->isRunning.store(false);
}
/*
* view::AnimDataModule::~AnimDataModule
*/
view::AnimDataModule::~AnimDataModule(void) {
this->Release();
Frame ** frames = this->frameCache;
// this->frameCache = NULL;
this->isRunning.store(false);
if (this->loader.IsRunning()) {
this->loader.Join();
}
this->frameCache = NULL;
if (frames != NULL) {
for (unsigned int i = 0; i < this->cacheSize; i++) {
delete frames[i];
}
delete[] frames;
}
}
/*
* view::AnimDataModule::initframeCache
*/
void view::AnimDataModule::initFrameCache(unsigned int cacheSize) {
ASSERT(this->loader.IsRunning() == false);
ASSERT(cacheSize > 0);
ASSERT(this->frameCnt > 0);
if (cacheSize > this->frameCnt) {
cacheSize = this->frameCnt; // because we don't need more
}
if (this->frameCache != NULL) {
for (unsigned int i = 0; i < this->cacheSize; i++) {
delete this->frameCache[i];
}
delete[] this->frameCache;
}
this->cacheSize = cacheSize;
this->frameCache = new Frame*[this->cacheSize];
bool frameConstructionError = false;
for (unsigned int i = 0; i < this->cacheSize; i++) {
this->frameCache[i] = this->constructFrame();
ASSERT(&this->frameCache[i]->owner == this);
if (this->frameCache[i] != NULL) {
this->frameCache[i]->state = Frame::STATE_INVALID;
} else {
frameConstructionError = true;
}
}
if (!frameConstructionError) {
this->frameCache[0]->state = Frame::STATE_LOADING;
this->loadFrame(this->frameCache[0], 0); // load first frame directly.
this->frameCache[0]->state = Frame::STATE_AVAILABLE;
this->lastRequested = 0;
this->isRunning.store(true);
this->loader.Start(this);
} else {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to create frame data cache ('constructFrame' returned 'NULL').");
}
}
/*
* view::AnimDataModule::requestFrame
*/
view::AnimDataModule::Frame * view::AnimDataModule::requestLockedFrame(unsigned int idx) {
Frame *retval = NULL;
int dist, minDist = this->frameCnt;
static bool deadlockwarning = true;
this->stateLock.Lock();
this->lastRequested = idx; // TODO: choose better caching strategy!!!
for (unsigned int i = 0; i < this->cacheSize; i++) {
if ((this->frameCache[i]->state == Frame::STATE_AVAILABLE)
|| (this->frameCache[i]->state == Frame::STATE_INUSE)) {
// note: do not wrap distance around!
dist = labs(this->frameCache[i]->frame - idx);
if (dist == 0) {
retval = this->frameCache[i];
break;
} else if (dist < minDist) {
retval = this->frameCache[i];
minDist = dist;
}
}
}
if (retval != NULL) {
retval->state = Frame::STATE_INUSE;
}
this->stateLock.Unlock();
if (deadlockwarning
#if !(defined(DEBUG) || defined(_DEBUG))
&& (this->cacheSize < this->frameCnt)
// streaming is required to handle this data set
#endif /* !(defined(DEBUG) || defined(_DEBUG)) */
) {
unsigned int clcf = 0;
for (unsigned int i = 0; i < this->cacheSize; i++) {
if (this->frameCache[i]->state == Frame::STATE_INUSE) {
clcf++;
}
}
//printf("======== %u frames locked\n", clcf);
if ((clcf == this->cacheSize) && (this->cacheSize > 2)) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Possible data frame cache deadlock detected!");
deadlockwarning = false;
}
}
return retval;
}
/*
* view::AnimDataModule::requestLockedFrame
*/
view::AnimDataModule::Frame * view::AnimDataModule::requestLockedFrame(unsigned int idx, bool forceIdx) {
Frame *f = this->requestLockedFrame(idx);
if ((f->FrameNumber() == idx) || (!forceIdx)) return f;
// wrong frame number and frame is forced
// clamp idx
if (idx >= this->frameCnt) {
idx = this->frameCnt - 1;
f->Unlock();
f = this->requestLockedFrame(idx);
}
// wait for the new frame
while (idx != f->FrameNumber()) {
f->Unlock();
// HAZARD: This will wait for all eternity if the requested frame is never loaded
vislib::sys::Thread::Sleep(100); // time for the loader thread to load
f = this->requestLockedFrame(idx);
}
return f;
}
/*
* view::AnimDataModule::resetFrameCache
*/
void view::AnimDataModule::resetFrameCache(void) {
Frame ** frames = this->frameCache;
// this->frameCache = NULL;
this->isRunning.store(false);
if (this->loader.IsRunning()) {
this->loader.Join();
}
this->frameCache = NULL;
if (frames != NULL) {
for (unsigned int i = 0; i < this->cacheSize; i++) {
delete frames[i];
}
delete[] frames;
}
this->frameCnt = 0;
this->cacheSize = 0;
this->lastRequested = 0;
}
/*
* view::AnimDataModule::setFrameCount
*/
void view::AnimDataModule::setFrameCount(unsigned int cnt) {
ASSERT(this->loader.IsRunning() == false);
ASSERT(cnt > 0);
this->frameCnt = cnt;
}
/*
* view::AnimDataModule::loaderFunction
*/
DWORD view::AnimDataModule::loaderFunction(void *userData) {
AnimDataModule *This = static_cast<AnimDataModule*>(userData);
ASSERT(This != NULL);
unsigned int index, i, j, req;
#ifdef _LOADING_REPORTING
unsigned int l;
#endif /* _LOADING_REPORTING */
Frame *frame;
while (This->isRunning.load()) {
// sleep to enforce thread changes
vislib::sys::Thread::Sleep(1);
if (!This->isRunning.load()) break;
// idea:
// 1. search for the most important frame to be loaded.
// 2. search for the best cached frame to be overwritten.
// 3. load the frame
// 1.
// Note: we do not need to lock here, because we won't change the frame
// state now, and the different states that can be set outside this
// thread are aquivalent for us.
index = req = This->lastRequested;
for (j = 0; j < This->cacheSize; j++) {
for (i = 0; i < This->cacheSize; i++) {
if (!This->isRunning.load()) break;
if (((This->frameCache[i]->state == Frame::STATE_AVAILABLE)
|| (This->frameCache[i]->state == Frame::STATE_INUSE))
&& (This->frameCache[i]->frame == index)) {
break;
}
}
if (!This->isRunning.load()) break;
if (i >= This->cacheSize) {
break;
}
index = (index + 1) % This->frameCnt;
}
if (!This->isRunning.load()) break;
if (j >= This->cacheSize) {
if (j >= This->frameCnt) {
ASSERT(This->frameCnt == This->cacheSize);
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO,
"All frames of the dataset loaded into cache. Terminating loading Thread.");
break;
}
continue;
}
// 2.
// Note: We now need to lock, because we must synchronise against
// frames changing from 'STATE_AVAILABLE' to 'STATE_INUSE'.
This->stateLock.Lock();
// core idea: search for the frame with the largest distance to the requested frame
frame = NULL; // the frame to be overwritten
j = 0; // the distance to the found frame to be overwritten
for (i = 0; i < This->cacheSize; i++) {
if (This->frameCache[i]->state == Frame::STATE_INVALID) {
frame = This->frameCache[i];
// j = UINT_MAX; // not required, since we instantly leave the loop
#ifdef _LOADING_REPORTING
l = i;
#endif /* _LOADING_REPORTING */
break;
} else if (This->frameCache[i]->state == Frame::STATE_AVAILABLE) {
// distance to the frame[i];
long ld = static_cast<long>(This->frameCache[i]->frame) - static_cast<long>(req);
if (ld < 0) {
if (ld < (static_cast<long>(This->frameCnt)) / 10) {
ld += static_cast<long>(This->frameCnt);
if (ld < 0) ld = 0; // should never happen
} else {
ld = -10 * ld;
}
}
if (j < static_cast<unsigned int>(ld)) {
frame = This->frameCache[i];
j = static_cast<unsigned int>(ld);
#ifdef _LOADING_REPORTING
l = i;
#endif /* _LOADING_REPORTING */
}
}
if (!This->isRunning.load()) break;
}
// 3.
if (frame != NULL) {
frame->state = Frame::STATE_LOADING;
}
// if frame is NULL no suitable cache buffer found for loading. This is
// mostly the case if the cache is too small or if the data source
// locks too much frames.
This->stateLock.Unlock();
if ((frame != NULL) && This->isRunning.load()) {
#ifdef _LOADING_REPORTING
printf("Loading frame %i into cache %i\n", index, l);
#endif /* _LOADING_REPORTING */
This->loadFrame(frame, index);
// we no not need to lock here, because this transition from
// 'STATE_LOADING' to 'STATE_AVAILABLE' is safe for the using
// thread.
frame->state = Frame::STATE_AVAILABLE;
}
}
vislib::sys::Log::DefaultLog.WriteInfo("The loader thread is exiting.");
return 0;
}
/*
* view::AnimDataModule::unlock
*/
void view::AnimDataModule::unlock(view::AnimDataModule::Frame *frame) {
ASSERT(&frame->owner == this);
ASSERT(frame->state == Frame::STATE_INUSE);
this->stateLock.Lock();
frame->state = Frame::STATE_AVAILABLE;
this->stateLock.Unlock();
}
<commit_msg>AnimDataModule can now measure load speed<commit_after>/*
* AnimDataModule.cpp
*
* Copyright (C) 2008 - 2009 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/view/AnimDataModule.h"
#include "vislib/assert.h"
#include "vislib/sys/Log.h"
#include <chrono>
using namespace megamol::core;
#define MM_ADM_COUNT_LOCKED_FRAMES
/*
* view::AnimDataModule::AnimDataModule
*/
view::AnimDataModule::AnimDataModule(void) : Module(), frameCnt(0),
loader(loaderFunction), frameCache(NULL), cacheSize(0),
stateLock(), lastRequested(0) {
this->isRunning.store(false);
}
/*
* view::AnimDataModule::~AnimDataModule
*/
view::AnimDataModule::~AnimDataModule(void) {
this->Release();
Frame ** frames = this->frameCache;
// this->frameCache = NULL;
this->isRunning.store(false);
if (this->loader.IsRunning()) {
this->loader.Join();
}
this->frameCache = NULL;
if (frames != NULL) {
for (unsigned int i = 0; i < this->cacheSize; i++) {
delete frames[i];
}
delete[] frames;
}
}
/*
* view::AnimDataModule::initframeCache
*/
void view::AnimDataModule::initFrameCache(unsigned int cacheSize) {
ASSERT(this->loader.IsRunning() == false);
ASSERT(cacheSize > 0);
ASSERT(this->frameCnt > 0);
if (cacheSize > this->frameCnt) {
cacheSize = this->frameCnt; // because we don't need more
}
if (this->frameCache != NULL) {
for (unsigned int i = 0; i < this->cacheSize; i++) {
delete this->frameCache[i];
}
delete[] this->frameCache;
}
this->cacheSize = cacheSize;
this->frameCache = new Frame*[this->cacheSize];
bool frameConstructionError = false;
for (unsigned int i = 0; i < this->cacheSize; i++) {
this->frameCache[i] = this->constructFrame();
ASSERT(&this->frameCache[i]->owner == this);
if (this->frameCache[i] != NULL) {
this->frameCache[i]->state = Frame::STATE_INVALID;
} else {
frameConstructionError = true;
}
}
if (!frameConstructionError) {
this->frameCache[0]->state = Frame::STATE_LOADING;
this->loadFrame(this->frameCache[0], 0); // load first frame directly.
this->frameCache[0]->state = Frame::STATE_AVAILABLE;
this->lastRequested = 0;
this->isRunning.store(true);
this->loader.Start(this);
} else {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Unable to create frame data cache ('constructFrame' returned 'NULL').");
}
}
/*
* view::AnimDataModule::requestFrame
*/
view::AnimDataModule::Frame * view::AnimDataModule::requestLockedFrame(unsigned int idx) {
Frame *retval = NULL;
int dist, minDist = this->frameCnt;
static bool deadlockwarning = true;
this->stateLock.Lock();
this->lastRequested = idx; // TODO: choose better caching strategy!!!
for (unsigned int i = 0; i < this->cacheSize; i++) {
if ((this->frameCache[i]->state == Frame::STATE_AVAILABLE)
|| (this->frameCache[i]->state == Frame::STATE_INUSE)) {
// note: do not wrap distance around!
dist = labs(this->frameCache[i]->frame - idx);
if (dist == 0) {
retval = this->frameCache[i];
break;
} else if (dist < minDist) {
retval = this->frameCache[i];
minDist = dist;
}
}
}
if (retval != NULL) {
retval->state = Frame::STATE_INUSE;
}
this->stateLock.Unlock();
if (deadlockwarning
#if !(defined(DEBUG) || defined(_DEBUG))
&& (this->cacheSize < this->frameCnt)
// streaming is required to handle this data set
#endif /* !(defined(DEBUG) || defined(_DEBUG)) */
) {
unsigned int clcf = 0;
for (unsigned int i = 0; i < this->cacheSize; i++) {
if (this->frameCache[i]->state == Frame::STATE_INUSE) {
clcf++;
}
}
//printf("======== %u frames locked\n", clcf);
if ((clcf == this->cacheSize) && (this->cacheSize > 2)) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR,
"Possible data frame cache deadlock detected!");
deadlockwarning = false;
}
}
return retval;
}
/*
* view::AnimDataModule::requestLockedFrame
*/
view::AnimDataModule::Frame * view::AnimDataModule::requestLockedFrame(unsigned int idx, bool forceIdx) {
Frame *f = this->requestLockedFrame(idx);
if ((f->FrameNumber() == idx) || (!forceIdx)) return f;
// wrong frame number and frame is forced
// clamp idx
if (idx >= this->frameCnt) {
idx = this->frameCnt - 1;
f->Unlock();
f = this->requestLockedFrame(idx);
}
// wait for the new frame
while (idx != f->FrameNumber()) {
f->Unlock();
// HAZARD: This will wait for all eternity if the requested frame is never loaded
vislib::sys::Thread::Sleep(100); // time for the loader thread to load
f = this->requestLockedFrame(idx);
}
return f;
}
/*
* view::AnimDataModule::resetFrameCache
*/
void view::AnimDataModule::resetFrameCache(void) {
Frame ** frames = this->frameCache;
// this->frameCache = NULL;
this->isRunning.store(false);
if (this->loader.IsRunning()) {
this->loader.Join();
}
this->frameCache = NULL;
if (frames != NULL) {
for (unsigned int i = 0; i < this->cacheSize; i++) {
delete frames[i];
}
delete[] frames;
}
this->frameCnt = 0;
this->cacheSize = 0;
this->lastRequested = 0;
}
/*
* view::AnimDataModule::setFrameCount
*/
void view::AnimDataModule::setFrameCount(unsigned int cnt) {
ASSERT(this->loader.IsRunning() == false);
ASSERT(cnt > 0);
this->frameCnt = cnt;
}
/*
* view::AnimDataModule::loaderFunction
*/
DWORD view::AnimDataModule::loaderFunction(void *userData) {
AnimDataModule *This = static_cast<AnimDataModule*>(userData);
ASSERT(This != NULL);
unsigned int index, i, j, req;
#ifdef _LOADING_REPORTING
unsigned int l;
#endif /* _LOADING_REPORTING */
Frame *frame;
std::chrono::high_resolution_clock::duration accumDuration;
unsigned int accumCount = 0;
std::chrono::system_clock::time_point lastReportTime = std::chrono::system_clock::now();
const std::chrono::system_clock::duration lastReportDistance = std::chrono::seconds(3);
while (This->isRunning.load()) {
// sleep to enforce thread changes
vislib::sys::Thread::Sleep(1);
if (!This->isRunning.load()) break;
// idea:
// 1. search for the most important frame to be loaded.
// 2. search for the best cached frame to be overwritten.
// 3. load the frame
// 1.
// Note: we do not need to lock here, because we won't change the frame
// state now, and the different states that can be set outside this
// thread are aquivalent for us.
index = req = This->lastRequested;
for (j = 0; j < This->cacheSize; j++) {
for (i = 0; i < This->cacheSize; i++) {
if (!This->isRunning.load()) break;
if (((This->frameCache[i]->state == Frame::STATE_AVAILABLE)
|| (This->frameCache[i]->state == Frame::STATE_INUSE))
&& (This->frameCache[i]->frame == index)) {
break;
}
}
if (!This->isRunning.load()) break;
if (i >= This->cacheSize) {
break;
}
index = (index + 1) % This->frameCnt;
}
if (!This->isRunning.load()) break;
if (j >= This->cacheSize) {
if (j >= This->frameCnt) {
ASSERT(This->frameCnt == This->cacheSize);
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_INFO,
"All frames of the dataset loaded into cache. Terminating loading Thread.");
break;
}
continue;
}
// 2.
// Note: We now need to lock, because we must synchronise against
// frames changing from 'STATE_AVAILABLE' to 'STATE_INUSE'.
This->stateLock.Lock();
// core idea: search for the frame with the largest distance to the requested frame
frame = NULL; // the frame to be overwritten
j = 0; // the distance to the found frame to be overwritten
for (i = 0; i < This->cacheSize; i++) {
if (This->frameCache[i]->state == Frame::STATE_INVALID) {
frame = This->frameCache[i];
// j = UINT_MAX; // not required, since we instantly leave the loop
#ifdef _LOADING_REPORTING
l = i;
#endif /* _LOADING_REPORTING */
break;
} else if (This->frameCache[i]->state == Frame::STATE_AVAILABLE) {
// distance to the frame[i];
long ld = static_cast<long>(This->frameCache[i]->frame) - static_cast<long>(req);
if (ld < 0) {
if (ld < (static_cast<long>(This->frameCnt)) / 10) {
ld += static_cast<long>(This->frameCnt);
if (ld < 0) ld = 0; // should never happen
} else {
ld = -10 * ld;
}
}
if (j < static_cast<unsigned int>(ld)) {
frame = This->frameCache[i];
j = static_cast<unsigned int>(ld);
#ifdef _LOADING_REPORTING
l = i;
#endif /* _LOADING_REPORTING */
}
}
if (!This->isRunning.load()) break;
}
// 3.
if (frame != NULL) {
frame->state = Frame::STATE_LOADING;
}
// if frame is NULL no suitable cache buffer found for loading. This is
// mostly the case if the cache is too small or if the data source
// locks too much frames.
This->stateLock.Unlock();
if ((frame != NULL) && This->isRunning.load()) {
#ifdef _LOADING_REPORTING
printf("Loading frame %i into cache %i\n", index, l);
#endif /* _LOADING_REPORTING */
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
This->loadFrame(frame, index);
std::chrono::high_resolution_clock::duration duration = std::chrono::high_resolution_clock::now() - start;
accumDuration += duration;
accumCount++;
std::chrono::system_clock::time_point reportTime = std::chrono::system_clock::now();
if ((reportTime - lastReportTime) > lastReportDistance) {
lastReportTime = reportTime;
if (accumCount > 0) {
vislib::sys::Log::DefaultLog.WriteInfo(100, "[%s] Loading speed: %f ms/f (%u)",
This->FullName().PeekBuffer(),
1000.0 * std::chrono::duration_cast<std::chrono::duration<double>>(accumDuration).count() / static_cast<double>(accumCount),
static_cast<unsigned int>(accumCount)
);
}
}
// we no not need to lock here, because this transition from
// 'STATE_LOADING' to 'STATE_AVAILABLE' is safe for the using
// thread.
frame->state = Frame::STATE_AVAILABLE;
}
}
if (accumCount > 0) {
vislib::sys::Log::DefaultLog.WriteInfo(100, "[%s] Loading speed: %f ms/f (%u)",
This->FullName().PeekBuffer(),
1000.0 * std::chrono::duration_cast<std::chrono::duration<double>>(accumDuration).count() / static_cast<double>(accumCount),
static_cast<unsigned int>(accumCount)
);
}
vislib::sys::Log::DefaultLog.WriteInfo("The loader thread is exiting.");
return 0;
}
/*
* view::AnimDataModule::unlock
*/
void view::AnimDataModule::unlock(view::AnimDataModule::Frame *frame) {
ASSERT(&frame->owner == this);
ASSERT(frame->state == Frame::STATE_INUSE);
this->stateLock.Lock();
frame->state = Frame::STATE_AVAILABLE;
this->stateLock.Unlock();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014-2015 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <iomanip>
#include <iostream>
#include <limits>
#include "ConsoleBotView.hpp"
static int numberOfDigits(int number) {
int digits = 0;
while (number) {
number /= 10;
digits++;
}
return digits;
}
static void printSpaces(int spaces) {
for (int i = 0; i < spaces; i++) {
std::cout << " ";
}
}
void ConsoleBotView::view() {
while (true) {
start();
char mode;
std::cin >> mode;
switch (mode) {
case 't':
gameWithTime();
break;
case 'w':
gameForWin();
break;
case 's':
gameForScore();
break;
case 'q':
return;
default:
sendHelpMessage_impl();
}
}
}
void ConsoleBotView::timeNumberMessage() const {
std::cout << "How many minutes you want to play?" << std::endl;
std::cout << "The default is " << Rules::DEFAULT_TIME
<< std::endl;
prompt();
}
void ConsoleBotView::winNumberMessage() const {
int square = getBoardsSquare();
std::cout << "What score you want to finish the "
"game?" << std::endl;
std::cout << "The default is " << square * 4
<< std::endl;
prompt();
}
void ConsoleBotView::deskSizeMessage() const {
std::cout << "Please enter size of the game board."
<< std::endl;
std::cout << "Your board will have x * x square."
<< std::endl;
std::cout << "(Where x is input size)" << std::endl;
std::cout << "Minimum size is " << Rules::MIN_WIDTH
<< " and maximum is " << Rules::MAX_WIDTH
<< std::endl;
std::cout << "But try to choose size which "
"corresponds to the size of your screen."
<< std::endl;
prompt();
}
void ConsoleBotView::outputGeneral() const {
int digits = numberOfDigits(maxDeskNumber());
int width = Console::NUMBER_OF_SPACES + digits;
int row_number = game_->desk->getRowNumber();
for (int i = row_number - 1; i >= 0; i--) {
std::cout << std::right
<< std::setw(Console::MAX_INDEX_LENGTH)
<< i << " ||";
for (int x = 0; x < row_number; x++) {
Point point;
point.col = i;
point.row = x;
std::cout << std::right << std::setw(width)
<< game_->desk->getDeskNumber(point);
}
std::cout << std::endl;
}
rowIndices(width);
std::cout << std::endl;
}
void ConsoleBotView::prompt() const {
std::cout << ">>> ";
}
void ConsoleBotView::typeError() const {
std::cout << "Error: you must enter the NUMBER" << std::endl;
std::cout << "Try again: " << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), '\n');
}
void ConsoleBotView::rangeError(TypeOfChecking type) const {
int max_int = std::numeric_limits<int>::max();
std::cout << "This number is out of allowable "
"range." << std::endl;
if (type == TIME) {
std::cout << "Please enter a POSITIVE INTEGER"
<< std::endl;
std::cout << "Maximum is " << max_int << std::endl;
} else if (type == SCORE) {
int square = getBoardsSquare();
std::cout << "For this size of the game board "
<< "minimum is " << square * 2 + 1
<< std::endl;
std::cout << "Maximum is " << max_int << std::endl;
}
std::cout << "Try again: " << std::endl;
std::cin.clear();
std::cin.ignore(max_int, '\n');
}
bool ConsoleBotView::checkRange(int verifiable,
TypeOfChecking type) const {
switch (type) {
case BOARDS_SIZE:
return ((verifiable >= Rules::MIN_WIDTH) &&
(verifiable <= Rules::MAX_WIDTH));
case TIME:
// By checking that verifiable is greater than
// zero we make sure that it's less or equal
// to the allowable maximum for int also.
// See cyclic mechanism of ints in C++.
return (verifiable > 0);
case SCORE:
int square = getBoardsSquare();
return (verifiable > square * 2);
}
}
int ConsoleBotView::getBoardsSquare() const {
int boards_size = game_->desk->getRowNumber();
return boards_size * boards_size;
}
const GameDesk* ConsoleBotView::getDesk() const {
return game_->desk.data();
}
void ConsoleBotView::finish_impl(bool fail, int score,
int steps_number) const {
if (fail) {
std::cout << "You are loser... Your score is " << score << std::endl;
} else {
std::cout << "You are winner! Your score is " << score << std::endl;
}
std::cout << "You have completed the game in " << steps_number << " steps." << std::endl;
}
void ConsoleBotView::sendHelpMessage_impl() const {
std::cout << "You must enter t, w, s or q" << std::endl;
std::cout << "Try again please." << std::endl;
}
void ConsoleBotView::startGame_impl(int row_number) {
try {
game_ = Game::make(row_number);
game_->controller->initialStateOfBoard();
} catch (std::exception& e) {
errorHandling_impl(e);
}
}
void ConsoleBotView::errorHandling_impl(std::exception& e) const {
std::cout << e.what() << std::endl;
}
int ConsoleBotView::maxDeskNumber() const {
const GameDesk* desk = game_->desk.data();
int boards_size = desk->getRowNumber();
int max = 0;
for (int i = boards_size - 1; i >= 0; i--) {
for (int x = 0; x < boards_size; x++) {
Point pt;
pt.col = i;
pt.row = x;
int current_number = desk->getDeskNumber(pt);
if (current_number > max) {
max = current_number;
}
}
}
return max;
}
void ConsoleBotView::rowIndices(int width) const {
int boards_size = game_->desk->getRowNumber();
printSpaces(Console::INDEX_FIELD);
for (int i = 0; i < width * boards_size; i++) {
std::cout << "=";
}
std::cout << std::endl;
printSpaces(Console::INDEX_FIELD);
for (int i = 0; i < boards_size; i++) {
std::cout << std::right << std::setw(width) << i;
}
}
void ConsoleBotView::start() const {
std::cout << "*** BIN_GAME ***" << std::endl;
std::cout << "----------------" << std::endl;
std::cout << "t: time mode | w: play for score | s: "
"play while not lose" << std::endl;
std::cout << "q: quit" << std::endl;
prompt();
}
void ConsoleBotView::gameForWin() {
int desk_size = getDeskSize_impl();
startGame_impl(desk_size);
int win_number = getWinNumber_impl();
const GameDesk* desk = game_->desk.data();
output_impl();
int steps_number = 0;
while (!checkFail(*desk) && !checkWin(*desk,
win_number)) {
steps_number += 1;
play();
}
finish_impl(checkFail(*desk), score(*desk),
steps_number);
}
void ConsoleBotView::gameForScore() {
int desk_size = getDeskSize_impl();
startGame_impl(desk_size);
const GameDesk* desk = game_->desk.data();
output_impl();
int steps_number = 0;
while (!checkFail(*desk)) {
steps_number += 1;
play();
}
finish_impl(checkFail(*desk), score(*desk),
steps_number);
}
void ConsoleBotView::gameWithTime() {
int desk_size = getDeskSize_impl();
int time_number = getTimeNumber_impl();
startGame_impl(desk_size);
int t1 = time(NULL);
int t2 = 0;
const GameDesk* desk = game_->desk.data();
output_impl();
int steps_number = 0;
while (!checkFail(*desk) &&
((t2 - t1) < time_number * 60)) {
steps_number += 1;
play();
t2 = time(NULL);
}
finish_impl(checkFail(*desk), score(*desk),
steps_number);
}
void ConsoleBotView::play() {
Points points = getIndex_impl();
try {
game_->controller->replace(points);
} catch (std::exception& e) {
errorHandling_impl(e);
}
output_impl();
}
<commit_msg>Console: message about font's size<commit_after>/*
* Copyright (C) 2014-2015 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#include <iomanip>
#include <iostream>
#include <limits>
#include "ConsoleBotView.hpp"
static int numberOfDigits(int number) {
int digits = 0;
while (number) {
number /= 10;
digits++;
}
return digits;
}
static void printSpaces(int spaces) {
for (int i = 0; i < spaces; i++) {
std::cout << " ";
}
}
void ConsoleBotView::view() {
while (true) {
start();
char mode;
std::cin >> mode;
switch (mode) {
case 't':
gameWithTime();
break;
case 'w':
gameForWin();
break;
case 's':
gameForScore();
break;
case 'q':
return;
default:
sendHelpMessage_impl();
}
}
}
void ConsoleBotView::timeNumberMessage() const {
std::cout << "How many minutes you want to play?" << std::endl;
std::cout << "The default is " << Rules::DEFAULT_TIME
<< std::endl;
prompt();
}
void ConsoleBotView::winNumberMessage() const {
int square = getBoardsSquare();
std::cout << "What score you want to finish the "
"game?" << std::endl;
std::cout << "The default is " << square * 4
<< std::endl;
prompt();
}
void ConsoleBotView::deskSizeMessage() const {
std::cout << "Please enter size of the game board."
<< std::endl;
std::cout << "Your board will have x * x square."
<< std::endl;
std::cout << "(Where x is input size)" << std::endl;
std::cout << "Minimum size is " << Rules::MIN_WIDTH
<< " and maximum is " << Rules::MAX_WIDTH
<< std::endl;
std::cout << "Please note that you can change font's "
"size in your Terminal Preferences if"
<< std::endl;
std::cout << "you have size mismatch of screen and "
"game board."
<< std::endl;
prompt();
}
void ConsoleBotView::outputGeneral() const {
int digits = numberOfDigits(maxDeskNumber());
int width = Console::NUMBER_OF_SPACES + digits;
int row_number = game_->desk->getRowNumber();
for (int i = row_number - 1; i >= 0; i--) {
std::cout << std::right
<< std::setw(Console::MAX_INDEX_LENGTH)
<< i << " ||";
for (int x = 0; x < row_number; x++) {
Point point;
point.col = i;
point.row = x;
std::cout << std::right << std::setw(width)
<< game_->desk->getDeskNumber(point);
}
std::cout << std::endl;
}
rowIndices(width);
std::cout << std::endl;
}
void ConsoleBotView::prompt() const {
std::cout << ">>> ";
}
void ConsoleBotView::typeError() const {
std::cout << "Error: you must enter the NUMBER" << std::endl;
std::cout << "Try again: " << std::endl;
std::cin.clear();
std::cin.ignore(std::numeric_limits<int>::max(), '\n');
}
void ConsoleBotView::rangeError(TypeOfChecking type) const {
int max_int = std::numeric_limits<int>::max();
std::cout << "This number is out of allowable "
"range." << std::endl;
if (type == TIME) {
std::cout << "Please enter a POSITIVE INTEGER"
<< std::endl;
std::cout << "Maximum is " << max_int << std::endl;
} else if (type == SCORE) {
int square = getBoardsSquare();
std::cout << "For this size of the game board "
<< "minimum is " << square * 2 + 1
<< std::endl;
std::cout << "Maximum is " << max_int << std::endl;
}
std::cout << "Try again: " << std::endl;
std::cin.clear();
std::cin.ignore(max_int, '\n');
}
bool ConsoleBotView::checkRange(int verifiable,
TypeOfChecking type) const {
switch (type) {
case BOARDS_SIZE:
return ((verifiable >= Rules::MIN_WIDTH) &&
(verifiable <= Rules::MAX_WIDTH));
case TIME:
// By checking that verifiable is greater than
// zero we make sure that it's less or equal
// to the allowable maximum for int also.
// See cyclic mechanism of ints in C++.
return (verifiable > 0);
case SCORE:
int square = getBoardsSquare();
return (verifiable > square * 2);
}
}
int ConsoleBotView::getBoardsSquare() const {
int boards_size = game_->desk->getRowNumber();
return boards_size * boards_size;
}
const GameDesk* ConsoleBotView::getDesk() const {
return game_->desk.data();
}
void ConsoleBotView::finish_impl(bool fail, int score,
int steps_number) const {
if (fail) {
std::cout << "You are loser... Your score is " << score << std::endl;
} else {
std::cout << "You are winner! Your score is " << score << std::endl;
}
std::cout << "You have completed the game in " << steps_number << " steps." << std::endl;
}
void ConsoleBotView::sendHelpMessage_impl() const {
std::cout << "You must enter t, w, s or q" << std::endl;
std::cout << "Try again please." << std::endl;
}
void ConsoleBotView::startGame_impl(int row_number) {
try {
game_ = Game::make(row_number);
game_->controller->initialStateOfBoard();
} catch (std::exception& e) {
errorHandling_impl(e);
}
}
void ConsoleBotView::errorHandling_impl(std::exception& e) const {
std::cout << e.what() << std::endl;
}
int ConsoleBotView::maxDeskNumber() const {
const GameDesk* desk = game_->desk.data();
int boards_size = desk->getRowNumber();
int max = 0;
for (int i = boards_size - 1; i >= 0; i--) {
for (int x = 0; x < boards_size; x++) {
Point pt;
pt.col = i;
pt.row = x;
int current_number = desk->getDeskNumber(pt);
if (current_number > max) {
max = current_number;
}
}
}
return max;
}
void ConsoleBotView::rowIndices(int width) const {
int boards_size = game_->desk->getRowNumber();
printSpaces(Console::INDEX_FIELD);
for (int i = 0; i < width * boards_size; i++) {
std::cout << "=";
}
std::cout << std::endl;
printSpaces(Console::INDEX_FIELD);
for (int i = 0; i < boards_size; i++) {
std::cout << std::right << std::setw(width) << i;
}
}
void ConsoleBotView::start() const {
std::cout << "*** BIN_GAME ***" << std::endl;
std::cout << "----------------" << std::endl;
std::cout << "t: time mode | w: play for score | s: "
"play while not lose" << std::endl;
std::cout << "q: quit" << std::endl;
prompt();
}
void ConsoleBotView::gameForWin() {
int desk_size = getDeskSize_impl();
startGame_impl(desk_size);
int win_number = getWinNumber_impl();
const GameDesk* desk = game_->desk.data();
output_impl();
int steps_number = 0;
while (!checkFail(*desk) && !checkWin(*desk,
win_number)) {
steps_number += 1;
play();
}
finish_impl(checkFail(*desk), score(*desk),
steps_number);
}
void ConsoleBotView::gameForScore() {
int desk_size = getDeskSize_impl();
startGame_impl(desk_size);
const GameDesk* desk = game_->desk.data();
output_impl();
int steps_number = 0;
while (!checkFail(*desk)) {
steps_number += 1;
play();
}
finish_impl(checkFail(*desk), score(*desk),
steps_number);
}
void ConsoleBotView::gameWithTime() {
int desk_size = getDeskSize_impl();
int time_number = getTimeNumber_impl();
startGame_impl(desk_size);
int t1 = time(NULL);
int t2 = 0;
const GameDesk* desk = game_->desk.data();
output_impl();
int steps_number = 0;
while (!checkFail(*desk) &&
((t2 - t1) < time_number * 60)) {
steps_number += 1;
play();
t2 = time(NULL);
}
finish_impl(checkFail(*desk), score(*desk),
steps_number);
}
void ConsoleBotView::play() {
Points points = getIndex_impl();
try {
game_->controller->replace(points);
} catch (std::exception& e) {
errorHandling_impl(e);
}
output_impl();
}
<|endoftext|>
|
<commit_before>#include "../NULLC/nullc.h"
#pragma warning(disable : 4996)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
int main(int argc, char** argv)
{
nullcInit("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 0;
}
int argIndex = 1;
FILE *mergeFile = NULL;
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 0;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 0;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 0;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 0;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 0;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return false;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return false;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -lstdc++");
pos += strlen(pos);
char tmp[256];
sprintf(tmp, "runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
}
}
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return false;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
break;
}
strcpy(moduleName, argv[argIndex++]);
}else{
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<commit_msg>Return type fix<commit_after>#include "../NULLC/nullc.h"
#pragma warning(disable : 4996)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
int main(int argc, char** argv)
{
nullcInit("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 0;
}
int argIndex = 1;
FILE *mergeFile = NULL;
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 0;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 0;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 0;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 0;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 0;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 0;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 0;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -lstdc++");
pos += strlen(pos);
char tmp[256];
sprintf(tmp, "runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/runtime.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
else
{
sprintf(tmp, "translation/%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(FILE *file = fopen(tmp, "r"))
{
*(pos++) = ' ';
strcpy(pos, tmp);
pos += strlen(pos);
fclose(file);
}
}
}
}
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 0;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
break;
}
strcpy(moduleName, argv[argIndex++]);
}else{
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<|endoftext|>
|
<commit_before>#include "../NULLC/nullc.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
bool AddSourceFile(char *&buf, const char *name)
{
if(FILE *file = fopen(name, "r"))
{
*(buf++) = ' ';
strcpy(buf, name);
buf += strlen(buf);
fclose(file);
return true;
}
return false;
}
bool SearchAndAddSourceFile(char*& buf, const char* name)
{
char tmp[256];
sprintf(tmp, "%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "NULLC/translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "../NULLC/translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
return false;
}
int main(int argc, char** argv)
{
nullcInit();
nullcAddImportPath("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c output.cpp file.nc\n");
printf("usage: nullcl -x output.exe file.nc\n");
return 1;
}
int argIndex = 1;
FILE *mergeFile = NULL;
bool verbose = false;
if(strcmp("-v", argv[argIndex]) == 0)
{
argIndex++;
verbose = true;
}
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 1;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found\n");
nullcTerminate();
return 1;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 1;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -Itranslation");
pos += strlen(pos);
strcpy(pos, " -INULLC/translation");
pos += strlen(pos);
strcpy(pos, " -I../NULLC/translation");
pos += strlen(pos);
strcpy(pos, " -O2");
pos += strlen(pos);
if(!SearchAndAddSourceFile(pos, "runtime.cpp"))
printf("Failed to find 'runtime.cpp' input file\n");
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
char tmp[256];
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(!SearchAndAddSourceFile(pos, tmp))
printf("Failed to find '%s' input file\n", tmp);
}
}
strcpy(pos, " -lstdc++ -lm");
pos += strlen(pos);
if (verbose)
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
nullcTerminate();
return 1;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
delete[] bytecode;
break;
}
if(strlen(argv[argIndex]) + 1 >= 1024)
{
printf("Module name is too long\n");
delete[] bytecode;
break;
}
strcpy(moduleName, argv[argIndex]);
argIndex++;
}
else
{
if(strlen(fileName) + 1 >= 1024)
{
printf("File name is too long\n");
delete[] bytecode;
break;
}
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
// Ont extra character for 'm' appended at the end
if(strlen(fileName) + 1 >= 1024 - 1)
{
printf("File name is too long\n");
delete[] bytecode;
break;
}
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
delete[] bytecode;
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
delete[] bytecode;
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<commit_msg>Added support for additional import paths in nullcl -c/-x options<commit_after>#include "../NULLC/nullc.h"
#if defined(_MSC_VER)
#pragma warning(disable: 4996)
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char* translationDependencies[128];
unsigned translationDependencyCount = 0;
void AddDependency(const char *fileName)
{
if(translationDependencyCount < 128)
translationDependencies[translationDependencyCount++] = fileName;
}
bool AddSourceFile(char *&buf, const char *name)
{
if(FILE *file = fopen(name, "r"))
{
*(buf++) = ' ';
strcpy(buf, name);
buf += strlen(buf);
fclose(file);
return true;
}
return false;
}
bool SearchAndAddSourceFile(char*& buf, const char* name)
{
char tmp[256];
sprintf(tmp, "%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "NULLC/translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
sprintf(tmp, "../NULLC/translation/%s", name);
if(AddSourceFile(buf, tmp))
return true;
return false;
}
int main(int argc, char** argv)
{
nullcInit();
nullcAddImportPath("Modules/");
if(argc == 1)
{
printf("usage: nullcl [-o output.ncm] file.nc [-m module.name] [file2.nc [-m module.name] ...]\n");
printf("usage: nullcl -c [-i import_folder] output.cpp file.nc\n");
printf("usage: nullcl -x [-i import_folder] output.exe file.nc\n");
return 1;
}
int argIndex = 1;
FILE *mergeFile = NULL;
bool verbose = false;
if(strcmp("-v", argv[argIndex]) == 0)
{
argIndex++;
verbose = true;
}
if(strcmp("-o", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Output file name not found after -o\n");
nullcTerminate();
return 1;
}
mergeFile = fopen(argv[argIndex], "wb");
if(!mergeFile)
{
printf("Cannot create output file %s\n", argv[argIndex]);
nullcTerminate();
return 1;
}
argIndex++;
}else if(strcmp("-c", argv[argIndex]) == 0 || strcmp("-x", argv[argIndex]) == 0){
bool link = strcmp("-x", argv[argIndex]) == 0;
argIndex++;
while(argIndex < argc && strcmp("-i", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Missing folder name after -i\n");
nullcTerminate();
return 1;
}
const char* folder = argv[argIndex++];
nullcAddImportPath(folder);
}
if(argIndex == argc)
{
printf("Output file name not found after options\n");
nullcTerminate();
return 1;
}
const char *outputName = argv[argIndex++];
if(argIndex == argc)
{
printf("Input file name not found after output file name\n");
nullcTerminate();
return 1;
}
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
nullcTerminate();
return 1;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(!nullcTranslateToC(link ? "__temp.cpp" : outputName, "main", AddDependency))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
return 1;
}
if(link)
{
// $$$ move this to a dependency file?
char cmdLine[4096];
char *pos = cmdLine;
strcpy(pos, "gcc -g -o ");
pos += strlen(pos);
strcpy(pos, outputName);
pos += strlen(pos);
strcpy(pos, " __temp.cpp");
pos += strlen(pos);
strcpy(pos, " -Itranslation");
pos += strlen(pos);
strcpy(pos, " -INULLC/translation");
pos += strlen(pos);
strcpy(pos, " -I../NULLC/translation");
pos += strlen(pos);
strcpy(pos, " -O2");
pos += strlen(pos);
if(!SearchAndAddSourceFile(pos, "runtime.cpp"))
printf("Failed to find 'runtime.cpp' input file\n");
for(unsigned i = 0; i < translationDependencyCount; i++)
{
const char *dependency = translationDependencies[i];
*(pos++) = ' ';
strcpy(pos, dependency);
pos += strlen(pos);
if(strstr(dependency, "import_"))
{
char tmp[256];
sprintf(tmp, "%s", dependency + strlen("import_"));
if(char *pos = strstr(tmp, "_nc.cpp"))
strcpy(pos, "_bind.cpp");
if(!SearchAndAddSourceFile(pos, tmp))
printf("Failed to find '%s' input file\n", tmp);
}
}
strcpy(pos, " -lstdc++ -lm");
pos += strlen(pos);
if (verbose)
printf("Command line: %s\n", cmdLine);
system(cmdLine);
}
delete[] fileContent;
nullcTerminate();
return 0;
}
int currIndex = argIndex;
while(argIndex < argc)
{
const char *fileName = argv[argIndex++];
FILE *ncFile = fopen(fileName, "rb");
if(!ncFile)
{
printf("Cannot open file %s\n", fileName);
break;
}
fseek(ncFile, 0, SEEK_END);
unsigned int textSize = ftell(ncFile);
fseek(ncFile, 0, SEEK_SET);
char *fileContent = new char[textSize+1];
fread(fileContent, 1, textSize, ncFile);
fileContent[textSize] = 0;
fclose(ncFile);
if(!nullcCompile(fileContent))
{
printf("Compilation of %s failed with error:\n%s\n", fileName, nullcGetLastError());
delete[] fileContent;
nullcTerminate();
return 1;
}
unsigned int *bytecode = NULL;
nullcGetBytecode((char**)&bytecode);
delete[] fileContent;
// Create module name
char moduleName[1024];
if(argIndex < argc && strcmp("-m", argv[argIndex]) == 0)
{
argIndex++;
if(argIndex == argc)
{
printf("Module name not found after -m\n");
delete[] bytecode;
break;
}
if(strlen(argv[argIndex]) + 1 >= 1024)
{
printf("Module name is too long\n");
delete[] bytecode;
break;
}
strcpy(moduleName, argv[argIndex]);
argIndex++;
}
else
{
if(strlen(fileName) + 1 >= 1024)
{
printf("File name is too long\n");
delete[] bytecode;
break;
}
strcpy(moduleName, fileName);
if(char *extensionPos = strchr(moduleName, '.'))
*extensionPos = '\0';
char *pos = moduleName;
while(*pos)
{
if(*pos++ == '\\' || *pos++ == '/')
pos[-1] = '.';
}
}
nullcLoadModuleByBinary(moduleName, (const char*)bytecode);
if(!mergeFile)
{
char newName[1024];
// Ont extra character for 'm' appended at the end
if(strlen(fileName) + 1 >= 1024 - 1)
{
printf("File name is too long\n");
delete[] bytecode;
break;
}
strcpy(newName, fileName);
strcat(newName, "m");
FILE *nmcFile = fopen(newName, "wb");
if(!nmcFile)
{
printf("Cannot create output file %s\n", newName);
delete[] bytecode;
break;
}
fwrite(moduleName, 1, strlen(moduleName) + 1, nmcFile);
fwrite(bytecode, 1, *bytecode, nmcFile);
fclose(nmcFile);
}else{
fwrite(moduleName, 1, strlen(moduleName) + 1, mergeFile);
fwrite(bytecode, 1, *bytecode, mergeFile);
}
delete[] bytecode;
}
if(currIndex == argIndex)
printf("None of the input files were found\n");
if(mergeFile)
fclose(mergeFile);
nullcTerminate();
return argIndex != argc;
}
<|endoftext|>
|
<commit_before>#include "StdAfx.h"
#define BUFFERSIZE (2 * 1024 * 1024)
char gBuffer[BUFFERSIZE];
int lastFrame = -1;
int framesReceived = 0;
/*
The Ultracomm object is not available in the callback, so we copy some of
its attributes into file-local variables that the callback can access.
*/
ofstream* mystream;
int myframesize;
ofstream* myindexstream;
/*
Construct Ultracomm object, connect to server,
and set/check parameters.
*/
Ultracomm::Ultracomm(const UltracommOptions& myuopt)
: uopt(myuopt),
address(myuopt.opt["address"].as<string>()),
acqmode(myuopt.opt["acqmode"].as<string>()),
datatype(myuopt.opt["datatype"].as<int>()),
verbose(myuopt.opt["verbose"].as<int>())
{
connect();
if (verbose) {
cerr << "Setting data to acquire to datatype " << datatype << ".\n";
}
ult.setDataToAcquire(datatype);
set_int_imaging_params();
check_int_imaging_params();
const int compstat = uopt.opt["compression_status"].as<int>();
if (verbose) {
cerr << "Setting compression status to " << compstat << ".\n";
}
if (! ult.setCompressionStatus(compstat)) {
cerr << "Failed to set compression status to " << compstat << ".\n";
throw ParameterMismatchError();
}
if (! ult.getDataDescriptor((uData)datatype, desc))
{
throw DataDescriptorError();
}
if (! ult.isDataAvailable((uData)datatype))
{
throw DataError();
}
// TODO: framesize assumes desc.ss is always a multiple of 8, and that might not be safe.
framesize = (desc.ss / 8) * desc.w * desc.h;
myframesize = framesize;
std::string outname = myuopt.opt["output"].as<string>();
outfile.open(outname, ios::out | ios::binary),
mystream = &outfile;
std::string outindexname = outname + ".idx.txt";
outindexfile.open(outindexname, ios::out | ios::binary);
myindexstream = &outindexfile;
if (acqmode == "continuous") {
ult.setCallback(frame_callback);
write_header(outfile, desc, 0);
}
}
/*
Connect to the Ultrasonix.
*/
void Ultracomm::connect()
{
if (verbose) {
cerr << "Connecting to ultrasonix at address " << address << ".\n";
}
if (!ult.connect(address.c_str()))
{
throw ConnectionError();
}
// Stop streaming, if necessary.
//if (ult.getStreamStatus()) {
// ult.stopStream();
//}
/*
int imgmode = ult.getActiveImagingMode();
cout << "Imaging mode is " << imgmode << ".\n";
bool im = ult.getInjectMode();
cout << "Inject mode is " << im << ".\n";
bool ss = ult.getStreamStatus();
cout << "Stream status is " << ss << ".\n";
*/
/*
TODO: throw different errors depending on problem. Note that FD_CONNECT error
is when server address is bad (e.g. 123), and SOCKET_ERROR is when we couldn't connect
(address good but not in research mode). Should also test when address is good
but ultrasound machine not running):
C:\build\ultracomm\bin\Debug>ultracomm --address 123 --output asdf
monitorConnection(): FD_CONNECT had ERROR
Could not connect to Ultrasonix.
C:\build\ultracomm\bin\Debug>ultracomm --address 192.168.1.200 --output asdf
monitorConnection(): WSAEnumNetworkEvents() ret SOCKET_ERROR (10093)
CmonitorConnection(): CONNECTION_COMM lost
ould not connect to Ultrasonix.
*/
}
/*
Disconnect from Ultrasonix.
*/
void Ultracomm::disconnect()
{
write_numframes_in_header(outfile, framesReceived);
outfile.close();
outindexfile.close();
//printf("Last frame was %d.\n", lastFrame);
double pct = 100.0 * framesReceived / (lastFrame+1);
printf("Acquired %d of %d frames (%0.4f percent).\n", framesReceived, lastFrame+1, pct);
if (ult.isConnected())
{
if (verbose) {
cerr << "Disconnecting from Ultrasonix.\n";
}
ult.disconnect();
}
else
{
if (verbose) {
cerr << "Already disconnected from Ultrasonix.\n";
}
}
}
/*
Put Ultrasonix into freeze state and wait for confirmation.
*/
void Ultracomm::wait_for_freeze()
{
// 1 = FROZEN; 0 = IMAGING
if (ult.getFreezeState() != 1)
{
if (verbose) {
cerr << "Freezing Ultrasonix.\n";
}
ult.toggleFreeze();
}
else
{
if (verbose) {
cerr << "Ultrasonix already frozen.\n";
}
}
// Wait for server to acknowledge it has frozen.
// TODO: this would be safer with a timeout.
while (ult.getFreezeState() != 1)
{
if (verbose) {
cerr << "Waiting for confirmation that Ultrasonix has frozen.\n";
}
}
/*
FIXME: Occasionally we get the message
sendAndWait(): WaitForSingleObject() ret WAIT_TIMEOUT
when retrieving cine data. When --verbose is turned on this message
usually appears in save_data() after the call to getCineData() and
before write(). According to the discussion at
http://research.ultrasonix.com/viewtopic.php?f=5&t=1100&p=4245&hilit=delay#p4245
adding a delay after toggleFreeze() can prevent this condition, so
we add it here.
Possibly this delay is not necessary when used with newer versions of
the Ultrasonix library.
*/
if (
uopt.opt["ms_delay_after_freeze"].as<int>() > 0 &&
!uopt.opt.count("freeze-only")
)
{
Sleep(uopt.opt["ms_delay_after_freeze"].as<int>());
}
}
/*
Put ultrasonix into imaging state.
*/
void Ultracomm::wait_for_unfreeze()
{
// 1 = FROZEN; 0 = IMAGING
if (ult.getFreezeState() != 0)
{
if (verbose) {
cerr << "Unfreezing Ultrasonix.\n";
}
ult.toggleFreeze();
}
else
{
if (verbose) {
cerr << "Ultrasonix already imaging.\n";
}
}
// Wait for server to acknowledge it has switched to imaging.
// TODO: this would be safer with a timeout.
while (ult.getFreezeState() != 0)
{
if (verbose) {
cerr << "Waiting for confirmation that Ultrasonix is imaging.\n";
}
}
}
/*
Print all ultrasonix parameters.
*/
void Ultracomm::dump_params()
{
int i = 0;
int val;
uParam param;
cout << "index\tparam.id\tvalue\tparam.name\tparam.source\tparam.type\n";
while (ult.getParam(i++, param))
{
// TODO: Learn about different param types and how to get their values.
// This probably doesn't work properly for non-integer param values.
// Have not been able to get getParamValue() to return false either.
if (ult.getParamValue(param.id, val))
{
cout << i << "\t" << param.id << "\t" << val << "\t" << param.name << "\t" << param.source << "\t" << param.type << "\t" << param.unit << "\n";
}
else
{
cerr << i << "\t'" << param.id << "'\t" << param.name << "\tFAILED\n";
}
}
}
/*
Set all integer-type Ultrasonix imaging parameters, as specified on the
command line or in the parameter file.
*/
void Ultracomm::set_int_imaging_params()
{
po::variables_map params = uopt.opt;
po::options_description iopts = uopt.int_imaging_params;
for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)
{
/*
Ultracomm program options do not contain spaces. Some of the
parameters used by the ulterius setParamValue() call do contain
spaces, and none appear to use underscore. The convention is that
ultracomm program options containing underscore correspond to
ulterius parameters that have the same name, but with the
underscores replaced with spaces (' ').
optname: the name as used in ultracomm program options (underscores)
ultname: the name as used by ulterius setParamValue() (spaces)
*/
string optname = (*iter)->long_name();
string ultname = boost::replace_all_copy(optname, "_", " ");
if (params.count(optname)) {
int val = params[optname].as<int>();
if (verbose) {
cerr << "Setting '" << ultname << "' to value " << val << ".\n";
}
ult.setParamValue(ultname.c_str(), val);
}
}
}
/*
Verify that integer-type Ultrasonix imaging parameters have value as
specified by user.
*/
void Ultracomm::check_int_imaging_params()
{
po::variables_map params = uopt.opt;
po::options_description iopts = uopt.int_imaging_params;
for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)
{
/*
See comments in set_int_imaging_params() for mangling of
parameter names.
*/
string optname = (*iter)->long_name();
string ultname = boost::replace_all_copy(optname, "_", " ");
if (params.count(optname)) {
int expected, got;
expected = params[optname].as<int>();
ult.getParamValue(ultname.c_str(), got);
if (verbose) {
cerr << "Got value of '" << ultname << "'. Expected " << expected << " and got " << got << ".\n";
}
if (got != expected) {
cerr << "Parameter '" << ultname << "' expected " << expected << " and got " << got << ".\n";
throw ParameterMismatchError();
}
}
}
}
/*
Get data from Ultrasonix and save to file.
*/
void Ultracomm::save_data()
{
int num_frames = ult.getCineDataCount((uData)datatype);
write_header(outfile, desc, num_frames);
// TODO: figure out why buffer and sz makes program crash
//const int sz = 2 * 1024 * 1024;
//char buffer[BUFFERSIZE]; // TODO: determine appropriate sizes on the fly
// int num_frames = ult.getCineDataCount((uData)datatype);
for (int idx = 0; idx < num_frames; idx++)
{
if (verbose) {
cerr << "Getting cine data for frame " << idx << ".\n";
}
ult.getCineData((uData)datatype, idx, false, (char**)&gBuffer, BUFFERSIZE);
outfile.write(gBuffer, framesize);
if (verbose) {
cerr << "Wrote cine data for frame " << idx << ".\n";
}
}
outfile.close();
}
/*
TODO: header information is probably correct for .bpr files but possibly
not for other datatypes.
*/
void Ultracomm::write_header(ofstream& outfile, const uDataDesc& desc, const int& num_frames)
{
if (verbose) {
cerr << "Writing header.\n";
}
// Integer fields that we can write directly. Luckily these all are
// consecutive fields in the header.
const int isize = sizeof(__int32);
static const int fields[] = {
datatype,
num_frames,
desc.w,
desc.h,
desc.ss,
desc.roi.ulx,
desc.roi.uly,
desc.roi.urx,
desc.roi.ury,
desc.roi.brx,
desc.roi.bry,
desc.roi.blx,
desc.roi.bly,
uopt.opt["probe-id"].as<int>()
};
for (int i = 0; i < sizeof(fields) / sizeof(fields[0]); ++i) {
outfile.write(reinterpret_cast<const char *>(&(__int32)fields[i]), isize);
}
// Integer fields that we have to query from Ultrasonix. These are also
// consecutive in the header.
// FIXME: Determine if these are the correct params to put in the header.
static const string queries[] = {
"b-freq",
"vec-freq",
"frame rate",
"b-ldensity"
};
for (int i = 0; i < sizeof(queries) / sizeof(queries[0]); ++i) {
int val;
ult.getParamValue(queries[i].c_str(), val);
outfile.write(reinterpret_cast<const char *>(&(__int32)val), isize);
}
// FIXME: Figure out how to determine the value of the 'extra' field.
// It will probably be added to queries[], but I don't know the param name.
// For now we'll hard code it with value 0.
int extra = 0;
outfile.write(reinterpret_cast<const char *>(&(__int32)extra), isize);
}
/*
TODO: kind of a hack.
*/
void Ultracomm::write_numframes_in_header(ofstream& outfile, const int& num_frames)
{
const int isize = sizeof(__int32);
outfile.seekp(isize);
outfile.write(reinterpret_cast<const char *>(&(__int32)num_frames), isize);
}
/*
Callback.
*/
bool Ultracomm::frame_callback(void* data, int type, int sz, bool cine, int frmnum)
{
/*
if (verbose) {
cerr << "In callback.\n";
}
if (!data || !sz)
{
// TODO: proper error
printf("Error: no actual frame data received\n");
return false;
}
if (BUFFERSIZE < sz)
{
// TODO: proper error
printf("Error: frame too large for current buffer\n");
return false;
}
*/
//printf("[Rx] type:(%d) size:(%d) cine:(%d) gBuffer:(%d) frame:(%d)\n", type, sz, cine, &gBuffer, frmnum);
// printf("%d\n", frmnum);
/*
if (frmnum != lastFrame + 1) {
printf("Skipped frame(s) %d - %d.\n", lastFrame + 1, frmnum - 1);
}
*/
lastFrame = frmnum;
framesReceived++;
// make sure we dont do an operation that takes longer than the acquisition frame rate
//memcpy(gBuffer, data, sz);
std::string frmint = std::to_string(long double(frmnum)) + "\n";
myindexstream->write(frmint.c_str(), frmint.size());
mystream->write((const char*)data, sz);
return true;
}
<commit_msg>Update message.<commit_after>#include "StdAfx.h"
#define BUFFERSIZE (2 * 1024 * 1024)
char gBuffer[BUFFERSIZE];
int lastFrame = -1;
int framesReceived = 0;
/*
The Ultracomm object is not available in the callback, so we copy some of
its attributes into file-local variables that the callback can access.
*/
ofstream* mystream;
int myframesize;
ofstream* myindexstream;
/*
Construct Ultracomm object, connect to server,
and set/check parameters.
*/
Ultracomm::Ultracomm(const UltracommOptions& myuopt)
: uopt(myuopt),
address(myuopt.opt["address"].as<string>()),
acqmode(myuopt.opt["acqmode"].as<string>()),
datatype(myuopt.opt["datatype"].as<int>()),
verbose(myuopt.opt["verbose"].as<int>())
{
connect();
if (verbose) {
cerr << "Setting data to acquire to datatype " << datatype << ".\n";
}
ult.setDataToAcquire(datatype);
set_int_imaging_params();
check_int_imaging_params();
const int compstat = uopt.opt["compression_status"].as<int>();
if (verbose) {
cerr << "Setting compression status to " << compstat << ".\n";
}
if (! ult.setCompressionStatus(compstat)) {
cerr << "Failed to set compression status to " << compstat << ".\n";
throw ParameterMismatchError();
}
if (! ult.getDataDescriptor((uData)datatype, desc))
{
throw DataDescriptorError();
}
if (! ult.isDataAvailable((uData)datatype))
{
throw DataError();
}
// TODO: framesize assumes desc.ss is always a multiple of 8, and that might not be safe.
framesize = (desc.ss / 8) * desc.w * desc.h;
myframesize = framesize;
std::string outname = myuopt.opt["output"].as<string>();
outfile.open(outname, ios::out | ios::binary),
mystream = &outfile;
std::string outindexname = outname + ".idx.txt";
outindexfile.open(outindexname, ios::out | ios::binary);
myindexstream = &outindexfile;
if (acqmode == "continuous") {
ult.setCallback(frame_callback);
write_header(outfile, desc, 0);
}
}
/*
Connect to the Ultrasonix.
*/
void Ultracomm::connect()
{
if (verbose) {
cerr << "Connecting to ultrasonix at address " << address << ".\n";
}
if (!ult.connect(address.c_str()))
{
throw ConnectionError();
}
// Stop streaming, if necessary.
//if (ult.getStreamStatus()) {
// ult.stopStream();
//}
/*
int imgmode = ult.getActiveImagingMode();
cout << "Imaging mode is " << imgmode << ".\n";
bool im = ult.getInjectMode();
cout << "Inject mode is " << im << ".\n";
bool ss = ult.getStreamStatus();
cout << "Stream status is " << ss << ".\n";
*/
/*
TODO: throw different errors depending on problem. Note that FD_CONNECT error
is when server address is bad (e.g. 123), and SOCKET_ERROR is when we couldn't connect
(address good but not in research mode). Should also test when address is good
but ultrasound machine not running):
C:\build\ultracomm\bin\Debug>ultracomm --address 123 --output asdf
monitorConnection(): FD_CONNECT had ERROR
Could not connect to Ultrasonix.
C:\build\ultracomm\bin\Debug>ultracomm --address 192.168.1.200 --output asdf
monitorConnection(): WSAEnumNetworkEvents() ret SOCKET_ERROR (10093)
CmonitorConnection(): CONNECTION_COMM lost
ould not connect to Ultrasonix.
*/
}
/*
Disconnect from Ultrasonix.
*/
void Ultracomm::disconnect()
{
write_numframes_in_header(outfile, framesReceived);
outfile.close();
outindexfile.close();
//printf("Last frame was %d.\n", lastFrame);
double pct = 100.0 * framesReceived / (lastFrame+1);
if (framesReceived > 0 )
{
printf("Acquired %d of %d frames (%0.4f percent).\n", framesReceived, lastFrame+1, pct);
}
else
{
printf("No frames acquired.\n");
}
if (ult.isConnected())
{
if (verbose) {
cerr << "Disconnecting from Ultrasonix.\n";
}
ult.disconnect();
}
else
{
if (verbose) {
cerr << "Already disconnected from Ultrasonix.\n";
}
}
}
/*
Put Ultrasonix into freeze state and wait for confirmation.
*/
void Ultracomm::wait_for_freeze()
{
// 1 = FROZEN; 0 = IMAGING
if (ult.getFreezeState() != 1)
{
if (verbose) {
cerr << "Freezing Ultrasonix.\n";
}
ult.toggleFreeze();
}
else
{
if (verbose) {
cerr << "Ultrasonix already frozen.\n";
}
}
// Wait for server to acknowledge it has frozen.
// TODO: this would be safer with a timeout.
while (ult.getFreezeState() != 1)
{
if (verbose) {
cerr << "Waiting for confirmation that Ultrasonix has frozen.\n";
}
}
/*
FIXME: Occasionally we get the message
sendAndWait(): WaitForSingleObject() ret WAIT_TIMEOUT
when retrieving cine data. When --verbose is turned on this message
usually appears in save_data() after the call to getCineData() and
before write(). According to the discussion at
http://research.ultrasonix.com/viewtopic.php?f=5&t=1100&p=4245&hilit=delay#p4245
adding a delay after toggleFreeze() can prevent this condition, so
we add it here.
Possibly this delay is not necessary when used with newer versions of
the Ultrasonix library.
*/
if (
uopt.opt["ms_delay_after_freeze"].as<int>() > 0 &&
!uopt.opt.count("freeze-only")
)
{
Sleep(uopt.opt["ms_delay_after_freeze"].as<int>());
}
}
/*
Put ultrasonix into imaging state.
*/
void Ultracomm::wait_for_unfreeze()
{
// 1 = FROZEN; 0 = IMAGING
if (ult.getFreezeState() != 0)
{
if (verbose) {
cerr << "Unfreezing Ultrasonix.\n";
}
ult.toggleFreeze();
}
else
{
if (verbose) {
cerr << "Ultrasonix already imaging.\n";
}
}
// Wait for server to acknowledge it has switched to imaging.
// TODO: this would be safer with a timeout.
while (ult.getFreezeState() != 0)
{
if (verbose) {
cerr << "Waiting for confirmation that Ultrasonix is imaging.\n";
}
}
}
/*
Print all ultrasonix parameters.
*/
void Ultracomm::dump_params()
{
int i = 0;
int val;
uParam param;
cout << "index\tparam.id\tvalue\tparam.name\tparam.source\tparam.type\n";
while (ult.getParam(i++, param))
{
// TODO: Learn about different param types and how to get their values.
// This probably doesn't work properly for non-integer param values.
// Have not been able to get getParamValue() to return false either.
if (ult.getParamValue(param.id, val))
{
cout << i << "\t" << param.id << "\t" << val << "\t" << param.name << "\t" << param.source << "\t" << param.type << "\t" << param.unit << "\n";
}
else
{
cerr << i << "\t'" << param.id << "'\t" << param.name << "\tFAILED\n";
}
}
}
/*
Set all integer-type Ultrasonix imaging parameters, as specified on the
command line or in the parameter file.
*/
void Ultracomm::set_int_imaging_params()
{
po::variables_map params = uopt.opt;
po::options_description iopts = uopt.int_imaging_params;
for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)
{
/*
Ultracomm program options do not contain spaces. Some of the
parameters used by the ulterius setParamValue() call do contain
spaces, and none appear to use underscore. The convention is that
ultracomm program options containing underscore correspond to
ulterius parameters that have the same name, but with the
underscores replaced with spaces (' ').
optname: the name as used in ultracomm program options (underscores)
ultname: the name as used by ulterius setParamValue() (spaces)
*/
string optname = (*iter)->long_name();
string ultname = boost::replace_all_copy(optname, "_", " ");
if (params.count(optname)) {
int val = params[optname].as<int>();
if (verbose) {
cerr << "Setting '" << ultname << "' to value " << val << ".\n";
}
ult.setParamValue(ultname.c_str(), val);
}
}
}
/*
Verify that integer-type Ultrasonix imaging parameters have value as
specified by user.
*/
void Ultracomm::check_int_imaging_params()
{
po::variables_map params = uopt.opt;
po::options_description iopts = uopt.int_imaging_params;
for ( auto iter = iopts.options().begin(); iter != iopts.options().end(); ++iter)
{
/*
See comments in set_int_imaging_params() for mangling of
parameter names.
*/
string optname = (*iter)->long_name();
string ultname = boost::replace_all_copy(optname, "_", " ");
if (params.count(optname)) {
int expected, got;
expected = params[optname].as<int>();
ult.getParamValue(ultname.c_str(), got);
if (verbose) {
cerr << "Got value of '" << ultname << "'. Expected " << expected << " and got " << got << ".\n";
}
if (got != expected) {
cerr << "Parameter '" << ultname << "' expected " << expected << " and got " << got << ".\n";
throw ParameterMismatchError();
}
}
}
}
/*
Get data from Ultrasonix and save to file.
*/
void Ultracomm::save_data()
{
int num_frames = ult.getCineDataCount((uData)datatype);
write_header(outfile, desc, num_frames);
// TODO: figure out why buffer and sz makes program crash
//const int sz = 2 * 1024 * 1024;
//char buffer[BUFFERSIZE]; // TODO: determine appropriate sizes on the fly
// int num_frames = ult.getCineDataCount((uData)datatype);
for (int idx = 0; idx < num_frames; idx++)
{
if (verbose) {
cerr << "Getting cine data for frame " << idx << ".\n";
}
ult.getCineData((uData)datatype, idx, false, (char**)&gBuffer, BUFFERSIZE);
outfile.write(gBuffer, framesize);
if (verbose) {
cerr << "Wrote cine data for frame " << idx << ".\n";
}
}
outfile.close();
}
/*
TODO: header information is probably correct for .bpr files but possibly
not for other datatypes.
*/
void Ultracomm::write_header(ofstream& outfile, const uDataDesc& desc, const int& num_frames)
{
if (verbose) {
cerr << "Writing header.\n";
}
// Integer fields that we can write directly. Luckily these all are
// consecutive fields in the header.
const int isize = sizeof(__int32);
static const int fields[] = {
datatype,
num_frames,
desc.w,
desc.h,
desc.ss,
desc.roi.ulx,
desc.roi.uly,
desc.roi.urx,
desc.roi.ury,
desc.roi.brx,
desc.roi.bry,
desc.roi.blx,
desc.roi.bly,
uopt.opt["probe-id"].as<int>()
};
for (int i = 0; i < sizeof(fields) / sizeof(fields[0]); ++i) {
outfile.write(reinterpret_cast<const char *>(&(__int32)fields[i]), isize);
}
// Integer fields that we have to query from Ultrasonix. These are also
// consecutive in the header.
// FIXME: Determine if these are the correct params to put in the header.
static const string queries[] = {
"b-freq",
"vec-freq",
"frame rate",
"b-ldensity"
};
for (int i = 0; i < sizeof(queries) / sizeof(queries[0]); ++i) {
int val;
ult.getParamValue(queries[i].c_str(), val);
outfile.write(reinterpret_cast<const char *>(&(__int32)val), isize);
}
// FIXME: Figure out how to determine the value of the 'extra' field.
// It will probably be added to queries[], but I don't know the param name.
// For now we'll hard code it with value 0.
int extra = 0;
outfile.write(reinterpret_cast<const char *>(&(__int32)extra), isize);
}
/*
TODO: kind of a hack.
*/
void Ultracomm::write_numframes_in_header(ofstream& outfile, const int& num_frames)
{
const int isize = sizeof(__int32);
outfile.seekp(isize);
outfile.write(reinterpret_cast<const char *>(&(__int32)num_frames), isize);
}
/*
Callback.
*/
bool Ultracomm::frame_callback(void* data, int type, int sz, bool cine, int frmnum)
{
/*
if (verbose) {
cerr << "In callback.\n";
}
if (!data || !sz)
{
// TODO: proper error
printf("Error: no actual frame data received\n");
return false;
}
if (BUFFERSIZE < sz)
{
// TODO: proper error
printf("Error: frame too large for current buffer\n");
return false;
}
*/
//printf("[Rx] type:(%d) size:(%d) cine:(%d) gBuffer:(%d) frame:(%d)\n", type, sz, cine, &gBuffer, frmnum);
// printf("%d\n", frmnum);
/*
if (frmnum != lastFrame + 1) {
printf("Skipped frame(s) %d - %d.\n", lastFrame + 1, frmnum - 1);
}
*/
lastFrame = frmnum;
framesReceived++;
// make sure we dont do an operation that takes longer than the acquisition frame rate
//memcpy(gBuffer, data, sz);
std::string frmint = std::to_string(long double(frmnum)) + "\n";
myindexstream->write(frmint.c_str(), frmint.size());
mystream->write((const char*)data, sz);
return true;
}
<|endoftext|>
|
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <stltest/stltest.hpp> /// defines transfer struct (abi)
#include <array>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <eoslib/eos.hpp>
#include <eoslib/token.hpp>
#include <eoslib/dispatcher.hpp>
using namespace eosio;
namespace stltest {
class contract {
public:
typedef eosio::token<N(mycurrency),S(4,MYCUR)> token_type;
static const uint64_t code = token_type::code;
static const uint64_t symbol = token_type::symbol;
static const uint64_t sent_table_name = N(sent);
static const uint64_t received_table_name = N(received);
struct message {
account_name from;
account_name to;
string msg;
static uint64_t get_account() { return current_receiver(); }
static uint64_t get_name() { return N(message); }
template<typename DataStream>
friend DataStream& operator << ( DataStream& ds, const message& m ){
return ds << m.from << m.to << m.msg;
}
template<typename DataStream>
friend DataStream& operator >> ( DataStream& ds, message& m ){
return ds >> m.from >> m.to >> m.msg;
}
};
static void on(const message& msg) {
std::array<uint32_t, 10> arr;
arr[0] = 0;
std::vector<uint32_t> v;
v.push_back(0);
std::stack<char> stack;
stack.push('J');
std::queue<unsigned int> q;
q.push(0);
std::deque<float> dq;
dq.push_front(0.0f);
std::list<uint32_t> l;
l.push_back(0);
std::string s;
s.append(1, 'a');
std::map<int, double> m;
m.emplace(0, 1.0);
std::set<long> st;
st.insert(0);
std::unordered_map<int, string> hm;
//hm[0] = "abc";
std::unordered_set<int> hs;
//hs.insert(0);
}
static void apply( account_name c, action_name act) {
eosio::dispatch<stltest::contract, message>(c,act);
}
};
} /// namespace eosio
extern "C" {
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t code, uint64_t action ) {
stltest::contract::apply( code, action );
}
}
<commit_msg>test for STL draft in wasm_test<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#include <stltest/stltest.hpp> /// defines transfer struct (abi)
#include <array>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <eoslib/eos.hpp>
#include <eoslib/token.hpp>
#include <eoslib/dispatcher.hpp>
using namespace eosio;
namespace stltest {
class contract {
public:
typedef eosio::token<N(mycurrency),S(4,MYCUR)> token_type;
static const uint64_t code = token_type::code;
static const uint64_t symbol = token_type::symbol;
static const uint64_t sent_table_name = N(sent);
static const uint64_t received_table_name = N(received);
struct message {
account_name from;
account_name to;
string msg;
static uint64_t get_account() { return current_receiver(); }
static uint64_t get_name() { return N(message); }
template<typename DataStream>
friend DataStream& operator << ( DataStream& ds, const message& m ){
return ds << m.from << m.to << m.msg;
}
template<typename DataStream>
friend DataStream& operator >> ( DataStream& ds, message& m ){
return ds >> m.from >> m.to >> m.msg;
}
};
static void on(const message& msg) {
print("STL test start.");
std::array<uint32_t, 10> arr;
arr[0] = 0;
std::vector<uint32_t> v;
v.push_back(0);
std::stack<char> stack;
stack.push('J');
std::queue<unsigned int> q;
q.push(0);
std::deque<float> dq;
dq.push_front(0.0f);
std::list<uint32_t> l;
l.push_back(0);
std::string s;
s.append(1, 'a');
std::map<int, double> m;
m.emplace(0, 1.0);
std::set<long> st;
st.insert(0);
std::unordered_map<int, string> hm;
//hm[0] = "abc";
std::unordered_set<int> hs;
//hs.insert(0);
print("STL test done.");
}
static void apply( account_name c, action_name act) {
eosio::dispatch<stltest::contract, message>(c,act);
}
};
} /// namespace eosio
extern "C" {
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t code, uint64_t action ) {
stltest::contract::apply( code, action );
}
}
<|endoftext|>
|
<commit_before>#include <mesos_sched.hpp>
#include <libgen.h>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include "foreach.hpp"
using namespace std;
using namespace mesos;
using boost::lexical_cast;
class MyScheduler : public Scheduler
{
string executor;
int tasksLaunched;
int tasksFinished;
int totalTasks;
public:
MyScheduler(const string& exec)
: executor(exec), tasksLaunched(0), tasksFinished(0), totalTasks(5) {}
virtual ~MyScheduler() {}
virtual string getFrameworkName(SchedulerDriver*) {
return "C++ Test Framework";
}
virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) {
return ExecutorInfo(executor, "");
}
virtual void registered(SchedulerDriver*, FrameworkID fid) {
cout << "Registered!" << endl;
}
virtual void resourceOffer(SchedulerDriver* d,
OfferID id,
const std::vector<SlaveOffer>& offers) {
cout << "." << flush;
vector<TaskDescription> tasks;
foreach (const SlaveOffer &offer, offers) {
// This is kind of ugly because operator[] isn't a const function
int32_t cpus = lexical_cast<int32_t>(offer.params.find("cpus")->second);
int32_t mem = lexical_cast<int64_t>(offer.params.find("mem")->second);
if ((tasksLaunched < totalTasks) && (cpus >= 1 && mem >= 32)) {
TaskID tid = tasksLaunched++;
cout << endl << "Starting task " << tid << endl;
string name = "Task " + lexical_cast<string>(tid);
map<string, string> taskParams;
taskParams["cpus"] = "1";
taskParams["mem"] = "32";
TaskDescription desc(tid, offer.slaveId, name, taskParams, "");
tasks.push_back(desc);
}
}
map<string, string> params;
params["timeout"] = "-1";
d->replyToOffer(id, tasks, params);
}
virtual void statusUpdate(SchedulerDriver* d, const TaskStatus& status) {
cout << endl;
cout << "Task " << status.taskId << " is in state " << status.state << endl;
if (status.state == TASK_FINISHED)
tasksFinished++;
if (tasksFinished == totalTasks)
d->stop();
}
};
int main(int argc, char ** argv) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <masterPid>" << endl;
return -1;
}
// Find this executable's directory to locate executor
char buf[4096];
realpath(dirname(argv[0]), buf);
string executor = string(buf) + "/cpp-test-executor";
// Run a Mesos scheduler
MyScheduler sched(executor);
MesosSchedulerDriver driver(&sched, argv[1]);
driver.run();
return 0;
}
<commit_msg>Updated C++ test framework to launch multiple tasks per offer<commit_after>#include <mesos_sched.hpp>
#include <libgen.h>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <boost/lexical_cast.hpp>
#include "foreach.hpp"
using namespace std;
using namespace mesos;
using boost::lexical_cast;
const int32_t CPUS_PER_TASK = 1;
const int32_t MEM_PER_TASK = 32;
class MyScheduler : public Scheduler
{
string executor;
int tasksLaunched;
int tasksFinished;
int totalTasks;
public:
MyScheduler(const string& exec)
: executor(exec), tasksLaunched(0), tasksFinished(0), totalTasks(5) {}
virtual ~MyScheduler() {}
virtual string getFrameworkName(SchedulerDriver*) {
return "C++ Test Framework";
}
virtual ExecutorInfo getExecutorInfo(SchedulerDriver*) {
return ExecutorInfo(executor, "");
}
virtual void registered(SchedulerDriver*, FrameworkID fid) {
cout << "Registered!" << endl;
}
virtual void resourceOffer(SchedulerDriver* d,
OfferID id,
const std::vector<SlaveOffer>& offers) {
cout << "." << flush;
vector<TaskDescription> tasks;
foreach (const SlaveOffer &offer, offers) {
// This is kind of ugly because operator[] isn't a const function
int32_t cpus = lexical_cast<int32_t>(offer.params.find("cpus")->second);
int32_t mem = lexical_cast<int64_t>(offer.params.find("mem")->second);
while (tasksLaunched < totalTasks && cpus >= CPUS_PER_TASK &&
mem >= MEM_PER_TASK) {
TaskID tid = tasksLaunched++;
cout << endl << "Starting task " << tid << endl;
string name = "Task " + lexical_cast<string>(tid);
map<string, string> taskParams;
taskParams["cpus"] = lexical_cast<string>(CPUS_PER_TASK);
taskParams["mem"] = lexical_cast<string>(MEM_PER_TASK);
TaskDescription desc(tid, offer.slaveId, name, taskParams, "");
tasks.push_back(desc);
cpus -= CPUS_PER_TASK;
mem -= MEM_PER_TASK;
}
}
map<string, string> params;
params["timeout"] = "-1";
d->replyToOffer(id, tasks, params);
}
virtual void statusUpdate(SchedulerDriver* d, const TaskStatus& status) {
cout << endl;
cout << "Task " << status.taskId << " is in state " << status.state << endl;
if (status.state == TASK_FINISHED)
tasksFinished++;
if (tasksFinished == totalTasks)
d->stop();
}
};
int main(int argc, char ** argv) {
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <masterPid>" << endl;
return -1;
}
// Find this executable's directory to locate executor
char buf[4096];
realpath(dirname(argv[0]), buf);
string executor = string(buf) + "/cpp-test-executor";
// Run a Mesos scheduler
MyScheduler sched(executor);
MesosSchedulerDriver driver(&sched, argv[1]);
driver.run();
return 0;
}
<|endoftext|>
|
<commit_before>/*!
* \file glyph_cache.cpp
* \brief file glyph_cache.cpp
*
* Copyright 2016 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#include <map>
#include <vector>
#include <fastuidraw/text/glyph_cache.hpp>
#include <fastuidraw/text/glyph_render_data.hpp>
#include "../private/util_private.hpp"
namespace
{
class GlyphCachePrivate;
class GlyphDataPrivate
{
public:
GlyphDataPrivate(GlyphCachePrivate *c, unsigned int I):
m_cache(c),
m_cache_location(I),
m_geometry_offset(-1),
m_geometry_length(0),
m_uploaded_to_atlas(false),
m_glyph_data(NULL)
{}
void
clear(void);
enum fastuidraw::return_code
upload_to_atlas(void);
/* owner
*/
GlyphCachePrivate *m_cache;
/* location into m_cache->m_glyphs
*/
unsigned int m_cache_location;
/* layout magicks
*/
fastuidraw::GlyphLayoutData m_layout;
fastuidraw::GlyphRender m_render;
/* Location in atlas
*/
fastuidraw::vecN<fastuidraw::GlyphLocation, 2> m_atlas_location;
int m_geometry_offset, m_geometry_length;
bool m_uploaded_to_atlas;
/* data to generate glyph data
*/
fastuidraw::GlyphRenderData *m_glyph_data;
};
class GlyphSource
{
public:
GlyphSource(void):
m_glyph_code(0)
{}
GlyphSource(fastuidraw::FontBase::const_handle f,
uint32_t gc, fastuidraw::GlyphRender r):
m_font(f),
m_glyph_code(gc),
m_render(r)
{}
bool
operator<(const GlyphSource &rhs) const
{
return (m_font != rhs.m_font) ? m_font < rhs.m_font :
(m_glyph_code != rhs.m_glyph_code) ? m_glyph_code < rhs.m_glyph_code :
m_render < rhs.m_render;
}
fastuidraw::FontBase::const_handle m_font;
uint32_t m_glyph_code;
fastuidraw::GlyphRender m_render;
};
class GlyphCachePrivate
{
public:
explicit
GlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas, fastuidraw::GlyphCache *p);
~GlyphCachePrivate();
/* When the atlas is full, we will clear the atlas, but save
the values in m_glyphs but mark them as not having been
uploaded, this way returned values are safe and we do
not have to regenerate data either.
*/
GlyphDataPrivate*
fetch_or_allocate_glyph(GlyphSource src);
fastuidraw::GlyphAtlas::handle m_atlas;
std::map<GlyphSource, GlyphDataPrivate*> m_glyph_map;
std::vector<GlyphDataPrivate*> m_glyphs;
std::vector<unsigned int> m_free_slots;
fastuidraw::GlyphCache *m_p;
};
}
/////////////////////////////////////////////////////////
// GlyphDataPrivate methods
void
GlyphDataPrivate::
clear(void)
{
m_render = fastuidraw::GlyphRender();
assert(!m_render.valid());
if(m_atlas_location[0].valid())
{
m_cache->m_atlas->deallocate(m_atlas_location[0]);
m_atlas_location[0] = fastuidraw::GlyphLocation();
}
if(m_atlas_location[1].valid())
{
m_cache->m_atlas->deallocate(m_atlas_location[1]);
m_atlas_location[1] = fastuidraw::GlyphLocation();
}
if(m_geometry_offset != -1)
{
m_cache->m_atlas->deallocate_geometry_data(m_geometry_offset, m_geometry_length);
m_geometry_offset = -1;
m_geometry_length = 0;
}
m_uploaded_to_atlas = false;
if(m_glyph_data)
{
FASTUIDRAWdelete(m_glyph_data);
m_glyph_data = NULL;
}
}
enum fastuidraw::return_code
GlyphDataPrivate::
upload_to_atlas(void)
{
/* TODO:
1. this method is not thread safe if different threads
attempt to access the same glyph (or if different
threads call this routine and clear_atlas()
at the same time).
2. this routine is hideous to read due to the handling
of allocation failures. Should likely bunch the
allocation behind objects whose ctors and dtors
do the right thing.
*/
enum fastuidraw::return_code return_value;
if(m_uploaded_to_atlas)
{
return fastuidraw::routine_success;
}
assert(m_glyph_data);
return_value = m_glyph_data->upload_to_atlas(m_cache->m_atlas,
m_atlas_location[0],
m_atlas_location[1],
m_geometry_offset,
m_geometry_length);
if(return_value == fastuidraw::routine_success)
{
m_uploaded_to_atlas = true;
}
return return_value;
}
/////////////////////////////////////////////////
// GlyphCachePrivate methods
GlyphCachePrivate::
GlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas,
fastuidraw::GlyphCache *p):
m_atlas(patlas),
m_p(p)
{}
GlyphCachePrivate::
~GlyphCachePrivate()
{
for(unsigned int i = 0, endi = m_glyphs.size(); i < endi; ++i)
{
m_glyphs[i]->clear();
FASTUIDRAWdelete(m_glyphs[i]);
}
}
GlyphDataPrivate*
GlyphCachePrivate::
fetch_or_allocate_glyph(GlyphSource src)
{
std::map<GlyphSource, GlyphDataPrivate*>::iterator iter;
GlyphDataPrivate *G;
iter = m_glyph_map.find(src);
if(iter != m_glyph_map.end())
{
return iter->second;
}
if(m_free_slots.empty())
{
G = FASTUIDRAWnew GlyphDataPrivate(this, m_glyphs.size());
m_glyphs.push_back(G);
assert(!G->m_render.valid());
}
else
{
unsigned int v(m_free_slots.back());
m_free_slots.pop_back();
G = m_glyphs[v];
assert(!G->m_render.valid());
}
m_glyph_map[src] = G;
return G;
}
///////////////////////////////////////////////////////
// fastuidraw::Glyph methods
enum fastuidraw::glyph_type
fastuidraw::Glyph::
type(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL);
return p->m_render.m_type;
}
const fastuidraw::GlyphLayoutData&
fastuidraw::Glyph::
layout(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_layout;
}
fastuidraw::reference_counted_ptr<fastuidraw::GlyphCache>
fastuidraw::Glyph::
cache(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_cache->m_p;
}
unsigned int
fastuidraw::Glyph::
cache_location(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_cache_location;
}
fastuidraw::GlyphLocation
fastuidraw::Glyph::
atlas_location(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_atlas_location[0];
}
fastuidraw::GlyphLocation
fastuidraw::Glyph::
secondary_atlas_location(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_atlas_location[1];
}
int
fastuidraw::Glyph::
geometry_offset(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_geometry_offset;
}
enum fastuidraw::return_code
fastuidraw::Glyph::
upload_to_atlas(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->upload_to_atlas();
}
//////////////////////////////////////////////////////////
// fastuidraw::GlyphCache methods
fastuidraw::GlyphCache::
GlyphCache(GlyphAtlas::handle patlas)
{
m_d = FASTUIDRAWnew GlyphCachePrivate(patlas, this);
}
fastuidraw::GlyphCache::
~GlyphCache()
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
FASTUIDRAWdelete(d);
m_d = NULL;
}
fastuidraw::Glyph
fastuidraw::GlyphCache::
fetch_glyph(GlyphRender render, FontBase::const_handle font, uint32_t glyph_code)
{
if(!font || !font->can_create_rendering_data(render.m_type))
{
return Glyph();
}
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
GlyphDataPrivate *q;
GlyphSource src(font, glyph_code, render);
q = d->fetch_or_allocate_glyph(src);
if(!q->m_render.valid())
{
q->m_render = render;
assert(!q->m_glyph_data);
q->m_glyph_data = font->compute_rendering_data(q->m_render, glyph_code, q->m_layout);
}
return Glyph(q);
}
void
fastuidraw::GlyphCache::
delete_glyph(Glyph G)
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(G.m_opaque);
assert(p != NULL);
assert(p->m_cache == d);
assert(p->m_render.valid());
GlyphSource src(p->m_layout.m_font, p->m_layout.m_glyph_code, p->m_render);
d->m_glyph_map.erase(src);
p->clear();
d->m_free_slots.push_back(p->m_cache_location);
}
void
fastuidraw::GlyphCache::
clear_atlas(void)
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
d->m_atlas->clear();
for(unsigned int i = 0, endi = d->m_glyphs.size(); i < endi; ++i)
{
d->m_glyphs[i]->m_uploaded_to_atlas = false;
}
}
void
fastuidraw::GlyphCache::
clear_cache(void)
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
clear_atlas();
d->m_glyphs.clear();
d->m_free_slots.clear();
}
<commit_msg>fastuidraw/text: fix for bookkeeping when GlyphAtlas is cleared from GlyphCache<commit_after>/*!
* \file glyph_cache.cpp
* \brief file glyph_cache.cpp
*
* Copyright 2016 by Intel.
*
* Contact: kevin.rogovin@intel.com
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <kevin.rogovin@intel.com>
*
*/
#include <map>
#include <vector>
#include <fastuidraw/text/glyph_cache.hpp>
#include <fastuidraw/text/glyph_render_data.hpp>
#include "../private/util_private.hpp"
namespace
{
class GlyphCachePrivate;
class GlyphDataPrivate
{
public:
GlyphDataPrivate(GlyphCachePrivate *c, unsigned int I):
m_cache(c),
m_cache_location(I),
m_geometry_offset(-1),
m_geometry_length(0),
m_uploaded_to_atlas(false),
m_glyph_data(NULL)
{}
void
clear(void);
enum fastuidraw::return_code
upload_to_atlas(void);
/* owner
*/
GlyphCachePrivate *m_cache;
/* location into m_cache->m_glyphs
*/
unsigned int m_cache_location;
/* layout magicks
*/
fastuidraw::GlyphLayoutData m_layout;
fastuidraw::GlyphRender m_render;
/* Location in atlas
*/
fastuidraw::vecN<fastuidraw::GlyphLocation, 2> m_atlas_location;
int m_geometry_offset, m_geometry_length;
bool m_uploaded_to_atlas;
/* data to generate glyph data
*/
fastuidraw::GlyphRenderData *m_glyph_data;
};
class GlyphSource
{
public:
GlyphSource(void):
m_glyph_code(0)
{}
GlyphSource(fastuidraw::FontBase::const_handle f,
uint32_t gc, fastuidraw::GlyphRender r):
m_font(f),
m_glyph_code(gc),
m_render(r)
{}
bool
operator<(const GlyphSource &rhs) const
{
return (m_font != rhs.m_font) ? m_font < rhs.m_font :
(m_glyph_code != rhs.m_glyph_code) ? m_glyph_code < rhs.m_glyph_code :
m_render < rhs.m_render;
}
fastuidraw::FontBase::const_handle m_font;
uint32_t m_glyph_code;
fastuidraw::GlyphRender m_render;
};
class GlyphCachePrivate
{
public:
explicit
GlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas, fastuidraw::GlyphCache *p);
~GlyphCachePrivate();
/* When the atlas is full, we will clear the atlas, but save
the values in m_glyphs but mark them as not having been
uploaded, this way returned values are safe and we do
not have to regenerate data either.
*/
GlyphDataPrivate*
fetch_or_allocate_glyph(GlyphSource src);
fastuidraw::GlyphAtlas::handle m_atlas;
std::map<GlyphSource, GlyphDataPrivate*> m_glyph_map;
std::vector<GlyphDataPrivate*> m_glyphs;
std::vector<unsigned int> m_free_slots;
fastuidraw::GlyphCache *m_p;
};
}
/////////////////////////////////////////////////////////
// GlyphDataPrivate methods
void
GlyphDataPrivate::
clear(void)
{
m_render = fastuidraw::GlyphRender();
assert(!m_render.valid());
if(m_atlas_location[0].valid())
{
m_cache->m_atlas->deallocate(m_atlas_location[0]);
m_atlas_location[0] = fastuidraw::GlyphLocation();
}
if(m_atlas_location[1].valid())
{
m_cache->m_atlas->deallocate(m_atlas_location[1]);
m_atlas_location[1] = fastuidraw::GlyphLocation();
}
if(m_geometry_offset != -1)
{
m_cache->m_atlas->deallocate_geometry_data(m_geometry_offset, m_geometry_length);
m_geometry_offset = -1;
m_geometry_length = 0;
}
m_uploaded_to_atlas = false;
if(m_glyph_data)
{
FASTUIDRAWdelete(m_glyph_data);
m_glyph_data = NULL;
}
}
enum fastuidraw::return_code
GlyphDataPrivate::
upload_to_atlas(void)
{
/* TODO:
1. this method is not thread safe if different threads
attempt to access the same glyph (or if different
threads call this routine and clear_atlas()
at the same time).
2. this routine is hideous to read due to the handling
of allocation failures. Should likely bunch the
allocation behind objects whose ctors and dtors
do the right thing.
*/
enum fastuidraw::return_code return_value;
if(m_uploaded_to_atlas)
{
return fastuidraw::routine_success;
}
assert(m_glyph_data);
return_value = m_glyph_data->upload_to_atlas(m_cache->m_atlas,
m_atlas_location[0],
m_atlas_location[1],
m_geometry_offset,
m_geometry_length);
if(return_value == fastuidraw::routine_success)
{
m_uploaded_to_atlas = true;
}
return return_value;
}
/////////////////////////////////////////////////
// GlyphCachePrivate methods
GlyphCachePrivate::
GlyphCachePrivate(fastuidraw::GlyphAtlas::handle patlas,
fastuidraw::GlyphCache *p):
m_atlas(patlas),
m_p(p)
{}
GlyphCachePrivate::
~GlyphCachePrivate()
{
for(unsigned int i = 0, endi = m_glyphs.size(); i < endi; ++i)
{
m_glyphs[i]->clear();
FASTUIDRAWdelete(m_glyphs[i]);
}
}
GlyphDataPrivate*
GlyphCachePrivate::
fetch_or_allocate_glyph(GlyphSource src)
{
std::map<GlyphSource, GlyphDataPrivate*>::iterator iter;
GlyphDataPrivate *G;
iter = m_glyph_map.find(src);
if(iter != m_glyph_map.end())
{
return iter->second;
}
if(m_free_slots.empty())
{
G = FASTUIDRAWnew GlyphDataPrivate(this, m_glyphs.size());
m_glyphs.push_back(G);
assert(!G->m_render.valid());
}
else
{
unsigned int v(m_free_slots.back());
m_free_slots.pop_back();
G = m_glyphs[v];
assert(!G->m_render.valid());
}
m_glyph_map[src] = G;
return G;
}
///////////////////////////////////////////////////////
// fastuidraw::Glyph methods
enum fastuidraw::glyph_type
fastuidraw::Glyph::
type(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL);
return p->m_render.m_type;
}
const fastuidraw::GlyphLayoutData&
fastuidraw::Glyph::
layout(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_layout;
}
fastuidraw::reference_counted_ptr<fastuidraw::GlyphCache>
fastuidraw::Glyph::
cache(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_cache->m_p;
}
unsigned int
fastuidraw::Glyph::
cache_location(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_cache_location;
}
fastuidraw::GlyphLocation
fastuidraw::Glyph::
atlas_location(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_atlas_location[0];
}
fastuidraw::GlyphLocation
fastuidraw::Glyph::
secondary_atlas_location(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_atlas_location[1];
}
int
fastuidraw::Glyph::
geometry_offset(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->m_geometry_offset;
}
enum fastuidraw::return_code
fastuidraw::Glyph::
upload_to_atlas(void) const
{
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(m_opaque);
assert(p != NULL && p->m_render.valid());
return p->upload_to_atlas();
}
//////////////////////////////////////////////////////////
// fastuidraw::GlyphCache methods
fastuidraw::GlyphCache::
GlyphCache(GlyphAtlas::handle patlas)
{
m_d = FASTUIDRAWnew GlyphCachePrivate(patlas, this);
}
fastuidraw::GlyphCache::
~GlyphCache()
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
FASTUIDRAWdelete(d);
m_d = NULL;
}
fastuidraw::Glyph
fastuidraw::GlyphCache::
fetch_glyph(GlyphRender render, FontBase::const_handle font, uint32_t glyph_code)
{
if(!font || !font->can_create_rendering_data(render.m_type))
{
return Glyph();
}
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
GlyphDataPrivate *q;
GlyphSource src(font, glyph_code, render);
q = d->fetch_or_allocate_glyph(src);
if(!q->m_render.valid())
{
q->m_render = render;
assert(!q->m_glyph_data);
q->m_glyph_data = font->compute_rendering_data(q->m_render, glyph_code, q->m_layout);
}
return Glyph(q);
}
void
fastuidraw::GlyphCache::
delete_glyph(Glyph G)
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
GlyphDataPrivate *p;
p = reinterpret_cast<GlyphDataPrivate*>(G.m_opaque);
assert(p != NULL);
assert(p->m_cache == d);
assert(p->m_render.valid());
GlyphSource src(p->m_layout.m_font, p->m_layout.m_glyph_code, p->m_render);
d->m_glyph_map.erase(src);
p->clear();
d->m_free_slots.push_back(p->m_cache_location);
}
void
fastuidraw::GlyphCache::
clear_atlas(void)
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
d->m_atlas->clear();
for(unsigned int i = 0, endi = d->m_glyphs.size(); i < endi; ++i)
{
d->m_glyphs[i]->m_uploaded_to_atlas = false;
d->m_glyphs[i]->m_atlas_location[0] = fastuidraw::GlyphLocation();
d->m_glyphs[i]->m_atlas_location[1] = fastuidraw::GlyphLocation();
d->m_glyphs[i]->m_geometry_offset = -1;
d->m_glyphs[i]->m_geometry_length = 0;
}
}
void
fastuidraw::GlyphCache::
clear_cache(void)
{
GlyphCachePrivate *d;
d = reinterpret_cast<GlyphCachePrivate*>(m_d);
clear_atlas();
d->m_glyphs.clear();
d->m_free_slots.clear();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 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 <compat.h>
#include <util/time.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <tinyformat.h>
#include <atomic>
#include <ctime>
#include <thread>
void UninterruptibleSleep(const std::chrono::microseconds &n) {
std::this_thread::sleep_for(n);
}
//! For unit testing
static std::atomic<int64_t> nMockTime(0);
int64_t GetTime() {
int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
if (mocktime) {
return mocktime;
}
time_t now = time(nullptr);
assert(now > 0);
return now;
}
bool ChronoSanityCheck() {
// std::chrono::system_clock.time_since_epoch and time_t(0) are not
// guaranteed to use the Unix epoch timestamp, prior to C++20, but in
// practice they almost certainly will. Any differing behavior will be
// assumed to be an error, unless certain platforms prove to consistently
// deviate, at which point we'll cope with it by adding offsets.
// Create a new clock from time_t(0) and make sure that it represents 0
// seconds from the system_clock's time_since_epoch. Then convert that back
// to a time_t and verify that it's the same as before.
const time_t time_t_epoch{};
auto clock = std::chrono::system_clock::from_time_t(time_t_epoch);
if (std::chrono::duration_cast<std::chrono::seconds>(
clock.time_since_epoch())
.count() != 0) {
return false;
}
time_t time_val = std::chrono::system_clock::to_time_t(clock);
if (time_val != time_t_epoch) {
return false;
}
// Check that the above zero time is actually equal to the known unix
// timestamp.
struct tm epoch;
#ifdef _WIN32
if (gmtime_s(&epoch, &time_val) != 0) {
#else
if (gmtime_r(&time_val, &epoch) == nullptr) {
#endif
return false;
}
if ((epoch.tm_sec != 0) || (epoch.tm_min != 0) || (epoch.tm_hour != 0) ||
(epoch.tm_mday != 1) || (epoch.tm_mon != 0) || (epoch.tm_year != 70)) {
return false;
}
return true;
}
template <typename T> T GetTime() {
const std::chrono::seconds mocktime{
nMockTime.load(std::memory_order_relaxed)};
return std::chrono::duration_cast<T>(
mocktime.count() ? mocktime
: std::chrono::microseconds{GetTimeMicros()});
}
template std::chrono::seconds GetTime();
template std::chrono::milliseconds GetTime();
template std::chrono::microseconds GetTime();
void SetMockTime(int64_t nMockTimeIn) {
assert(nMockTimeIn >= 0);
nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
}
int64_t GetMockTime() {
return nMockTime.load(std::memory_order_relaxed);
}
int64_t GetTimeMillis() {
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_milliseconds();
assert(now > 0);
return now;
}
int64_t GetTimeMicros() {
int64_t now = (boost::posix_time::microsec_clock::universal_time() -
boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1)))
.total_microseconds();
assert(now > 0);
return now;
}
int64_t GetTimeSeconds() {
return GetTimeMicros() / 1000000;
}
std::string FormatISO8601DateTime(int64_t nTime) {
struct tm ts;
time_t time_val = nTime;
#ifdef _WIN32
if (gmtime_s(&ts, &time_val) != 0) {
#else
if (gmtime_r(&time_val, &ts) == nullptr) {
#endif
return {};
}
return strprintf("%04i-%02i-%02iT%02i:%02i:%02iZ", ts.tm_year + 1900,
ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min,
ts.tm_sec);
}
std::string FormatISO8601Date(int64_t nTime) {
struct tm ts;
time_t time_val = nTime;
#ifdef _WIN32
if (gmtime_s(&ts, &time_val) != 0) {
#else
if (gmtime_r(&time_val, &ts) == nullptr) {
#endif
return {};
}
return strprintf("%04i-%02i-%02i", ts.tm_year + 1900, ts.tm_mon + 1,
ts.tm_mday);
}
int64_t ParseISO8601DateTime(const std::string &str) {
static const boost::posix_time::ptime epoch =
boost::posix_time::from_time_t(0);
static const std::locale loc(
std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time() || epoch > ptime) {
return 0;
}
return (ptime - epoch).total_seconds();
}
struct timeval MillisToTimeval(int64_t nTimeout) {
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
struct timeval MillisToTimeval(std::chrono::milliseconds ms) {
return MillisToTimeval(count_milliseconds(ms));
}
<commit_msg>util: Use std::chrono for time getters<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2019 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 <compat.h>
#include <util/time.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <tinyformat.h>
#include <atomic>
#include <ctime>
#include <thread>
void UninterruptibleSleep(const std::chrono::microseconds &n) {
std::this_thread::sleep_for(n);
}
//! For unit testing
static std::atomic<int64_t> nMockTime(0);
int64_t GetTime() {
int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
if (mocktime) {
return mocktime;
}
time_t now = time(nullptr);
assert(now > 0);
return now;
}
bool ChronoSanityCheck() {
// std::chrono::system_clock.time_since_epoch and time_t(0) are not
// guaranteed to use the Unix epoch timestamp, prior to C++20, but in
// practice they almost certainly will. Any differing behavior will be
// assumed to be an error, unless certain platforms prove to consistently
// deviate, at which point we'll cope with it by adding offsets.
// Create a new clock from time_t(0) and make sure that it represents 0
// seconds from the system_clock's time_since_epoch. Then convert that back
// to a time_t and verify that it's the same as before.
const time_t time_t_epoch{};
auto clock = std::chrono::system_clock::from_time_t(time_t_epoch);
if (std::chrono::duration_cast<std::chrono::seconds>(
clock.time_since_epoch())
.count() != 0) {
return false;
}
time_t time_val = std::chrono::system_clock::to_time_t(clock);
if (time_val != time_t_epoch) {
return false;
}
// Check that the above zero time is actually equal to the known unix
// timestamp.
struct tm epoch;
#ifdef _WIN32
if (gmtime_s(&epoch, &time_val) != 0) {
#else
if (gmtime_r(&time_val, &epoch) == nullptr) {
#endif
return false;
}
if ((epoch.tm_sec != 0) || (epoch.tm_min != 0) || (epoch.tm_hour != 0) ||
(epoch.tm_mday != 1) || (epoch.tm_mon != 0) || (epoch.tm_year != 70)) {
return false;
}
return true;
}
template <typename T> T GetTime() {
const std::chrono::seconds mocktime{
nMockTime.load(std::memory_order_relaxed)};
return std::chrono::duration_cast<T>(
mocktime.count() ? mocktime
: std::chrono::microseconds{GetTimeMicros()});
}
template std::chrono::seconds GetTime();
template std::chrono::milliseconds GetTime();
template std::chrono::microseconds GetTime();
template <typename T> static T GetSystemTime() {
const auto now = std::chrono::duration_cast<T>(
std::chrono::system_clock::now().time_since_epoch());
assert(now.count() > 0);
return now;
}
void SetMockTime(int64_t nMockTimeIn) {
assert(nMockTimeIn >= 0);
nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
}
int64_t GetMockTime() {
return nMockTime.load(std::memory_order_relaxed);
}
int64_t GetTimeMillis() {
return int64_t{GetSystemTime<std::chrono::milliseconds>().count()};
}
int64_t GetTimeMicros() {
return int64_t{GetSystemTime<std::chrono::microseconds>().count()};
}
int64_t GetTimeSeconds() {
return int64_t{GetSystemTime<std::chrono::seconds>().count()};
}
std::string FormatISO8601DateTime(int64_t nTime) {
struct tm ts;
time_t time_val = nTime;
#ifdef _WIN32
if (gmtime_s(&ts, &time_val) != 0) {
#else
if (gmtime_r(&time_val, &ts) == nullptr) {
#endif
return {};
}
return strprintf("%04i-%02i-%02iT%02i:%02i:%02iZ", ts.tm_year + 1900,
ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min,
ts.tm_sec);
}
std::string FormatISO8601Date(int64_t nTime) {
struct tm ts;
time_t time_val = nTime;
#ifdef _WIN32
if (gmtime_s(&ts, &time_val) != 0) {
#else
if (gmtime_r(&time_val, &ts) == nullptr) {
#endif
return {};
}
return strprintf("%04i-%02i-%02i", ts.tm_year + 1900, ts.tm_mon + 1,
ts.tm_mday);
}
int64_t ParseISO8601DateTime(const std::string &str) {
static const boost::posix_time::ptime epoch =
boost::posix_time::from_time_t(0);
static const std::locale loc(
std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time() || epoch > ptime) {
return 0;
}
return (ptime - epoch).total_seconds();
}
struct timeval MillisToTimeval(int64_t nTimeout) {
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
struct timeval MillisToTimeval(std::chrono::milliseconds ms) {
return MillisToTimeval(count_milliseconds(ms));
}
<|endoftext|>
|
<commit_before>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#include <cstring>
#include <exceptions.hpp>
#include <immediate.hpp>
#include <instruction.hpp>
namespace triton {
namespace arch {
Instruction::Instruction() {
this->address = 0;
this->branch = false;
this->conditionTaken = false;
this->controlFlow = false;
this->prefix = 0;
this->size = 0;
this->tainted = false;
this->tid = 0;
this->type = 0;
std::memset(this->opcodes, 0x00, sizeof(this->opcodes));
}
Instruction::Instruction(const triton::uint8* opcodes, triton::uint32 opSize) : Instruction::Instruction() {
this->setOpcodes(opcodes, opSize);
}
Instruction::~Instruction() {
}
Instruction::Instruction(const Instruction& other) {
this->copy(other);
}
void Instruction::operator=(const Instruction& other) {
this->copy(other);
}
void Instruction::copy(const Instruction& other) {
this->address = other.address;
this->branch = other.branch;
this->conditionTaken = other.conditionTaken;
this->controlFlow = other.controlFlow;
this->loadAccess = other.loadAccess;
this->memoryAccess = other.memoryAccess;
this->operands = other.operands;
this->prefix = other.prefix;
this->readRegisters = other.readRegisters;
this->registerState = other.registerState;
this->size = other.size;
this->storeAccess = other.storeAccess;
this->symbolicExpressions = other.symbolicExpressions;
this->tainted = other.tainted;
this->tid = other.tid;
this->type = other.type;
this->writtenRegisters = other.writtenRegisters;
std::memcpy(this->opcodes, other.opcodes, sizeof(this->opcodes));
this->disassembly.clear();
this->disassembly.str(other.disassembly.str());
}
triton::uint32 Instruction::getThreadId(void) const {
return this->tid;
}
void Instruction::setThreadId(triton::uint32 tid) {
this->tid = tid;
}
triton::uint64 Instruction::getAddress(void) const {
return this->address;
}
triton::uint64 Instruction::getNextAddress(void) const {
return this->address + this->size;
}
void Instruction::setAddress(triton::uint64 addr) {
this->address = addr;
}
std::string Instruction::getDisassembly(void) const {
return this->disassembly.str();
}
const triton::uint8* Instruction::getOpcodes(void) const {
return this->opcodes;
}
void Instruction::setOpcodes(const triton::uint8* opcodes, triton::uint32 size) {
if (size >= sizeof(this->opcodes))
throw triton::exceptions::Instruction("Instruction::setOpcodes(): Invalid size (too big).");
std::memcpy(this->opcodes, opcodes, size);
this->size = size;
}
triton::uint32 Instruction::getSize(void) const {
return this->size;
}
triton::uint32 Instruction::getType(void) const {
return this->type;
}
triton::uint32 Instruction::getPrefix(void) const {
return this->prefix;
}
const std::set<std::pair<triton::arch::MemoryAccess, triton::ast::AbstractNode*>>& Instruction::getLoadAccess(void) const {
return this->loadAccess;
}
const std::set<std::pair<triton::arch::MemoryAccess, triton::ast::AbstractNode*>>& Instruction::getStoreAccess(void) const {
return this->storeAccess;
}
const std::set<std::pair<triton::arch::Register, triton::ast::AbstractNode*>>& Instruction::getReadRegisters(void) const {
return this->readRegisters;
}
const std::set<std::pair<triton::arch::Register, triton::ast::AbstractNode*>>& Instruction::getWrittenRegisters(void) const {
return this->writtenRegisters;
}
const std::set<std::pair<triton::arch::Immediate, triton::ast::AbstractNode*>>& Instruction::getReadImmediates(void) const {
return this->readImmediates;
}
void Instruction::updateContext(const triton::arch::MemoryAccess& mem) {
this->memoryAccess.push_back(mem);
}
/* If there is a concrete value recorded, build the appropriate Register. Otherwise, perfrom the analysis on zero. */
triton::arch::Register Instruction::getRegisterState(triton::uint32 regId) {
triton::arch::Register reg(regId);
if (this->registerState.find(regId) != this->registerState.end())
reg = this->registerState[regId];
return reg;
}
void Instruction::setLoadAccess(const triton::arch::MemoryAccess& mem, triton::ast::AbstractNode* node) {
this->loadAccess.insert(std::make_pair(mem, node));
}
void Instruction::removeLoadAccess(const triton::arch::MemoryAccess& mem) {
auto it = this->loadAccess.begin();
while (it != this->loadAccess.end()) {
if (it->first.getAddress() == mem.getAddress())
it = this->loadAccess.erase(it);
else
++it;
}
}
void Instruction::setStoreAccess(const triton::arch::MemoryAccess& mem, triton::ast::AbstractNode* node) {
this->storeAccess.insert(std::make_pair(mem, node));
}
void Instruction::removeStoreAccess(const triton::arch::MemoryAccess& mem) {
auto it = this->storeAccess.begin();
while (it != this->storeAccess.end()) {
if (it->first.getAddress() == mem.getAddress())
it = this->storeAccess.erase(it);
else
++it;
}
}
void Instruction::setReadRegister(const triton::arch::Register& reg, triton::ast::AbstractNode* node) {
this->readRegisters.insert(std::make_pair(reg, node));
}
void Instruction::removeReadRegister(const triton::arch::Register& reg) {
auto it = this->readRegisters.begin();
while (it != this->readRegisters.end()) {
if (it->first.getId() == reg.getId())
it = this->readRegisters.erase(it);
else
++it;
}
}
void Instruction::setWrittenRegister(const triton::arch::Register& reg, triton::ast::AbstractNode* node) {
this->writtenRegisters.insert(std::make_pair(reg, node));
}
void Instruction::removeWrittenRegister(const triton::arch::Register& reg) {
auto it = this->writtenRegisters.begin();
while (it != this->writtenRegisters.end()) {
if (it->first.getId() == reg.getId())
it = this->writtenRegisters.erase(it);
else
++it;
}
}
void Instruction::setReadImmediate(const triton::arch::Immediate& imm, triton::ast::AbstractNode* node) {
this->readImmediates.insert(std::make_pair(imm, node));
}
void Instruction::removeReadImmediate(const triton::arch::Immediate& imm) {
auto it = this->readImmediates.begin();
while (it != this->readImmediates.end()) {
if (it->first.getValue() == imm.getValue())
it = this->readImmediates.erase(it);
else
++it;
}
}
void Instruction::setSize(triton::uint32 size) {
this->size = size;
}
void Instruction::setType(triton::uint32 type) {
this->type = type;
}
void Instruction::setPrefix(triton::uint32 prefix) {
this->prefix = prefix;
}
void Instruction::setDisassembly(const std::string& str) {
this->disassembly.clear();
this->disassembly.str(str);
}
void Instruction::setTaint(bool state) {
this->tainted = state;
}
void Instruction::setTaint(void) {
std::vector<triton::engines::symbolic::SymbolicExpression*>::const_iterator it;
for (it = this->symbolicExpressions.begin(); it != this->symbolicExpressions.end(); it++) {
if ((*it)->isTainted == true) {
this->tainted = true;
break;
}
}
}
void Instruction::updateContext(const triton::arch::Register& reg) {
this->registerState[reg.getId()] = reg;
}
void Instruction::addSymbolicExpression(triton::engines::symbolic::SymbolicExpression* expr) {
if (expr == nullptr)
throw triton::exceptions::Instruction("Instruction::addSymbolicExpression(): Cannot add a null expression.");
this->symbolicExpressions.push_back(expr);
}
bool Instruction::isBranch(void) const {
return this->branch;
}
bool Instruction::isControlFlow(void) const {
return this->controlFlow;
}
bool Instruction::isConditionTaken(void) const {
return this->conditionTaken;
}
bool Instruction::isTainted(void) const {
return this->tainted;
}
bool Instruction::isSymbolized(void) const {
std::vector<triton::engines::symbolic::SymbolicExpression*>::const_iterator it;
for (it = this->symbolicExpressions.begin(); it != this->symbolicExpressions.end(); it++) {
if ((*it)->isSymbolized() == true)
return true;
}
return false;
}
bool Instruction::isMemoryRead(void) const {
if (this->loadAccess.size() >= 1)
return true;
return false;
}
bool Instruction::isMemoryWrite(void) const {
if (this->storeAccess.size() >= 1)
return true;
return false;
}
bool Instruction::isReadFrom(const triton::arch::OperandWrapper& target) const {
switch(target.getType()) {
case triton::arch::OP_IMM:
for (auto&& pair : this->readImmediates) {
if (pair.first == target.getConstImmediate())
return true;
}
break;
case triton::arch::OP_MEM:
for (auto&& pair : this->loadAccess) {
const triton::arch::MemoryAccess& m1 = pair.first;
const triton::arch::MemoryAccess& m2 = target.getConstMemory();
if (m1.isOverlapWith(m2))
return true;
}
break;
case triton::arch::OP_REG:
for (auto&& pair : this->readRegisters) {
const triton::arch::Register& r1 = pair.first;
const triton::arch::Register& r2 = target.getConstRegister();
if (r1.isOverlapWith(r2))
return true;
}
break;
default:
throw triton::exceptions::Instruction("Instruction::isReadFrom(): Invalid type operand.");
}
return false;
}
bool Instruction::isWriteTo(const triton::arch::OperandWrapper& target) const {
switch(target.getType()) {
case triton::arch::OP_IMM:
break;
case triton::arch::OP_MEM:
for (auto&& pair : this->storeAccess) {
const triton::arch::MemoryAccess& m1 = pair.first;
const triton::arch::MemoryAccess& m2 = target.getConstMemory();
if (m1.isOverlapWith(m2))
return true;
}
break;
case triton::arch::OP_REG:
for (auto&& pair : this->writtenRegisters) {
const triton::arch::Register& r1 = pair.first;
const triton::arch::Register& r2 = target.getConstRegister();
if (r1.isOverlapWith(r2))
return true;
}
break;
default:
throw triton::exceptions::Instruction("Instruction::isWriteTo(): Invalid type operand.");
}
return false;
}
bool Instruction::isPrefixed(void) const {
if (this->prefix)
return true;
return false;
}
void Instruction::setBranch(bool flag) {
this->branch = flag;
}
void Instruction::setControlFlow(bool flag) {
this->controlFlow = flag;
}
void Instruction::setConditionTaken(bool flag) {
this->conditionTaken = flag;
}
void Instruction::reset(void) {
this->partialReset();
this->memoryAccess.clear();
this->registerState.clear();
}
void Instruction::partialReset(void) {
this->address = 0;
this->branch = false;
this->conditionTaken = false;
this->controlFlow = false;
this->size = 0;
this->tainted = false;
this->tid = 0;
this->type = 0;
this->disassembly.clear();
this->loadAccess.clear();
this->operands.clear();
this->readImmediates.clear();
this->readRegisters.clear();
this->storeAccess.clear();
this->symbolicExpressions.clear();
this->writtenRegisters.clear();
std::memset(this->opcodes, 0x00, sizeof(this->opcodes));
}
std::ostream& operator<<(std::ostream& stream, const Instruction& inst) {
stream << std::hex << inst.getAddress() << ": " << inst.getDisassembly() << std::dec;
return stream;
}
std::ostream& operator<<(std::ostream& stream, const Instruction* inst) {
stream << *inst;
return stream;
}
};
};
<commit_msg>Use hex prefix for opcode location.<commit_after>//! \file
/*
** Copyright (C) - Triton
**
** This program is under the terms of the BSD License.
*/
#include <cstring>
#include <exceptions.hpp>
#include <immediate.hpp>
#include <instruction.hpp>
namespace triton {
namespace arch {
Instruction::Instruction() {
this->address = 0;
this->branch = false;
this->conditionTaken = false;
this->controlFlow = false;
this->prefix = 0;
this->size = 0;
this->tainted = false;
this->tid = 0;
this->type = 0;
std::memset(this->opcodes, 0x00, sizeof(this->opcodes));
}
Instruction::Instruction(const triton::uint8* opcodes, triton::uint32 opSize) : Instruction::Instruction() {
this->setOpcodes(opcodes, opSize);
}
Instruction::~Instruction() {
}
Instruction::Instruction(const Instruction& other) {
this->copy(other);
}
void Instruction::operator=(const Instruction& other) {
this->copy(other);
}
void Instruction::copy(const Instruction& other) {
this->address = other.address;
this->branch = other.branch;
this->conditionTaken = other.conditionTaken;
this->controlFlow = other.controlFlow;
this->loadAccess = other.loadAccess;
this->memoryAccess = other.memoryAccess;
this->operands = other.operands;
this->prefix = other.prefix;
this->readRegisters = other.readRegisters;
this->registerState = other.registerState;
this->size = other.size;
this->storeAccess = other.storeAccess;
this->symbolicExpressions = other.symbolicExpressions;
this->tainted = other.tainted;
this->tid = other.tid;
this->type = other.type;
this->writtenRegisters = other.writtenRegisters;
std::memcpy(this->opcodes, other.opcodes, sizeof(this->opcodes));
this->disassembly.clear();
this->disassembly.str(other.disassembly.str());
}
triton::uint32 Instruction::getThreadId(void) const {
return this->tid;
}
void Instruction::setThreadId(triton::uint32 tid) {
this->tid = tid;
}
triton::uint64 Instruction::getAddress(void) const {
return this->address;
}
triton::uint64 Instruction::getNextAddress(void) const {
return this->address + this->size;
}
void Instruction::setAddress(triton::uint64 addr) {
this->address = addr;
}
std::string Instruction::getDisassembly(void) const {
return this->disassembly.str();
}
const triton::uint8* Instruction::getOpcodes(void) const {
return this->opcodes;
}
void Instruction::setOpcodes(const triton::uint8* opcodes, triton::uint32 size) {
if (size >= sizeof(this->opcodes))
throw triton::exceptions::Instruction("Instruction::setOpcodes(): Invalid size (too big).");
std::memcpy(this->opcodes, opcodes, size);
this->size = size;
}
triton::uint32 Instruction::getSize(void) const {
return this->size;
}
triton::uint32 Instruction::getType(void) const {
return this->type;
}
triton::uint32 Instruction::getPrefix(void) const {
return this->prefix;
}
const std::set<std::pair<triton::arch::MemoryAccess, triton::ast::AbstractNode*>>& Instruction::getLoadAccess(void) const {
return this->loadAccess;
}
const std::set<std::pair<triton::arch::MemoryAccess, triton::ast::AbstractNode*>>& Instruction::getStoreAccess(void) const {
return this->storeAccess;
}
const std::set<std::pair<triton::arch::Register, triton::ast::AbstractNode*>>& Instruction::getReadRegisters(void) const {
return this->readRegisters;
}
const std::set<std::pair<triton::arch::Register, triton::ast::AbstractNode*>>& Instruction::getWrittenRegisters(void) const {
return this->writtenRegisters;
}
const std::set<std::pair<triton::arch::Immediate, triton::ast::AbstractNode*>>& Instruction::getReadImmediates(void) const {
return this->readImmediates;
}
void Instruction::updateContext(const triton::arch::MemoryAccess& mem) {
this->memoryAccess.push_back(mem);
}
/* If there is a concrete value recorded, build the appropriate Register. Otherwise, perfrom the analysis on zero. */
triton::arch::Register Instruction::getRegisterState(triton::uint32 regId) {
triton::arch::Register reg(regId);
if (this->registerState.find(regId) != this->registerState.end())
reg = this->registerState[regId];
return reg;
}
void Instruction::setLoadAccess(const triton::arch::MemoryAccess& mem, triton::ast::AbstractNode* node) {
this->loadAccess.insert(std::make_pair(mem, node));
}
void Instruction::removeLoadAccess(const triton::arch::MemoryAccess& mem) {
auto it = this->loadAccess.begin();
while (it != this->loadAccess.end()) {
if (it->first.getAddress() == mem.getAddress())
it = this->loadAccess.erase(it);
else
++it;
}
}
void Instruction::setStoreAccess(const triton::arch::MemoryAccess& mem, triton::ast::AbstractNode* node) {
this->storeAccess.insert(std::make_pair(mem, node));
}
void Instruction::removeStoreAccess(const triton::arch::MemoryAccess& mem) {
auto it = this->storeAccess.begin();
while (it != this->storeAccess.end()) {
if (it->first.getAddress() == mem.getAddress())
it = this->storeAccess.erase(it);
else
++it;
}
}
void Instruction::setReadRegister(const triton::arch::Register& reg, triton::ast::AbstractNode* node) {
this->readRegisters.insert(std::make_pair(reg, node));
}
void Instruction::removeReadRegister(const triton::arch::Register& reg) {
auto it = this->readRegisters.begin();
while (it != this->readRegisters.end()) {
if (it->first.getId() == reg.getId())
it = this->readRegisters.erase(it);
else
++it;
}
}
void Instruction::setWrittenRegister(const triton::arch::Register& reg, triton::ast::AbstractNode* node) {
this->writtenRegisters.insert(std::make_pair(reg, node));
}
void Instruction::removeWrittenRegister(const triton::arch::Register& reg) {
auto it = this->writtenRegisters.begin();
while (it != this->writtenRegisters.end()) {
if (it->first.getId() == reg.getId())
it = this->writtenRegisters.erase(it);
else
++it;
}
}
void Instruction::setReadImmediate(const triton::arch::Immediate& imm, triton::ast::AbstractNode* node) {
this->readImmediates.insert(std::make_pair(imm, node));
}
void Instruction::removeReadImmediate(const triton::arch::Immediate& imm) {
auto it = this->readImmediates.begin();
while (it != this->readImmediates.end()) {
if (it->first.getValue() == imm.getValue())
it = this->readImmediates.erase(it);
else
++it;
}
}
void Instruction::setSize(triton::uint32 size) {
this->size = size;
}
void Instruction::setType(triton::uint32 type) {
this->type = type;
}
void Instruction::setPrefix(triton::uint32 prefix) {
this->prefix = prefix;
}
void Instruction::setDisassembly(const std::string& str) {
this->disassembly.clear();
this->disassembly.str(str);
}
void Instruction::setTaint(bool state) {
this->tainted = state;
}
void Instruction::setTaint(void) {
std::vector<triton::engines::symbolic::SymbolicExpression*>::const_iterator it;
for (it = this->symbolicExpressions.begin(); it != this->symbolicExpressions.end(); it++) {
if ((*it)->isTainted == true) {
this->tainted = true;
break;
}
}
}
void Instruction::updateContext(const triton::arch::Register& reg) {
this->registerState[reg.getId()] = reg;
}
void Instruction::addSymbolicExpression(triton::engines::symbolic::SymbolicExpression* expr) {
if (expr == nullptr)
throw triton::exceptions::Instruction("Instruction::addSymbolicExpression(): Cannot add a null expression.");
this->symbolicExpressions.push_back(expr);
}
bool Instruction::isBranch(void) const {
return this->branch;
}
bool Instruction::isControlFlow(void) const {
return this->controlFlow;
}
bool Instruction::isConditionTaken(void) const {
return this->conditionTaken;
}
bool Instruction::isTainted(void) const {
return this->tainted;
}
bool Instruction::isSymbolized(void) const {
std::vector<triton::engines::symbolic::SymbolicExpression*>::const_iterator it;
for (it = this->symbolicExpressions.begin(); it != this->symbolicExpressions.end(); it++) {
if ((*it)->isSymbolized() == true)
return true;
}
return false;
}
bool Instruction::isMemoryRead(void) const {
if (this->loadAccess.size() >= 1)
return true;
return false;
}
bool Instruction::isMemoryWrite(void) const {
if (this->storeAccess.size() >= 1)
return true;
return false;
}
bool Instruction::isReadFrom(const triton::arch::OperandWrapper& target) const {
switch(target.getType()) {
case triton::arch::OP_IMM:
for (auto&& pair : this->readImmediates) {
if (pair.first == target.getConstImmediate())
return true;
}
break;
case triton::arch::OP_MEM:
for (auto&& pair : this->loadAccess) {
const triton::arch::MemoryAccess& m1 = pair.first;
const triton::arch::MemoryAccess& m2 = target.getConstMemory();
if (m1.isOverlapWith(m2))
return true;
}
break;
case triton::arch::OP_REG:
for (auto&& pair : this->readRegisters) {
const triton::arch::Register& r1 = pair.first;
const triton::arch::Register& r2 = target.getConstRegister();
if (r1.isOverlapWith(r2))
return true;
}
break;
default:
throw triton::exceptions::Instruction("Instruction::isReadFrom(): Invalid type operand.");
}
return false;
}
bool Instruction::isWriteTo(const triton::arch::OperandWrapper& target) const {
switch(target.getType()) {
case triton::arch::OP_IMM:
break;
case triton::arch::OP_MEM:
for (auto&& pair : this->storeAccess) {
const triton::arch::MemoryAccess& m1 = pair.first;
const triton::arch::MemoryAccess& m2 = target.getConstMemory();
if (m1.isOverlapWith(m2))
return true;
}
break;
case triton::arch::OP_REG:
for (auto&& pair : this->writtenRegisters) {
const triton::arch::Register& r1 = pair.first;
const triton::arch::Register& r2 = target.getConstRegister();
if (r1.isOverlapWith(r2))
return true;
}
break;
default:
throw triton::exceptions::Instruction("Instruction::isWriteTo(): Invalid type operand.");
}
return false;
}
bool Instruction::isPrefixed(void) const {
if (this->prefix)
return true;
return false;
}
void Instruction::setBranch(bool flag) {
this->branch = flag;
}
void Instruction::setControlFlow(bool flag) {
this->controlFlow = flag;
}
void Instruction::setConditionTaken(bool flag) {
this->conditionTaken = flag;
}
void Instruction::reset(void) {
this->partialReset();
this->memoryAccess.clear();
this->registerState.clear();
}
void Instruction::partialReset(void) {
this->address = 0;
this->branch = false;
this->conditionTaken = false;
this->controlFlow = false;
this->size = 0;
this->tainted = false;
this->tid = 0;
this->type = 0;
this->disassembly.clear();
this->loadAccess.clear();
this->operands.clear();
this->readImmediates.clear();
this->readRegisters.clear();
this->storeAccess.clear();
this->symbolicExpressions.clear();
this->writtenRegisters.clear();
std::memset(this->opcodes, 0x00, sizeof(this->opcodes));
}
std::ostream& operator<<(std::ostream& stream, const Instruction& inst) {
stream << "0x" << std::hex << inst.getAddress() << ": " << inst.getDisassembly() << std::dec;
return stream;
}
std::ostream& operator<<(std::ostream& stream, const Instruction* inst) {
stream << *inst;
return stream;
}
};
};
<|endoftext|>
|
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2016-2017 Raffaello D. Di Napoli
This file is part of Lofty.
Lofty is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Lofty 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 Lofty. If not, see
<http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------------------------------------*/
#include <lofty.hxx>
#include <lofty/collections/vector.hxx>
#include <lofty/text/parsers/dynamic.hxx>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace lofty { namespace text { namespace parsers {
namespace {
//! Backtracking data structure.
struct backtrack {
dynamic::state const * state;
bool did_consume_cp:1;
bool repetition:1;
bool accepted_repetition:1;
static backtrack make_default(dynamic::state const * state_, bool did_consume_cp) {
backtrack new_backtrack;
new_backtrack.state = state_;
new_backtrack.did_consume_cp = did_consume_cp;
new_backtrack.repetition = false;
new_backtrack.accepted_repetition = false;
return _std::move(new_backtrack);
}
static backtrack make_repetition(dynamic::state const * state_, bool accepted) {
backtrack new_backtrack;
new_backtrack.state = state_;
new_backtrack.did_consume_cp = false;
new_backtrack.repetition = true;
new_backtrack.accepted_repetition = accepted;
return _std::move(new_backtrack);
}
};
//! Used to track the acceptance of repetition states.
struct repetition {
explicit repetition(dynamic::state const * state_) :
state(state_),
count(0) {
}
dynamic::state const * state;
std::uint16_t count;
};
} //namespace
struct dynamic::match::capture_node {
//! Pointer to the capture_begin state.
struct state const * state;
//! Pointer to the parent (containing) capture. Only nullptr for capture 0.
capture_node * parent;
//! Owning pointer to the first nested capture, if any.
_std::unique_ptr<capture_node> first_nested;
//! Non-owning pointer to the last nested capture, if any.
capture_node * last_nested;
//! Non-owning pointer to the previous same-level capture, if any.
capture_node * prev_sibling;
//! Owning pointer to the next same-level capture, if any.
_std::unique_ptr<capture_node> next_sibling;
//! Offset of the start of the capture.
std::size_t begin;
//! Offset of the end of the capture.
std::size_t end;
/*! Constructor.
@param state_
Pointer to the related capture_begin state.
*/
explicit capture_node(struct state const * state_) :
state(state_),
parent(nullptr),
last_nested(nullptr),
prev_sibling(nullptr) {
}
//! Destructor.
~capture_node() {
// last_nested is the only non-owning forward pointer, so it must be updated manually.
if (parent && parent->last_nested == this) {
parent->last_nested = prev_sibling;
}
}
/*! Adds a new capture_node at the end of the nested capture nodes list.
@param state_
Pointer to the related capture_begin state.
*/
capture_node * append_nested(struct state const * state_) {
_std::unique_ptr<capture_node> ret_owner(new capture_node(state_));
auto ret = ret_owner.get();
if (last_nested) {
last_nested->next_sibling = _std::move(ret_owner);
ret->prev_sibling = last_nested;
} else {
first_nested = _std::move(ret_owner);
last_nested = ret;
}
ret->parent = this;
return ret;
}
};
dynamic::match::match() {
}
dynamic::match::match(match && src) :
captures_buffer(_std::move(src.captures_buffer)),
capture0(_std::move(src.capture0)) {
}
dynamic::match::~match() {
}
dynamic::dynamic() :
initial_state(nullptr) {
}
dynamic::dynamic(dynamic && src) :
states_list(_std::move(src.states_list)),
initial_state(src.initial_state) {
src.initial_state = nullptr;
}
dynamic::~dynamic() {
}
dynamic::state * dynamic::create_begin_state() {
return create_uninitialized_state(state_type::begin);
}
dynamic::state * dynamic::create_capture_begin_state() {
return create_uninitialized_state(state_type::capture_begin);
}
dynamic::state * dynamic::create_capture_end_state() {
return create_uninitialized_state(state_type::capture_end);
}
dynamic::state * dynamic::create_code_point_state(char32_t cp) {
state * ret = create_uninitialized_state(state_type::range);
ret->u.range.first_cp = cp;
ret->u.range.last_cp = cp;
return ret;
}
dynamic::state * dynamic::create_code_point_range_state(char32_t first_cp, char32_t last_cp) {
state * ret = create_uninitialized_state(state_type::range);
ret->u.range.first_cp = first_cp;
ret->u.range.last_cp = last_cp;
return ret;
}
dynamic::state * dynamic::create_end_state() {
return create_uninitialized_state(state_type::end);
}
dynamic::state * dynamic::create_repetition_state(
state const * repeated_state, std::uint16_t min, std::uint16_t max /*= 0*/
) {
state * ret = create_uninitialized_state(state_type::repetition);
ret->u.repetition.repeated_state = repeated_state;
ret->u.repetition.min = min;
ret->u.repetition.max = max;
ret->u.repetition.greedy = true;
return ret;
}
dynamic::state * dynamic::create_uninitialized_state(state_type type) {
states_list.push_back(state());
state * ret = static_cast<state *>(&states_list.back());
ret->type = type.base();
ret->next = nullptr;
ret->alternative = nullptr;
return ret;
}
dynamic::match dynamic::run(str const & s) const {
io::text::str_istream istream(external_buffer, &s);
return run(&istream);
}
dynamic::match dynamic::run(io::text::istream * istream) const {
LOFTY_TRACE_FUNC(this, istream);
match ret;
auto curr_state = initial_state;
// Cache this condition to quickly determine whether we’re allowed to skip input code points.
bool begin_anchor = (curr_state && curr_state->type == state_type::begin && !curr_state->alternative);
// Setup the two sources of code points: a history and a peek buffer from the input stream.
str & history_buf = ret.captures_buffer, peek_buf = istream->peek_chars(1);
auto history_begin_itr(history_buf.cbegin()), history_end(history_buf.cend());
auto history_itr(history_begin_itr), peek_itr(peek_buf.cbegin()), peek_end(peek_buf.cend());
ret.capture0.reset(new match::capture_node(curr_state));
auto curr_capture = ret.capture0.get();
// TODO: change these two variables to use collections::stack once that’s available.
collections::vector<backtrack> backtracking_stack;
/* Stack of repetition counters. A new counter is pushed when a new repetition is started, and popped when
that repetition is a) matched max times or b) backtracked over. */
collections::vector<repetition> reps_stack;
bool accepted = false;
while (curr_state) {
state const * next = nullptr;
bool did_consume_cp = false;
switch (curr_state->type) {
case state_type::range: {
// Get a code point from either history or the peek buffer.
char32_t cp;
bool save_peeked_cp_to_history;
if (history_itr != history_end) {
cp = *history_itr;
save_peeked_cp_to_history = false;
} else {
if (peek_itr == peek_end) {
istream->consume_chars(peek_buf.size_in_chars());
peek_buf = istream->peek_chars(1);
peek_itr = peek_buf.cbegin();
peek_end = peek_buf.cend();
if (peek_itr == peek_end) {
// Run out of code points.
break;
}
}
cp = *peek_itr;
save_peeked_cp_to_history = true;
}
if (cp >= curr_state->u.range.first_cp && cp <= curr_state->u.range.last_cp) {
accepted = true;
did_consume_cp = true;
next = curr_state->next;
if (save_peeked_cp_to_history) {
history_buf += cp;
++history_end;
++peek_itr;
}
++history_itr;
}
break;
}
case state_type::repetition:
repetition * rep;
if (reps_stack && (rep = &reps_stack.front())->state == curr_state) {
++rep->count;
} else {
// New repetition: save it on the stack and begin counting.
reps_stack.push_back(repetition(curr_state));
// TODO: FIXME: pushing back but then using front?!
rep = &reps_stack.front();
}
if (curr_state->u.repetition.max == 0 || rep->count <= curr_state->u.repetition.max) {
if (rep->count >= curr_state->u.repetition.min) {
// Repetitions within [min, max] are accepting.
accepted = true;
}
// Try one more repetition.
next = curr_state->u.repetition.repeated_state;
} else {
// Repeated max times; pop the stack and move on to the next state.
reps_stack.pop_back();
next = curr_state->next;
}
// This code is very similar to the “if (accepted)” after this switch statement.
if (!next) {
// No more states; this means that the input was accepted.
break;
}
backtracking_stack.push_back(backtrack::make_repetition(curr_state, accepted));
accepted = false;
curr_state = next;
// Skip the accept/backtrack logic at the end of the loop.
continue;
case state_type::begin:
if (history_itr == history_begin_itr) {
accepted = true;
next = curr_state->next;
}
break;
case state_type::end:
if (history_itr == history_end && peek_itr == peek_end) {
/* We consumed history and peek buffer, but “end” really means end, so also check that the
stream is empty. */
/* TODO: this might be redundant, since other code point consumers in this function always do
this after consuming a code point. */
istream->consume_chars(peek_buf.size_in_chars());
peek_buf = istream->peek_chars(1);
if (!peek_buf) {
accepted = true;
next = curr_state->next;
}
}
break;
case state_type::capture_begin:
// Nest this capture into the currently-open capture.
curr_capture = curr_capture->append_nested(curr_state);
curr_capture->begin = history_itr.char_index();
accepted = true;
next = curr_state->next;
break;
case state_type::capture_end:
curr_capture->end = history_itr.char_index();
// This capture is over; resume its parent.
curr_capture = curr_capture->parent;
accepted = true;
next = curr_state->next;
break;
case state_type::look_ahead:
// TODO: implement look-ahead assertions.
break;
}
if (accepted) {
if (!next) {
// No more states; this means that the input was accepted.
break;
}
// Still one or more states to check; this means that we can’t accept the input just yet.
backtracking_stack.push_back(backtrack::make_default(curr_state, did_consume_cp));
accepted = false;
curr_state = next;
} else {
// Consider the next alternative of the current state or a prior one.
curr_state = curr_state->alternative;
while (!curr_state && backtracking_stack) {
auto backtrack(backtracking_stack.pop_back());
switch (backtrack.state->type) {
case state_type::repetition:
// If we’re backtracking the current top-of-the-stack repetition, pop it out of it.
if (reps_stack && reps_stack.back().state == backtrack.state) {
reps_stack.pop_back();
}
break;
case state_type::capture_begin: {
// Discard *curr_capture (by resetting its owner’s pointer) and move back to its parent.
auto parent_capture = curr_capture->parent;
if (auto prev_sibling = curr_capture->prev_sibling) {
prev_sibling->next_sibling.reset();
} else {
parent_capture->first_nested.reset();
}
curr_capture = parent_capture;
break;
}
case state_type::capture_end:
// Re-enter the last (closed) nested capture.
curr_capture = curr_capture->last_nested;
break;
default:
// No special action needed.
break;
}
if (backtrack.accepted_repetition) {
// This must be a repetition’s Nth occurrence, with N in the acceptable range.
if (!backtrack.state->next) {
// If there was no following state, the input is accepted.
accepted = true;
goto break_outer_while;
}
curr_state = backtrack.state->next;
} else {
// Not a repetition, or Nth occurrence with N not in the acceptable range.
curr_state = backtrack.state->alternative;
}
// If the state we’re rolling back consumed a code point, it must’ve saved it in history_buf.
if (backtrack.did_consume_cp) {
--history_itr;
}
}
/* If we run out of alternatives and can’t backtrack any further, and the pattern is not anchored,
we’re allowed to move one code point to history and try the whole pattern again from the initial
state. */
if (!curr_state && !begin_anchor) {
if (history_itr == history_end) {
if (peek_itr == peek_end) {
istream->consume_chars(peek_buf.size_in_chars());
peek_buf = istream->peek_chars(1);
if (!peek_buf) {
// Run out of code points.
break;
}
peek_itr = peek_buf.cbegin();
peek_end = peek_buf.cend();
}
history_buf += *peek_itr++;
++history_end;
}
++history_itr;
curr_state = initial_state;
}
}
}
break_outer_while:
if (!accepted) {
ret.capture0.reset();
}
return _std::move(ret);
}
}}} //namespace lofty::text::parsers
<commit_msg>Remove unneeded member variable<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2016-2017 Raffaello D. Di Napoli
This file is part of Lofty.
Lofty is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General
Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
Lofty 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 Lofty. If not, see
<http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------------------------------------*/
#include <lofty.hxx>
#include <lofty/collections/vector.hxx>
#include <lofty/text/parsers/dynamic.hxx>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace lofty { namespace text { namespace parsers {
namespace {
//! Backtracking data structure.
struct backtrack {
dynamic::state const * state;
bool did_consume_cp:1;
bool accepted_repetition:1;
static backtrack make_default(dynamic::state const * state_, bool did_consume_cp) {
backtrack new_backtrack;
new_backtrack.state = state_;
new_backtrack.did_consume_cp = did_consume_cp;
new_backtrack.accepted_repetition = false;
return _std::move(new_backtrack);
}
static backtrack make_repetition(dynamic::state const * state_, bool accepted) {
backtrack new_backtrack;
new_backtrack.state = state_;
new_backtrack.did_consume_cp = false;
new_backtrack.accepted_repetition = accepted;
return _std::move(new_backtrack);
}
};
//! Used to track the acceptance of repetition states.
struct repetition {
explicit repetition(dynamic::state const * state_) :
state(state_),
count(0) {
}
dynamic::state const * state;
std::uint16_t count;
};
} //namespace
struct dynamic::match::capture_node {
//! Pointer to the capture_begin state.
struct state const * state;
//! Pointer to the parent (containing) capture. Only nullptr for capture 0.
capture_node * parent;
//! Owning pointer to the first nested capture, if any.
_std::unique_ptr<capture_node> first_nested;
//! Non-owning pointer to the last nested capture, if any.
capture_node * last_nested;
//! Non-owning pointer to the previous same-level capture, if any.
capture_node * prev_sibling;
//! Owning pointer to the next same-level capture, if any.
_std::unique_ptr<capture_node> next_sibling;
//! Offset of the start of the capture.
std::size_t begin;
//! Offset of the end of the capture.
std::size_t end;
/*! Constructor.
@param state_
Pointer to the related capture_begin state.
*/
explicit capture_node(struct state const * state_) :
state(state_),
parent(nullptr),
last_nested(nullptr),
prev_sibling(nullptr) {
}
//! Destructor.
~capture_node() {
// last_nested is the only non-owning forward pointer, so it must be updated manually.
if (parent && parent->last_nested == this) {
parent->last_nested = prev_sibling;
}
}
/*! Adds a new capture_node at the end of the nested capture nodes list.
@param state_
Pointer to the related capture_begin state.
*/
capture_node * append_nested(struct state const * state_) {
_std::unique_ptr<capture_node> ret_owner(new capture_node(state_));
auto ret = ret_owner.get();
if (last_nested) {
last_nested->next_sibling = _std::move(ret_owner);
ret->prev_sibling = last_nested;
} else {
first_nested = _std::move(ret_owner);
last_nested = ret;
}
ret->parent = this;
return ret;
}
};
dynamic::match::match() {
}
dynamic::match::match(match && src) :
captures_buffer(_std::move(src.captures_buffer)),
capture0(_std::move(src.capture0)) {
}
dynamic::match::~match() {
}
dynamic::dynamic() :
initial_state(nullptr) {
}
dynamic::dynamic(dynamic && src) :
states_list(_std::move(src.states_list)),
initial_state(src.initial_state) {
src.initial_state = nullptr;
}
dynamic::~dynamic() {
}
dynamic::state * dynamic::create_begin_state() {
return create_uninitialized_state(state_type::begin);
}
dynamic::state * dynamic::create_capture_begin_state() {
return create_uninitialized_state(state_type::capture_begin);
}
dynamic::state * dynamic::create_capture_end_state() {
return create_uninitialized_state(state_type::capture_end);
}
dynamic::state * dynamic::create_code_point_state(char32_t cp) {
state * ret = create_uninitialized_state(state_type::range);
ret->u.range.first_cp = cp;
ret->u.range.last_cp = cp;
return ret;
}
dynamic::state * dynamic::create_code_point_range_state(char32_t first_cp, char32_t last_cp) {
state * ret = create_uninitialized_state(state_type::range);
ret->u.range.first_cp = first_cp;
ret->u.range.last_cp = last_cp;
return ret;
}
dynamic::state * dynamic::create_end_state() {
return create_uninitialized_state(state_type::end);
}
dynamic::state * dynamic::create_repetition_state(
state const * repeated_state, std::uint16_t min, std::uint16_t max /*= 0*/
) {
state * ret = create_uninitialized_state(state_type::repetition);
ret->u.repetition.repeated_state = repeated_state;
ret->u.repetition.min = min;
ret->u.repetition.max = max;
ret->u.repetition.greedy = true;
return ret;
}
dynamic::state * dynamic::create_uninitialized_state(state_type type) {
states_list.push_back(state());
state * ret = static_cast<state *>(&states_list.back());
ret->type = type.base();
ret->next = nullptr;
ret->alternative = nullptr;
return ret;
}
dynamic::match dynamic::run(str const & s) const {
io::text::str_istream istream(external_buffer, &s);
return run(&istream);
}
dynamic::match dynamic::run(io::text::istream * istream) const {
LOFTY_TRACE_FUNC(this, istream);
match ret;
auto curr_state = initial_state;
// Cache this condition to quickly determine whether we’re allowed to skip input code points.
bool begin_anchor = (curr_state && curr_state->type == state_type::begin && !curr_state->alternative);
// Setup the two sources of code points: a history and a peek buffer from the input stream.
str & history_buf = ret.captures_buffer, peek_buf = istream->peek_chars(1);
auto history_begin_itr(history_buf.cbegin()), history_end(history_buf.cend());
auto history_itr(history_begin_itr), peek_itr(peek_buf.cbegin()), peek_end(peek_buf.cend());
ret.capture0.reset(new match::capture_node(curr_state));
auto curr_capture = ret.capture0.get();
// TODO: change these two variables to use collections::stack once that’s available.
collections::vector<backtrack> backtracking_stack;
/* Stack of repetition counters. A new counter is pushed when a new repetition is started, and popped when
that repetition is a) matched max times or b) backtracked over. */
collections::vector<repetition> reps_stack;
bool accepted = false;
while (curr_state) {
state const * next = nullptr;
bool did_consume_cp = false;
switch (curr_state->type) {
case state_type::range: {
// Get a code point from either history or the peek buffer.
char32_t cp;
bool save_peeked_cp_to_history;
if (history_itr != history_end) {
cp = *history_itr;
save_peeked_cp_to_history = false;
} else {
if (peek_itr == peek_end) {
istream->consume_chars(peek_buf.size_in_chars());
peek_buf = istream->peek_chars(1);
peek_itr = peek_buf.cbegin();
peek_end = peek_buf.cend();
if (peek_itr == peek_end) {
// Run out of code points.
break;
}
}
cp = *peek_itr;
save_peeked_cp_to_history = true;
}
if (cp >= curr_state->u.range.first_cp && cp <= curr_state->u.range.last_cp) {
accepted = true;
did_consume_cp = true;
next = curr_state->next;
if (save_peeked_cp_to_history) {
history_buf += cp;
++history_end;
++peek_itr;
}
++history_itr;
}
break;
}
case state_type::repetition:
repetition * rep;
if (reps_stack && (rep = &reps_stack.front())->state == curr_state) {
++rep->count;
} else {
// New repetition: save it on the stack and begin counting.
reps_stack.push_back(repetition(curr_state));
// TODO: FIXME: pushing back but then using front?!
rep = &reps_stack.front();
}
if (curr_state->u.repetition.max == 0 || rep->count <= curr_state->u.repetition.max) {
if (rep->count >= curr_state->u.repetition.min) {
// Repetitions within [min, max] are accepting.
accepted = true;
}
// Try one more repetition.
next = curr_state->u.repetition.repeated_state;
} else {
// Repeated max times; pop the stack and move on to the next state.
reps_stack.pop_back();
next = curr_state->next;
}
// This code is very similar to the “if (accepted)” after this switch statement.
if (!next) {
// No more states; this means that the input was accepted.
break;
}
backtracking_stack.push_back(backtrack::make_repetition(curr_state, accepted));
accepted = false;
curr_state = next;
// Skip the accept/backtrack logic at the end of the loop.
continue;
case state_type::begin:
if (history_itr == history_begin_itr) {
accepted = true;
next = curr_state->next;
}
break;
case state_type::end:
if (history_itr == history_end && peek_itr == peek_end) {
/* We consumed history and peek buffer, but “end” really means end, so also check that the
stream is empty. */
/* TODO: this might be redundant, since other code point consumers in this function always do
this after consuming a code point. */
istream->consume_chars(peek_buf.size_in_chars());
peek_buf = istream->peek_chars(1);
if (!peek_buf) {
accepted = true;
next = curr_state->next;
}
}
break;
case state_type::capture_begin:
// Nest this capture into the currently-open capture.
curr_capture = curr_capture->append_nested(curr_state);
curr_capture->begin = history_itr.char_index();
accepted = true;
next = curr_state->next;
break;
case state_type::capture_end:
curr_capture->end = history_itr.char_index();
// This capture is over; resume its parent.
curr_capture = curr_capture->parent;
accepted = true;
next = curr_state->next;
break;
case state_type::look_ahead:
// TODO: implement look-ahead assertions.
break;
}
if (accepted) {
if (!next) {
// No more states; this means that the input was accepted.
break;
}
// Still one or more states to check; this means that we can’t accept the input just yet.
backtracking_stack.push_back(backtrack::make_default(curr_state, did_consume_cp));
accepted = false;
curr_state = next;
} else {
// Consider the next alternative of the current state or a prior one.
curr_state = curr_state->alternative;
while (!curr_state && backtracking_stack) {
auto backtrack(backtracking_stack.pop_back());
switch (backtrack.state->type) {
case state_type::repetition:
// If we’re backtracking the current top-of-the-stack repetition, pop it out of it.
if (reps_stack && reps_stack.back().state == backtrack.state) {
reps_stack.pop_back();
}
break;
case state_type::capture_begin: {
// Discard *curr_capture (by resetting its owner’s pointer) and move back to its parent.
auto parent_capture = curr_capture->parent;
if (auto prev_sibling = curr_capture->prev_sibling) {
prev_sibling->next_sibling.reset();
} else {
parent_capture->first_nested.reset();
}
curr_capture = parent_capture;
break;
}
case state_type::capture_end:
// Re-enter the last (closed) nested capture.
curr_capture = curr_capture->last_nested;
break;
default:
// No special action needed.
break;
}
if (backtrack.accepted_repetition) {
// This must be a repetition’s Nth occurrence, with N in the acceptable range.
if (!backtrack.state->next) {
// If there was no following state, the input is accepted.
accepted = true;
goto break_outer_while;
}
curr_state = backtrack.state->next;
} else {
// Not a repetition, or Nth occurrence with N not in the acceptable range.
curr_state = backtrack.state->alternative;
}
// If the state we’re rolling back consumed a code point, it must’ve saved it in history_buf.
if (backtrack.did_consume_cp) {
--history_itr;
}
}
/* If we run out of alternatives and can’t backtrack any further, and the pattern is not anchored,
we’re allowed to move one code point to history and try the whole pattern again from the initial
state. */
if (!curr_state && !begin_anchor) {
if (history_itr == history_end) {
if (peek_itr == peek_end) {
istream->consume_chars(peek_buf.size_in_chars());
peek_buf = istream->peek_chars(1);
if (!peek_buf) {
// Run out of code points.
break;
}
peek_itr = peek_buf.cbegin();
peek_end = peek_buf.cend();
}
history_buf += *peek_itr++;
++history_end;
}
++history_itr;
curr_state = initial_state;
}
}
}
break_outer_while:
if (!accepted) {
ret.capture0.reset();
}
return _std::move(ret);
}
}}} //namespace lofty::text::parsers
<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/gui/TileGenerator.h>
#include <vw/gui/ImageTileGenerator.h>
#include <vw/gui/PlatefileTileGenerator.h>
#include <vw/gui/TestPatternTileGenerator.h>
#include <vw/gui/WebTileGenerator.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Core/Debugging.h>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;
using namespace vw::platefile;
namespace vw { namespace gui {
ConstantSrc::ConstantSrc(const uint8* data, size_t size, const ImageFormat& fmt)
: m_fmt(fmt), m_size(size), m_data(new uint8[m_size]) {
VW_ASSERT(size >= fmt.byte_size(), LogicErr() << VW_CURRENT_FUNCTION << ": ImageFormat does not match data");
std::copy(data+0, data+size, const_cast<uint8*>(&m_data[0]));
}
void ConstantSrc::read( ImageBuffer const& dst, BBox2i const& bbox ) const {
VW_ASSERT( dst.format.cols == size_t(bbox.width()) && dst.format.rows == size_t(bbox.height()),
ArgumentErr() << VW_CURRENT_FUNCTION << ": Destination buffer has wrong dimensions!" );
VW_ASSERT( dst.format.cols == size_t(cols()) && dst.format.rows == size_t(rows()),
ArgumentErr() << VW_CURRENT_FUNCTION << ": Partial reads are not supported");
const ImageBuffer src(m_fmt, const_cast<uint8*>(m_data.get()));
convert(dst, src, true);
}
std::ostream& operator<<(std::ostream& o, const TileLocator& l) {
o << l.col << "," << l.row << "@" << l.level << ", t=" << l.transaction_id << " exact=" << (l.exact_transaction_id_match ? "YES" : "NO");
return o;
}
BBox2i tile_to_bbox(Vector2i tile_size, int col, int row, int level, int max_level) {
if (col < 0 || row < 0 || col >= (1 << max_level) || row >= (1 << max_level) ) {
return BBox2i();
} else {
BBox2i result(tile_size[0]*col, tile_size[1]*row, tile_size[0], tile_size[1]);
return result * (1 << (max_level - level));
}
}
std::list<TileLocator> bbox_to_tiles(Vector2i tile_size, BBox2i bbox, int level, int max_level, int transaction_id, bool exact_transaction_id_match) {
std::list<TileLocator> results;
// Compute the bounding box at the current level.
BBox2i level_bbox = bbox / (1 << (max_level - level));
// Grow that bounding box to align with tile boundaries
BBox2i aligned_level_bbox = level_bbox;
aligned_level_bbox.min().x() = ( (level_bbox.min().x() / tile_size[0]) * tile_size[0] );
aligned_level_bbox.min().y() = ( (level_bbox.min().y() / tile_size[1]) * tile_size[1] );
aligned_level_bbox.max().x() = ( int(ceilf( float(level_bbox.max().x()) / float(tile_size[0]) ))
* tile_size[0] );
aligned_level_bbox.max().y() = ( int(ceilf( float(level_bbox.max().y()) / float(tile_size[1]) ))
* tile_size[1] );
int tile_y = aligned_level_bbox.min().y() / tile_size[1];
int dest_row = 0;
while ( tile_y < aligned_level_bbox.max().y() / tile_size[1] ) {
int tile_x = aligned_level_bbox.min().x() / tile_size[0];
int dest_col = 0;
while ( tile_x < aligned_level_bbox.max().x() / tile_size[0] ) {
BBox2i tile_bbox(dest_col, dest_row, tile_size[0], tile_size[1]);
TileLocator loc;
loc.col = tile_x;
loc.row = tile_y;
loc.level = level;
loc.transaction_id = transaction_id;
loc.exact_transaction_id_match = exact_transaction_id_match;
results.push_back(loc);
++tile_x;
dest_col += tile_size[0];
}
++tile_y;
dest_row += tile_size[1];
}
return results;
}
boost::shared_ptr<TileGenerator> TileGenerator::create(std::string filename_) {
// Remove trailing /
boost::trim_right_if(filename_, boost::is_any_of("/"));
Url u(filename_);
try {
if (u.scheme() == "http") {
return boost::shared_ptr<TileGenerator>( new WebTileGenerator(u.string(),17));
} else if (u.scheme() == "file") {
if (fs::extension(u.path()) == ".plate")
return boost::shared_ptr<TileGenerator>( new PlatefileTileGenerator(u.path()) );
else if (u.path() == "testpattern")
return boost::shared_ptr<TileGenerator>( new TestPatternTileGenerator(256) );
else
return boost::shared_ptr<TileGenerator>( new ImageTileGenerator(u.path()) );
} else if (u.scheme() == "pf" && fs::extension(u.path()) == ".plate") {
std::cout << "Loading: " << u.path() << "\n";
return boost::shared_ptr<TileGenerator>( new PlatefileTileGenerator(u.string()) );
} else {
std::cerr << "Could not open " << u << ":\n\t" << "No handler for url scheme " << u.scheme() << std::endl;
}
} catch (const vw::Exception& e) {
std::cerr << "Could not open " << u << ":\n\t" << e.what() << std::endl;
}
exit(EXIT_FAILURE);
}
}} // namespace vw::gui
<commit_msg>vwv: allow opening of arbitrary urls as plates<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
#include <vw/gui/TileGenerator.h>
#include <vw/gui/ImageTileGenerator.h>
#include <vw/gui/PlatefileTileGenerator.h>
#include <vw/gui/TestPatternTileGenerator.h>
#include <vw/gui/WebTileGenerator.h>
#include <vw/Plate/HTTPUtils.h>
#include <vw/Core/Debugging.h>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;
using namespace vw::platefile;
namespace vw { namespace gui {
ConstantSrc::ConstantSrc(const uint8* data, size_t size, const ImageFormat& fmt)
: m_fmt(fmt), m_size(size), m_data(new uint8[m_size]) {
VW_ASSERT(size >= fmt.byte_size(), LogicErr() << VW_CURRENT_FUNCTION << ": ImageFormat does not match data");
std::copy(data+0, data+size, const_cast<uint8*>(&m_data[0]));
}
void ConstantSrc::read( ImageBuffer const& dst, BBox2i const& bbox ) const {
VW_ASSERT( dst.format.cols == size_t(bbox.width()) && dst.format.rows == size_t(bbox.height()),
ArgumentErr() << VW_CURRENT_FUNCTION << ": Destination buffer has wrong dimensions!" );
VW_ASSERT( dst.format.cols == size_t(cols()) && dst.format.rows == size_t(rows()),
ArgumentErr() << VW_CURRENT_FUNCTION << ": Partial reads are not supported");
const ImageBuffer src(m_fmt, const_cast<uint8*>(m_data.get()));
convert(dst, src, true);
}
std::ostream& operator<<(std::ostream& o, const TileLocator& l) {
o << l.col << "," << l.row << "@" << l.level << ", t=" << l.transaction_id << " exact=" << (l.exact_transaction_id_match ? "YES" : "NO");
return o;
}
BBox2i tile_to_bbox(Vector2i tile_size, int col, int row, int level, int max_level) {
if (col < 0 || row < 0 || col >= (1 << max_level) || row >= (1 << max_level) ) {
return BBox2i();
} else {
BBox2i result(tile_size[0]*col, tile_size[1]*row, tile_size[0], tile_size[1]);
return result * (1 << (max_level - level));
}
}
std::list<TileLocator> bbox_to_tiles(Vector2i tile_size, BBox2i bbox, int level, int max_level, int transaction_id, bool exact_transaction_id_match) {
std::list<TileLocator> results;
// Compute the bounding box at the current level.
BBox2i level_bbox = bbox / (1 << (max_level - level));
// Grow that bounding box to align with tile boundaries
BBox2i aligned_level_bbox = level_bbox;
aligned_level_bbox.min().x() = ( (level_bbox.min().x() / tile_size[0]) * tile_size[0] );
aligned_level_bbox.min().y() = ( (level_bbox.min().y() / tile_size[1]) * tile_size[1] );
aligned_level_bbox.max().x() = ( int(ceilf( float(level_bbox.max().x()) / float(tile_size[0]) ))
* tile_size[0] );
aligned_level_bbox.max().y() = ( int(ceilf( float(level_bbox.max().y()) / float(tile_size[1]) ))
* tile_size[1] );
int tile_y = aligned_level_bbox.min().y() / tile_size[1];
int dest_row = 0;
while ( tile_y < aligned_level_bbox.max().y() / tile_size[1] ) {
int tile_x = aligned_level_bbox.min().x() / tile_size[0];
int dest_col = 0;
while ( tile_x < aligned_level_bbox.max().x() / tile_size[0] ) {
BBox2i tile_bbox(dest_col, dest_row, tile_size[0], tile_size[1]);
TileLocator loc;
loc.col = tile_x;
loc.row = tile_y;
loc.level = level;
loc.transaction_id = transaction_id;
loc.exact_transaction_id_match = exact_transaction_id_match;
results.push_back(loc);
++tile_x;
dest_col += tile_size[0];
}
++tile_y;
dest_row += tile_size[1];
}
return results;
}
boost::shared_ptr<TileGenerator> TileGenerator::create(std::string filename_) {
// Remove trailing /
boost::trim_right_if(filename_, boost::is_any_of("/"));
Url u(filename_);
try {
if (u.scheme() == "http") {
return boost::shared_ptr<TileGenerator>( new WebTileGenerator(u.string(),17));
} else if (u.scheme() == "file") {
if (fs::extension(u.path()) == ".plate")
return boost::shared_ptr<TileGenerator>( new PlatefileTileGenerator(u.path()) );
else if (u.path() == "testpattern")
return boost::shared_ptr<TileGenerator>( new TestPatternTileGenerator(256) );
else
return boost::shared_ptr<TileGenerator>( new ImageTileGenerator(u.path()) );
} else if (fs::extension(u.path()) == ".plate") {
return boost::shared_ptr<TileGenerator>( new PlatefileTileGenerator(u.string()) );
} else {
std::cerr << "Could not open " << u << ":\n\t" << "No handler for url scheme " << u.scheme() << std::endl;
}
} catch (const vw::Exception& e) {
std::cerr << "Could not open " << u << ":\n\t" << e.what() << std::endl;
}
exit(EXIT_FAILURE);
}
}} // namespace vw::gui
<|endoftext|>
|
<commit_before>#include <sstream>
#include "controller.hpp"
Controller::Controller(): n("~"), new_task(false), ac_speak("/speak", true), ac_gaze("/gaze_at_pose", true), memory_ppl(), name_dict(), person_id(-1)
{
name_tag_sub = n.subscribe<std_msgs::Int32>(/* "/" + robot +*/ "/tag_name_detected", 1000, &Controller::tagSubscriber, this);
rnd_walk_start = n.serviceClient<std_srvs::Empty>("/start_random_walk");
rnd_walk_stop = n.serviceClient<std_srvs::Empty>("/stop_random_walk");
fillDictionary();
ros::spinOnce();
}
void Controller::startDialog()
{
std::cerr<<"I feel like I should talk more..."<<std::endl;
ac_speak.waitForServer();
std::stringstream ss;
std::string name = "";
// get the name for that person
std::map<int,std::string>::iterator it;
it = name_dict.find(person_id);
if(it != name_dict.end()) {
name = it->second;
} else {
name = "unknown person. I do not recognize you"; // start an alarm?
}
ss << "Hi " << name << ".";
// check how often we have seen that person before
std::map<int,int>::iterator it_count;
it_count = memory_ppl.find(person_id);
if(it_count != memory_ppl.end()) {
ss << "We have already met " << it_count->second << " times before.";
ss << "I hope we'll keep in touch." << std::endl;
} else {
ss << " Welcome to the E C M R.";
ss << " Be aware of the other robots. They are plotting an evil plan";
ss << " against you. Especially the green one.";
ss << " I am looking forward to seeing you again.";
ss << std::endl;
}
mary_tts::maryttsGoal goal;
goal.text = ss.str();
ac_speak.sendGoal(goal);
bool finished_before_timeout = ac_speak.waitForResult(ros::Duration(30.0));
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = ac_speak.getState();
ROS_INFO("Action finished: %s",state.toString().c_str());
}
}
void Controller::startGaze()
{
ac_gaze.waitForServer();
strands_gazing::GazeAtPoseGoal goal;
goal.runtime_sec = 0;
goal.topic_name = "/upper_body_detector/closest_bounding_box_centre";
ac_gaze.sendGoal(goal);
bool finished_before_timeout = ac_gaze.waitForResult(ros::Duration(30.0));
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = ac_gaze.getState();
ROS_INFO("Action finished: %s",state.toString().c_str());
}
}
void Controller::tagSubscriber(const std_msgs::Int32::ConstPtr& _msg)
{
if( person_id != _msg->data )
{
new_task = true;
person_id = _msg->data;
std::cerr<<"This is another person with the id: "<<person_id<<std::endl;
}
}
void Controller::update()
{
std_srvs::Empty srv;
if (new_task)
{
new_task = false;
// update our people memory
updatePersonSeen(person_id);
std::cerr<<"Let's stop here for a while..."<<std::endl;
rnd_walk_stop.call(srv);
startGaze();
std::cerr<<"I feel active..."<<std::endl;
startDialog();
ac_gaze.cancelAllGoals();
std::cerr<<"I would like to start roaming again..."<<std::endl;
rnd_walk_start.call(srv);
}
}
void Controller::updatePersonSeen(const int & _person_id) {
// check whether that person exists in the memory
std::map<int,int>::iterator it;
it = memory_ppl.find(_person_id);
if(it != memory_ppl.end()) {
// increase it for a known user
std::cerr<<"I have seen the person already "<<it->second<<" times."<<std::endl;
memory_ppl[_person_id] = it->second++;
} else {
// init new user
std::cerr<<"This is a new person to me."<<std::endl;
memory_ppl[_person_id] = 1;
}
}
void Controller::fillDictionary() {
// fill the name dictionary with peoples' names
name_dict[0] = "Bob";
name_dict[1] = "Betty";
name_dict[2] = "Linda";
name_dict[3] = "Lucie";
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "controller_bev");
Controller theController;
ros::Rate loop_rate(5); // [Hz]
while(ros::ok())
{
theController.update();
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<commit_msg>changed timeout for speaking to 10s<commit_after>#include <sstream>
#include "controller.hpp"
Controller::Controller(): n("~"), new_task(false), ac_speak("/speak", true), ac_gaze("/gaze_at_pose", true), memory_ppl(), name_dict(), person_id(-1)
{
name_tag_sub = n.subscribe<std_msgs::Int32>(/* "/" + robot +*/ "/tag_name_detected", 1000, &Controller::tagSubscriber, this);
rnd_walk_start = n.serviceClient<std_srvs::Empty>("/start_random_walk");
rnd_walk_stop = n.serviceClient<std_srvs::Empty>("/stop_random_walk");
fillDictionary();
ros::spinOnce();
}
void Controller::startDialog()
{
std::cerr<<"I feel like I should talk more..."<<std::endl;
ac_speak.waitForServer();
std::stringstream ss;
std::string name = "";
// get the name for that person
std::map<int,std::string>::iterator it;
it = name_dict.find(person_id);
if(it != name_dict.end()) {
name = it->second;
} else {
name = "unknown person. I do not recognize you"; // start an alarm?
}
ss << "Hi " << name << ".";
// check how often we have seen that person before
std::map<int,int>::iterator it_count;
it_count = memory_ppl.find(person_id);
if(it_count != memory_ppl.end()) {
ss << "We have already met " << it_count->second << " times before.";
ss << "I hope we'll keep in touch." << std::endl;
} else {
ss << " Welcome to the E C M R.";
ss << " Be aware of the other robots. They are plotting an evil plan";
ss << " against you. Especially the green one.";
ss << " I am looking forward to seeing you again.";
ss << std::endl;
}
mary_tts::maryttsGoal goal;
goal.text = ss.str();
ac_speak.sendGoal(goal);
bool finished_before_timeout = ac_speak.waitForResult(ros::Duration(30.0));
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = ac_speak.getState();
ROS_INFO("Action finished: %s",state.toString().c_str());
}
}
void Controller::startGaze()
{
ac_gaze.waitForServer();
strands_gazing::GazeAtPoseGoal goal;
goal.runtime_sec = 0;
goal.topic_name = "/upper_body_detector/closest_bounding_box_centre";
ac_gaze.sendGoal(goal);
bool finished_before_timeout = ac_gaze.waitForResult(ros::Duration(10.0));
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = ac_gaze.getState();
ROS_INFO("Action finished: %s",state.toString().c_str());
}
}
void Controller::tagSubscriber(const std_msgs::Int32::ConstPtr& _msg)
{
if( person_id != _msg->data )
{
new_task = true;
person_id = _msg->data;
std::cerr<<"This is another person with the id: "<<person_id<<std::endl;
}
}
void Controller::update()
{
std_srvs::Empty srv;
if (new_task)
{
new_task = false;
// update our people memory
updatePersonSeen(person_id);
std::cerr<<"Let's stop here for a while..."<<std::endl;
rnd_walk_stop.call(srv);
startGaze();
std::cerr<<"I feel active..."<<std::endl;
startDialog();
ac_gaze.cancelAllGoals();
std::cerr<<"I would like to start roaming again..."<<std::endl;
rnd_walk_start.call(srv);
}
}
void Controller::updatePersonSeen(const int & _person_id) {
// check whether that person exists in the memory
std::map<int,int>::iterator it;
it = memory_ppl.find(_person_id);
if(it != memory_ppl.end()) {
// increase it for a known user
std::cerr<<"I have seen the person already "<<it->second<<" times."<<std::endl;
memory_ppl[_person_id] = it->second++;
} else {
// init new user
std::cerr<<"This is a new person to me."<<std::endl;
memory_ppl[_person_id] = 1;
}
}
void Controller::fillDictionary() {
// fill the name dictionary with peoples' names
name_dict[0] = "Bob";
name_dict[1] = "Betty";
name_dict[2] = "Linda";
name_dict[3] = "Lucie";
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "controller_bev");
Controller theController;
ros::Rate loop_rate(5); // [Hz]
while(ros::ok())
{
theController.update();
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
<|endoftext|>
|
<commit_before>/**
* @file graphReader.hpp
* @ingroup group
* @author Chirag Jain <cjain7@gatech.edu>
* @brief Parallel graph reader using BLISS parallel IO support
*
* Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved.
*/
#ifndef PAR_GRAPH_READER_HPP
#define PAR_GRAPH_READER_HPP
//Includes
#include <iostream>
//Own includes
#include "graphGen/common/timer.hpp"
#include "utils/logging.hpp"
//External includes
#include "io/file_loader.hpp"
#include "common/base_types.hpp"
#include "mxx/comm.hpp"
namespace conn
{
namespace graphGen
{
/*
* @class conn::graphGen::graphFileLoader
* @brief Enables parallel reading of the edgelist file
*/
template<typename Iterator>
class GraphFileLoader : public bliss::io::BaseFileParser<Iterator >
{
public:
using RangeType = bliss::partition::range<size_t>;
//Adjust the file loader's range by informing it how
//to find the beginning of the first record
std::size_t find_first_record(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange)
{
Iterator curr(_data);
Iterator end(_data);
std::size_t i = searchRange.start;
std::advance(end, searchRange.end - searchRange.start);
//every rank except 0 skips initial partial or full record
if(searchRange.start == parentRange.start)
{
this->findEOL(curr, end, i);
this->findNonEOL(curr, end, i);
}
//skip initial sentences beginning with '%'
//There is an assumption here that comments
//are very few and will fall in rank 0's partition
if(searchRange.start != parentRange.start)
{
//Jump to next line if we see a comment
while(*curr == '%')
{
this->findEOL(curr, end, i);
this->findNonEOL(curr, end, i);
}
}
}
/// initializes the parser. only useful for FASTA parser for now. Assumes searchRange do NOT overlap between processes.
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange, const mxx::comm& comm)
{
return find_first_record(_data, parentRange, inMemRange, searchRange);
};
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange)
{
return find_first_record(_data, parentRange, inMemRange, searchRange);
};
};
/**
* @class conn::graphGen::GraphFileParser
* @brief Enables parallel reading of the edgelist file
*/
template<typename Iterator, typename E>
class GraphFileParser : public bliss::io::BaseFileParser<Iterator >
{
private:
//Type of base class
using baseType = typename bliss::io::BaseFileParser<Iterator >;
//MPI communicator
mxx::comm comm;
//Switch to determine if reverse of each edge should be included as well
bool addReverseEdge;
//Reference to the distributed edge list
std::vector< std::pair<E,E> > &edgeList;
const static int OVERLAP = 50;
std::string &filename;
public:
/**
* @brief constructor for this class
* @param[in] edgeList Edgelist to build
* @param[in] comm mpi communicator
*/
template <typename vID>
GraphFileParser(std::vector< std::pair<vID, vID> > &edgeList, bool addReverseEdge,
std::string &filename, const mxx::comm &comm)
: edgeList(edgeList),
addReverseEdge(addReverseEdge),
filename(filename),
comm(comm.copy())
{
static_assert(std::is_same<E, vID>::value, "Edge vector type should match");
}
/**
* @brief populates the edge list vector
* @param[in] filename name of the file to read
*/
void populateEdgeList()
{
Timer timer;
//Value type over which Iterator is defined
typedef typename std::iterator_traits<Iterator>::value_type IteratorValueType;
//Define file loader type
typedef bliss::io::FileLoader<IteratorValueType, OVERLAP, GraphFileLoader > FileLoaderType;
FileLoaderType loader(filename, comm);
//==== now process the file, one L1 block partition per MPI Rank
typename FileLoaderType::L1BlockType partition = loader.getNextL1Block();
//Range of the file partition this MPI rank reads
auto localFileRange = partition.getRange();
//Iterator over data in the file
typename FileLoaderType::L1BlockType::iterator dataIter = partition.begin();
//Initialize the byte offset counter over the range of this rank
std::size_t i = localFileRange.start;
bool lastEdgeRead = true;
//Begin parsing the contents
//lastEdgeRead will be false when we reach the partition end boundary
while (lastEdgeRead) {
lastEdgeRead = readAnEdge(dataIter, partition.end(), i);
}
timer.end_section("File IO completed, graph built");
}
/**
* @brief reads an edge assuming iterator points to
* beginning of a valid record
* @param[in] curr current iterator position
* @return true if edge is read successfully,
* false if partition boundary is encountered
*/
template <typename Iter>
bool readAnEdge(Iter& curr, const Iter &end, std::size_t& offset)
{
//make sure we point to non EOL value
this->findNonEOL(curr, end, offset);
//string to save the contents of a line
std::string readLine;
//till we see end of line
while( ! (*curr == baseType::eol || *curr == baseType::cr))
{
//return if we are crossing the boundary
if(curr == end)
return false;
//keep pushing the character to string
readLine.append(curr, 1);
//advance iterator
curr++; offset++;
//return if we are crossing the boundary
if(curr == end)
return false;
}
parseStringForEdge(readLine);
return true;
}
/**
* @brief assumes string with two integers as input,
* parse the integers and insert to edgeList
* @param[in] record string with 2 integers separated by space
*/
inline void parseStringForEdge(std::string &record)
{
std::stringstream stream(record);
size_t n = std::count(record.begin(), record.end(), ' ');
E vertex1, vertex2;
stream >> vertex1;
stream >> vertex2;
if(n == 1)
{
edgeList.emplace_back(vertex1, vertex2);
if(addReverseEdge)
edgeList.emplace_back(vertex2, vertex1);
}
}
};
}
}
#endif
<commit_msg>Bug fixed<commit_after>/**
* @file graphReader.hpp
* @ingroup group
* @author Chirag Jain <cjain7@gatech.edu>
* @brief Parallel graph reader using BLISS parallel IO support
*
* Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved.
*/
#ifndef PAR_GRAPH_READER_HPP
#define PAR_GRAPH_READER_HPP
//Includes
#include <iostream>
//Own includes
#include "graphGen/common/timer.hpp"
#include "utils/logging.hpp"
//External includes
#include "io/file_loader.hpp"
#include "common/base_types.hpp"
#include "mxx/comm.hpp"
namespace conn
{
namespace graphGen
{
/*
* @class conn::graphGen::graphFileLoader
* @brief Enables parallel reading of the edgelist file
*/
template<typename Iterator>
class GraphFileLoader : public bliss::io::BaseFileParser<Iterator >
{
public:
using RangeType = bliss::partition::range<size_t>;
//Adjust the file loader's range by informing it how
//to find the beginning of the first record
std::size_t find_first_record(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange)
{
Iterator curr(_data);
Iterator end(_data);
RangeType r = RangeType::intersect(inMemRange, searchRange);
std::size_t i = r.start;
std::advance(end, r.end - r.start);
//every rank except 0 skips initial partial or full record
if(r.start != parentRange.start)
{
this->findEOL(curr, end, i);
this->findNonEOL(curr, end, i);
}
//skip initial sentences beginning with '%'
//There is an assumption here that comments
//are very few and will fall in rank 0's partition
if(r.start == parentRange.start)
{
//Jump to next line if we see a comment
while(*curr == '%')
{
this->findEOL(curr, end, i);
this->findNonEOL(curr, end, i);
}
}
return i;
}
/// initializes the parser. only useful for FASTA parser for now. Assumes searchRange do NOT overlap between processes.
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange, const mxx::comm& comm)
{
return find_first_record(_data, parentRange, inMemRange, searchRange);
};
virtual std::size_t init_parser(const Iterator &_data, const RangeType &parentRange, const RangeType &inMemRange, const RangeType &searchRange)
{
return find_first_record(_data, parentRange, inMemRange, searchRange);
};
};
/**
* @class conn::graphGen::GraphFileParser
* @brief Enables parallel reading of the edgelist file
*/
template<typename Iterator, typename E>
class GraphFileParser : public bliss::io::BaseFileParser<Iterator >
{
private:
//Type of base class
using baseType = typename bliss::io::BaseFileParser<Iterator >;
//MPI communicator
mxx::comm comm;
//Switch to determine if reverse of each edge should be included as well
bool addReverseEdge;
//Reference to the distributed edge list
std::vector< std::pair<E,E> > &edgeList;
const static int OVERLAP = 50;
std::string &filename;
public:
/**
* @brief constructor for this class
* @param[in] edgeList Edgelist to build
* @param[in] comm mpi communicator
*/
template <typename vID>
GraphFileParser(std::vector< std::pair<vID, vID> > &edgeList, bool addReverseEdge,
std::string &filename, const mxx::comm &comm)
: edgeList(edgeList),
addReverseEdge(addReverseEdge),
filename(filename),
comm(comm.copy())
{
static_assert(std::is_same<E, vID>::value, "Edge vector type should match");
}
/**
* @brief populates the edge list vector
* @param[in] filename name of the file to read
*/
void populateEdgeList()
{
Timer timer;
//Value type over which Iterator is defined
typedef typename std::iterator_traits<Iterator>::value_type IteratorValueType;
//Define file loader type
typedef bliss::io::FileLoader<IteratorValueType, OVERLAP, GraphFileLoader > FileLoaderType;
FileLoaderType loader(filename, comm);
//==== now process the file, one L1 block partition per MPI Rank
typename FileLoaderType::L1BlockType partition = loader.getNextL1Block();
//Range of the file partition this MPI rank reads
auto localFileRange = partition.getRange();
//Iterator over data in the file
typename FileLoaderType::L1BlockType::iterator dataIter = partition.begin();
//Initialize the byte offset counter over the range of this rank
std::size_t i = localFileRange.start;
bool lastEdgeRead = true;
//Begin parsing the contents
//lastEdgeRead will be false when we reach the partition end boundary
while (lastEdgeRead) {
lastEdgeRead = readAnEdge(dataIter, partition.end(), i);
}
timer.end_section("File IO completed, graph built");
}
/**
* @brief reads an edge assuming iterator points to
* beginning of a valid record
* @param[in] curr current iterator position
* @return true if edge is read successfully,
* false if partition boundary is encountered
*/
template <typename Iter>
bool readAnEdge(Iter& curr, const Iter &end, std::size_t& offset)
{
//make sure we point to non EOL value
this->findNonEOL(curr, end, offset);
//string to save the contents of a line
std::string readLine;
//till we see end of line
while( ! (*curr == baseType::eol || *curr == baseType::cr))
{
//return if we are crossing the boundary
if(curr == end)
return false;
//keep pushing the character to string
readLine.append(curr, 1);
//advance iterator
curr++; offset++;
//return if we are crossing the boundary
if(curr == end)
return false;
}
parseStringForEdge(readLine);
return true;
}
/**
* @brief assumes string with two integers as input,
* parse the integers and insert to edgeList
* @param[in] record string with 2 integers separated by space
*/
inline void parseStringForEdge(std::string &record)
{
std::stringstream stream(record);
size_t n = std::count(record.begin(), record.end(), ' ');
E vertex1, vertex2;
stream >> vertex1;
stream >> vertex2;
if(n == 1)
{
edgeList.emplace_back(vertex1, vertex2);
if(addReverseEdge)
edgeList.emplace_back(vertex2, vertex1);
}
}
};
}
}
#endif
<|endoftext|>
|
<commit_before>#include "vast/query.h"
#include <cppa/cppa.hpp>
#include "vast/event.h"
#include "vast/logger.h"
namespace vast {
namespace {
struct cow_segment_less_than
{
bool operator()(cow<segment> const& x, cow<segment> const& y) const
{
return x->base() < y->base();
}
};
cow_segment_less_than segment_lt;
} // namespace <anonymous>
query::query(expr::ast ast, std::function<void(event)> fn)
: ast_{std::move(ast)},
fn_{fn}
{
processed_ = bitstream_type{};
extracted_ = bitstream_type{};
}
void query::update(bitstream result)
{
assert(result);
if (hits_)
hits_ |= result;
else
hits_ = std::move(result);
unprocessed_ = hits_ - processed_;
}
bool query::add(cow<segment> s)
{
auto i = std::lower_bound(segments_.begin(), segments_.end(), s, segment_lt);
if (! (i == segments_.end() || segment_lt(s, *i)))
return false;
segments_.emplace(i, s);
return true;
}
size_t query::consolidate(size_t before, size_t after)
{
auto i = std::lower_bound(
segments_.begin(), segments_.end(), current_, segment_lt);
assert(i != segments_.end());
size_t earlier = std::distance(segments_.begin(), i);
size_t later = std::distance(i, segments_.end()) - 1;
size_t n = 0;
if (earlier > before)
{
auto purge = earlier - before;
VAST_LOG_DEBUG("query removes " << purge << " segments before current");
segments_.erase(segments_.begin(), segments_.begin() + purge);
n = purge;
}
if (later > after)
{
auto purge = later - after;
VAST_LOG_DEBUG("query removes " << purge << " segments after current");
segments_.erase(segments_.end() - purge, segments_.end());
n += purge;
}
return n;
}
optional<size_t> query::extract()
{
if (! unprocessed_)
{
VAST_LOG_DEBUG("query has no unprocessed hits available");
return {};
}
if (! reader_ || ! current_->contains(reader_->position()))
{
auto last = unprocessed_.find_last();
if (last == bitstream::npos)
return {};
auto found = false;
for (auto i = segments_.rbegin(); i != segments_.rend(); ++i)
{
if ((**i).contains(last))
{
found = true;
current_ = *i;
break;
}
}
if (! found)
{
VAST_LOG_DEBUG("query has no segment for id " << last);
return {};
}
reader_ = make_unique<segment::reader>(¤t_.read());
VAST_LOG_DEBUG("query instantiates reader for segment " <<
current_->id() << " covering [" << current_->base() << ','
<< current_->base() + current_->events() << ')');
masked_ = bitstream_type{};
masked_.append(current_->base(), false);
masked_.append(current_->events(), true);
masked_ &= unprocessed_;
}
if (masked_.empty())
return {};
size_t n = 0;
for (auto id : masked_)
{
auto e = reader_->read(id);
if (! e)
{
VAST_LOG_ERROR("query failed to extract event " << id);
break;
}
extracted_.append(e->id() - extracted_.size(), false);
extracted_.push_back(true);
if (evaluate(ast_, *e).get<bool>())
{
fn_(std::move(*e));
++n;
}
else
{
VAST_LOG_WARN("query " << ast_ << " ignores false positive: " << *e);
}
}
if (! extracted_.empty())
{
processed_ |= extracted_;
unprocessed_ -= extracted_;
masked_ -= extracted_;
extracted_ = bitstream_type{};
}
if (n == 0)
VAST_LOG_WARN("query could not find a single result in segment " <<
current_->id());
return n;
}
std::vector<event_id> query::scan() const
{
std::vector<event_id> eids;
for (auto i = segments_.begin(); i != segments_.end(); ++i)
{
auto& s = *i;
auto prev_hit = unprocessed_.find_prev(s->base());
if (prev_hit != 0 // May occur when results get bitwise flipped.
&& prev_hit != bitstream::npos
&& ! ((i != segments_.begin() && (*(i - 1))->contains(prev_hit))))
eids.push_back(prev_hit);
auto next_hit = unprocessed_.find_next(s->base() + s->events() - 1);
if (next_hit != bitstream::npos
&& ! (i + 1 != segments_.end() && (*(i + 1))->contains(next_hit)))
eids.push_back(next_hit);
}
return eids;
}
size_t query::segments() const
{
return segments_.size();
}
optional<event_id> query::last() const
{
auto id = unprocessed_.find_last();
if (id != bitstream::npos)
return id;
return {};
}
using namespace cppa;
query_actor::query_actor(actor_ptr archive, actor_ptr sink, expr::ast ast)
: archive_{std::move(archive)},
sink_{std::move(sink)},
query_{std::move(ast), [=](event e) { send(sink_, std::move(e)); }}
{
}
void query_actor::act()
{
become(
on_arg_match >> [=](bitstream const& bs)
{
assert(bs);
cow<bitstream> cbs = *tuple_cast<bitstream>(last_dequeued());
VAST_LOG_ACTOR_DEBUG("got new result starting at " <<
(cbs->empty() ? 0 : cbs->find_first()));
query_.update(std::move(*cbs));
// TODO: figure out a strategy to avoid asking for duplicate segments.
send(self, atom("fetch"));
send(self, atom("extract"));
},
on_arg_match >> [=](event_id eid)
{
VAST_LOG_ACTOR_ERROR("could not obtain segment for event ID " << eid);
quit(exit::error);
},
on_arg_match >> [=](segment const&)
{
cow<segment> s = *tuple_cast<segment>(last_dequeued());
VAST_LOG_ACTOR_DEBUG("adds segment " << s->id());
if (! query_.add(s))
VAST_LOG_ACTOR_WARN("ignores duplicate segment " << s->id());
auto n = query_.consolidate();
if (n > 0)
VAST_LOG_ACTOR_DEBUG("purged " << n << " segments");
send(self, atom("fetch"));
send(self, atom("extract"));
},
on(atom("fetch")) >> [=]
{
if (query_.segments() == 0)
{
if (auto last = query_.last())
{
VAST_LOG_ACTOR_DEBUG("asks for segment containing id " << *last);
send(archive_, atom("segment"), *last);
}
}
else if (query_.segments() <= 3) // TODO: Make configurable.
{
for (auto eid : query_.scan())
{
send(archive_, atom("segment"), eid);
VAST_LOG_ACTOR_DEBUG(
"asks for neighboring segment containing id " << eid);
}
}
},
on(atom("extract")) >> [=]
{
VAST_LOG_ACTOR_DEBUG("asked to extract events");
if (auto got = query_.extract())
VAST_LOG_ACTOR_DEBUG("extracted " << *got << " events");
},
others() >> [=]
{
VAST_LOG_ACTOR_ERROR("got unexpected message from @" <<
last_sender()->id() << ": " <<
to_string(last_dequeued()));
});
}
char const* query_actor::description() const
{
return "query";
}
} // namespace vast
<commit_msg>Disconnect reader after full segment processing.<commit_after>#include "vast/query.h"
#include <cppa/cppa.hpp>
#include "vast/event.h"
#include "vast/logger.h"
namespace vast {
namespace {
struct cow_segment_less_than
{
bool operator()(cow<segment> const& x, cow<segment> const& y) const
{
return x->base() < y->base();
}
};
cow_segment_less_than segment_lt;
} // namespace <anonymous>
query::query(expr::ast ast, std::function<void(event)> fn)
: ast_{std::move(ast)},
fn_{fn}
{
processed_ = bitstream_type{};
extracted_ = bitstream_type{};
}
void query::update(bitstream result)
{
assert(result);
if (hits_)
hits_ |= result;
else
hits_ = std::move(result);
unprocessed_ = hits_ - processed_;
}
bool query::add(cow<segment> s)
{
auto i = std::lower_bound(segments_.begin(), segments_.end(), s, segment_lt);
if (! (i == segments_.end() || segment_lt(s, *i)))
return false;
segments_.emplace(i, s);
return true;
}
size_t query::consolidate(size_t before, size_t after)
{
auto i = std::lower_bound(
segments_.begin(), segments_.end(), current_, segment_lt);
assert(i != segments_.end());
size_t earlier = std::distance(segments_.begin(), i);
size_t later = std::distance(i, segments_.end()) - 1;
size_t n = 0;
if (earlier > before)
{
auto purge = earlier - before;
VAST_LOG_DEBUG("query removes " << purge << " segments before current");
segments_.erase(segments_.begin(), segments_.begin() + purge);
n = purge;
}
if (later > after)
{
auto purge = later - after;
VAST_LOG_DEBUG("query removes " << purge << " segments after current");
segments_.erase(segments_.end() - purge, segments_.end());
n += purge;
}
return n;
}
optional<size_t> query::extract()
{
if (! unprocessed_)
{
VAST_LOG_DEBUG("query has no unprocessed hits available");
return {};
}
if (! reader_ || ! current_->contains(reader_->position()))
{
auto last = unprocessed_.find_last();
if (last == bitstream::npos)
return {};
auto found = false;
for (auto i = segments_.rbegin(); i != segments_.rend(); ++i)
{
if ((**i).contains(last))
{
found = true;
current_ = *i;
break;
}
}
if (! found)
{
VAST_LOG_DEBUG("query has no segment for id " << last);
return {};
}
reader_ = make_unique<segment::reader>(¤t_.read());
VAST_LOG_DEBUG("query instantiates reader for segment " <<
current_->id() << " covering [" << current_->base() << ','
<< current_->base() + current_->events() << ')');
masked_ = bitstream_type{};
masked_.append(current_->base(), false);
masked_.append(current_->events(), true);
masked_ &= unprocessed_;
}
if (masked_.empty())
return {};
size_t n = 0;
for (auto id : masked_)
{
auto e = reader_->read(id);
if (! e)
{
VAST_LOG_ERROR("query failed to extract event " << id);
break;
}
extracted_.append(e->id() - extracted_.size(), false);
extracted_.push_back(true);
if (evaluate(ast_, *e).get<bool>())
{
fn_(std::move(*e));
++n;
}
else
{
VAST_LOG_WARN("query " << ast_ << " ignores false positive: " << *e);
}
}
if (! extracted_.empty())
{
processed_ |= extracted_;
unprocessed_ -= extracted_;
masked_ -= extracted_;
extracted_ = bitstream_type{};
// We've processed this segment entirely and the next call to extract
// should instantiate a new reader for a different segment.
assert(masked_.empty());
reader_.reset();
}
if (n == 0)
VAST_LOG_WARN("query could not find a single result in segment " <<
current_->id());
return n;
}
std::vector<event_id> query::scan() const
{
std::vector<event_id> eids;
for (auto i = segments_.begin(); i != segments_.end(); ++i)
{
auto& s = *i;
auto prev_hit = unprocessed_.find_prev(s->base());
if (prev_hit != 0 // May occur when results get bitwise flipped.
&& prev_hit != bitstream::npos
&& ! ((i != segments_.begin() && (*(i - 1))->contains(prev_hit))))
eids.push_back(prev_hit);
auto next_hit = unprocessed_.find_next(s->base() + s->events() - 1);
if (next_hit != bitstream::npos
&& ! (i + 1 != segments_.end() && (*(i + 1))->contains(next_hit)))
eids.push_back(next_hit);
}
return eids;
}
size_t query::segments() const
{
return segments_.size();
}
optional<event_id> query::last() const
{
auto id = unprocessed_.find_last();
if (id != bitstream::npos)
return id;
return {};
}
using namespace cppa;
query_actor::query_actor(actor_ptr archive, actor_ptr sink, expr::ast ast)
: archive_{std::move(archive)},
sink_{std::move(sink)},
query_{std::move(ast), [=](event e) { send(sink_, std::move(e)); }}
{
}
void query_actor::act()
{
become(
on_arg_match >> [=](bitstream const& bs)
{
assert(bs);
cow<bitstream> cbs = *tuple_cast<bitstream>(last_dequeued());
VAST_LOG_ACTOR_DEBUG("got new result starting at " <<
(cbs->empty() ? 0 : cbs->find_first()));
query_.update(std::move(*cbs));
// TODO: figure out a strategy to avoid asking for duplicate segments.
send(self, atom("fetch"));
send(self, atom("extract"));
},
on_arg_match >> [=](event_id eid)
{
VAST_LOG_ACTOR_ERROR("could not obtain segment for event ID " << eid);
quit(exit::error);
},
on_arg_match >> [=](segment const&)
{
cow<segment> s = *tuple_cast<segment>(last_dequeued());
VAST_LOG_ACTOR_DEBUG("adds segment " << s->id());
if (! query_.add(s))
VAST_LOG_ACTOR_WARN("ignores duplicate segment " << s->id());
auto n = query_.consolidate();
if (n > 0)
VAST_LOG_ACTOR_DEBUG("purged " << n << " segments");
send(self, atom("fetch"));
send(self, atom("extract"));
},
on(atom("fetch")) >> [=]
{
if (query_.segments() == 0)
{
if (auto last = query_.last())
{
VAST_LOG_ACTOR_DEBUG("asks for segment containing id " << *last);
send(archive_, atom("segment"), *last);
}
}
else if (query_.segments() <= 3) // TODO: Make configurable.
{
for (auto eid : query_.scan())
{
send(archive_, atom("segment"), eid);
VAST_LOG_ACTOR_DEBUG(
"asks for neighboring segment containing id " << eid);
}
}
},
on(atom("extract")) >> [=]
{
VAST_LOG_ACTOR_DEBUG("asked to extract events");
if (auto got = query_.extract())
VAST_LOG_ACTOR_DEBUG("extracted " << *got << " events");
},
others() >> [=]
{
VAST_LOG_ACTOR_ERROR("got unexpected message from @" <<
last_sender()->id() << ": " <<
to_string(last_dequeued()));
});
}
char const* query_actor::description() const
{
return "query";
}
} // namespace vast
<|endoftext|>
|
<commit_before>/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2022, The Regents of the University of California
// All rights reserved.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////
#include "globalConnectDialog.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
Q_DECLARE_METATYPE(odb::dbNet*);
Q_DECLARE_METATYPE(odb::dbRegion*);
namespace gui {
enum class GlobalConnectField
{
Instance,
Pin,
Net,
Region,
Run,
Remove
};
static int toValue(GlobalConnectField f)
{
return static_cast<int>(f);
}
/////////
GlobalConnectDialog::GlobalConnectDialog(odb::dbBlock* block, QWidget* parent)
: QDialog(parent),
block_(block),
layout_(new QGridLayout),
add_(new QPushButton(this)),
clear_(new QPushButton(this)),
run_(new QPushButton(this)),
rules_({}),
inst_pattern_(new QLineEdit(this)),
pin_pattern_(new QLineEdit(this)),
net_(new QComboBox(this)),
region_(new QComboBox(this))
{
setWindowTitle("Global Connect Rules");
QVBoxLayout* layout = new QVBoxLayout;
layout->addLayout(layout_);
QHBoxLayout* button_layout = new QHBoxLayout;
button_layout->addWidget(clear_);
button_layout->addWidget(run_);
layout->addLayout(button_layout);
setLayout(layout);
add_->setIcon(QIcon(":/add.png"));
add_->setToolTip(tr("Run"));
add_->setAutoDefault(false);
add_->setDefault(false);
run_->setIcon(QIcon(":/play.png"));
run_->setToolTip(tr("Run"));
run_->setAutoDefault(false);
run_->setDefault(false);
clear_->setIcon(QIcon(":/delete.png"));
clear_->setToolTip(tr("Clear"));
clear_->setAutoDefault(false);
clear_->setDefault(false);
connect(add_, SIGNAL(pressed()), this, SLOT(makeRule()));
connect(run_, SIGNAL(pressed()), this, SLOT(runRules()));
connect(clear_, SIGNAL(pressed()), this, SLOT(clearRules()));
layout_->addWidget(new QLabel("Instance pattern", this),
0,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
layout_->addWidget(new QLabel("Pin pattern", this),
0,
toValue(GlobalConnectField::Pin),
Qt::AlignCenter);
layout_->addWidget(new QLabel("Net", this),
0,
toValue(GlobalConnectField::Net),
Qt::AlignCenter);
layout_->addWidget(new QLabel("Region", this),
0,
toValue(GlobalConnectField::Region),
Qt::AlignCenter);
for (auto* rule : block_->getGlobalConnects()) {
addRule(rule);
}
region_->addItem("All",
QVariant::fromValue(static_cast<odb::dbRegion*>(nullptr)));
for (auto* region : block_->getRegions()) {
region_->addItem(QString::fromStdString(region->getName()),
QVariant::fromValue(static_cast<odb::dbRegion*>(region)));
}
for (auto* net : block_->getNets()) {
if (!net->isSpecial()) {
continue;
}
net_->addItem(QString::fromStdString(net->getName()),
QVariant::fromValue(static_cast<odb::dbNet*>(net)));
}
const int row_idx = rules_.size() + 1;
layout_->addWidget(inst_pattern_,
row_idx,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
layout_->addWidget(
pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);
layout_->addWidget(
net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);
layout_->addWidget(
region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);
layout_->addWidget(
add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);
}
void GlobalConnectDialog::runRules()
{
block_->globalConnect();
}
void GlobalConnectDialog::clearRules()
{
auto rule_set = block_->getGlobalConnects();
std::set<odb::dbGlobalConnect*> rules(rule_set.begin(), rule_set.end());
for (auto* rule : rules) {
deleteRule(rule);
}
}
void GlobalConnectDialog::deleteRule(odb::dbGlobalConnect* gc)
{
auto& widgets = rules_[gc];
layout_->removeWidget(widgets.inst_pattern);
layout_->removeWidget(widgets.pin_pattern);
layout_->removeWidget(widgets.net);
layout_->removeWidget(widgets.region);
layout_->removeWidget(widgets.run);
layout_->removeWidget(widgets.remove);
delete widgets.inst_pattern;
delete widgets.pin_pattern;
delete widgets.net;
delete widgets.region;
delete widgets.run;
delete widgets.remove;
rules_.erase(gc);
odb::dbGlobalConnect::destroy(gc);
adjustSize();
}
void GlobalConnectDialog::addRule(odb::dbGlobalConnect* gc)
{
const int row_idx = rules_.size() + 1;
auto& widgets = rules_[gc];
widgets.inst_pattern = new QLineEdit(this);
widgets.inst_pattern->setReadOnly(true);
widgets.inst_pattern->setText(QString::fromStdString(gc->getInstPattern()));
layout_->addWidget(widgets.inst_pattern,
row_idx,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
widgets.pin_pattern = new QLineEdit(this);
widgets.pin_pattern->setReadOnly(true);
widgets.pin_pattern->setText(QString::fromStdString(gc->getPinPattern()));
layout_->addWidget(widgets.pin_pattern,
row_idx,
toValue(GlobalConnectField::Pin),
Qt::AlignCenter);
widgets.net = new QLineEdit(this);
widgets.net->setReadOnly(true);
widgets.net->setText(QString::fromStdString(gc->getNet()->getName()));
layout_->addWidget(
widgets.net, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);
widgets.region = new QLineEdit(this);
odb::dbRegion* dbregion = gc->getRegion();
if (dbregion == nullptr) {
widgets.region->setText("All");
} else {
widgets.region->setText(QString::fromStdString(dbregion->getName()));
}
widgets.region->setReadOnly(true);
layout_->addWidget(widgets.region,
row_idx,
toValue(GlobalConnectField::Region),
Qt::AlignCenter);
widgets.run = new QPushButton(this);
widgets.run->setIcon(QIcon(":/play.png"));
widgets.run->setToolTip(tr("Run"));
widgets.run->setAutoDefault(false);
widgets.run->setDefault(false);
connect(widgets.run, &QPushButton::pressed, this, [this, gc]() {
block_->globalConnect(gc);
});
layout_->addWidget(
widgets.run, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);
widgets.remove = new QPushButton(this);
widgets.remove->setIcon(QIcon(":/delete.png"));
widgets.remove->setToolTip(tr("Delete"));
widgets.remove->setAutoDefault(false);
widgets.remove->setDefault(false);
connect(widgets.remove, &QPushButton::pressed, this, [this, gc]() {
deleteRule(gc);
});
layout_->addWidget(widgets.remove,
row_idx,
toValue(GlobalConnectField::Remove),
Qt::AlignCenter);
adjustSize();
}
void GlobalConnectDialog::makeRule()
{
const std::string inst_pattern = inst_pattern_->text().toStdString();
const std::string pin_pattern = pin_pattern_->text().toStdString();
odb::dbNet* net = net_->currentData().value<odb::dbNet*>();
odb::dbRegion* region = region_->currentData().value<odb::dbRegion*>();
try {
auto* rule
= odb::dbGlobalConnect::create(net, region, inst_pattern, pin_pattern);
addRule(rule);
} catch (const std::runtime_error&) {
}
layout_->removeWidget(inst_pattern_);
layout_->removeWidget(pin_pattern_);
layout_->removeWidget(net_);
layout_->removeWidget(region_);
layout_->removeWidget(add_);
const int row_idx = rules_.size() + 1;
layout_->addWidget(inst_pattern_,
row_idx,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
layout_->addWidget(
pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);
layout_->addWidget(
net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);
layout_->addWidget(
region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);
layout_->addWidget(
add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);
adjustSize();
}
} // namespace gui
<commit_msg>gui: make fields gray, using disabled prevents selecting and copying<commit_after>/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2022, The Regents of the University of California
// All rights reserved.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////
#include "globalConnectDialog.h"
#include <QHBoxLayout>
#include <QLabel>
#include <QVBoxLayout>
Q_DECLARE_METATYPE(odb::dbNet*);
Q_DECLARE_METATYPE(odb::dbRegion*);
namespace gui {
enum class GlobalConnectField
{
Instance,
Pin,
Net,
Region,
Run,
Remove
};
static int toValue(GlobalConnectField f)
{
return static_cast<int>(f);
}
/////////
GlobalConnectDialog::GlobalConnectDialog(odb::dbBlock* block, QWidget* parent)
: QDialog(parent),
block_(block),
layout_(new QGridLayout),
add_(new QPushButton(this)),
clear_(new QPushButton(this)),
run_(new QPushButton(this)),
rules_({}),
inst_pattern_(new QLineEdit(this)),
pin_pattern_(new QLineEdit(this)),
net_(new QComboBox(this)),
region_(new QComboBox(this))
{
setWindowTitle("Global Connect Rules");
QVBoxLayout* layout = new QVBoxLayout;
layout->addLayout(layout_);
QHBoxLayout* button_layout = new QHBoxLayout;
button_layout->addWidget(clear_);
button_layout->addWidget(run_);
layout->addLayout(button_layout);
setLayout(layout);
add_->setIcon(QIcon(":/add.png"));
add_->setToolTip(tr("Run"));
add_->setAutoDefault(false);
add_->setDefault(false);
run_->setIcon(QIcon(":/play.png"));
run_->setToolTip(tr("Run"));
run_->setAutoDefault(false);
run_->setDefault(false);
clear_->setIcon(QIcon(":/delete.png"));
clear_->setToolTip(tr("Clear"));
clear_->setAutoDefault(false);
clear_->setDefault(false);
connect(add_, SIGNAL(pressed()), this, SLOT(makeRule()));
connect(run_, SIGNAL(pressed()), this, SLOT(runRules()));
connect(clear_, SIGNAL(pressed()), this, SLOT(clearRules()));
layout_->addWidget(new QLabel("Instance pattern", this),
0,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
layout_->addWidget(new QLabel("Pin pattern", this),
0,
toValue(GlobalConnectField::Pin),
Qt::AlignCenter);
layout_->addWidget(new QLabel("Net", this),
0,
toValue(GlobalConnectField::Net),
Qt::AlignCenter);
layout_->addWidget(new QLabel("Region", this),
0,
toValue(GlobalConnectField::Region),
Qt::AlignCenter);
for (auto* rule : block_->getGlobalConnects()) {
addRule(rule);
}
region_->addItem("All",
QVariant::fromValue(static_cast<odb::dbRegion*>(nullptr)));
for (auto* region : block_->getRegions()) {
region_->addItem(QString::fromStdString(region->getName()),
QVariant::fromValue(static_cast<odb::dbRegion*>(region)));
}
for (auto* net : block_->getNets()) {
if (!net->isSpecial()) {
continue;
}
net_->addItem(QString::fromStdString(net->getName()),
QVariant::fromValue(static_cast<odb::dbNet*>(net)));
}
const int row_idx = rules_.size() + 1;
layout_->addWidget(inst_pattern_,
row_idx,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
layout_->addWidget(
pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);
layout_->addWidget(
net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);
layout_->addWidget(
region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);
layout_->addWidget(
add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);
}
void GlobalConnectDialog::runRules()
{
block_->globalConnect();
}
void GlobalConnectDialog::clearRules()
{
auto rule_set = block_->getGlobalConnects();
std::set<odb::dbGlobalConnect*> rules(rule_set.begin(), rule_set.end());
for (auto* rule : rules) {
deleteRule(rule);
}
}
void GlobalConnectDialog::deleteRule(odb::dbGlobalConnect* gc)
{
auto& widgets = rules_[gc];
layout_->removeWidget(widgets.inst_pattern);
layout_->removeWidget(widgets.pin_pattern);
layout_->removeWidget(widgets.net);
layout_->removeWidget(widgets.region);
layout_->removeWidget(widgets.run);
layout_->removeWidget(widgets.remove);
delete widgets.inst_pattern;
delete widgets.pin_pattern;
delete widgets.net;
delete widgets.region;
delete widgets.run;
delete widgets.remove;
rules_.erase(gc);
odb::dbGlobalConnect::destroy(gc);
adjustSize();
}
void GlobalConnectDialog::addRule(odb::dbGlobalConnect* gc)
{
const int row_idx = rules_.size() + 1;
auto& widgets = rules_[gc];
auto setup_line = [](QLineEdit* line) {
line->setReadOnly(true);
line->setStyleSheet("color: black; background-color: lightGray");
};
widgets.inst_pattern = new QLineEdit(this);
setup_line(widgets.inst_pattern);
widgets.inst_pattern->setText(QString::fromStdString(gc->getInstPattern()));
layout_->addWidget(widgets.inst_pattern,
row_idx,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
widgets.pin_pattern = new QLineEdit(this);
setup_line(widgets.pin_pattern);
widgets.pin_pattern->setText(QString::fromStdString(gc->getPinPattern()));
layout_->addWidget(widgets.pin_pattern,
row_idx,
toValue(GlobalConnectField::Pin),
Qt::AlignCenter);
widgets.net = new QLineEdit(this);
setup_line(widgets.net);
widgets.net->setText(QString::fromStdString(gc->getNet()->getName()));
layout_->addWidget(
widgets.net, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);
widgets.region = new QLineEdit(this);
odb::dbRegion* dbregion = gc->getRegion();
if (dbregion == nullptr) {
widgets.region->setText("All");
} else {
widgets.region->setText(QString::fromStdString(dbregion->getName()));
}
setup_line(widgets.region);
layout_->addWidget(widgets.region,
row_idx,
toValue(GlobalConnectField::Region),
Qt::AlignCenter);
widgets.run = new QPushButton(this);
widgets.run->setIcon(QIcon(":/play.png"));
widgets.run->setToolTip(tr("Run"));
widgets.run->setAutoDefault(false);
widgets.run->setDefault(false);
connect(widgets.run, &QPushButton::pressed, this, [this, gc]() {
block_->globalConnect(gc);
});
layout_->addWidget(
widgets.run, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);
widgets.remove = new QPushButton(this);
widgets.remove->setIcon(QIcon(":/delete.png"));
widgets.remove->setToolTip(tr("Delete"));
widgets.remove->setAutoDefault(false);
widgets.remove->setDefault(false);
connect(widgets.remove, &QPushButton::pressed, this, [this, gc]() {
deleteRule(gc);
});
layout_->addWidget(widgets.remove,
row_idx,
toValue(GlobalConnectField::Remove),
Qt::AlignCenter);
adjustSize();
}
void GlobalConnectDialog::makeRule()
{
const std::string inst_pattern = inst_pattern_->text().toStdString();
const std::string pin_pattern = pin_pattern_->text().toStdString();
odb::dbNet* net = net_->currentData().value<odb::dbNet*>();
odb::dbRegion* region = region_->currentData().value<odb::dbRegion*>();
try {
auto* rule
= odb::dbGlobalConnect::create(net, region, inst_pattern, pin_pattern);
addRule(rule);
} catch (const std::runtime_error&) {
}
layout_->removeWidget(inst_pattern_);
layout_->removeWidget(pin_pattern_);
layout_->removeWidget(net_);
layout_->removeWidget(region_);
layout_->removeWidget(add_);
const int row_idx = rules_.size() + 1;
layout_->addWidget(inst_pattern_,
row_idx,
toValue(GlobalConnectField::Instance),
Qt::AlignCenter);
layout_->addWidget(
pin_pattern_, row_idx, toValue(GlobalConnectField::Pin), Qt::AlignCenter);
layout_->addWidget(
net_, row_idx, toValue(GlobalConnectField::Net), Qt::AlignCenter);
layout_->addWidget(
region_, row_idx, toValue(GlobalConnectField::Region), Qt::AlignCenter);
layout_->addWidget(
add_, row_idx, toValue(GlobalConnectField::Run), Qt::AlignCenter);
adjustSize();
}
} // namespace gui
<|endoftext|>
|
<commit_before>/**
* \file RunnerAgent.cpp
* \date Apr 1, 2010
* \author samael
*/
#include <cstdio>
#include <sys/time.h>
#include <unistd.h>
#include <UDPSocket.h>
#include <TLVReaderWriter.h>
#include <Thread.h>
#include <SingletonAutoDestructor.h>
#include <HelperMacros.h>
#include "D2MCE.h"
#include "RunnerAgent.h"
#include "TLVMessage.h"
using namespace std;
using namespace cml;
namespace wfe
{
SINGLETON_REGISTRATION(RunnerAgent);
const char *RunnerAgent::StateString[] = { "Not Ready", "Ready" };
RunnerAgent *RunnerAgent::_instance = NULL;
pthread_mutex_t RunnerAgent::_mutex = PTHREAD_MUTEX_INITIALIZER;
/**
* \internal
* The internal private class used to accept connections from runners.
*/
class PrivateAcceptThread: public Thread
{
public:
PrivateAcceptThread(): _stop(false), _msock(NULL), _ssocks(NULL) {}
void setparam(TCPSocket *server, vector<TCPSocket *> *runners)
{
_msock = server;
_ssocks = runners;
}
void run()
{
_msock->setNonblock(true);
while (!_stop) {
TCPSocket *tsock;
if ((tsock = _msock->accept())) {
TLVReaderWriter tcprw(tsock);
TLVMessage *msg;
if (!(msg = dynamic_cast<TLVMessage *>(tcprw.read()))) {
PERR << "Invalid incoming message.\n";
} else if (msg->command() != TLVMessage::HELLO_SLAVE) {
PERR << "Expected command " <<
TLVMessage::CommandString[TLVMessage::HELLO_SLAVE] <<
"but got " <<
TLVMessage::CommandString[msg->command()] << ".\n";
} else {
PINFO("Got one runner.");
_ssocks->push_back(tsock);
}
delete msg;
}
usleep(tsock ? 0 : 50000);
}
}
void stop() { _stop = true; }
private:
bool _stop;
TCPSocket *_msock;
vector<TCPSocket *> *_ssocks;
};
/**
* Get the instance of the agent.
*/
RunnerAgent* RunnerAgent::instance()
{
pthread_mutex_lock(&_mutex);
if (!_instance)
_instance = new RunnerAgent();
pthread_mutex_unlock(&_mutex);
return _instance;
}
/**
* Release the instance.
*/
void RunnerAgent::release()
{
PINFO("Releasing RunnerAgent.");
pthread_mutex_lock(&_mutex);
delete _instance;
_instance = NULL;
pthread_mutex_unlock(&_mutex);
}
/**
* Setup the agent. It must be called before other agent operations.
*/
bool RunnerAgent::setup(unsigned short runner_port, unsigned short master_port,
const string &appname, unsigned int timeout)
{
if (_state != NOT_READY)
return false;
// Listen and wait for join message.
PrivateAcceptThread athread;
_msock.passiveOpen(master_port);
athread.setparam(&_msock, &_ssocks);
athread.start();
#ifdef ENABLE_D2MCE
// Join D2MCE computing group.
D2MCE::instance()->join(appname);
printf("Info: %s: %d: %d nodes inside the group, node id = %d.\n",
__PRETTY_FUNCTION__, __LINE__,
D2MCE::instance()->getNumberOfNodes(),
D2MCE::instance()->nodeId());
#endif
// Broadcast notification.
UDPSocket usock;
TLVReaderWriter udprw(&usock);
usock.setBroadcast(true);
usock.setTTL(1);
udprw.sendto(TLVMessage(TLVMessage::HELLO_MASTER),
HostAddress::BroadcastAddress, runner_port);
// Wait until timed out.
sleep(timeout);
athread.stop();
athread.join();
if (_ssocks.size() == 0) {
PERR << "No runner found.\n";
return false;
}
_state = READY;
return true;
}
/**
* Send an worker actor to runners to execute.
*
* \param[in] actor
* Actor to send.
*
* \param[in] rsock
* Socket of runner to send actor to, or NULL for all runners.
*/
bool RunnerAgent::sendActor(AbstractWorkerActor *actor, TCPSocket *rsock)
{
if (_state != READY)
return false;
TLVMessage msg;
msg.setCommand(TLVMessage::RUN_ACTOR);
msg.setParameter(actor);
// Send to given runner.
if (rsock) {
TLVReaderWriter rw(rsock);
return rw.write(msg);
}
// Send to all runners.
bool success = true;
for (int i = 0; i < (int)_ssocks.size(); i++) {
TLVReaderWriter rw(_ssocks[i]);
success &= rw.write(msg);
}
return success;
}
}
<commit_msg><commit_after>/**
* \file RunnerAgent.cpp
* \date Apr 1, 2010
* \author samael
*/
#include <cstdio>
#include <sys/time.h>
#include <unistd.h>
#include <UDPSocket.h>
#include <TLVReaderWriter.h>
#include <Thread.h>
#include <SingletonAutoDestructor.h>
#include <HelperMacros.h>
#include "D2MCE.h"
#include "RunnerAgent.h"
#include "TLVMessage.h"
using namespace std;
using namespace cml;
namespace wfe
{
SINGLETON_REGISTRATION(RunnerAgent);
const char *RunnerAgent::StateString[] = { "Not Ready", "Ready" };
RunnerAgent *RunnerAgent::_instance = NULL;
pthread_mutex_t RunnerAgent::_mutex = PTHREAD_MUTEX_INITIALIZER;
/**
* \internal
* The internal private class used to accept connections from runners.
*/
class PrivateAcceptThread: public Thread
{
public:
PrivateAcceptThread(): _stop(false), _msock(NULL), _ssocks(NULL) {}
void setparam(TCPSocket *server, vector<TCPSocket *> *runners)
{
_msock = server;
_ssocks = runners;
}
void run()
{
_msock->setNonblock(true);
while (!_stop) {
TCPSocket *tsock;
if ((tsock = _msock->accept())) {
TLVReaderWriter tcprw(tsock);
TLVMessage *msg;
if (!(msg = dynamic_cast<TLVMessage *>(tcprw.read()))) {
PERR << "Invalid incoming message.\n";
} else if (msg->command() != TLVMessage::HELLO_SLAVE) {
PERR << "Expected command " <<
TLVMessage::CommandString[TLVMessage::HELLO_SLAVE] <<
"but got " <<
TLVMessage::CommandString[msg->command()] << ".\n";
} else {
PINFO("Got one runner.");
_ssocks->push_back(tsock);
}
delete msg;
}
usleep(tsock ? 0 : 50000);
}
}
void stop() { _stop = true; }
private:
bool _stop;
TCPSocket *_msock;
vector<TCPSocket *> *_ssocks;
};
/**
* Get the instance of the agent.
*/
RunnerAgent* RunnerAgent::instance()
{
pthread_mutex_lock(&_mutex);
if (!_instance)
_instance = new RunnerAgent();
pthread_mutex_unlock(&_mutex);
return _instance;
}
/**
* Release the instance.
*/
void RunnerAgent::release()
{
PINFO("Releasing RunnerAgent.");
pthread_mutex_lock(&_mutex);
delete _instance;
_instance = NULL;
pthread_mutex_unlock(&_mutex);
}
/**
* Setup the agent. It must be called before other agent operations.
*/
bool RunnerAgent::setup(unsigned short runner_port, unsigned short master_port,
const string &appname, unsigned int timeout)
{
if (_state != NOT_READY)
return false;
// Listen and wait for join message.
PrivateAcceptThread athread;
_msock.passiveOpen(master_port);
athread.setparam(&_msock, &_ssocks);
athread.start();
#ifdef ENABLE_D2MCE
// Join D2MCE computing group.
D2MCE::instance()->join(appname);
// printf("Info: %s: %d: %d nodes inside the group, node id = %d.\n",
// __PRETTY_FUNCTION__, __LINE__,
// D2MCE::instance()->getNumberOfNodes(),
// D2MCE::instance()->nodeId());
#endif
// Broadcast notification.
UDPSocket usock;
TLVReaderWriter udprw(&usock);
usock.setBroadcast(true);
usock.setTTL(1);
udprw.sendto(TLVMessage(TLVMessage::HELLO_MASTER),
HostAddress::BroadcastAddress, runner_port);
// Wait until timed out.
sleep(timeout);
athread.stop();
athread.join();
if (_ssocks.size() == 0) {
PERR << "No runner found.\n";
return false;
}
_state = READY;
return true;
}
/**
* Send an worker actor to runners to execute.
*
* \param[in] actor
* Actor to send.
*
* \param[in] rsock
* Socket of runner to send actor to, or NULL for all runners.
*/
bool RunnerAgent::sendActor(AbstractWorkerActor *actor, TCPSocket *rsock)
{
if (_state != READY)
return false;
TLVMessage msg;
msg.setCommand(TLVMessage::RUN_ACTOR);
msg.setParameter(actor);
// Send to given runner.
if (rsock) {
TLVReaderWriter rw(rsock);
return rw.write(msg);
}
// Send to all runners.
bool success = true;
for (int i = 0; i < (int)_ssocks.size(); i++) {
TLVReaderWriter rw(_ssocks[i]);
success &= rw.write(msg);
}
return success;
}
}
<|endoftext|>
|
<commit_before>#include "Action.h"
#include <Exd/ExdDataGenerated.h>
#include <Util/Util.h>
#include "Framework.h"
#include "Script/ScriptMgr.h"
#include "Actor/Player.h"
#include <Network/CommonActorControl.h>
#include "Network/PacketWrappers/ActorControlPacket142.h"
#include "Network/PacketWrappers/ActorControlPacket143.h"
#include "Network/PacketWrappers/ActorControlPacket144.h"
using namespace Sapphire::Common;
using namespace Sapphire::Network;
using namespace Sapphire::Network::Packets;
using namespace Sapphire::Network::Packets::Server;
using namespace Sapphire::Network::ActorControl;
Sapphire::Action::Action::Action() = default;
Sapphire::Action::Action::~Action() = default;
Sapphire::Action::Action::Action( Entity::CharaPtr caster, uint32_t actionId,
Data::ActionPtr action, FrameworkPtr fw ) :
m_pSource( std::move( caster ) ),
m_pFw( std::move( fw ) ),
m_id( actionId ),
m_startTime( 0 ),
m_interruptType( ActionInterruptType::None )
{
m_castTime = static_cast< uint32_t >( action->cast100ms * 100 );
m_cooldownTime = static_cast< uint16_t >( action->recast100ms * 100 );
m_cooldownGroup = action->cooldownGroup;
m_actionCost.fill( { Common::ActionCostType::None, 0 } );
m_actionCost[ 0 ] = {
static_cast< Common::ActionCostType >( action->costType ),
action->cost
};
calculateActionCost();
}
uint32_t Sapphire::Action::Action::getId() const
{
return m_id;
}
void Sapphire::Action::Action::setPos( Sapphire::Common::FFXIVARR_POSITION3 pos )
{
m_pos = pos;
}
Sapphire::Common::FFXIVARR_POSITION3 Sapphire::Action::Action::getPos() const
{
return m_pos;
}
void Sapphire::Action::Action::setTargetChara( Sapphire::Entity::CharaPtr chara )
{
assert( chara );
m_pTarget = chara;
m_targetId = chara->getId();
}
Sapphire::Entity::CharaPtr Sapphire::Action::Action::getTargetChara() const
{
return m_pTarget;
}
bool Sapphire::Action::Action::isInterrupted() const
{
return m_interruptType != ActionInterruptType::None;
}
void Sapphire::Action::Action::setInterrupted( ActionInterruptType type )
{
m_interruptType = type;
}
void Sapphire::Action::Action::start()
{
m_startTime = Util::getTimeMs();
onStart();
}
uint32_t Sapphire::Action::Action::getCastTime() const
{
return m_castTime;
}
void Sapphire::Action::Action::setCastTime( uint32_t castTime )
{
m_castTime = castTime;
}
bool Sapphire::Action::Action::isCastedAction() const
{
return m_castTime > 0;
}
Sapphire::Entity::CharaPtr Sapphire::Action::Action::getActionSource() const
{
return m_pSource;
}
bool Sapphire::Action::Action::update()
{
// action has not been started yet
if( m_startTime == 0 )
return false;
if( isInterrupted() )
{
onInterrupt();
return true;
}
uint64_t currTime = Util::getTimeMs();
if( !isCastedAction() || std::difftime( currTime, m_startTime ) > m_castTime )
{
onFinish();
return true;
}
return false;
}
void Sapphire::Action::Action::onStart()
{
assert( m_pSource );
if( isCastedAction() )
{
m_pSource->getAsPlayer()->sendDebug( "onStart()" );
auto castPacket = makeZonePacket< Server::FFXIVIpcActorCast >( getId() );
castPacket->data().action_id = m_id;
castPacket->data().skillType = Common::SkillType::Normal;
castPacket->data().unknown_1 = m_id;
// This is used for the cast bar above the target bar of the caster.
castPacket->data().cast_time = m_castTime / 1000.f;
castPacket->data().target_id = m_targetId;
m_pSource->sendToInRangeSet( castPacket, true );
m_pSource->getAsPlayer()->setStateFlag( PlayerStateFlag::Casting );
}
}
void Sapphire::Action::Action::onInterrupt()
{
assert( m_pSource );
// things that aren't players don't care about cooldowns and state flags
if( m_pSource->isPlayer() )
{
auto player = m_pSource->getAsPlayer();
auto resetCooldownPkt = makeActorControl143( m_pSource->getId(), ActorControlType::SetActionCooldown, 1, getId(), 0 );
player->queuePacket( resetCooldownPkt );
// todo: reset cooldown for actual player
// reset state flag
// player->unsetStateFlag( PlayerStateFlag::Occupied1 );
player->unsetStateFlag( PlayerStateFlag::Casting );
}
if( isCastedAction() )
{
uint8_t interruptEffect = 0;
if( m_interruptType == ActionInterruptType::DamageInterrupt )
interruptEffect = 1;
// Note: When cast interrupt from taking too much damage, set the last value to 1.
// This enables the cast interrupt effect.
auto control = makeActorControl142( m_pSource->getId(), ActorControlType::CastInterrupt,
0x219, 1, m_id, interruptEffect );
m_pSource->sendToInRangeSet( control, true );
}
}
void Sapphire::Action::Action::onFinish()
{
assert( m_pSource );
auto pScriptMgr = m_pFw->get< Scripting::ScriptMgr >();
auto pPlayer = m_pSource->getAsPlayer();
pPlayer->sendDebug( "onFinish()" );
if( isCastedAction() )
{
pPlayer->unsetStateFlag( PlayerStateFlag::Casting );
/*auto control = ActorControlPacket143( m_pTarget->getId(), ActorControlType::Unk7,
0x219, m_id, m_id, m_id, m_id );
m_pSource->sendToInRangeSet( control, true );*/
pScriptMgr->onCastFinish( *pPlayer, m_pTarget, m_id );
}
}
void Sapphire::Action::Action::buildEffectPacket()
{
for( int i = 0; i < EffectPacketIdentity::MAX_ACTION_EFFECT_PACKET_IDENT; ++i )
{
auto& packetData = m_effects[ static_cast< EffectPacketIdentity >( i ) ];
// todo: this
}
}
void Sapphire::Action::Action::damageTarget( uint32_t amount, Entity::Chara& chara,
Common::ActionAspect aspect )
{
Common::EffectEntry entry{};
// todo: handle cases where the action misses/is blocked?
entry.effectType = Common::ActionEffectType::Damage;
// todo: handle crits
entry.hitSeverity = Common::ActionHitSeverityType::NormalDamage;
// todo: handle > 65535 damage values, not sure if this is right?
if( amount > 65535 )
{
entry.value = static_cast< int16_t >( amount / 10 );
// todo: rename this? need to confirm how it works again
entry.bonusPercent = 1;
}
else
entry.value = static_cast< int16_t >( amount );
// todo: aspected damage?
chara.takeDamage( amount );
m_effects[ EffectPacketIdentity::DamageEffect ].m_entries.emplace_back( entry );
// todo: make sure that we don't add the same actor more than once
m_effects[ EffectPacketIdentity::DamageEffect ].m_hitActors.emplace_back( chara.getId() );
}
void Sapphire::Action::Action::healTarget( uint32_t amount, Entity::Chara& chara )
{
Common::EffectEntry entry{};
entry.effectType = Common::ActionEffectType::Heal;
// todo: handle crits
entry.hitSeverity = Common::ActionHitSeverityType::NormalHeal;
// todo: handle > 65535 healing values, not sure if this is right?
if( amount > 65535 )
{
entry.value = static_cast< int16_t >( amount / 10 );
// todo: rename this? need to confirm how it works again
entry.bonusPercent = 1;
}
else
entry.value = static_cast< int16_t >( amount );
chara.heal( amount );
m_effects[ EffectPacketIdentity::HealingEffect ].m_entries.emplace_back( entry );
// todo: make sure that we don't add the same actor more than once
m_effects[ EffectPacketIdentity::HealingEffect ].m_hitActors.emplace_back( chara.getId() );
}
const Sapphire::Action::Action::ActionCostArray& Sapphire::Action::Action::getCostArray() const
{
return m_actionCost;
}
void Sapphire::Action::Action::calculateActionCost()
{
for( uint8_t i = 0; i < m_actionCost.size(); ++i )
{
auto& entry = m_actionCost[ i ];
if( entry.m_costType == ActionCostType::MagicPoints )
calculateMPCost( i );
}
}
void Sapphire::Action::Action::calculateMPCost( uint8_t costArrayIndex )
{
auto level = m_pSource->getLevel();
// each level range is 1-10, 11-20, 21-30, ... therefore:
// level 50 should be in the 4th group, not the 5th
// dividing by 10 on the border will break this unless we subtract 1
auto levelGroup = std::max< uint8_t >( level - 1, 1 ) / 10;
auto& costEntry = m_actionCost[ costArrayIndex ];
float cost = costEntry.m_cost;
// thanks to andrew for helping me figure this shit out, should be pretty accurate
switch( levelGroup )
{
// level 1-10
case 0:
{
// r^2 = 0.9999
cost = 0.0952f * level + 0.9467f;
break;
}
// level 11-20
case 1:
{
// r^2 = 1
cost = 0.19f * level;
break;
}
// level 21-30
case 2:
{
// r^2 = 1
cost = 0.38f * level - 3.8f;
break;
}
// level 31-40
case 3:
{
// r^2 = 1
cost = 0.6652f * level - 12.358f;
break;
}
// level 41-50
case 4:
{
// r^2 = 1
cost = 1.2352f * level - 35.159f;
break;
}
// level 51-60
case 5:
{
// r^2 = 1
cost = 0.0654f * std::exp( 0.1201f * level );
break;
}
// level 61-70
case 6:
{
// r^2 = 0.9998
cost = 0.2313f * ( level * level ) - 26.98f * level + 875.21f;
break;
}
default:
return;
}
// m_cost is the base cost, cost is the multiplier for the current player level
costEntry.m_cost = static_cast< uint16_t >( std::round( cost * costEntry.m_cost ) );
}<commit_msg>minor cleanup in regards to how we handle players who cast actions<commit_after>#include "Action.h"
#include <Exd/ExdDataGenerated.h>
#include <Util/Util.h>
#include "Framework.h"
#include "Script/ScriptMgr.h"
#include "Actor/Player.h"
#include <Network/CommonActorControl.h>
#include "Network/PacketWrappers/ActorControlPacket142.h"
#include "Network/PacketWrappers/ActorControlPacket143.h"
#include "Network/PacketWrappers/ActorControlPacket144.h"
using namespace Sapphire::Common;
using namespace Sapphire::Network;
using namespace Sapphire::Network::Packets;
using namespace Sapphire::Network::Packets::Server;
using namespace Sapphire::Network::ActorControl;
Sapphire::Action::Action::Action() = default;
Sapphire::Action::Action::~Action() = default;
Sapphire::Action::Action::Action( Entity::CharaPtr caster, uint32_t actionId,
Data::ActionPtr action, FrameworkPtr fw ) :
m_pSource( std::move( caster ) ),
m_pFw( std::move( fw ) ),
m_id( actionId ),
m_startTime( 0 ),
m_interruptType( ActionInterruptType::None )
{
m_castTime = static_cast< uint32_t >( action->cast100ms * 100 );
m_cooldownTime = static_cast< uint16_t >( action->recast100ms * 100 );
m_cooldownGroup = action->cooldownGroup;
m_actionCost.fill( { Common::ActionCostType::None, 0 } );
m_actionCost[ 0 ] = {
static_cast< Common::ActionCostType >( action->costType ),
action->cost
};
calculateActionCost();
}
uint32_t Sapphire::Action::Action::getId() const
{
return m_id;
}
void Sapphire::Action::Action::setPos( Sapphire::Common::FFXIVARR_POSITION3 pos )
{
m_pos = pos;
}
Sapphire::Common::FFXIVARR_POSITION3 Sapphire::Action::Action::getPos() const
{
return m_pos;
}
void Sapphire::Action::Action::setTargetChara( Sapphire::Entity::CharaPtr chara )
{
assert( chara );
m_pTarget = chara;
m_targetId = chara->getId();
}
Sapphire::Entity::CharaPtr Sapphire::Action::Action::getTargetChara() const
{
return m_pTarget;
}
bool Sapphire::Action::Action::isInterrupted() const
{
return m_interruptType != ActionInterruptType::None;
}
void Sapphire::Action::Action::setInterrupted( ActionInterruptType type )
{
m_interruptType = type;
}
void Sapphire::Action::Action::start()
{
m_startTime = Util::getTimeMs();
onStart();
}
uint32_t Sapphire::Action::Action::getCastTime() const
{
return m_castTime;
}
void Sapphire::Action::Action::setCastTime( uint32_t castTime )
{
m_castTime = castTime;
}
bool Sapphire::Action::Action::isCastedAction() const
{
return m_castTime > 0;
}
Sapphire::Entity::CharaPtr Sapphire::Action::Action::getActionSource() const
{
return m_pSource;
}
bool Sapphire::Action::Action::update()
{
// action has not been started yet
if( m_startTime == 0 )
return false;
if( isInterrupted() )
{
onInterrupt();
return true;
}
uint64_t currTime = Util::getTimeMs();
if( !isCastedAction() || std::difftime( currTime, m_startTime ) > m_castTime )
{
onFinish();
return true;
}
return false;
}
void Sapphire::Action::Action::onStart()
{
assert( m_pSource );
if( isCastedAction() )
{
auto castPacket = makeZonePacket< Server::FFXIVIpcActorCast >( getId() );
castPacket->data().action_id = static_cast< uint16_t >( m_id );
castPacket->data().skillType = Common::SkillType::Normal;
castPacket->data().unknown_1 = m_id;
// This is used for the cast bar above the target bar of the caster.
castPacket->data().cast_time = m_castTime / 1000.f;
castPacket->data().target_id = static_cast< uint32_t >( m_targetId );
m_pSource->sendToInRangeSet( castPacket, true );
if( auto player = m_pSource->getAsPlayer() )
{
player->setStateFlag( PlayerStateFlag::Casting );
player->sendDebug( "onStart()" );
}
}
}
void Sapphire::Action::Action::onInterrupt()
{
assert( m_pSource );
// things that aren't players don't care about cooldowns and state flags
if( m_pSource->isPlayer() )
{
auto player = m_pSource->getAsPlayer();
auto resetCooldownPkt = makeActorControl143( m_pSource->getId(), ActorControlType::SetActionCooldown, 1, getId(), 0 );
player->queuePacket( resetCooldownPkt );
// todo: reset cooldown for actual player
// reset state flag
//player->unsetStateFlag( PlayerStateFlag::Occupied1 );
player->unsetStateFlag( PlayerStateFlag::Casting );
player->sendDebug( "onInterrupt()" );
}
if( isCastedAction() )
{
uint8_t interruptEffect = 0;
if( m_interruptType == ActionInterruptType::DamageInterrupt )
interruptEffect = 1;
// Note: When cast interrupt from taking too much damage, set the last value to 1.
// This enables the cast interrupt effect.
auto control = makeActorControl142( m_pSource->getId(), ActorControlType::CastInterrupt,
0x219, 1, m_id, interruptEffect );
m_pSource->sendToInRangeSet( control, true );
}
}
void Sapphire::Action::Action::onFinish()
{
assert( m_pSource );
auto pScriptMgr = m_pFw->get< Scripting::ScriptMgr >();
auto pPlayer = m_pSource->getAsPlayer();
pPlayer->sendDebug( "onFinish()" );
if( isCastedAction() )
{
/*auto control = ActorControlPacket143( m_pTarget->getId(), ActorControlType::Unk7,
0x219, m_id, m_id, m_id, m_id );
m_pSource->sendToInRangeSet( control, true );*/
pScriptMgr->onCastFinish( *pPlayer, m_pTarget, m_id );
}
}
void Sapphire::Action::Action::buildEffectPacket()
{
for( int i = 0; i < EffectPacketIdentity::MAX_ACTION_EFFECT_PACKET_IDENT; ++i )
{
auto& packetData = m_effects[ static_cast< EffectPacketIdentity >( i ) ];
// todo: this
}
}
void Sapphire::Action::Action::damageTarget( uint32_t amount, Entity::Chara& chara,
Common::ActionAspect aspect )
{
Common::EffectEntry entry{};
// todo: handle cases where the action misses/is blocked?
entry.effectType = Common::ActionEffectType::Damage;
// todo: handle crits
entry.hitSeverity = Common::ActionHitSeverityType::NormalDamage;
// todo: handle > 65535 damage values, not sure if this is right?
if( amount > 65535 )
{
entry.value = static_cast< int16_t >( amount / 10 );
// todo: rename this? need to confirm how it works again
entry.bonusPercent = 1;
}
else
entry.value = static_cast< int16_t >( amount );
// todo: aspected damage?
chara.takeDamage( amount );
m_effects[ EffectPacketIdentity::DamageEffect ].m_entries.emplace_back( entry );
// todo: make sure that we don't add the same actor more than once
m_effects[ EffectPacketIdentity::DamageEffect ].m_hitActors.emplace_back( chara.getId() );
}
void Sapphire::Action::Action::healTarget( uint32_t amount, Entity::Chara& chara )
{
Common::EffectEntry entry{};
entry.effectType = Common::ActionEffectType::Heal;
// todo: handle crits
entry.hitSeverity = Common::ActionHitSeverityType::NormalHeal;
// todo: handle > 65535 healing values, not sure if this is right?
if( amount > 65535 )
{
entry.value = static_cast< int16_t >( amount / 10 );
// todo: rename this? need to confirm how it works again
entry.bonusPercent = 1;
}
else
entry.value = static_cast< int16_t >( amount );
chara.heal( amount );
m_effects[ EffectPacketIdentity::HealingEffect ].m_entries.emplace_back( entry );
// todo: make sure that we don't add the same actor more than once
m_effects[ EffectPacketIdentity::HealingEffect ].m_hitActors.emplace_back( chara.getId() );
}
const Sapphire::Action::Action::ActionCostArray& Sapphire::Action::Action::getCostArray() const
{
return m_actionCost;
}
void Sapphire::Action::Action::calculateActionCost()
{
for( uint8_t i = 0; i < m_actionCost.size(); ++i )
{
auto& entry = m_actionCost[ i ];
if( entry.m_costType == ActionCostType::MagicPoints )
calculateMPCost( i );
}
}
void Sapphire::Action::Action::calculateMPCost( uint8_t costArrayIndex )
{
auto level = m_pSource->getLevel();
// each level range is 1-10, 11-20, 21-30, ... therefore:
// level 50 should be in the 4th group, not the 5th
// dividing by 10 on the border will break this unless we subtract 1
auto levelGroup = std::max< uint8_t >( level - 1, 1 ) / 10;
auto& costEntry = m_actionCost[ costArrayIndex ];
float cost = costEntry.m_cost;
// thanks to andrew for helping me figure this shit out, should be pretty accurate
switch( levelGroup )
{
// level 1-10
case 0:
{
// r^2 = 0.9999
cost = 0.0952f * level + 0.9467f;
break;
}
// level 11-20
case 1:
{
// r^2 = 1
cost = 0.19f * level;
break;
}
// level 21-30
case 2:
{
// r^2 = 1
cost = 0.38f * level - 3.8f;
break;
}
// level 31-40
case 3:
{
// r^2 = 1
cost = 0.6652f * level - 12.358f;
break;
}
// level 41-50
case 4:
{
// r^2 = 1
cost = 1.2352f * level - 35.159f;
break;
}
// level 51-60
case 5:
{
// r^2 = 1
cost = 0.0654f * std::exp( 0.1201f * level );
break;
}
// level 61-70
case 6:
{
// r^2 = 0.9998
cost = 0.2313f * ( level * level ) - 26.98f * level + 875.21f;
break;
}
default:
return;
}
// m_cost is the base cost, cost is the multiplier for the current player level
costEntry.m_cost = static_cast< uint16_t >( std::round( cost * costEntry.m_cost ) );
}<|endoftext|>
|
<commit_before>/** @file driverif.H
* @brief Provides the device driver interfaces for performing device access
* and enabling routing registration.
*
* @note These interfaces should only be used by device drivers. User code
* wanting to perform device operations should use userif.H instead.
*/
#ifndef __DEVICEFW_DRIVERIF
#define __DEVICEFW_DRIVERIF
#include <devicefw/userif.H>
#include <stdarg.h>
#include <builtins.h>
#include <targeting/targetservice.H>
namespace DeviceFW
{
/** @enum AccessType_DriverOnly
* @brief Access types to be used internally by drivers for routing
* requests to other drivers.
*/
enum AccessType_DriverOnly
{
XSCOM = LAST_ACCESS_TYPE,
FSISCOM,
I2C,
LAST_DRIVER_ACCESS_TYPE
};
/** @enum OperationType
* @brief Set of operations which can be registered for.
*/
enum OperationType
{
READ = 0,
WRITE,
LAST_OP_TYPE
};
/** @enum DriverSpecial
* @brief Special Wildcard enum that can be used for drivers to do
* routing registrations.
*/
enum DriverSpecial
{
WILDCARD = -1,
};
/** Construct the device addressing parameters for XSCOM device ops.
* @param[in] i_address - XSCom address to operate on.
*/
#define DEVICE_XSCOM_ADDRESS(i_address) \
DeviceFW::XSCOM, static_cast<uint64_t>((i_address))
/**
* Construct the device addressing parameters for the I2C device ops.
*/
#define DEVICE_I2C_ADDRESS( i_address )\
DeviceFW::I2C, static_cast<uint64_t>(( i_address ))
/** @class InvalidParameterType
* @brief Unused type to cause compiler fails for invalid template types.
*
* Forward Declaration of type that is never actually used anywhere.
*
* Assists in making more developer friendly compiler fails when a
* template function is called for which there is no specialization and
* the default template function should never be used. This is used for
* allowing function calls that take multiple enum types but still provide
* type-safety above a int-parameter.
*/
class InvalidParameterType;
/** @typedef deviceOp_t
* @brief Function prototype for registered device-driver operations.
*/
typedef errlHndl_t(*deviceOp_t)(OperationType,
TARGETING::Target*,
void*, size_t&,
int64_t, va_list);
/**
* @brief Register a device driver routing function with the framework.
*
* @param[in] i_opType - Enumeration specifying the operation this
* driver performs. (Read, Write, Wildcard)
* @param[in] i_accessType - Enumeration specifying the access type this
* driver performs. (SCOM, XSCOM, PNOR, etc.)
* @param[in] i_targetType - Enumeration specifying the target type this
* driver performs. (Proc, MC, Wildcard, etc.)
* @param[in] i_regRoute - The function being registered.
*
* This function call be called to register a device driver routing
* function with the framework. If it is desired to always register a
* device driver when the module associated with that driver is loaded,
* the DEVICE_REGISTER_ROUTE macro can be used.
*
* <PRE>
* Example usage:
* // High-level address manipulation routing function.
* deviceRegisterRoute(WILDCARD,
* SCOM,
* TYPE_CORE,
* &scomAdjustCoreAddresses);
*
* // Low-level (internal) XSCOM read operation.
* deviceRegisterRoute(READ,
* XSCOM,
* TYPE_PROC,
* &xscomPerformRead);
* </PRE>
*
* @note Valid OpType are OperatorType enum or WILDCARD.
* @note Valid TargType are TargetType enum or WILDCARD.
* @note Valid AccType are AccessType or AccessType_DriverOnly; WILDCARD is
* not permitted.
*
* @note Any unsupported enumeration type will result in a compile error
* referencing a InvalidParameterType class.
*/
template <typename OpType, typename AccType, typename TargType>
void deviceRegisterRoute(OpType i_opType,
AccType i_accessType,
TargType i_targetType,
deviceOp_t i_regRoute)
{
return InvalidParameterType(); // Cause a compile fail if not one of
// the explicit template specializations.
}
/** Assistance macro for stringification. */
#define __DEVICE_REGISTER_ROUTE_XY(X,Y) X##Y
/** Assistance macro for stringification. */
#define __DEVICE_REGISTER_ROUTE_MAKENAME(X,Y) __DEVICE_REGISTER_ROUTE_XY(X,Y)
/**
* @brief Create a static constructed registration of a device driver
* function when a module is loaded.
*
* Parameters are the same as DeviceFW::deviceRegisterRoute, except the
* route function should be passed by name as opposed to pointer.
*
* If the route function is in a namespace, then this definition must
* also be placed into that namespace.
*/
#define DEVICE_REGISTER_ROUTE(i_opType, i_accessType, \
i_targetType, i_regRoute) \
class __DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_, \
i_regRoute) \
{ \
public: \
__DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_, \
i_regRoute)() \
{ \
DeviceFW::deviceRegisterRoute(i_opType, i_accessType, \
i_targetType, &i_regRoute); \
} \
}; \
__DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_, i_regRoute) \
__DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_instance_, \
i_regRoute);
/**
* @brief Perform a device operation by routing through the framework and
* calling the appropriate registered operation.
*
* @param[in] i_opType - Operation request (READ vs WRITE).
* @param[in] i_target - Target to perform operation on.
* @param[in,out] io_buffer - Data buffer for operation.
* @param[in,out] io_buflen - Length of buffer / result size.
* @param[in] i_accessType - Type of hardware access method to perform.
*
* This function has similar behavior as the user-visible deviceRead and
* deviceWrite functions and is meant as a method for device drivers to
* perform accesses which may be only visible to internal drivers.
*/
template <typename AccType>
errlHndl_t deviceOp(OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer, size_t& io_buflen,
AccType i_accessType, ...)
{
return InvalidParameterType(); // Cause a compile fail if not one of
// the explicit template specializations.
}
// --- Below are template specializations to aid in type-safety. ---
// deviceRegisterRoute:
// OpType - OperationType or WILDCARD
// TargType - TargetType or WILDCARD
// AccType - AccessType, AccessType_DriverOnly (no WILDCARD).
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType_DriverOnly i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType_DriverOnly i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType_DriverOnly i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType_DriverOnly i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
// deviceOp:
// OpType - OperationType only.
// TargType - TargetType only.
// AccType - AccessType, AccessType_DriverOnly (no WILDCARD).
template <>
errlHndl_t deviceOp<>(OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer, size_t& io_buflen,
AccessType i_accessType, ...);
template <>
errlHndl_t deviceOp<>(OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer, size_t& io_buflen,
AccessType_DriverOnly i_accessType, ...);
};
#endif
<commit_msg>Allow multiple driver registrations of the same function.<commit_after>/** @file driverif.H
* @brief Provides the device driver interfaces for performing device access
* and enabling routing registration.
*
* @note These interfaces should only be used by device drivers. User code
* wanting to perform device operations should use userif.H instead.
*/
#ifndef __DEVICEFW_DRIVERIF
#define __DEVICEFW_DRIVERIF
#include <devicefw/userif.H>
#include <stdarg.h>
#include <builtins.h>
#include <targeting/targetservice.H>
namespace DeviceFW
{
/** @enum AccessType_DriverOnly
* @brief Access types to be used internally by drivers for routing
* requests to other drivers.
*/
enum AccessType_DriverOnly
{
XSCOM = LAST_ACCESS_TYPE,
FSISCOM,
I2C,
LAST_DRIVER_ACCESS_TYPE
};
/** @enum OperationType
* @brief Set of operations which can be registered for.
*/
enum OperationType
{
READ = 0,
WRITE,
LAST_OP_TYPE
};
/** @enum DriverSpecial
* @brief Special Wildcard enum that can be used for drivers to do
* routing registrations.
*/
enum DriverSpecial
{
WILDCARD = -1,
};
/** Construct the device addressing parameters for XSCOM device ops.
* @param[in] i_address - XSCom address to operate on.
*/
#define DEVICE_XSCOM_ADDRESS(i_address) \
DeviceFW::XSCOM, static_cast<uint64_t>((i_address))
/**
* Construct the device addressing parameters for the I2C device ops.
*/
#define DEVICE_I2C_ADDRESS( i_address )\
DeviceFW::I2C, static_cast<uint64_t>(( i_address ))
/** @class InvalidParameterType
* @brief Unused type to cause compiler fails for invalid template types.
*
* Forward Declaration of type that is never actually used anywhere.
*
* Assists in making more developer friendly compiler fails when a
* template function is called for which there is no specialization and
* the default template function should never be used. This is used for
* allowing function calls that take multiple enum types but still provide
* type-safety above a int-parameter.
*/
class InvalidParameterType;
/** @typedef deviceOp_t
* @brief Function prototype for registered device-driver operations.
*/
typedef errlHndl_t(*deviceOp_t)(OperationType,
TARGETING::Target*,
void*, size_t&,
int64_t, va_list);
/**
* @brief Register a device driver routing function with the framework.
*
* @param[in] i_opType - Enumeration specifying the operation this
* driver performs. (Read, Write, Wildcard)
* @param[in] i_accessType - Enumeration specifying the access type this
* driver performs. (SCOM, XSCOM, PNOR, etc.)
* @param[in] i_targetType - Enumeration specifying the target type this
* driver performs. (Proc, MC, Wildcard, etc.)
* @param[in] i_regRoute - The function being registered.
*
* This function call be called to register a device driver routing
* function with the framework. If it is desired to always register a
* device driver when the module associated with that driver is loaded,
* the DEVICE_REGISTER_ROUTE macro can be used.
*
* <PRE>
* Example usage:
* // High-level address manipulation routing function.
* deviceRegisterRoute(WILDCARD,
* SCOM,
* TYPE_CORE,
* &scomAdjustCoreAddresses);
*
* // Low-level (internal) XSCOM read operation.
* deviceRegisterRoute(READ,
* XSCOM,
* TYPE_PROC,
* &xscomPerformRead);
* </PRE>
*
* @note Valid OpType are OperatorType enum or WILDCARD.
* @note Valid TargType are TargetType enum or WILDCARD.
* @note Valid AccType are AccessType or AccessType_DriverOnly; WILDCARD is
* not permitted.
*
* @note Any unsupported enumeration type will result in a compile error
* referencing a InvalidParameterType class.
*/
template <typename OpType, typename AccType, typename TargType>
void deviceRegisterRoute(OpType i_opType,
AccType i_accessType,
TargType i_targetType,
deviceOp_t i_regRoute)
{
return InvalidParameterType(); // Cause a compile fail if not one of
// the explicit template specializations.
}
/** Assistance macro for stringification. */
#define __DEVICE_REGISTER_ROUTE_XYZ(X,Y,Z) X##Y##Z
/** Assistance macro for stringification. */
#define __DEVICE_REGISTER_ROUTE_MAKENAME(X,Y,Z) \
__DEVICE_REGISTER_ROUTE_XYZ(X,Y,Z)
/**
* @brief Create a static constructed registration of a device driver
* function when a module is loaded.
*
* Parameters are the same as DeviceFW::deviceRegisterRoute, except the
* route function should be passed by name as opposed to pointer.
*
* If the route function is in a namespace, then this definition must
* also be placed into that namespace.
*/
#define DEVICE_REGISTER_ROUTE(i_opType, i_accessType, \
i_targetType, i_regRoute) \
class __DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_, \
i_regRoute, __LINE__) \
{ \
public: \
__DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_, \
i_regRoute, __LINE__)() \
{ \
DeviceFW::deviceRegisterRoute(i_opType, i_accessType, \
i_targetType, &i_regRoute); \
} \
}; \
__DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_, \
i_regRoute, __LINE__) \
__DEVICE_REGISTER_ROUTE_MAKENAME(DeviceRouteRegistrator_instance_, \
i_regRoute, __LINE__);
/**
* @brief Perform a device operation by routing through the framework and
* calling the appropriate registered operation.
*
* @param[in] i_opType - Operation request (READ vs WRITE).
* @param[in] i_target - Target to perform operation on.
* @param[in,out] io_buffer - Data buffer for operation.
* @param[in,out] io_buflen - Length of buffer / result size.
* @param[in] i_accessType - Type of hardware access method to perform.
*
* This function has similar behavior as the user-visible deviceRead and
* deviceWrite functions and is meant as a method for device drivers to
* perform accesses which may be only visible to internal drivers.
*/
template <typename AccType>
errlHndl_t deviceOp(OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer, size_t& io_buflen,
AccType i_accessType, ...)
{
return InvalidParameterType(); // Cause a compile fail if not one of
// the explicit template specializations.
}
// --- Below are template specializations to aid in type-safety. ---
// deviceRegisterRoute:
// OpType - OperationType or WILDCARD
// TargType - TargetType or WILDCARD
// AccType - AccessType, AccessType_DriverOnly (no WILDCARD).
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType_DriverOnly i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(OperationType i_opType,
AccessType_DriverOnly i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType_DriverOnly i_accessType,
TARGETING::TYPE i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
template <>
void deviceRegisterRoute<>(DriverSpecial i_opType,
AccessType_DriverOnly i_accessType,
DriverSpecial i_targetType,
deviceOp_t i_regRoute);
// deviceOp:
// OpType - OperationType only.
// TargType - TargetType only.
// AccType - AccessType, AccessType_DriverOnly (no WILDCARD).
template <>
errlHndl_t deviceOp<>(OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer, size_t& io_buflen,
AccessType i_accessType, ...);
template <>
errlHndl_t deviceOp<>(OperationType i_opType,
TARGETING::Target* i_target,
void* io_buffer, size_t& io_buflen,
AccessType_DriverOnly i_accessType, ...);
};
#endif
<|endoftext|>
|
<commit_before>#include "PluginManager.h"
#include <fstream>
#include <filesystem>
#include <Logger/Logger.h>
#include <Tools.h>
#include <API/UE/Math/ColorList.h>
#include "../Commands.h"
namespace ArkApi
{
PluginManager::PluginManager()
{
Commands& commands = Commands::Get();
commands.AddConsoleCommand("plugins.load", &LoadPluginCmd);
commands.AddConsoleCommand("plugins.unload", &UnloadPluginCmd);
}
PluginManager& PluginManager::Get()
{
static PluginManager instance;
return instance;
}
void PluginManager::LoadAllPlugins()
{
namespace fs = std::experimental::filesystem;
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins";
for (const auto& dir_name : fs::directory_iterator(dir_path))
{
const auto& path = dir_name.path();
const auto filename = path.filename().stem().generic_string();
try
{
std::stringstream stream;
std::shared_ptr<Plugin>& plugin = LoadPlugin(filename);
stream << "Loaded plugin " << (plugin->full_name.empty() ? plugin->name : plugin->full_name) << " V" << std::fixed
<< std::setprecision(1) << plugin->version << " (" << plugin->description << ")";
Log::GetLog()->info(stream.str());
}
catch (const std::exception& error)
{
Log::GetLog()->warn(error.what());
}
}
CheckPluginsDependencies();
Log::GetLog()->info("Loaded all plugins\n");
}
std::shared_ptr<Plugin>& PluginManager::LoadPlugin(const std::string& plugin_name) noexcept(false)
{
namespace fs = std::experimental::filesystem;
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins/" + plugin_name;
const std::string full_path = dir_path + "/" + plugin_name + ".dll";
if (!fs::exists(full_path))
throw std::runtime_error("Plugin " + plugin_name + " does not exist");
if (IsPluginLoaded(plugin_name))
throw std::runtime_error("Plugin " + plugin_name + " was already loaded");
auto plugin_info = ReadPluginInfo(plugin_name);
// Check version
const auto required_version = static_cast<float>(plugin_info["MinApiVersion"]);
if (required_version != .0f && std::stof(API_VERSION) < required_version)
throw std::runtime_error("Plugin " + plugin_name + " requires newer API version!");
HINSTANCE h_module = LoadLibraryExA(full_path.c_str(), nullptr, LOAD_LIBRARY_SEARCH_USER_DIRS);
if (!h_module)
throw std::runtime_error(
"Failed to load plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError()));
return loaded_plugins_.emplace_back(std::make_shared<Plugin>(h_module, plugin_name, plugin_info["FullName"],
plugin_info["Description"], plugin_info["Version"],
plugin_info["MinApiVersion"],
plugin_info["Dependencies"]));
}
void PluginManager::UnloadPlugin(const std::string& plugin_name) noexcept(false)
{
namespace fs = std::experimental::filesystem;
const auto iter = FindPlugin(plugin_name);
if (iter == loaded_plugins_.end())
throw std::runtime_error("Plugin " + plugin_name + " is not loaded");
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins/" + plugin_name;
const std::string full_path = dir_path + "/" + plugin_name + ".dll";
if (!fs::exists(full_path))
throw std::runtime_error("Plugin " + plugin_name + " does not exist");
const BOOL result = FreeLibrary((*iter)->h_module);
if (!result)
throw std::runtime_error(
"Failed to unload plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError()));
loaded_plugins_.erase(remove(loaded_plugins_.begin(), loaded_plugins_.end(), *iter), loaded_plugins_.end());
}
nlohmann::json PluginManager::ReadPluginInfo(const std::string& plugin_name)
{
nlohmann::json plugin_info = nlohmann::json::object();
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins/" + plugin_name;
const std::string config_path = dir_path + "/PluginInfo.json";
std::ifstream file{config_path};
if (file.is_open())
{
file >> plugin_info;
file.close();
}
plugin_info["FullName"] = plugin_info.value("FullName", "");
plugin_info["Description"] = plugin_info.value("Description", "No description");
plugin_info["Version"] = plugin_info.value("Version", 1.0f);
plugin_info["MinApiVersion"] = plugin_info.value("MinApiVersion", .0f);
plugin_info["Dependencies"] = plugin_info.value("Dependencies", std::vector<std::string>{});
return plugin_info;
}
void PluginManager::CheckPluginsDependencies()
{
for (const auto& plugin : loaded_plugins_)
{
if (plugin->dependencies.empty())
continue;
for (const std::string& dependency : plugin->dependencies)
{
if (!IsPluginLoaded(dependency))
{
Log::GetLog()->error("Plugin {} is missing! {} might not work correctly", dependency, plugin->name);
}
}
}
}
std::vector<std::shared_ptr<Plugin>>::const_iterator PluginManager::FindPlugin(const std::string& plugin_name)
{
const auto iter = std::find_if(loaded_plugins_.begin(), loaded_plugins_.end(),
[plugin_name](const std::shared_ptr<Plugin>& plugin) -> bool
{
return plugin->name == plugin_name;
});
return iter;
}
bool PluginManager::IsPluginLoaded(const std::string& plugin_name)
{
return FindPlugin(plugin_name) != loaded_plugins_.end();
}
// Callbacks
void PluginManager::LoadPluginCmd(APlayerController* player_controller, FString* cmd, bool)
{
TArray<FString> parsed;
cmd->ParseIntoArray(parsed, L" ", true);
if (parsed.IsValidIndex(1))
{
AShooterPlayerController* shooter_controller = static_cast<AShooterPlayerController*>(player_controller);
const std::string plugin_name = parsed[1].ToString();
try
{
Get().LoadPlugin(plugin_name);
}
catch (const std::exception& error)
{
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Red, "Failed to load plugin - {}", error.what());
Log::GetLog()->warn(error.what());
return;
}
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Green, "Successfully loaded plugin");
Log::GetLog()->info("Loaded plugin - {}", plugin_name.c_str());
}
}
void PluginManager::UnloadPluginCmd(APlayerController* player_controller, FString* cmd, bool)
{
TArray<FString> parsed;
cmd->ParseIntoArray(parsed, L" ", true);
if (parsed.IsValidIndex(1))
{
AShooterPlayerController* shooter_controller = static_cast<AShooterPlayerController*>(player_controller);
const std::string plugin_name = parsed[1].ToString();
try
{
Get().UnloadPlugin(plugin_name);
}
catch (const std::exception& error)
{
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Red, "Failed to unload plugin - {}", error.what());
Log::GetLog()->warn(error.what());
return;
}
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Green, "Successfully unloaded plugin");
Log::GetLog()->info("Unloaded plugin - {}", plugin_name.c_str());
}
}
}
<commit_msg>Fixed plugins loading bug<commit_after>#include "PluginManager.h"
#include <fstream>
#include <filesystem>
#include <Logger/Logger.h>
#include <Tools.h>
#include <API/UE/Math/ColorList.h>
#include "../Commands.h"
namespace ArkApi
{
PluginManager::PluginManager()
{
Commands& commands = Commands::Get();
commands.AddConsoleCommand("plugins.load", &LoadPluginCmd);
commands.AddConsoleCommand("plugins.unload", &UnloadPluginCmd);
}
PluginManager& PluginManager::Get()
{
static PluginManager instance;
return instance;
}
void PluginManager::LoadAllPlugins()
{
namespace fs = std::experimental::filesystem;
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins";
for (const auto& dir_name : fs::directory_iterator(dir_path))
{
const auto& path = dir_name.path();
const auto filename = path.filename().stem().generic_string();
try
{
std::stringstream stream;
std::shared_ptr<Plugin>& plugin = LoadPlugin(filename);
stream << "Loaded plugin " << (plugin->full_name.empty() ? plugin->name : plugin->full_name) << " V" << std::fixed
<< std::setprecision(1) << plugin->version << " (" << plugin->description << ")";
Log::GetLog()->info(stream.str());
}
catch (const std::exception& error)
{
Log::GetLog()->warn(error.what());
}
}
CheckPluginsDependencies();
Log::GetLog()->info("Loaded all plugins\n");
}
std::shared_ptr<Plugin>& PluginManager::LoadPlugin(const std::string& plugin_name) noexcept(false)
{
namespace fs = std::experimental::filesystem;
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins/" + plugin_name;
const std::string full_path = dir_path + "/" + plugin_name + ".dll";
if (!fs::exists(full_path))
throw std::runtime_error("Plugin " + plugin_name + " does not exist");
if (IsPluginLoaded(plugin_name))
throw std::runtime_error("Plugin " + plugin_name + " was already loaded");
auto plugin_info = ReadPluginInfo(plugin_name);
// Check version
const auto required_version = static_cast<float>(plugin_info["MinApiVersion"]);
if (required_version != .0f && std::stof(API_VERSION) < required_version)
throw std::runtime_error("Plugin " + plugin_name + " requires newer API version!");
HINSTANCE h_module = LoadLibraryA(full_path.c_str());
if (!h_module)
throw std::runtime_error(
"Failed to load plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError()));
return loaded_plugins_.emplace_back(std::make_shared<Plugin>(h_module, plugin_name, plugin_info["FullName"],
plugin_info["Description"], plugin_info["Version"],
plugin_info["MinApiVersion"],
plugin_info["Dependencies"]));
}
void PluginManager::UnloadPlugin(const std::string& plugin_name) noexcept(false)
{
namespace fs = std::experimental::filesystem;
const auto iter = FindPlugin(plugin_name);
if (iter == loaded_plugins_.end())
throw std::runtime_error("Plugin " + plugin_name + " is not loaded");
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins/" + plugin_name;
const std::string full_path = dir_path + "/" + plugin_name + ".dll";
if (!fs::exists(full_path))
throw std::runtime_error("Plugin " + plugin_name + " does not exist");
const BOOL result = FreeLibrary((*iter)->h_module);
if (!result)
throw std::runtime_error(
"Failed to unload plugin - " + plugin_name + "\nError code: " + std::to_string(GetLastError()));
loaded_plugins_.erase(remove(loaded_plugins_.begin(), loaded_plugins_.end(), *iter), loaded_plugins_.end());
}
nlohmann::json PluginManager::ReadPluginInfo(const std::string& plugin_name)
{
nlohmann::json plugin_info = nlohmann::json::object();
const std::string dir_path = Tools::GetCurrentDir() + "/ArkApi/Plugins/" + plugin_name;
const std::string config_path = dir_path + "/PluginInfo.json";
std::ifstream file{config_path};
if (file.is_open())
{
file >> plugin_info;
file.close();
}
plugin_info["FullName"] = plugin_info.value("FullName", "");
plugin_info["Description"] = plugin_info.value("Description", "No description");
plugin_info["Version"] = plugin_info.value("Version", 1.0f);
plugin_info["MinApiVersion"] = plugin_info.value("MinApiVersion", .0f);
plugin_info["Dependencies"] = plugin_info.value("Dependencies", std::vector<std::string>{});
return plugin_info;
}
void PluginManager::CheckPluginsDependencies()
{
for (const auto& plugin : loaded_plugins_)
{
if (plugin->dependencies.empty())
continue;
for (const std::string& dependency : plugin->dependencies)
{
if (!IsPluginLoaded(dependency))
{
Log::GetLog()->error("Plugin {} is missing! {} might not work correctly", dependency, plugin->name);
}
}
}
}
std::vector<std::shared_ptr<Plugin>>::const_iterator PluginManager::FindPlugin(const std::string& plugin_name)
{
const auto iter = std::find_if(loaded_plugins_.begin(), loaded_plugins_.end(),
[plugin_name](const std::shared_ptr<Plugin>& plugin) -> bool
{
return plugin->name == plugin_name;
});
return iter;
}
bool PluginManager::IsPluginLoaded(const std::string& plugin_name)
{
return FindPlugin(plugin_name) != loaded_plugins_.end();
}
// Callbacks
void PluginManager::LoadPluginCmd(APlayerController* player_controller, FString* cmd, bool)
{
TArray<FString> parsed;
cmd->ParseIntoArray(parsed, L" ", true);
if (parsed.IsValidIndex(1))
{
AShooterPlayerController* shooter_controller = static_cast<AShooterPlayerController*>(player_controller);
const std::string plugin_name = parsed[1].ToString();
try
{
Get().LoadPlugin(plugin_name);
}
catch (const std::exception& error)
{
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Red, "Failed to load plugin - {}", error.what());
Log::GetLog()->warn(error.what());
return;
}
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Green, "Successfully loaded plugin");
Log::GetLog()->info("Loaded plugin - {}", plugin_name.c_str());
}
}
void PluginManager::UnloadPluginCmd(APlayerController* player_controller, FString* cmd, bool)
{
TArray<FString> parsed;
cmd->ParseIntoArray(parsed, L" ", true);
if (parsed.IsValidIndex(1))
{
AShooterPlayerController* shooter_controller = static_cast<AShooterPlayerController*>(player_controller);
const std::string plugin_name = parsed[1].ToString();
try
{
Get().UnloadPlugin(plugin_name);
}
catch (const std::exception& error)
{
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Red, "Failed to unload plugin - {}", error.what());
Log::GetLog()->warn(error.what());
return;
}
GetApiUtils().SendServerMessage(shooter_controller, FColorList::Green, "Successfully unloaded plugin");
Log::GetLog()->info("Unloaded plugin - {}", plugin_name.c_str());
}
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/c/task/processor/classification_result.h"
#include <memory>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
void TfLiteClassificationResultDelete(
TfLiteClassificationResult* classification_result) {
for (int head = 0; head < classification_result->size; ++head) {
TfLiteClassifications classifications =
classification_result->classifications[head];
for (int rank = 0; rank < classifications.size; ++rank) {
// `strdup` obtains memory using `malloc` and the memory needs to be
// released using `free`.
free(classifications.categories[rank].display_name);
free(classifications.categories[rank].label);
}
if (classifications.size >= 1) delete[] classifications.categories;
}
if (classification_result->size >= 1)
delete[] classification_result->classifications;
delete classification_result;
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
<commit_msg>Removed check of size before deletion in classification result.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/c/task/processor/classification_result.h"
#include <memory>
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
void TfLiteClassificationResultDelete(
TfLiteClassificationResult* classification_result) {
for (int head = 0; head < classification_result->size; ++head) {
TfLiteClassifications classifications =
classification_result->classifications[head];
for (int rank = 0; rank < classifications.size; ++rank) {
// `strdup` obtains memory using `malloc` and the memory needs to be
// released using `free`.
free(classifications.categories[rank].display_name);
free(classifications.categories[rank].label);
}
delete[] classifications.categories;
}
delete[] classification_result->classifications;
delete classification_result;
}
#ifdef __cplusplus
} // extern "C"
#endif // __cplusplus
<|endoftext|>
|
<commit_before>#ifndef STAN_MATH_OPENCL_VALUE_TYPE_HPP
#define STAN_MATH_OPENCL_VALUE_TYPE_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/kernel_generator/is_kernel_expression.hpp>
#include <type_traits>
namespace stan {
/** \ingroup type_traits
* Return the value type of an OpenCL matrix.
*/
template <typename T>
struct value_type<T, math::require_all_kernel_expressions_and_none_scalar_t<T>> {
using type = typename std::decay_t<T>::Scalar;
};
} // namespace stan
#endif
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags/RELEASE_600/final)<commit_after>#ifndef STAN_MATH_OPENCL_VALUE_TYPE_HPP
#define STAN_MATH_OPENCL_VALUE_TYPE_HPP
#ifdef STAN_OPENCL
#include <stan/math/prim/meta.hpp>
#include <stan/math/opencl/kernel_generator/is_kernel_expression.hpp>
#include <type_traits>
namespace stan {
/** \ingroup type_traits
* Return the value type of an OpenCL matrix.
*/
template <typename T>
struct value_type<T,
math::require_all_kernel_expressions_and_none_scalar_t<T>> {
using type = typename std::decay_t<T>::Scalar;
};
} // namespace stan
#endif
#endif
<|endoftext|>
|
<commit_before>#include "gen_tex.h"
#include "base/utils.h"
#include <vector>
#define COMP_LATTICE_PROBABILITY 0.25f
void gen_texture(glm::u8vec4 * tex_data, ushort dim, ushort grid_dim, unsigned seed){
if (grid_dim <= 0){
return;
}
srand(seed);
int max = (int)(1 / COMP_LATTICE_PROBABILITY);
int lattice_dim = dim / grid_dim;
glm::u8vec4 base_color(50, 50, 50, 255);
glm::u8vec4 complement_color(200, 200, 200, 255);
std::vector<glm::u8vec4> grid;
grid.resize(grid_dim*grid_dim, base_color);
for (int i = 0; i < grid_dim*grid_dim; i++){
if (util::rndFromInterval(1, max) == 1){
grid[i] = glm::u8vec4(complement_color.x, complement_color.y, complement_color.z, util::rndFromInterval(100, 255));
}
}
for (ushort y = 0; y < dim; y++){
for (ushort x = 0; x < dim; x++){
tex_data[y*dim + x] = grid[(y / lattice_dim)*grid_dim + (x / lattice_dim)];
}
}
}
ushort rgb888_to_rgb565(uint8 r, uint8 g, uint8 b) {
return ((r >> 3) << 11) | (((g >> 2) & 0x3f) << 5) | ((b >> 3) & 0x1f);
}
glm::ivec2 gen_dxt1_block(uint8 r, uint8 g, uint8 b, uint8 a) {
ushort rgb565 = rgb888_to_rgb565(r, g, b);
return glm::ivec2(rgb565 << 16 | rgb565, 0xaaaaaaaa);
}<commit_msg>less operations<commit_after>#include "gen_tex.h"
#include "base/utils.h"
#include <vector>
#define COMP_LATTICE_PROBABILITY 0.25f
void gen_texture(glm::u8vec4 * tex_data, ushort dim, ushort grid_dim, unsigned seed){
if (grid_dim <= 0){
return;
}
srand(seed);
int max = (int)(1 / COMP_LATTICE_PROBABILITY);
int lattice_dim = dim / grid_dim;
glm::u8vec4 base_color(50, 50, 50, 255);
glm::u8vec4 complement_color(200, 200, 200, 255);
std::vector<glm::u8vec4> grid;
grid.resize(grid_dim*grid_dim, base_color);
for (int i = 0; i < grid_dim*grid_dim; i++){
if (util::rndFromInterval(1, max) == 1){
grid[i] = glm::u8vec4(complement_color.x, complement_color.y, complement_color.z, util::rndFromInterval(100, 255));
}
}
for (ushort y = 0; y < dim; y++){
for (ushort x = 0; x < dim; x++){
tex_data[y*dim + x] = grid[(y / lattice_dim)*grid_dim + (x / lattice_dim)];
}
}
}
ushort rgb888_to_rgb565(uint8 r, uint8 g, uint8 b) {
return ((ushort(r) >> 3) << 11) | (((ushort(g) >> 2)) << 5) | ((ushort(b) >> 3));
}
glm::ivec2 gen_dxt1_block(uint8 r, uint8 g, uint8 b, uint8 a) {
ushort rgb565 = rgb888_to_rgb565(r, g, b);
return glm::ivec2(rgb565 << 16 | rgb565, 0xaaaaaaaa);
}<|endoftext|>
|
<commit_before>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include <boost/filesystem.hpp>
#include <boost/assert.hpp>
#include <boost/format.hpp>
#include <experimental/filesystem>
#include <armnn/IRuntime.hpp>
#include <armnn/TypesUtils.hpp>
#include "test/TensorHelpers.hpp"
#include "armnnTfLiteParser/ITfLiteParser.hpp"
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <schema_generated.h>
#include <iostream>
using armnnTfLiteParser::ITfLiteParser;
using TensorRawPtr = const tflite::TensorT *;
struct ParserFlatbuffersFixture
{
ParserFlatbuffersFixture()
: m_Parser(ITfLiteParser::Create()), m_NetworkIdentifier(-1)
{
armnn::IRuntime::CreationOptions options;
m_Runtimes.push_back(std::make_pair(armnn::IRuntime::Create(options), armnn::Compute::CpuRef));
#if ARMCOMPUTENEON_ENABLED
m_Runtimes.push_back(std::make_pair(armnn::IRuntime::Create(options), armnn::Compute::CpuAcc));
#endif
#if ARMCOMPUTECL_ENABLED
m_Runtimes.push_back(std::make_pair(armnn::IRuntime::Create(options), armnn::Compute::GpuAcc));
#endif
}
std::vector<uint8_t> m_GraphBinary;
std::string m_JsonString;
std::unique_ptr<ITfLiteParser, void (*)(ITfLiteParser *parser)> m_Parser;
std::vector<std::pair<armnn::IRuntimePtr, armnn::BackendId>> m_Runtimes;
armnn::NetworkId m_NetworkIdentifier;
/// If the single-input-single-output overload of Setup() is called, these will store the input and output name
/// so they don't need to be passed to the single-input-single-output overload of RunTest().
std::string m_SingleInputName;
std::string m_SingleOutputName;
void Setup()
{
bool ok = ReadStringToBinary();
if (!ok) {
throw armnn::Exception("LoadNetwork failed while reading binary input");
}
for (auto&& runtime : m_Runtimes)
{
armnn::INetworkPtr network =
m_Parser->CreateNetworkFromBinary(m_GraphBinary);
if (!network) {
throw armnn::Exception("The parser failed to create an ArmNN network");
}
auto optimized = Optimize(*network,
{ runtime.second, armnn::Compute::CpuRef },
runtime.first->GetDeviceSpec());
std::string errorMessage;
armnn::Status ret = runtime.first->LoadNetwork(m_NetworkIdentifier,
move(optimized),
errorMessage);
if (ret != armnn::Status::Success)
{
throw armnn::Exception(
boost::str(
boost::format("The runtime failed to load the network. "
"Error was: %1%. in %2% [%3%:%4%]") %
errorMessage %
__func__ %
__FILE__ %
__LINE__));
}
}
}
void SetupSingleInputSingleOutput(const std::string& inputName, const std::string& outputName)
{
// Store the input and output name so they don't need to be passed to the single-input-single-output RunTest().
m_SingleInputName = inputName;
m_SingleOutputName = outputName;
Setup();
}
bool ReadStringToBinary()
{
const char* schemafileName = getenv("ARMNN_TF_LITE_SCHEMA_PATH");
if (schemafileName == nullptr)
{
schemafileName = ARMNN_TF_LITE_SCHEMA_PATH;
}
std::string schemafile;
bool ok = flatbuffers::LoadFile(schemafileName, false, &schemafile);
BOOST_ASSERT_MSG(ok, "Couldn't load schema file " ARMNN_TF_LITE_SCHEMA_PATH);
if (!ok)
{
return false;
}
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
ok &= parser.Parse(schemafile.c_str());
BOOST_ASSERT_MSG(ok, "Failed to parse schema file");
ok &= parser.Parse(m_JsonString.c_str());
BOOST_ASSERT_MSG(ok, "Failed to parse json input");
if (!ok)
{
return false;
}
{
const uint8_t * bufferPtr = parser.builder_.GetBufferPointer();
size_t size = static_cast<size_t>(parser.builder_.GetSize());
m_GraphBinary.assign(bufferPtr, bufferPtr+size);
}
return ok;
}
/// Executes the network with the given input tensor and checks the result against the given output tensor.
/// This overload assumes the network has a single input and a single output.
template <std::size_t NumOutputDimensions, typename DataType>
void RunTest(size_t subgraphId,
const std::vector<DataType>& inputData,
const std::vector<DataType>& expectedOutputData);
/// Executes the network with the given input tensors and checks the results against the given output tensors.
/// This overload supports multiple inputs and multiple outputs, identified by name.
template <std::size_t NumOutputDimensions, typename DataType>
void RunTest(size_t subgraphId,
const std::map<std::string, std::vector<DataType>>& inputData,
const std::map<std::string, std::vector<DataType>>& expectedOutputData);
void CheckTensors(const TensorRawPtr& tensors, size_t shapeSize, const std::vector<int32_t>& shape,
tflite::TensorType tensorType, uint32_t buffer, const std::string& name,
const std::vector<float>& min, const std::vector<float>& max,
const std::vector<float>& scale, const std::vector<int64_t>& zeroPoint)
{
BOOST_CHECK(tensors);
BOOST_CHECK_EQUAL(shapeSize, tensors->shape.size());
BOOST_CHECK_EQUAL_COLLECTIONS(shape.begin(), shape.end(), tensors->shape.begin(), tensors->shape.end());
BOOST_CHECK_EQUAL(tensorType, tensors->type);
BOOST_CHECK_EQUAL(buffer, tensors->buffer);
BOOST_CHECK_EQUAL(name, tensors->name);
BOOST_CHECK(tensors->quantization);
BOOST_CHECK_EQUAL_COLLECTIONS(min.begin(), min.end(), tensors->quantization.get()->min.begin(),
tensors->quantization.get()->min.end());
BOOST_CHECK_EQUAL_COLLECTIONS(max.begin(), max.end(), tensors->quantization.get()->max.begin(),
tensors->quantization.get()->max.end());
BOOST_CHECK_EQUAL_COLLECTIONS(scale.begin(), scale.end(), tensors->quantization.get()->scale.begin(),
tensors->quantization.get()->scale.end());
BOOST_CHECK_EQUAL_COLLECTIONS(zeroPoint.begin(), zeroPoint.end(),
tensors->quantization.get()->zero_point.begin(),
tensors->quantization.get()->zero_point.end());
}
};
template <std::size_t NumOutputDimensions, typename DataType>
void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
const std::vector<DataType>& inputData,
const std::vector<DataType>& expectedOutputData)
{
RunTest<NumOutputDimensions, DataType>(subgraphId,
{ { m_SingleInputName, inputData } },
{ { m_SingleOutputName, expectedOutputData } });
}
template <std::size_t NumOutputDimensions, typename DataType>
void
ParserFlatbuffersFixture::RunTest(size_t subgraphId,
const std::map<std::string, std::vector<DataType>>& inputData,
const std::map<std::string, std::vector<DataType>>& expectedOutputData)
{
for (auto&& runtime : m_Runtimes)
{
using BindingPointInfo = std::pair<armnn::LayerBindingId, armnn::TensorInfo>;
// Setup the armnn input tensors from the given vectors.
armnn::InputTensors inputTensors;
for (auto&& it : inputData)
{
BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
armnn::VerifyTensorInfoDataType<DataType>(bindingInfo.second);
inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
}
// Allocate storage for the output tensors to be written to and setup the armnn output tensors.
std::map<std::string, boost::multi_array<DataType, NumOutputDimensions>> outputStorage;
armnn::OutputTensors outputTensors;
for (auto&& it : expectedOutputData)
{
BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
armnn::VerifyTensorInfoDataType<DataType>(bindingInfo.second);
outputStorage.emplace(it.first, MakeTensor<DataType, NumOutputDimensions>(bindingInfo.second));
outputTensors.push_back(
{ bindingInfo.first, armnn::Tensor(bindingInfo.second, outputStorage.at(it.first).data()) });
}
runtime.first->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
// Compare each output tensor to the expected values
for (auto&& it : expectedOutputData)
{
BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
auto outputExpected = MakeTensor<DataType, NumOutputDimensions>(bindingInfo.second, it.second);
BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first]));
}
}
}
<commit_msg>IVGCVSW-2057: Remove ARMCOMPUTE(CL/NEON)_ENABLED and ARMCOMPUTENEON_ENABLED from src/armnnTfliteParser/test/ParserFlatBufferFixture.hpp<commit_after>//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include <boost/filesystem.hpp>
#include <boost/assert.hpp>
#include <boost/format.hpp>
#include <experimental/filesystem>
#include <armnn/IRuntime.hpp>
#include <armnn/TypesUtils.hpp>
#include "test/TensorHelpers.hpp"
#include "armnnTfLiteParser/ITfLiteParser.hpp"
#include <backends/BackendRegistry.hpp>
#include "flatbuffers/idl.h"
#include "flatbuffers/util.h"
#include <schema_generated.h>
#include <iostream>
using armnnTfLiteParser::ITfLiteParser;
using TensorRawPtr = const tflite::TensorT *;
struct ParserFlatbuffersFixture
{
ParserFlatbuffersFixture()
: m_Parser(ITfLiteParser::Create()), m_NetworkIdentifier(-1)
{
armnn::IRuntime::CreationOptions options;
const armnn::BackendIdSet availableBackendIds = armnn::BackendRegistryInstance().GetBackendIds();
for (auto& backendId : availableBackendIds)
{
m_Runtimes.push_back(std::make_pair(armnn::IRuntime::Create(options), backendId));
}
}
std::vector<uint8_t> m_GraphBinary;
std::string m_JsonString;
std::unique_ptr<ITfLiteParser, void (*)(ITfLiteParser *parser)> m_Parser;
std::vector<std::pair<armnn::IRuntimePtr, armnn::BackendId>> m_Runtimes;
armnn::NetworkId m_NetworkIdentifier;
/// If the single-input-single-output overload of Setup() is called, these will store the input and output name
/// so they don't need to be passed to the single-input-single-output overload of RunTest().
std::string m_SingleInputName;
std::string m_SingleOutputName;
void Setup()
{
bool ok = ReadStringToBinary();
if (!ok) {
throw armnn::Exception("LoadNetwork failed while reading binary input");
}
for (auto&& runtime : m_Runtimes)
{
armnn::INetworkPtr network =
m_Parser->CreateNetworkFromBinary(m_GraphBinary);
if (!network) {
throw armnn::Exception("The parser failed to create an ArmNN network");
}
auto optimized = Optimize(*network,
{ runtime.second, armnn::Compute::CpuRef },
runtime.first->GetDeviceSpec());
std::string errorMessage;
armnn::Status ret = runtime.first->LoadNetwork(m_NetworkIdentifier,
move(optimized),
errorMessage);
if (ret != armnn::Status::Success)
{
throw armnn::Exception(
boost::str(
boost::format("The runtime failed to load the network. "
"Error was: %1%. in %2% [%3%:%4%]") %
errorMessage %
__func__ %
__FILE__ %
__LINE__));
}
}
}
void SetupSingleInputSingleOutput(const std::string& inputName, const std::string& outputName)
{
// Store the input and output name so they don't need to be passed to the single-input-single-output RunTest().
m_SingleInputName = inputName;
m_SingleOutputName = outputName;
Setup();
}
bool ReadStringToBinary()
{
const char* schemafileName = getenv("ARMNN_TF_LITE_SCHEMA_PATH");
if (schemafileName == nullptr)
{
schemafileName = ARMNN_TF_LITE_SCHEMA_PATH;
}
std::string schemafile;
bool ok = flatbuffers::LoadFile(schemafileName, false, &schemafile);
BOOST_ASSERT_MSG(ok, "Couldn't load schema file " ARMNN_TF_LITE_SCHEMA_PATH);
if (!ok)
{
return false;
}
// parse schema first, so we can use it to parse the data after
flatbuffers::Parser parser;
ok &= parser.Parse(schemafile.c_str());
BOOST_ASSERT_MSG(ok, "Failed to parse schema file");
ok &= parser.Parse(m_JsonString.c_str());
BOOST_ASSERT_MSG(ok, "Failed to parse json input");
if (!ok)
{
return false;
}
{
const uint8_t * bufferPtr = parser.builder_.GetBufferPointer();
size_t size = static_cast<size_t>(parser.builder_.GetSize());
m_GraphBinary.assign(bufferPtr, bufferPtr+size);
}
return ok;
}
/// Executes the network with the given input tensor and checks the result against the given output tensor.
/// This overload assumes the network has a single input and a single output.
template <std::size_t NumOutputDimensions, typename DataType>
void RunTest(size_t subgraphId,
const std::vector<DataType>& inputData,
const std::vector<DataType>& expectedOutputData);
/// Executes the network with the given input tensors and checks the results against the given output tensors.
/// This overload supports multiple inputs and multiple outputs, identified by name.
template <std::size_t NumOutputDimensions, typename DataType>
void RunTest(size_t subgraphId,
const std::map<std::string, std::vector<DataType>>& inputData,
const std::map<std::string, std::vector<DataType>>& expectedOutputData);
void CheckTensors(const TensorRawPtr& tensors, size_t shapeSize, const std::vector<int32_t>& shape,
tflite::TensorType tensorType, uint32_t buffer, const std::string& name,
const std::vector<float>& min, const std::vector<float>& max,
const std::vector<float>& scale, const std::vector<int64_t>& zeroPoint)
{
BOOST_CHECK(tensors);
BOOST_CHECK_EQUAL(shapeSize, tensors->shape.size());
BOOST_CHECK_EQUAL_COLLECTIONS(shape.begin(), shape.end(), tensors->shape.begin(), tensors->shape.end());
BOOST_CHECK_EQUAL(tensorType, tensors->type);
BOOST_CHECK_EQUAL(buffer, tensors->buffer);
BOOST_CHECK_EQUAL(name, tensors->name);
BOOST_CHECK(tensors->quantization);
BOOST_CHECK_EQUAL_COLLECTIONS(min.begin(), min.end(), tensors->quantization.get()->min.begin(),
tensors->quantization.get()->min.end());
BOOST_CHECK_EQUAL_COLLECTIONS(max.begin(), max.end(), tensors->quantization.get()->max.begin(),
tensors->quantization.get()->max.end());
BOOST_CHECK_EQUAL_COLLECTIONS(scale.begin(), scale.end(), tensors->quantization.get()->scale.begin(),
tensors->quantization.get()->scale.end());
BOOST_CHECK_EQUAL_COLLECTIONS(zeroPoint.begin(), zeroPoint.end(),
tensors->quantization.get()->zero_point.begin(),
tensors->quantization.get()->zero_point.end());
}
};
template <std::size_t NumOutputDimensions, typename DataType>
void ParserFlatbuffersFixture::RunTest(size_t subgraphId,
const std::vector<DataType>& inputData,
const std::vector<DataType>& expectedOutputData)
{
RunTest<NumOutputDimensions, DataType>(subgraphId,
{ { m_SingleInputName, inputData } },
{ { m_SingleOutputName, expectedOutputData } });
}
template <std::size_t NumOutputDimensions, typename DataType>
void
ParserFlatbuffersFixture::RunTest(size_t subgraphId,
const std::map<std::string, std::vector<DataType>>& inputData,
const std::map<std::string, std::vector<DataType>>& expectedOutputData)
{
for (auto&& runtime : m_Runtimes)
{
using BindingPointInfo = std::pair<armnn::LayerBindingId, armnn::TensorInfo>;
// Setup the armnn input tensors from the given vectors.
armnn::InputTensors inputTensors;
for (auto&& it : inputData)
{
BindingPointInfo bindingInfo = m_Parser->GetNetworkInputBindingInfo(subgraphId, it.first);
armnn::VerifyTensorInfoDataType<DataType>(bindingInfo.second);
inputTensors.push_back({ bindingInfo.first, armnn::ConstTensor(bindingInfo.second, it.second.data()) });
}
// Allocate storage for the output tensors to be written to and setup the armnn output tensors.
std::map<std::string, boost::multi_array<DataType, NumOutputDimensions>> outputStorage;
armnn::OutputTensors outputTensors;
for (auto&& it : expectedOutputData)
{
BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
armnn::VerifyTensorInfoDataType<DataType>(bindingInfo.second);
outputStorage.emplace(it.first, MakeTensor<DataType, NumOutputDimensions>(bindingInfo.second));
outputTensors.push_back(
{ bindingInfo.first, armnn::Tensor(bindingInfo.second, outputStorage.at(it.first).data()) });
}
runtime.first->EnqueueWorkload(m_NetworkIdentifier, inputTensors, outputTensors);
// Compare each output tensor to the expected values
for (auto&& it : expectedOutputData)
{
BindingPointInfo bindingInfo = m_Parser->GetNetworkOutputBindingInfo(subgraphId, it.first);
auto outputExpected = MakeTensor<DataType, NumOutputDimensions>(bindingInfo.second, it.second);
BOOST_TEST(CompareTensors(outputExpected, outputStorage[it.first]));
}
}
}
<|endoftext|>
|
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "mainwindow.h"
//..............................................................................
int main (int argc, char* argv [])
{
#if (_JNC_OS_WIN)
WSADATA WsaData;
WSAStartup (0x0202, &WsaData);
#endif
jnc::initialize ("jnc_test_qt");
srand ((int) sys::getTimestamp ());
QApplication app (argc, argv);
QCoreApplication::setOrganizationName ("Tibbo");
QCoreApplication::setOrganizationDomain ("tibbo.com");
QCoreApplication::setApplicationName ("JancyEdit");
MainWindow mainWindow;
mainWindow.showMaximized();
return app.exec ();
}
//..............................................................................
<commit_msg>[jnc_test_qt] added setvbuf<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "mainwindow.h"
//..............................................................................
int main (int argc, char* argv [])
{
#if (_JNC_OS_WIN)
WSADATA WsaData;
WSAStartup (0x0202, &WsaData);
#endif
#if _AXL_OS_POSIX
setvbuf (stdout, NULL, _IOLBF, 1024);
#endif
jnc::initialize ("jnc_test_qt");
srand ((int) sys::getTimestamp ());
QApplication app (argc, argv);
QCoreApplication::setOrganizationName ("Tibbo");
QCoreApplication::setOrganizationDomain ("tibbo.com");
QCoreApplication::setApplicationName ("JancyEdit");
MainWindow mainWindow;
mainWindow.showMaximized();
return app.exec ();
}
//..............................................................................
<|endoftext|>
|
<commit_before>#include "sceneGridHandler.h"
#include "../nodeElement.h"
#include "../../view/editorViewScene.h"
using namespace qReal;
namespace {
// TODO: find a way to remove it
// magic constants
const int widthLineX = 15000;
const int widthLineY = 11000;
}
SceneGridHandler::SceneGridHandler(NodeElement *node)
: mNode(node), mGuidesPixmap(NULL)
{
mGuidesPen = QPen(QColor(0, 0, 0, 42), 1, Qt::DashLine);
mShowAlignment = SettingsManager::value("ShowAlignment").toBool();
mSwitchGrid = SettingsManager::value("ActivateGrid").toBool();
mSwitchAlignment = SettingsManager::value("ActivateAlignment").toBool();
}
SceneGridHandler::~SceneGridHandler()
{
delete mGuidesPixmap;
}
void SceneGridHandler::delUnusedLines()
{
EditorViewScene *evScene = dynamic_cast<EditorViewScene *>(mNode->scene());
evScene->deleteFromForeground(mGuidesPixmap);
delete mGuidesPixmap;
mGuidesPixmap = NULL;
mLines.clear();
}
void SceneGridHandler::drawLineY(qreal pointY, QRectF const &sceneRect)
{
pointY -= sceneRect.y();
QLineF const newLine(0, pointY, sceneRect.width(), pointY);
// checking whether the scene already has this line or not.
// if not (lineIsFound is false), then adding it
foreach (QLineF const &line, mLines) {
if (qAbs(line.y1() - newLine.y1()) < indistinguishabilitySpace
&& line.y2() == line.y1())
{
return;
}
}
mLines.push_back(newLine);
}
void SceneGridHandler::drawLineX(qreal pointX, QRectF const &sceneRect)
{
pointX -= sceneRect.x();
QLineF const newLine(pointX, 0, pointX, sceneRect.height());
// checking whether the scene already has this line or not.
// if not (lineIsFound is false), then adding it
foreach (QLineF const &line, mLines) {
if (qAbs(line.x1() - newLine.x1()) < indistinguishabilitySpace
&& line.x2() == line.x1())
{
return;
}
}
mLines.push_back(newLine);
}
// checking whether we should align with the vertical line or not
bool SceneGridHandler::makeJumpX(qreal deltaX, qreal pointX)
{
if (mSwitchAlignment && deltaX <= radiusJump) {
mNode->setX(pointX - mNode->contentsRect().x());
return true;
}
return false;
}
// checking whether we should align with the horizontal line or not
bool SceneGridHandler::makeJumpY(qreal deltaY, qreal pointY)
{
if (mSwitchAlignment && deltaY <= radiusJump) {
mNode->setY(pointY - mNode->contentsRect().y());
return true;
}
return false;
}
// build a vertical line: draw it and check for alignment
void SceneGridHandler::buildLineX(qreal deltaX
, qreal pointX, qreal correctionX, qreal &myX1, qreal &myX2, QRectF const &sceneRect)
{
if (deltaX > radius) {
return;
}
if (mShowAlignment) {
drawLineX(pointX, sceneRect);
}
if (makeJumpX(deltaX, pointX - correctionX)) {
myX1 = recalculateX1();
myX2 = recalculateX2(myX1);
}
}
// build a horizontal line: draw it and check for alignment
void SceneGridHandler::buildLineY(qreal deltaY
, qreal pointY, qreal correctionY, qreal &myY1, qreal &myY2, QRectF const &sceneRect)
{
if (deltaY > radius) {
return;
}
if (mShowAlignment) {
drawLineY(pointY, sceneRect);
}
if (makeJumpY(deltaY, pointY - correctionY)) {
myY1 = recalculateY1();
myY2 = recalculateY2(myY1);
}
}
qreal SceneGridHandler::recalculateX1() const
{
return mNode->scenePos().x() + mNode->boundingRect().x();
}
qreal SceneGridHandler::recalculateX2(qreal myX1) const
{
return myX1 + mNode->boundingRect().width();
}
qreal SceneGridHandler::recalculateY1() const
{
return mNode->scenePos().y() + mNode->boundingRect().y();
}
qreal SceneGridHandler::recalculateY2(qreal myY1) const
{
return myY1 + mNode->boundingRect().height();
}
qreal SceneGridHandler::alignedCoordinate(qreal coord, int coef, int indexGrid)
{
int const coefSign = coef != 0 ? coef / qAbs(coef) : 0;
if (qAbs(qAbs(coord) - qAbs(coef) * indexGrid) <= indexGrid / 2) {
return coef * indexGrid;
} else if (qAbs(qAbs(coord) - (qAbs(coef) + 1) * indexGrid) < indexGrid / 2) {
return (coef + coefSign) * indexGrid;
}
return coord;
}
void SceneGridHandler::makeGridMovingX(qreal myX, int coef, int indexGrid)
{
mNode->setX(alignedCoordinate(myX, coef, indexGrid));
mNode->adjustLinks();
}
void SceneGridHandler::makeGridMovingY(qreal myY, int coef, int indexGrid)
{
mNode->setY(alignedCoordinate(myY, coef, indexGrid));
mNode->adjustLinks();
}
qreal SceneGridHandler::makeGridAlignment(qreal coord)
{
int const indexGrid = SettingsManager::value("IndexGrid").toInt();
int const coef = static_cast<int>(coord) / indexGrid;
return alignedCoordinate(coord, coef, indexGrid);
}
void SceneGridHandler::setShowAlignmentMode(bool mode)
{
mShowAlignment = mode;
}
void SceneGridHandler::setGridMode(bool mode)
{
mSwitchGrid = mode;
}
void SceneGridHandler::setAlignmentMode(bool mode)
{
mSwitchAlignment = mode;
}
QList<QGraphicsItem *> SceneGridHandler::getAdjancedNodes() const
{
QPointF const nodeScenePos = mNode->scenePos();
QRectF const contentsRect = mNode->contentsRect();
// verical
QList<QGraphicsItem *> listX = mNode->scene()->items(nodeScenePos.x(), 0
, contentsRect.width(), widthLineY
, Qt::IntersectsItemBoundingRect, Qt::SortOrder(), QTransform());
// horizontal
QList<QGraphicsItem *> listY = mNode->scene()->items(0, nodeScenePos.y()
, widthLineX, contentsRect.height()
, Qt::IntersectsItemBoundingRect, Qt::SortOrder(), QTransform());
return listX + listY;
}
void SceneGridHandler::alignToGrid()
{
if (!mSwitchGrid) {
return;
}
int const indexGrid = SettingsManager::value("IndexGrid").toInt();
QPointF const nodePos = mNode->pos();
QRectF const contentsRect = mNode->contentsRect();
qreal myX1 = nodePos.x() + contentsRect.x();
qreal myY1 = nodePos.y() + contentsRect.y();
int coefX = static_cast<int>(myX1) / indexGrid;
int coefY = static_cast<int>(myY1) / indexGrid;
makeGridMovingX(myX1, coefX, indexGrid);
makeGridMovingY(myY1, coefY, indexGrid);
/*foreach(EdgeElement *edge, mNode->getEdges()) {
edge->alignToGrid(indexGrid);
}*/
}
void SceneGridHandler::drawGuides()
{
QPointF const nodeScenePos = mNode->scenePos();
QRectF const contentsRect = mNode->contentsRect();
QRectF const sceneRect = mNode->scene()->sceneRect();
delUnusedLines();
QList<QGraphicsItem *> list = getAdjancedNodes();
qreal myX1 = nodeScenePos.x() + contentsRect.x();
qreal myY1 = nodeScenePos.y() + contentsRect.y();
qreal myX2 = myX1 + contentsRect.width();
qreal myY2 = myY1 + contentsRect.height();
foreach (QGraphicsItem *graphicsItem, list) {
NodeElement *item = dynamic_cast<NodeElement *>(graphicsItem);
if (item == NULL || item->parentItem() != NULL || item == mNode) {
continue;
}
QPointF const point = item->scenePos();
QRectF const contents = item->contentsRect();
qreal const pointX1 = point.x() + contents.x() - spacing;
qreal const pointY1 = point.y() + contents.y() - spacing;
qreal const pointX2 = pointX1 + contents.width() + 2 * spacing;
qreal const pointY2 = pointY1 + contents.height() + 2 * spacing;
if (pointX1 != myX1 || pointY1 != myY1) {
qreal const deltaY1 = qAbs(pointY1 - myY1);
qreal const deltaY2 = qAbs(pointY2 - myY2);
qreal const deltaX1 = qAbs(pointX1 - myX1);
qreal const deltaX2 = qAbs(pointX2 - myX2);
buildLineY(deltaY1, pointY1, 0, myY1, myY2, sceneRect);
buildLineY(deltaY2, pointY2, contentsRect.height(), myY1, myY2, sceneRect);
buildLineX(deltaX1, pointX1, 0, myX1, myX2, sceneRect);
buildLineX(deltaX2, pointX2, contentsRect.width(), myX1, myX2, sceneRect);
buildLineY(qAbs(pointY1 - myY2), pointY1, contentsRect.height(), myY1, myY2, sceneRect);
buildLineX(qAbs(pointX1 - myX2), pointX1, contentsRect.width(), myX1, myX2, sceneRect);
buildLineY(qAbs(pointY2 - myY1), pointY2, 0, myY1, myY2, sceneRect);
buildLineX(qAbs(pointX2 - myX1), pointX2, 0, myX1, myX2, sceneRect);
}
}
if (mLines.size()) {
EditorViewScene *evScene = dynamic_cast<EditorViewScene *>(mNode->scene());
mGuidesPixmap = new QPixmap(sceneRect.width(), sceneRect.height());
mGuidesPixmap->fill(Qt::transparent);
QPainter painter(mGuidesPixmap);
painter.setPen(mGuidesPen);
painter.drawLines(mLines);
evScene->putOnForeground(mGuidesPixmap);
}
}
void SceneGridHandler::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
NodeElement *parItem = dynamic_cast<NodeElement*>(mNode->parentItem());
if (parItem) {
return;
}
foreach (QGraphicsItem *item, mNode->scene()->items()) {
NodeElement *e = dynamic_cast<NodeElement *>(item);
if (e && e->isSelected()) {
e->alignToGrid();
}
}
drawGuides();
mNode->adjustLinks();
}
<commit_msg>minor correction<commit_after>#include "sceneGridHandler.h"
#include "../nodeElement.h"
#include "../../view/editorViewScene.h"
using namespace qReal;
namespace {
// TODO: find a way to remove it
// magic constants
const int widthLineX = 15000;
const int widthLineY = 11000;
}
SceneGridHandler::SceneGridHandler(NodeElement *node)
: mNode(node), mGuidesPixmap(NULL)
{
mGuidesPen = QPen(QColor(0, 0, 0, 42), 1, Qt::DashLine);
mShowAlignment = SettingsManager::value("ShowAlignment").toBool();
mSwitchGrid = SettingsManager::value("ActivateGrid").toBool();
mSwitchAlignment = SettingsManager::value("ActivateAlignment").toBool();
}
SceneGridHandler::~SceneGridHandler()
{
delete mGuidesPixmap;
}
void SceneGridHandler::delUnusedLines()
{
EditorViewScene *evScene = dynamic_cast<EditorViewScene *>(mNode->scene());
evScene->deleteFromForeground(mGuidesPixmap);
delete mGuidesPixmap;
mGuidesPixmap = NULL;
mLines.clear();
}
void SceneGridHandler::drawLineY(qreal pointY, QRectF const &sceneRect)
{
pointY -= sceneRect.y();
QLineF const newLine(0, pointY, sceneRect.width(), pointY);
// checking whether the scene already has this line or not.
// if not (lineIsFound is false), then adding it
foreach (QLineF const &line, mLines) {
if (qAbs(line.y1() - newLine.y1()) < indistinguishabilitySpace
&& line.y2() == line.y1())
{
return;
}
}
mLines.push_back(newLine);
}
void SceneGridHandler::drawLineX(qreal pointX, QRectF const &sceneRect)
{
pointX -= sceneRect.x();
QLineF const newLine(pointX, 0, pointX, sceneRect.height());
// checking whether the scene already has this line or not.
// if not (lineIsFound is false), then adding it
foreach (QLineF const &line, mLines) {
if (qAbs(line.x1() - newLine.x1()) < indistinguishabilitySpace
&& line.x2() == line.x1())
{
return;
}
}
mLines.push_back(newLine);
}
// checking whether we should align with the vertical line or not
bool SceneGridHandler::makeJumpX(qreal deltaX, qreal pointX)
{
if (mSwitchAlignment && deltaX <= radiusJump) {
mNode->setX(pointX - mNode->contentsRect().x());
return true;
}
return false;
}
// checking whether we should align with the horizontal line or not
bool SceneGridHandler::makeJumpY(qreal deltaY, qreal pointY)
{
if (mSwitchAlignment && deltaY <= radiusJump) {
mNode->setY(pointY - mNode->contentsRect().y());
return true;
}
return false;
}
// build a vertical line: draw it and check for alignment
void SceneGridHandler::buildLineX(qreal deltaX
, qreal pointX, qreal correctionX, qreal &myX1, qreal &myX2, QRectF const &sceneRect)
{
if (deltaX > radius) {
return;
}
if (mShowAlignment) {
drawLineX(pointX, sceneRect);
}
if (makeJumpX(deltaX, pointX - correctionX)) {
myX1 = recalculateX1();
myX2 = recalculateX2(myX1);
}
}
// build a horizontal line: draw it and check for alignment
void SceneGridHandler::buildLineY(qreal deltaY
, qreal pointY, qreal correctionY, qreal &myY1, qreal &myY2, QRectF const &sceneRect)
{
if (deltaY > radius) {
return;
}
if (mShowAlignment) {
drawLineY(pointY, sceneRect);
}
if (makeJumpY(deltaY, pointY - correctionY)) {
myY1 = recalculateY1();
myY2 = recalculateY2(myY1);
}
}
qreal SceneGridHandler::recalculateX1() const
{
return mNode->scenePos().x() + mNode->boundingRect().x();
}
qreal SceneGridHandler::recalculateX2(qreal myX1) const
{
return myX1 + mNode->boundingRect().width();
}
qreal SceneGridHandler::recalculateY1() const
{
return mNode->scenePos().y() + mNode->boundingRect().y();
}
qreal SceneGridHandler::recalculateY2(qreal myY1) const
{
return myY1 + mNode->boundingRect().height();
}
qreal SceneGridHandler::alignedCoordinate(qreal coord, int coef, int indexGrid)
{
int const coefSign = coef != 0 ? coef / qAbs(coef) : 0;
if (qAbs(qAbs(coord) - qAbs(coef) * indexGrid) <= indexGrid / 2) {
return coef * indexGrid;
} else if (qAbs(qAbs(coord) - (qAbs(coef) + 1) * indexGrid) < indexGrid / 2) {
return (coef + coefSign) * indexGrid;
}
return coord;
}
void SceneGridHandler::makeGridMovingX(qreal myX, int coef, int indexGrid)
{
mNode->setX(alignedCoordinate(myX, coef, indexGrid));
mNode->adjustLinks();
}
void SceneGridHandler::makeGridMovingY(qreal myY, int coef, int indexGrid)
{
mNode->setY(alignedCoordinate(myY, coef, indexGrid));
mNode->adjustLinks();
}
qreal SceneGridHandler::makeGridAlignment(qreal coord)
{
int const indexGrid = SettingsManager::value("IndexGrid").toInt();
int const coef = static_cast<int>(coord) / indexGrid;
return alignedCoordinate(coord, coef, indexGrid);
}
void SceneGridHandler::setShowAlignmentMode(bool mode)
{
mShowAlignment = mode;
}
void SceneGridHandler::setGridMode(bool mode)
{
mSwitchGrid = mode;
}
void SceneGridHandler::setAlignmentMode(bool mode)
{
mSwitchAlignment = mode;
}
QList<QGraphicsItem *> SceneGridHandler::getAdjancedNodes() const
{
QPointF const nodeScenePos = mNode->scenePos();
QRectF const contentsRect = mNode->contentsRect();
// verical
QList<QGraphicsItem *> listX = mNode->scene()->items(nodeScenePos.x(), 0
, contentsRect.width(), widthLineY
, Qt::IntersectsItemBoundingRect, Qt::SortOrder(), QTransform());
// horizontal
QList<QGraphicsItem *> listY = mNode->scene()->items(0, nodeScenePos.y()
, widthLineX, contentsRect.height()
, Qt::IntersectsItemBoundingRect, Qt::SortOrder(), QTransform());
return listX + listY;
}
void SceneGridHandler::alignToGrid()
{
if (!mSwitchGrid) {
return;
}
int const indexGrid = SettingsManager::value("IndexGrid").toInt();
QPointF const nodePos = mNode->pos();
QRectF const contentsRect = mNode->contentsRect();
qreal myX1 = nodePos.x() + contentsRect.x();
qreal myY1 = nodePos.y() + contentsRect.y();
int coefX = static_cast<int>(myX1) / indexGrid;
int coefY = static_cast<int>(myY1) / indexGrid;
makeGridMovingX(myX1, coefX, indexGrid);
makeGridMovingY(myY1, coefY, indexGrid);
}
void SceneGridHandler::drawGuides()
{
QPointF const nodeScenePos = mNode->scenePos();
QRectF const contentsRect = mNode->contentsRect();
QRectF const sceneRect = mNode->scene()->sceneRect();
delUnusedLines();
QList<QGraphicsItem *> list = getAdjancedNodes();
qreal myX1 = nodeScenePos.x() + contentsRect.x();
qreal myY1 = nodeScenePos.y() + contentsRect.y();
qreal myX2 = myX1 + contentsRect.width();
qreal myY2 = myY1 + contentsRect.height();
foreach (QGraphicsItem *graphicsItem, list) {
NodeElement *item = dynamic_cast<NodeElement *>(graphicsItem);
if (item == NULL || item->parentItem() != NULL || item == mNode) {
continue;
}
QPointF const point = item->scenePos();
QRectF const contents = item->contentsRect();
qreal const pointX1 = point.x() + contents.x() - spacing;
qreal const pointY1 = point.y() + contents.y() - spacing;
qreal const pointX2 = pointX1 + contents.width() + 2 * spacing;
qreal const pointY2 = pointY1 + contents.height() + 2 * spacing;
if (pointX1 != myX1 || pointY1 != myY1) {
qreal const deltaY1 = qAbs(pointY1 - myY1);
qreal const deltaY2 = qAbs(pointY2 - myY2);
qreal const deltaX1 = qAbs(pointX1 - myX1);
qreal const deltaX2 = qAbs(pointX2 - myX2);
buildLineY(deltaY1, pointY1, 0, myY1, myY2, sceneRect);
buildLineY(deltaY2, pointY2, contentsRect.height(), myY1, myY2, sceneRect);
buildLineX(deltaX1, pointX1, 0, myX1, myX2, sceneRect);
buildLineX(deltaX2, pointX2, contentsRect.width(), myX1, myX2, sceneRect);
buildLineY(qAbs(pointY1 - myY2), pointY1, contentsRect.height(), myY1, myY2, sceneRect);
buildLineX(qAbs(pointX1 - myX2), pointX1, contentsRect.width(), myX1, myX2, sceneRect);
buildLineY(qAbs(pointY2 - myY1), pointY2, 0, myY1, myY2, sceneRect);
buildLineX(qAbs(pointX2 - myX1), pointX2, 0, myX1, myX2, sceneRect);
}
}
if (mLines.size()) {
EditorViewScene *evScene = dynamic_cast<EditorViewScene *>(mNode->scene());
mGuidesPixmap = new QPixmap(sceneRect.width(), sceneRect.height());
mGuidesPixmap->fill(Qt::transparent);
QPainter painter(mGuidesPixmap);
painter.setPen(mGuidesPen);
painter.drawLines(mLines);
evScene->putOnForeground(mGuidesPixmap);
}
}
void SceneGridHandler::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
NodeElement *parItem = dynamic_cast<NodeElement*>(mNode->parentItem());
if (parItem) {
return;
}
foreach (QGraphicsItem *item, mNode->scene()->items()) {
NodeElement *e = dynamic_cast<NodeElement *>(item);
if (e && e->isSelected()) {
e->alignToGrid();
}
}
drawGuides();
mNode->adjustLinks();
}
<|endoftext|>
|
<commit_before>#ifndef VPP_ALGORITHMS_FILTERS_SCHARR_HH_
# define VPP_ALGORITHMS_FILTERS_SCHARR_HH_
# include <vpp/core/image2d.hh>
# include <vpp/core/vector.hh>
namespace vpp
{
template <typename U, typename V>
void scharr(const image2d<vector<U, 1>>& in, image2d<vector<V, 2>>& out)
{
assert(in.border() >= 1);
int nr = out.nrows();
int nc = out.ncols();
#pragma omp parallel for
for (int r = 0; r < nr; r++)
{
vector<V, 2>* out_row = &out(r, 0);
const vector<U, 1>* row1 = &in(r - 1, 0);
const vector<U, 1>* row2 = &in(r, 0);
const vector<U, 1>* row3 = &in(r + 1, 0);
#pragma omp simd
for (int c = 0; c < nc; c++)
{
out_row[c] = vector<V, 2>(
(3 * int(row1[c - 1][0]) +
10 * int(row2[c - 1][0]) +
3 * int(row3[c - 1][0])
-
3 * int(row1[c + 1][0]) -
10 * int(row2[c + 1][0]) -
3 * int(row3[c + 1][0])) / 32.f
,
(3 * int(row1[c - 1][0]) +
10 * int(row1[c][0]) +
3 * int(row1[c + 1][0])
-
3 * int(row3[c - 1][0]) -
10 * int(row3[c ][0]) -
3 * int(row3[c + 1][0])) / 32.f
);
}
}
}
};
#endif
<commit_msg>Fix scharr filter.<commit_after>#ifndef VPP_ALGORITHMS_FILTERS_SCHARR_HH_
# define VPP_ALGORITHMS_FILTERS_SCHARR_HH_
# include <vpp/core/image2d.hh>
# include <vpp/core/vector.hh>
namespace vpp
{
template <typename U, typename V>
void scharr(const image2d<vector<U, 1>>& in, image2d<vector<V, 2>>& out)
{
assert(in.border() >= 1);
int nr = out.nrows();
int nc = out.ncols();
#pragma omp parallel for
for (int r = 0; r < nr; r++)
{
vector<V, 2>* out_row = &out(r, 0);
const vector<U, 1>* row1 = &in(r - 1, 0);
const vector<U, 1>* row2 = &in(r, 0);
const vector<U, 1>* row3 = &in(r + 1, 0);
#pragma omp simd
for (int c = 0; c < nc; c++)
{
out_row[c] = vector<V, 2>(
(3 * int(row3[c - 1][0]) +
10 * int(row3[c][0]) +
3 * int(row3[c + 1][0])
-
3 * int(row1[c - 1][0]) -
10 * int(row1[c ][0]) -
3 * int(row1[c + 1][0])) / 32.f
,
(3 * int(row1[c + 1][0]) +
10 * int(row2[c + 1][0]) +
3 * int(row3[c + 1][0])
-
3 * int(row1[c - 1][0]) -
10 * int(row2[c - 1][0]) -
3 * int(row3[c - 1][0])) / 32.f
);
}
}
}
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "airbourne_board.h"
#include "rosflight.h"
#include "mavlink.h"
extern "C" {
/* The prototype shows it is a naked function - in effect this is just an
assembly function. */
void HardFault_Handler( void ) __attribute__( ( naked ) );
void reset(bool);
/* The fault handler implementation calls a function called
prvGetRegistersFromStack(). */
void HardFault_Handler(void)
{
__asm volatile
(
" tst lr, #4 \n"
" ite eq \n"
" mrseq r0, msp \n"
" mrsne r0, psp \n"
" ldr r1, [r0, #24] \n"
" ldr r2, handler2_address_const \n"
" bx r2 \n"
" handler2_address_const: .word prvGetRegistersFromStack \n"
);
}
void prvGetRegistersFromStack( uint32_t *pulFaultStackAddress )
{
/* These are volatile to try and prevent the compiler/linker optimising them
away as the variables never actually get used. If the debugger won't show the
values of the variables, make them global my moving their declaration outside
of this function. */
volatile uint32_t r0;
volatile uint32_t r1;
volatile uint32_t r2;
volatile uint32_t r3;
volatile uint32_t r12;
volatile uint32_t lr; /* Link register. */
volatile uint32_t pc; /* Program counter. */
volatile uint32_t psr;/* Program status register. */
r0 = pulFaultStackAddress[ 0 ];
r1 = pulFaultStackAddress[ 1 ];
r2 = pulFaultStackAddress[ 2 ];
r3 = pulFaultStackAddress[ 3 ];
r12 = pulFaultStackAddress[ 4 ];
lr = pulFaultStackAddress[ 5 ];
pc = pulFaultStackAddress[ 6 ];
psr = pulFaultStackAddress[ 7 ];
// avoid compiler warnings about unused variables
(void) r0;
(void) r1;
(void) r2;
(void) r3;
(void) r12;
(void) lr;
(void) pc;
(void) psr;
/* When the following line is hit, the variables contain the register values. */
//reset(false);
NVIC_SystemReset();
}
void NMI_Handler()
{
while(1) {}
}
void MemManage_Handler()
{
while(1) {}
}
void BusFault_Handler()
{
while(1) {}
}
void UsageFault_Handler()
{
while(1) {}
}
void WWDG_IRQHandler()
{
while(1) {}
}
}
void reset(bool hard_reset)
{
rosflight_firmware::AirbourneBoard board;
rosflight_firmware::Mavlink mavlink(board);
rosflight_firmware::ROSflight firmware(board, mavlink);
board.init_board();
firmware.init(hard_reset);
while (true)
{
firmware.run();
if(board.clock_micros()/5e6>1e6)
{
void(*crashPtr)()=nullptr;
crashPtr();
}
}
}
int main(void)
{
reset(true);
return 0;
}
<commit_msg>Remove soft reset abilities<commit_after>/*
* Copyright (c) 2017, James Jackson and Daniel Koch, BYU MAGICC Lab
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "airbourne_board.h"
#include "rosflight.h"
#include "mavlink.h"
extern "C" {
/* The prototype shows it is a naked function - in effect this is just an
assembly function. */
void HardFault_Handler( void ) __attribute__( ( naked ) );
void reset(bool);
/* The fault handler implementation calls a function called
prvGetRegistersFromStack(). */
void HardFault_Handler(void)
{
__asm volatile
(
" tst lr, #4 \n"
" ite eq \n"
" mrseq r0, msp \n"
" mrsne r0, psp \n"
" ldr r1, [r0, #24] \n"
" ldr r2, handler2_address_const \n"
" bx r2 \n"
" handler2_address_const: .word prvGetRegistersFromStack \n"
);
}
void prvGetRegistersFromStack( uint32_t *pulFaultStackAddress )
{
/* These are volatile to try and prevent the compiler/linker optimising them
away as the variables never actually get used. If the debugger won't show the
values of the variables, make them global my moving their declaration outside
of this function. */
volatile uint32_t r0;
volatile uint32_t r1;
volatile uint32_t r2;
volatile uint32_t r3;
volatile uint32_t r12;
volatile uint32_t lr; /* Link register. */
volatile uint32_t pc; /* Program counter. */
volatile uint32_t psr;/* Program status register. */
r0 = pulFaultStackAddress[ 0 ];
r1 = pulFaultStackAddress[ 1 ];
r2 = pulFaultStackAddress[ 2 ];
r3 = pulFaultStackAddress[ 3 ];
r12 = pulFaultStackAddress[ 4 ];
lr = pulFaultStackAddress[ 5 ];
pc = pulFaultStackAddress[ 6 ];
psr = pulFaultStackAddress[ 7 ];
// avoid compiler warnings about unused variables
(void) r0;
(void) r1;
(void) r2;
(void) r3;
(void) r12;
(void) lr;
(void) pc;
(void) psr;
/* When the following line is hit, the variables contain the register values. */
//reset(false);
NVIC_SystemReset();
}
void NMI_Handler()
{
while(1) {}
}
void MemManage_Handler()
{
while(1) {}
}
void BusFault_Handler()
{
while(1) {}
}
void UsageFault_Handler()
{
while(1) {}
}
void WWDG_IRQHandler()
{
while(1) {}
}
}
//Currently soft resets are not supported
void reset(bool hard_reset)
{
rosflight_firmware::AirbourneBoard board;
rosflight_firmware::Mavlink mavlink(board);
rosflight_firmware::ROSflight firmware(board, mavlink);
board.init_board();
firmware.init();
while (true)
{
firmware.run();
if(board.clock_micros()/5e6>1e6)
{
void(*crashPtr)()=nullptr;
crashPtr();
}
}
}
int main(void)
{
reset(true);
return 0;
}
<|endoftext|>
|
<commit_before>// The MIT License (MIT)
// Copyright (c) 2014 Rapptz
// 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.
#ifndef JSONPP_VALUE_HPP
#define JSONPP_VALUE_HPP
#include "type_traits.hpp"
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <cassert>
#include <memory>
namespace json {
inline namespace v1 {
struct value {
public:
using object = std::map<std::string, value>;
using array = std::vector<value>;
private:
union storage_t {
double number;
bool boolean;
std::string* str;
array* arr;
object* obj;
} storage;
type storage_type;
void copy(const value& other) {
switch(other.storage_type) {
case type::array:
storage.arr = new array(*(other.storage.arr));
break;
case type::string:
storage.str = new std::string(*(other.storage.str));
break;
case type::object:
storage.obj = new object(*(other.storage.obj));
break;
case type::number:
storage.number = other.storage.number;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
default:
break;
}
storage_type = other.storage_type;
}
public:
value() noexcept: storage_type(type::null) {}
value(null) noexcept: storage_type(type::null) {}
~value() {
clear();
}
value(double v) noexcept: storage_type(type::number) {
storage.number = v;
}
template<typename T, EnableIf<is_bool<T>> = 0>
value(const T& b) noexcept: storage_type(type::boolean) {
storage.boolean = b;
}
template<typename T, EnableIf<is_string<T>> = 0>
value(const T& str): storage_type(type::string) {
storage.str = new std::string(str);
}
value(const array& arr): storage_type(type::array) {
storage.arr = new array(arr);
}
value(const object& obj): storage_type(type::object) {
storage.obj = new object(obj);
}
value(std::initializer_list<array::value_type> l): storage_type(type::array) {
storage.arr = new array(l.begin(), l.end());
}
value(const value& other) {
copy(other);
}
value(value&& other) noexcept {
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
}
value& operator=(const value& other) noexcept {
if(this != &other) {
clear();
copy(other);
}
return *this;
}
value& operator=(value&& other) {
if(this != &other) {
clear();
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
}
return *this;
}
void clear() noexcept {
switch(storage_type) {
case type::array:
delete storage.arr;
break;
case type::string:
delete storage.str;
break;
case type::object:
delete storage.obj;
break;
default:
break;
}
storage_type = type::null;
}
std::string to_string(unsigned precision = 6) const {
switch(storage_type) {
case type::null:
return "null";
case type::number: {
char buffer[328];
std::snprintf(buffer, 328, "%.*g", precision, storage.number);
return buffer;
}
case type::boolean:
return storage.boolean ? "true" : "false";
case type::string:
return '"' + *(storage.str) + '"';
case type::array: {
std::ostringstream ss;
ss.precision(precision);
ss << "[";
auto first = storage.arr->begin();
auto last = storage.arr->end();
if(first != last) {
ss << first->to_string(precision);
++first;
}
while(first != last) {
ss << ',' << first->to_string(precision);
++first;
}
ss << "]";
return ss.str();
}
case type::object: {
std::ostringstream ss;
ss.precision(precision);
ss << "{";
auto begin = storage.obj->begin();
auto end = storage.obj->end();
if(begin != end) {
ss << '"' << begin->first << "\":" << begin->second.to_string(precision);
++begin;
}
while(begin != end) {
ss << ",\"" << begin->first << "\":" << begin->second.to_string(precision);
++begin;
}
ss << "}";
return ss.str();
}
}
return "";
}
template<typename T, EnableIf<is_string<T>> = 0>
bool is() const noexcept {
return storage_type == type::string;
}
template<typename T, EnableIf<is_null<T>> = 0>
bool is() const noexcept {
return storage_type == type::null;
}
template<typename T, EnableIf<is_number<T>> = 0>
bool is() const noexcept {
return storage_type == type::number;
}
template<typename T, EnableIf<is_bool<T>> = 0>
bool is() const noexcept {
return storage_type == type::boolean;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
bool is() const noexcept {
return storage_type == type::object;
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
bool is() const noexcept {
return storage_type == type::array;
}
template<typename T, EnableIf<std::is_same<T, const char*>> = 0>
T as() const noexcept {
assert(is<T>());
return storage.str->c_str();
}
template<typename T, EnableIf<std::is_same<T, std::string>> = 0>
T as() const noexcept {
assert(is<T>());
return *(storage.str);
}
template<typename T, EnableIf<is_null<T>> = 0>
T as() const noexcept {
assert(is<T>());
return {};
}
template<typename T, EnableIf<is_bool<T>> = 0>
T as() const noexcept {
assert(is<T>());
return storage.boolean;
}
template<typename T, EnableIf<is_number<T>> = 0>
T as() const noexcept {
assert(is<T>());
return storage.number;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
T as() const noexcept {
assert(is<T>());
return *(storage.obj);
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
T as() const noexcept {
assert(is<T>());
return *(storage.arr);
}
template<typename T>
T as(Identity<T>&& def) const noexcept {
return is<T>() ? as<T>() : std::forward<T>(def);
}
};
using array = value::array;
using object = value::object;
namespace impl {
inline std::string prettify(const value& v, unsigned spaces, unsigned precision, unsigned current_indent);
inline void indent(std::ostringstream& ss, unsigned& current_indent) {
for(unsigned i = 0; i < current_indent; ++i) {
ss << ' ';
}
}
inline std::string prettify_object(const value& v, unsigned spaces, unsigned precision, unsigned& current_indent) {
std::ostringstream ss;
current_indent += spaces;
auto&& obj = v.as<object>();
auto begin = obj.begin();
auto end = obj.end();
ss << '{';
if(begin != end) {
ss << '\n';
indent(ss, current_indent);
ss << '"' << begin->first << "\": " << prettify(begin->second, spaces, precision, current_indent);
++begin;
}
while(begin != end) {
ss << ",\n";
indent(ss, current_indent);
ss << '"' << begin->first << "\": " << prettify(begin->second, spaces, precision, current_indent);
++begin;
}
current_indent -= spaces;
ss << "\n}";
return ss.str();
}
inline std::string prettify_array(const value& v, unsigned /*spaces*/, unsigned precision) {
std::ostringstream ss;
ss.precision(precision);
ss << "[";
auto&& arr = v.as<array>();
auto first = arr.begin();
auto last = arr.end();
if(first != last) {
ss << first->to_string(precision);
++first;
}
while(first != last) {
ss << ", " << first->to_string(precision);
++first;
}
ss << "]";
return ss.str();
}
inline std::string prettify(const value& v, unsigned spaces, unsigned precision, unsigned current_indent) {
if(v.is<double>() || v.is<std::string>() || v.is<bool>() || v.is<null>()) {
return v.to_string(precision);
}
if(v.is<object>()) {
return prettify_object(v, spaces, precision, current_indent);
}
else if(v.is<array>()) {
return prettify_array(v, spaces, precision);
}
throw std::runtime_error("invalid value passed");
}
} // impl
inline std::string prettify(const value& v, unsigned spaces = 4, unsigned precision = 6) {
return impl::prettify(v, spaces, precision, 0);
}
} // v1
} // json
#endif // JSONPP_VALUE_HPP
<commit_msg>Remove prettifying for now<commit_after>// The MIT License (MIT)
// Copyright (c) 2014 Rapptz
// 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.
#ifndef JSONPP_VALUE_HPP
#define JSONPP_VALUE_HPP
#include "type_traits.hpp"
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <cassert>
#include <memory>
namespace json {
inline namespace v1 {
struct value {
public:
using object = std::map<std::string, value>;
using array = std::vector<value>;
private:
union storage_t {
double number;
bool boolean;
std::string* str;
array* arr;
object* obj;
} storage;
type storage_type;
void copy(const value& other) {
switch(other.storage_type) {
case type::array:
storage.arr = new array(*(other.storage.arr));
break;
case type::string:
storage.str = new std::string(*(other.storage.str));
break;
case type::object:
storage.obj = new object(*(other.storage.obj));
break;
case type::number:
storage.number = other.storage.number;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
default:
break;
}
storage_type = other.storage_type;
}
public:
value() noexcept: storage_type(type::null) {}
value(null) noexcept: storage_type(type::null) {}
~value() {
clear();
}
value(double v) noexcept: storage_type(type::number) {
storage.number = v;
}
template<typename T, EnableIf<is_bool<T>> = 0>
value(const T& b) noexcept: storage_type(type::boolean) {
storage.boolean = b;
}
template<typename T, EnableIf<is_string<T>> = 0>
value(const T& str): storage_type(type::string) {
storage.str = new std::string(str);
}
value(const array& arr): storage_type(type::array) {
storage.arr = new array(arr);
}
value(const object& obj): storage_type(type::object) {
storage.obj = new object(obj);
}
value(std::initializer_list<array::value_type> l): storage_type(type::array) {
storage.arr = new array(l.begin(), l.end());
}
value(const value& other) {
copy(other);
}
value(value&& other) noexcept {
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
}
value& operator=(const value& other) noexcept {
if(this != &other) {
clear();
copy(other);
}
return *this;
}
value& operator=(value&& other) {
if(this != &other) {
clear();
switch(other.storage_type) {
case type::array:
storage.arr = other.storage.arr;
other.storage.arr = nullptr;
break;
case type::string:
storage.str = other.storage.str;
other.storage.str = nullptr;
break;
case type::object:
storage.obj = other.storage.obj;
other.storage.obj = nullptr;
break;
case type::boolean:
storage.boolean = other.storage.boolean;
break;
case type::number:
storage.number = other.storage.number;
break;
default:
break;
}
storage_type = other.storage_type;
other.storage_type = type::null;
}
return *this;
}
void clear() noexcept {
switch(storage_type) {
case type::array:
delete storage.arr;
break;
case type::string:
delete storage.str;
break;
case type::object:
delete storage.obj;
break;
default:
break;
}
storage_type = type::null;
}
std::string to_string(unsigned precision = 6) const {
switch(storage_type) {
case type::null:
return "null";
case type::number: {
char buffer[328];
std::snprintf(buffer, 328, "%.*g", precision, storage.number);
return buffer;
}
case type::boolean:
return storage.boolean ? "true" : "false";
case type::string:
return '"' + *(storage.str) + '"';
case type::array: {
std::ostringstream ss;
ss.precision(precision);
ss << "[";
auto first = storage.arr->begin();
auto last = storage.arr->end();
if(first != last) {
ss << first->to_string(precision);
++first;
}
while(first != last) {
ss << ',' << first->to_string(precision);
++first;
}
ss << "]";
return ss.str();
}
case type::object: {
std::ostringstream ss;
ss.precision(precision);
ss << "{";
auto begin = storage.obj->begin();
auto end = storage.obj->end();
if(begin != end) {
ss << '"' << begin->first << "\":" << begin->second.to_string(precision);
++begin;
}
while(begin != end) {
ss << ",\"" << begin->first << "\":" << begin->second.to_string(precision);
++begin;
}
ss << "}";
return ss.str();
}
}
return "";
}
template<typename T, EnableIf<is_string<T>> = 0>
bool is() const noexcept {
return storage_type == type::string;
}
template<typename T, EnableIf<is_null<T>> = 0>
bool is() const noexcept {
return storage_type == type::null;
}
template<typename T, EnableIf<is_number<T>> = 0>
bool is() const noexcept {
return storage_type == type::number;
}
template<typename T, EnableIf<is_bool<T>> = 0>
bool is() const noexcept {
return storage_type == type::boolean;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
bool is() const noexcept {
return storage_type == type::object;
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
bool is() const noexcept {
return storage_type == type::array;
}
template<typename T, EnableIf<std::is_same<T, const char*>> = 0>
T as() const noexcept {
assert(is<T>());
return storage.str->c_str();
}
template<typename T, EnableIf<std::is_same<T, std::string>> = 0>
T as() const noexcept {
assert(is<T>());
return *(storage.str);
}
template<typename T, EnableIf<is_null<T>> = 0>
T as() const noexcept {
assert(is<T>());
return {};
}
template<typename T, EnableIf<is_bool<T>> = 0>
T as() const noexcept {
assert(is<T>());
return storage.boolean;
}
template<typename T, EnableIf<is_number<T>> = 0>
T as() const noexcept {
assert(is<T>());
return storage.number;
}
template<typename T, EnableIf<std::is_same<T, object>> = 0>
T as() const noexcept {
assert(is<T>());
return *(storage.obj);
}
template<typename T, EnableIf<std::is_same<T, array>> = 0>
T as() const noexcept {
assert(is<T>());
return *(storage.arr);
}
template<typename T>
T as(Identity<T>&& def) const noexcept {
return is<T>() ? as<T>() : std::forward<T>(def);
}
};
using array = value::array;
using object = value::object;
} // v1
} // json
#endif // JSONPP_VALUE_HPP
<|endoftext|>
|
<commit_before>#include "Navigator.h"
Navigator* g_pNavigator;
void onMouseNavigator(int event, int x, int y, int flags, void* userdata)
{
g_pNavigator->handleMouse(event, x, y, flags);
}
namespace kai
{
Navigator::Navigator()
{
AppBase();
m_pCamFront = NULL;
m_pAP = NULL;
m_pMavlink = NULL;
m_pCascade = NULL;
m_pFlow = NULL;
m_pROITracker = NULL;
m_pDD = NULL;
m_pMD = NULL;
m_pUniverse = NULL;
m_pFCN = NULL;
m_pSSD = NULL;
m_pFrame = NULL;
}
Navigator::~Navigator()
{
}
bool Navigator::start(JSON* pJson)
{
//TODO: Caffe set data to GPU directly
//TODO: Solve caffe ROI in DepthDetector
//TODO: Optimize FCN
g_pNavigator = this;
int FPS;
string camName;
CHECK_INFO(pJson->getVal("APP_SHOW_SCREEN", &m_bShowScreen));
CHECK_INFO(pJson->getVal("APP_FULL_SCREEN", &m_bFullScreen));
CHECK_INFO(pJson->getVal("APP_WAIT_KEY", &m_waitKey));
m_pFrame = new Frame();
//Init Camera
CHECK_INFO(pJson->getVal("CAM_MAIN_NAME", &camName));
if (camName != "video")
{
m_pCamFront = new _Stream();
CHECK_FATAL(m_pCamFront->init(pJson, camName));
m_pCamFront->start();
}
//Init ROI Tracker
FPS=0;
CHECK_INFO(pJson->getVal("ROITRACKER_MAIN_FPS", &FPS));
if (FPS > 0)
{
m_pROITracker = new _ROITracker();
m_pROITracker->init(pJson, "MAIN");
m_pROITracker->m_pCamStream = m_pCamFront;
m_pROITracker->start();
}
//Init Marker Detector
FPS=0;
CHECK_INFO(pJson->getVal("MARKER_LANDING_FPS", &FPS));
if (FPS > 0)
{
m_pMD = new _Bullseye();
m_pMD->init(pJson, "LANDING");
m_pMD->m_pCamStream = m_pCamFront;
m_pCamFront->m_bGray = true;
m_pCamFront->m_bHSV = true;
m_pMD->start();
}
//Init AprilTags Detector
FPS=0;
CHECK_INFO(pJson->getVal("APRILTAGS_LANDING_FPS", &FPS));
if (FPS > 0)
{
m_pAT = new _AprilTags();
m_pAT->init(pJson, "LANDING");
m_pAT->m_pCamStream = m_pCamFront;
m_pAT->start();
}
//Init Mavlink
FPS=0;
CHECK_INFO(pJson->getVal("SERIALPORT_MAVLINK_FPS", &FPS));
if (FPS > 0)
{
m_pMavlink = new _Mavlink();
CHECK_FATAL(m_pMavlink->setup(pJson, "MAVLINK"));
m_pMavlink->start();
}
//Init Autopilot
FPS=0;
CHECK_INFO(pJson->getVal("AUTOPILOT_MAIN_FPS", &FPS));
if (FPS > 0)
{
m_pAP = new _AutoPilot();
CHECK_FATAL(m_pAP->init(pJson, "MAIN"));
m_pAP->m_pMavlink = m_pMavlink;
m_pAP->m_pROITracker = m_pROITracker;
m_pAP->m_pMD = m_pMD;
m_pAP->m_pAT = m_pAT;
m_pAP->start();
}
//Init Universe
FPS=0;
CHECK_INFO(pJson->getVal("UNIVERSE_FPS", &FPS));
if (FPS > 0)
{
m_pUniverse = new _Universe();
m_pUniverse->init(pJson);
m_pUniverse->start();
}
//Init SSD
FPS=0;
CHECK_INFO(pJson->getVal("CAFFE_SSD_FPS", &FPS));
if (FPS > 0)
{
m_pSSD = new _SSD();
m_pSSD->init(pJson, "_MAIN");
m_pSSD->m_pCamStream = m_pCamFront;
m_pSSD->m_pUniverse = m_pUniverse;
m_pSSD->start();
}
//Init Optical Flow
FPS=0;
CHECK_INFO(pJson->getVal("FLOW_FRONTL_FPS", &FPS));
if (FPS > 0)
{
m_pFlow = new _Flow();
CHECK_FATAL(m_pFlow->init(pJson, "FRONTL"));
m_pFlow->m_pCamStream = m_pCamFront;
m_pCamFront->m_bGray = true;
m_pFlow->start();
}
//Init Depth Object Detector
FPS=0;
CHECK_INFO(pJson->getVal("DEPTH_OBJDETECTOR_FPS", &FPS));
if (FPS > 0)
{
m_pDD = new _Depth();
CHECK_FATAL(m_pDD->init(pJson, "FRONTL"));
m_pDD->m_pCamStream = m_pCamFront;
m_pDD->m_pUniverse = m_pUniverse;
m_pDD->m_pFlow = m_pFlow;
m_pDD->start();
}
//Init FCN
FPS=0;
CHECK_INFO(pJson->getVal("FCN_FPS", &FPS));
if (FPS > 0)
{
m_pFCN = new _FCN();
m_pFCN->init("",pJson);
m_pFCN->m_pCamStream = m_pCamFront;
m_pFCN->start();
}
//UI thread
m_bRun = true;
if (m_bShowScreen)
{
namedWindow(APP_NAME, CV_WINDOW_NORMAL);
if (m_bFullScreen)
{
setWindowProperty(APP_NAME,
CV_WND_PROP_FULLSCREEN,
CV_WINDOW_FULLSCREEN);
}
setMouseCallback(APP_NAME, onMouseNavigator, NULL);
}
while (m_bRun)
{
// Mavlink_Messages mMsg;
// mMsg = m_pMavlink->current_messages;
// m_pCamFront->m_pCamL->m_bGimbal = true;
// m_pCamFront->m_pCamL->setAttitude(mMsg.attitude.roll, 0, mMsg.time_stamps.attitude);
if (m_bShowScreen)
{
draw();
}
//Handle key input
m_key = waitKey(m_waitKey);
handleKey(m_key);
}
STOP(m_pAP);
STOP(m_pMavlink);
STOP(m_pROITracker);
STOP(m_pMD);
STOP(m_pUniverse);
STOP(m_pDD);
STOP(m_pFlow);
STOP(m_pFCN);
m_pMavlink->complete();
m_pMavlink->close();
COMPLETE(m_pAP);
COMPLETE(m_pROITracker);
COMPLETE(m_pMD);
COMPLETE(m_pUniverse);
COMPLETE(m_pDD);
COMPLETE(m_pFlow);
COMPLETE(m_pFCN);
COMPLETE(m_pCamFront);
RELEASE(m_pMavlink);
RELEASE(m_pCamFront);
RELEASE(m_pROITracker);
RELEASE(m_pAP);
RELEASE(m_pMD);
RELEASE(m_pUniverse);
RELEASE(m_pDD);
RELEASE(m_pFlow);
RELEASE(m_pFCN);
return 0;
}
void Navigator::draw(void)
{
iVector4 textPos;
textPos.m_x = 15;
textPos.m_y = 20;
textPos.m_w = 20;
textPos.m_z = 500;
if(m_pCamFront)
{
if(!m_pCamFront->draw(m_pFrame, &textPos))return;
}
if(m_pAP)
{
m_pAP->draw(m_pFrame, &textPos);
}
if(m_pAT)
{
m_pAT->draw(m_pFrame, &textPos);
}
if(m_pUniverse)
{
m_pUniverse->draw(m_pFrame, &textPos);
}
if(m_pSSD)
{
m_pSSD->draw(m_pFrame, &textPos);
}
if(m_pMavlink)
{
m_pMavlink->draw(m_pFrame, &textPos);
}
if(m_pFCN)
{
m_pFCN->draw(m_pFrame, &textPos);
}
imshow(APP_NAME, *m_pFrame->getCMat());
}
void Navigator::handleKey(int key)
{
switch (key)
{
case 27:
m_bRun = false; //ESC
break;
default:
break;
}
}
void Navigator::handleMouse(int event, int x, int y, int flags)
{
switch (event)
{
case EVENT_LBUTTONDOWN:
break;
case EVENT_LBUTTONUP:
break;
case EVENT_MOUSEMOVE:
break;
case EVENT_RBUTTONDOWN:
break;
default:
break;
}
}
}
<commit_msg>Bug fix<commit_after>#include "Navigator.h"
Navigator* g_pNavigator;
void onMouseNavigator(int event, int x, int y, int flags, void* userdata)
{
g_pNavigator->handleMouse(event, x, y, flags);
}
namespace kai
{
Navigator::Navigator()
{
AppBase();
m_pCamFront = NULL;
m_pAP = NULL;
m_pMavlink = NULL;
m_pCascade = NULL;
m_pFlow = NULL;
m_pROITracker = NULL;
m_pDD = NULL;
m_pMD = NULL;
m_pUniverse = NULL;
m_pFCN = NULL;
m_pSSD = NULL;
m_pFrame = NULL;
m_pAT = NULL;
}
Navigator::~Navigator()
{
}
bool Navigator::start(JSON* pJson)
{
//TODO: Caffe set data to GPU directly
//TODO: Solve caffe ROI in DepthDetector
//TODO: Optimize FCN
g_pNavigator = this;
int FPS;
string camName;
CHECK_INFO(pJson->getVal("APP_SHOW_SCREEN", &m_bShowScreen));
CHECK_INFO(pJson->getVal("APP_FULL_SCREEN", &m_bFullScreen));
CHECK_INFO(pJson->getVal("APP_WAIT_KEY", &m_waitKey));
m_pFrame = new Frame();
//Init Camera
CHECK_INFO(pJson->getVal("CAM_MAIN_NAME", &camName));
if (camName != "video")
{
m_pCamFront = new _Stream();
CHECK_FATAL(m_pCamFront->init(pJson, camName));
m_pCamFront->start();
}
//Init ROI Tracker
FPS=0;
CHECK_INFO(pJson->getVal("ROITRACKER_MAIN_FPS", &FPS));
if (FPS > 0)
{
m_pROITracker = new _ROITracker();
m_pROITracker->init(pJson, "MAIN");
m_pROITracker->m_pCamStream = m_pCamFront;
m_pROITracker->start();
}
//Init Marker Detector
FPS=0;
CHECK_INFO(pJson->getVal("MARKER_LANDING_FPS", &FPS));
if (FPS > 0)
{
m_pMD = new _Bullseye();
m_pMD->init(pJson, "LANDING");
m_pMD->m_pCamStream = m_pCamFront;
m_pCamFront->m_bGray = true;
m_pCamFront->m_bHSV = true;
m_pMD->start();
}
//Init AprilTags Detector
FPS=0;
CHECK_INFO(pJson->getVal("APRILTAGS_LANDING_FPS", &FPS));
if (FPS > 0)
{
m_pAT = new _AprilTags();
m_pAT->init(pJson, "LANDING");
m_pAT->m_pCamStream = m_pCamFront;
m_pAT->start();
}
//Init Mavlink
FPS=0;
CHECK_INFO(pJson->getVal("SERIALPORT_MAVLINK_FPS", &FPS));
if (FPS > 0)
{
m_pMavlink = new _Mavlink();
CHECK_FATAL(m_pMavlink->setup(pJson, "MAVLINK"));
m_pMavlink->start();
}
//Init Autopilot
FPS=0;
CHECK_INFO(pJson->getVal("AUTOPILOT_MAIN_FPS", &FPS));
if (FPS > 0)
{
m_pAP = new _AutoPilot();
CHECK_FATAL(m_pAP->init(pJson, "MAIN"));
m_pAP->m_pMavlink = m_pMavlink;
m_pAP->m_pROITracker = m_pROITracker;
m_pAP->m_pMD = m_pMD;
m_pAP->m_pAT = m_pAT;
m_pAP->start();
}
//Init Universe
FPS=0;
CHECK_INFO(pJson->getVal("UNIVERSE_FPS", &FPS));
if (FPS > 0)
{
m_pUniverse = new _Universe();
m_pUniverse->init(pJson);
m_pUniverse->start();
}
//Init SSD
FPS=0;
CHECK_INFO(pJson->getVal("CAFFE_SSD_FPS", &FPS));
if (FPS > 0)
{
m_pSSD = new _SSD();
m_pSSD->init(pJson, "_MAIN");
m_pSSD->m_pCamStream = m_pCamFront;
m_pSSD->m_pUniverse = m_pUniverse;
m_pSSD->start();
}
//Init Optical Flow
FPS=0;
CHECK_INFO(pJson->getVal("FLOW_FRONTL_FPS", &FPS));
if (FPS > 0)
{
m_pFlow = new _Flow();
CHECK_FATAL(m_pFlow->init(pJson, "FRONTL"));
m_pFlow->m_pCamStream = m_pCamFront;
m_pCamFront->m_bGray = true;
m_pFlow->start();
}
//Init Depth Object Detector
FPS=0;
CHECK_INFO(pJson->getVal("DEPTH_OBJDETECTOR_FPS", &FPS));
if (FPS > 0)
{
m_pDD = new _Depth();
CHECK_FATAL(m_pDD->init(pJson, "FRONTL"));
m_pDD->m_pCamStream = m_pCamFront;
m_pDD->m_pUniverse = m_pUniverse;
m_pDD->m_pFlow = m_pFlow;
m_pDD->start();
}
//Init FCN
FPS=0;
CHECK_INFO(pJson->getVal("FCN_FPS", &FPS));
if (FPS > 0)
{
m_pFCN = new _FCN();
m_pFCN->init("",pJson);
m_pFCN->m_pCamStream = m_pCamFront;
m_pFCN->start();
}
//UI thread
m_bRun = true;
if (m_bShowScreen)
{
namedWindow(APP_NAME, CV_WINDOW_NORMAL);
if (m_bFullScreen)
{
setWindowProperty(APP_NAME,
CV_WND_PROP_FULLSCREEN,
CV_WINDOW_FULLSCREEN);
}
setMouseCallback(APP_NAME, onMouseNavigator, NULL);
}
while (m_bRun)
{
// Mavlink_Messages mMsg;
// mMsg = m_pMavlink->current_messages;
// m_pCamFront->m_pCamL->m_bGimbal = true;
// m_pCamFront->m_pCamL->setAttitude(mMsg.attitude.roll, 0, mMsg.time_stamps.attitude);
if (m_bShowScreen)
{
draw();
}
//Handle key input
m_key = waitKey(m_waitKey);
handleKey(m_key);
}
STOP(m_pAP);
STOP(m_pMavlink);
STOP(m_pROITracker);
STOP(m_pMD);
STOP(m_pUniverse);
STOP(m_pDD);
STOP(m_pFlow);
STOP(m_pFCN);
m_pMavlink->complete();
m_pMavlink->close();
COMPLETE(m_pAP);
COMPLETE(m_pROITracker);
COMPLETE(m_pMD);
COMPLETE(m_pUniverse);
COMPLETE(m_pDD);
COMPLETE(m_pFlow);
COMPLETE(m_pFCN);
COMPLETE(m_pCamFront);
RELEASE(m_pMavlink);
RELEASE(m_pCamFront);
RELEASE(m_pROITracker);
RELEASE(m_pAP);
RELEASE(m_pMD);
RELEASE(m_pUniverse);
RELEASE(m_pDD);
RELEASE(m_pFlow);
RELEASE(m_pFCN);
return 0;
}
void Navigator::draw(void)
{
iVector4 textPos;
textPos.m_x = 15;
textPos.m_y = 20;
textPos.m_w = 20;
textPos.m_z = 500;
if(m_pCamFront)
{
if(!m_pCamFront->draw(m_pFrame, &textPos))return;
}
if(m_pAP)
{
m_pAP->draw(m_pFrame, &textPos);
}
if(m_pAT)
{
m_pAT->draw(m_pFrame, &textPos);
}
if(m_pUniverse)
{
m_pUniverse->draw(m_pFrame, &textPos);
}
if(m_pSSD)
{
m_pSSD->draw(m_pFrame, &textPos);
}
if(m_pMavlink)
{
m_pMavlink->draw(m_pFrame, &textPos);
}
if(m_pFCN)
{
m_pFCN->draw(m_pFrame, &textPos);
}
imshow(APP_NAME, *m_pFrame->getCMat());
}
void Navigator::handleKey(int key)
{
switch (key)
{
case 27:
m_bRun = false; //ESC
break;
default:
break;
}
}
void Navigator::handleMouse(int event, int x, int y, int flags)
{
switch (event)
{
case EVENT_LBUTTONDOWN:
break;
case EVENT_LBUTTONUP:
break;
case EVENT_MOUSEMOVE:
break;
case EVENT_RBUTTONDOWN:
break;
default:
break;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlg_InsertLegend.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 00:27:22 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CHART2_DLG_INSERT_LEGEND_GRID_HXX
#define _CHART2_DLG_INSERT_LEGEND_GRID_HXX
// header for class ModalDialog
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
// header for class FixedLine
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
// header for class CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
// header for class SfxItemSet
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
/*************************************************************************
|*
|* Legenden-Dialog
|*
\************************************************************************/
class SchLegendDlg : public ModalDialog
{
private:
CheckBox aCbxShow;
RadioButton aRbtLeft;
RadioButton aRbtTop;
RadioButton aRbtRight;
RadioButton aRbtBottom;
FixedLine aFlLegend;
OKButton aBtnOK;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
const SfxItemSet& m_rInAttrs;
void Reset();
DECL_LINK (CbxClick, CheckBox *);
public:
SchLegendDlg(Window* pParent, const SfxItemSet& rInAttrs);
virtual ~SchLegendDlg();
void GetAttr(SfxItemSet& rOutAttrs);
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.3.12); FILE MERGED 2006/01/06 20:28:28 iha 1.3.12.1: added legendposition to wizard and restructured legend postiion control classes<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dlg_InsertLegend.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2007-05-22 17:58:55 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CHART2_DLG_INSERT_LEGEND_GRID_HXX
#define _CHART2_DLG_INSERT_LEGEND_GRID_HXX
// header for class ModalDialog
#ifndef _SV_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
// header for class CheckBox
#ifndef _SV_BUTTON_HXX
#include <vcl/button.hxx>
#endif
//for auto_ptr
#include <memory>
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
class LegendPositionResources;
class SchLegendDlg : public ModalDialog
{
private:
::std::auto_ptr< LegendPositionResources > m_apLegendPositionResources;
OKButton aBtnOK;
CancelButton aBtnCancel;
HelpButton aBtnHelp;
public:
SchLegendDlg( Window* pParent, const ::com::sun::star::uno::Reference<
::com::sun::star::uno::XComponentContext>& xCC );
virtual ~SchLegendDlg();
void init( const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xChartModel );
bool writeToModel( const ::com::sun::star::uno::Reference<
::com::sun::star::frame::XModel >& xChartModel ) const;
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include "gtest/gtest.h"
#include "TRint.h"
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;
TEST(TRint, UnrecognizedOptions)
{
// Create array of options.
// We need to create it as a dynamic array for the following reasons:
// - TRint constructor accepts a char** so we construct directly that type
// - TRint will modify this array, removing recognized options and leaving
// only unrecognized ones, so we can't create an std::vector and pass its
// data to TRint directly.
int argc{4};
char **argv = new char *[argc];
argv[0] = const_cast<char *>("-q");
argv[1] = const_cast<char *>("-z");
argv[2] = const_cast<char *>("--nonexistingoption");
argv[3] = const_cast<char *>("-b");
CaptureStderr();
// Unrecognized options will be printed to stderr
TRint app{"App", &argc, argv};
std::string trinterr = GetCapturedStderr();
const std::string expected{"root: unrecognized option '-z'\n"
"root: unrecognized option '--nonexistingoption'\n"
"Try 'root --help' for more information.\n"};
EXPECT_EQ(trinterr, expected);
// Properly delete the array
for (int i = 0; i < argc; i++) {
delete[] argv[i];
}
delete[] argv;
argv = nullptr;
}
<commit_msg>[core] Fix invalid pointer error in TRintTests.cxx<commit_after>#include <iostream>
#include <string>
#include "gtest/gtest.h"
#include "TRint.h"
using testing::internal::CaptureStderr;
using testing::internal::GetCapturedStderr;
TEST(TRint, UnrecognizedOptions)
{
// Create array of options.
// We need to create it as a dynamic array for the following reasons:
// - TRint constructor accepts a char** so we construct directly that type
// - TRint will modify this array, removing recognized options and leaving
// only unrecognized ones, so we can't create an std::vector and pass its
// data to TRint directly.
int argc{4};
char e1[]{"-q"};
char e2[]{"-z"};
char e3[]{"--nonexistingoption"};
char e4[]{"-b"};
char *argv[]{e1, e2, e3, e4};
CaptureStderr();
// Unrecognized options will be printed to stderr
TRint app{"App", &argc, argv};
std::string trinterr = GetCapturedStderr();
const std::string expected{"root: unrecognized option '-z'\n"
"root: unrecognized option '--nonexistingoption'\n"
"Try 'root --help' for more information.\n"};
EXPECT_EQ(trinterr, expected);
}
<|endoftext|>
|
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_OUTDATED_INDEX_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_OUTDATED_INDEX_HPP_
#include <map>
#include <set>
#include <string>
#include "clustering/administration/issues/issue.hpp"
#include "clustering/table_manager/multi_table_manager.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/pump_coro.hpp"
#include "containers/scoped.hpp"
#include "rdb_protocol/store.hpp"
class outdated_index_issue_t : public issue_t {
public:
typedef std::map<namespace_id_t, std::set<std::string> > index_map_t;
outdated_index_issue_t();
explicit outdated_index_issue_t(index_map_t indexes);
const datum_string_t &get_name() const { return outdated_index_issue_type; }
bool is_critical() const { return false; }
index_map_t indexes;
private:
bool build_info_and_description(
const metadata_t &metadata,
server_config_client_t *server_config_client,
table_meta_client_t *table_meta_client,
admin_identifier_format_t identifier_format,
ql::datum_t *info_out,
datum_string_t *description_out) const;
static const datum_string_t outdated_index_issue_type;
static const uuid_u base_issue_id;
};
class outdated_index_issue_tracker_t : public issue_tracker_t {
public:
outdated_index_issue_tracker_t(table_meta_client_t *_table_meta_client);
std::vector<scoped_ptr_t<issue_t> > get_issues(signal_t *interruptor) const;
static void log_outdated_indexes(multi_table_manager_t *multi_table_manager,
const cluster_semilattice_metadata_t &metadata,
signal_t *interruptor);
private:
table_meta_client_t *table_meta_client;
DISABLE_COPYING(outdated_index_issue_tracker_t);
};
#endif /* CLUSTERING_ADMINISTRATION_ISSUES_OUTDATED_INDEX_HPP_ */
<commit_msg>Missing explicit in outdated_index_issue_tracker_t<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CLUSTERING_ADMINISTRATION_ISSUES_OUTDATED_INDEX_HPP_
#define CLUSTERING_ADMINISTRATION_ISSUES_OUTDATED_INDEX_HPP_
#include <map>
#include <set>
#include <string>
#include "clustering/administration/issues/issue.hpp"
#include "clustering/table_manager/multi_table_manager.hpp"
#include "concurrency/one_per_thread.hpp"
#include "concurrency/pump_coro.hpp"
#include "containers/scoped.hpp"
#include "rdb_protocol/store.hpp"
class outdated_index_issue_t : public issue_t {
public:
typedef std::map<namespace_id_t, std::set<std::string> > index_map_t;
outdated_index_issue_t();
explicit outdated_index_issue_t(index_map_t indexes);
const datum_string_t &get_name() const { return outdated_index_issue_type; }
bool is_critical() const { return false; }
index_map_t indexes;
private:
bool build_info_and_description(
const metadata_t &metadata,
server_config_client_t *server_config_client,
table_meta_client_t *table_meta_client,
admin_identifier_format_t identifier_format,
ql::datum_t *info_out,
datum_string_t *description_out) const;
static const datum_string_t outdated_index_issue_type;
static const uuid_u base_issue_id;
};
class outdated_index_issue_tracker_t : public issue_tracker_t {
public:
explicit outdated_index_issue_tracker_t(table_meta_client_t *_table_meta_client);
std::vector<scoped_ptr_t<issue_t> > get_issues(signal_t *interruptor) const;
static void log_outdated_indexes(multi_table_manager_t *multi_table_manager,
const cluster_semilattice_metadata_t &metadata,
signal_t *interruptor);
private:
table_meta_client_t *table_meta_client;
DISABLE_COPYING(outdated_index_issue_tracker_t);
};
#endif /* CLUSTERING_ADMINISTRATION_ISSUES_OUTDATED_INDEX_HPP_ */
<|endoftext|>
|
<commit_before>// csabbg_testdriver.t.cpp -*-C++-*-
#include <bsl_cstdlib.h>
#include <bsl_iostream.h>
namespace bde_verify { }
using namespace bde_verify;
using bsl::cout;
using bsl::cerr;
using bsl::endl;
using bsl::flush;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
/// Overview
/// --------
// Primary Manipulators:
//: o void setF();
// Basic Accessors:
//: o int F() const;
//-----------------------------------------------------------------------------
// MANIPULATORS
// [ ] void setF();
// [ 2] void setG();
// ACCESSORS
// [ 5] int F() const;
//-----------------------------------------------------------------------------
// [ ] BREATHING TEST
// [ ] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST MACRO
// ----------------------------------------------------------------------------
static int testStatus = 0;
static void aSsErT(int c, const char *s, int i)
{
if (c) {
cout << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << endl;
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
// ============================================================================
// STANDARD BDE TEST DRIVER MACROS
// ----------------------------------------------------------------------------
#define C_(X) << #X << ": " << X << '\t'
#define A_(X,S) { if (!(X)) { cout S << endl; aSsErT(1, #X, __LINE__); } }
#define LOOP_ASSERT(I,X) A_(X,C_(I))
#define LOOP2_ASSERT(I,J,X) A_(X,C_(I)C_(J))
#define LOOP3_ASSERT(I,J,K,X) A_(X,C_(I)C_(J)C_(K))
#define LOOP4_ASSERT(I,J,K,L,X) A_(X,C_(I)C_(J)C_(K)C_(L))
#define LOOP5_ASSERT(I,J,K,L,M,X) A_(X,C_(I)C_(J)C_(K)C_(L)C_(M))
#define LOOP6_ASSERT(I,J,K,L,M,N,X) A_(X,C_(I)C_(J)C_(K)C_(L)C_(M)C_(N))
//=============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
//-----------------------------------------------------------------------------
#define P(X) cout << #X " = " << (X) << endl; // Print identifier and value.
#define Q(X) cout << "<| " #X " |>" << endl; // Quote identifier literally.
#define P_(X) cout << #X " = " << (X) << ", " << flush; // P(X) without '\n'
#define L_ __LINE__ // current Line number
#define T_ cout << "\t" << flush; // Print tab w/o newline
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_FAIL BSLS_ASSERTTEST_ASSERT_FAIL
#define ASSERT_PASS BSLS_ASSERTTEST_ASSERT_PASS
// ============================================================================
// EXCEPTION TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define EXCEPTION_COUNT bslmaExceptionCounter
// ============================================================================
// GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------
typedef int Obj;
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? bsl::atoi(argv[1]) : 0;
int verbose = argc > 2;
int veryVerbose = argc > 3;
int veryVeryVerbose = argc > 4;
int veryVeryVeryVerbose = argc > 5;
printf("%s %i\n", "TEST " __FILE__ " CASE ", test);
switch (test) { case 0: // Zero is always the leading case.
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concerns:
// The usage example provided in the component header file must
// compile, link, and run on all platforms as shown.
//
// Plan:
// Incorporate usage example from header into driver, remove leading
// comment characters, and replace 'assert' with 'ASSERT'. The code
// has been incorporated both above and here, since it includes
// freestanding data objects, functions, and function templates. C-1
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) {
printf("Usage Example\n=============\n");
}
static volatile const bool b = false;
// These should not complain, because usage example.
for (; b; ) { }
while (b) { }
do { } while (b);
} break;
case 2: {
// --------------------------------------------------------------------
// 'f' AND "setf"
// Test the 'f' and 'setF' methods.
//
// Concerns:
//
// Plan:
//
// Testing:
// int F() const;
// int G() const;
// --------------------------------------------------------------------
if (verbose) {
cout << endl << "'f' AND 'setf'" << endl << "==========" << '\n';
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
if (verbose) cout << "BREATHING TEST" << endl
<< "==============" << endl;
extern int F();
static volatile const bool b = false;
// The following three triplets are the basic tests.
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// These should also not generate a complaint.
if (veryVerbose) { for (; b; ) { F(); } }
if (veryVerbose) { while (b) { F(); } }
if (veryVerbose) { do { F(); } while (b); }
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
// Repeat the basic tests within a non-loop substatement.
if (b) {
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// These should also not generate a complaint.
if (veryVerbose) { for (; b; ) { F(); } }
if (veryVerbose) { while (b) { F(); } }
if (veryVerbose) { do { F(); } while (b); }
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
}
// Repeat the basic tests within a loop substatement that has no direct
// "very verbose" action. Policy is not to complain about this.
while (b) {
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
}
// Repeat the basic tests within a loop substatement that has a direct
// very verbose action.
while (b) {
if (veryVerbose) { cout << endl; F(); }
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// These should also not generate a complaint.
if (veryVerbose) { for (; b; ) { } F(); }
if (veryVerbose) { while (b) { } F(); }
if (veryVerbose) { do { } while (b); F(); }
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
}
} break;
case -1: {
} break;
default: {
bsl::cerr << "WARNING: CASE `" << test << "' NOT FOUND." << bsl::endl;
// testStatus = -1;
}
}
return testStatus ? testStatus : 0;
}
// ============================================================================
// TEST CLASS
// ============================================================================
//
//@CLASSES:
// joe : just a class : stuff
// bsl::basic_nonesuch : not there::more stuff
#define x() x()
namespace bde_verify
{
struct joe {
void setF();
void setG();
int F() const;
int F();
int G() const;
joe();
joe(int);
~joe();
void x();
template <int N> void H();
};
}
// ---------------------------------------------------------------------------
// NOTICE:
// Copyright (C) Bloomberg L.P., 2013
// All Rights Reserved.
// Property of Bloomberg L.P. (BLP)
// This software is made available solely pursuant to the
// terms of a BLP license agreement which governs its use.
// ----------------------------- END-OF-FILE ---------------------------------
<commit_msg>Change print to something more complicated.<commit_after>// csabbg_testdriver.t.cpp -*-C++-*-
#include <bsl_cstdlib.h>
#include <bsl_iostream.h>
namespace bde_verify { }
using namespace bde_verify;
using bsl::cout;
using bsl::cerr;
using bsl::endl;
using bsl::flush;
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
/// Overview
/// --------
// Primary Manipulators:
//: o void setF();
// Basic Accessors:
//: o int F() const;
//-----------------------------------------------------------------------------
// MANIPULATORS
// [ ] void setF();
// [ 2] void setG();
// ACCESSORS
// [ 5] int F() const;
//-----------------------------------------------------------------------------
// [ ] BREATHING TEST
// [ ] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST MACRO
// ----------------------------------------------------------------------------
static int testStatus = 0;
static void aSsErT(int c, const char *s, int i)
{
if (c) {
cout << "Error " << __FILE__ << "(" << i << "): " << s
<< " (failed)" << endl;
if (testStatus >= 0 && testStatus <= 100) ++testStatus;
}
}
# define ASSERT(X) { aSsErT(!(X), #X, __LINE__); }
// ============================================================================
// STANDARD BDE TEST DRIVER MACROS
// ----------------------------------------------------------------------------
#define C_(X) << #X << ": " << X << '\t'
#define A_(X,S) { if (!(X)) { cout S << endl; aSsErT(1, #X, __LINE__); } }
#define LOOP_ASSERT(I,X) A_(X,C_(I))
#define LOOP2_ASSERT(I,J,X) A_(X,C_(I)C_(J))
#define LOOP3_ASSERT(I,J,K,X) A_(X,C_(I)C_(J)C_(K))
#define LOOP4_ASSERT(I,J,K,L,X) A_(X,C_(I)C_(J)C_(K)C_(L))
#define LOOP5_ASSERT(I,J,K,L,M,X) A_(X,C_(I)C_(J)C_(K)C_(L)C_(M))
#define LOOP6_ASSERT(I,J,K,L,M,N,X) A_(X,C_(I)C_(J)C_(K)C_(L)C_(M)C_(N))
//=============================================================================
// SEMI-STANDARD TEST OUTPUT MACROS
//-----------------------------------------------------------------------------
#define P(X) cout << #X " = " << (X) << endl; // Print identifier and value.
#define Q(X) cout << "<| " #X " |>" << endl; // Quote identifier literally.
#define P_(X) cout << #X " = " << (X) << ", " << flush; // P(X) without '\n'
#define L_ __LINE__ // current Line number
#define T_ cout << "\t" << flush; // Print tab w/o newline
// ============================================================================
// NEGATIVE-TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT_FAIL BSLS_ASSERTTEST_ASSERT_FAIL
#define ASSERT_PASS BSLS_ASSERTTEST_ASSERT_PASS
// ============================================================================
// EXCEPTION TEST MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define EXCEPTION_COUNT bslmaExceptionCounter
// ============================================================================
// GLOBAL TYPEDEFS FOR TESTING
// ----------------------------------------------------------------------------
typedef int Obj;
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? bsl::atoi(argv[1]) : 0;
int verbose = argc > 2;
int veryVerbose = argc > 3;
int veryVeryVerbose = argc > 4;
int veryVeryVeryVerbose = argc > 5;
printf("%s %i\n", "TEST " __FILE__ " CASE ", test);
switch (test) { case 0: // Zero is always the leading case.
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Concerns:
// The usage example provided in the component header file must
// compile, link, and run on all platforms as shown.
//
// Plan:
// Incorporate usage example from header into driver, remove leading
// comment characters, and replace 'assert' with 'ASSERT'. The code
// has been incorporated both above and here, since it includes
// freestanding data objects, functions, and function templates. C-1
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) {
printf("Usage Example\n=============\n");
}
static volatile const bool b = false;
// These should not complain, because usage example.
for (; b; ) { }
while (b) { }
do { } while (b);
} break;
case 2: {
// --------------------------------------------------------------------
// 'f' AND "setf"
// Test the 'f' and 'setF' methods.
//
// Concerns:
//
// Plan:
//
// Testing:
// int F() const;
// int G() const;
// --------------------------------------------------------------------
if (verbose) {
cout << endl << "'f' AND 'setf'" << endl << "==========" << '\n';
}
} break;
case 1: {
// --------------------------------------------------------------------
// BREATHING TEST
// This case exercises (but does not fully test) basic functionality.
//
// Concerns:
//: 1 The class is sufficiently functional to enable comprehensive
//: testing in subsequent test cases.
//
// Plan:
//
// Testing:
// BREATHING TEST
// --------------------------------------------------------------------
if (verbose) cout << "\nBREATHING TEST"
"\n==============\n" << bsl::flush;
extern int F();
static volatile const bool b = false;
// The following three triplets are the basic tests.
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// These should also not generate a complaint.
if (veryVerbose) { for (; b; ) { F(); } }
if (veryVerbose) { while (b) { F(); } }
if (veryVerbose) { do { F(); } while (b); }
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
// Repeat the basic tests within a non-loop substatement.
if (b) {
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// These should also not generate a complaint.
if (veryVerbose) { for (; b; ) { F(); } }
if (veryVerbose) { while (b) { F(); } }
if (veryVerbose) { do { F(); } while (b); }
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
}
// Repeat the basic tests within a loop substatement that has no direct
// "very verbose" action. Policy is not to complain about this.
while (b) {
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
}
// Repeat the basic tests within a loop substatement that has a direct
// very verbose action.
while (b) {
if (veryVerbose) { cout << endl; F(); }
// These should generate no complaint.
for (; b; ) { if (veryVerbose) { cout << endl; } F(); }
while (b) { if (veryVerbose) { cout << endl; } F(); }
do { if (veryVerbose) { cout << endl; } F(); } while (b);
// These should also not generate a complaint.
if (veryVerbose) { for (; b; ) { } F(); }
if (veryVerbose) { while (b) { } F(); }
if (veryVerbose) { do { } while (b); F(); }
// Complain about using "verbose" inside loops.
for (; b; ) { if (verbose) { cout << endl; } F(); }
while (b) { if (verbose) { cout << endl; } F(); }
do { if (verbose) { cout << endl; } F(); } while (b);
// Complain about no "very verbose" action in loops.
for (; b; ) { F(); }
while (b) { F(); }
do { F(); } while (b);
}
} break;
case -1: {
} break;
default: {
bsl::cerr << "WARNING: CASE `" << test << "' NOT FOUND." << bsl::endl;
// testStatus = -1;
}
}
return testStatus ? testStatus : 0;
}
// ============================================================================
// TEST CLASS
// ============================================================================
//
//@CLASSES:
// joe : just a class : stuff
// bsl::basic_nonesuch : not there::more stuff
#define x() x()
namespace bde_verify
{
struct joe {
void setF();
void setG();
int F() const;
int F();
int G() const;
joe();
joe(int);
~joe();
void x();
template <int N> void H();
};
}
// ---------------------------------------------------------------------------
// NOTICE:
// Copyright (C) Bloomberg L.P., 2013
// All Rights Reserved.
// Property of Bloomberg L.P. (BLP)
// This software is made available solely pursuant to the
// terms of a BLP license agreement which governs its use.
// ----------------------------- END-OF-FILE ---------------------------------
<|endoftext|>
|
<commit_before>/**
A portable OpenAL audio subsystem implementation
Based on https://github.com/corporateshark/Android-NDK-Game-Development-Cookbook/tree/master/Chapter5
**/
#include <algorithm>
#include <atomic>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "OpenAL/LAL.h"
#include "Utils.h"
const int BUFFER_DURATION = 250; // milliseconds
const int BUFFER_SIZE = 44100 * 2 * 2 * BUFFER_DURATION / 1000;
static ALenum ConvertWaveDataFormatToAL( const sWaveDataFormat& F )
{
if ( F.m_BitsPerSample == 8 )
{
return ( F.m_NumChannels == 2 ) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
}
if ( F.m_BitsPerSample == 16 )
{
return ( F.m_NumChannels == 2 ) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
}
return AL_FORMAT_MONO8;
}
class clAudioSubsystem_OpenAL;
class clAudioSource_OpenAL: public iAudioSource, public std::enable_shared_from_this<clAudioSource_OpenAL>
{
public:
explicit clAudioSource_OpenAL( clAudioSubsystem_OpenAL* AudioSubsystem )
: m_AudioSubsystem( AudioSubsystem )
, m_DataProvider()
, m_BuffersCount(0)
, m_SourceID(0)
, m_BufferID()
{
alGenSources( 1, &m_SourceID );
}
virtual ~clAudioSource_OpenAL()
{
this->Stop();
alDeleteSources( 1, &m_SourceID );
alDeleteBuffers( m_BuffersCount, m_BufferID );
}
virtual void BindDataProvider( const std::shared_ptr<iWaveDataProvider>& Provider ) override;
virtual void Play() override;
virtual void Stop() override;
virtual bool IsPlaying() const override;
virtual void SetLooping( bool Looping ) override;
private:
void PrepareBuffers();
void UnqueueAllBuffers();
void UpdateBuffers();
void EnqueueOneBuffer();
size_t StreamBuffer( ALuint bufferId, size_t Size );
friend class clAudioSubsystem_OpenAL;
private:
clAudioSubsystem_OpenAL* m_AudioSubsystem;
std::shared_ptr<iWaveDataProvider> m_DataProvider;
// OpenAL stuff
ALsizei m_BuffersCount;
ALuint m_SourceID;
ALuint m_BufferID[2];
};
class clAudioSubsystem_OpenAL: public iAudioSubsystem
{
public:
clAudioSubsystem_OpenAL();
virtual ~clAudioSubsystem_OpenAL();
virtual void Start() override;
virtual void Stop() override;
virtual std::shared_ptr<iAudioSource> CreateAudioSource() override;
virtual void SetListenerGain( float Gain ) override;
private:
void DebugPrintVersion();
void RegisterSource( const std::shared_ptr<clAudioSource_OpenAL>& Source );
void UnregisterSource( clAudioSource_OpenAL* Source );
std::vector< std::shared_ptr<clAudioSource_OpenAL> > GetLockedSources()
{
std::unique_lock<std::mutex> Lock( m_ActiveSourcesMutex );
return m_ActiveSources;
}
friend class clAudioSource_OpenAL;
private:
ALCdevice* m_Device;
ALCcontext* m_Context;
std::shared_ptr<std::thread> m_AudioThread;
std::atomic<bool> m_IsPendingExit;
std::atomic<bool> m_IsInitialized;
std::vector< std::shared_ptr<clAudioSource_OpenAL> > m_ActiveSources;
std::mutex m_ActiveSourcesMutex;
};
void clAudioSource_OpenAL::BindDataProvider( const std::shared_ptr<iWaveDataProvider>& Provider )
{
m_DataProvider = Provider;
if ( !m_DataProvider ) return;
if ( m_BuffersCount )
{
alDeleteBuffers( m_BuffersCount, m_BufferID );
}
sWaveDataFormat Format = m_DataProvider->GetWaveDataFormat();
if ( m_DataProvider->IsStreaming() )
{
m_BuffersCount = 2;
alGenBuffers( m_BuffersCount, m_BufferID );
}
else
{
m_BuffersCount = 1;
alGenBuffers( m_BuffersCount, m_BufferID );
alBufferData(
m_BufferID[0],
ConvertWaveDataFormatToAL( Format ),
m_DataProvider->GetWaveData(),
m_DataProvider->GetWaveDataSize(),
Format.m_SamplesPerSecond
);
alSourcei( m_SourceID, AL_BUFFER, m_BufferID[0] );
}
}
void clAudioSource_OpenAL::PrepareBuffers()
{
if ( !m_DataProvider ) return;
int State;
alGetSourcei( m_SourceID, AL_SOURCE_STATE, &State );
if ( State != AL_PAUSED && m_DataProvider->IsStreaming() )
{
UnqueueAllBuffers();
int BuffersToQueue = 2;
StreamBuffer( m_BufferID[0], BUFFER_SIZE );
if ( StreamBuffer( m_BufferID[1], BUFFER_SIZE ) == 0 )
{
if ( IsLooping() )
{
m_DataProvider->Seek(0);
StreamBuffer(m_BufferID[1], BUFFER_SIZE);
}
else
{
BuffersToQueue = 1;
}
}
alSourceQueueBuffers( m_SourceID, BuffersToQueue, &m_BufferID[0] );
m_AudioSubsystem->RegisterSource( shared_from_this() );
}
}
void clAudioSource_OpenAL::UnqueueAllBuffers()
{
int NumQueued;
alGetSourcei( m_SourceID, AL_BUFFERS_QUEUED, &NumQueued );
if ( NumQueued > 0 )
{
alSourceUnqueueBuffers( m_SourceID, NumQueued, &m_BufferID[0] );
}
}
size_t clAudioSource_OpenAL::StreamBuffer( ALuint BufferID, size_t Size )
{
if ( !m_DataProvider ) return 0;
size_t ActualSize = m_DataProvider->StreamWaveData( Size );
if ( !ActualSize ) return 0;
const uint8_t* Data = m_DataProvider->GetWaveData();
size_t DataSize = m_DataProvider->GetWaveDataSize();
const sWaveDataFormat& Format = m_DataProvider->GetWaveDataFormat();
alBufferData(
BufferID,
ConvertWaveDataFormatToAL( Format ),
Data,
DataSize,
Format.m_SamplesPerSecond
);
return ActualSize;
}
void clAudioSource_OpenAL::EnqueueOneBuffer()
{
ALuint BufID;
alSourceUnqueueBuffers( m_SourceID, 1, &BufID );
size_t Size = this->StreamBuffer( BufID, BUFFER_SIZE );
if ( m_DataProvider->IsEndOfStream() )
{
if ( this->IsLooping() )
{
m_DataProvider->Seek( 0 );
if ( !Size ) Size = StreamBuffer( BufID, BUFFER_SIZE );
}
}
if ( Size )
{
alSourceQueueBuffers(m_SourceID, 1, &BufID);
}
else
{
// there is nothing more to play, but don't stop now if something is still playing
if ( !this->IsPlaying() ) this->Stop();
}
}
void clAudioSource_OpenAL::UpdateBuffers()
{
if ( !m_DataProvider ) return;
if ( m_DataProvider->IsStreaming() )
{
int NumProcessed = 0;
alGetSourcei( m_SourceID, AL_BUFFERS_PROCESSED, &NumProcessed );
switch ( NumProcessed )
{
case 0:
// nothing was processed
break;
case 1:
{
EnqueueOneBuffer();
break;
}
case 2:
{
EnqueueOneBuffer();
EnqueueOneBuffer();
alSourcePlay( m_SourceID );
break;
}
default:
break;
}
}
}
void clAudioSource_OpenAL::Play()
{
if ( this->IsPlaying() ) return;
if ( !m_DataProvider ) return;
PrepareBuffers();
alSourcePlay( m_SourceID );
}
void clAudioSource_OpenAL::Stop()
{
alSourceStop( m_SourceID );
UnqueueAllBuffers();
m_AudioSubsystem->UnregisterSource( this );
if ( m_DataProvider )
{
m_DataProvider->Seek( 0.0f );
}
}
bool clAudioSource_OpenAL::IsPlaying() const
{
ALint State = 0;
alGetSourcei( m_SourceID, AL_SOURCE_STATE, &State );
return State == AL_PLAYING;
}
void clAudioSource_OpenAL::SetLooping( bool Looping )
{
iAudioSource::SetLooping( Looping );
bool IsStreaming = m_DataProvider && m_DataProvider->IsStreaming();
if ( !IsStreaming )
{
alSourcei( m_SourceID, AL_LOOPING, Looping ? AL_TRUE : AL_FALSE );
}
}
std::shared_ptr<iAudioSubsystem> CreateAudioSubsystem_OpenAL()
{
return std::make_shared<clAudioSubsystem_OpenAL>();
}
clAudioSubsystem_OpenAL::clAudioSubsystem_OpenAL()
: m_Device( nullptr )
, m_Context( nullptr )
, m_AudioThread()
, m_IsPendingExit( false )
, m_IsInitialized( false )
{
LoadAL();
}
clAudioSubsystem_OpenAL::~clAudioSubsystem_OpenAL()
{
std::lock_guard<std::mutex> Lock( m_ActiveSourcesMutex );
m_ActiveSources.clear();
UnloadAL();
}
void clAudioSubsystem_OpenAL::DebugPrintVersion()
{
printf( "OpenAL version : %s\n", alGetString( AL_VERSION ) );
printf( "OpenAL vendor : %s\n", alGetString( AL_VENDOR ) );
printf( "OpenAL renderer: %s\n", alGetString( AL_RENDERER ) );
printf( "OpenAL extensions:\n%s\n\n", alGetString( AL_EXTENSIONS ) );
}
void clAudioSubsystem_OpenAL::Start()
{
m_AudioThread = std::make_shared<std::thread>(
[this]()
{
m_Device = alcOpenDevice( nullptr );
m_Context = alcCreateContext( m_Device, nullptr );
alcMakeContextCurrent( m_Context );
if ( IsVerbose() ) DebugPrintVersion();
m_IsInitialized = true;
while ( !m_IsPendingExit )
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{
auto sources = this->GetLockedSources();
for (auto i : sources)
{
i->UpdateBuffers();
}
}
}
// A dirty workaround for a possible bug in OpenAL Soft
// http://openal.org/pipermail/openal/2015-January/000312.html
#if !defined(_WIN32)
alcDestroyContext( m_Context );
alcCloseDevice( m_Device );
#endif
m_IsInitialized = false;
}
);
// wait
while ( !m_IsInitialized );
}
void clAudioSubsystem_OpenAL::RegisterSource( const std::shared_ptr<clAudioSource_OpenAL>& Source )
{
std::unique_lock<std::mutex> Lock( m_ActiveSourcesMutex );
if ( std::find( m_ActiveSources.begin(), m_ActiveSources.end(), Source) != m_ActiveSources.end() ) return;
m_ActiveSources.push_back( Source );
}
void clAudioSubsystem_OpenAL::UnregisterSource( clAudioSource_OpenAL* Source )
{
std::unique_lock<std::mutex> Lock( m_ActiveSourcesMutex );
m_ActiveSources.erase(
std::remove_if( m_ActiveSources.begin(), m_ActiveSources.end(),
[Source](const std::shared_ptr<clAudioSource_OpenAL>& Src){ return Src.get() == Source; } ),
m_ActiveSources.end()
);
}
void clAudioSubsystem_OpenAL::Stop()
{
m_IsPendingExit = true;
m_AudioThread->join();
}
std::shared_ptr<iAudioSource> clAudioSubsystem_OpenAL::CreateAudioSource()
{
return std::make_shared<clAudioSource_OpenAL>( this );
}
void clAudioSubsystem_OpenAL::SetListenerGain( float Gain )
{
alListenerf( AL_GAIN, Gain );
}
<commit_msg>Fixed looping bug<commit_after>/**
A portable OpenAL audio subsystem implementation
Based on https://github.com/corporateshark/Android-NDK-Game-Development-Cookbook/tree/master/Chapter5
**/
#include <algorithm>
#include <atomic>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
#include "AudioSubsystem_OpenAL.h"
#include "Decoders/iWaveDataProvider.h"
#include "OpenAL/LAL.h"
#include "Utils.h"
const int BUFFER_DURATION = 250; // milliseconds
const int BUFFER_SIZE = 44100 * 2 * 2 * BUFFER_DURATION / 1000;
static ALenum ConvertWaveDataFormatToAL( const sWaveDataFormat& F )
{
if ( F.m_BitsPerSample == 8 )
{
return ( F.m_NumChannels == 2 ) ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8;
}
if ( F.m_BitsPerSample == 16 )
{
return ( F.m_NumChannels == 2 ) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
}
return AL_FORMAT_MONO8;
}
class clAudioSubsystem_OpenAL;
class clAudioSource_OpenAL: public iAudioSource, public std::enable_shared_from_this<clAudioSource_OpenAL>
{
public:
explicit clAudioSource_OpenAL( clAudioSubsystem_OpenAL* AudioSubsystem )
: m_AudioSubsystem( AudioSubsystem )
, m_DataProvider()
, m_BuffersCount(0)
, m_SourceID(0)
, m_BufferID()
{
alGenSources( 1, &m_SourceID );
}
virtual ~clAudioSource_OpenAL()
{
this->Stop();
alDeleteSources( 1, &m_SourceID );
alDeleteBuffers( m_BuffersCount, m_BufferID );
}
virtual void BindDataProvider( const std::shared_ptr<iWaveDataProvider>& Provider ) override;
virtual void Play() override;
virtual void Stop() override;
virtual bool IsPlaying() const override;
virtual void SetLooping( bool Looping ) override;
private:
void PrepareBuffers();
void UnqueueAllBuffers();
void UpdateBuffers();
void EnqueueOneBuffer();
size_t StreamBuffer( ALuint bufferId, size_t Size );
friend class clAudioSubsystem_OpenAL;
private:
clAudioSubsystem_OpenAL* m_AudioSubsystem;
std::shared_ptr<iWaveDataProvider> m_DataProvider;
// OpenAL stuff
ALsizei m_BuffersCount;
ALuint m_SourceID;
ALuint m_BufferID[2];
};
class clAudioSubsystem_OpenAL: public iAudioSubsystem
{
public:
clAudioSubsystem_OpenAL();
virtual ~clAudioSubsystem_OpenAL();
virtual void Start() override;
virtual void Stop() override;
virtual std::shared_ptr<iAudioSource> CreateAudioSource() override;
virtual void SetListenerGain( float Gain ) override;
private:
void DebugPrintVersion();
void RegisterSource( const std::shared_ptr<clAudioSource_OpenAL>& Source );
void UnregisterSource( clAudioSource_OpenAL* Source );
std::vector< std::shared_ptr<clAudioSource_OpenAL> > GetLockedSources()
{
std::unique_lock<std::mutex> Lock( m_ActiveSourcesMutex );
return m_ActiveSources;
}
friend class clAudioSource_OpenAL;
private:
ALCdevice* m_Device;
ALCcontext* m_Context;
std::shared_ptr<std::thread> m_AudioThread;
std::atomic<bool> m_IsPendingExit;
std::atomic<bool> m_IsInitialized;
std::vector< std::shared_ptr<clAudioSource_OpenAL> > m_ActiveSources;
std::mutex m_ActiveSourcesMutex;
};
void clAudioSource_OpenAL::BindDataProvider( const std::shared_ptr<iWaveDataProvider>& Provider )
{
m_DataProvider = Provider;
if ( !m_DataProvider ) return;
if ( m_BuffersCount )
{
alDeleteBuffers( m_BuffersCount, m_BufferID );
}
sWaveDataFormat Format = m_DataProvider->GetWaveDataFormat();
if ( m_DataProvider->IsStreaming() )
{
m_BuffersCount = 2;
alGenBuffers( m_BuffersCount, m_BufferID );
}
else
{
m_BuffersCount = 1;
alGenBuffers( m_BuffersCount, m_BufferID );
alBufferData(
m_BufferID[0],
ConvertWaveDataFormatToAL( Format ),
m_DataProvider->GetWaveData(),
m_DataProvider->GetWaveDataSize(),
Format.m_SamplesPerSecond
);
alSourcei( m_SourceID, AL_BUFFER, m_BufferID[0] );
}
}
void clAudioSource_OpenAL::PrepareBuffers()
{
if ( !m_DataProvider ) return;
int State;
alGetSourcei( m_SourceID, AL_SOURCE_STATE, &State );
if ( State != AL_PAUSED && m_DataProvider->IsStreaming() )
{
UnqueueAllBuffers();
int BuffersToQueue = 2;
StreamBuffer( m_BufferID[0], BUFFER_SIZE );
if ( StreamBuffer( m_BufferID[1], BUFFER_SIZE ) == 0 )
{
if ( IsLooping() )
{
m_DataProvider->Seek(0);
StreamBuffer(m_BufferID[1], BUFFER_SIZE);
}
else
{
BuffersToQueue = 1;
}
}
alSourceQueueBuffers( m_SourceID, BuffersToQueue, &m_BufferID[0] );
m_AudioSubsystem->RegisterSource( shared_from_this() );
}
}
void clAudioSource_OpenAL::UnqueueAllBuffers()
{
int NumQueued;
alGetSourcei( m_SourceID, AL_BUFFERS_QUEUED, &NumQueued );
if ( NumQueued > 0 )
{
alSourceUnqueueBuffers( m_SourceID, NumQueued, &m_BufferID[0] );
}
}
size_t clAudioSource_OpenAL::StreamBuffer( ALuint BufferID, size_t Size )
{
if ( !m_DataProvider ) return 0;
size_t ActualSize = m_DataProvider->StreamWaveData( Size );
if ( !ActualSize ) return 0;
const uint8_t* Data = m_DataProvider->GetWaveData();
size_t DataSize = m_DataProvider->GetWaveDataSize();
const sWaveDataFormat& Format = m_DataProvider->GetWaveDataFormat();
alBufferData(
BufferID,
ConvertWaveDataFormatToAL( Format ),
Data,
DataSize,
Format.m_SamplesPerSecond
);
return ActualSize;
}
void clAudioSource_OpenAL::EnqueueOneBuffer()
{
ALuint BufID;
alSourceUnqueueBuffers( m_SourceID, 1, &BufID );
size_t Size = this->StreamBuffer( BufID, BUFFER_SIZE );
if ( m_DataProvider->IsEndOfStream() )
{
if ( this->IsLooping() )
{
m_DataProvider->Seek( 0 );
if ( !Size ) Size = StreamBuffer( BufID, BUFFER_SIZE );
}
}
if ( Size )
{
alSourceQueueBuffers(m_SourceID, 1, &BufID);
}
else
{
// there is nothing more to play, but don't stop now if something is still playing
if ( !this->IsPlaying() ) this->Stop();
}
}
void clAudioSource_OpenAL::UpdateBuffers()
{
if ( !m_DataProvider ) return;
if ( m_DataProvider->IsStreaming() )
{
int NumProcessed = 0;
alGetSourcei( m_SourceID, AL_BUFFERS_PROCESSED, &NumProcessed );
switch ( NumProcessed )
{
case 0:
// nothing was processed
break;
case 1:
{
EnqueueOneBuffer();
break;
}
case 2:
{
EnqueueOneBuffer();
EnqueueOneBuffer();
alSourcePlay( m_SourceID );
break;
}
default:
break;
}
}
}
void clAudioSource_OpenAL::Play()
{
if ( this->IsPlaying() ) return;
if ( !m_DataProvider ) return;
PrepareBuffers();
alSourcePlay( m_SourceID );
}
void clAudioSource_OpenAL::Stop()
{
alSourceStop( m_SourceID );
UnqueueAllBuffers();
m_AudioSubsystem->UnregisterSource( this );
if ( m_DataProvider )
{
m_DataProvider->Seek( 0.0f );
}
}
bool clAudioSource_OpenAL::IsPlaying() const
{
ALint State = 0;
alGetSourcei( m_SourceID, AL_SOURCE_STATE, &State );
return State == AL_PLAYING;
}
void clAudioSource_OpenAL::SetLooping( bool Looping )
{
iAudioSource::SetLooping( Looping );
bool IsStreaming = m_DataProvider && m_DataProvider->IsStreaming();
if ( m_DataProvider && !IsStreaming )
{
alSourcei( m_SourceID, AL_LOOPING, Looping ? AL_TRUE : AL_FALSE );
}
}
std::shared_ptr<iAudioSubsystem> CreateAudioSubsystem_OpenAL()
{
return std::make_shared<clAudioSubsystem_OpenAL>();
}
clAudioSubsystem_OpenAL::clAudioSubsystem_OpenAL()
: m_Device( nullptr )
, m_Context( nullptr )
, m_AudioThread()
, m_IsPendingExit( false )
, m_IsInitialized( false )
{
LoadAL();
}
clAudioSubsystem_OpenAL::~clAudioSubsystem_OpenAL()
{
std::lock_guard<std::mutex> Lock( m_ActiveSourcesMutex );
m_ActiveSources.clear();
UnloadAL();
}
void clAudioSubsystem_OpenAL::DebugPrintVersion()
{
printf( "OpenAL version : %s\n", alGetString( AL_VERSION ) );
printf( "OpenAL vendor : %s\n", alGetString( AL_VENDOR ) );
printf( "OpenAL renderer: %s\n", alGetString( AL_RENDERER ) );
printf( "OpenAL extensions:\n%s\n\n", alGetString( AL_EXTENSIONS ) );
}
void clAudioSubsystem_OpenAL::Start()
{
m_AudioThread = std::make_shared<std::thread>(
[this]()
{
m_Device = alcOpenDevice( nullptr );
m_Context = alcCreateContext( m_Device, nullptr );
alcMakeContextCurrent( m_Context );
if ( IsVerbose() ) DebugPrintVersion();
m_IsInitialized = true;
while ( !m_IsPendingExit )
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
{
auto sources = this->GetLockedSources();
for (auto i : sources)
{
i->UpdateBuffers();
}
}
}
// A dirty workaround for a possible bug in OpenAL Soft
// http://openal.org/pipermail/openal/2015-January/000312.html
#if !defined(_WIN32)
alcDestroyContext( m_Context );
alcCloseDevice( m_Device );
#endif
m_IsInitialized = false;
}
);
// wait
while ( !m_IsInitialized );
}
void clAudioSubsystem_OpenAL::RegisterSource( const std::shared_ptr<clAudioSource_OpenAL>& Source )
{
std::unique_lock<std::mutex> Lock( m_ActiveSourcesMutex );
if ( std::find( m_ActiveSources.begin(), m_ActiveSources.end(), Source) != m_ActiveSources.end() ) return;
m_ActiveSources.push_back( Source );
}
void clAudioSubsystem_OpenAL::UnregisterSource( clAudioSource_OpenAL* Source )
{
std::unique_lock<std::mutex> Lock( m_ActiveSourcesMutex );
m_ActiveSources.erase(
std::remove_if( m_ActiveSources.begin(), m_ActiveSources.end(),
[Source](const std::shared_ptr<clAudioSource_OpenAL>& Src){ return Src.get() == Source; } ),
m_ActiveSources.end()
);
}
void clAudioSubsystem_OpenAL::Stop()
{
m_IsPendingExit = true;
m_AudioThread->join();
}
std::shared_ptr<iAudioSource> clAudioSubsystem_OpenAL::CreateAudioSource()
{
return std::make_shared<clAudioSource_OpenAL>( this );
}
void clAudioSubsystem_OpenAL::SetListenerGain( float Gain )
{
alListenerf( AL_GAIN, Gain );
}
<|endoftext|>
|
<commit_before>#include "global.h"
#include "ycsb.h"
#include "tpcc.h"
#include "test.h"
#include "thread.h"
#include "manager.h"
#include "mem_alloc.h"
#include "query.h"
#include "plock.h"
#include "occ.h"
#include "vll.h"
#include "transport.h"
void * f(void *);
void * g(void *);
void * worker(void *);
void * nn_worker(void *);
void network_test();
void network_test_recv();
// TODO the following global variables are HACK
thread_t * m_thds;
// defined in parser.cpp
void parser(int argc, char * argv[]);
int main(int argc, char* argv[])
{
// 0. initialize global data structure
parser(argc, argv);
uint64_t seed = get_sys_clock();
srand(seed);
printf("Random seed: %ld\n",seed);
#if NETWORK_TEST
tport_man.init(g_node_id);
sleep(3);
if(g_node_id == 0)
network_test();
else if(g_node_id == 1)
network_test_recv();
return 0;
#endif
// per-partition malloc
mem_allocator.init(g_part_cnt, MEM_SIZE / g_part_cnt);
stats.init();
glob_manager.init();
if (g_cc_alg == DL_DETECT)
dl_detector.init();
printf("mem_allocator initialized!\n");
workload * m_wl;
switch (WORKLOAD) {
case YCSB :
m_wl = new ycsb_wl; break;
case TPCC :
m_wl = new tpcc_wl; break;
case TEST :
m_wl = new TestWorkload;
((TestWorkload *)m_wl)->tick();
break;
default:
assert(false);
}
m_wl->init();
printf("workload initialized!\n");
rem_qry_man.init(g_node_id,m_wl);
tport_man.init(g_node_id);
work_queue.init();
txn_pool.init();
// 2. spawn multiple threads
uint64_t thd_cnt = g_thread_cnt;
uint64_t rthd_cnt = g_rem_thread_cnt;
pthread_t * p_thds =
(pthread_t *) malloc(sizeof(pthread_t) * (thd_cnt + rthd_cnt));
pthread_attr_t attr;
pthread_attr_init(&attr);
cpu_set_t cpus;
m_thds = new thread_t[thd_cnt + rthd_cnt];
// query_queue should be the last one to be initialized!!!
// because it collects txn latency
if (WORKLOAD != TEST) {
query_queue.init(m_wl);
}
pthread_barrier_init( &warmup_bar, NULL, g_thread_cnt );
printf("query_queue initialized!\n");
#if CC_ALG == HSTORE
part_lock_man.init(g_node_id);
#elif CC_ALG == OCC
occ_man.init();
#elif CC_ALG == VLL
vll_man.init();
#endif
for (uint32_t i = 0; i < thd_cnt + rthd_cnt; i++)
m_thds[i].init(i, g_node_id, m_wl);
if (WARMUP > 0){
printf("WARMUP start!\n");
for (uint32_t i = 0; i < thd_cnt - 1; i++) {
uint64_t vid = i;
CPU_ZERO(&cpus);
CPU_SET(i, &cpus);
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&p_thds[i], &attr, f, (void *)vid);
}
f((void *)(thd_cnt - 1));
for (uint32_t i = 0; i < thd_cnt - 1; i++)
pthread_join(p_thds[i], NULL);
printf("WARMUP finished!\n");
}
warmup_finish = true;
pthread_barrier_init( &warmup_bar, NULL, thd_cnt + rthd_cnt);
#ifndef NOGRAPHITE
CarbonBarrierInit(&enable_barrier, thd_cnt+ rthd_cnt);
#endif
pthread_barrier_init( &warmup_bar, NULL, thd_cnt + rthd_cnt);
uint64_t cpu_cnt = 0;
// spawn and run txns again.
int64_t starttime = get_server_clock();
for (uint32_t i = 0; i < thd_cnt; i++) {
uint64_t vid = i;
CPU_ZERO(&cpus);
#if TPORT_TYPE_IPC
CPU_SET(g_node_id * (g_thread_cnt) + cpu_cnt, &cpus);
#else
CPU_SET(cpu_cnt, &cpus);
#endif
cpu_cnt++;
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&p_thds[i], &attr, worker, (void *)vid);
}
nn_worker((void *)(thd_cnt));
for (uint32_t i = 0; i < thd_cnt; i++)
pthread_join(p_thds[i], NULL);
/*
for (uint32_t i = 0; i < thd_cnt; i++) {
uint64_t vid = i;
CPU_ZERO(&cpus);
#if TPORT_TYPE_IPC
CPU_SET(g_node_id * (g_thread_cnt) + cpu_cnt, &cpus);
//CPU_SET(g_node_id * (g_thread_cnt + g_rem_thread_cnt) + cpu_cnt, &cpus);
#else
CPU_SET(cpu_cnt, &cpus);
#endif
cpu_cnt++;
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&p_thds[i], &attr, f, (void *)vid);
}
for (uint32_t i = 0; i < rthd_cnt; i++) {
CPU_ZERO(&cpus);
#if TPORT_TYPE_IPC
//CPU_SET(g_node_id * (g_thread_cnt + g_rem_thread_cnt) + cpu_cnt, &cpus);
#else
CPU_SET(cpu_cnt, &cpus);
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
#endif
cpu_cnt++;
pthread_create(&p_thds[thd_cnt+i], &attr, g, (void *)(thd_cnt + i));
//g((void *)(thd_cnt));
}
for (uint32_t i = 0; i < thd_cnt + rthd_cnt; i++)
pthread_join(p_thds[i], NULL);
*/
int64_t endtime = get_server_clock();
if (WORKLOAD != TEST) {
printf("PASS! SimTime = %ld\n", endtime - starttime);
if (STATS_ENABLE)
stats.print();
} else {
((TestWorkload *)m_wl)->summarize();
}
return 0;
}
void * worker(void * id) {
uint64_t tid = (uint64_t)id;
m_thds[tid].run();
return NULL;
}
void * nn_worker(void * id) {
uint64_t tid = (uint64_t)id;
m_thds[tid].run_remote();
return NULL;
}
void network_test() {
ts_t start;
ts_t end;
double time;
int bytes;
for(int i=4; i < 257; i+=4) {
time = 0;
for(int j=0;j < 1000; j++) {
start = get_sys_clock();
tport_man.simple_send_msg(i);
while((bytes = tport_man.simple_recv_msg()) == 0) {}
end = get_sys_clock();
assert(bytes == i);
time += end-start;
}
time = time/1000;
printf("Network Bytes: %d, s: %f\n",i,time/BILLION);
}
}
void network_test_recv() {
int bytes;
while(1) {
if( (bytes = tport_man.simple_recv_msg()) > 0)
tport_man.simple_send_msg(bytes);
}
}
<commit_msg>Print out initialization time<commit_after>#include "global.h"
#include "ycsb.h"
#include "tpcc.h"
#include "test.h"
#include "thread.h"
#include "manager.h"
#include "mem_alloc.h"
#include "query.h"
#include "plock.h"
#include "occ.h"
#include "vll.h"
#include "transport.h"
void * f(void *);
void * g(void *);
void * worker(void *);
void * nn_worker(void *);
void network_test();
void network_test_recv();
// TODO the following global variables are HACK
thread_t * m_thds;
// defined in parser.cpp
void parser(int argc, char * argv[]);
int main(int argc, char* argv[])
{
// 0. initialize global data structure
parser(argc, argv);
uint64_t seed = get_sys_clock();
srand(seed);
printf("Random seed: %ld\n",seed);
#if NETWORK_TEST
tport_man.init(g_node_id);
sleep(3);
if(g_node_id == 0)
network_test();
else if(g_node_id == 1)
network_test_recv();
return 0;
#endif
int64_t starttime;
int64_t endtime;
starttime = get_server_clock();
// per-partition malloc
mem_allocator.init(g_part_cnt, MEM_SIZE / g_part_cnt);
stats.init();
glob_manager.init();
if (g_cc_alg == DL_DETECT)
dl_detector.init();
printf("mem_allocator initialized!\n");
workload * m_wl;
switch (WORKLOAD) {
case YCSB :
m_wl = new ycsb_wl; break;
case TPCC :
m_wl = new tpcc_wl; break;
case TEST :
m_wl = new TestWorkload;
((TestWorkload *)m_wl)->tick();
break;
default:
assert(false);
}
m_wl->init();
printf("workload initialized!\n");
rem_qry_man.init(g_node_id,m_wl);
tport_man.init(g_node_id);
work_queue.init();
txn_pool.init();
// 2. spawn multiple threads
uint64_t thd_cnt = g_thread_cnt;
uint64_t rthd_cnt = g_rem_thread_cnt;
pthread_t * p_thds =
(pthread_t *) malloc(sizeof(pthread_t) * (thd_cnt + rthd_cnt));
pthread_attr_t attr;
pthread_attr_init(&attr);
cpu_set_t cpus;
m_thds = new thread_t[thd_cnt + rthd_cnt];
// query_queue should be the last one to be initialized!!!
// because it collects txn latency
if (WORKLOAD != TEST) {
query_queue.init(m_wl);
}
pthread_barrier_init( &warmup_bar, NULL, g_thread_cnt );
printf("query_queue initialized!\n");
#if CC_ALG == HSTORE
part_lock_man.init(g_node_id);
#elif CC_ALG == OCC
occ_man.init();
#elif CC_ALG == VLL
vll_man.init();
#endif
for (uint32_t i = 0; i < thd_cnt + rthd_cnt; i++)
m_thds[i].init(i, g_node_id, m_wl);
endtime = get_server_clock();
printf("Initialization Time = %ld\n", endtime - starttime);
if (WARMUP > 0){
printf("WARMUP start!\n");
for (uint32_t i = 0; i < thd_cnt - 1; i++) {
uint64_t vid = i;
CPU_ZERO(&cpus);
CPU_SET(i, &cpus);
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&p_thds[i], &attr, f, (void *)vid);
}
f((void *)(thd_cnt - 1));
for (uint32_t i = 0; i < thd_cnt - 1; i++)
pthread_join(p_thds[i], NULL);
printf("WARMUP finished!\n");
}
warmup_finish = true;
pthread_barrier_init( &warmup_bar, NULL, thd_cnt + rthd_cnt);
#ifndef NOGRAPHITE
CarbonBarrierInit(&enable_barrier, thd_cnt+ rthd_cnt);
#endif
pthread_barrier_init( &warmup_bar, NULL, thd_cnt + rthd_cnt);
uint64_t cpu_cnt = 0;
// spawn and run txns again.
starttime = get_server_clock();
for (uint32_t i = 0; i < thd_cnt; i++) {
uint64_t vid = i;
CPU_ZERO(&cpus);
#if TPORT_TYPE_IPC
CPU_SET(g_node_id * (g_thread_cnt) + cpu_cnt, &cpus);
#else
CPU_SET(cpu_cnt, &cpus);
#endif
cpu_cnt++;
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&p_thds[i], &attr, worker, (void *)vid);
}
nn_worker((void *)(thd_cnt));
for (uint32_t i = 0; i < thd_cnt; i++)
pthread_join(p_thds[i], NULL);
/*
for (uint32_t i = 0; i < thd_cnt; i++) {
uint64_t vid = i;
CPU_ZERO(&cpus);
#if TPORT_TYPE_IPC
CPU_SET(g_node_id * (g_thread_cnt) + cpu_cnt, &cpus);
//CPU_SET(g_node_id * (g_thread_cnt + g_rem_thread_cnt) + cpu_cnt, &cpus);
#else
CPU_SET(cpu_cnt, &cpus);
#endif
cpu_cnt++;
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
pthread_create(&p_thds[i], &attr, f, (void *)vid);
}
for (uint32_t i = 0; i < rthd_cnt; i++) {
CPU_ZERO(&cpus);
#if TPORT_TYPE_IPC
//CPU_SET(g_node_id * (g_thread_cnt + g_rem_thread_cnt) + cpu_cnt, &cpus);
#else
CPU_SET(cpu_cnt, &cpus);
pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpus);
#endif
cpu_cnt++;
pthread_create(&p_thds[thd_cnt+i], &attr, g, (void *)(thd_cnt + i));
//g((void *)(thd_cnt));
}
for (uint32_t i = 0; i < thd_cnt + rthd_cnt; i++)
pthread_join(p_thds[i], NULL);
*/
endtime = get_server_clock();
if (WORKLOAD != TEST) {
printf("PASS! SimTime = %ld\n", endtime - starttime);
if (STATS_ENABLE)
stats.print();
} else {
((TestWorkload *)m_wl)->summarize();
}
return 0;
}
void * worker(void * id) {
uint64_t tid = (uint64_t)id;
m_thds[tid].run();
return NULL;
}
void * nn_worker(void * id) {
uint64_t tid = (uint64_t)id;
m_thds[tid].run_remote();
return NULL;
}
void network_test() {
ts_t start;
ts_t end;
double time;
int bytes;
for(int i=4; i < 257; i+=4) {
time = 0;
for(int j=0;j < 1000; j++) {
start = get_sys_clock();
tport_man.simple_send_msg(i);
while((bytes = tport_man.simple_recv_msg()) == 0) {}
end = get_sys_clock();
assert(bytes == i);
time += end-start;
}
time = time/1000;
printf("Network Bytes: %d, s: %f\n",i,time/BILLION);
}
}
void network_test_recv() {
int bytes;
while(1) {
if( (bytes = tport_man.simple_recv_msg()) > 0)
tport_man.simple_send_msg(bytes);
}
}
<|endoftext|>
|
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "Leases.h"
#include "NebulaLog.h"
/* ************************************************************************** */
/* ************************************************************************** */
/* Lease class */
/* ************************************************************************** */
/* ************************************************************************** */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::to_string(string &_ip,
string &_mac) const
{
mac_to_string(mac, _mac);
ip_to_string(ip, _ip);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::ip_to_number(const string& _ip, unsigned int& i_ip)
{
istringstream iss;
size_t pos=0;
int count = 0;
unsigned int tmp;
string ip = _ip;
while ( (pos = ip.find('.')) != string::npos )
{
ip.replace(pos,1," ");
count++;
}
if (count != 3)
{
return -1;
}
iss.str(ip);
i_ip = 0;
for (int i=0;i<4;i++)
{
iss >> dec >> tmp >> ws;
if ( tmp > 255 )
{
return -1;
}
i_ip <<= 8;
i_ip += tmp;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::ip_to_string(const unsigned int i_ip, string& ip)
{
unsigned int temp_byte;
ostringstream oss;
// Convert the IP from unsigned int to string
for (int index=0;index<4;index++)
{
temp_byte = i_ip;
temp_byte >>= (24-index*8);
temp_byte &= 255;
oss << temp_byte;
if(index!=3)
{
oss << ".";
}
}
ip = oss.str();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::mac_to_number(const string& _mac, unsigned int i_mac[])
{
istringstream iss;
size_t pos=0;
int count = 0;
unsigned int tmp;
string mac = _mac;
while ( (pos = mac.find(':')) != string::npos )
{
mac.replace(pos,1," ");
count++;
}
if (count != 5)
{
return -1;
}
iss.str(mac);
i_mac[PREFIX] = 0;
i_mac[SUFFIX] = 0;
iss >> hex >> i_mac[PREFIX] >> ws >> hex >> tmp >> ws;
i_mac[PREFIX] <<= 8;
i_mac[PREFIX] += tmp;
for (int i=0;i<4;i++)
{
iss >> hex >> tmp >> ws;
i_mac[SUFFIX] <<= 8;
i_mac[SUFFIX] += tmp;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::mac_to_string(const unsigned int i_mac[], string& mac)
{
ostringstream oss;
unsigned int temp_byte;
oss.str("");
for (int i=5;i>=0;i--)
{
if ( i < 4 )
{
temp_byte = i_mac[SUFFIX];
temp_byte >>= i*8;
}
else
{
temp_byte = i_mac[PREFIX];
temp_byte >>= (i%4)*8;
}
temp_byte &= 255;
oss.width(2);
oss.fill('0');
oss << hex << temp_byte;
if(i!=0)
{
oss << ":";
}
}
mac = oss.str();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator<<(ostream& os, Leases::Lease& _lease)
{
string xml;
os << _lease.to_xml(xml);
return os;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Leases::Lease::to_xml(string& str) const
{
string ip;
string mac;
ostringstream os;
to_string(ip,mac);
os <<
"<LEASE>" <<
"<IP>" << ip << "</IP>" <<
"<MAC>" << mac << "</MAC>" <<
"<USED>"<< used << "</USED>"<<
"<VID>" << vid << "</VID>" <<
"</LEASE>";
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Leases::Lease::to_xml_db(string& str) const
{
ostringstream os;
os <<
"<LEASE>" <<
"<IP>" << ip << "</IP>" <<
"<MAC_PREFIX>" << mac[Lease::PREFIX] << "</MAC_PREFIX>" <<
"<MAC_SUFFIX>" << mac[Lease::SUFFIX] << "</MAC_SUFFIX>" <<
"<USED>" << used << "</USED>"<<
"<VID>" << vid << "</VID>" <<
"</LEASE>";
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::from_xml(const string &xml_str)
{
int rc = 0;
int int_used;
// Initialize the internal XML object
update_from_str(xml_str);
rc += xpath(ip , "/LEASE/IP" , 0);
rc += xpath(mac[Lease::PREFIX], "/LEASE/MAC_PREFIX" , 0);
rc += xpath(mac[Lease::SUFFIX], "/LEASE/MAC_SUFFIX" , 0);
rc += xpath(int_used , "/LEASE/USED" , 0);
rc += xpath(vid , "/LEASE/VID" , 0);
used = static_cast<bool>(int_used);
if (rc != 0)
{
return -1;
}
return 0;
}
/* ************************************************************************** */
/* ************************************************************************** */
/* Leases class */
/* ************************************************************************** */
/* ************************************************************************** */
const char * Leases::table = "leases";
const char * Leases::db_names = "oid, ip, body";
const char * Leases::db_bootstrap = "CREATE TABLE IF NOT EXISTS leases ("
"oid INTEGER, ip BIGINT, body TEXT, PRIMARY KEY(oid,ip))";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::select_cb(void *nil, int num, char **values, char **names)
{
Lease * lease;
int rc;
if ( (!values[0]) || (num != 1) )
{
return -1;
}
lease = new Lease();
rc = lease->from_xml(values[0]);
if (rc != 0)
{
return -1;
}
leases.insert(make_pair(lease->ip, lease));
if(lease->used)
{
n_used++;
}
return 0;
}
/* -------------------------------------------------------------------------- */
int Leases::select(SqlDB * db)
{
ostringstream oss;
int rc;
// Reset the used leases counter
n_used = 0;
set_callback(static_cast<Callbackable::Callback>(&Leases::select_cb));
oss << "SELECT body FROM " << table << " WHERE oid = " << oid;
rc = db->exec(oss,this);
unset_callback();
if (rc != 0)
{
goto error_id;
}
return 0;
error_id:
oss.str("");
oss << "Error getting leases for network nid: " << oid;
NebulaLog::log("VNM", Log::ERROR, oss);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::drop(SqlDB * db)
{
ostringstream oss;
// Drop all the leases
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
return db->exec(oss);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::insert(SqlDB * db, string& error_str)
{
error_str = "Should not access to Leases.insert().";
NebulaLog::log("VNM", Log::ERROR, error_str);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::update(SqlDB * db)
{
NebulaLog::log("VNM", Log::ERROR, "Should not access to Leases.update()");
return -1;
}
/* ************************************************************************** */
/* Leases :: Interface Methods */
/* ************************************************************************** */
bool Leases::check(const string& ip)
{
unsigned int _ip;
Leases::Lease::ip_to_number(ip,_ip);
return check(_ip);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Leases::check(unsigned int ip)
{
map<unsigned int,Lease *>::iterator it;
it=leases.find(ip);
if (it!=leases.end())
{
return it->second->used;
}
else
{
return false;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::hold_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
int rc;
string ip;
string mac;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if ( single_attr_lease == 0 )
{
error_msg = "Empty lease description.";
return -1;
}
ip = single_attr_lease->vector_value("IP");
if ( check(ip) )
{
error_msg = "Lease is in use.";
return -1;
}
rc = set(-1, ip, mac);
if ( rc != 0 )
{
error_msg = "Lease is not part of the NET.";
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::free_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
map<unsigned int,Lease *>::iterator it;
unsigned int i_ip;
string st_ip;
string mac;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if ( single_attr_lease == 0 )
{
error_msg = "Empty lease description.";
return -1;
}
st_ip = single_attr_lease->vector_value("IP");
if ( Leases::Lease::ip_to_number(st_ip,i_ip) != 0 )
{
error_msg = "Wrong Lease format.";
return -1;
}
it = leases.find(i_ip);
if ( it == leases.end() || (it->second->used && it->second->vid != -1) )
{
error_msg = "Lease is not on hold.";
return -1;
}
release(st_ip);
return 0;
}
/* ************************************************************************** */
/* Leases :: Misc */
/* ************************************************************************** */
string& Leases::to_xml(string& xml) const
{
map<unsigned int, Leases::Lease *>::const_iterator it;
ostringstream os;
string lease_xml;
os << "<LEASES>";
for(it=leases.begin();it!=leases.end();it++)
{
os << it->second->to_xml(lease_xml);
}
os << "</LEASES>";
xml = os.str();
return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator<<(ostream& os, Leases& _leases)
{
string xml;
os << _leases.to_xml(xml);
return os;
};
<commit_msg>Feature #602: onevnet release returns error if a Lease is not used, this achieves the same behaviour for fixed and ranged networks<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "Leases.h"
#include "NebulaLog.h"
/* ************************************************************************** */
/* ************************************************************************** */
/* Lease class */
/* ************************************************************************** */
/* ************************************************************************** */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::to_string(string &_ip,
string &_mac) const
{
mac_to_string(mac, _mac);
ip_to_string(ip, _ip);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::ip_to_number(const string& _ip, unsigned int& i_ip)
{
istringstream iss;
size_t pos=0;
int count = 0;
unsigned int tmp;
string ip = _ip;
while ( (pos = ip.find('.')) != string::npos )
{
ip.replace(pos,1," ");
count++;
}
if (count != 3)
{
return -1;
}
iss.str(ip);
i_ip = 0;
for (int i=0;i<4;i++)
{
iss >> dec >> tmp >> ws;
if ( tmp > 255 )
{
return -1;
}
i_ip <<= 8;
i_ip += tmp;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::ip_to_string(const unsigned int i_ip, string& ip)
{
unsigned int temp_byte;
ostringstream oss;
// Convert the IP from unsigned int to string
for (int index=0;index<4;index++)
{
temp_byte = i_ip;
temp_byte >>= (24-index*8);
temp_byte &= 255;
oss << temp_byte;
if(index!=3)
{
oss << ".";
}
}
ip = oss.str();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::mac_to_number(const string& _mac, unsigned int i_mac[])
{
istringstream iss;
size_t pos=0;
int count = 0;
unsigned int tmp;
string mac = _mac;
while ( (pos = mac.find(':')) != string::npos )
{
mac.replace(pos,1," ");
count++;
}
if (count != 5)
{
return -1;
}
iss.str(mac);
i_mac[PREFIX] = 0;
i_mac[SUFFIX] = 0;
iss >> hex >> i_mac[PREFIX] >> ws >> hex >> tmp >> ws;
i_mac[PREFIX] <<= 8;
i_mac[PREFIX] += tmp;
for (int i=0;i<4;i++)
{
iss >> hex >> tmp >> ws;
i_mac[SUFFIX] <<= 8;
i_mac[SUFFIX] += tmp;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Leases::Lease::mac_to_string(const unsigned int i_mac[], string& mac)
{
ostringstream oss;
unsigned int temp_byte;
oss.str("");
for (int i=5;i>=0;i--)
{
if ( i < 4 )
{
temp_byte = i_mac[SUFFIX];
temp_byte >>= i*8;
}
else
{
temp_byte = i_mac[PREFIX];
temp_byte >>= (i%4)*8;
}
temp_byte &= 255;
oss.width(2);
oss.fill('0');
oss << hex << temp_byte;
if(i!=0)
{
oss << ":";
}
}
mac = oss.str();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator<<(ostream& os, Leases::Lease& _lease)
{
string xml;
os << _lease.to_xml(xml);
return os;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Leases::Lease::to_xml(string& str) const
{
string ip;
string mac;
ostringstream os;
to_string(ip,mac);
os <<
"<LEASE>" <<
"<IP>" << ip << "</IP>" <<
"<MAC>" << mac << "</MAC>" <<
"<USED>"<< used << "</USED>"<<
"<VID>" << vid << "</VID>" <<
"</LEASE>";
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
string& Leases::Lease::to_xml_db(string& str) const
{
ostringstream os;
os <<
"<LEASE>" <<
"<IP>" << ip << "</IP>" <<
"<MAC_PREFIX>" << mac[Lease::PREFIX] << "</MAC_PREFIX>" <<
"<MAC_SUFFIX>" << mac[Lease::SUFFIX] << "</MAC_SUFFIX>" <<
"<USED>" << used << "</USED>"<<
"<VID>" << vid << "</VID>" <<
"</LEASE>";
str = os.str();
return str;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::Lease::from_xml(const string &xml_str)
{
int rc = 0;
int int_used;
// Initialize the internal XML object
update_from_str(xml_str);
rc += xpath(ip , "/LEASE/IP" , 0);
rc += xpath(mac[Lease::PREFIX], "/LEASE/MAC_PREFIX" , 0);
rc += xpath(mac[Lease::SUFFIX], "/LEASE/MAC_SUFFIX" , 0);
rc += xpath(int_used , "/LEASE/USED" , 0);
rc += xpath(vid , "/LEASE/VID" , 0);
used = static_cast<bool>(int_used);
if (rc != 0)
{
return -1;
}
return 0;
}
/* ************************************************************************** */
/* ************************************************************************** */
/* Leases class */
/* ************************************************************************** */
/* ************************************************************************** */
const char * Leases::table = "leases";
const char * Leases::db_names = "oid, ip, body";
const char * Leases::db_bootstrap = "CREATE TABLE IF NOT EXISTS leases ("
"oid INTEGER, ip BIGINT, body TEXT, PRIMARY KEY(oid,ip))";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::select_cb(void *nil, int num, char **values, char **names)
{
Lease * lease;
int rc;
if ( (!values[0]) || (num != 1) )
{
return -1;
}
lease = new Lease();
rc = lease->from_xml(values[0]);
if (rc != 0)
{
return -1;
}
leases.insert(make_pair(lease->ip, lease));
if(lease->used)
{
n_used++;
}
return 0;
}
/* -------------------------------------------------------------------------- */
int Leases::select(SqlDB * db)
{
ostringstream oss;
int rc;
// Reset the used leases counter
n_used = 0;
set_callback(static_cast<Callbackable::Callback>(&Leases::select_cb));
oss << "SELECT body FROM " << table << " WHERE oid = " << oid;
rc = db->exec(oss,this);
unset_callback();
if (rc != 0)
{
goto error_id;
}
return 0;
error_id:
oss.str("");
oss << "Error getting leases for network nid: " << oid;
NebulaLog::log("VNM", Log::ERROR, oss);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::drop(SqlDB * db)
{
ostringstream oss;
// Drop all the leases
oss << "DELETE FROM " << table << " WHERE oid=" << oid;
return db->exec(oss);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::insert(SqlDB * db, string& error_str)
{
error_str = "Should not access to Leases.insert().";
NebulaLog::log("VNM", Log::ERROR, error_str);
return -1;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::update(SqlDB * db)
{
NebulaLog::log("VNM", Log::ERROR, "Should not access to Leases.update()");
return -1;
}
/* ************************************************************************** */
/* Leases :: Interface Methods */
/* ************************************************************************** */
bool Leases::check(const string& ip)
{
unsigned int _ip;
Leases::Lease::ip_to_number(ip,_ip);
return check(_ip);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
bool Leases::check(unsigned int ip)
{
map<unsigned int,Lease *>::iterator it;
it=leases.find(ip);
if (it!=leases.end())
{
return it->second->used;
}
else
{
return false;
}
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::hold_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
int rc;
string ip;
string mac;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if ( single_attr_lease == 0 )
{
error_msg = "Empty lease description.";
return -1;
}
ip = single_attr_lease->vector_value("IP");
if ( check(ip) )
{
error_msg = "Lease is in use.";
return -1;
}
rc = set(-1, ip, mac);
if ( rc != 0 )
{
error_msg = "Lease is not part of the NET.";
return -1;
}
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int Leases::free_leases(vector<const Attribute*>& vector_leases,
string& error_msg)
{
const VectorAttribute * single_attr_lease = 0;
map<unsigned int,Lease *>::iterator it;
unsigned int i_ip;
string st_ip;
string mac;
if ( vector_leases.size() > 0 )
{
single_attr_lease =
dynamic_cast<const VectorAttribute *>(vector_leases[0]);
}
if ( single_attr_lease == 0 )
{
error_msg = "Empty lease description.";
return -1;
}
st_ip = single_attr_lease->vector_value("IP");
if ( Leases::Lease::ip_to_number(st_ip,i_ip) != 0 )
{
error_msg = "Wrong Lease format.";
return -1;
}
it = leases.find(i_ip);
if ( it == leases.end() || !it->second->used || it->second->vid != -1 )
{
error_msg = "Lease is not on hold.";
return -1;
}
release(st_ip);
return 0;
}
/* ************************************************************************** */
/* Leases :: Misc */
/* ************************************************************************** */
string& Leases::to_xml(string& xml) const
{
map<unsigned int, Leases::Lease *>::const_iterator it;
ostringstream os;
string lease_xml;
os << "<LEASES>";
for(it=leases.begin();it!=leases.end();it++)
{
os << it->second->to_xml(lease_xml);
}
os << "</LEASES>";
xml = os.str();
return xml;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
ostream& operator<<(ostream& os, Leases& _leases)
{
string xml;
os << _leases.to_xml(xml);
return os;
};
<|endoftext|>
|
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "NavRoutingPolylineFactory.h"
#include "PolylineShapeBuilder.h"
namespace ExampleApp
{
namespace NavRouting
{
namespace SdkModel
{
namespace
{
bool AreApproximatelyEqual(
const Eegeo::Space::LatLong& first,
const Eegeo::Space::LatLong& second
)
{
// <= 1mm separation
const double epsilonSq = 1e-6;
return first.ToECEF().SquareDistanceTo(second.ToECEF()) <= epsilonSq;
}
bool AreCoordinateElevationPairApproximatelyEqual(
std::pair<Eegeo::Space::LatLong, double>& a,
std::pair<Eegeo::Space::LatLong, double>& b
)
{
const double elevationEpsilon = 1e-3;
if (!AreApproximatelyEqual(a.first, b.first))
{
return false;
}
return std::abs(a.second - b.second) <= elevationEpsilon;
}
void RemoveCoincidentPoints(std::vector<Eegeo::Space::LatLong>& coordinates)
{
coordinates.erase(
std::unique(coordinates.begin(), coordinates.end(), AreApproximatelyEqual),
coordinates.end());
}
void RemoveCoincidentPointsWithElevations(
std::vector<Eegeo::Space::LatLong>& coordinates,
std::vector<double>& perPointElevations
)
{
Eegeo_ASSERT(coordinates.size() == perPointElevations.size());
std::vector<std::pair<Eegeo::Space::LatLong, double>> zipped;
zipped.reserve(coordinates.size());
for (int i = 0; i < coordinates.size(); ++i)
{
zipped.push_back(std::make_pair(coordinates[i], perPointElevations[i]));
}
const auto newEnd = std::unique(zipped.begin(), zipped.end(), AreCoordinateElevationPairApproximatelyEqual);
if (newEnd != zipped.end())
{
zipped.erase(newEnd, zipped.end());
coordinates.clear();
perPointElevations.clear();
for (const auto& pair : zipped)
{
coordinates.push_back(pair.first);
perPointElevations.push_back(pair.second);
}
}
}
NavRoutingPolylineCreateParams MakeNavRoutingPolylineCreateParams(
const std::vector<Eegeo::Space::LatLong>& coordinates,
const Eegeo::v4& color,
const std::string& indoorMapId,
int indoorMapFloorId
)
{
return {coordinates, color, indoorMapId, indoorMapFloorId, {}};
}
NavRoutingPolylineCreateParams MakeNavRoutingPolylineCreateParamsForVerticalLine(
const std::vector<Eegeo::Space::LatLong>& coordinates,
const Eegeo::v4& color,
const std::string& indoorMapId,
int indoorMapFloorId,
double heightStart,
double heightEnd
)
{
return {coordinates, color, indoorMapId, indoorMapFloorId, {heightStart, heightEnd}};
}
bool CanAmalgamate(
const NavRoutingPolylineCreateParams& a,
const NavRoutingPolylineCreateParams& b
)
{
if (a.IsIndoor() != b.IsIndoor())
{
return false;
}
if (a.GetIndoorMapId() != b.GetIndoorMapId())
{
return false;
}
if (a.GetIndoorMapFloorId() != b.GetIndoorMapFloorId())
{
return false;
}
if (a.GetColor() != b.GetColor())
{
return false;
}
return true;
}
std::vector<std::pair<size_t, size_t>> BuildAmalgamationRanges(const std::vector<NavRoutingPolylineCreateParams>& polylineCreateParams)
{
std::vector<std::pair<size_t, size_t>> ranges;
if (polylineCreateParams.empty())
{
return ranges;
}
size_t rangeStart = 0;
for (size_t i = 1; i < polylineCreateParams.size(); ++i)
{
const auto &a = polylineCreateParams[i - 1];
const auto &b = polylineCreateParams[i];
if (!CanAmalgamate(a, b))
{
ranges.push_back(std::make_pair(rangeStart, i));
rangeStart = i;
}
}
ranges.push_back(std::make_pair(rangeStart, polylineCreateParams.size()));
return ranges;
}
}
NavRoutingPolylineFactory::NavRoutingPolylineFactory(
PolyLineArgs::IShapeService& shapeService,
const NavRoutingPolylineConfig& polylineConfig
)
: m_shapeService(shapeService)
, m_polylineConfig(polylineConfig)
{
}
std::vector<NavRoutingPolylineCreateParams> NavRoutingPolylineFactory::CreateLinesForRouteDirection(
const NavRoutingDirectionModel& directionModel,
const Eegeo::v4& color
)
{
std::vector<NavRoutingPolylineCreateParams> results;
std::vector<Eegeo::Space::LatLong> uniqueCoordinates(directionModel.GetPath());
RemoveCoincidentPoints(uniqueCoordinates);
if(uniqueCoordinates.size()>1)
{
results.push_back(MakeNavRoutingPolylineCreateParams(
uniqueCoordinates,
color,
directionModel.GetIndoorMapId().Value(),
directionModel.GetIndoorMapFloorId())
);
}
return results;
}
std::vector<NavRoutingPolylineCreateParams> NavRoutingPolylineFactory::CreateLinesForRouteDirection(const NavRoutingDirectionModel& directionModel,
const Eegeo::v4& forwardColor,
const Eegeo::v4& backwardColor,
int splitIndex,
const Eegeo::Space::LatLong& closestPointOnRoute)
{
const auto& coordinates = directionModel.GetPath();
std::size_t coordinatesSize = coordinates.size();
bool hasReachedEnd = splitIndex == (coordinatesSize-1);
if (hasReachedEnd)
{
return CreateLinesForRouteDirection(directionModel,
backwardColor);
}
else
{
std::vector<NavRoutingPolylineCreateParams> results;
std::vector<Eegeo::Space::LatLong> backwardPath;
std::vector<Eegeo::Space::LatLong> forwardPath;
auto forwardPathSize = coordinatesSize - (splitIndex + 1);
forwardPath.reserve(forwardPathSize + 1); //Extra space for the split point
auto backwardPathSize = coordinatesSize - forwardPathSize;
backwardPath.reserve(backwardPathSize + 1); //Extra space for the split point
//Forward path starts with the split point
forwardPath.emplace_back(closestPointOnRoute);
for (int i = 0; i < coordinatesSize; i++)
{
if(i<=splitIndex)
{
backwardPath.emplace_back(coordinates[i]);
}
else
{
forwardPath.emplace_back(coordinates[i]);
}
}
//Backward path ends with the split point
backwardPath.emplace_back(closestPointOnRoute);
RemoveCoincidentPoints(backwardPath);
RemoveCoincidentPoints(forwardPath);
if(backwardPath.size()>1)
{
results.emplace_back(MakeNavRoutingPolylineCreateParams(
backwardPath,
backwardColor,
directionModel.GetIndoorMapId().Value(),
directionModel.GetIndoorMapFloorId())
);
}
if(forwardPath.size()>1)
{
results.emplace_back(MakeNavRoutingPolylineCreateParams(
forwardPath,
forwardColor,
directionModel.GetIndoorMapId().Value(),
directionModel.GetIndoorMapFloorId())
);
}
return results;
}
}
std::vector<NavRoutingPolylineCreateParams> NavRoutingPolylineFactory::CreateLinesForFloorTransition(
const std::vector<Eegeo::Space::LatLong>& coordinates,
const std::string& indoorMapId,
int floorBefore,
int floorAfter,
const Eegeo::v4& color
)
{
double verticalLineHeight = 5.0;
double lineHeight = (floorAfter > floorBefore) ? verticalLineHeight : -verticalLineHeight;
std::vector<NavRoutingPolylineCreateParams> results;
uint coordinateCount = static_cast<uint>(coordinates.size());
Eegeo_ASSERT(coordinateCount >= 2, "Can't make a floor transition line with a single point");
std::vector<Eegeo::Space::LatLong> startCoords;
startCoords.push_back(coordinates.at(0));
startCoords.push_back(coordinates.at(1));
std::vector<Eegeo::Space::LatLong> endCoords;
endCoords.push_back(coordinates.at(coordinateCount-2));
endCoords.push_back(coordinates.at(coordinateCount-1));
results.push_back(MakeNavRoutingPolylineCreateParamsForVerticalLine(startCoords, color, indoorMapId, floorBefore, 0, lineHeight));
results.push_back(MakeNavRoutingPolylineCreateParamsForVerticalLine(endCoords, color, indoorMapId, floorAfter, -lineHeight, 0));
return results;
}
RoutePolylineIdVector NavRoutingPolylineFactory::CreatePolylines(const std::vector<NavRoutingPolylineCreateParams>& polylineCreateParams)
{
RoutePolylineIdVector result;
const auto& ranges = BuildAmalgamationRanges(polylineCreateParams);
for (const auto& range : ranges)
{
const auto& polylineIds = CreateAmalgamatedPolylinesForRange(polylineCreateParams, range.first, range.second);
result.insert(result.end(), polylineIds.begin(), polylineIds.end());
}
return result;
}
RoutePolylineIdVector NavRoutingPolylineFactory::CreateAmalgamatedPolylinesForRange(
const std::vector<NavRoutingPolylineCreateParams>& polylineCreateParams,
const int rangeStartIndex,
const int rangeEndIndex
)
{
Eegeo_ASSERT(rangeStartIndex < rangeEndIndex);
Eegeo_ASSERT(rangeStartIndex >= 0);
Eegeo_ASSERT(rangeEndIndex <= polylineCreateParams.size());
RoutePolylineIdVector result;
std::vector<Eegeo::Space::LatLong> joinedCoordinates;
std::vector<double> joinedPerPointElevations;
bool anyPerPointElevations = false;
for (int i = rangeStartIndex; i < rangeEndIndex; ++i)
{
const auto& params = polylineCreateParams[i];
const auto& coordinates = params.GetCoordinates();
joinedCoordinates.insert(joinedCoordinates.end(), coordinates.begin(), coordinates.end());
if (!params.GetPerPointElevations().empty())
{
anyPerPointElevations = true;
}
}
if (anyPerPointElevations)
{
for (int i = rangeStartIndex; i < rangeEndIndex; ++i)
{
const auto& params = polylineCreateParams[i];
const auto& perPointElevations = params.GetPerPointElevations();
if (perPointElevations.empty())
{
// fill with zero
joinedPerPointElevations.insert(joinedPerPointElevations.end(), params.GetCoordinates().size(), 0.0);
}
else
{
joinedPerPointElevations.insert(joinedPerPointElevations.end(), perPointElevations.begin(), perPointElevations.end());
}
}
RemoveCoincidentPointsWithElevations(joinedCoordinates, joinedPerPointElevations);
}
else
{
RemoveCoincidentPoints(joinedCoordinates);
}
if (joinedCoordinates.size() > 1)
{
const auto& commonParams = polylineCreateParams[rangeStartIndex];
const auto& polylineParams = Eegeo::Shapes::Polylines::PolylineShapeBuilder()
.SetCoordinates(joinedCoordinates)
.SetPerPointElevations(joinedPerPointElevations)
.SetIndoorMap(commonParams.GetIndoorMapId(), commonParams.GetIndoorMapFloorId())
.SetFillColor(commonParams.GetColor())
.SetThickness(m_polylineConfig.routeThickness)
.SetMiterLimit(m_polylineConfig.miterLimit)
.SetElevation(m_polylineConfig.routeElevation)
.SetElevationMode(m_polylineConfig.routeElevationMode)
.SetShouldScaleWithMap(m_polylineConfig.shouldScaleWithMap)
.Build();
const auto& polylineId = m_shapeService.Create(polylineParams);
result.push_back(polylineId);
}
return result;
}
}
}
}
<commit_msg>build fix attempt 2 (prev sent ios red)<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "NavRoutingPolylineFactory.h"
#include "PolylineShapeBuilder.h"
namespace ExampleApp
{
namespace NavRouting
{
namespace SdkModel
{
namespace
{
bool AreApproximatelyEqual(
const Eegeo::Space::LatLong& first,
const Eegeo::Space::LatLong& second
)
{
// <= 1mm separation
const double epsilonSq = 1e-6;
return first.ToECEF().SquareDistanceTo(second.ToECEF()) <= epsilonSq;
}
bool AreCoordinateElevationPairApproximatelyEqual(
std::pair<Eegeo::Space::LatLong, double>& a,
std::pair<Eegeo::Space::LatLong, double>& b
)
{
const double elevationEpsilon = 1e-3;
if (!AreApproximatelyEqual(a.first, b.first))
{
return false;
}
return std::abs(a.second - b.second) <= elevationEpsilon;
}
void RemoveCoincidentPoints(std::vector<Eegeo::Space::LatLong>& coordinates)
{
coordinates.erase(
std::unique(coordinates.begin(), coordinates.end(), AreApproximatelyEqual),
coordinates.end());
}
void RemoveCoincidentPointsWithElevations(
std::vector<Eegeo::Space::LatLong>& coordinates,
std::vector<double>& perPointElevations
)
{
Eegeo_ASSERT(coordinates.size() == perPointElevations.size());
std::vector<std::pair<Eegeo::Space::LatLong, double>> zipped;
zipped.reserve(coordinates.size());
for (int i = 0; i < coordinates.size(); ++i)
{
zipped.push_back(std::make_pair(coordinates[i], perPointElevations[i]));
}
const auto newEnd = std::unique(zipped.begin(), zipped.end(), AreCoordinateElevationPairApproximatelyEqual);
if (newEnd != zipped.end())
{
zipped.erase(newEnd, zipped.end());
coordinates.clear();
perPointElevations.clear();
for (const auto& pair : zipped)
{
coordinates.push_back(pair.first);
perPointElevations.push_back(pair.second);
}
}
}
NavRoutingPolylineCreateParams MakeNavRoutingPolylineCreateParams(
const std::vector<Eegeo::Space::LatLong>& coordinates,
const Eegeo::v4& color,
const std::string& indoorMapId,
int indoorMapFloorId
)
{
return {coordinates, color, indoorMapId, indoorMapFloorId, {}};
}
NavRoutingPolylineCreateParams MakeNavRoutingPolylineCreateParamsForVerticalLine(
const std::vector<Eegeo::Space::LatLong>& coordinates,
const Eegeo::v4& color,
const std::string& indoorMapId,
int indoorMapFloorId,
double heightStart,
double heightEnd
)
{
return {coordinates, color, indoorMapId, indoorMapFloorId, {heightStart, heightEnd}};
}
bool CanAmalgamate(
const NavRoutingPolylineCreateParams& a,
const NavRoutingPolylineCreateParams& b
)
{
if (a.IsIndoor() != b.IsIndoor())
{
return false;
}
if (a.GetIndoorMapId() != b.GetIndoorMapId())
{
return false;
}
if (a.GetIndoorMapFloorId() != b.GetIndoorMapFloorId())
{
return false;
}
if (a.GetColor() != b.GetColor())
{
return false;
}
return true;
}
std::vector<std::pair<int, int>> BuildAmalgamationRanges(const std::vector<NavRoutingPolylineCreateParams>& polylineCreateParams)
{
std::vector<std::pair<int, int>> ranges;
if (polylineCreateParams.empty())
{
return ranges;
}
int rangeStart = 0;
for (int i = 1; i < polylineCreateParams.size(); ++i)
{
const auto &a = polylineCreateParams[i - 1];
const auto &b = polylineCreateParams[i];
if (!CanAmalgamate(a, b))
{
ranges.push_back(std::make_pair(rangeStart, i));
rangeStart = i;
}
}
ranges.push_back(std::make_pair(rangeStart, int(polylineCreateParams.size())));
return ranges;
}
}
NavRoutingPolylineFactory::NavRoutingPolylineFactory(
PolyLineArgs::IShapeService& shapeService,
const NavRoutingPolylineConfig& polylineConfig
)
: m_shapeService(shapeService)
, m_polylineConfig(polylineConfig)
{
}
std::vector<NavRoutingPolylineCreateParams> NavRoutingPolylineFactory::CreateLinesForRouteDirection(
const NavRoutingDirectionModel& directionModel,
const Eegeo::v4& color
)
{
std::vector<NavRoutingPolylineCreateParams> results;
std::vector<Eegeo::Space::LatLong> uniqueCoordinates(directionModel.GetPath());
RemoveCoincidentPoints(uniqueCoordinates);
if(uniqueCoordinates.size()>1)
{
results.push_back(MakeNavRoutingPolylineCreateParams(
uniqueCoordinates,
color,
directionModel.GetIndoorMapId().Value(),
directionModel.GetIndoorMapFloorId())
);
}
return results;
}
std::vector<NavRoutingPolylineCreateParams> NavRoutingPolylineFactory::CreateLinesForRouteDirection(const NavRoutingDirectionModel& directionModel,
const Eegeo::v4& forwardColor,
const Eegeo::v4& backwardColor,
int splitIndex,
const Eegeo::Space::LatLong& closestPointOnRoute)
{
const auto& coordinates = directionModel.GetPath();
std::size_t coordinatesSize = coordinates.size();
bool hasReachedEnd = splitIndex == (coordinatesSize-1);
if (hasReachedEnd)
{
return CreateLinesForRouteDirection(directionModel,
backwardColor);
}
else
{
std::vector<NavRoutingPolylineCreateParams> results;
std::vector<Eegeo::Space::LatLong> backwardPath;
std::vector<Eegeo::Space::LatLong> forwardPath;
auto forwardPathSize = coordinatesSize - (splitIndex + 1);
forwardPath.reserve(forwardPathSize + 1); //Extra space for the split point
auto backwardPathSize = coordinatesSize - forwardPathSize;
backwardPath.reserve(backwardPathSize + 1); //Extra space for the split point
//Forward path starts with the split point
forwardPath.emplace_back(closestPointOnRoute);
for (int i = 0; i < coordinatesSize; i++)
{
if(i<=splitIndex)
{
backwardPath.emplace_back(coordinates[i]);
}
else
{
forwardPath.emplace_back(coordinates[i]);
}
}
//Backward path ends with the split point
backwardPath.emplace_back(closestPointOnRoute);
RemoveCoincidentPoints(backwardPath);
RemoveCoincidentPoints(forwardPath);
if(backwardPath.size()>1)
{
results.emplace_back(MakeNavRoutingPolylineCreateParams(
backwardPath,
backwardColor,
directionModel.GetIndoorMapId().Value(),
directionModel.GetIndoorMapFloorId())
);
}
if(forwardPath.size()>1)
{
results.emplace_back(MakeNavRoutingPolylineCreateParams(
forwardPath,
forwardColor,
directionModel.GetIndoorMapId().Value(),
directionModel.GetIndoorMapFloorId())
);
}
return results;
}
}
std::vector<NavRoutingPolylineCreateParams> NavRoutingPolylineFactory::CreateLinesForFloorTransition(
const std::vector<Eegeo::Space::LatLong>& coordinates,
const std::string& indoorMapId,
int floorBefore,
int floorAfter,
const Eegeo::v4& color
)
{
double verticalLineHeight = 5.0;
double lineHeight = (floorAfter > floorBefore) ? verticalLineHeight : -verticalLineHeight;
std::vector<NavRoutingPolylineCreateParams> results;
uint coordinateCount = static_cast<uint>(coordinates.size());
Eegeo_ASSERT(coordinateCount >= 2, "Can't make a floor transition line with a single point");
std::vector<Eegeo::Space::LatLong> startCoords;
startCoords.push_back(coordinates.at(0));
startCoords.push_back(coordinates.at(1));
std::vector<Eegeo::Space::LatLong> endCoords;
endCoords.push_back(coordinates.at(coordinateCount-2));
endCoords.push_back(coordinates.at(coordinateCount-1));
results.push_back(MakeNavRoutingPolylineCreateParamsForVerticalLine(startCoords, color, indoorMapId, floorBefore, 0, lineHeight));
results.push_back(MakeNavRoutingPolylineCreateParamsForVerticalLine(endCoords, color, indoorMapId, floorAfter, -lineHeight, 0));
return results;
}
RoutePolylineIdVector NavRoutingPolylineFactory::CreatePolylines(const std::vector<NavRoutingPolylineCreateParams>& polylineCreateParams)
{
RoutePolylineIdVector result;
const auto& ranges = BuildAmalgamationRanges(polylineCreateParams);
for (const auto& range : ranges)
{
const auto& polylineIds = CreateAmalgamatedPolylinesForRange(polylineCreateParams, range.first, range.second);
result.insert(result.end(), polylineIds.begin(), polylineIds.end());
}
return result;
}
RoutePolylineIdVector NavRoutingPolylineFactory::CreateAmalgamatedPolylinesForRange(
const std::vector<NavRoutingPolylineCreateParams>& polylineCreateParams,
const int rangeStartIndex,
const int rangeEndIndex
)
{
Eegeo_ASSERT(rangeStartIndex < rangeEndIndex);
Eegeo_ASSERT(rangeStartIndex >= 0);
Eegeo_ASSERT(rangeEndIndex <= polylineCreateParams.size());
RoutePolylineIdVector result;
std::vector<Eegeo::Space::LatLong> joinedCoordinates;
std::vector<double> joinedPerPointElevations;
bool anyPerPointElevations = false;
for (int i = rangeStartIndex; i < rangeEndIndex; ++i)
{
const auto& params = polylineCreateParams[i];
const auto& coordinates = params.GetCoordinates();
joinedCoordinates.insert(joinedCoordinates.end(), coordinates.begin(), coordinates.end());
if (!params.GetPerPointElevations().empty())
{
anyPerPointElevations = true;
}
}
if (anyPerPointElevations)
{
for (int i = rangeStartIndex; i < rangeEndIndex; ++i)
{
const auto& params = polylineCreateParams[i];
const auto& perPointElevations = params.GetPerPointElevations();
if (perPointElevations.empty())
{
// fill with zero
joinedPerPointElevations.insert(joinedPerPointElevations.end(), params.GetCoordinates().size(), 0.0);
}
else
{
joinedPerPointElevations.insert(joinedPerPointElevations.end(), perPointElevations.begin(), perPointElevations.end());
}
}
RemoveCoincidentPointsWithElevations(joinedCoordinates, joinedPerPointElevations);
}
else
{
RemoveCoincidentPoints(joinedCoordinates);
}
if (joinedCoordinates.size() > 1)
{
const auto& commonParams = polylineCreateParams[rangeStartIndex];
const auto& polylineParams = Eegeo::Shapes::Polylines::PolylineShapeBuilder()
.SetCoordinates(joinedCoordinates)
.SetPerPointElevations(joinedPerPointElevations)
.SetIndoorMap(commonParams.GetIndoorMapId(), commonParams.GetIndoorMapFloorId())
.SetFillColor(commonParams.GetColor())
.SetThickness(m_polylineConfig.routeThickness)
.SetMiterLimit(m_polylineConfig.miterLimit)
.SetElevation(m_polylineConfig.routeElevation)
.SetElevationMode(m_polylineConfig.routeElevationMode)
.SetShouldScaleWithMap(m_polylineConfig.shouldScaleWithMap)
.Build();
const auto& polylineId = m_shapeService.Create(polylineParams);
result.push_back(polylineId);
}
return result;
}
}
}
}
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file unit.cpp
* @author Dimitry Khokhlov <Dimitry@ethdev.com>
* @date 2015
* libethereum unit test functions coverage.
*/
#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>
#include <test/TestHelper.h>
#include "../JsonSpiritHeaders.h"
#include <libdevcore/TransientDirectory.h>
#include <libethereum/Defaults.h>
#include <libethereum/AccountDiff.h>
#include <libethereum/BlockChain.h>
#include <libethereum/BlockQueue.h>
using namespace dev;
using namespace eth;
BOOST_AUTO_TEST_SUITE(libethereum)
BOOST_AUTO_TEST_CASE(AccountDiff)
{
dev::eth::AccountDiff accDiff;
// Testing changeType
// exist = true exist_from = true AccountChange::Deletion
accDiff.exist = dev::Diff<bool>(true, false);
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::Deletion, "Account change type expected to be Deletion!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "XXX") == 0, "Deletion lead expected to be 'XXX'!");
// exist = true exist_from = false AccountChange::Creation
accDiff.exist = dev::Diff<bool>(false, true);
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::Creation, "Account change type expected to be Creation!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "+++") == 0, "Creation lead expected to be '+++'!");
// exist = false bn = true sc = true AccountChange::All
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::All, "Account change type expected to be All!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "***") == 0, "All lead expected to be '***'!");
// exist = false bn = true sc = false AccountChange::Intrinsic
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("00"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::Intrinsic, "Account change type expected to be Intrinsic!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), " * ") == 0, "Intrinsic lead expected to be ' * '!");
// exist = false bn = false sc = true AccountChange::CodeStorage
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 1);
accDiff.balance = dev::Diff<dev::u256>(1, 1);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::CodeStorage, "Account change type expected to be CodeStorage!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), "* *") == 0, "CodeStorage lead expected to be '* *'!");
// exist = false bn = false sc = false AccountChange::None
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 1);
accDiff.balance = dev::Diff<dev::u256>(1, 1);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("00"));
BOOST_CHECK_MESSAGE(accDiff.changeType() == dev::eth::AccountChange::None, "Account change type expected to be None!");
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead(accDiff.changeType()), " ") == 0, "None lead expected to be ' '!");
//ofstream
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.balance = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
std::map<dev::u256, dev::Diff<dev::u256>> storage;
storage[1] = accDiff.nonce;
accDiff.storage = storage;
std::stringstream buffer;
//if (!_s.exist.to())
buffer << accDiff;
BOOST_CHECK_MESSAGE(strcmp(buffer.str().c_str(), "") == 0, "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
accDiff.exist = dev::Diff<bool>(false, true);
buffer << accDiff;
BOOST_CHECK_MESSAGE(strcmp(buffer.str().c_str(), "#2 (+1) 2 (+1) $[1] ([0]) \n * 0000000000000000000000000000000000000000000000000000000000000001: 2 (1)") == 0, "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
storage[1] = dev::Diff<dev::u256>(0, 0);
accDiff.storage = storage;
buffer << accDiff;
BOOST_CHECK_MESSAGE(strcmp(buffer.str().c_str(), "#2 (+1) 2 (+1) $[1] ([0]) \n + 0000000000000000000000000000000000000000000000000000000000000001: 0") == 0, "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
storage[1] = dev::Diff<dev::u256>(1, 0);
accDiff.storage = storage;
buffer << accDiff;
BOOST_CHECK_MESSAGE(strcmp(buffer.str().c_str(), "#2 (+1) 2 (+1) $[1] ([0]) \nXXX 0000000000000000000000000000000000000000000000000000000000000001 (1)") == 0, "Not expected output: '" + buffer.str() + "'");
buffer.str(std::string());
BOOST_CHECK_MESSAGE(accDiff.changed() == true, "dev::eth::AccountDiff::changed(): incorrect return value");
//unexpected value
BOOST_CHECK_MESSAGE(strcmp(dev::eth::lead((dev::eth::AccountChange)123), "") != 0, "Not expected output when dev::eth::lead on unexpected value");
}
BOOST_AUTO_TEST_CASE(StateDiff)
{
dev::eth::StateDiff stateDiff;
dev::eth::AccountDiff accDiff;
accDiff.exist = dev::Diff<bool>(false, false);
accDiff.nonce = dev::Diff<dev::u256>(1, 2);
accDiff.balance = dev::Diff<dev::u256>(1, 2);
accDiff.code = dev::Diff<dev::bytes>(dev::fromHex("00"), dev::fromHex("01"));
std::map<dev::u256, dev::Diff<dev::u256>> storage;
storage[1] = accDiff.nonce;
accDiff.storage = storage;
std::stringstream buffer;
dev::Address address("001122334455667788991011121314151617181920");
stateDiff.accounts[address] = accDiff;
buffer << stateDiff;
BOOST_CHECK_MESSAGE(strcmp(buffer.str().c_str(), "1 accounts changed:\n*** 0000000000000000000000000000000000000000: \n") == 0, "Not expected output: '" + buffer.str() + "'");
}
BOOST_AUTO_TEST_CASE(BlockChain)
{
std::string genesisRLP = "0xf901fcf901f7a00000000000000000000000000000000000000000000000000000000000000000a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0cafd881ab193703b83816c49ff6c2bf6ba6f464a1be560c42106128c8dbc35e7a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421a056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000080832fefd8808454c98c8142a09eb47d85ccdf855f34cce66288b11d43a90d288dfc12eb7a900dcb7953a69a5a88448f2f62ce8e0392c0c0";
dev::bytes genesisBlockRLP = dev::test::importByteArray(genesisRLP);
BlockInfo biGenesisBlock(genesisBlockRLP);
std::string blockRLP = "0xf90260f901f9a01f08d9b73350445d921aa74a44861b5cc12d1258a4da8ac3e0a41d1757aa8112a01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0ef1552a40b7165c3cd773806b9e0c165b75356e0314bf0706f279c729f51e017a0dff021d89bbd62a468fc16a27430f8fbf0cc9e41473f26601fa9e4bebd0660d5a0bc37d79753ad738a6dac4921e57392f145d8887476de3f783dfa7edae9283e52b90100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008302000001832fefd882520884558c98ed80a0f8e40e5173c7d73b2214e311c109fec63eb116b8ff90f78989e1a65082d6e74f8871f5f6541955ba68f861f85f800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d870a801ca0a1da1d695f9ff1595dcd950cd8f001bfb69e0ed6e731ad51353f52ed9c7117e3a0fe5f0ef2425069a91b2619d3147ab3a8386542be9b4c7ef738a0553d22361646c0";
dev::bytes blockRLPbytes = dev::test::importByteArray(blockRLP);
BlockInfo biBlock(blockRLPbytes);
TransientDirectory td1, td2;
State trueState(OverlayDB(State::openDB(td1.path())), BaseState::Empty, biGenesisBlock.coinbaseAddress);
dev::eth::BlockChain trueBc(genesisBlockRLP, td2.path(), WithExisting::Verify);
json_spirit::mObject o;
json_spirit::mObject accountaddress;
json_spirit::mObject account;
account["balance"] = "0x02540be400";
account["code"] = "0x";
account["nonce"] = "0x00";
account["storage"] = json_spirit::mObject();
accountaddress["a94f5374fce5edbc8e2a8697c15331677e6ebf0b"] = account;
o["pre"] = accountaddress;
dev::test::ImportTest importer(o["pre"].get_obj());
importer.importState(o["pre"].get_obj(), trueState);
trueState.commit();
trueBc.import(blockRLPbytes, trueState.db());
std::stringstream buffer;
buffer << trueBc;
BOOST_CHECK_MESSAGE(strcmp(buffer.str().c_str(), "96d3fba448912a3f714221956ad5b6b7984236d4a1748c7f8ff5d637ca88e19f00: 1 @ 1f08d9b73350445d921aa74a44861b5cc12d1258a4da8ac3e0a41d1757aa8112\n") == 0, "Not expected output: '" + buffer.str() + "'");
trueBc.garbageCollect(true);
//Block Queue Test
BlockQueue bcQueue;
bcQueue.tick(trueBc);
QueueStatus bStatus = bcQueue.blockStatus(trueBc.info().hash());
BOOST_CHECK(bStatus == QueueStatus::Unknown);
dev::bytesConstRef bytesConst(&blockRLPbytes.at(0), blockRLPbytes.size());
bcQueue.import(bytesConst, trueBc);
bStatus = bcQueue.blockStatus(biBlock.hash());
BOOST_CHECK(bStatus == QueueStatus::Unknown);
bcQueue.clear();
}
BOOST_AUTO_TEST_CASE(BlockQueue)
{
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Cover: remove unit.cpp<commit_after><|endoftext|>
|
<commit_before>//Copyright (c) 2019 Ultimaker B.V.
#include "BeadingOrderOptimizer.h"
#include <iterator>
#include <unordered_map>
#include <vector>
#include <list>
#include "utils/SparsePointGridInclusive.h"
namespace arachne
{
void BeadingOrderOptimizer::optimize(std::vector<std::list<ExtrusionLine>>& polygons_per_index, std::vector<std::list<ExtrusionLine>>& polylines_per_index, bool reduce_overlapping_segments)
{
BeadingOrderOptimizer optimizer(polylines_per_index);
optimizer.fuzzyConnect(polygons_per_index, snap_dist, reduce_overlapping_segments);
}
BeadingOrderOptimizer::BeadingOrderOptimizer(std::vector<std::list<ExtrusionLine>>& polylines_per_index)
: polylines_per_index(polylines_per_index)
{
for (auto& polylines : polylines_per_index)
{
for (std::list<ExtrusionLine>::iterator polyline_it = polylines.begin(); polyline_it != polylines.end(); ++polyline_it)
{
ExtrusionLine& polyline = *polyline_it;
assert(polyline.junctions.size() >= 2); // otherwise the front and back ExtrusionLineEndRef would be mapped to from the same location
if (polyline.junctions.empty()) continue; // shouldn't happen
polyline_end_points.emplace(polyline.junctions.front().p, ExtrusionLineEndRef(polyline.inset_idx, polyline_it, true));
polyline_end_points.emplace(polyline.junctions.back().p, ExtrusionLineEndRef(polyline.inset_idx, polyline_it, false));
}
}
}
void BeadingOrderOptimizer::fuzzyConnect(std::vector<std::list<ExtrusionLine>>& polygons_per_index, coord_t snap_dist, bool reduce_overlapping_segments)
{
struct Locator
{
Point operator()(const ExtrusionLineEndRef& it)
{
return it.p();
}
};
SparsePointGridInclusive<ExtrusionLineEndRef> polyline_grid(snap_dist); // inclusive because iterators might get invalidated
for (std::list<ExtrusionLine>& polys : polylines_per_index)
{
for (auto poly_it = polys.begin(); poly_it != polys.end(); ++poly_it)
{
for (bool front : { true, false })
{
ExtrusionLineEndRef ref(poly_it->inset_idx, poly_it, front);
polyline_grid.insert(ref.p(), ref);
}
}
}
struct PointLocator
{
Point operator()(const Point& p) { return p; }
};
SparsePointGrid<Point, PointLocator> polygon_grid(snap_dist); // inclusive because iterators might get invalidated
for (auto polygons : polygons_per_index)
for (auto polygon : polygons)
for (ExtrusionJunction& junction : polygon.junctions)
polygon_grid.insert(junction.p);
// order of end_points_to_check and nearby_end_points determines which ends are connected together
// TODO: decide on the best way to connect polylines at 3-way intersections
std::list<ExtrusionLineEndRef> end_points_to_check;
for (std::list<ExtrusionLine>& polys : polylines_per_index)
{
for (auto poly_it = polys.begin(); poly_it != polys.end(); ++poly_it)
{
assert(poly_it->junctions.size() > 1);
for (bool front : { true, false })
{
end_points_to_check.emplace_back(poly_it->inset_idx, poly_it, front);
}
}
}
for (auto it = end_points_to_check.begin(); it != end_points_to_check.end(); ++it)
{
ExtrusionLineEndRef& end_point = *it;
if (end_point.polyline->junctions.empty())
{ // there is no line. We cannot do anything because we don't know where this ghost line initially was
continue;
}
Point p = end_point.p();
bool end_point_has_changed = false; // Whether the end_point ref now points to a new end compared to where it was initially pointing to
bool has_connected = polygon_grid.getAnyNearby(p, snap_dist) != nullptr; // we check whether polygons were already connected together here
if (has_connected && !reduce_overlapping_segments)
{ // don't process nearby polyline endpoints
continue;
}
if (has_connected)
{
coord_t extrusion_width = end_point.front? end_point.polyline->junctions.front().w : end_point.polyline->junctions.back().w;
if (end_point.front)
{
reduceIntersectionOverlap(*end_point.polyline, end_point.polyline->junctions.begin(), 0, extrusion_width / 2);
}
else
{
reduceIntersectionOverlap(*end_point.polyline, end_point.polyline->junctions.rbegin(), 0, extrusion_width / 2);
}
}
std::vector<ExtrusionLineEndRef> nearby_end_points = polyline_grid.getNearbyVals(p, snap_dist);
for (size_t other_end_idx = 0; other_end_idx < nearby_end_points.size(); ++other_end_idx)
{
ExtrusionLineEndRef& other_end = nearby_end_points[other_end_idx];
assert(!end_point.polyline->junctions.empty() || has_connected);
if (other_end.polyline->junctions.empty())
{
continue;
}
if (end_point == other_end)
if ((!has_connected || !end_point_has_changed) // only reduce overlap if the end point ref hasn't changed because of connecting
// NOTE: connecting might change the junctions in polyline and therefore the ExtrusionLineRef [end_point] might now refer to a new end point!
)
{
continue;
}
if (!shorterThen(p - other_end.p(), snap_dist)
)
{ // the other end is not really a nearby other end
continue;
}
coord_t other_end_polyline_length = other_end.polyline->computeLength();
if (&*end_point.polyline == &*other_end.polyline
&& (other_end.polyline->junctions.size() <= 2 || other_end_polyline_length < snap_dist * 2)
)
{ // the other end is of the same really short polyline
continue;
}
if (!has_connected)
{
int_fast8_t changed_side_is_front = -1; // unset bool; whether we have changed what the front of the polyline of [end_point] is rather than the back (stays -1 if we don't need to reinsert any list change because it is now a closed polygon)
if (&*end_point.polyline == &*other_end.polyline)
{ // we can close this polyline into a polygon
polygons_per_index.resize(std::max(polygons_per_index.size(), static_cast<size_t>(end_point.inset_idx + 1)));
polygons_per_index[end_point.inset_idx].emplace_back(*end_point.polyline);
for (ExtrusionJunction& junction : end_point.polyline->junctions)
polygon_grid.insert(junction.p);
end_point.polyline->junctions.clear();
}
else if (!end_point.front && other_end.front)
{
end_point.polyline->junctions.splice(end_point.polyline->junctions.end(), other_end.polyline->junctions);
changed_side_is_front = 0;
}
else if (end_point.front && !other_end.front)
{
end_point.polyline->junctions.splice(end_point.polyline->junctions.begin(), other_end.polyline->junctions);
changed_side_is_front = 1;
}
else if (end_point.front && other_end.front)
{
end_point.polyline->junctions.insert(end_point.polyline->junctions.begin(), other_end.polyline->junctions.rbegin(), other_end.polyline->junctions.rend());
other_end.polyline->junctions.clear();
changed_side_is_front = 1;
}
else // if (!end_point.front && !other_end.front)
{
end_point.polyline->junctions.insert(end_point.polyline->junctions.end(), other_end.polyline->junctions.rbegin(), other_end.polyline->junctions.rend());
other_end.polyline->junctions.clear();
changed_side_is_front = 0;
}
if (changed_side_is_front != -1)
{
ExtrusionLineEndRef line_untouched_end(end_point.inset_idx, end_point.polyline, changed_side_is_front);
polyline_grid.insert(line_untouched_end.p(), line_untouched_end);
end_points_to_check.emplace_back(line_untouched_end);
nearby_end_points.emplace_back(line_untouched_end);
end_point_has_changed = end_point.front == changed_side_is_front && other_end_polyline_length > snap_dist * 2;
}
has_connected = true;
if (!reduce_overlapping_segments)
{ // don't continue going over nearby polyline ends
break;
}
}
else
{
coord_t extrusion_width = other_end.front? other_end.polyline->junctions.front().w : other_end.polyline->junctions.back().w;
if (other_end.front)
{
reduceIntersectionOverlap(*other_end.polyline, other_end.polyline->junctions.begin(), 0, extrusion_width / 2);
}
else
{
reduceIntersectionOverlap(*other_end.polyline, other_end.polyline->junctions.rbegin(), 0, extrusion_width / 2);
}
}
}
}
// remove emptied lists
// afterwards, because otherwise iterators would be invalid during the connecting algorithm
for (std::list<ExtrusionLine>& polys : polylines_per_index)
{
for (auto poly_it = polys.begin(); poly_it != polys.end();)
{
if (poly_it->junctions.empty()
|| poly_it->computeLength() < 2 * snap_dist) // too small segments might have been overlooked byecause of the fuzzy nature of matching end points to each other
{
poly_it = polys.erase(poly_it);
}
else
{
poly_it++;
}
}
}
}
template<typename directional_iterator>
void BeadingOrderOptimizer::reduceIntersectionOverlap(ExtrusionLine& polyline, directional_iterator polyline_it, coord_t traveled_dist, coord_t reduction_length)
{
ExtrusionJunction& start_junction = *polyline_it;
directional_iterator next_junction_it = polyline_it; next_junction_it++;
if (isEnd(next_junction_it, polyline))
{
return;
}
ExtrusionJunction& next_junction = *next_junction_it;
Point a = start_junction.p;
Point b = next_junction.p;
Point ab = b - a;
coord_t length = vSize(ab);
coord_t total_reduction_length = reduction_length + start_junction.w / 2;
total_reduction_length *= (1.0 - intersection_overlap);
if (length > 0 && traveled_dist + length > total_reduction_length)
{
coord_t reduction_left = total_reduction_length - traveled_dist;
Point mid = a + ab * std::max(static_cast<coord_t>(0), std::min(length, reduction_left)) / length;
std::list<ExtrusionJunction>::iterator forward_it = getInsertPosIt(next_junction_it);
coord_t mid_w = start_junction.w + (next_junction.w - start_junction.w) * reduction_left / length;
polyline.junctions.insert(forward_it, ExtrusionJunction(mid, mid_w, start_junction.perimeter_index));
}
else
{
// NOTE: polyline_start_it was already increased
reduceIntersectionOverlap(polyline, next_junction_it, traveled_dist + length, reduction_length);
}
if (polyline.junctions.size() > 1)
{
polyline.junctions.erase(getSelfPosIt(polyline_it));
}
if (polyline.junctions.size() == 1)
{
polyline.junctions.clear();
}
}
template<>
bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::iterator it, ExtrusionLine& polyline)
{
return it == polyline.junctions.end();
}
template<>
bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::reverse_iterator it, ExtrusionLine& polyline)
{
return it == polyline.junctions.rend();
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::iterator it)
{
return it;
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::reverse_iterator it)
{
return it.base();
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::iterator it)
{
return it;
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::reverse_iterator it)
{
return (++it).base();
}
void BeadingOrderOptimizer::debugCheck()
{
#ifdef DEBUG
for (auto& polylines : polylines_per_index)
{
for (ExtrusionLine& polyline : polylines)
{
for (ExtrusionJunction& junction : polyline.junctions)
{
assert(junction.perimeter_index == polyline.inset_idx);
assert(junction.p.X < 1000000 && junction.p.Y < 1000000);
assert(junction.p.X > -1000000 && junction.p.Y > -1000000);
}
}
}
#endif
};
} // namespace arachne
<commit_msg>connect odd segments to polygons preferably<commit_after>//Copyright (c) 2019 Ultimaker B.V.
#include "BeadingOrderOptimizer.h"
#include <iterator>
#include <unordered_map>
#include <vector>
#include <list>
#include "utils/SparsePointGridInclusive.h"
namespace arachne
{
void BeadingOrderOptimizer::optimize(std::vector<std::list<ExtrusionLine>>& polygons_per_index, std::vector<std::list<ExtrusionLine>>& polylines_per_index, bool reduce_overlapping_segments)
{
BeadingOrderOptimizer optimizer(polylines_per_index);
optimizer.fuzzyConnect(polygons_per_index, snap_dist, reduce_overlapping_segments);
}
BeadingOrderOptimizer::BeadingOrderOptimizer(std::vector<std::list<ExtrusionLine>>& polylines_per_index)
: polylines_per_index(polylines_per_index)
{
for (auto& polylines : polylines_per_index)
{
for (std::list<ExtrusionLine>::iterator polyline_it = polylines.begin(); polyline_it != polylines.end(); ++polyline_it)
{
ExtrusionLine& polyline = *polyline_it;
assert(polyline.junctions.size() >= 2); // otherwise the front and back ExtrusionLineEndRef would be mapped to from the same location
if (polyline.junctions.empty()) continue; // shouldn't happen
polyline_end_points.emplace(polyline.junctions.front().p, ExtrusionLineEndRef(polyline.inset_idx, polyline_it, true));
polyline_end_points.emplace(polyline.junctions.back().p, ExtrusionLineEndRef(polyline.inset_idx, polyline_it, false));
}
}
}
void BeadingOrderOptimizer::fuzzyConnect(std::vector<std::list<ExtrusionLine>>& polygons_per_index, coord_t snap_dist, bool reduce_overlapping_segments)
{
struct Locator
{
Point operator()(const ExtrusionLineEndRef& it)
{
return it.p();
}
};
SparsePointGridInclusive<ExtrusionLineEndRef> polyline_grid(snap_dist); // inclusive because iterators might get invalidated
for (std::list<ExtrusionLine>& polys : polylines_per_index)
{
for (auto poly_it = polys.begin(); poly_it != polys.end(); ++poly_it)
{
for (bool front : { true, false })
{
ExtrusionLineEndRef ref(poly_it->inset_idx, poly_it, front);
polyline_grid.insert(ref.p(), ref);
}
}
}
struct PointLocator
{
Point operator()(const Point& p) { return p; }
};
SparsePointGrid<Point, PointLocator> polygon_grid(snap_dist); // inclusive because iterators might get invalidated
for (auto polygons : polygons_per_index)
for (auto polygon : polygons)
for (ExtrusionJunction& junction : polygon.junctions)
polygon_grid.insert(junction.p);
// order of end_points_to_check and nearby_end_points determines which ends are connected together
// TODO: decide on the best way to connect polylines at 3-way intersections
std::list<ExtrusionLineEndRef> end_points_to_check;
for (std::list<ExtrusionLine>& polys : polylines_per_index)
{
for (bool odd_lines : { true, false })
{ // try to combine odd lines into polygons first!
for (auto poly_it = polys.begin(); poly_it != polys.end(); ++poly_it)
{
if (poly_it->is_odd != odd_lines)
{
continue;
}
assert(poly_it->junctions.size() > 1);
for (bool front : { true, false })
{
end_points_to_check.emplace_back(poly_it->inset_idx, poly_it, front);
}
}
}
}
for (auto it = end_points_to_check.begin(); it != end_points_to_check.end(); ++it)
{
ExtrusionLineEndRef& end_point = *it;
if (end_point.polyline->junctions.empty())
{ // there is no line. We cannot do anything because we don't know where this ghost line initially was
continue;
}
Point p = end_point.p();
bool end_point_has_changed = false; // Whether the end_point ref now points to a new end compared to where it was initially pointing to
bool has_connected = polygon_grid.getAnyNearby(p, snap_dist) != nullptr; // we check whether polygons were already connected together here
if (has_connected && !reduce_overlapping_segments)
{ // don't process nearby polyline endpoints
continue;
}
if (has_connected)
{
coord_t extrusion_width = end_point.front? end_point.polyline->junctions.front().w : end_point.polyline->junctions.back().w;
if (end_point.front)
{
reduceIntersectionOverlap(*end_point.polyline, end_point.polyline->junctions.begin(), 0, extrusion_width / 2);
}
else
{
reduceIntersectionOverlap(*end_point.polyline, end_point.polyline->junctions.rbegin(), 0, extrusion_width / 2);
}
}
std::vector<ExtrusionLineEndRef> nearby_end_points = polyline_grid.getNearbyVals(p, snap_dist);
for (size_t other_end_idx = 0; other_end_idx < nearby_end_points.size(); ++other_end_idx)
{
ExtrusionLineEndRef& other_end = nearby_end_points[other_end_idx];
assert(!end_point.polyline->junctions.empty() || has_connected);
if (other_end.polyline->junctions.empty())
{
continue;
}
if (end_point == other_end)
if ((!has_connected || !end_point_has_changed) // only reduce overlap if the end point ref hasn't changed because of connecting
// NOTE: connecting might change the junctions in polyline and therefore the ExtrusionLineRef [end_point] might now refer to a new end point!
)
{
continue;
}
if (!shorterThen(p - other_end.p(), snap_dist)
)
{ // the other end is not really a nearby other end
continue;
}
coord_t other_end_polyline_length = other_end.polyline->computeLength();
if (&*end_point.polyline == &*other_end.polyline
&& (other_end.polyline->junctions.size() <= 2 || other_end_polyline_length < snap_dist * 2)
)
{ // the other end is of the same really short polyline
continue;
}
if (!has_connected)
{
int_fast8_t changed_side_is_front = -1; // unset bool; whether we have changed what the front of the polyline of [end_point] is rather than the back (stays -1 if we don't need to reinsert any list change because it is now a closed polygon)
if (&*end_point.polyline == &*other_end.polyline)
{ // we can close this polyline into a polygon
polygons_per_index.resize(std::max(polygons_per_index.size(), static_cast<size_t>(end_point.inset_idx + 1)));
polygons_per_index[end_point.inset_idx].emplace_back(*end_point.polyline);
for (ExtrusionJunction& junction : end_point.polyline->junctions)
polygon_grid.insert(junction.p);
end_point.polyline->junctions.clear();
}
else if (!end_point.front && other_end.front)
{
end_point.polyline->junctions.splice(end_point.polyline->junctions.end(), other_end.polyline->junctions);
changed_side_is_front = 0;
}
else if (end_point.front && !other_end.front)
{
end_point.polyline->junctions.splice(end_point.polyline->junctions.begin(), other_end.polyline->junctions);
changed_side_is_front = 1;
}
else if (end_point.front && other_end.front)
{
end_point.polyline->junctions.insert(end_point.polyline->junctions.begin(), other_end.polyline->junctions.rbegin(), other_end.polyline->junctions.rend());
other_end.polyline->junctions.clear();
changed_side_is_front = 1;
}
else // if (!end_point.front && !other_end.front)
{
end_point.polyline->junctions.insert(end_point.polyline->junctions.end(), other_end.polyline->junctions.rbegin(), other_end.polyline->junctions.rend());
other_end.polyline->junctions.clear();
changed_side_is_front = 0;
}
if (changed_side_is_front != -1)
{
ExtrusionLineEndRef line_untouched_end(end_point.inset_idx, end_point.polyline, changed_side_is_front);
polyline_grid.insert(line_untouched_end.p(), line_untouched_end);
end_points_to_check.emplace_back(line_untouched_end);
nearby_end_points.emplace_back(line_untouched_end);
end_point_has_changed = end_point.front == changed_side_is_front && other_end_polyline_length > snap_dist * 2;
}
has_connected = true;
if (!reduce_overlapping_segments)
{ // don't continue going over nearby polyline ends
break;
}
}
else
{
coord_t extrusion_width = other_end.front? other_end.polyline->junctions.front().w : other_end.polyline->junctions.back().w;
if (other_end.front)
{
reduceIntersectionOverlap(*other_end.polyline, other_end.polyline->junctions.begin(), 0, extrusion_width / 2);
}
else
{
reduceIntersectionOverlap(*other_end.polyline, other_end.polyline->junctions.rbegin(), 0, extrusion_width / 2);
}
}
}
}
// remove emptied lists
// afterwards, because otherwise iterators would be invalid during the connecting algorithm
for (std::list<ExtrusionLine>& polys : polylines_per_index)
{
for (auto poly_it = polys.begin(); poly_it != polys.end();)
{
if (poly_it->junctions.empty()
|| poly_it->computeLength() < 2 * snap_dist) // too small segments might have been overlooked byecause of the fuzzy nature of matching end points to each other
{
poly_it = polys.erase(poly_it);
}
else
{
poly_it++;
}
}
}
}
template<typename directional_iterator>
void BeadingOrderOptimizer::reduceIntersectionOverlap(ExtrusionLine& polyline, directional_iterator polyline_it, coord_t traveled_dist, coord_t reduction_length)
{
ExtrusionJunction& start_junction = *polyline_it;
directional_iterator next_junction_it = polyline_it; next_junction_it++;
if (isEnd(next_junction_it, polyline))
{
return;
}
ExtrusionJunction& next_junction = *next_junction_it;
Point a = start_junction.p;
Point b = next_junction.p;
Point ab = b - a;
coord_t length = vSize(ab);
coord_t total_reduction_length = reduction_length + start_junction.w / 2;
total_reduction_length *= (1.0 - intersection_overlap);
if (length > 0 && traveled_dist + length > total_reduction_length)
{
coord_t reduction_left = total_reduction_length - traveled_dist;
Point mid = a + ab * std::max(static_cast<coord_t>(0), std::min(length, reduction_left)) / length;
std::list<ExtrusionJunction>::iterator forward_it = getInsertPosIt(next_junction_it);
coord_t mid_w = start_junction.w + (next_junction.w - start_junction.w) * reduction_left / length;
polyline.junctions.insert(forward_it, ExtrusionJunction(mid, mid_w, start_junction.perimeter_index));
}
else
{
// NOTE: polyline_start_it was already increased
reduceIntersectionOverlap(polyline, next_junction_it, traveled_dist + length, reduction_length);
}
if (polyline.junctions.size() > 1)
{
polyline.junctions.erase(getSelfPosIt(polyline_it));
}
if (polyline.junctions.size() == 1)
{
polyline.junctions.clear();
}
}
template<>
bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::iterator it, ExtrusionLine& polyline)
{
return it == polyline.junctions.end();
}
template<>
bool BeadingOrderOptimizer::isEnd(std::list<ExtrusionJunction>::reverse_iterator it, ExtrusionLine& polyline)
{
return it == polyline.junctions.rend();
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::iterator it)
{
return it;
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getInsertPosIt(std::list<ExtrusionJunction>::reverse_iterator it)
{
return it.base();
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::iterator it)
{
return it;
}
template<>
std::list<ExtrusionJunction>::iterator BeadingOrderOptimizer::getSelfPosIt(std::list<ExtrusionJunction>::reverse_iterator it)
{
return (++it).base();
}
void BeadingOrderOptimizer::debugCheck()
{
#ifdef DEBUG
for (auto& polylines : polylines_per_index)
{
for (ExtrusionLine& polyline : polylines)
{
for (ExtrusionJunction& junction : polyline.junctions)
{
assert(junction.perimeter_index == polyline.inset_idx);
assert(junction.p.X < 1000000 && junction.p.Y < 1000000);
assert(junction.p.X > -1000000 && junction.p.Y > -1000000);
}
}
}
#endif
};
} // namespace arachne
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_attr_update.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_attr_update.H
/// @brief Programatic over-rides related to effective config
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Luke Mulkey <lwmulkey@us.ibm.com>
// *HWP FW Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
using fapi2::TARGET_TYPE_MCS;
typedef fapi2::ReturnCode (*p9_mss_attr_update_FP_t) (const fapi2::Target<TARGET_TYPE_MCS>&);
extern "C"
{
///
/// @brief Programatic over-rides related to effective config
/// @param[in] i_target, the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_attr_update( const fapi2::Target<TARGET_TYPE_MCS>& i_target );
}
<commit_msg>Change L1 headers to include defines to avoid duplicate inclusion<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_attr_update.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_mss_attr_update.H
/// @brief Programatic over-rides related to effective config
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Luke Mulkey <lwmulkey@us.ibm.com>
// *HWP FW Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
#ifndef __P9_MSS_ATTR_UPDATE__
#define __P9_MSS_ATTR_UPDATE__
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_mss_attr_update_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_MCS>&);
extern "C"
{
///
/// @brief Programatic over-rides related to effective config
/// @param[in] i_target, the controller (e.g., MCS)
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_attr_update( const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_target );
}
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/browser_actions_toolbar_gtk.h"
#include <gtk/gtk.h>
#include <vector>
#include "app/gfx/canvas_paint.h"
#include "app/gfx/gtk_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_browser_event_router.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/image_loading_tracker.h"
#include "chrome/browser/gtk/extension_popup_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
// The size of each button on the toolbar.
static const int kButtonSize = 29;
class BrowserActionButton : public NotificationObserver,
public ImageLoadingTracker::Observer {
public:
BrowserActionButton(Browser* browser, Extension* extension)
: browser_(browser),
extension_(extension),
button_(gtk_chrome_button_new()) {
DCHECK(extension_->browser_action());
gtk_widget_set_size_request(button_.get(), kButtonSize, kButtonSize);
browser_action_icons_.resize(
extension->browser_action()->icon_paths().size(), NULL);
tracker_ = new ImageLoadingTracker(this, browser_action_icons_.size());
for (size_t i = 0; i < extension->browser_action()->icon_paths().size();
++i) {
tracker_->PostLoadImageTask(
extension->GetResource(extension->browser_action()->icon_paths()[i]),
gfx::Size(Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize));
}
OnStateUpdated();
// We need to hook up extension popups here. http://crbug.com/23897
g_signal_connect(button_.get(), "clicked",
G_CALLBACK(OnButtonClicked), this);
g_signal_connect_after(button_.get(), "expose-event",
G_CALLBACK(OnExposeEvent), this);
registrar_.Add(this, NotificationType::EXTENSION_BROWSER_ACTION_UPDATED,
Source<ExtensionAction>(extension->browser_action()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
OnThemeChanged();
}
~BrowserActionButton() {
for (size_t i = 0; i < browser_action_icons_.size(); ++i) {
if (browser_action_icons_[i])
g_object_unref(browser_action_icons_[i]);
}
button_.Destroy();
tracker_->StopTrackingImageLoad();
}
GtkWidget* widget() { return button_.get(); }
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSION_BROWSER_ACTION_UPDATED)
OnStateUpdated();
else if (type == NotificationType::BROWSER_THEME_CHANGED)
OnThemeChanged();
else
NOTREACHED();
}
// ImageLoadingTracker::Observer implementation.
void OnImageLoaded(SkBitmap* image, size_t index) {
SkBitmap empty;
SkBitmap* bitmap = image ? image : ∅
browser_action_icons_[index] = gfx::GdkPixbufFromSkBitmap(bitmap);
OnStateUpdated();
}
private:
// Called when the tooltip has changed or an image has loaded.
void OnStateUpdated() {
gtk_widget_set_tooltip_text(button_.get(),
extension_->browser_action_state()->title().c_str());
if (browser_action_icons_.empty())
return;
GdkPixbuf* image =
browser_action_icons_[extension_->browser_action_state()->icon_index()];
if (image) {
gtk_button_set_image(GTK_BUTTON(button_.get()),
gtk_image_new_from_pixbuf(image));
}
}
void OnThemeChanged() {
gtk_chrome_button_set_use_gtk_rendering(GTK_CHROME_BUTTON(button_.get()),
GtkThemeProvider::GetFrom(browser_->profile())->UseGtkTheme());
}
static void OnButtonClicked(GtkWidget* widget, BrowserActionButton* action) {
if (action->extension_->browser_action()->is_popup()) {
ExtensionPopupGtk::Show(action->extension_->browser_action()->popup_url(),
action->browser_, gfx::Rect(widget->allocation));
} else {
ExtensionBrowserEventRouter::GetInstance()->BrowserActionExecuted(
action->browser_->profile(), action->extension_->id(),
action->browser_);
}
}
static gboolean OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
BrowserActionButton* action) {
if (action->extension_->browser_action_state()->badge_text().empty())
return FALSE;
gfx::CanvasPaint canvas(event, false);
gfx::Rect bounding_rect(widget->allocation);
action->extension_->browser_action_state()->PaintBadge(&canvas,
bounding_rect);
return FALSE;
}
// The Browser that executes a command when the button is pressed.
Browser* browser_;
// The extension that contains this browser action.
Extension* extension_;
// The gtk widget for this browser action.
OwnedWidgetGtk button_;
// Loads the button's icons for us on the file thread.
ImageLoadingTracker* tracker_;
// Icons for all the different states the button can be in. These will be NULL
// while they are loading.
std::vector<GdkPixbuf*> browser_action_icons_;
NotificationRegistrar registrar_;
};
BrowserActionsToolbarGtk::BrowserActionsToolbarGtk(Browser* browser)
: browser_(browser),
profile_(browser->profile()),
hbox_(gtk_hbox_new(0, FALSE)) {
ExtensionsService* extension_service = profile_->GetExtensionsService();
registrar_.Add(this, NotificationType::EXTENSION_LOADED,
Source<ExtensionsService>(extension_service));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
Source<ExtensionsService>(extension_service));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,
Source<ExtensionsService>(extension_service));
CreateAllButtons();
}
BrowserActionsToolbarGtk::~BrowserActionsToolbarGtk() {
hbox_.Destroy();
}
void BrowserActionsToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
Extension* extension = Details<Extension>(details).ptr();
if (type == NotificationType::EXTENSION_LOADED) {
CreateButtonForExtension(extension);
} else if (type == NotificationType::EXTENSION_UNLOADED ||
type == NotificationType::EXTENSION_UNLOADED_DISABLED) {
RemoveButtonForExtension(extension);
} else {
NOTREACHED() << "Received unexpected notification";
}
}
void BrowserActionsToolbarGtk::CreateAllButtons() {
ExtensionsService* extension_service = profile_->GetExtensionsService();
if (!extension_service) // The |extension_service| can be NULL in Incognito.
return;
// Get all browser actions, including those with popups.
std::vector<ExtensionAction*> browser_actions =
extension_service->GetBrowserActions(true);
for (size_t i = 0; i < browser_actions.size(); ++i) {
Extension* extension = extension_service->GetExtensionById(
browser_actions[i]->extension_id());
CreateButtonForExtension(extension);
}
}
void BrowserActionsToolbarGtk::CreateButtonForExtension(Extension* extension) {
// Only show extensions with browser actions and that have an icon.
if (!extension->browser_action() ||
extension->browser_action()->icon_paths().empty()) {
return;
}
RemoveButtonForExtension(extension);
linked_ptr<BrowserActionButton> button(
new BrowserActionButton(browser_, extension));
gtk_box_pack_end(GTK_BOX(hbox_.get()), button->widget(), FALSE, FALSE, 0);
gtk_widget_show(button->widget());
extension_button_map_[extension->id()] = button;
UpdateVisibility();
}
void BrowserActionsToolbarGtk::RemoveButtonForExtension(Extension* extension) {
if (extension_button_map_.erase(extension->id()))
UpdateVisibility();
}
void BrowserActionsToolbarGtk::UpdateVisibility() {
if (button_count() == 0)
gtk_widget_hide(widget());
else
gtk_widget_show(widget());
}
<commit_msg>Support for chrome.browserAction.setIcon(imageData) on linux.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gtk/browser_actions_toolbar_gtk.h"
#include <gtk/gtk.h>
#include <vector>
#include "app/gfx/canvas_paint.h"
#include "app/gfx/gtk_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extension_browser_event_router.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/image_loading_tracker.h"
#include "chrome/browser/gtk/extension_popup_gtk.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_source.h"
#include "chrome/common/notification_type.h"
// The size of each button on the toolbar.
static const int kButtonSize = 29;
class BrowserActionButton : public NotificationObserver,
public ImageLoadingTracker::Observer {
public:
BrowserActionButton(Browser* browser, Extension* extension)
: browser_(browser),
extension_(extension),
button_(gtk_chrome_button_new()),
gdk_icon_(NULL) {
DCHECK(extension_->browser_action());
gtk_widget_set_size_request(button_.get(), kButtonSize, kButtonSize);
browser_action_icons_.resize(
extension->browser_action()->icon_paths().size());
tracker_ = new ImageLoadingTracker(this, browser_action_icons_.size());
for (size_t i = 0; i < extension->browser_action()->icon_paths().size();
++i) {
tracker_->PostLoadImageTask(
extension->GetResource(extension->browser_action()->icon_paths()[i]),
gfx::Size(Extension::kBrowserActionIconMaxSize,
Extension::kBrowserActionIconMaxSize));
}
OnStateUpdated();
// We need to hook up extension popups here. http://crbug.com/23897
g_signal_connect(button_.get(), "clicked",
G_CALLBACK(OnButtonClicked), this);
g_signal_connect_after(button_.get(), "expose-event",
G_CALLBACK(OnExposeEvent), this);
registrar_.Add(this, NotificationType::EXTENSION_BROWSER_ACTION_UPDATED,
Source<ExtensionAction>(extension->browser_action()));
registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED,
NotificationService::AllSources());
OnThemeChanged();
}
~BrowserActionButton() {
if (gdk_icon_)
g_object_unref(gdk_icon_);
button_.Destroy();
tracker_->StopTrackingImageLoad();
}
GtkWidget* widget() { return button_.get(); }
void Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::EXTENSION_BROWSER_ACTION_UPDATED)
OnStateUpdated();
else if (type == NotificationType::BROWSER_THEME_CHANGED)
OnThemeChanged();
else
NOTREACHED();
}
// ImageLoadingTracker::Observer implementation.
void OnImageLoaded(SkBitmap* image, size_t index) {
DCHECK(index < browser_action_icons_.size());
browser_action_icons_[index] = image ? *image : SkBitmap();
OnStateUpdated();
}
private:
// Called when the tooltip has changed or an image has loaded.
void OnStateUpdated() {
gtk_widget_set_tooltip_text(button_.get(),
extension_->browser_action_state()->title().c_str());
SkBitmap* image = extension_->browser_action_state()->icon();
if (!image) {
if (static_cast<size_t>(
extension_->browser_action_state()->icon_index()) <
browser_action_icons_.size()) {
image = &browser_action_icons_[
extension_->browser_action_state()->icon_index()];
}
}
if (image && !image->empty()) {
GdkPixbuf* current_gdk_icon = gdk_icon_;
gdk_icon_ = gfx::GdkPixbufFromSkBitmap(image);
gtk_button_set_image(GTK_BUTTON(button_.get()),
gtk_image_new_from_pixbuf(gdk_icon_));
if (current_gdk_icon)
g_object_unref(current_gdk_icon);
}
}
void OnThemeChanged() {
gtk_chrome_button_set_use_gtk_rendering(GTK_CHROME_BUTTON(button_.get()),
GtkThemeProvider::GetFrom(browser_->profile())->UseGtkTheme());
}
static void OnButtonClicked(GtkWidget* widget, BrowserActionButton* action) {
if (action->extension_->browser_action()->is_popup()) {
ExtensionPopupGtk::Show(action->extension_->browser_action()->popup_url(),
action->browser_, gfx::Rect(widget->allocation));
} else {
ExtensionBrowserEventRouter::GetInstance()->BrowserActionExecuted(
action->browser_->profile(), action->extension_->id(),
action->browser_);
}
}
static gboolean OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
BrowserActionButton* action) {
if (action->extension_->browser_action_state()->badge_text().empty())
return FALSE;
gfx::CanvasPaint canvas(event, false);
gfx::Rect bounding_rect(widget->allocation);
action->extension_->browser_action_state()->PaintBadge(&canvas,
bounding_rect);
return FALSE;
}
// The Browser that executes a command when the button is pressed.
Browser* browser_;
// The extension that contains this browser action.
Extension* extension_;
// The gtk widget for this browser action.
OwnedWidgetGtk button_;
// Loads the button's icons for us on the file thread.
ImageLoadingTracker* tracker_;
// Icons for all the different states the button can be in. These will be
// empty while they are loading.
std::vector<SkBitmap> browser_action_icons_;
// SkBitmap must be converted to GdkPixbuf before assignment to the button.
// This stores the current icon while it is in use.
GdkPixbuf* gdk_icon_;
NotificationRegistrar registrar_;
};
BrowserActionsToolbarGtk::BrowserActionsToolbarGtk(Browser* browser)
: browser_(browser),
profile_(browser->profile()),
hbox_(gtk_hbox_new(0, FALSE)) {
ExtensionsService* extension_service = profile_->GetExtensionsService();
registrar_.Add(this, NotificationType::EXTENSION_LOADED,
Source<ExtensionsService>(extension_service));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED,
Source<ExtensionsService>(extension_service));
registrar_.Add(this, NotificationType::EXTENSION_UNLOADED_DISABLED,
Source<ExtensionsService>(extension_service));
CreateAllButtons();
}
BrowserActionsToolbarGtk::~BrowserActionsToolbarGtk() {
hbox_.Destroy();
}
void BrowserActionsToolbarGtk::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
Extension* extension = Details<Extension>(details).ptr();
if (type == NotificationType::EXTENSION_LOADED) {
CreateButtonForExtension(extension);
} else if (type == NotificationType::EXTENSION_UNLOADED ||
type == NotificationType::EXTENSION_UNLOADED_DISABLED) {
RemoveButtonForExtension(extension);
} else {
NOTREACHED() << "Received unexpected notification";
}
}
void BrowserActionsToolbarGtk::CreateAllButtons() {
ExtensionsService* extension_service = profile_->GetExtensionsService();
if (!extension_service) // The |extension_service| can be NULL in Incognito.
return;
// Get all browser actions, including those with popups.
std::vector<ExtensionAction*> browser_actions =
extension_service->GetBrowserActions(true);
for (size_t i = 0; i < browser_actions.size(); ++i) {
Extension* extension = extension_service->GetExtensionById(
browser_actions[i]->extension_id());
CreateButtonForExtension(extension);
}
}
void BrowserActionsToolbarGtk::CreateButtonForExtension(Extension* extension) {
// Only show extensions with browser actions and that have an icon.
if (!extension->browser_action() ||
extension->browser_action()->icon_paths().empty()) {
return;
}
RemoveButtonForExtension(extension);
linked_ptr<BrowserActionButton> button(
new BrowserActionButton(browser_, extension));
gtk_box_pack_end(GTK_BOX(hbox_.get()), button->widget(), FALSE, FALSE, 0);
gtk_widget_show(button->widget());
extension_button_map_[extension->id()] = button;
UpdateVisibility();
}
void BrowserActionsToolbarGtk::RemoveButtonForExtension(Extension* extension) {
if (extension_button_map_.erase(extension->id()))
UpdateVisibility();
}
void BrowserActionsToolbarGtk::UpdateVisibility() {
if (button_count() == 0)
gtk_widget_hide(widget());
else
gtk_widget_show(widget());
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
* Copyright (c) 2018 MCCI Corporation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This the HAL to run LMIC on top of the Arduino environment.
*******************************************************************************/
#include <Arduino.h>
#include <SPI.h>
// include all the lmic header files, including ../lmic/hal.h
#include "../lmic.h"
// include the C++ hal.h
#include "hal.h"
// we may need some things from stdio.
#include <stdio.h>
// -----------------------------------------------------------------------------
// I/O
static const Arduino_LMIC::HalPinmap_t *plmic_pins;
static Arduino_LMIC::HalConfiguration_t *pHalConfig;
static Arduino_LMIC::HalConfiguration_t nullHalConig;
static void hal_interrupt_init(); // Fwd declaration
static void hal_io_init () {
// NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK
ASSERT(plmic_pins->nss != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[0] != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[1] != LMIC_UNUSED_PIN || plmic_pins->dio[2] != LMIC_UNUSED_PIN);
// Serial.print("nss: "); Serial.println(plmic_pins->nss);
// Serial.print("rst: "); Serial.println(plmic_pins->rst);
// Serial.print("dio[0]: "); Serial.println(plmic_pins->dio[0]);
// Serial.print("dio[1]: "); Serial.println(plmic_pins->dio[1]);
// Serial.print("dio[2]: "); Serial.println(plmic_pins->dio[2]);
// initialize SPI chip select to high (it's active low)
digitalWrite(plmic_pins->nss, HIGH);
pinMode(plmic_pins->nss, OUTPUT);
if (plmic_pins->rxtx != LMIC_UNUSED_PIN) {
// initialize to RX
digitalWrite(plmic_pins->rxtx, LOW != plmic_pins->rxtx_rx_active);
pinMode(plmic_pins->rxtx, OUTPUT);
}
if (plmic_pins->rst != LMIC_UNUSED_PIN) {
// initialize RST to floating
pinMode(plmic_pins->rst, INPUT);
}
hal_interrupt_init();
}
// val == 1 => tx
void hal_pin_rxtx (u1_t val) {
if (plmic_pins->rxtx != LMIC_UNUSED_PIN)
digitalWrite(plmic_pins->rxtx, val != plmic_pins->rxtx_rx_active);
}
// set radio RST pin to given value (or keep floating!)
void hal_pin_rst (u1_t val) {
if (plmic_pins->rst == LMIC_UNUSED_PIN)
return;
if(val == 0 || val == 1) { // drive pin
digitalWrite(plmic_pins->rst, val);
pinMode(plmic_pins->rst, OUTPUT);
} else { // keep pin floating
pinMode(plmic_pins->rst, INPUT);
}
}
s1_t hal_getRssiCal (void) {
return plmic_pins->rssi_cal;
}
#if !defined(LMIC_USE_INTERRUPTS)
static void hal_interrupt_init() {
pinMode(plmic_pins->dio[0], INPUT);
if (plmic_pins->dio[1] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[1], INPUT);
if (plmic_pins->dio[2] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[2], INPUT);
}
static bool dio_states[NUM_DIO] = {0};
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
if (dio_states[i] != digitalRead(plmic_pins->dio[i])) {
dio_states[i] = !dio_states[i];
if (dio_states[i])
radio_irq_handler(i);
}
}
}
#else
// Interrupt handlers
static ostime_t interrupt_time[NUM_DIO] = {0};
static void hal_isrPin0() {
ostime_t now = os_getTime();
interrupt_time[0] = now ? now : 1;
}
static void hal_isrPin1() {
ostime_t now = os_getTime();
interrupt_time[1] = now ? now : 1;
}
static void hal_isrPin2() {
ostime_t now = os_getTime();
interrupt_time[2] = now ? now : 1;
}
typedef void (*isr_t)();
static isr_t interrupt_fns[NUM_DIO] = {hal_isrPin0, hal_isrPin1, hal_isrPin2};
static void hal_interrupt_init() {
for (uint8_t i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
attachInterrupt(digitalPinToInterrupt(plmic_pins->dio[i]), interrupt_fns[i], RISING);
}
}
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
ostime_t iTime;
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
iTime = interrupt_time[i];
if (iTime) {
interrupt_time[i] = 0;
radio_irq_handler_v2(i, iTime);
}
}
}
#endif // LMIC_USE_INTERRUPTS
// -----------------------------------------------------------------------------
// SPI
static void hal_spi_init () {
SPI.begin();
}
void hal_pin_nss (u1_t val) {
if (!val) {
uint32_t spi_freq;
if ((spi_freq = plmic_pins->spi_freq) == 0)
spi_freq = LMIC_SPI_FREQ;
SPISettings settings(spi_freq, MSBFIRST, SPI_MODE0);
SPI.beginTransaction(settings);
} else {
SPI.endTransaction();
}
//Serial.println(val?">>":"<<");
digitalWrite(plmic_pins->nss, val);
}
// perform SPI transaction with radio
u1_t hal_spi (u1_t out) {
u1_t res = SPI.transfer(out);
/*
Serial.print(">");
Serial.print(out, HEX);
Serial.print("<");
Serial.println(res, HEX);
*/
return res;
}
// -----------------------------------------------------------------------------
// TIME
static void hal_time_init () {
// Nothing to do
}
u4_t hal_ticks () {
// Because micros() is scaled down in this function, micros() will
// overflow before the tick timer should, causing the tick timer to
// miss a significant part of its values if not corrected. To fix
// this, the "overflow" serves as an overflow area for the micros()
// counter. It consists of three parts:
// - The US_PER_OSTICK upper bits are effectively an extension for
// the micros() counter and are added to the result of this
// function.
// - The next bit overlaps with the most significant bit of
// micros(). This is used to detect micros() overflows.
// - The remaining bits are always zero.
//
// By comparing the overlapping bit with the corresponding bit in
// the micros() return value, overflows can be detected and the
// upper bits are incremented. This is done using some clever
// bitwise operations, to remove the need for comparisons and a
// jumps, which should result in efficient code. By avoiding shifts
// other than by multiples of 8 as much as possible, this is also
// efficient on AVR (which only has 1-bit shifts).
static uint8_t overflow = 0;
// Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,
// the others will be the lower bits of our return value.
uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;
// Most significant byte of scaled
uint8_t msb = scaled >> 24;
// Mask pointing to the overlapping bit in msb and overflow.
const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));
// Update overflow. If the overlapping bit is different
// between overflow and msb, it is added to the stored value,
// so the overlapping bit becomes equal again and, if it changed
// from 1 to 0, the upper bits are incremented.
overflow += (msb ^ overflow) & mask;
// Return the scaled value with the upper bits of stored added. The
// overlapping bit will be equal and the lower bits will be 0, so
// bitwise or is a no-op for them.
return scaled | ((uint32_t)overflow << 24);
// 0 leads to correct, but overly complex code (it could just return
// micros() unmodified), 8 leaves no room for the overlapping bit.
static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value");
}
// Returns the number of ticks until time. Negative values indicate that
// time has already passed.
static s4_t delta_time(u4_t time) {
return (s4_t)(time - hal_ticks());
}
void hal_waitUntil (u4_t time) {
s4_t delta = delta_time(time);
// From delayMicroseconds docs: Currently, the largest value that
// will produce an accurate delay is 16383.
while (delta > (16000 / US_PER_OSTICK)) {
delay(16);
delta -= (16000 / US_PER_OSTICK);
}
if (delta > 0)
delayMicroseconds(delta * US_PER_OSTICK);
}
// check and rewind for target time
u1_t hal_checkTimer (u4_t time) {
// No need to schedule wakeup, since we're not sleeping
return delta_time(time) <= 0;
}
static uint8_t irqlevel = 0;
void hal_disableIRQs () {
noInterrupts();
irqlevel++;
}
void hal_enableIRQs () {
if(--irqlevel == 0) {
interrupts();
// Instead of using proper interrupts (which are a bit tricky
// and/or not available on all pins on AVR), just poll the pin
// values. Since os_runloop disables and re-enables interrupts,
// putting this here makes sure we check at least once every
// loop.
//
// As an additional bonus, this prevents the can of worms that
// we would otherwise get for running SPI transfers inside ISRs
hal_io_check();
}
}
void hal_sleep () {
// Not implemented
}
// -----------------------------------------------------------------------------
#if defined(LMIC_PRINTF_TO)
#if !defined(__AVR)
static ssize_t uart_putchar (void *, const char *buf, size_t len) {
return LMIC_PRINTF_TO.write((const uint8_t *)buf, len);
}
static cookie_io_functions_t functions =
{
.read = NULL,
.write = uart_putchar,
.seek = NULL,
.close = NULL
};
void hal_printf_init() {
stdout = fopencookie(NULL, "w", functions);
if (stdout != nullptr) {
setvbuf(stdout, NULL, _IONBF, 0);
}
}
#else // defined(__AVR)
static int uart_putchar (char c, FILE *)
{
LMIC_PRINTF_TO.write(c) ;
return 0 ;
}
void hal_printf_init() {
// create a FILE structure to reference our UART output function
static FILE uartout;
memset(&uartout, 0, sizeof(uartout));
// fill in the UART file descriptor with pointer to writer.
fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
// The uart is the standard output device STDOUT.
stdout = &uartout ;
}
#endif // !defined(ESP8266) || defined(ESP31B) || defined(ESP32)
#endif // defined(LMIC_PRINTF_TO)
void hal_init (void) {
// use the global constant
Arduino_LMIC::hal_init_with_pinmap(&lmic_pins);
}
// hal_init_ex is a C API routine, written in C++, and it's called
// with a pointer to an lmic_pinmap. This is deprecated!
void hal_init_ex (const void *pContext) {
const lmic_pinmap * const pHalPinmap = (const lmic_pinmap *) pContext;
if (! Arduino_LMIC::hal_init_with_pinmap(pHalPinmap)) {
hal_failed(__FILE__, __LINE__);
}
}
// C++ API: initialize the HAL properly with a configuration object
namespace Arduino_LMIC {
bool hal_init_with_pinmap(const HalPinmap_t *pPinmap)
{
if (pPinmap == nullptr)
return false;
// set the static pinmap pointer.
plmic_pins = pPinmap;
// set the static HalConfiguration pointer.
HalConfiguration_t * const pThisHalConfig = pPinmap->pConfig;
if (pThisHalConfig != nullptr)
pHalConfig = pThisHalConfig;
else
pHalConfig = &nullHalConig;
pHalConfig->begin();
// configure radio I/O and interrupt handler
hal_io_init();
// configure radio SPI
hal_spi_init();
// configure timer and interrupt handler
hal_time_init();
#if defined(LMIC_PRINTF_TO)
// printf support
hal_printf_init();
#endif
// declare success
return true;
}
}; // namespace Arduino_LMIC
void hal_failed (const char *file, u2_t line) {
#if defined(LMIC_FAILURE_TO)
LMIC_FAILURE_TO.println("FAILURE ");
LMIC_FAILURE_TO.print(file);
LMIC_FAILURE_TO.print(':');
LMIC_FAILURE_TO.println(line);
LMIC_FAILURE_TO.flush();
#endif
hal_disableIRQs();
while(1);
}
ostime_t hal_setTcxoPower (u1_t val) {
// remove the const attribute for this call, because we
// the enclosing object might not be const afterall; it's just
// const to us.
return pHalConfig->setTcxoPower(val);
}
bit_t hal_queryTcxoControl(void) {
return pHalConfig->queryTcxoControl();
}<commit_msg>Clean up comments in hal.cpp<commit_after>/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
* Copyright (c) 2018 MCCI Corporation
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This the HAL to run LMIC on top of the Arduino environment.
*******************************************************************************/
#include <Arduino.h>
#include <SPI.h>
// include all the lmic header files, including ../lmic/hal.h
#include "../lmic.h"
// include the C++ hal.h
#include "hal.h"
// we may need some things from stdio.
#include <stdio.h>
// -----------------------------------------------------------------------------
// I/O
static const Arduino_LMIC::HalPinmap_t *plmic_pins;
static Arduino_LMIC::HalConfiguration_t *pHalConfig;
static Arduino_LMIC::HalConfiguration_t nullHalConig;
static void hal_interrupt_init(); // Fwd declaration
static void hal_io_init () {
// NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK
ASSERT(plmic_pins->nss != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[0] != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[1] != LMIC_UNUSED_PIN || plmic_pins->dio[2] != LMIC_UNUSED_PIN);
// Serial.print("nss: "); Serial.println(plmic_pins->nss);
// Serial.print("rst: "); Serial.println(plmic_pins->rst);
// Serial.print("dio[0]: "); Serial.println(plmic_pins->dio[0]);
// Serial.print("dio[1]: "); Serial.println(plmic_pins->dio[1]);
// Serial.print("dio[2]: "); Serial.println(plmic_pins->dio[2]);
// initialize SPI chip select to high (it's active low)
digitalWrite(plmic_pins->nss, HIGH);
pinMode(plmic_pins->nss, OUTPUT);
if (plmic_pins->rxtx != LMIC_UNUSED_PIN) {
// initialize to RX
digitalWrite(plmic_pins->rxtx, LOW != plmic_pins->rxtx_rx_active);
pinMode(plmic_pins->rxtx, OUTPUT);
}
if (plmic_pins->rst != LMIC_UNUSED_PIN) {
// initialize RST to floating
pinMode(plmic_pins->rst, INPUT);
}
hal_interrupt_init();
}
// val == 1 => tx
void hal_pin_rxtx (u1_t val) {
if (plmic_pins->rxtx != LMIC_UNUSED_PIN)
digitalWrite(plmic_pins->rxtx, val != plmic_pins->rxtx_rx_active);
}
// set radio RST pin to given value (or keep floating!)
void hal_pin_rst (u1_t val) {
if (plmic_pins->rst == LMIC_UNUSED_PIN)
return;
if(val == 0 || val == 1) { // drive pin
digitalWrite(plmic_pins->rst, val);
pinMode(plmic_pins->rst, OUTPUT);
} else { // keep pin floating
pinMode(plmic_pins->rst, INPUT);
}
}
s1_t hal_getRssiCal (void) {
return plmic_pins->rssi_cal;
}
#if !defined(LMIC_USE_INTERRUPTS)
static void hal_interrupt_init() {
pinMode(plmic_pins->dio[0], INPUT);
if (plmic_pins->dio[1] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[1], INPUT);
if (plmic_pins->dio[2] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[2], INPUT);
}
static bool dio_states[NUM_DIO] = {0};
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
if (dio_states[i] != digitalRead(plmic_pins->dio[i])) {
dio_states[i] = !dio_states[i];
if (dio_states[i])
radio_irq_handler(i);
}
}
}
#else
// Interrupt handlers
static ostime_t interrupt_time[NUM_DIO] = {0};
static void hal_isrPin0() {
ostime_t now = os_getTime();
interrupt_time[0] = now ? now : 1;
}
static void hal_isrPin1() {
ostime_t now = os_getTime();
interrupt_time[1] = now ? now : 1;
}
static void hal_isrPin2() {
ostime_t now = os_getTime();
interrupt_time[2] = now ? now : 1;
}
typedef void (*isr_t)();
static isr_t interrupt_fns[NUM_DIO] = {hal_isrPin0, hal_isrPin1, hal_isrPin2};
static void hal_interrupt_init() {
for (uint8_t i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
attachInterrupt(digitalPinToInterrupt(plmic_pins->dio[i]), interrupt_fns[i], RISING);
}
}
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
ostime_t iTime;
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
iTime = interrupt_time[i];
if (iTime) {
interrupt_time[i] = 0;
radio_irq_handler_v2(i, iTime);
}
}
}
#endif // LMIC_USE_INTERRUPTS
// -----------------------------------------------------------------------------
// SPI
static void hal_spi_init () {
SPI.begin();
}
void hal_pin_nss (u1_t val) {
if (!val) {
uint32_t spi_freq;
if ((spi_freq = plmic_pins->spi_freq) == 0)
spi_freq = LMIC_SPI_FREQ;
SPISettings settings(spi_freq, MSBFIRST, SPI_MODE0);
SPI.beginTransaction(settings);
} else {
SPI.endTransaction();
}
//Serial.println(val?">>":"<<");
digitalWrite(plmic_pins->nss, val);
}
// perform SPI transaction with radio
u1_t hal_spi (u1_t out) {
u1_t res = SPI.transfer(out);
/*
Serial.print(">");
Serial.print(out, HEX);
Serial.print("<");
Serial.println(res, HEX);
*/
return res;
}
// -----------------------------------------------------------------------------
// TIME
static void hal_time_init () {
// Nothing to do
}
u4_t hal_ticks () {
// Because micros() is scaled down in this function, micros() will
// overflow before the tick timer should, causing the tick timer to
// miss a significant part of its values if not corrected. To fix
// this, the "overflow" serves as an overflow area for the micros()
// counter. It consists of three parts:
// - The US_PER_OSTICK upper bits are effectively an extension for
// the micros() counter and are added to the result of this
// function.
// - The next bit overlaps with the most significant bit of
// micros(). This is used to detect micros() overflows.
// - The remaining bits are always zero.
//
// By comparing the overlapping bit with the corresponding bit in
// the micros() return value, overflows can be detected and the
// upper bits are incremented. This is done using some clever
// bitwise operations, to remove the need for comparisons and a
// jumps, which should result in efficient code. By avoiding shifts
// other than by multiples of 8 as much as possible, this is also
// efficient on AVR (which only has 1-bit shifts).
static uint8_t overflow = 0;
// Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,
// the others will be the lower bits of our return value.
uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;
// Most significant byte of scaled
uint8_t msb = scaled >> 24;
// Mask pointing to the overlapping bit in msb and overflow.
const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));
// Update overflow. If the overlapping bit is different
// between overflow and msb, it is added to the stored value,
// so the overlapping bit becomes equal again and, if it changed
// from 1 to 0, the upper bits are incremented.
overflow += (msb ^ overflow) & mask;
// Return the scaled value with the upper bits of stored added. The
// overlapping bit will be equal and the lower bits will be 0, so
// bitwise or is a no-op for them.
return scaled | ((uint32_t)overflow << 24);
// 0 leads to correct, but overly complex code (it could just return
// micros() unmodified), 8 leaves no room for the overlapping bit.
static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value");
}
// Returns the number of ticks until time. Negative values indicate that
// time has already passed.
static s4_t delta_time(u4_t time) {
return (s4_t)(time - hal_ticks());
}
void hal_waitUntil (u4_t time) {
s4_t delta = delta_time(time);
// From delayMicroseconds docs: Currently, the largest value that
// will produce an accurate delay is 16383.
while (delta > (16000 / US_PER_OSTICK)) {
delay(16);
delta -= (16000 / US_PER_OSTICK);
}
if (delta > 0)
delayMicroseconds(delta * US_PER_OSTICK);
}
// check and rewind for target time
u1_t hal_checkTimer (u4_t time) {
// No need to schedule wakeup, since we're not sleeping
return delta_time(time) <= 0;
}
static uint8_t irqlevel = 0;
void hal_disableIRQs () {
noInterrupts();
irqlevel++;
}
void hal_enableIRQs () {
if(--irqlevel == 0) {
interrupts();
// Instead of using proper interrupts (which are a bit tricky
// and/or not available on all pins on AVR), just poll the pin
// values. Since os_runloop disables and re-enables interrupts,
// putting this here makes sure we check at least once every
// loop.
//
// As an additional bonus, this prevents the can of worms that
// we would otherwise get for running SPI transfers inside ISRs
hal_io_check();
}
}
void hal_sleep () {
// Not implemented
}
// -----------------------------------------------------------------------------
#if defined(LMIC_PRINTF_TO)
#if !defined(__AVR)
static ssize_t uart_putchar (void *, const char *buf, size_t len) {
return LMIC_PRINTF_TO.write((const uint8_t *)buf, len);
}
static cookie_io_functions_t functions =
{
.read = NULL,
.write = uart_putchar,
.seek = NULL,
.close = NULL
};
void hal_printf_init() {
stdout = fopencookie(NULL, "w", functions);
if (stdout != nullptr) {
setvbuf(stdout, NULL, _IONBF, 0);
}
}
#else // defined(__AVR)
static int uart_putchar (char c, FILE *)
{
LMIC_PRINTF_TO.write(c) ;
return 0 ;
}
void hal_printf_init() {
// create a FILE structure to reference our UART output function
static FILE uartout;
memset(&uartout, 0, sizeof(uartout));
// fill in the UART file descriptor with pointer to writer.
fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
// The uart is the standard output device STDOUT.
stdout = &uartout ;
}
#endif // !defined(ESP8266) || defined(ESP31B) || defined(ESP32)
#endif // defined(LMIC_PRINTF_TO)
void hal_init (void) {
// use the global constant
Arduino_LMIC::hal_init_with_pinmap(&lmic_pins);
}
// hal_init_ex is a C API routine, written in C++, and it's called
// with a pointer to an lmic_pinmap.
void hal_init_ex (const void *pContext) {
const lmic_pinmap * const pHalPinmap = (const lmic_pinmap *) pContext;
if (! Arduino_LMIC::hal_init_with_pinmap(pHalPinmap)) {
hal_failed(__FILE__, __LINE__);
}
}
// C++ API: initialize the HAL properly with a configuration object
namespace Arduino_LMIC {
bool hal_init_with_pinmap(const HalPinmap_t *pPinmap)
{
if (pPinmap == nullptr)
return false;
// set the static pinmap pointer.
plmic_pins = pPinmap;
// set the static HalConfiguration pointer.
HalConfiguration_t * const pThisHalConfig = pPinmap->pConfig;
if (pThisHalConfig != nullptr)
pHalConfig = pThisHalConfig;
else
pHalConfig = &nullHalConig;
pHalConfig->begin();
// configure radio I/O and interrupt handler
hal_io_init();
// configure radio SPI
hal_spi_init();
// configure timer and interrupt handler
hal_time_init();
#if defined(LMIC_PRINTF_TO)
// printf support
hal_printf_init();
#endif
// declare success
return true;
}
}; // namespace Arduino_LMIC
void hal_failed (const char *file, u2_t line) {
#if defined(LMIC_FAILURE_TO)
LMIC_FAILURE_TO.println("FAILURE ");
LMIC_FAILURE_TO.print(file);
LMIC_FAILURE_TO.print(':');
LMIC_FAILURE_TO.println(line);
LMIC_FAILURE_TO.flush();
#endif
hal_disableIRQs();
while(1);
}
ostime_t hal_setTcxoPower (u1_t val) {
return pHalConfig->setTcxoPower(val);
}
bit_t hal_queryTcxoControl(void) {
return pHalConfig->queryTcxoControl();
}<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/test/test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
class LoadTimingObserverUITest : public UITest {
public:
LoadTimingObserverUITest()
: http_server_(net::TestServer::TYPE_HTTP, FilePath()) {
dom_automation_enabled_ = true;
}
protected:
net::TestServer http_server_;
};
TEST_F(LoadTimingObserverUITest, CacheHitAfterRedirect) {
ASSERT_TRUE(http_server_.Start());
GURL cached_page = http_server_.GetURL("cachetime");
std::string redirect = "server-redirect?" + cached_page.spec();
NavigateToURL(cached_page);
NavigateToURL(http_server_.GetURL(redirect));
scoped_refptr<TabProxy> tab_proxy = GetActiveTab();
int response_start = 0;
int response_end = 0;
ASSERT_TRUE(tab_proxy->ExecuteAndExtractInt(
L"", L"window.domAutomationController.send("
L"window.performance.timing.responseStart - "
L"window.performance.timing.navigationStart)", &response_start));
ASSERT_TRUE(tab_proxy->ExecuteAndExtractInt(
L"", L"window.domAutomationController.send("
L"window.performance.timing.responseEnd - "
L"window.performance.timing.navigationStart)", &response_end));
EXPECT_LE(response_start, response_end);
}
<commit_msg>Mark CacheHitAfterRedirect as flaky.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/test/test_server.h"
#include "testing/gtest/include/gtest/gtest.h"
class LoadTimingObserverUITest : public UITest {
public:
LoadTimingObserverUITest()
: http_server_(net::TestServer::TYPE_HTTP, FilePath()) {
dom_automation_enabled_ = true;
}
protected:
net::TestServer http_server_;
};
// http://crbug.com/102030
TEST_F(LoadTimingObserverUITest, FLAKY_CacheHitAfterRedirect) {
ASSERT_TRUE(http_server_.Start());
GURL cached_page = http_server_.GetURL("cachetime");
std::string redirect = "server-redirect?" + cached_page.spec();
NavigateToURL(cached_page);
NavigateToURL(http_server_.GetURL(redirect));
scoped_refptr<TabProxy> tab_proxy = GetActiveTab();
int response_start = 0;
int response_end = 0;
ASSERT_TRUE(tab_proxy->ExecuteAndExtractInt(
L"", L"window.domAutomationController.send("
L"window.performance.timing.responseStart - "
L"window.performance.timing.navigationStart)", &response_start));
ASSERT_TRUE(tab_proxy->ExecuteAndExtractInt(
L"", L"window.domAutomationController.send("
L"window.performance.timing.responseEnd - "
L"window.performance.timing.navigationStart)", &response_end));
EXPECT_LE(response_start, response_end);
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This the HAL to run LMIC on top of the Arduino environment.
*******************************************************************************/
#include <Arduino.h>
#include <SPI.h>
#include "../lmic.h"
#include "hal.h"
#include <stdio.h>
// -----------------------------------------------------------------------------
// I/O
static const lmic_pinmap *plmic_pins;
static void hal_interrupt_init(); // Fwd declaration
static void hal_io_init () {
// NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK
ASSERT(plmic_pins->nss != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[0] != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[1] != LMIC_UNUSED_PIN || plmic_pins->dio[2] != LMIC_UNUSED_PIN);
// Serial.print("nss: "); Serial.println(plmic_pins->nss);
// Serial.print("rst: "); Serial.println(plmic_pins->rst);
// Serial.print("dio[0]: "); Serial.println(plmic_pins->dio[0]);
// Serial.print("dio[1]: "); Serial.println(plmic_pins->dio[1]);
// Serial.print("dio[2]: "); Serial.println(plmic_pins->dio[2]);
pinMode(plmic_pins->nss, OUTPUT);
if (plmic_pins->rxtx != LMIC_UNUSED_PIN)
pinMode(plmic_pins->rxtx, OUTPUT);
if (plmic_pins->rst != LMIC_UNUSED_PIN)
pinMode(plmic_pins->rst, OUTPUT);
hal_interrupt_init();
}
// val == 1 => tx
void hal_pin_rxtx (u1_t val) {
if (plmic_pins->rxtx != LMIC_UNUSED_PIN)
digitalWrite(plmic_pins->rxtx, val != plmic_pins->rxtx_rx_active);
}
// set radio RST pin to given value (or keep floating!)
void hal_pin_rst (u1_t val) {
if (plmic_pins->rst == LMIC_UNUSED_PIN)
return;
if(val == 0 || val == 1) { // drive pin
pinMode(plmic_pins->rst, OUTPUT);
digitalWrite(plmic_pins->rst, val);
} else { // keep pin floating
pinMode(plmic_pins->rst, INPUT);
}
}
s1_t hal_getRssiCal (void) {
return plmic_pins->rssi_cal;
}
#if !defined(LMIC_USE_INTERRUPTS)
static void hal_interrupt_init() {
pinMode(plmic_pins->dio[0], INPUT);
if (plmic_pins->dio[1] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[1], INPUT);
if (plmic_pins->dio[2] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[2], INPUT);
}
static bool dio_states[NUM_DIO] = {0};
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
if (dio_states[i] != digitalRead(plmic_pins->dio[i])) {
dio_states[i] = !dio_states[i];
if (dio_states[i])
radio_irq_handler(i);
}
}
}
#else
// Interrupt handlers
static bool interrupt_flags[NUM_DIO] = {0};
static void hal_isrPin0() {
interrupt_flags[0] = true;
}
static void hal_isrPin1() {
interrupt_flags[1] = true;
}
static void hal_isrPin2() {
interrupt_flags[2] = true;
}
typedef void (*isr_t)();
static isr_t interrupt_fns[NUM_DIO] = {hal_isrPin0, hal_isrPin1, hal_isrPin2};
static void hal_interrupt_init() {
for (uint8_t i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
attachInterrupt(digitalPinToInterrupt(plmic_pins->dio[i]), interrupt_fns[i], RISING);
}
}
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
if (interrupt_flags[i]) {
interrupt_flags[i] = false;
radio_irq_handler(i);
}
}
}
#endif // LMIC_USE_INTERRUPTS
// -----------------------------------------------------------------------------
// SPI
static void hal_spi_init () {
SPI.begin();
}
void hal_pin_nss (u1_t val) {
if (!val) {
uint32_t spi_freq;
if ((spi_freq = plmic_pins->spi_freq) == 0)
spi_freq = LMIC_SPI_FREQ;
SPISettings settings(spi_freq, MSBFIRST, SPI_MODE0);
SPI.beginTransaction(settings);
} else {
SPI.endTransaction();
}
//Serial.println(val?">>":"<<");
digitalWrite(plmic_pins->nss, val);
}
// perform SPI transaction with radio
u1_t hal_spi (u1_t out) {
u1_t res = SPI.transfer(out);
/*
Serial.print(">");
Serial.print(out, HEX);
Serial.print("<");
Serial.println(res, HEX);
*/
return res;
}
// -----------------------------------------------------------------------------
// TIME
static void hal_time_init () {
// Nothing to do
}
u4_t hal_ticks () {
// Because micros() is scaled down in this function, micros() will
// overflow before the tick timer should, causing the tick timer to
// miss a significant part of its values if not corrected. To fix
// this, the "overflow" serves as an overflow area for the micros()
// counter. It consists of three parts:
// - The US_PER_OSTICK upper bits are effectively an extension for
// the micros() counter and are added to the result of this
// function.
// - The next bit overlaps with the most significant bit of
// micros(). This is used to detect micros() overflows.
// - The remaining bits are always zero.
//
// By comparing the overlapping bit with the corresponding bit in
// the micros() return value, overflows can be detected and the
// upper bits are incremented. This is done using some clever
// bitwise operations, to remove the need for comparisons and a
// jumps, which should result in efficient code. By avoiding shifts
// other than by multiples of 8 as much as possible, this is also
// efficient on AVR (which only has 1-bit shifts).
static uint8_t overflow = 0;
// Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,
// the others will be the lower bits of our return value.
uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;
// Most significant byte of scaled
uint8_t msb = scaled >> 24;
// Mask pointing to the overlapping bit in msb and overflow.
const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));
// Update overflow. If the overlapping bit is different
// between overflow and msb, it is added to the stored value,
// so the overlapping bit becomes equal again and, if it changed
// from 1 to 0, the upper bits are incremented.
overflow += (msb ^ overflow) & mask;
// Return the scaled value with the upper bits of stored added. The
// overlapping bit will be equal and the lower bits will be 0, so
// bitwise or is a no-op for them.
return scaled | ((uint32_t)overflow << 24);
// 0 leads to correct, but overly complex code (it could just return
// micros() unmodified), 8 leaves no room for the overlapping bit.
static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value");
}
// Returns the number of ticks until time. Negative values indicate that
// time has already passed.
static s4_t delta_time(u4_t time) {
return (s4_t)(time - hal_ticks());
}
void hal_waitUntil (u4_t time) {
s4_t delta = delta_time(time);
// From delayMicroseconds docs: Currently, the largest value that
// will produce an accurate delay is 16383.
while (delta > (16000 / US_PER_OSTICK)) {
delay(16);
delta -= (16000 / US_PER_OSTICK);
}
if (delta > 0)
delayMicroseconds(delta * US_PER_OSTICK);
}
// check and rewind for target time
u1_t hal_checkTimer (u4_t time) {
// No need to schedule wakeup, since we're not sleeping
return delta_time(time) <= 0;
}
static uint8_t irqlevel = 0;
void hal_disableIRQs () {
noInterrupts();
irqlevel++;
}
void hal_enableIRQs () {
if(--irqlevel == 0) {
interrupts();
// Instead of using proper interrupts (which are a bit tricky
// and/or not available on all pins on AVR), just poll the pin
// values. Since os_runloop disables and re-enables interrupts,
// putting this here makes sure we check at least once every
// loop.
//
// As an additional bonus, this prevents the can of worms that
// we would otherwise get for running SPI transfers inside ISRs
hal_io_check();
}
}
void hal_sleep () {
// Not implemented
}
// -----------------------------------------------------------------------------
#if defined(LMIC_PRINTF_TO)
static int uart_putchar (char c, FILE *)
{
LMIC_PRINTF_TO.write(c) ;
return 0 ;
}
void hal_printf_init() {
// create a FILE structure to reference our UART output function
static FILE uartout;
memset(&uartout, 0, sizeof(uartout));
// fill in the UART file descriptor with pointer to writer.
fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
// The uart is the standard output device STDOUT.
stdout = &uartout ;
}
#endif // defined(LMIC_PRINTF_TO)
void hal_init (void) {
hal_init_ex(&lmic_pins);
}
void hal_init_ex (const void *pContext) {
plmic_pins = (const lmic_pinmap *)pContext;
// configure radio I/O and interrupt handler
hal_io_init();
// configure radio SPI
hal_spi_init();
// configure timer and interrupt handler
hal_time_init();
#if defined(LMIC_PRINTF_TO)
// printf support
hal_printf_init();
#endif
}
void hal_failed (const char *file, u2_t line) {
#if defined(LMIC_FAILURE_TO)
LMIC_FAILURE_TO.println("FAILURE ");
LMIC_FAILURE_TO.print(file);
LMIC_FAILURE_TO.print(':');
LMIC_FAILURE_TO.println(line);
LMIC_FAILURE_TO.flush();
#endif
hal_disableIRQs();
while(1);
}
<commit_msg>Heltec Wifi LoRa v2 (ESP32) fix for printf<commit_after>/*******************************************************************************
* Copyright (c) 2015 Matthijs Kooijman
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* This the HAL to run LMIC on top of the Arduino environment.
*******************************************************************************/
#include <Arduino.h>
#include <SPI.h>
#include "../lmic.h"
#include "hal.h"
#include <stdio.h>
// -----------------------------------------------------------------------------
// I/O
static const lmic_pinmap *plmic_pins;
static void hal_interrupt_init(); // Fwd declaration
static void hal_io_init () {
// NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK
ASSERT(plmic_pins->nss != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[0] != LMIC_UNUSED_PIN);
ASSERT(plmic_pins->dio[1] != LMIC_UNUSED_PIN || plmic_pins->dio[2] != LMIC_UNUSED_PIN);
// Serial.print("nss: "); Serial.println(plmic_pins->nss);
// Serial.print("rst: "); Serial.println(plmic_pins->rst);
// Serial.print("dio[0]: "); Serial.println(plmic_pins->dio[0]);
// Serial.print("dio[1]: "); Serial.println(plmic_pins->dio[1]);
// Serial.print("dio[2]: "); Serial.println(plmic_pins->dio[2]);
pinMode(plmic_pins->nss, OUTPUT);
if (plmic_pins->rxtx != LMIC_UNUSED_PIN)
pinMode(plmic_pins->rxtx, OUTPUT);
if (plmic_pins->rst != LMIC_UNUSED_PIN)
pinMode(plmic_pins->rst, OUTPUT);
hal_interrupt_init();
}
// val == 1 => tx
void hal_pin_rxtx (u1_t val) {
if (plmic_pins->rxtx != LMIC_UNUSED_PIN)
digitalWrite(plmic_pins->rxtx, val != plmic_pins->rxtx_rx_active);
}
// set radio RST pin to given value (or keep floating!)
void hal_pin_rst (u1_t val) {
if (plmic_pins->rst == LMIC_UNUSED_PIN)
return;
if(val == 0 || val == 1) { // drive pin
pinMode(plmic_pins->rst, OUTPUT);
digitalWrite(plmic_pins->rst, val);
} else { // keep pin floating
pinMode(plmic_pins->rst, INPUT);
}
}
s1_t hal_getRssiCal (void) {
return plmic_pins->rssi_cal;
}
#if !defined(LMIC_USE_INTERRUPTS)
static void hal_interrupt_init() {
pinMode(plmic_pins->dio[0], INPUT);
if (plmic_pins->dio[1] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[1], INPUT);
if (plmic_pins->dio[2] != LMIC_UNUSED_PIN)
pinMode(plmic_pins->dio[2], INPUT);
}
static bool dio_states[NUM_DIO] = {0};
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
if (dio_states[i] != digitalRead(plmic_pins->dio[i])) {
dio_states[i] = !dio_states[i];
if (dio_states[i])
radio_irq_handler(i);
}
}
}
#else
// Interrupt handlers
static bool interrupt_flags[NUM_DIO] = {0};
static void hal_isrPin0() {
interrupt_flags[0] = true;
}
static void hal_isrPin1() {
interrupt_flags[1] = true;
}
static void hal_isrPin2() {
interrupt_flags[2] = true;
}
typedef void (*isr_t)();
static isr_t interrupt_fns[NUM_DIO] = {hal_isrPin0, hal_isrPin1, hal_isrPin2};
static void hal_interrupt_init() {
for (uint8_t i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
attachInterrupt(digitalPinToInterrupt(plmic_pins->dio[i]), interrupt_fns[i], RISING);
}
}
static void hal_io_check() {
uint8_t i;
for (i = 0; i < NUM_DIO; ++i) {
if (plmic_pins->dio[i] == LMIC_UNUSED_PIN)
continue;
if (interrupt_flags[i]) {
interrupt_flags[i] = false;
radio_irq_handler(i);
}
}
}
#endif // LMIC_USE_INTERRUPTS
// -----------------------------------------------------------------------------
// SPI
static void hal_spi_init () {
SPI.begin();
}
void hal_pin_nss (u1_t val) {
if (!val) {
uint32_t spi_freq;
if ((spi_freq = plmic_pins->spi_freq) == 0)
spi_freq = LMIC_SPI_FREQ;
SPISettings settings(spi_freq, MSBFIRST, SPI_MODE0);
SPI.beginTransaction(settings);
} else {
SPI.endTransaction();
}
//Serial.println(val?">>":"<<");
digitalWrite(plmic_pins->nss, val);
}
// perform SPI transaction with radio
u1_t hal_spi (u1_t out) {
u1_t res = SPI.transfer(out);
/*
Serial.print(">");
Serial.print(out, HEX);
Serial.print("<");
Serial.println(res, HEX);
*/
return res;
}
// -----------------------------------------------------------------------------
// TIME
static void hal_time_init () {
// Nothing to do
}
u4_t hal_ticks () {
// Because micros() is scaled down in this function, micros() will
// overflow before the tick timer should, causing the tick timer to
// miss a significant part of its values if not corrected. To fix
// this, the "overflow" serves as an overflow area for the micros()
// counter. It consists of three parts:
// - The US_PER_OSTICK upper bits are effectively an extension for
// the micros() counter and are added to the result of this
// function.
// - The next bit overlaps with the most significant bit of
// micros(). This is used to detect micros() overflows.
// - The remaining bits are always zero.
//
// By comparing the overlapping bit with the corresponding bit in
// the micros() return value, overflows can be detected and the
// upper bits are incremented. This is done using some clever
// bitwise operations, to remove the need for comparisons and a
// jumps, which should result in efficient code. By avoiding shifts
// other than by multiples of 8 as much as possible, this is also
// efficient on AVR (which only has 1-bit shifts).
static uint8_t overflow = 0;
// Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,
// the others will be the lower bits of our return value.
uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;
// Most significant byte of scaled
uint8_t msb = scaled >> 24;
// Mask pointing to the overlapping bit in msb and overflow.
const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));
// Update overflow. If the overlapping bit is different
// between overflow and msb, it is added to the stored value,
// so the overlapping bit becomes equal again and, if it changed
// from 1 to 0, the upper bits are incremented.
overflow += (msb ^ overflow) & mask;
// Return the scaled value with the upper bits of stored added. The
// overlapping bit will be equal and the lower bits will be 0, so
// bitwise or is a no-op for them.
return scaled | ((uint32_t)overflow << 24);
// 0 leads to correct, but overly complex code (it could just return
// micros() unmodified), 8 leaves no room for the overlapping bit.
static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, "Invalid US_PER_OSTICK_EXPONENT value");
}
// Returns the number of ticks until time. Negative values indicate that
// time has already passed.
static s4_t delta_time(u4_t time) {
return (s4_t)(time - hal_ticks());
}
void hal_waitUntil (u4_t time) {
s4_t delta = delta_time(time);
// From delayMicroseconds docs: Currently, the largest value that
// will produce an accurate delay is 16383.
while (delta > (16000 / US_PER_OSTICK)) {
delay(16);
delta -= (16000 / US_PER_OSTICK);
}
if (delta > 0)
delayMicroseconds(delta * US_PER_OSTICK);
}
// check and rewind for target time
u1_t hal_checkTimer (u4_t time) {
// No need to schedule wakeup, since we're not sleeping
return delta_time(time) <= 0;
}
static uint8_t irqlevel = 0;
void hal_disableIRQs () {
noInterrupts();
irqlevel++;
}
void hal_enableIRQs () {
if(--irqlevel == 0) {
interrupts();
// Instead of using proper interrupts (which are a bit tricky
// and/or not available on all pins on AVR), just poll the pin
// values. Since os_runloop disables and re-enables interrupts,
// putting this here makes sure we check at least once every
// loop.
//
// As an additional bonus, this prevents the can of worms that
// we would otherwise get for running SPI transfers inside ISRs
hal_io_check();
}
}
void hal_sleep () {
// Not implemented
}
// -----------------------------------------------------------------------------
#if defined(LMIC_PRINTF_TO)
#if defined(ESP8266) || defined(ESP31B) || defined(ESP32)
//ESPXX specific PRINTF, only tested with ESP32 Haltec LoRA Wifi so far
static ssize_t uart_putchar (void *, const char *buf, size_t len) {
return LMIC_PRINTF_TO.write((const uint8_t *)buf, len);
}
static cookie_io_functions_t functions =
{
.read = NULL,
.write = uart_putchar,
.seek = NULL,
.close = NULL
};
void hal_printf_init() {
stdout = fopencookie(NULL, "w", functions);
}
#else // !defined(ESP8266) || defined(ESP31B) || defined(ESP32)
// all else, like AVR
static int uart_putchar (char c, FILE *)
{
LMIC_PRINTF_TO.write(c) ;
return 0 ;
}
void hal_printf_init() {
// create a FILE structure to reference our UART output function
static FILE uartout;
memset(&uartout, 0, sizeof(uartout));
// fill in the UART file descriptor with pointer to writer.
fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
// The uart is the standard output device STDOUT.
stdout = &uartout ;
}
#endif // !defined(ESP8266) || defined(ESP31B) || defined(ESP32)
#endif // defined(LMIC_PRINTF_TO)
void hal_init (void) {
hal_init_ex(&lmic_pins);
}
void hal_init_ex (const void *pContext) {
plmic_pins = (const lmic_pinmap *)pContext;
// configure radio I/O and interrupt handler
hal_io_init();
// configure radio SPI
hal_spi_init();
// configure timer and interrupt handler
hal_time_init();
#if defined(LMIC_PRINTF_TO)
// printf support
hal_printf_init();
#endif
}
void hal_failed (const char *file, u2_t line) {
#if defined(LMIC_FAILURE_TO)
LMIC_FAILURE_TO.println("FAILURE ");
LMIC_FAILURE_TO.print(file);
LMIC_FAILURE_TO.print(':');
LMIC_FAILURE_TO.println(line);
LMIC_FAILURE_TO.flush();
#endif
hal_disableIRQs();
while(1);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/service/service_process_control.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/process_util.h"
#include "base/stl_util-inl.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/upgrade_detector.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/service_messages.h"
#include "chrome/common/service_process_util.h"
#include "content/browser/browser_thread.h"
#include "content/common/child_process_host.h"
#include "content/common/notification_service.h"
#include "ui/base/ui_base_switches.h"
// ServiceProcessControl implementation.
ServiceProcessControl::ServiceProcessControl(Profile* profile)
: profile_(profile) {
}
ServiceProcessControl::~ServiceProcessControl() {
STLDeleteElements(&connect_done_tasks_);
STLDeleteElements(&connect_success_tasks_);
STLDeleteElements(&connect_failure_tasks_);
}
void ServiceProcessControl::ConnectInternal() {
// If the channel has already been established then we run the task
// and return.
if (channel_.get()) {
RunConnectDoneTasks();
return;
}
// Actually going to connect.
VLOG(1) << "Connecting to Service Process IPC Server";
// Run the IPC channel on the shared IO thread.
base::Thread* io_thread = g_browser_process->io_thread();
// TODO(hclam): Handle error connecting to channel.
const IPC::ChannelHandle channel_id = GetServiceProcessChannel();
channel_.reset(
new IPC::SyncChannel(channel_id, IPC::Channel::MODE_NAMED_CLIENT, this,
io_thread->message_loop(), true,
g_browser_process->shutdown_event()));
}
void ServiceProcessControl::RunConnectDoneTasks() {
// The tasks executed here may add more tasks to the vector. So copy
// them to the stack before executing them. This way recursion is
// avoided.
TaskList tasks;
tasks.swap(connect_done_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
if (is_connected()) {
tasks.swap(connect_success_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
STLDeleteElements(&connect_failure_tasks_);
} else {
tasks.swap(connect_failure_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
STLDeleteElements(&connect_success_tasks_);
}
DCHECK(connect_done_tasks_.empty());
DCHECK(connect_success_tasks_.empty());
DCHECK(connect_failure_tasks_.empty());
}
// static
void ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) {
TaskList::iterator index = task_list->begin();
while (index != task_list->end()) {
(*index)->Run();
delete (*index);
index = task_list->erase(index);
}
}
void ServiceProcessControl::Launch(Task* success_task, Task* failure_task) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (success_task) {
if (success_task == failure_task) {
// If the tasks are the same, then the same task needs to be invoked
// for success and failure.
failure_task = NULL;
connect_done_tasks_.push_back(success_task);
} else {
connect_success_tasks_.push_back(success_task);
}
}
if (failure_task)
connect_failure_tasks_.push_back(failure_task);
// If we already in the process of launching, then we are done.
if (launcher_) {
return;
}
// If the service process is already running then connects to it.
if (CheckServiceProcessReady()) {
ConnectInternal();
return;
}
// A service process should have a different mechanism for starting, but now
// we start it as if it is a child process.
FilePath exe_path = ChildProcessHost::GetChildPath(true);
if (exe_path.empty()) {
NOTREACHED() << "Unable to get service process binary name.";
}
CommandLine* cmd_line = new CommandLine(exe_path);
cmd_line->AppendSwitchASCII(switches::kProcessType,
switches::kServiceProcess);
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
FilePath user_data_dir =
browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
if (!user_data_dir.empty())
cmd_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
std::string logging_level = browser_command_line.GetSwitchValueASCII(
switches::kLoggingLevel);
if (!logging_level.empty())
cmd_line->AppendSwitchASCII(switches::kLoggingLevel, logging_level);
std::string v_level = browser_command_line.GetSwitchValueASCII(
switches::kV);
if (!v_level.empty())
cmd_line->AppendSwitchASCII(switches::kV, v_level);
if (browser_command_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
cmd_line->AppendSwitch(switches::kWaitForDebugger);
}
if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
cmd_line->AppendSwitch(switches::kEnableLogging);
}
std::string locale = g_browser_process->GetApplicationLocale();
cmd_line->AppendSwitchASCII(switches::kLang, locale);
// And then start the process asynchronously.
launcher_ = new Launcher(this, cmd_line);
launcher_->Run(
NewRunnableMethod(this, &ServiceProcessControl::OnProcessLaunched));
}
void ServiceProcessControl::OnProcessLaunched() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (launcher_->launched()) {
// After we have successfully created the service process we try to connect
// to it. The launch task is transfered to a connect task.
ConnectInternal();
} else {
// If we don't have process handle that means launching the service process
// has failed.
RunConnectDoneTasks();
}
// We don't need the launcher anymore.
launcher_ = NULL;
}
bool ServiceProcessControl::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl, message)
IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_IsEnabled,
OnCloudPrintProxyIsEnabled)
IPC_MESSAGE_HANDLER(ServiceHostMsg_RemotingHost_HostInfo,
OnRemotingHostInfo)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void ServiceProcessControl::OnChannelConnected(int32 peer_pid) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
channel_->set_sync_messages_with_no_timeout_allowed(false);
// We just established a channel with the service process. Notify it if an
// upgrade is available.
if (UpgradeDetector::GetInstance()->notify_upgrade()) {
Send(new ServiceMsg_UpdateAvailable);
} else {
if (registrar_.IsEmpty())
registrar_.Add(this, NotificationType::UPGRADE_RECOMMENDED,
NotificationService::AllSources());
}
RunConnectDoneTasks();
}
void ServiceProcessControl::OnChannelError() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
channel_.reset();
RunConnectDoneTasks();
}
bool ServiceProcessControl::Send(IPC::Message* message) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!channel_.get())
return false;
return channel_->Send(message);
}
// NotificationObserver implementation.
void ServiceProcessControl::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::UPGRADE_RECOMMENDED) {
Send(new ServiceMsg_UpdateAvailable);
}
}
void ServiceProcessControl::OnCloudPrintProxyIsEnabled(bool enabled,
std::string email) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (cloud_print_status_callback_ != NULL) {
cloud_print_status_callback_->Run(enabled, email);
cloud_print_status_callback_.reset();
}
}
void ServiceProcessControl::OnRemotingHostInfo(
const remoting::ChromotingHostInfo& host_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::set<MessageHandler*>::iterator it = message_handlers_.begin();
it != message_handlers_.end(); ++it) {
(*it)->OnRemotingHostInfo(host_info);
}
}
bool ServiceProcessControl::GetCloudPrintProxyStatus(
Callback2<bool, std::string>::Type* cloud_print_status_callback) {
DCHECK(cloud_print_status_callback);
cloud_print_status_callback_.reset(cloud_print_status_callback);
return Send(new ServiceMsg_IsCloudPrintProxyEnabled);
}
bool ServiceProcessControl::Shutdown() {
bool ret = Send(new ServiceMsg_Shutdown());
channel_.reset();
return ret;
}
bool ServiceProcessControl::SetRemotingHostCredentials(
const std::string& user,
const std::string& talk_token) {
return Send(
new ServiceMsg_SetRemotingHostCredentials(user, talk_token));
}
bool ServiceProcessControl::EnableRemotingHost() {
return Send(new ServiceMsg_EnableRemotingHost());
}
bool ServiceProcessControl::DisableRemotingHost() {
return Send(new ServiceMsg_DisableRemotingHost());
}
bool ServiceProcessControl::RequestRemotingHostStatus() {
if (CheckServiceProcessReady()) {
remoting::ChromotingHostInfo failure_host_info;
failure_host_info.enabled = false;
Launch(NewRunnableMethod(this, &ServiceProcessControl::Send,
new ServiceMsg_GetRemotingHostInfo),
NewRunnableMethod(this,
&ServiceProcessControl::OnRemotingHostInfo,
failure_host_info));
return true;
}
return false;
}
void ServiceProcessControl::AddMessageHandler(
MessageHandler* message_handler) {
message_handlers_.insert(message_handler);
}
void ServiceProcessControl::RemoveMessageHandler(
MessageHandler* message_handler) {
message_handlers_.erase(message_handler);
}
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControl);
ServiceProcessControl::Launcher::Launcher(ServiceProcessControl* process,
CommandLine* cmd_line)
: process_(process),
cmd_line_(cmd_line),
launched_(false),
retry_count_(0) {
}
// Execute the command line to start the process asynchronously.
// After the command is executed, |task| is called with the process handle on
// the UI thread.
void ServiceProcessControl::Launcher::Run(Task* task) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
notify_task_.reset(task);
BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
NewRunnableMethod(this, &Launcher::DoRun));
}
ServiceProcessControl::Launcher::~Launcher() {}
void ServiceProcessControl::Launcher::Notify() {
DCHECK(notify_task_.get());
notify_task_->Run();
notify_task_.reset();
}
#if !defined(OS_MACOSX)
void ServiceProcessControl::Launcher::DoDetectLaunched() {
DCHECK(notify_task_.get());
const uint32 kMaxLaunchDetectRetries = 10;
launched_ = CheckServiceProcessReady();
if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &Launcher::Notify));
return;
}
retry_count_++;
// If the service process is not launched yet then check again in 2 seconds.
const int kDetectLaunchRetry = 2000;
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &Launcher::DoDetectLaunched),
kDetectLaunchRetry);
}
void ServiceProcessControl::Launcher::DoRun() {
DCHECK(notify_task_.get());
if (base::LaunchApp(*cmd_line_, false, true, NULL)) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&Launcher::DoDetectLaunched));
} else {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &Launcher::Notify));
}
}
#endif // !OS_MACOSX
<commit_msg>BUG=none TEST=Start Chrome with a --vmodule command-line flag, and verify that the service process produces verbose logging accordingly.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/service/service_process_control.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/process_util.h"
#include "base/stl_util-inl.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/io_thread.h"
#include "chrome/browser/upgrade_detector.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/service_messages.h"
#include "chrome/common/service_process_util.h"
#include "content/browser/browser_thread.h"
#include "content/common/child_process_host.h"
#include "content/common/notification_service.h"
#include "ui/base/ui_base_switches.h"
// ServiceProcessControl implementation.
ServiceProcessControl::ServiceProcessControl(Profile* profile)
: profile_(profile) {
}
ServiceProcessControl::~ServiceProcessControl() {
STLDeleteElements(&connect_done_tasks_);
STLDeleteElements(&connect_success_tasks_);
STLDeleteElements(&connect_failure_tasks_);
}
void ServiceProcessControl::ConnectInternal() {
// If the channel has already been established then we run the task
// and return.
if (channel_.get()) {
RunConnectDoneTasks();
return;
}
// Actually going to connect.
VLOG(1) << "Connecting to Service Process IPC Server";
// Run the IPC channel on the shared IO thread.
base::Thread* io_thread = g_browser_process->io_thread();
// TODO(hclam): Handle error connecting to channel.
const IPC::ChannelHandle channel_id = GetServiceProcessChannel();
channel_.reset(
new IPC::SyncChannel(channel_id, IPC::Channel::MODE_NAMED_CLIENT, this,
io_thread->message_loop(), true,
g_browser_process->shutdown_event()));
}
void ServiceProcessControl::RunConnectDoneTasks() {
// The tasks executed here may add more tasks to the vector. So copy
// them to the stack before executing them. This way recursion is
// avoided.
TaskList tasks;
tasks.swap(connect_done_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
if (is_connected()) {
tasks.swap(connect_success_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
STLDeleteElements(&connect_failure_tasks_);
} else {
tasks.swap(connect_failure_tasks_);
RunAllTasksHelper(&tasks);
DCHECK(tasks.empty());
STLDeleteElements(&connect_success_tasks_);
}
DCHECK(connect_done_tasks_.empty());
DCHECK(connect_success_tasks_.empty());
DCHECK(connect_failure_tasks_.empty());
}
// static
void ServiceProcessControl::RunAllTasksHelper(TaskList* task_list) {
TaskList::iterator index = task_list->begin();
while (index != task_list->end()) {
(*index)->Run();
delete (*index);
index = task_list->erase(index);
}
}
void ServiceProcessControl::Launch(Task* success_task, Task* failure_task) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (success_task) {
if (success_task == failure_task) {
// If the tasks are the same, then the same task needs to be invoked
// for success and failure.
failure_task = NULL;
connect_done_tasks_.push_back(success_task);
} else {
connect_success_tasks_.push_back(success_task);
}
}
if (failure_task)
connect_failure_tasks_.push_back(failure_task);
// If we already in the process of launching, then we are done.
if (launcher_) {
return;
}
// If the service process is already running then connects to it.
if (CheckServiceProcessReady()) {
ConnectInternal();
return;
}
// A service process should have a different mechanism for starting, but now
// we start it as if it is a child process.
FilePath exe_path = ChildProcessHost::GetChildPath(true);
if (exe_path.empty()) {
NOTREACHED() << "Unable to get service process binary name.";
}
CommandLine* cmd_line = new CommandLine(exe_path);
cmd_line->AppendSwitchASCII(switches::kProcessType,
switches::kServiceProcess);
const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
FilePath user_data_dir =
browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
if (!user_data_dir.empty())
cmd_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
std::string logging_level = browser_command_line.GetSwitchValueASCII(
switches::kLoggingLevel);
if (!logging_level.empty())
cmd_line->AppendSwitchASCII(switches::kLoggingLevel, logging_level);
std::string v_level = browser_command_line.GetSwitchValueASCII(
switches::kV);
if (!v_level.empty())
cmd_line->AppendSwitchASCII(switches::kV, v_level);
std::string v_modules = browser_command_line.GetSwitchValueASCII(
switches::kVModule);
if (!v_modules.empty())
cmd_line->AppendSwitchASCII(switches::kVModule, v_modules);
if (browser_command_line.HasSwitch(switches::kWaitForDebuggerChildren)) {
cmd_line->AppendSwitch(switches::kWaitForDebugger);
}
if (browser_command_line.HasSwitch(switches::kEnableLogging)) {
cmd_line->AppendSwitch(switches::kEnableLogging);
}
std::string locale = g_browser_process->GetApplicationLocale();
cmd_line->AppendSwitchASCII(switches::kLang, locale);
// And then start the process asynchronously.
launcher_ = new Launcher(this, cmd_line);
launcher_->Run(
NewRunnableMethod(this, &ServiceProcessControl::OnProcessLaunched));
}
void ServiceProcessControl::OnProcessLaunched() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (launcher_->launched()) {
// After we have successfully created the service process we try to connect
// to it. The launch task is transfered to a connect task.
ConnectInternal();
} else {
// If we don't have process handle that means launching the service process
// has failed.
RunConnectDoneTasks();
}
// We don't need the launcher anymore.
launcher_ = NULL;
}
bool ServiceProcessControl::OnMessageReceived(const IPC::Message& message) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP(ServiceProcessControl, message)
IPC_MESSAGE_HANDLER(ServiceHostMsg_CloudPrintProxy_IsEnabled,
OnCloudPrintProxyIsEnabled)
IPC_MESSAGE_HANDLER(ServiceHostMsg_RemotingHost_HostInfo,
OnRemotingHostInfo)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void ServiceProcessControl::OnChannelConnected(int32 peer_pid) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
channel_->set_sync_messages_with_no_timeout_allowed(false);
// We just established a channel with the service process. Notify it if an
// upgrade is available.
if (UpgradeDetector::GetInstance()->notify_upgrade()) {
Send(new ServiceMsg_UpdateAvailable);
} else {
if (registrar_.IsEmpty())
registrar_.Add(this, NotificationType::UPGRADE_RECOMMENDED,
NotificationService::AllSources());
}
RunConnectDoneTasks();
}
void ServiceProcessControl::OnChannelError() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
channel_.reset();
RunConnectDoneTasks();
}
bool ServiceProcessControl::Send(IPC::Message* message) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (!channel_.get())
return false;
return channel_->Send(message);
}
// NotificationObserver implementation.
void ServiceProcessControl::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
if (type == NotificationType::UPGRADE_RECOMMENDED) {
Send(new ServiceMsg_UpdateAvailable);
}
}
void ServiceProcessControl::OnCloudPrintProxyIsEnabled(bool enabled,
std::string email) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (cloud_print_status_callback_ != NULL) {
cloud_print_status_callback_->Run(enabled, email);
cloud_print_status_callback_.reset();
}
}
void ServiceProcessControl::OnRemotingHostInfo(
const remoting::ChromotingHostInfo& host_info) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::set<MessageHandler*>::iterator it = message_handlers_.begin();
it != message_handlers_.end(); ++it) {
(*it)->OnRemotingHostInfo(host_info);
}
}
bool ServiceProcessControl::GetCloudPrintProxyStatus(
Callback2<bool, std::string>::Type* cloud_print_status_callback) {
DCHECK(cloud_print_status_callback);
cloud_print_status_callback_.reset(cloud_print_status_callback);
return Send(new ServiceMsg_IsCloudPrintProxyEnabled);
}
bool ServiceProcessControl::Shutdown() {
bool ret = Send(new ServiceMsg_Shutdown());
channel_.reset();
return ret;
}
bool ServiceProcessControl::SetRemotingHostCredentials(
const std::string& user,
const std::string& talk_token) {
return Send(
new ServiceMsg_SetRemotingHostCredentials(user, talk_token));
}
bool ServiceProcessControl::EnableRemotingHost() {
return Send(new ServiceMsg_EnableRemotingHost());
}
bool ServiceProcessControl::DisableRemotingHost() {
return Send(new ServiceMsg_DisableRemotingHost());
}
bool ServiceProcessControl::RequestRemotingHostStatus() {
if (CheckServiceProcessReady()) {
remoting::ChromotingHostInfo failure_host_info;
failure_host_info.enabled = false;
Launch(NewRunnableMethod(this, &ServiceProcessControl::Send,
new ServiceMsg_GetRemotingHostInfo),
NewRunnableMethod(this,
&ServiceProcessControl::OnRemotingHostInfo,
failure_host_info));
return true;
}
return false;
}
void ServiceProcessControl::AddMessageHandler(
MessageHandler* message_handler) {
message_handlers_.insert(message_handler);
}
void ServiceProcessControl::RemoveMessageHandler(
MessageHandler* message_handler) {
message_handlers_.erase(message_handler);
}
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcessControl);
ServiceProcessControl::Launcher::Launcher(ServiceProcessControl* process,
CommandLine* cmd_line)
: process_(process),
cmd_line_(cmd_line),
launched_(false),
retry_count_(0) {
}
// Execute the command line to start the process asynchronously.
// After the command is executed, |task| is called with the process handle on
// the UI thread.
void ServiceProcessControl::Launcher::Run(Task* task) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
notify_task_.reset(task);
BrowserThread::PostTask(BrowserThread::PROCESS_LAUNCHER, FROM_HERE,
NewRunnableMethod(this, &Launcher::DoRun));
}
ServiceProcessControl::Launcher::~Launcher() {}
void ServiceProcessControl::Launcher::Notify() {
DCHECK(notify_task_.get());
notify_task_->Run();
notify_task_.reset();
}
#if !defined(OS_MACOSX)
void ServiceProcessControl::Launcher::DoDetectLaunched() {
DCHECK(notify_task_.get());
const uint32 kMaxLaunchDetectRetries = 10;
launched_ = CheckServiceProcessReady();
if (launched_ || (retry_count_ >= kMaxLaunchDetectRetries)) {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &Launcher::Notify));
return;
}
retry_count_++;
// If the service process is not launched yet then check again in 2 seconds.
const int kDetectLaunchRetry = 2000;
MessageLoop::current()->PostDelayedTask(
FROM_HERE,
NewRunnableMethod(this, &Launcher::DoDetectLaunched),
kDetectLaunchRetry);
}
void ServiceProcessControl::Launcher::DoRun() {
DCHECK(notify_task_.get());
if (base::LaunchApp(*cmd_line_, false, true, NULL)) {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(this,
&Launcher::DoDetectLaunched));
} else {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
NewRunnableMethod(this, &Launcher::Notify));
}
}
#endif // !OS_MACOSX
<|endoftext|>
|
<commit_before>/*
Copyright 2012 Joe Hermaszewski. 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 JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "expression_statement.hpp"
#include <cassert>
#include <memory>
#include <compiler/complete_type.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/shader_writer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/statements/statement.hpp>
namespace JoeLang
{
namespace Compiler
{
//------------------------------------------------------------------------------
// ExpressionStatement
//------------------------------------------------------------------------------
ExpressionStatement::ExpressionStatement( Expression_up expression )
:Statement( TokenTy::ExpressionStatement )
,m_Expression( std::move(expression) )
{
assert( m_Expression && "ExpressionStatement given a null expression" );
}
ExpressionStatement::~ExpressionStatement()
{
}
bool ExpressionStatement::AlwaysReturns() const
{
return false;
}
std::set<Function_sp> ExpressionStatement::GetCallees() const
{
return m_Expression->GetCallees();
}
std::set<Variable_sp> ExpressionStatement::GetVariables() const
{
return m_Expression->GetVariables();
}
std::set<Variable_sp> ExpressionStatement::GetWrittenToVariables() const
{
return m_Expression->GetWrittenToVariables();
}
void ExpressionStatement::PerformSema( SemaAnalyzer& sema,
const CompleteType& return_type )
{
m_Expression->ResolveIdentifiers( sema );
m_Expression->PerformSema( sema );
}
void ExpressionStatement::CodeGen( CodeGenerator& code_gen )
{
m_Expression->CodeGen( code_gen );
}
void ExpressionStatement::Write( ShaderWriter& shader_writer ) const
{
shader_writer << *m_Expression << ";";
}
bool ExpressionStatement::Parse( Parser& parser, ExpressionStatement_up& token )
{
Expression_up expression;
if( !parser.Expect<Expression>( expression ) )
return false;
if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
{
parser.Error( "Expected ';' after expression" );
return false;
}
token.reset( new ExpressionStatement( std::move(expression) ) );
return true;
}
} // namespace Compiler
} // namespace JoeLang
<commit_msg>[+] returning if we cannot resolve identifiers<commit_after>/*
Copyright 2012 Joe Hermaszewski. 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 JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.
The views and conclusions contained in the software and documentation are
those of the authors and should not be interpreted as representing official
policies, either expressed or implied, of Joe Hermaszewski.
*/
#include "expression_statement.hpp"
#include <cassert>
#include <memory>
#include <compiler/complete_type.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/shader_writer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/statements/statement.hpp>
namespace JoeLang
{
namespace Compiler
{
//------------------------------------------------------------------------------
// ExpressionStatement
//------------------------------------------------------------------------------
ExpressionStatement::ExpressionStatement( Expression_up expression )
:Statement( TokenTy::ExpressionStatement )
,m_Expression( std::move(expression) )
{
assert( m_Expression && "ExpressionStatement given a null expression" );
}
ExpressionStatement::~ExpressionStatement()
{
}
bool ExpressionStatement::AlwaysReturns() const
{
return false;
}
std::set<Function_sp> ExpressionStatement::GetCallees() const
{
return m_Expression->GetCallees();
}
std::set<Variable_sp> ExpressionStatement::GetVariables() const
{
return m_Expression->GetVariables();
}
std::set<Variable_sp> ExpressionStatement::GetWrittenToVariables() const
{
return m_Expression->GetWrittenToVariables();
}
void ExpressionStatement::PerformSema( SemaAnalyzer& sema,
const CompleteType& return_type )
{
if( !m_Expression->ResolveIdentifiers( sema ) )
return;
m_Expression->PerformSema( sema );
}
void ExpressionStatement::CodeGen( CodeGenerator& code_gen )
{
m_Expression->CodeGen( code_gen );
}
void ExpressionStatement::Write( ShaderWriter& shader_writer ) const
{
shader_writer << *m_Expression << ";";
}
bool ExpressionStatement::Parse( Parser& parser, ExpressionStatement_up& token )
{
Expression_up expression;
if( !parser.Expect<Expression>( expression ) )
return false;
if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
{
parser.Error( "Expected ';' after expression" );
return false;
}
token.reset( new ExpressionStatement( std::move(expression) ) );
return true;
}
} // namespace Compiler
} // namespace JoeLang
<|endoftext|>
|
<commit_before>#pragma once
#include <Core/Geometry/Curve2D.hpp>
namespace Ra {
namespace Core {
namespace Geometry {
/*--------------------------------------------------*/
void CubicBezier::addPoint( const Curve2D::Vector p ) {
if ( size < 4 ) { m_points[size++] = p; }
}
Curve2D::Vector CubicBezier::f( Scalar u ) const {
Vector grad;
return fdf( u, grad );
}
Curve2D::Vector CubicBezier::df( Scalar u ) const {
Vector grad;
fdf( u, grad );
return grad;
}
Curve2D::Vector CubicBezier::fdf( Scalar t, Vector& grad ) const {
float t2 = t * t;
float t3 = t2 * t;
float oneMinusT = 1.0 - t;
float oneMinusT2 = oneMinusT * oneMinusT;
float oneMinusT3 = oneMinusT2 * oneMinusT;
grad = 3.0 * oneMinusT2 * ( m_points[1] - m_points[0] ) +
6.0 * oneMinusT * t * ( m_points[2] - m_points[1] ) +
3.0 * t2 * ( m_points[3] - m_points[2] );
return oneMinusT3 * m_points[0] + 3.0 * oneMinusT2 * t * m_points[1] +
3.0 * oneMinusT * t2 * m_points[2] + t3 * m_points[3];
}
/*--------------------------------------------------*/
void Line::addPoint( const Curve2D::Vector p ) {
if ( size < 2 ) { m_points[size++] = p; }
}
Curve2D::Vector Line::f( Scalar u ) const {
return ( 1.0 - u ) * m_points[0] + u * m_points[1];
}
Curve2D::Vector Line::df( Scalar u ) const {
return m_points[1] - m_points[0];
}
Curve2D::Vector Line::fdf( Scalar t, Vector& grad ) const {
grad = m_points[1] - m_points[0];
return ( 1.0 - t ) * m_points[0] + t * m_points[1];
}
/*--------------------------------------------------*/
void SplineCurve::addPoint( const Curve2D::Vector p ) {
m_points.push_back( p );
++size;
}
Curve2D::Vector SplineCurve::f( Scalar u ) const {
Spline<2, 3> spline;
spline.setCtrlPoints( m_points );
return spline.f( u );
}
Curve2D::Vector SplineCurve::df( Scalar u ) const {
Spline<2, 3> spline;
spline.setCtrlPoints( m_points );
return spline.df( u );
}
Curve2D::Vector SplineCurve::fdf( Scalar u, Curve2D::Vector& grad ) const {
Spline<2, 3> spline;
spline.setCtrlPoints( m_points );
grad = spline.df( u );
return spline.f( u );
}
/*--------------------------------------------------*/
void QuadraSpline::addPoint( const Curve2D::Vector p ) {
m_points.push_back( p );
++size;
}
Curve2D::Vector QuadraSpline::f( Scalar u ) const {
Spline<2, 2> spline;
spline.setCtrlPoints( m_points );
return spline.f( u );
}
Curve2D::Vector QuadraSpline::df( Scalar u ) const {
Spline<2, 2> spline;
spline.setCtrlPoints( m_points );
return spline.df( u );
}
Curve2D::Vector QuadraSpline::fdf( Scalar u, Vector& grad ) const {
Spline<2, 2> spline;
spline.setCtrlPoints( m_points );
grad = spline.df( u );
return spline.f( u );
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
<commit_msg>[core] fix unused warning<commit_after>#pragma once
#include <Core/Geometry/Curve2D.hpp>
namespace Ra {
namespace Core {
namespace Geometry {
/*--------------------------------------------------*/
void CubicBezier::addPoint( const Curve2D::Vector p ) {
if ( size < 4 ) { m_points[size++] = p; }
}
Curve2D::Vector CubicBezier::f( Scalar u ) const {
Vector grad;
return fdf( u, grad );
}
Curve2D::Vector CubicBezier::df( Scalar u ) const {
Vector grad;
fdf( u, grad );
return grad;
}
Curve2D::Vector CubicBezier::fdf( Scalar t, Vector& grad ) const {
float t2 = t * t;
float t3 = t2 * t;
float oneMinusT = 1.0 - t;
float oneMinusT2 = oneMinusT * oneMinusT;
float oneMinusT3 = oneMinusT2 * oneMinusT;
grad = 3.0 * oneMinusT2 * ( m_points[1] - m_points[0] ) +
6.0 * oneMinusT * t * ( m_points[2] - m_points[1] ) +
3.0 * t2 * ( m_points[3] - m_points[2] );
return oneMinusT3 * m_points[0] + 3.0 * oneMinusT2 * t * m_points[1] +
3.0 * oneMinusT * t2 * m_points[2] + t3 * m_points[3];
}
/*--------------------------------------------------*/
void Line::addPoint( const Curve2D::Vector p ) {
if ( size < 2 ) { m_points[size++] = p; }
}
Curve2D::Vector Line::f( Scalar u ) const {
return ( 1.0 - u ) * m_points[0] + u * m_points[1];
}
Curve2D::Vector Line::df( Scalar /*u*/ ) const {
return m_points[1] - m_points[0];
}
Curve2D::Vector Line::fdf( Scalar t, Vector& grad ) const {
grad = m_points[1] - m_points[0];
return ( 1.0 - t ) * m_points[0] + t * m_points[1];
}
/*--------------------------------------------------*/
void SplineCurve::addPoint( const Curve2D::Vector p ) {
m_points.push_back( p );
++size;
}
Curve2D::Vector SplineCurve::f( Scalar u ) const {
Spline<2, 3> spline;
spline.setCtrlPoints( m_points );
return spline.f( u );
}
Curve2D::Vector SplineCurve::df( Scalar u ) const {
Spline<2, 3> spline;
spline.setCtrlPoints( m_points );
return spline.df( u );
}
Curve2D::Vector SplineCurve::fdf( Scalar u, Curve2D::Vector& grad ) const {
Spline<2, 3> spline;
spline.setCtrlPoints( m_points );
grad = spline.df( u );
return spline.f( u );
}
/*--------------------------------------------------*/
void QuadraSpline::addPoint( const Curve2D::Vector p ) {
m_points.push_back( p );
++size;
}
Curve2D::Vector QuadraSpline::f( Scalar u ) const {
Spline<2, 2> spline;
spline.setCtrlPoints( m_points );
return spline.f( u );
}
Curve2D::Vector QuadraSpline::df( Scalar u ) const {
Spline<2, 2> spline;
spline.setCtrlPoints( m_points );
return spline.df( u );
}
Curve2D::Vector QuadraSpline::fdf( Scalar u, Vector& grad ) const {
Spline<2, 2> spline;
spline.setCtrlPoints( m_points );
grad = spline.df( u );
return spline.f( u );
}
} // namespace Geometry
} // namespace Core
} // namespace Ra
<|endoftext|>
|
<commit_before>#include "cirkit_unit03_driver.hpp"
// inclusive dependency
#include "ThirdRobotInterface/ThirdRobotInterface.h"
// dependency to ROS
#include <nav_msgs/Odometry.h> // odom
// dependency to Boost
#include <boost/thread.hpp>
// dependency to std
#include <iostream>
#include <stdexcept>
using namespace std; // FIXME: this software is library to cirkit_unit03_driver_node, don't erosion grobal area.
cirkit::CirkitUnit03Driver::CirkitUnit03Driver(const std::string& imcs01_port_, const ros::NodeHandle& nh)
: nh_ {nh},
rate_ {100},
odom_pub_ {nh_.advertise<nav_msgs::Odometry>("/odom", 1)},
steer_pub_ {nh_.advertise<geometry_msgs::Twist>("/steer_ctrl", 1)},
cmd_vel_sub_ {nh_.subscribe<geometry_msgs::Twist>("/cmd_vel", 1, boost::bind(&cirkit::CirkitUnit03Driver::cmdVelReceived, this, _1))},
odom_broadcaster_ {},
imcs01_port_ {}, // over write by rosparam
current_time_ {},
last_time_ {},
access_mutex_ {},
steer_dir_ {},
cirkit_unit03_ {new cirkit::ThirdRobotInterface(imcs01_port_, 0)}
{
double pulse_rate {40.0};
double geer_rate {33.0};
double wheel_diameter_right {0.275};
double wheel_diameter_left {0.275};
double tred_width {0.595};
n.param("pulse_rate", pulse_rate, pulse_rate);
n.param("geer_rate", geer_rate, geer_rate);
n.param("wheel_diameter_right", wheel_diameter_right, wheel_diameter_right);
n.param("wheel_diameter_left", wheel_diameter_left, wheel_diameter_left);
n.param("tred_width", tred_width, tred_width);
cirkit_unit03_->setParams(pulse_rate, geer_rate, wheel_diameter_right, wheel_diameter_left, tred_width);
resetCommunication();
}
cirkit::CirkitUnit03Driver::~CirkitUnit03Driver() {
cirkit_unit03_->closeSerialPort();
delete cirkit_unit03_;
}
void cirkit::CirkitUnit03Driver::resetCommunication() {
if (cirkit_unit03_->openSerialPort() == 0) {
ROS_INFO("Connected to cirkit unit03.");
cirkit_unit03_->driveDirect(0, 0);
} else {
ROS_FATAL("Could not connect to cirkit unit03.");
delete cirkit_unit03_;
throw runtime_error {"Could not connect to cirkit unit03"};
}
cirkit_unit03_->resetOdometry();
cirkit_unit03_->setOdometry(0, 0, 0);
}
void cirkit::CirkitUnit03Driver::run() {
double last_x, last_y, last_yaw;
double vel_x, vel_y, vel_yaw;
double dt;
while (nh_.ok()) {
current_time_ = ros::Time::now();
last_x = cirkit_unit03_->odometry_x_;
last_y = cirkit_unit03_->odometry_y_;
last_yaw = cirkit_unit03_->odometry_yaw_;
{
boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
if (cirkit_unit03_->getEncoderPacket() == -1) ROS_ERROR("Could not retrieve encoder packet.");
else cirkit_unit03_->calculateOdometry();
}
dt = (current_time_ - last_time_).toSec();
vel_x = (cirkit_unit03_->odometry_x_ - last_x)/dt;
vel_y = (cirkit_unit03_->odometry_y_ - last_y)/dt;
vel_yaw = (cirkit_unit03_->odometry_yaw_ - last_yaw)/dt;
geometry_msgs::Quaternion odom_quat {tf::createQuaternionMsgFromYaw(cirkit_unit03_->odometry_yaw_)};
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time_;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_link";
odom_trans.transform.translation.x = cirkit_unit03_->odometry_x_;
odom_trans.transform.translation.y = cirkit_unit03_->odometry_y_;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
odom_broadcaster_.sendTransform(odom_trans);
nav_msgs::Odometry odom;
odom.header.stamp = current_time_;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = cirkit_unit03_->odometry_x_;
odom.pose.pose.position.y = cirkit_unit03_->odometry_y_;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vel_x;
odom.twist.twist.linear.y = vel_y;
odom.twist.twist.angular.z = vel_yaw;
//publish the message
odom_pub_.publish(odom);
ros::spinOnce();
rate_.sleep();
}
}
void cirkit::CirkitUnit03Driver::cmdVelReceived(const geometry_msgs::Twist::ConstPtr& cmd_vel) {
static int steer {0};
{
boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
steer_dir_ = cirkit_unit03_->drive(cmd_vel->linear.x, cmd_vel->angular.z);
}
steer_pub_.publish(steer_dir_);
}
<commit_msg>Fix pravate nodehandle<commit_after>#include "cirkit_unit03_driver.hpp"
// inclusive dependency
#include "ThirdRobotInterface/ThirdRobotInterface.h"
// dependency to ROS
#include <nav_msgs/Odometry.h> // odom
// dependency to Boost
#include <boost/thread.hpp>
// dependency to std
#include <iostream>
#include <stdexcept>
using namespace std; // FIXME: this software is library to cirkit_unit03_driver_node, don't erosion grobal area.
cirkit::CirkitUnit03Driver::CirkitUnit03Driver(const std::string& imcs01_port_, const ros::NodeHandle& nh)
: nh_ {nh},
rate_ {100},
odom_pub_ {nh_.advertise<nav_msgs::Odometry>("/odom", 1)},
steer_pub_ {nh_.advertise<geometry_msgs::Twist>("/steer_ctrl", 1)},
cmd_vel_sub_ {nh_.subscribe<geometry_msgs::Twist>("/cmd_vel", 1, boost::bind(&cirkit::CirkitUnit03Driver::cmdVelReceived, this, _1))},
odom_broadcaster_ {},
imcs01_port_ {}, // over write by rosparam
current_time_ {},
last_time_ {},
access_mutex_ {},
steer_dir_ {},
cirkit_unit03_ {new cirkit::ThirdRobotInterface(imcs01_port_, 0)}
{
double pulse_rate {40.0};
double geer_rate {33.0};
double wheel_diameter_right {0.275};
double wheel_diameter_left {0.275};
double tred_width {0.595};
ros::NodeHandle n {"~"};
n.param("pulse_rate", pulse_rate, pulse_rate);
n.param("geer_rate", geer_rate, geer_rate);
n.param("wheel_diameter_right", wheel_diameter_right, wheel_diameter_right);
n.param("wheel_diameter_left", wheel_diameter_left, wheel_diameter_left);
n.param("tred_width", tred_width, tred_width);
cirkit_unit03_->setParams(pulse_rate, geer_rate, wheel_diameter_right, wheel_diameter_left, tred_width);
resetCommunication();
}
cirkit::CirkitUnit03Driver::~CirkitUnit03Driver() {
cirkit_unit03_->closeSerialPort();
delete cirkit_unit03_;
}
void cirkit::CirkitUnit03Driver::resetCommunication() {
if (cirkit_unit03_->openSerialPort() == 0) {
ROS_INFO("Connected to cirkit unit03.");
cirkit_unit03_->driveDirect(0, 0);
} else {
ROS_FATAL("Could not connect to cirkit unit03.");
delete cirkit_unit03_;
throw runtime_error {"Could not connect to cirkit unit03"};
}
cirkit_unit03_->resetOdometry();
cirkit_unit03_->setOdometry(0, 0, 0);
}
void cirkit::CirkitUnit03Driver::run() {
double last_x, last_y, last_yaw;
double vel_x, vel_y, vel_yaw;
double dt;
while (nh_.ok()) {
current_time_ = ros::Time::now();
last_x = cirkit_unit03_->odometry_x_;
last_y = cirkit_unit03_->odometry_y_;
last_yaw = cirkit_unit03_->odometry_yaw_;
{
boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
if (cirkit_unit03_->getEncoderPacket() == -1) ROS_ERROR("Could not retrieve encoder packet.");
else cirkit_unit03_->calculateOdometry();
}
dt = (current_time_ - last_time_).toSec();
vel_x = (cirkit_unit03_->odometry_x_ - last_x)/dt;
vel_y = (cirkit_unit03_->odometry_y_ - last_y)/dt;
vel_yaw = (cirkit_unit03_->odometry_yaw_ - last_yaw)/dt;
geometry_msgs::Quaternion odom_quat {tf::createQuaternionMsgFromYaw(cirkit_unit03_->odometry_yaw_)};
geometry_msgs::TransformStamped odom_trans;
odom_trans.header.stamp = current_time_;
odom_trans.header.frame_id = "odom";
odom_trans.child_frame_id = "base_link";
odom_trans.transform.translation.x = cirkit_unit03_->odometry_x_;
odom_trans.transform.translation.y = cirkit_unit03_->odometry_y_;
odom_trans.transform.translation.z = 0.0;
odom_trans.transform.rotation = odom_quat;
odom_broadcaster_.sendTransform(odom_trans);
nav_msgs::Odometry odom;
odom.header.stamp = current_time_;
odom.header.frame_id = "odom";
//set the position
odom.pose.pose.position.x = cirkit_unit03_->odometry_x_;
odom.pose.pose.position.y = cirkit_unit03_->odometry_y_;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = odom_quat;
//set the velocity
odom.child_frame_id = "base_link";
odom.twist.twist.linear.x = vel_x;
odom.twist.twist.linear.y = vel_y;
odom.twist.twist.angular.z = vel_yaw;
//publish the message
odom_pub_.publish(odom);
ros::spinOnce();
rate_.sleep();
}
}
void cirkit::CirkitUnit03Driver::cmdVelReceived(const geometry_msgs::Twist::ConstPtr& cmd_vel) {
static int steer {0};
{
boost::mutex::scoped_lock {access_mutex_}; // why use mutex?
steer_dir_ = cirkit_unit03_->drive(cmd_vel->linear.x, cmd_vel->angular.z);
}
steer_pub_.publish(steer_dir_);
}
<|endoftext|>
|
<commit_before>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "kalloc.hh"
#include "cpputil.hh"
extern "C" void zpage(void*);
extern "C" void zrun_nc(run*);
static const bool prezero = true;
struct zallocator {
run* run;
kmem kmem;
wframe frame;
void init(int);
char* alloc(const char*);
void free(char*);
void tryrefill();
};
percpu<zallocator> z_;
struct zwork : public work {
zwork(wframe* frame, zallocator* zer)
: frame_(frame), zer_(zer)
{
frame_->inc();
}
virtual void run() {
for (int i = 0; i < 32; i++) {
struct run* r = (struct run*)kalloc("zpage");
if (r == nullptr)
break;
zrun_nc(r);
zer_->kmem.free(r);
}
frame_->dec();
delete this;
}
wframe* frame_;
zallocator* zer_;
NEW_DELETE_OPS(zwork);
};
//
// zallocator
//
void
zallocator::tryrefill(void)
{
if (prezero && kmem.nfree < 16 && frame.zero()) {
zwork* w = new zwork(&frame, this);
if (wq_push(w) < 0)
delete w;
}
}
void
zallocator::init(int c)
{
frame.clear();
kmem.name[0] = (char) c + '0';
safestrcpy(kmem.name+1, "zmem", MAXNAME-1);
kmem.size = PGSIZE;
}
char*
zallocator::alloc(const char* name)
{
char* p;
p = (char*) kmem.alloc(name);
if (p == nullptr) {
p = kalloc(name);
if (p != nullptr)
zpage(p);
}
tryrefill();
return p;
}
void
zallocator::free(char* p)
{
if (0)
for (int i = 0; i < 4096; i++)
assert(p[i] == 0);
kmem.free((struct run*)p);
}
char*
zalloc(const char* name)
{
return z_->alloc(name);
}
void
zfree(char* p)
{
z_->free(p);
}
void
initz(void)
{
for (int c = 0; c < NCPU; c++)
z_[c].init(c);
}
<commit_msg>Fix the zero page allocator<commit_after>#include "types.h"
#include "amd64.h"
#include "kernel.hh"
#include "percpu.hh"
#include "wq.hh"
#include "kalloc.hh"
#include "cpputil.hh"
extern "C" void zpage(void*);
extern "C" void zrun_nc(run*);
static const bool prezero = true;
struct zallocator {
run* run;
kmem kmem;
wframe frame;
void init(int);
char* alloc(const char*);
void free(char*);
void tryrefill();
};
percpu<zallocator> z_;
struct zwork : public work {
zwork(wframe* frame, zallocator* zer)
: frame_(frame), zer_(zer)
{
frame_->inc();
}
virtual void run() {
for (int i = 0; i < 32; i++) {
struct run* r = (struct run*)kalloc("zpage");
if (r == nullptr)
break;
zrun_nc(r);
zer_->kmem.free(r);
}
frame_->dec();
delete this;
}
wframe* frame_;
zallocator* zer_;
NEW_DELETE_OPS(zwork);
};
//
// zallocator
//
void
zallocator::tryrefill(void)
{
if (prezero && kmem.nfree < 16 && frame.zero()) {
zwork* w = new zwork(&frame, this);
if (wq_push(w) < 0)
delete w;
}
}
void
zallocator::init(int c)
{
frame.clear();
kmem.name[0] = (char) c + '0';
safestrcpy(kmem.name+1, "zmem", MAXNAME-1);
kmem.size = PGSIZE;
}
char*
zallocator::alloc(const char* name)
{
char* p;
p = (char*) kmem.alloc(name);
if (p == nullptr) {
p = kalloc(name);
if (p != nullptr)
zpage(p);
} else {
// Zero the run header used by kmem
memset(p, 0, sizeof(struct run));
}
tryrefill();
return p;
}
void
zallocator::free(char* p)
{
if (0)
for (int i = 0; i < 4096; i++)
assert(p[i] == 0);
kmem.free((struct run*)p);
}
char*
zalloc(const char* name)
{
return z_->alloc(name);
}
void
zfree(char* p)
{
z_->free(p);
}
void
initz(void)
{
for (int c = 0; c < NCPU; c++)
z_[c].init(c);
}
<|endoftext|>
|
<commit_before>#include "../ClipperUtils.hpp"
#include "../ExPolygon.hpp"
#include "../Surface.hpp"
#include "../Geometry.hpp"
#include "../AABBTreeIndirect.hpp"
#include "FillAdaptive.hpp"
namespace Slic3r {
void FillAdaptive::_fill_surface_single(
const FillParams ¶ms,
unsigned int thickness_layers,
const std::pair<float, Point> &direction,
ExPolygon &expolygon,
Polylines &polylines_out)
{
std::vector<Polylines> infill_polylines(3);
this->generate_polylines(this->adapt_fill_octree->root_cube.get(), this->z, this->adapt_fill_octree->origin, infill_polylines);
for (Polylines &infill_polyline : infill_polylines) {
// Crop all polylines
infill_polyline = intersection_pl(infill_polyline, to_polygons(expolygon));
polylines_out.insert(polylines_out.end(), infill_polyline.begin(), infill_polyline.end());
}
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRuna = 0;
BoundingBox bbox_svg = this->bounding_box;
{
::Slic3r::SVG svg(debug_out_path("FillAdaptive-%d.svg", iRuna), bbox_svg);
for (const Polyline &polyline : polylines_out)
{
for (const Line &line : polyline.lines())
{
Point from = line.a;
Point to = line.b;
Point diff = to - from;
float shrink_length = scale_(0.4);
float line_slope = (float)diff.y() / diff.x();
float shrink_x = shrink_length / (float)std::sqrt(1.0 + (line_slope * line_slope));
float shrink_y = line_slope * shrink_x;
to.x() -= shrink_x;
to.y() -= shrink_y;
from.x() += shrink_x;
from.y() += shrink_y;
svg.draw(Line(from, to));
}
}
}
iRuna++;
}
#endif /* SLIC3R_DEBUG */
}
void FillAdaptive::generate_polylines(
FillAdaptive_Internal::Cube *cube,
double z_position,
const Vec3d &origin,
std::vector<Polylines> &polylines_out)
{
using namespace FillAdaptive_Internal;
if(cube == nullptr)
{
return;
}
double z_diff = std::abs(z_position - cube->center.z());
if (z_diff > cube->properties.height / 2)
{
return;
}
if (z_diff < cube->properties.line_z_distance)
{
Point from(
scale_((cube->properties.diagonal_length / 2) * (cube->properties.line_z_distance - z_diff) / cube->properties.line_z_distance),
scale_(cube->properties.line_xy_distance - ((z_position - (cube->center.z() - cube->properties.line_z_distance)) / sqrt(2))));
Point to(-from.x(), from.y());
// Relative to cube center
float rotation_angle = Geometry::deg2rad(120.0);
for (int i = 0; i < 3; i++)
{
Vec3d offset = cube->center - origin;
Point from_abs(from), to_abs(to);
from_abs.x() += scale_(offset.x());
from_abs.y() += scale_(offset.y());
to_abs.x() += scale_(offset.x());
to_abs.y() += scale_(offset.y());
// polylines_out[i].push_back(Polyline(from_abs, to_abs));
this->merge_polylines(polylines_out[i], Line(from_abs, to_abs));
from.rotate(rotation_angle);
to.rotate(rotation_angle);
}
}
for(const std::unique_ptr<Cube> &child : cube->children)
{
generate_polylines(child.get(), z_position, origin, polylines_out);
}
}
void FillAdaptive::merge_polylines(Polylines &polylines, const Line &new_line)
{
int eps = scale_(0.10);
bool modified = false;
for (Polyline &polyline : polylines)
{
if (std::abs(new_line.a.x() - polyline.points[1].x()) < eps && std::abs(new_line.a.y() - polyline.points[1].y()) < eps)
{
polyline.points[1].x() = new_line.b.x();
polyline.points[1].y() = new_line.b.y();
modified = true;
}
if (std::abs(new_line.b.x() - polyline.points[0].x()) < eps && std::abs(new_line.b.y() - polyline.points[0].y()) < eps)
{
polyline.points[0].x() = new_line.a.x();
polyline.points[0].y() = new_line.a.y();
modified = true;
}
}
if(!modified)
{
polylines.emplace_back(Polyline(new_line.a, new_line.b));
}
}
std::unique_ptr<FillAdaptive_Internal::Octree> FillAdaptive::build_octree(
TriangleMesh &triangleMesh,
coordf_t line_spacing,
const BoundingBoxf3 &printer_volume,
const Vec3d &cube_center)
{
using namespace FillAdaptive_Internal;
if(line_spacing <= 0)
{
return nullptr;
}
// The furthest point from center of bed.
double furthest_point = std::sqrt(((printer_volume.size()[0] * printer_volume.size()[0]) / 4.0) +
((printer_volume.size()[1] * printer_volume.size()[1]) / 4.0) +
(printer_volume.size()[2] * printer_volume.size()[2]));
double max_cube_edge_length = furthest_point * 2;
std::vector<CubeProperties> cubes_properties;
for (double edge_length = (line_spacing * 2); edge_length < (max_cube_edge_length * 2); edge_length *= 2)
{
CubeProperties props{};
props.edge_length = edge_length;
props.height = edge_length * sqrt(3);
props.diagonal_length = edge_length * sqrt(2);
props.line_z_distance = edge_length / sqrt(3);
props.line_xy_distance = edge_length / sqrt(6);
cubes_properties.push_back(props);
}
if (triangleMesh.its.vertices.empty())
{
triangleMesh.require_shared_vertices();
}
Vec3d rotation = Vec3d(Geometry::deg2rad(225.0), Geometry::deg2rad(215.0), Geometry::deg2rad(30.0));
Transform3d rotation_matrix = Geometry::assemble_transform(Vec3d::Zero(), rotation, Vec3d::Ones(), Vec3d::Ones());
AABBTreeIndirect::Tree3f aabbTree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(triangleMesh.its.vertices, triangleMesh.its.indices);
std::unique_ptr<Octree> octree = std::unique_ptr<Octree>(
new Octree{std::unique_ptr<Cube>(new Cube{cube_center, cubes_properties.size() - 1, cubes_properties.back()}), cube_center});
FillAdaptive::expand_cube(octree->root_cube.get(), cubes_properties, rotation_matrix, aabbTree, triangleMesh);
return octree;
}
void FillAdaptive::expand_cube(
FillAdaptive_Internal::Cube *cube,
const std::vector<FillAdaptive_Internal::CubeProperties> &cubes_properties,
const Transform3d &rotation_matrix,
const AABBTreeIndirect::Tree3f &distanceTree,
const TriangleMesh &triangleMesh)
{
using namespace FillAdaptive_Internal;
if (cube == nullptr || cube->depth == 0)
{
return;
}
std::vector<Vec3d> child_centers = {
Vec3d(-1, -1, -1), Vec3d( 1, -1, -1), Vec3d(-1, 1, -1), Vec3d(-1, -1, 1),
Vec3d( 1, 1, 1), Vec3d(-1, 1, 1), Vec3d( 1, -1, 1), Vec3d( 1, 1, -1)
};
double cube_radius_squared = (cube->properties.height * cube->properties.height) / 16;
for (const Vec3d &child_center : child_centers) {
Vec3d child_center_transformed = cube->center + rotation_matrix * (child_center * (cube->properties.edge_length / 4));
if(AABBTreeIndirect::is_any_triangle_in_radius(triangleMesh.its.vertices, triangleMesh.its.indices, distanceTree, child_center_transformed, cube_radius_squared)) {
cube->children.push_back(std::unique_ptr<Cube>(new Cube{child_center_transformed, cube->depth - 1, cubes_properties[cube->depth - 1]}));
FillAdaptive::expand_cube(cube->children.back().get(), cubes_properties, rotation_matrix, distanceTree, triangleMesh);
}
}
}
} // namespace Slic3r
<commit_msg>Fix discontinuous extrusion lines for adaptive infill<commit_after>#include "../ClipperUtils.hpp"
#include "../ExPolygon.hpp"
#include "../Surface.hpp"
#include "../Geometry.hpp"
#include "../AABBTreeIndirect.hpp"
#include "FillAdaptive.hpp"
namespace Slic3r {
void FillAdaptive::_fill_surface_single(
const FillParams ¶ms,
unsigned int thickness_layers,
const std::pair<float, Point> &direction,
ExPolygon &expolygon,
Polylines &polylines_out)
{
std::vector<Polylines> infill_polylines(3);
this->generate_polylines(this->adapt_fill_octree->root_cube.get(), this->z, this->adapt_fill_octree->origin, infill_polylines);
for (Polylines &infill_polyline : infill_polylines) {
// Crop all polylines
infill_polyline = intersection_pl(infill_polyline, to_polygons(expolygon));
polylines_out.insert(polylines_out.end(), infill_polyline.begin(), infill_polyline.end());
}
#ifdef SLIC3R_DEBUG_SLICE_PROCESSING
{
static int iRuna = 0;
BoundingBox bbox_svg = this->bounding_box;
{
::Slic3r::SVG svg(debug_out_path("FillAdaptive-%d.svg", iRuna), bbox_svg);
for (const Polyline &polyline : polylines_out)
{
for (const Line &line : polyline.lines())
{
Point from = line.a;
Point to = line.b;
Point diff = to - from;
float shrink_length = scale_(0.4);
float line_slope = (float)diff.y() / diff.x();
float shrink_x = shrink_length / (float)std::sqrt(1.0 + (line_slope * line_slope));
float shrink_y = line_slope * shrink_x;
to.x() -= shrink_x;
to.y() -= shrink_y;
from.x() += shrink_x;
from.y() += shrink_y;
svg.draw(Line(from, to));
}
}
}
iRuna++;
}
#endif /* SLIC3R_DEBUG */
}
void FillAdaptive::generate_polylines(
FillAdaptive_Internal::Cube *cube,
double z_position,
const Vec3d &origin,
std::vector<Polylines> &polylines_out)
{
using namespace FillAdaptive_Internal;
if(cube == nullptr)
{
return;
}
double z_diff = std::abs(z_position - cube->center.z());
if (z_diff > cube->properties.height / 2)
{
return;
}
if (z_diff < cube->properties.line_z_distance)
{
Point from(
scale_((cube->properties.diagonal_length / 2) * (cube->properties.line_z_distance - z_diff) / cube->properties.line_z_distance),
scale_(cube->properties.line_xy_distance - ((z_position - (cube->center.z() - cube->properties.line_z_distance)) / sqrt(2))));
Point to(-from.x(), from.y());
// Relative to cube center
float rotation_angle = Geometry::deg2rad(120.0);
for (int i = 0; i < polylines_out.size(); i++)
{
Vec3d offset = cube->center - origin;
Point from_abs(from), to_abs(to);
from_abs.x() += scale_(offset.x());
from_abs.y() += scale_(offset.y());
to_abs.x() += scale_(offset.x());
to_abs.y() += scale_(offset.y());
// polylines_out[i].push_back(Polyline(from_abs, to_abs));
this->merge_polylines(polylines_out[i], Line(from_abs, to_abs));
from.rotate(rotation_angle);
to.rotate(rotation_angle);
}
}
for(const std::unique_ptr<Cube> &child : cube->children)
{
generate_polylines(child.get(), z_position, origin, polylines_out);
}
}
void FillAdaptive::merge_polylines(Polylines &polylines, const Line &new_line)
{
int eps = scale_(0.10);
bool modified = false;
for (Polyline &polyline : polylines)
{
if (std::abs(new_line.a.x() - polyline.points[1].x()) < eps && std::abs(new_line.a.y() - polyline.points[1].y()) < eps)
{
polyline.points[1].x() = new_line.b.x();
polyline.points[1].y() = new_line.b.y();
modified = true;
}
if (std::abs(new_line.b.x() - polyline.points[0].x()) < eps && std::abs(new_line.b.y() - polyline.points[0].y()) < eps)
{
polyline.points[0].x() = new_line.a.x();
polyline.points[0].y() = new_line.a.y();
modified = true;
}
}
if(!modified)
{
polylines.emplace_back(Polyline(new_line.a, new_line.b));
}
}
std::unique_ptr<FillAdaptive_Internal::Octree> FillAdaptive::build_octree(
TriangleMesh &triangleMesh,
coordf_t line_spacing,
const BoundingBoxf3 &printer_volume,
const Vec3d &cube_center)
{
using namespace FillAdaptive_Internal;
if(line_spacing <= 0)
{
return nullptr;
}
// The furthest point from center of bed.
double furthest_point = std::sqrt(((printer_volume.size()[0] * printer_volume.size()[0]) / 4.0) +
((printer_volume.size()[1] * printer_volume.size()[1]) / 4.0) +
(printer_volume.size()[2] * printer_volume.size()[2]));
double max_cube_edge_length = furthest_point * 2;
std::vector<CubeProperties> cubes_properties;
for (double edge_length = (line_spacing * 2); edge_length < (max_cube_edge_length * 2); edge_length *= 2)
{
CubeProperties props{};
props.edge_length = edge_length;
props.height = edge_length * sqrt(3);
props.diagonal_length = edge_length * sqrt(2);
props.line_z_distance = edge_length / sqrt(3);
props.line_xy_distance = edge_length / sqrt(6);
cubes_properties.push_back(props);
}
if (triangleMesh.its.vertices.empty())
{
triangleMesh.require_shared_vertices();
}
Vec3d rotation = Vec3d(Geometry::deg2rad(225.0), Geometry::deg2rad(215.264), Geometry::deg2rad(30.0));
Transform3d rotation_matrix = Geometry::assemble_transform(Vec3d::Zero(), rotation, Vec3d::Ones(), Vec3d::Ones());
AABBTreeIndirect::Tree3f aabbTree = AABBTreeIndirect::build_aabb_tree_over_indexed_triangle_set(triangleMesh.its.vertices, triangleMesh.its.indices);
std::unique_ptr<Octree> octree = std::unique_ptr<Octree>(
new Octree{std::unique_ptr<Cube>(new Cube{cube_center, cubes_properties.size() - 1, cubes_properties.back()}), cube_center});
FillAdaptive::expand_cube(octree->root_cube.get(), cubes_properties, rotation_matrix, aabbTree, triangleMesh);
return octree;
}
void FillAdaptive::expand_cube(
FillAdaptive_Internal::Cube *cube,
const std::vector<FillAdaptive_Internal::CubeProperties> &cubes_properties,
const Transform3d &rotation_matrix,
const AABBTreeIndirect::Tree3f &distanceTree,
const TriangleMesh &triangleMesh)
{
using namespace FillAdaptive_Internal;
if (cube == nullptr || cube->depth == 0)
{
return;
}
std::vector<Vec3d> child_centers = {
Vec3d(-1, -1, -1), Vec3d( 1, -1, -1), Vec3d(-1, 1, -1), Vec3d(-1, -1, 1),
Vec3d( 1, 1, 1), Vec3d(-1, 1, 1), Vec3d( 1, -1, 1), Vec3d( 1, 1, -1)
};
double cube_radius_squared = (cube->properties.height * cube->properties.height) / 16;
for (const Vec3d &child_center : child_centers) {
Vec3d child_center_transformed = cube->center + rotation_matrix * (child_center * (cube->properties.edge_length / 4));
if(AABBTreeIndirect::is_any_triangle_in_radius(triangleMesh.its.vertices, triangleMesh.its.indices, distanceTree, child_center_transformed, cube_radius_squared)) {
cube->children.push_back(std::unique_ptr<Cube>(new Cube{child_center_transformed, cube->depth - 1, cubes_properties[cube->depth - 1]}));
FillAdaptive::expand_cube(cube->children.back().get(), cubes_properties, rotation_matrix, distanceTree, triangleMesh);
}
}
}
} // namespace Slic3r
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (c) Juergen Riegel (juergen.riegel@web.de) 2012 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <QApplication>
# include <Inventor/SoPickedPoint.h>
# include <Inventor/events/SoMouseButtonEvent.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoBaseColor.h>
# include <Inventor/nodes/SoFontStyle.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoText2.h>
# include <Inventor/nodes/SoTranslation.h>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoIndexedLineSet.h>
# include <Inventor/nodes/SoMarkerSet.h>
# include <Inventor/nodes/SoDrawStyle.h>
#endif
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/nodes/SoAnnotation.h>
#include <Inventor/details/SoLineDetail.h>
#include <Inventor/nodes/SoAsciiText.h>
#include "ViewProviderPlane.h"
#include "SoFCSelection.h"
#include "Application.h"
#include "Document.h"
#include "View3DInventorViewer.h"
#include "Inventor/SoAutoZoomTranslation.h"
#include "SoAxisCrossKit.h"
//#include <SoDepthBuffer.h>
#include <App/PropertyGeo.h>
#include <App/PropertyStandard.h>
#include <App/MeasureDistance.h>
#include <Base/Console.h>
using namespace Gui;
PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderGeometryObject)
ViewProviderPlane::ViewProviderPlane()
{
ADD_PROPERTY(Size,(1.0));
pMat = new SoMaterial();
pMat->ref();
float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox()
SbVec3f verts[4] =
{
SbVec3f(size,size,0), SbVec3f(size,-size,0),
SbVec3f(-size,-size,0), SbVec3f(-size,size,0),
};
// indexes used to create the edges
static const int32_t lines[6] =
{
0,1,2,3,0,-1
};
pMat->diffuseColor.setNum(1);
pMat->diffuseColor.set1Value(0, SbColor(1.0f, 1.0f, 1.0f));
pCoords = new SoCoordinate3();
pCoords->ref();
pCoords->point.setNum(4);
pCoords->point.setValues(0, 4, verts);
pLines = new SoIndexedLineSet();
pLines->ref();
pLines->coordIndex.setNum(6);
pLines->coordIndex.setValues(0, 6, lines);
pFont = new SoFont();
pFont->size.setValue(Size.getValue()/10.);
pTranslation = new SoTranslation();
pTranslation->translation.setValue(SbVec3f(-1,9./10.,0));
pText = new SoAsciiText();
pText->width.setValue(-1);
sPixmap = "view-measurement";
}
ViewProviderPlane::~ViewProviderPlane()
{
pCoords->unref();
pLines->unref();
pMat->unref();
}
void ViewProviderPlane::onChanged(const App::Property* prop)
{
if (prop == &Size){
float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox()
SbVec3f verts[4] =
{
SbVec3f(size,size,0), SbVec3f(size,-size,0),
SbVec3f(-size,-size,0), SbVec3f(-size,size,0),
};
pCoords->point.setValues(0, 4, verts);
pFont->size.setValue(Size.getValue()/10.);
pTranslation->translation.setValue(SbVec3f(-size,size*9./10.,0));
}
else
ViewProviderGeometryObject::onChanged(prop);
}
std::vector<std::string> ViewProviderPlane::getDisplayModes(void) const
{
// add modes
std::vector<std::string> StrList;
StrList.push_back("Base");
return StrList;
}
void ViewProviderPlane::setDisplayMode(const char* ModeName)
{
if (strcmp(ModeName, "Base") == 0)
setDisplayMaskMode("Base");
ViewProviderGeometryObject::setDisplayMode(ModeName);
}
void ViewProviderPlane::attach(App::DocumentObject* pcObject)
{
ViewProviderGeometryObject::attach(pcObject);
SoSeparator *sep = new SoSeparator();
SoAnnotation *lineSep = new SoAnnotation();
SoDrawStyle* style = new SoDrawStyle();
style->lineWidth = 1.0f;
SoMaterialBinding* matBinding = new SoMaterialBinding;
matBinding->value = SoMaterialBinding::PER_FACE;
sep->addChild(style);
sep->addChild(matBinding);
sep->addChild(pMat);
sep->addChild(pCoords);
sep->addChild(pLines);
style = new SoDrawStyle();
style->lineWidth = 1.0f;
style->linePattern.setValue(0x00FF);
lineSep->addChild(style);
lineSep->addChild(pLines);
lineSep->addChild(pFont);
pText->string.setValue(SbString(pcObject->Label.getValue()));
lineSep->addChild(pTranslation);
lineSep->addChild(pText);
sep->addChild(lineSep);
addDisplayMaskMode(sep, "Base");
}
void ViewProviderPlane::updateData(const App::Property* prop)
{
pText->string.setValue(SbString(pcObject->Label.getValue()));
ViewProviderGeometryObject::updateData(prop);
}
std::string ViewProviderPlane::getElement(const SoDetail* detail) const
{
if (detail) {
if (detail->getTypeId() == SoLineDetail::getClassTypeId()) {
const SoLineDetail* line_detail = static_cast<const SoLineDetail*>(detail);
int edge = line_detail->getLineIndex();
if (edge == 0)
{
return std::string("Main");
}
}
}
return std::string("");
}
SoDetail* ViewProviderPlane::getDetail(const char* subelement) const
{
SoLineDetail* detail = 0;
std::string subelem(subelement);
int edge = -1;
if(subelem == "Main") edge = 0;
if(edge >= 0) {
detail = new SoLineDetail();
detail->setPartIndex(edge);
}
return detail;
}
bool ViewProviderPlane::isSelectable(void) const
{
return true;
}
// ----------------------------------------------------------------------------
<commit_msg>highlight planes<commit_after>/***************************************************************************
* Copyright (c) Juergen Riegel (juergen.riegel@web.de) 2012 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* 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., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
# include <QApplication>
# include <Inventor/SoPickedPoint.h>
# include <Inventor/events/SoMouseButtonEvent.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoBaseColor.h>
# include <Inventor/nodes/SoFontStyle.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoText2.h>
# include <Inventor/nodes/SoTranslation.h>
# include <Inventor/nodes/SoCoordinate3.h>
# include <Inventor/nodes/SoIndexedLineSet.h>
# include <Inventor/nodes/SoMarkerSet.h>
# include <Inventor/nodes/SoDrawStyle.h>
#endif
#include <Inventor/nodes/SoMaterial.h>
#include <Inventor/nodes/SoAnnotation.h>
#include <Inventor/details/SoLineDetail.h>
#include <Inventor/nodes/SoAsciiText.h>
#include "ViewProviderPlane.h"
#include "SoFCSelection.h"
#include "Application.h"
#include "Document.h"
#include "View3DInventorViewer.h"
#include "Inventor/SoAutoZoomTranslation.h"
#include "SoAxisCrossKit.h"
//#include <SoDepthBuffer.h>
#include <App/PropertyGeo.h>
#include <App/PropertyStandard.h>
#include <App/MeasureDistance.h>
#include <Base/Console.h>
using namespace Gui;
PROPERTY_SOURCE(Gui::ViewProviderPlane, Gui::ViewProviderGeometryObject)
ViewProviderPlane::ViewProviderPlane()
{
ADD_PROPERTY(Size,(1.0));
pMat = new SoMaterial();
pMat->ref();
float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox()
SbVec3f verts[4] =
{
SbVec3f(size,size,0), SbVec3f(size,-size,0),
SbVec3f(-size,-size,0), SbVec3f(-size,size,0),
};
// indexes used to create the edges
static const int32_t lines[6] =
{
0,1,2,3,0,-1
};
pMat->diffuseColor.setNum(1);
pMat->diffuseColor.set1Value(0, SbColor(1.0f, 1.0f, 1.0f));
pCoords = new SoCoordinate3();
pCoords->ref();
pCoords->point.setNum(4);
pCoords->point.setValues(0, 4, verts);
pLines = new SoIndexedLineSet();
pLines->ref();
pLines->coordIndex.setNum(6);
pLines->coordIndex.setValues(0, 6, lines);
pFont = new SoFont();
pFont->size.setValue(Size.getValue()/10.);
pTranslation = new SoTranslation();
pTranslation->translation.setValue(SbVec3f(-1,9./10.,0));
pText = new SoAsciiText();
pText->width.setValue(-1);
sPixmap = "view-measurement";
}
ViewProviderPlane::~ViewProviderPlane()
{
pCoords->unref();
pLines->unref();
pMat->unref();
}
void ViewProviderPlane::onChanged(const App::Property* prop)
{
if (prop == &Size){
float size = Size.getValue(); // Note: If you change this, you need to also adapt App/Plane.cpp getBoundBox()
SbVec3f verts[4] =
{
SbVec3f(size,size,0), SbVec3f(size,-size,0),
SbVec3f(-size,-size,0), SbVec3f(-size,size,0),
};
pCoords->point.setValues(0, 4, verts);
pFont->size.setValue(Size.getValue()/10.);
pTranslation->translation.setValue(SbVec3f(-size,size*9./10.,0));
}
else
ViewProviderGeometryObject::onChanged(prop);
}
std::vector<std::string> ViewProviderPlane::getDisplayModes(void) const
{
// add modes
std::vector<std::string> StrList;
StrList.push_back("Base");
return StrList;
}
void ViewProviderPlane::setDisplayMode(const char* ModeName)
{
if (strcmp(ModeName, "Base") == 0)
setDisplayMaskMode("Base");
ViewProviderGeometryObject::setDisplayMode(ModeName);
}
void ViewProviderPlane::attach(App::DocumentObject* pcObject)
{
ViewProviderGeometryObject::attach(pcObject);
SoSeparator *sep = new SoSeparator();
SoAnnotation *lineSep = new SoAnnotation();
SoDrawStyle* style = new SoDrawStyle();
style->lineWidth = 2.0f;
SoMaterialBinding* matBinding = new SoMaterialBinding;
matBinding->value = SoMaterialBinding::OVERALL;
sep->addChild(matBinding);
sep->addChild(pMat);
sep->addChild(getHighlightNode());
pcHighlight->addChild(style);
pcHighlight->addChild(pCoords);
pcHighlight->addChild(pLines);
style = new SoDrawStyle();
style->lineWidth = 2.0f;
style->linePattern.setValue(0x00FF);
lineSep->addChild(style);
lineSep->addChild(pLines);
lineSep->addChild(pFont);
pText->string.setValue(SbString(pcObject->Label.getValue()));
lineSep->addChild(pTranslation);
lineSep->addChild(pText);
pcHighlight->addChild(lineSep);
pcHighlight->style = SoFCSelection::EMISSIVE_DIFFUSE;
addDisplayMaskMode(sep, "Base");
}
void ViewProviderPlane::updateData(const App::Property* prop)
{
pText->string.setValue(SbString(pcObject->Label.getValue()));
ViewProviderGeometryObject::updateData(prop);
}
std::string ViewProviderPlane::getElement(const SoDetail* detail) const
{
if (detail) {
if (detail->getTypeId() == SoLineDetail::getClassTypeId()) {
const SoLineDetail* line_detail = static_cast<const SoLineDetail*>(detail);
int edge = line_detail->getLineIndex();
if (edge == 0)
{
return std::string("Main");
}
}
}
return std::string("");
}
SoDetail* ViewProviderPlane::getDetail(const char* subelement) const
{
SoLineDetail* detail = 0;
std::string subelem(subelement);
int edge = -1;
if(subelem == "Main") edge = 0;
if(edge >= 0) {
detail = new SoLineDetail();
detail->setPartIndex(edge);
}
return detail;
}
bool ViewProviderPlane::isSelectable(void) const
{
return true;
}
// ----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/Helpers.h"
#include "BitFunnel/Index/IRecycler.h"
#include "BitFunnel/Index/ISliceBufferAllocator.h"
#include "LoggerInterfaces/Check.h"
#include "SimpleIndex.h"
namespace BitFunnel
{
//*************************************************************************
//
// Factory methods.
//
//*************************************************************************
std::unique_ptr<ISimpleIndex>
Factories::CreateSimpleIndex(IFileSystem& fileSystem)
{
return std::unique_ptr<ISimpleIndex>(new SimpleIndex(fileSystem));
}
//*************************************************************************
//
// SimpleIndex
//
//*************************************************************************
SimpleIndex::SimpleIndex(IFileSystem& fileSystem)
: m_fileSystem(fileSystem),
m_isStarted(false),
m_blockAllocatorBufferSize(0)
{
}
SimpleIndex::~SimpleIndex()
{
StopIndex();
}
//
// Setter methods.
//
void SimpleIndex::SetConfiguration(
std::unique_ptr<IConfiguration> config)
{
EnsureStarted(false);
CHECK_EQ(m_configuration.get(), nullptr)
<< "Attempting to overwrite existing Configuration.";
m_configuration = std::move(config);
}
void SimpleIndex::SetFactSet(
std::unique_ptr<IFactSet> facts)
{
EnsureStarted(false);
CHECK_EQ(m_facts.get(), nullptr)
<< "Attempting to overwrite existing FactSet.";
m_facts = std::move(facts);
}
void SimpleIndex::SetFileManager(
std::unique_ptr<IFileManager> fileManager)
{
EnsureStarted(false);
CHECK_EQ(m_fileManager.get(), nullptr)
<< "Attempting to overwrite existing FileManager.";
m_fileManager = std::move(fileManager);
}
//void SimpleIndex::SetFileSystem(
// std::unique_ptr<IFileSystem> fileSystem)
//{
// EnsureStarted(false);
// CHECK_EQ(m_fileSystem.get(), nullptr)
// << "Attempting to overwrite existing FileSystem.";
// m_fileSystem = std::move(fileSystem);
//}
void SimpleIndex::SetIdfTable(
std::unique_ptr<IIndexedIdfTable> idfTable)
{
EnsureStarted(false);
CHECK_EQ(m_idfTable.get(), nullptr)
<< "Attempting to overwrite existing IndexIdfTable.";
m_idfTable = std::move(idfTable);
}
void SimpleIndex::SetSchema(
std::unique_ptr<IDocumentDataSchema> schema)
{
EnsureStarted(false);
CHECK_EQ(m_schema.get(), nullptr)
<< "Attempting to overwrite existing DocumentDataSchema.";
m_schema = std::move(schema);
}
void SimpleIndex::SetShardDefinition(
std::unique_ptr<IShardDefinition> definition)
{
EnsureStarted(false);
CHECK_EQ(m_shardDefinition.get(), nullptr)
<< "Attempting to overwrite existing ShardDefinition.";
m_shardDefinition = std::move(definition);
}
void SimpleIndex::SetBlockAllocatorBufferSize(size_t size)
{
m_blockAllocatorBufferSize = size;
}
void SimpleIndex::SetSliceBufferAllocator(
std::unique_ptr<ISliceBufferAllocator> sliceAllocator)
{
EnsureStarted(false);
CHECK_EQ(m_sliceAllocator.get(), nullptr)
<< "Attempting to overwrite existing ShardDefinition.";
m_sliceAllocator = std::move(sliceAllocator);
}
void SimpleIndex::SetTermTableCollection(
std::unique_ptr<ITermTableCollection> termTables)
{
EnsureStarted(false);
CHECK_EQ(m_termTables.get(), nullptr)
<< "Attempting to overwrite existing TermTableCollection.";
m_termTables = std::move(termTables);
}
//
// Configuration methods.
//
void SimpleIndex::ConfigureForStatistics(char const * directory,
size_t gramSize,
bool generateTermToText)
{
EnsureStarted(false);
//if (m_fileSystem.get() == nullptr)
//{
// m_fileSystem = Factories::CreateFileSystem();
//}
if (m_fileManager.get() == nullptr)
{
m_fileManager = Factories::CreateFileManager(directory,
directory,
directory,
m_fileSystem);
}
// TODO: Load schema from file.
if (m_schema.get() == nullptr)
{
m_schema = Factories::CreateDocumentDataSchema();
}
// TODO: consider making this work if no ShardDefinition exists.
if (m_shardDefinition.get() == nullptr)
{
m_shardDefinition = Factories::LoadOrCreateDefaultShardDefinition(*m_fileManager);
}
if (m_termTables.get() == nullptr)
{
// When gathering corpus statistics, we don't yet have any
// TermTables. For now just create a collection of default
// initialized TermTables.
m_termTables =
Factories::CreateTermTableCollection(
m_shardDefinition->GetShardCount());
}
if (m_idfTable == nullptr)
{
// When we're building statistics we don't yet have an
// IndexedIdfTable. Just use an empty one for now. This means
// that terms that are created will all be marked with the
// default IDF value. This is not a problem since the term
// IDF values are not examined by the StatisticsBuild. They
// exist primarily for the query pipeline where the TermTable
// needs terms anotated with IDF values to handle the case
// where the terms have an implicit, or adhoc mapping to
// RowIds.
m_idfTable = Factories::CreateIndexedIdfTable();
}
if (m_facts.get() == nullptr)
{
m_facts = Factories::CreateFactSet();
}
if (m_configuration.get() == nullptr)
{
m_configuration =
Factories::CreateConfiguration(gramSize,
generateTermToText,
*m_idfTable,
*m_facts);
}
}
void SimpleIndex::ConfigureForServing(char const * directory,
size_t gramSize,
bool generateTermToText)
{
EnsureStarted(false);
//if (m_fileSystem.get() == nullptr)
//{
// m_fileSystem = Factories::CreateFileSystem();
//}
if (m_fileManager.get() == nullptr)
{
m_fileManager = Factories::CreateFileManager(directory,
directory,
directory,
m_fileSystem);
}
// TODO: Load schema from file.
if (m_schema.get() == nullptr)
{
m_schema = Factories::CreateDocumentDataSchema();
}
// TODO: Load shard definition from file.
if (m_shardDefinition.get() == nullptr)
{
m_shardDefinition = Factories::LoadOrCreateDefaultShardDefinition(*m_fileManager);
}
if (m_termTables.get() == nullptr)
{
m_termTables =
Factories::CreateTermTableCollection(
*m_fileManager,
m_shardDefinition->GetShardCount());
}
if (m_idfTable == nullptr)
{
auto input = m_fileManager->IndexedIdfTable(0).OpenForRead();
Term::IdfX10 defaultIdf = 60; // TODO: use proper value here.
m_idfTable = Factories::CreateIndexedIdfTable(*input, defaultIdf);
}
if (m_facts.get() == nullptr)
{
m_facts = Factories::CreateFactSet();
}
if (m_configuration.get() == nullptr)
{
m_configuration =
Factories::CreateConfiguration(gramSize,
generateTermToText,
*m_idfTable,
*m_facts);
}
}
void SimpleIndex::ConfigureAsMock(size_t gramSize,
bool generateTermToText)
{
EnsureStarted(false);
// TODO: Load schema from file.
if (m_schema.get() == nullptr)
{
m_schema = Factories::CreateDocumentDataSchema();
}
// TODO: Load shard definition from file.
if (m_shardDefinition.get() == nullptr)
{
m_shardDefinition =
Factories::CreateShardDefinition();
const double defaultDensity = 0.15;
m_shardDefinition->AddShard(0, defaultDensity);
}
if (m_termTables.get() == nullptr)
{
m_termTables =
Factories::CreateTermTableCollection(
m_shardDefinition->GetShardCount());
}
if (m_idfTable == nullptr)
{
m_idfTable = Factories::CreateIndexedIdfTable();
}
if (m_facts.get() == nullptr)
{
m_facts = Factories::CreateFactSet();
}
if (m_configuration.get() == nullptr)
{
m_configuration =
Factories::CreateConfiguration(gramSize,
generateTermToText,
*m_idfTable,
*m_facts);
}
}
void SimpleIndex::StartIndex()
{
EnsureStarted(false);
if (m_sliceAllocator.get() == nullptr)
{
// To calculate a large-enough m_blocksize, we need to calculate the
// largest blocksize required by any TermTable.
size_t m_blockSize = 0;
for (size_t tableId=0; tableId < m_termTables->size(); ++tableId)
{
const size_t tblBlockSize = 32 * GetReasonableBlockSize(*m_schema, m_termTables->GetTermTable(tableId));
if (tblBlockSize > m_blockSize)
{
m_blockSize = tblBlockSize;
}
}
// If the user didn't specify the block allocator buffer size, use
// a default that is small enough that it won't cause a CI failure.
// The CI machines don't have a lot of memory, so it is necessary
// to use a modest initial block count to allow unit tests to pass.
// See issue #388.
size_t blockCount = 512;
if (m_blockAllocatorBufferSize != 0)
{
// Otherwise, compute block count based on requested buffer size.
blockCount = m_blockAllocatorBufferSize / m_blockSize;
}
m_sliceAllocator =
Factories::CreateSliceBufferAllocator(m_blockSize,
blockCount);
}
if (m_recycler.get() == nullptr)
{
m_recycler = Factories::CreateRecycler();
m_recyclerThread = std::thread(RecyclerThreadEntryPoint, this);
}
m_ingestor = Factories::CreateIngestor(*m_schema,
*m_recycler,
*m_termTables,
*m_shardDefinition,
*m_sliceAllocator);
m_isStarted = true;
}
void SimpleIndex::StopIndex()
{
// StopIndex() can be called even if the index hasn't been started.
// If SimpleIndex::SimpleIndex() throws, ~SimpleIndex() will be
// invoked which will call StopIndex().
// See issue 308.
// https://github.com/BitFunnel/BitFunnel/issues/308
//EnsureStarted(true);
if (m_recycler != nullptr)
{
m_recycler->Shutdown();
m_recyclerThread.join();
}
}
IConfiguration const & SimpleIndex::GetConfiguration() const
{
EnsureStarted(true);
return *m_configuration;
}
IFileManager & SimpleIndex::GetFileManager() const
{
EnsureStarted(true);
return *m_fileManager;
}
IFileSystem & SimpleIndex::GetFileSystem() const
{
EnsureStarted(true);
return m_fileSystem;
}
IIngestor & SimpleIndex::GetIngestor() const
{
EnsureStarted(true);
return *m_ingestor;
}
IRecycler & SimpleIndex::GetRecycler() const
{
EnsureStarted(true);
return *m_recycler;
}
ITermTable const & SimpleIndex::GetTermTable0() const
{
return GetTermTable(0);
}
ITermTable const & SimpleIndex::GetTermTable(ShardId shardId) const
{
EnsureStarted(true);
return m_termTables->GetTermTable(shardId);
}
void SimpleIndex::EnsureStarted(bool started) const
{
CHECK_EQ(started, m_isStarted)
<< (started ? "not allowed before starting index." :
"not allowed after starting index.");
}
void SimpleIndex::RecyclerThreadEntryPoint(void * data)
{
SimpleIndex* index = reinterpret_cast<SimpleIndex*>(data);
index->m_recycler->Run();
}
}
<commit_msg>Turn indentation tabs into space<commit_after>// The MIT License (MIT)
// Copyright (c) 2016, Microsoft
// 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 "BitFunnel/Configuration/Factories.h"
#include "BitFunnel/Index/Factories.h"
#include "BitFunnel/Index/Helpers.h"
#include "BitFunnel/Index/IRecycler.h"
#include "BitFunnel/Index/ISliceBufferAllocator.h"
#include "LoggerInterfaces/Check.h"
#include "SimpleIndex.h"
namespace BitFunnel
{
//*************************************************************************
//
// Factory methods.
//
//*************************************************************************
std::unique_ptr<ISimpleIndex>
Factories::CreateSimpleIndex(IFileSystem& fileSystem)
{
return std::unique_ptr<ISimpleIndex>(new SimpleIndex(fileSystem));
}
//*************************************************************************
//
// SimpleIndex
//
//*************************************************************************
SimpleIndex::SimpleIndex(IFileSystem& fileSystem)
: m_fileSystem(fileSystem),
m_isStarted(false),
m_blockAllocatorBufferSize(0)
{
}
SimpleIndex::~SimpleIndex()
{
StopIndex();
}
//
// Setter methods.
//
void SimpleIndex::SetConfiguration(
std::unique_ptr<IConfiguration> config)
{
EnsureStarted(false);
CHECK_EQ(m_configuration.get(), nullptr)
<< "Attempting to overwrite existing Configuration.";
m_configuration = std::move(config);
}
void SimpleIndex::SetFactSet(
std::unique_ptr<IFactSet> facts)
{
EnsureStarted(false);
CHECK_EQ(m_facts.get(), nullptr)
<< "Attempting to overwrite existing FactSet.";
m_facts = std::move(facts);
}
void SimpleIndex::SetFileManager(
std::unique_ptr<IFileManager> fileManager)
{
EnsureStarted(false);
CHECK_EQ(m_fileManager.get(), nullptr)
<< "Attempting to overwrite existing FileManager.";
m_fileManager = std::move(fileManager);
}
//void SimpleIndex::SetFileSystem(
// std::unique_ptr<IFileSystem> fileSystem)
//{
// EnsureStarted(false);
// CHECK_EQ(m_fileSystem.get(), nullptr)
// << "Attempting to overwrite existing FileSystem.";
// m_fileSystem = std::move(fileSystem);
//}
void SimpleIndex::SetIdfTable(
std::unique_ptr<IIndexedIdfTable> idfTable)
{
EnsureStarted(false);
CHECK_EQ(m_idfTable.get(), nullptr)
<< "Attempting to overwrite existing IndexIdfTable.";
m_idfTable = std::move(idfTable);
}
void SimpleIndex::SetSchema(
std::unique_ptr<IDocumentDataSchema> schema)
{
EnsureStarted(false);
CHECK_EQ(m_schema.get(), nullptr)
<< "Attempting to overwrite existing DocumentDataSchema.";
m_schema = std::move(schema);
}
void SimpleIndex::SetShardDefinition(
std::unique_ptr<IShardDefinition> definition)
{
EnsureStarted(false);
CHECK_EQ(m_shardDefinition.get(), nullptr)
<< "Attempting to overwrite existing ShardDefinition.";
m_shardDefinition = std::move(definition);
}
void SimpleIndex::SetBlockAllocatorBufferSize(size_t size)
{
m_blockAllocatorBufferSize = size;
}
void SimpleIndex::SetSliceBufferAllocator(
std::unique_ptr<ISliceBufferAllocator> sliceAllocator)
{
EnsureStarted(false);
CHECK_EQ(m_sliceAllocator.get(), nullptr)
<< "Attempting to overwrite existing ShardDefinition.";
m_sliceAllocator = std::move(sliceAllocator);
}
void SimpleIndex::SetTermTableCollection(
std::unique_ptr<ITermTableCollection> termTables)
{
EnsureStarted(false);
CHECK_EQ(m_termTables.get(), nullptr)
<< "Attempting to overwrite existing TermTableCollection.";
m_termTables = std::move(termTables);
}
//
// Configuration methods.
//
void SimpleIndex::ConfigureForStatistics(char const * directory,
size_t gramSize,
bool generateTermToText)
{
EnsureStarted(false);
//if (m_fileSystem.get() == nullptr)
//{
// m_fileSystem = Factories::CreateFileSystem();
//}
if (m_fileManager.get() == nullptr)
{
m_fileManager = Factories::CreateFileManager(directory,
directory,
directory,
m_fileSystem);
}
// TODO: Load schema from file.
if (m_schema.get() == nullptr)
{
m_schema = Factories::CreateDocumentDataSchema();
}
// TODO: consider making this work if no ShardDefinition exists.
if (m_shardDefinition.get() == nullptr)
{
m_shardDefinition = Factories::LoadOrCreateDefaultShardDefinition(*m_fileManager);
}
if (m_termTables.get() == nullptr)
{
// When gathering corpus statistics, we don't yet have any
// TermTables. For now just create a collection of default
// initialized TermTables.
m_termTables =
Factories::CreateTermTableCollection(
m_shardDefinition->GetShardCount());
}
if (m_idfTable == nullptr)
{
// When we're building statistics we don't yet have an
// IndexedIdfTable. Just use an empty one for now. This means
// that terms that are created will all be marked with the
// default IDF value. This is not a problem since the term
// IDF values are not examined by the StatisticsBuild. They
// exist primarily for the query pipeline where the TermTable
// needs terms anotated with IDF values to handle the case
// where the terms have an implicit, or adhoc mapping to
// RowIds.
m_idfTable = Factories::CreateIndexedIdfTable();
}
if (m_facts.get() == nullptr)
{
m_facts = Factories::CreateFactSet();
}
if (m_configuration.get() == nullptr)
{
m_configuration =
Factories::CreateConfiguration(gramSize,
generateTermToText,
*m_idfTable,
*m_facts);
}
}
void SimpleIndex::ConfigureForServing(char const * directory,
size_t gramSize,
bool generateTermToText)
{
EnsureStarted(false);
//if (m_fileSystem.get() == nullptr)
//{
// m_fileSystem = Factories::CreateFileSystem();
//}
if (m_fileManager.get() == nullptr)
{
m_fileManager = Factories::CreateFileManager(directory,
directory,
directory,
m_fileSystem);
}
// TODO: Load schema from file.
if (m_schema.get() == nullptr)
{
m_schema = Factories::CreateDocumentDataSchema();
}
// TODO: Load shard definition from file.
if (m_shardDefinition.get() == nullptr)
{
m_shardDefinition = Factories::LoadOrCreateDefaultShardDefinition(*m_fileManager);
}
if (m_termTables.get() == nullptr)
{
m_termTables =
Factories::CreateTermTableCollection(
*m_fileManager,
m_shardDefinition->GetShardCount());
}
if (m_idfTable == nullptr)
{
auto input = m_fileManager->IndexedIdfTable(0).OpenForRead();
Term::IdfX10 defaultIdf = 60; // TODO: use proper value here.
m_idfTable = Factories::CreateIndexedIdfTable(*input, defaultIdf);
}
if (m_facts.get() == nullptr)
{
m_facts = Factories::CreateFactSet();
}
if (m_configuration.get() == nullptr)
{
m_configuration =
Factories::CreateConfiguration(gramSize,
generateTermToText,
*m_idfTable,
*m_facts);
}
}
void SimpleIndex::ConfigureAsMock(size_t gramSize,
bool generateTermToText)
{
EnsureStarted(false);
// TODO: Load schema from file.
if (m_schema.get() == nullptr)
{
m_schema = Factories::CreateDocumentDataSchema();
}
// TODO: Load shard definition from file.
if (m_shardDefinition.get() == nullptr)
{
m_shardDefinition =
Factories::CreateShardDefinition();
const double defaultDensity = 0.15;
m_shardDefinition->AddShard(0, defaultDensity);
}
if (m_termTables.get() == nullptr)
{
m_termTables =
Factories::CreateTermTableCollection(
m_shardDefinition->GetShardCount());
}
if (m_idfTable == nullptr)
{
m_idfTable = Factories::CreateIndexedIdfTable();
}
if (m_facts.get() == nullptr)
{
m_facts = Factories::CreateFactSet();
}
if (m_configuration.get() == nullptr)
{
m_configuration =
Factories::CreateConfiguration(gramSize,
generateTermToText,
*m_idfTable,
*m_facts);
}
}
void SimpleIndex::StartIndex()
{
EnsureStarted(false);
if (m_sliceAllocator.get() == nullptr)
{
// To calculate a large-enough m_blocksize, we need to calculate the
// largest blocksize required by any TermTable.
size_t m_blockSize = 0;
for (size_t tableId=0; tableId < m_termTables->size(); ++tableId)
{
const size_t tblBlockSize = 32 * GetReasonableBlockSize(*m_schema, m_termTables->GetTermTable(tableId));
if (tblBlockSize > m_blockSize)
{
m_blockSize = tblBlockSize;
}
}
// If the user didn't specify the block allocator buffer size, use
// a default that is small enough that it won't cause a CI failure.
// The CI machines don't have a lot of memory, so it is necessary
// to use a modest initial block count to allow unit tests to pass.
// See issue #388.
size_t blockCount = 512;
if (m_blockAllocatorBufferSize != 0)
{
// Otherwise, compute block count based on requested buffer size.
blockCount = m_blockAllocatorBufferSize / m_blockSize;
}
m_sliceAllocator =
Factories::CreateSliceBufferAllocator(m_blockSize,
blockCount);
}
if (m_recycler.get() == nullptr)
{
m_recycler = Factories::CreateRecycler();
m_recyclerThread = std::thread(RecyclerThreadEntryPoint, this);
}
m_ingestor = Factories::CreateIngestor(*m_schema,
*m_recycler,
*m_termTables,
*m_shardDefinition,
*m_sliceAllocator);
m_isStarted = true;
}
void SimpleIndex::StopIndex()
{
// StopIndex() can be called even if the index hasn't been started.
// If SimpleIndex::SimpleIndex() throws, ~SimpleIndex() will be
// invoked which will call StopIndex().
// See issue 308.
// https://github.com/BitFunnel/BitFunnel/issues/308
//EnsureStarted(true);
if (m_recycler != nullptr)
{
m_recycler->Shutdown();
m_recyclerThread.join();
}
}
IConfiguration const & SimpleIndex::GetConfiguration() const
{
EnsureStarted(true);
return *m_configuration;
}
IFileManager & SimpleIndex::GetFileManager() const
{
EnsureStarted(true);
return *m_fileManager;
}
IFileSystem & SimpleIndex::GetFileSystem() const
{
EnsureStarted(true);
return m_fileSystem;
}
IIngestor & SimpleIndex::GetIngestor() const
{
EnsureStarted(true);
return *m_ingestor;
}
IRecycler & SimpleIndex::GetRecycler() const
{
EnsureStarted(true);
return *m_recycler;
}
ITermTable const & SimpleIndex::GetTermTable0() const
{
return GetTermTable(0);
}
ITermTable const & SimpleIndex::GetTermTable(ShardId shardId) const
{
EnsureStarted(true);
return m_termTables->GetTermTable(shardId);
}
void SimpleIndex::EnsureStarted(bool started) const
{
CHECK_EQ(started, m_isStarted)
<< (started ? "not allowed before starting index." :
"not allowed after starting index.");
}
void SimpleIndex::RecyclerThreadEntryPoint(void * data)
{
SimpleIndex* index = reinterpret_cast<SimpleIndex*>(data);
index->m_recycler->Run();
}
}
<|endoftext|>
|
<commit_before>
#include "knote.h"
#include "knoteconfigdlg.h"
#include <kiconloader.h>
#include <klocale.h>
#include <kwin.h>
#include <kmessagebox.h>
#include <klineeditdlg.h>
#include <kstddirs.h>
#include <kprocess.h>
#include <kdebug.h>
#include <qpalette.h>
#include <qcolor.h>
#include <qdir.h>
#include <iostream.h>
//**** Initialization ************************************
KNote::KNote( KConfig* config, QWidget* parent, const char* name )
: QFrame( parent, name , WStyle_Customize | WStyle_NoBorderEx | WDestructiveClose )
{
kdDebug() << "start Knote::Knote" << endl;
//WABA: Get rid of decorations. I can hardly imagine that
//this is "The Right Way" of doing that.
KWin::setType( winId(), NET::Toolbar);
m_config = config;
m_notedir = new QDir( KGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
setFrameStyle( NoFrame );
//create the note header- button and label...
m_button = new KNoteButton( this );
m_button->setPixmap( BarIcon( "knotesclose" ) );
connect( m_button, SIGNAL( clicked() ), this, SLOT( slotClose() ) );
m_label = new QLabel( this );
m_label->setAlignment( AlignHCenter );
m_label->setText( m_config->entryMap("Data")["name"] );
m_label->installEventFilter( this ); //recieve events( for dragging & action menu )
//create Editor- it handles own events
m_editor = new KNoteEdit( this );
//load the saved text for this file...
QString datafile = "." + m_config->entryMap("Data")["name"] + "_data";
if( m_notedir->exists( datafile ) )
{
//load the text file and put in m_editor...
QString absfile = m_notedir->absFilePath( datafile );
m_editor->readFile( absfile );
}
//apply configuration settings
slotApplyConfig();
//create the menu items for note- not the editor...
//rename, mail, print, insert date, close, delete
m_menu = new KPopupMenu( this );
m_menu->insertItem( i18n("Rename"), this, SLOT(slotRename(int)) );
m_menu->insertItem( i18n("Mail"), this, SLOT(slotMail(int)) );
m_menu->insertItem( i18n("Print"), this, SLOT(slotPrint(int)) );
m_menu->insertItem( i18n("Insert Date"), this, SLOT(slotInsDate(int)) );
m_menu->insertSeparator();
m_menu->insertItem( i18n("Note Preferences..."), this, SLOT(slotConfig(int)) );
m_menu->insertSeparator();
m_menu->insertItem( i18n("Delete Note"), this, SLOT(slotKill(int)) );
}
KNote::~KNote()
{
//store data from multiline editor in the KConfig file...
if( m_editor && m_config ) //m_config has been deleted when note is killed/not closed
{
QString datafile = m_config->entryMap("Data")["name"];
if( datafile == QString::null )
{
kdDebug() << "note name was missing, not saving anything" << endl;
return;
}
datafile = "." + datafile + "_data";
kdDebug() << "saving data to: " << datafile << endl;
QString absdatafile = m_notedir->absFilePath( datafile );
m_editor->dumpToFile( absdatafile );
}
if( m_config )
m_config->sync();
}
//**** Private Utility functions *************************
void KNote::resizeEvent( QResizeEvent* qre )
{
QFrame::resizeEvent( qre );
m_button->setGeometry( width() - 15, 0, 15, 15 );
m_label->setGeometry( 0, 0, width() - 15, 15 );
m_editor->setGeometry( 0, 15, width(), height() - 15 );
}
void KNote::slotApplyConfig()
{
//do Display group- width, height, bgcolor, fgcolor, transparent
int width = (m_config->entryMap( "Display" )["width"]).toInt();
int height = (m_config->entryMap( "Display" )["height"]).toInt();
resize( width, height );
//create a pallete...
QColor bg = KNoteConfigDlg::getBGColor( *m_config );
QColor fg = KNoteConfigDlg::getFGColor( *m_config );
QPalette newpalette = palette();
newpalette.setColor( QColorGroup::Background, bg );
newpalette.setColor( QColorGroup::Base, bg );
newpalette.setColor( QColorGroup::Foreground, fg );
newpalette.setColor( QColorGroup::Text, fg );
setPalette( newpalette );
//set darker values for the label and button...
m_label->setBackgroundColor( bg.dark( 120 ) );
m_button->setBackgroundColor( bg.dark( 120 ) );
//do the Editor group: tabsize, autoindent, font, fontsize, fontstyle
QString str_font = m_config->entryMap("Editor")["font"];
int font_size =(m_config->entryMap("Editor")["fontsize"]).toInt();
int fontstyle =(m_config->entryMap("Editor")["fontstyle"]).toInt();
m_editor->setFont( QFont( str_font, font_size ) );
int tab_size = (m_config->entryMap("Editor")["tabsize"]).toInt();
m_editor->setDefaultTabStop( tab_size );
QString indent = m_config->entryMap("Editor")["autoindent"];
if( indent == "yes" )
m_editor->setAutoIndentMode( true );
else m_editor->setAutoIndentMode( false );
//do Actions Group, mail, print, date
//do the Data Group- name, data
QString notename = m_config->entryMap("Data")["name"];
m_label->setText( notename );
}
//**** Public Interface **********************************
void KNote::save()
{
}
//**** SLOTS *********************************************
bool KNote::eventFilter( QObject* o, QEvent* ev )
{
QMouseEvent* e = (QMouseEvent*)ev;
if( o == m_label )
{
if( ev->type() == QEvent::MouseButtonRelease )
{
if( e->button() == LeftButton )
{
m_dragging = false;
m_label->releaseMouse();
raise();
}
if (e->button() == MidButton)
lower();
return true;
}
if( ev->type() == QEvent::MouseButtonPress && e->button() == LeftButton )
{
m_pointerOffset = e->pos();
m_label->grabMouse(sizeAllCursor);
return true;
}
if( ev->type() == QEvent::MouseMove && m_label == mouseGrabber())
{
if ( m_dragging )
{
move( QCursor::pos() - m_pointerOffset );
}
else
{
m_dragging = (
(e->pos().x() - m_pointerOffset.x())
*
(e->pos().x() - m_pointerOffset.x())
+
(e->pos().y() - m_pointerOffset.y())
*
(e->pos().y() - m_pointerOffset.y())
>= 9 );
}
return true;
}
if( m_menu && ( ev->type() == QEvent::MouseButtonPress )
&& ( e->button() == RightButton ) )
{
m_menu->popup( QCursor::pos() );
return true;
}
return m_label->eventFilter( o, ev );
}
return QWidget::eventFilter( o, ev );
}
void KNote::slotMail( int id )
{
//sync up the data on note and the data file
QString data_name = m_config->entryMap("Data")["name"] + "_data";
data_name = m_notedir->absFilePath( data_name );
m_editor->dumpToFile( data_name );
QString fname = "\"";
fname += data_name;
fname += "\"";
//KMail doesn't really respect the --msg option it seems??
KProcess mail;
mail << "kmail" << "--composer" << "--msg" << fname;
if( !mail.start( KProcess::DontCare ) )
cerr << "could not start process" << endl;
}
void KNote::slotRename( int id )
{
QString newname;
QString oldname = m_config->entryMap("Data")["name"];
QString oldname_data = oldname + "_data";
while( true )
{
//pop up dialog to get the new name
newname = KLineEditDlg::getText( i18n("Please enter the new name"), QString::null, NULL, this );
//check the name to make sure that it's not already used
if( m_notedir->exists( newname ) )
{
KMessageBox::sorry( this,
i18n("There is already a note with that name") );
}
else
if( newname.isEmpty() )
KMessageBox::sorry( this,
i18n("A name must have at least one character") );
else break;
}
//close config, copy old file to new name
m_config->setGroup( "Data" );
m_config->writeEntry( "name", newname );
m_config->sync();
delete m_config;
if( !m_notedir->rename( oldname, newname ) )
kdDebug() << "rename failed" << endl;
if( !m_notedir->rename( "."+oldname+"_data", "."+newname+"_data" ) )
kdDebug() << "rename of data file failed" << endl;
//open new config
QString newconfig = m_notedir->absFilePath( newname );
m_config = new KConfig( newconfig );
//redo the label text
m_label->setText( newname );
//emit signal with oldname and newname
emit sigRenamed( oldname, newname );
}
void KNote::slotInsDate( int id )
{
int line, column;
m_editor->getCursorPosition( &line, &column );
m_editor->insertAt( KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()),
line, column );
}
void KNote::slotConfig ( int id )
{
//launch config dialog...
KNoteConfigDlg* localConfig = new KNoteConfigDlg( m_config, i18n("Local Settings") );
connect( localConfig, SIGNAL( updateConfig() ),
this, SLOT( slotApplyConfig() ) );
//launch preferences dialog...
localConfig->show();
}
void KNote::slotClose()
{
//save the note text...
QString datafile = "." + m_config->entryMap("Data")["name"] + "_data";
QString absname = m_notedir->absFilePath( datafile );
m_editor->dumpToFile( absname );
m_config->sync();
close();
emit sigClosed( m_config->entryMap("Data")["name"] );
}
void KNote::slotKill( int id )
{
//delete the config file...
QString conf_name = m_config->entryMap("Data")["name"];
m_notedir->remove( conf_name );
m_notedir->remove( "." + conf_name + "_data" );
kdDebug() << "KNote::slotKill, removed file: " << conf_name << endl;
kdDebug() << "KNote::slotKill, removed file: " << "." + conf_name + "_data" << endl;
//don't save anything- m_config checked in destructor
emit sigClosed( m_config->entryMap("Data")["name"] );
delete m_config;
m_config = NULL;
close();
}
void KNote::slotPrint( int id )
{
}
#include "knote.moc"
<commit_msg>removed WABA's net entry for removing window borders... KWin is respecting the Qt flags again it seems, it works without this now<commit_after>
#include "knote.h"
#include "knoteconfigdlg.h"
#include <kiconloader.h>
#include <klocale.h>
#include <kwin.h>
#include <kmessagebox.h>
#include <klineeditdlg.h>
#include <kstddirs.h>
#include <kprocess.h>
#include <kdebug.h>
#include <qpalette.h>
#include <qcolor.h>
#include <qdir.h>
#include <iostream.h>
//**** Initialization ************************************
KNote::KNote( KConfig* config, QWidget* parent, const char* name )
: QFrame( parent, name , WStyle_Customize | WStyle_NoBorderEx | WDestructiveClose )
{
kdDebug() << "start Knote::Knote" << endl;
m_config = config;
m_notedir = new QDir( KGlobal::dirs()->saveLocation( "appdata", "notes/" ) );
setFrameStyle( NoFrame );
//create the note header- button and label...
m_button = new KNoteButton( this );
m_button->setPixmap( BarIcon( "knotesclose" ) );
connect( m_button, SIGNAL( clicked() ), this, SLOT( slotClose() ) );
m_label = new QLabel( this );
m_label->setAlignment( AlignHCenter );
m_label->setText( m_config->entryMap("Data")["name"] );
m_label->installEventFilter( this ); //recieve events( for dragging & action menu )
//create Editor- it handles own events
m_editor = new KNoteEdit( this );
//load the saved text for this file...
QString datafile = "." + m_config->entryMap("Data")["name"] + "_data";
if( m_notedir->exists( datafile ) )
{
//load the text file and put in m_editor...
QString absfile = m_notedir->absFilePath( datafile );
m_editor->readFile( absfile );
}
//apply configuration settings
slotApplyConfig();
//create the menu items for note- not the editor...
//rename, mail, print, insert date, close, delete
m_menu = new KPopupMenu( this );
m_menu->insertItem( i18n("Rename"), this, SLOT(slotRename(int)) );
m_menu->insertItem( i18n("Mail"), this, SLOT(slotMail(int)) );
m_menu->insertItem( i18n("Print"), this, SLOT(slotPrint(int)) );
m_menu->insertItem( i18n("Insert Date"), this, SLOT(slotInsDate(int)) );
m_menu->insertSeparator();
m_menu->insertItem( i18n("Note Preferences..."), this, SLOT(slotConfig(int)) );
m_menu->insertSeparator();
m_menu->insertItem( i18n("Delete Note"), this, SLOT(slotKill(int)) );
}
KNote::~KNote()
{
//store data from multiline editor in the KConfig file...
if( m_editor && m_config ) //m_config has been deleted when note is killed/not closed
{
QString datafile = m_config->entryMap("Data")["name"];
if( datafile == QString::null )
{
kdDebug() << "note name was missing, not saving anything" << endl;
return;
}
datafile = "." + datafile + "_data";
kdDebug() << "saving data to: " << datafile << endl;
QString absdatafile = m_notedir->absFilePath( datafile );
m_editor->dumpToFile( absdatafile );
}
if( m_config )
m_config->sync();
}
//**** Private Utility functions *************************
void KNote::resizeEvent( QResizeEvent* qre )
{
QFrame::resizeEvent( qre );
m_button->setGeometry( width() - 15, 0, 15, 15 );
m_label->setGeometry( 0, 0, width() - 15, 15 );
m_editor->setGeometry( 0, 15, width(), height() - 15 );
}
void KNote::slotApplyConfig()
{
//do Display group- width, height, bgcolor, fgcolor, transparent
int width = (m_config->entryMap( "Display" )["width"]).toInt();
int height = (m_config->entryMap( "Display" )["height"]).toInt();
resize( width, height );
//create a pallete...
QColor bg = KNoteConfigDlg::getBGColor( *m_config );
QColor fg = KNoteConfigDlg::getFGColor( *m_config );
QPalette newpalette = palette();
newpalette.setColor( QColorGroup::Background, bg );
newpalette.setColor( QColorGroup::Base, bg );
newpalette.setColor( QColorGroup::Foreground, fg );
newpalette.setColor( QColorGroup::Text, fg );
setPalette( newpalette );
//set darker values for the label and button...
m_label->setBackgroundColor( bg.dark( 120 ) );
m_button->setBackgroundColor( bg.dark( 120 ) );
//do the Editor group: tabsize, autoindent, font, fontsize, fontstyle
QString str_font = m_config->entryMap("Editor")["font"];
int font_size =(m_config->entryMap("Editor")["fontsize"]).toInt();
int fontstyle =(m_config->entryMap("Editor")["fontstyle"]).toInt();
m_editor->setFont( QFont( str_font, font_size ) );
int tab_size = (m_config->entryMap("Editor")["tabsize"]).toInt();
m_editor->setDefaultTabStop( tab_size );
QString indent = m_config->entryMap("Editor")["autoindent"];
if( indent == "yes" )
m_editor->setAutoIndentMode( true );
else m_editor->setAutoIndentMode( false );
//do Actions Group, mail, print, date
//do the Data Group- name, data
QString notename = m_config->entryMap("Data")["name"];
m_label->setText( notename );
}
//**** Public Interface **********************************
void KNote::save()
{
}
//**** SLOTS *********************************************
bool KNote::eventFilter( QObject* o, QEvent* ev )
{
QMouseEvent* e = (QMouseEvent*)ev;
if( o == m_label )
{
if( ev->type() == QEvent::MouseButtonRelease )
{
if( e->button() == LeftButton )
{
m_dragging = false;
m_label->releaseMouse();
raise();
}
if (e->button() == MidButton)
lower();
return true;
}
if( ev->type() == QEvent::MouseButtonPress && e->button() == LeftButton )
{
m_pointerOffset = e->pos();
m_label->grabMouse(sizeAllCursor);
return true;
}
if( ev->type() == QEvent::MouseMove && m_label == mouseGrabber())
{
if ( m_dragging )
{
move( QCursor::pos() - m_pointerOffset );
}
else
{
m_dragging = (
(e->pos().x() - m_pointerOffset.x())
*
(e->pos().x() - m_pointerOffset.x())
+
(e->pos().y() - m_pointerOffset.y())
*
(e->pos().y() - m_pointerOffset.y())
>= 9 );
}
return true;
}
if( m_menu && ( ev->type() == QEvent::MouseButtonPress )
&& ( e->button() == RightButton ) )
{
m_menu->popup( QCursor::pos() );
return true;
}
return m_label->eventFilter( o, ev );
}
return QWidget::eventFilter( o, ev );
}
void KNote::slotMail( int id )
{
//sync up the data on note and the data file
QString data_name = m_config->entryMap("Data")["name"] + "_data";
data_name = m_notedir->absFilePath( data_name );
m_editor->dumpToFile( data_name );
QString fname = "\"";
fname += data_name;
fname += "\"";
//KMail doesn't really respect the --msg option it seems??
KProcess mail;
mail << "kmail" << "--composer" << "--msg" << fname;
if( !mail.start( KProcess::DontCare ) )
cerr << "could not start process" << endl;
}
void KNote::slotRename( int id )
{
QString newname;
QString oldname = m_config->entryMap("Data")["name"];
QString oldname_data = oldname + "_data";
while( true )
{
//pop up dialog to get the new name
newname = KLineEditDlg::getText( i18n("Please enter the new name"), QString::null, NULL, this );
//check the name to make sure that it's not already used
if( m_notedir->exists( newname ) )
{
KMessageBox::sorry( this,
i18n("There is already a note with that name") );
}
else
if( newname.isEmpty() )
KMessageBox::sorry( this,
i18n("A name must have at least one character") );
else break;
}
//close config, copy old file to new name
m_config->setGroup( "Data" );
m_config->writeEntry( "name", newname );
m_config->sync();
delete m_config;
if( !m_notedir->rename( oldname, newname ) )
kdDebug() << "rename failed" << endl;
if( !m_notedir->rename( "."+oldname+"_data", "."+newname+"_data" ) )
kdDebug() << "rename of data file failed" << endl;
//open new config
QString newconfig = m_notedir->absFilePath( newname );
m_config = new KConfig( newconfig );
//redo the label text
m_label->setText( newname );
//emit signal with oldname and newname
emit sigRenamed( oldname, newname );
}
void KNote::slotInsDate( int id )
{
int line, column;
m_editor->getCursorPosition( &line, &column );
m_editor->insertAt( KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()),
line, column );
}
void KNote::slotConfig ( int id )
{
//launch config dialog...
KNoteConfigDlg* localConfig = new KNoteConfigDlg( m_config, i18n("Local Settings") );
connect( localConfig, SIGNAL( updateConfig() ),
this, SLOT( slotApplyConfig() ) );
//launch preferences dialog...
localConfig->show();
}
void KNote::slotClose()
{
//save the note text...
QString datafile = "." + m_config->entryMap("Data")["name"] + "_data";
QString absname = m_notedir->absFilePath( datafile );
m_editor->dumpToFile( absname );
m_config->sync();
close();
emit sigClosed( m_config->entryMap("Data")["name"] );
}
void KNote::slotKill( int id )
{
//delete the config file...
QString conf_name = m_config->entryMap("Data")["name"];
m_notedir->remove( conf_name );
m_notedir->remove( "." + conf_name + "_data" );
kdDebug() << "KNote::slotKill, removed file: " << conf_name << endl;
kdDebug() << "KNote::slotKill, removed file: " << "." + conf_name + "_data" << endl;
//don't save anything- m_config checked in destructor
emit sigClosed( m_config->entryMap("Data")["name"] );
delete m_config;
m_config = NULL;
close();
}
void KNote::slotPrint( int id )
{
}
#include "knote.moc"
<|endoftext|>
|
<commit_before>#include "jsobject.h"
#include "typeconv.h"
#include <iostream>
#include "error.h"
#include "debug.h"
Nan::Persistent<v8::FunctionTemplate> JsPyWrapper::constructorTpl;
Nan::Persistent<v8::ObjectTemplate> JsPyWrapper::callableTpl;
bool JsPyWrapper::implicitConversionEnabled = true;
void JsPyWrapper::SetObject(PyObjectWithRef object, v8::Local<v8::Object> instance) {
this->object = std::move(object);
}
PyObjectWithRef JsPyWrapper::GetObject() {
return object;
}
JsPyWrapper *JsPyWrapper::UnWrap(v8::Local<v8::Object> object) {
Nan::HandleScope scope;
// find real `this`
while (!IsInstance(object)) {
v8::Local<v8::Value> prototypeValue = object->GetPrototype();
if (prototypeValue->IsNull()) {
return nullptr; // error
}
object = prototypeValue->ToObject();
}
return ObjectWrap::Unwrap<JsPyWrapper>(object);
}
v8::Local<v8::Object> JsPyWrapper::NewInstance(PyObjectWithRef object) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(constructorTpl)->GetFunction();
v8::Local<v8::Object> instance = cons->NewInstance(0, {});
JsPyWrapper *wrapper = UnWrap(instance);
wrapper->SetObject(object, instance);
return scope.Escape(instance);
}
bool JsPyWrapper::IsInstance(v8::Local<v8::Object> object) {
Nan::HandleScope scope;
return Nan::New(constructorTpl)->HasInstance(object);
}
v8::Local<v8::Object> JsPyWrapper::makeFunction(v8::Local<v8::Object> instance) {
Nan::EscapableHandleScope scope;
v8::Local<v8::ObjectTemplate> ctpl = Nan::New(callableTpl);
v8::Local<v8::Object> callable = ctpl->NewInstance();
callable->SetPrototype(instance);
return scope.Escape(callable);
}
void JsPyWrapper::Init(v8::Local<v8::Object> exports) {
GILStateHolder gilholder;
Nan::HandleScope scope;
// Prepare constructor template
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("PyObject").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
v8::Local<v8::ObjectTemplate> prototpl = tpl->PrototypeTemplate();
Nan::SetMethod(prototpl, "$repr", Repr);
Nan::SetMethod(prototpl, "$str", Str);
Nan::SetMethod(prototpl, "$call", Call);
Nan::SetMethod(prototpl, "$value", Value);
Nan::SetMethod(prototpl, "$attr", Attr);
Nan::SetMethod(prototpl, "$", Attr);
Nan::SetMethod(prototpl, "$type", Type);
Nan::SetMethod(prototpl, "toString", Str);
Nan::SetMethod(prototpl, "inspect", Repr);
Nan::SetMethod(prototpl, "valueOf", ValueOf);
Nan::SetNamedPropertyHandler(tpl->InstanceTemplate(), AttrGetter, AttrSetter, 0, 0, AttrEnumerator);
constructorTpl.Reset(tpl);
exports->Set(Nan::New("PyObject").ToLocalChecked(), tpl->GetFunction());
v8::Local<v8::ObjectTemplate> ctpl = Nan::New<v8::ObjectTemplate>();
Nan::SetNamedPropertyHandler(ctpl, AttrGetter, AttrSetter, 0, 0, AttrEnumerator);
Nan::SetCallAsFunctionHandler(ctpl, CallFunction);
callableTpl.Reset(ctpl);
Nan::SetAccessor(exports, Nan::New("implicitConversion").ToLocalChecked(),
[] (v8::Local<v8::String>, const Nan::PropertyCallbackInfo<v8::Value> &args) {
args.GetReturnValue().Set(Nan::New(implicitConversionEnabled));
}, [] (v8::Local<v8::String>, v8::Local<v8::Value> value, const Nan::PropertyCallbackInfo<void> &args) {
implicitConversionEnabled = value->BooleanValue();
}
);
}
void JsPyWrapper::New(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
Nan::HandleScope scope;
v8::Local<v8::Object> thisObject;
if (!args.IsConstructCall()) {
v8::Local<v8::Function> cons = Nan::New(constructorTpl)->GetFunction();
thisObject = cons->NewInstance();
} else {
thisObject = args.This();
}
JsPyWrapper *wrapper = new JsPyWrapper();
wrapper->Wrap(thisObject);
if (args.Length() >= 1) {
wrapper->SetObject(JsToPy(args[0]), thisObject);
} else {
wrapper->SetObject(JsToPy(Nan::Undefined()), thisObject);
}
args.GetReturnValue().Set(thisObject);
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Value(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
args.GetReturnValue().Set(PyToJs(wrapper->object));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Repr(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
args.GetReturnValue().Set(PyToJs(PyObjectWithRef(PyObject_Repr(wrapper->object))));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Str(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectWithRef object = PyObjectMakeRef(wrapper->object);
if (!PyUnicode_Check(object)) object = PyObjectWithRef(PyObject_Str(wrapper->object));
args.GetReturnValue().Set(PyToJs(object));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::ValueOf(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed object = wrapper->object;
if (PyLong_CheckExact(object)) {
args.GetReturnValue().Set(Nan::New<v8::Number>(PyLong_AsDouble(object)));
} else {
args.GetReturnValue().Set(PyToJs(object));
}
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Type(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed object = wrapper->object;
args.GetReturnValue().Set(PyToJs(PyObject_Type(object)));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Attr(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed object = wrapper->object;
Nan::HandleScope scope;
PyObjectWithRef attr(JsToPy(args[0]));
if (args.Length() == 1) {
PyObjectWithRef subObject(PyObject_GetAttr(object, attr));
if (subObject) {
args.GetReturnValue().Set(PyToJs(subObject, implicitConversionEnabled));
} else {
args.GetReturnValue().Set(Nan::Undefined());
}
} else if (args.Length() == 2) {
PyObject_SetAttr(object, attr, JsToPy(args[1]));
}
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::AttrGetter(v8::Local<v8::String> name, const Nan::PropertyCallbackInfo<v8::Value> &info) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(info.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
if (!name->IsString()) return;
PyObjectBorrowed object = wrapper->object;
PyObjectWithRef attr = JsToPy(name);
if (!PyObject_HasAttr(object, attr)) return;
PyObjectWithRef subObject(PyObject_GetAttr(object, attr));
info.GetReturnValue().Set(PyToJs(subObject, implicitConversionEnabled));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::AttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
const Nan::PropertyCallbackInfo<v8::Value> &info) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(info.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
if (!name->IsString()) return;
if (!IsInstance(info.This())) return;
PyObject_SetAttr(wrapper->object, JsToPy(name), JsToPy(value));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::AttrEnumerator(const Nan::PropertyCallbackInfo<v8::Array> &info) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(info.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
if (!IsInstance(info.This())) return;
PyObjectWithRef pyAttrs(PyObject_Dir(wrapper->object));
info.GetReturnValue().Set(PyToJs(pyAttrs).As<v8::Array>());
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Call(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed pyFunc = wrapper->object;
if (!PyCallable_Check(pyFunc)) {
return Nan::ThrowTypeError("not a function");
}
Nan::HandleScope scope;
if (args[0]->IsArray()) {
// arguments
v8::Local<v8::Array> jsArr = args[0].As<v8::Array>();
PyObjectWithRef pyTuple(PyTuple_New(jsArr->Length()));
for (ssize_t i = 0; i < jsArr->Length(); i++) {
int result = PyTuple_SetItem(pyTuple, i, JsToPy(jsArr->Get(i)).escape());
}
args.GetReturnValue().Set(PyToJs(PyObjectWithRef(PyObject_CallObject(pyFunc, pyTuple)), implicitConversionEnabled));
}
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::CallFunction(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed pyFunc = wrapper->object;
if (!PyCallable_Check(pyFunc)) {
return Nan::ThrowTypeError("not a function");
}
Nan::HandleScope scope;
// arguments
PyObjectWithRef pyTuple(PyTuple_New(args.Length()));
for (ssize_t i = 0; i < args.Length(); i++) {
int result = PyTuple_SetItem(pyTuple, i, JsToPy(args[i]).escape());
ASSERT(result != -1);
}
args.GetReturnValue().Set(PyToJs(PyObjectWithRef(PyObject_CallObject(pyFunc, pyTuple)), implicitConversionEnabled));
CHECK_PYTHON_ERROR;
}
<commit_msg>change $call method, adding kw support<commit_after>#include "jsobject.h"
#include "typeconv.h"
#include <iostream>
#include "error.h"
#include "debug.h"
Nan::Persistent<v8::FunctionTemplate> JsPyWrapper::constructorTpl;
Nan::Persistent<v8::ObjectTemplate> JsPyWrapper::callableTpl;
bool JsPyWrapper::implicitConversionEnabled = true;
void JsPyWrapper::SetObject(PyObjectWithRef object, v8::Local<v8::Object> instance) {
this->object = std::move(object);
}
PyObjectWithRef JsPyWrapper::GetObject() {
return object;
}
JsPyWrapper *JsPyWrapper::UnWrap(v8::Local<v8::Object> object) {
Nan::HandleScope scope;
// find real `this`
while (!IsInstance(object)) {
v8::Local<v8::Value> prototypeValue = object->GetPrototype();
if (prototypeValue->IsNull()) {
return nullptr; // error
}
object = prototypeValue->ToObject();
}
return ObjectWrap::Unwrap<JsPyWrapper>(object);
}
v8::Local<v8::Object> JsPyWrapper::NewInstance(PyObjectWithRef object) {
Nan::EscapableHandleScope scope;
v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(constructorTpl)->GetFunction();
v8::Local<v8::Object> instance = cons->NewInstance(0, {});
JsPyWrapper *wrapper = UnWrap(instance);
wrapper->SetObject(object, instance);
return scope.Escape(instance);
}
bool JsPyWrapper::IsInstance(v8::Local<v8::Object> object) {
Nan::HandleScope scope;
return Nan::New(constructorTpl)->HasInstance(object);
}
v8::Local<v8::Object> JsPyWrapper::makeFunction(v8::Local<v8::Object> instance) {
Nan::EscapableHandleScope scope;
v8::Local<v8::ObjectTemplate> ctpl = Nan::New(callableTpl);
v8::Local<v8::Object> callable = ctpl->NewInstance();
callable->SetPrototype(instance);
return scope.Escape(callable);
}
void JsPyWrapper::Init(v8::Local<v8::Object> exports) {
GILStateHolder gilholder;
Nan::HandleScope scope;
// Prepare constructor template
v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("PyObject").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
v8::Local<v8::ObjectTemplate> prototpl = tpl->PrototypeTemplate();
Nan::SetMethod(prototpl, "$repr", Repr);
Nan::SetMethod(prototpl, "$str", Str);
Nan::SetMethod(prototpl, "$call", Call);
Nan::SetMethod(prototpl, "$value", Value);
Nan::SetMethod(prototpl, "$attr", Attr);
Nan::SetMethod(prototpl, "$", Attr);
Nan::SetMethod(prototpl, "$type", Type);
Nan::SetMethod(prototpl, "toString", Str);
Nan::SetMethod(prototpl, "inspect", Repr);
Nan::SetMethod(prototpl, "valueOf", ValueOf);
Nan::SetNamedPropertyHandler(tpl->InstanceTemplate(), AttrGetter, AttrSetter, 0, 0, AttrEnumerator);
constructorTpl.Reset(tpl);
exports->Set(Nan::New("PyObject").ToLocalChecked(), tpl->GetFunction());
v8::Local<v8::ObjectTemplate> ctpl = Nan::New<v8::ObjectTemplate>();
Nan::SetNamedPropertyHandler(ctpl, AttrGetter, AttrSetter, 0, 0, AttrEnumerator);
Nan::SetCallAsFunctionHandler(ctpl, CallFunction);
callableTpl.Reset(ctpl);
Nan::SetAccessor(exports, Nan::New("implicitConversion").ToLocalChecked(),
[] (v8::Local<v8::String>, const Nan::PropertyCallbackInfo<v8::Value> &args) {
args.GetReturnValue().Set(Nan::New(implicitConversionEnabled));
}, [] (v8::Local<v8::String>, v8::Local<v8::Value> value, const Nan::PropertyCallbackInfo<void> &args) {
implicitConversionEnabled = value->BooleanValue();
}
);
}
void JsPyWrapper::New(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
Nan::HandleScope scope;
v8::Local<v8::Object> thisObject;
if (!args.IsConstructCall()) {
v8::Local<v8::Function> cons = Nan::New(constructorTpl)->GetFunction();
thisObject = cons->NewInstance();
} else {
thisObject = args.This();
}
JsPyWrapper *wrapper = new JsPyWrapper();
wrapper->Wrap(thisObject);
if (args.Length() >= 1) {
wrapper->SetObject(JsToPy(args[0]), thisObject);
} else {
wrapper->SetObject(JsToPy(Nan::Undefined()), thisObject);
}
args.GetReturnValue().Set(thisObject);
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Value(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
args.GetReturnValue().Set(PyToJs(wrapper->object));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Repr(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
args.GetReturnValue().Set(PyToJs(PyObjectWithRef(PyObject_Repr(wrapper->object))));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Str(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectWithRef object = PyObjectMakeRef(wrapper->object);
if (!PyUnicode_Check(object)) object = PyObjectWithRef(PyObject_Str(wrapper->object));
args.GetReturnValue().Set(PyToJs(object));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::ValueOf(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed object = wrapper->object;
if (PyLong_CheckExact(object)) {
args.GetReturnValue().Set(Nan::New<v8::Number>(PyLong_AsDouble(object)));
} else {
args.GetReturnValue().Set(PyToJs(object));
}
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Type(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed object = wrapper->object;
args.GetReturnValue().Set(PyToJs(PyObject_Type(object)));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Attr(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed object = wrapper->object;
Nan::HandleScope scope;
PyObjectWithRef attr(JsToPy(args[0]));
if (args.Length() == 1) {
PyObjectWithRef subObject(PyObject_GetAttr(object, attr));
if (subObject) {
args.GetReturnValue().Set(PyToJs(subObject, implicitConversionEnabled));
} else {
args.GetReturnValue().Set(Nan::Undefined());
}
} else if (args.Length() == 2) {
PyObject_SetAttr(object, attr, JsToPy(args[1]));
}
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::AttrGetter(v8::Local<v8::String> name, const Nan::PropertyCallbackInfo<v8::Value> &info) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(info.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
if (!name->IsString()) return;
PyObjectBorrowed object = wrapper->object;
PyObjectWithRef attr = JsToPy(name);
if (!PyObject_HasAttr(object, attr)) return;
PyObjectWithRef subObject(PyObject_GetAttr(object, attr));
info.GetReturnValue().Set(PyToJs(subObject, implicitConversionEnabled));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::AttrSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
const Nan::PropertyCallbackInfo<v8::Value> &info) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(info.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
if (!name->IsString()) return;
if (!IsInstance(info.This())) return;
PyObject_SetAttr(wrapper->object, JsToPy(name), JsToPy(value));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::AttrEnumerator(const Nan::PropertyCallbackInfo<v8::Array> &info) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(info.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
if (!IsInstance(info.This())) return;
PyObjectWithRef pyAttrs(PyObject_Dir(wrapper->object));
info.GetReturnValue().Set(PyToJs(pyAttrs).As<v8::Array>());
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::Call(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed pyFunc = wrapper->object;
if (!PyCallable_Check(pyFunc)) {
return Nan::ThrowTypeError("not a function");
}
Nan::HandleScope scope;
PyObjectWithRef pyArgs(PyTuple_New(0));
PyObjectWithRef pyKw(nullptr);
if (args[0]->IsArray()) {
v8::Local<v8::Array> jsArgs = args[0].As<v8::Array>();
pyArgs = PyObjectWithRef(PyTuple_New(jsArgs->Length()));
for (ssize_t i = 0; i < jsArgs->Length(); i++) {
int result = PyTuple_SetItem(pyArgs, i, JsToPy(jsArgs->Get(i)).escape());
}
if (args[1]->IsObject()) {
v8::Local<v8::Object> jsKw = args[1]->ToObject();
pyKw = PyObjectWithRef(PyDict_New());
v8::Local<v8::Array> keys = Nan::GetOwnPropertyNames(jsKw).ToLocalChecked();
for (ssize_t i = 0; i < keys->Length(); i++) {
v8::Local<v8::Value> jsKey = keys->Get(i);
v8::Local<v8::Value> jsValue = jsKw->Get(jsKey);
int result = PyDict_SetItem(pyKw, JsToPy(jsKey), JsToPy(jsValue));
ASSERT(result != -1);
}
}
}
args.GetReturnValue().Set(PyToJs(PyObjectWithRef(PyObject_Call(pyFunc, pyArgs, pyKw)), implicitConversionEnabled));
CHECK_PYTHON_ERROR;
}
void JsPyWrapper::CallFunction(const Nan::FunctionCallbackInfo<v8::Value> &args) {
GILStateHolder gilholder;
JsPyWrapper *wrapper = UnWrap(args.This());
if (!wrapper || !wrapper->object) return Nan::ThrowTypeError("Unexpected object");
PyObjectBorrowed pyFunc = wrapper->object;
if (!PyCallable_Check(pyFunc)) {
return Nan::ThrowTypeError("not a function");
}
Nan::HandleScope scope;
// arguments
PyObjectWithRef pyTuple(PyTuple_New(args.Length()));
for (ssize_t i = 0; i < args.Length(); i++) {
int result = PyTuple_SetItem(pyTuple, i, JsToPy(args[i]).escape());
ASSERT(result != -1);
}
args.GetReturnValue().Set(PyToJs(PyObjectWithRef(PyObject_CallObject(pyFunc, pyTuple)), implicitConversionEnabled));
CHECK_PYTHON_ERROR;
}
<|endoftext|>
|
<commit_before>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "common.h"
#include "sal.h"
#include "gcenv.structs.h"
#include "gcenv.base.h"
#include <stdlib.h>
#ifndef CPPCODEGEN
//
// This is the mechanism whereby multiple linked modules contribute their global data for initialization at
// startup of the application.
//
// ILC creates sections in the output obj file to mark the beginning and end of merged global data.
// It defines sentinel symbols that are used to get the addresses of the start and end of global data
// at runtime. The section names are platform-specific to match platform-specific linker conventions.
//
#if defined(_MSC_VER)
#pragma section(".modules$A", read)
#pragma section(".modules$Z", read)
extern "C" __declspec(allocate(".modules$A")) void * __modules_a[];
extern "C" __declspec(allocate(".modules$Z")) void * __modules_z[];
__declspec(allocate(".modules$A")) void * __modules_a[] = { nullptr };
__declspec(allocate(".modules$Z")) void * __modules_z[] = { nullptr };
//
// Each obj file compiled from managed code has a .modules$I section containing a pointer to its ReadyToRun
// data (which points at eager class constructors, frozen strings, etc).
//
// The #pragma ... /merge directive folds the book-end sections and all .modules$I sections from all input
// obj files into .rdata in alphabetical order.
//
#pragma comment(linker, "/merge:.modules=.rdata")
extern "C" void __managedcode_a();
extern "C" void __managedcode_z();
#else // _MSC_VER
#if defined(__APPLE__)
extern void * __modules_a[] __asm("section$start$__DATA$__modules");
extern void * __modules_z[] __asm("section$end$__DATA$__modules");
extern char __managedcode_a __asm("section$start$__TEXT$__managedcode");
extern char __managedcode_z __asm("section$end$__TEXT$__managedcode");
#else // __APPLE__
extern "C" void * __start___modules[];
extern "C" void * __stop___modules[];
static void * (&__modules_a)[] = __start___modules;
static void * (&__modules_z)[] = __stop___modules;
extern "C" char __start___managedcode;
extern "C" char __stop___managedcode;
static char& __managedcode_a = __start___managedcode;
static char& __managedcode_z = __stop___managedcode;
#endif // __APPLE__
#endif // _MSC_VER
#endif // !CPPCODEGEN
#ifdef CPPCODEGEN
#pragma warning(disable:4297)
extern "C" Object * RhNewObject(MethodTable * pMT);
extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements);
extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT);
extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT);
extern "C" void RhpStelemRef(void * pArray, int index, void * pObj);
extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT);
extern "C" __NORETURN void RhpThrowEx(void * pEx);
extern "C" Object * __allocate_object(MethodTable * pMT)
{
return RhNewObject(pMT);
}
extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT)
{
return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch
}
extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT)
{
return (Object *)RhTypeCast_CheckCast(obj, pTargetMT);
}
extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT)
{
return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT);
}
extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj)
{
RhpStelemRef(pArray, idx, obj);
}
extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type)
{
return RhpLdelemaRef(pArray, idx, type);
}
extern "C" void __throw_exception(void * pEx)
{
RhpThrowEx(pEx);
}
void __range_check_fail()
{
throw "ThrowRangeOverflowException";
}
extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame);
extern "C" void RhpReversePInvokeReturn2(ReversePInvokeFrame* pRevFrame);
void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame)
{
RhpReversePInvoke2(pRevFrame);
}
void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame)
{
RhpReversePInvokeReturn2(pRevFrame);
}
namespace System_Private_CoreLib { namespace System {
class Object {
public:
MethodTable * get_EEType() { return *(MethodTable **)this; }
};
class Array : public Object {
public:
int32_t GetArrayLength() {
return *(int32_t *)((void **)this + 1);
}
void * GetArrayData() {
return (void **)this + 2;
}
};
class String : public Object { public:
static MethodTable * __getMethodTable();
};
class String__Array : public Object { public:
static MethodTable * __getMethodTable();
};
class EETypePtr { public:
intptr_t m_value;
};
}; };
Object * __load_string_literal(const char * string)
{
// TODO: Cache/intern string literals
// TODO: Unicode string literals
size_t len = strlen(string);
Object * pString = RhNewArray(System_Private_CoreLib::System::String::__getMethodTable(), (int32_t)len);
uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t));
for (size_t i = 0; i < len; i++)
p[i] = string[i];
return pString;
}
extern "C" void RhpThrowEx(void * pEx)
{
throw "RhpThrowEx";
}
extern "C" void RhpThrowHwEx()
{
throw "RhpThrowHwEx";
}
extern "C" void RhpCallCatchFunclet()
{
throw "RhpCallCatchFunclet";
}
extern "C" void RhpCallFilterFunclet()
{
throw "RhpCallFilterFunclet";
}
extern "C" void RhpCallFinallyFunclet()
{
throw "RhpCallFinallyFunclet";
}
extern "C" void RhpUniversalTransition()
{
throw "RhpUniversalTransition";
}
extern "C" void RhpUniversalTransition_DebugStepTailCall()
{
throw "RhpUniversalTransition_DebugStepTailCall";
}
void* RtRHeaderWrapper();
#endif // CPPCODEGEN
extern "C" void __fail_fast()
{
// TODO: FailFast
printf("Call to an unimplemented runtime method; execution cannot continue.\n");
printf("Method: __fail_fast\n");
exit(-1);
}
extern "C" bool REDHAWK_PALAPI PalInit();
#define DLL_PROCESS_ATTACH 1
extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved);
extern "C" int32_t RhpEnableConservativeStackReporting();
extern "C" void RhpShutdown();
#ifndef CPPCODEGEN
extern "C" bool RhpRegisterCoffModule(void * pModule,
void * pvStartRange, uint32_t cbRange,
void ** pClasslibFunctions, uint32_t nClasslibFunctions);
extern "C" bool RhpRegisterUnixModule(void * pModule,
void * pvStartRange, uint32_t cbRange,
void ** pClasslibFunctions, uint32_t nClasslibFunctions);
#ifdef _WIN32
extern "C" void* WINAPI GetModuleHandleW(const wchar_t *);
#else
extern "C" void* WINAPI PalGetModuleHandleFromPointer(void* pointer);
#endif
extern "C" void GetRuntimeException();
extern "C" void FailFast();
extern "C" void AppendExceptionStackFrame();
typedef void(*pfn)();
static const pfn c_classlibFunctions[] = {
&GetRuntimeException,
&FailFast,
nullptr, // &UnhandledExceptionHandler,
&AppendExceptionStackFrame,
};
#endif // !CPPCODEGEN
extern "C" void InitializeModules(void ** modules, int count);
#if defined(_WIN32)
extern "C" int __managed__Main(int argc, wchar_t* argv[]);
int wmain(int argc, wchar_t* argv[])
#else
extern "C" int __managed__Main(int argc, char* argv[]);
int main(int argc, char* argv[])
#endif
{
if (!PalInit())
return -1;
if (!RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL))
return -1;
if (!RhpEnableConservativeStackReporting())
return -1;
#ifndef CPPCODEGEN
#if defined(_WIN32)
if (!RhpRegisterCoffModule(GetModuleHandleW(NULL),
#else // _WIN32
if (!RhpRegisterUnixModule(PalGetModuleHandleFromPointer((void*)&main),
#endif // _WIN32
(void*)&__managedcode_a, (uint32_t)((char *)&__managedcode_z - (char*)&__managedcode_a),
(void **)&c_classlibFunctions, _countof(c_classlibFunctions)))
{
return -1;
}
#endif // !CPPCODEGEN
#ifdef CPPCODEGEN
ReversePInvokeFrame frame;
__reverse_pinvoke(&frame);
#endif
#ifndef CPPCODEGEN
InitializeModules(__modules_a, (int)((__modules_z - __modules_a)));
#else // !CPPCODEGEN
InitializeModules((void**)RtRHeaderWrapper(), 2);
#endif // !CPPCODEGEN
int retval;
try
{
retval = __managed__Main(argc, argv);
}
catch (const char* &e)
{
printf("Call to an unimplemented runtime method; execution cannot continue.\n");
printf("Method: %s\n", e);
retval = -1;
}
#ifdef CPPCODEGEN
__reverse_pinvoke_return(&frame);
#endif
RhpShutdown();
return retval;
}
<commit_msg>Add a stubbed out CCWAddRef implementation for CppCodegen<commit_after>// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "common.h"
#include "sal.h"
#include "gcenv.structs.h"
#include "gcenv.base.h"
#include <stdlib.h>
#ifndef CPPCODEGEN
//
// This is the mechanism whereby multiple linked modules contribute their global data for initialization at
// startup of the application.
//
// ILC creates sections in the output obj file to mark the beginning and end of merged global data.
// It defines sentinel symbols that are used to get the addresses of the start and end of global data
// at runtime. The section names are platform-specific to match platform-specific linker conventions.
//
#if defined(_MSC_VER)
#pragma section(".modules$A", read)
#pragma section(".modules$Z", read)
extern "C" __declspec(allocate(".modules$A")) void * __modules_a[];
extern "C" __declspec(allocate(".modules$Z")) void * __modules_z[];
__declspec(allocate(".modules$A")) void * __modules_a[] = { nullptr };
__declspec(allocate(".modules$Z")) void * __modules_z[] = { nullptr };
//
// Each obj file compiled from managed code has a .modules$I section containing a pointer to its ReadyToRun
// data (which points at eager class constructors, frozen strings, etc).
//
// The #pragma ... /merge directive folds the book-end sections and all .modules$I sections from all input
// obj files into .rdata in alphabetical order.
//
#pragma comment(linker, "/merge:.modules=.rdata")
extern "C" void __managedcode_a();
extern "C" void __managedcode_z();
#else // _MSC_VER
#if defined(__APPLE__)
extern void * __modules_a[] __asm("section$start$__DATA$__modules");
extern void * __modules_z[] __asm("section$end$__DATA$__modules");
extern char __managedcode_a __asm("section$start$__TEXT$__managedcode");
extern char __managedcode_z __asm("section$end$__TEXT$__managedcode");
#else // __APPLE__
extern "C" void * __start___modules[];
extern "C" void * __stop___modules[];
static void * (&__modules_a)[] = __start___modules;
static void * (&__modules_z)[] = __stop___modules;
extern "C" char __start___managedcode;
extern "C" char __stop___managedcode;
static char& __managedcode_a = __start___managedcode;
static char& __managedcode_z = __stop___managedcode;
#endif // __APPLE__
#endif // _MSC_VER
#endif // !CPPCODEGEN
#ifdef CPPCODEGEN
#pragma warning(disable:4297)
extern "C" Object * RhNewObject(MethodTable * pMT);
extern "C" Object * RhNewArray(MethodTable * pMT, int32_t elements);
extern "C" void * RhTypeCast_IsInstanceOf(void * pObject, MethodTable * pMT);
extern "C" void * RhTypeCast_CheckCast(void * pObject, MethodTable * pMT);
extern "C" void RhpStelemRef(void * pArray, int index, void * pObj);
extern "C" void * RhpLdelemaRef(void * pArray, int index, MethodTable * pMT);
extern "C" __NORETURN void RhpThrowEx(void * pEx);
extern "C" Object * __allocate_object(MethodTable * pMT)
{
return RhNewObject(pMT);
}
extern "C" Object * __allocate_array(size_t elements, MethodTable * pMT)
{
return RhNewArray(pMT, (int32_t)elements); // TODO: type mismatch
}
extern "C" Object * __castclass(void * obj, MethodTable * pTargetMT)
{
return (Object *)RhTypeCast_CheckCast(obj, pTargetMT);
}
extern "C" Object * __isinst(void * obj, MethodTable * pTargetMT)
{
return (Object *)RhTypeCast_IsInstanceOf(obj, pTargetMT);
}
extern "C" void __stelem_ref(void * pArray, unsigned idx, void * obj)
{
RhpStelemRef(pArray, idx, obj);
}
extern "C" void* __ldelema_ref(void * pArray, unsigned idx, MethodTable * type)
{
return RhpLdelemaRef(pArray, idx, type);
}
extern "C" void __throw_exception(void * pEx)
{
RhpThrowEx(pEx);
}
void __range_check_fail()
{
throw "ThrowRangeOverflowException";
}
extern "C" void RhpReversePInvoke2(ReversePInvokeFrame* pRevFrame);
extern "C" void RhpReversePInvokeReturn2(ReversePInvokeFrame* pRevFrame);
void __reverse_pinvoke(ReversePInvokeFrame* pRevFrame)
{
RhpReversePInvoke2(pRevFrame);
}
void __reverse_pinvoke_return(ReversePInvokeFrame* pRevFrame)
{
RhpReversePInvokeReturn2(pRevFrame);
}
namespace System_Private_CoreLib { namespace System {
class Object {
public:
MethodTable * get_EEType() { return *(MethodTable **)this; }
};
class Array : public Object {
public:
int32_t GetArrayLength() {
return *(int32_t *)((void **)this + 1);
}
void * GetArrayData() {
return (void **)this + 2;
}
};
class String : public Object { public:
static MethodTable * __getMethodTable();
};
class String__Array : public Object { public:
static MethodTable * __getMethodTable();
};
class EETypePtr { public:
intptr_t m_value;
};
}; };
Object * __load_string_literal(const char * string)
{
// TODO: Cache/intern string literals
// TODO: Unicode string literals
size_t len = strlen(string);
Object * pString = RhNewArray(System_Private_CoreLib::System::String::__getMethodTable(), (int32_t)len);
uint16_t * p = (uint16_t *)((char*)pString + sizeof(intptr_t) + sizeof(int32_t));
for (size_t i = 0; i < len; i++)
p[i] = string[i];
return pString;
}
extern "C" void RhpThrowEx(void * pEx)
{
throw "RhpThrowEx";
}
extern "C" void RhpThrowHwEx()
{
throw "RhpThrowHwEx";
}
extern "C" void RhpCallCatchFunclet()
{
throw "RhpCallCatchFunclet";
}
extern "C" void RhpCallFilterFunclet()
{
throw "RhpCallFilterFunclet";
}
extern "C" void RhpCallFinallyFunclet()
{
throw "RhpCallFinallyFunclet";
}
extern "C" void RhpUniversalTransition()
{
throw "RhpUniversalTransition";
}
extern "C" void RhpUniversalTransition_DebugStepTailCall()
{
throw "RhpUniversalTransition_DebugStepTailCall";
}
extern "C" void CCWAddRef()
{
throw "CCWAddRef";
}
void* RtRHeaderWrapper();
#endif // CPPCODEGEN
extern "C" void __fail_fast()
{
// TODO: FailFast
printf("Call to an unimplemented runtime method; execution cannot continue.\n");
printf("Method: __fail_fast\n");
exit(-1);
}
extern "C" bool REDHAWK_PALAPI PalInit();
#define DLL_PROCESS_ATTACH 1
extern "C" BOOL WINAPI RtuDllMain(HANDLE hPalInstance, DWORD dwReason, void* pvReserved);
extern "C" int32_t RhpEnableConservativeStackReporting();
extern "C" void RhpShutdown();
#ifndef CPPCODEGEN
extern "C" bool RhpRegisterCoffModule(void * pModule,
void * pvStartRange, uint32_t cbRange,
void ** pClasslibFunctions, uint32_t nClasslibFunctions);
extern "C" bool RhpRegisterUnixModule(void * pModule,
void * pvStartRange, uint32_t cbRange,
void ** pClasslibFunctions, uint32_t nClasslibFunctions);
#ifdef _WIN32
extern "C" void* WINAPI GetModuleHandleW(const wchar_t *);
#else
extern "C" void* WINAPI PalGetModuleHandleFromPointer(void* pointer);
#endif
extern "C" void GetRuntimeException();
extern "C" void FailFast();
extern "C" void AppendExceptionStackFrame();
typedef void(*pfn)();
static const pfn c_classlibFunctions[] = {
&GetRuntimeException,
&FailFast,
nullptr, // &UnhandledExceptionHandler,
&AppendExceptionStackFrame,
};
#endif // !CPPCODEGEN
extern "C" void InitializeModules(void ** modules, int count);
#if defined(_WIN32)
extern "C" int __managed__Main(int argc, wchar_t* argv[]);
int wmain(int argc, wchar_t* argv[])
#else
extern "C" int __managed__Main(int argc, char* argv[]);
int main(int argc, char* argv[])
#endif
{
if (!PalInit())
return -1;
if (!RtuDllMain(NULL, DLL_PROCESS_ATTACH, NULL))
return -1;
if (!RhpEnableConservativeStackReporting())
return -1;
#ifndef CPPCODEGEN
#if defined(_WIN32)
if (!RhpRegisterCoffModule(GetModuleHandleW(NULL),
#else // _WIN32
if (!RhpRegisterUnixModule(PalGetModuleHandleFromPointer((void*)&main),
#endif // _WIN32
(void*)&__managedcode_a, (uint32_t)((char *)&__managedcode_z - (char*)&__managedcode_a),
(void **)&c_classlibFunctions, _countof(c_classlibFunctions)))
{
return -1;
}
#endif // !CPPCODEGEN
#ifdef CPPCODEGEN
ReversePInvokeFrame frame;
__reverse_pinvoke(&frame);
#endif
#ifndef CPPCODEGEN
InitializeModules(__modules_a, (int)((__modules_z - __modules_a)));
#else // !CPPCODEGEN
InitializeModules((void**)RtRHeaderWrapper(), 2);
#endif // !CPPCODEGEN
int retval;
try
{
retval = __managed__Main(argc, argv);
}
catch (const char* &e)
{
printf("Call to an unimplemented runtime method; execution cannot continue.\n");
printf("Method: %s\n", e);
retval = -1;
}
#ifdef CPPCODEGEN
__reverse_pinvoke_return(&frame);
#endif
RhpShutdown();
return retval;
}
<|endoftext|>
|
<commit_before>#include "t3d/filelist.h"
#include "core/assert.h"
#include "core/os.h"
#include "core/vfs.h"
#include <algorithm>
namespace euphoria::t3d
{
void
FileList::AddDirectory
(
const core::vfs::DirPath& directory,
core::vfs::FileSystem* file_system
)
{
auto listed_files = file_system->ListFiles(directory);
for(const auto& relative_file: listed_files)
{
const auto file = directory.GetFile(relative_file.name);
const auto my_ext = file.GetExtension();
const auto found_ext = std::find
(
extensions.begin(),
extensions.end(),
my_ext
);
const auto has_ext = found_ext != extensions.end();
if(has_ext)
{
files.emplace_back(file);
}
}
}
bool
FileList::HasMoreFiles() const
{
return !files.empty();
}
core::vfs::FilePath
FileList::NextFile()
{
ASSERT(!files.empty());
ASSERTX(index < files.size(), index, files.size());
const auto ret = files[index];
index += 1;
if(index >= files.size())
{
files.clear();
index = 0;
}
return ret;
}
}<commit_msg>don't add directories<commit_after>#include "t3d/filelist.h"
#include "core/assert.h"
#include "core/os.h"
#include "core/vfs.h"
#include <algorithm>
namespace euphoria::t3d
{
void
FileList::AddDirectory
(
const core::vfs::DirPath& directory,
core::vfs::FileSystem* file_system
)
{
auto listed_files = file_system->ListFiles(directory);
for(const auto& relative_file: listed_files)
{
if(relative_file.is_file == false) { continue; }
const auto file = directory.GetFile(relative_file.name);
const auto my_ext = file.GetExtension();
const auto found_ext = std::find
(
extensions.begin(),
extensions.end(),
my_ext
);
const auto has_ext = found_ext != extensions.end();
if(has_ext)
{
files.emplace_back(file);
}
}
}
bool
FileList::HasMoreFiles() const
{
return !files.empty();
}
core::vfs::FilePath
FileList::NextFile()
{
ASSERT(!files.empty());
ASSERTX(index < files.size(), index, files.size());
const auto ret = files[index];
index += 1;
if(index >= files.size())
{
files.clear();
index = 0;
}
return ret;
}
}<|endoftext|>
|
<commit_before>/****************************************************************************
* Copyright 2014-2015 Trefilov Dmitrij *
* *
* 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 "SqliteTransactionImpl.h"
#include "SqliteConnector.h"
namespace metacpp
{
namespace db
{
namespace sql
{
namespace connectors
{
namespace sqlite
{
SqliteTransactionImpl::SqliteTransactionImpl(sqlite3 *dbHandle)
: m_dbHandle(dbHandle)
{
}
SqliteTransactionImpl::~SqliteTransactionImpl()
{
std::lock_guard<std::mutex> _guard(m_statementsMutex);
if (m_statements.size())
{
std::cerr << "There's still " << m_statements.size() <<
" unclosed statements while destroing the sqlite transaction" << std::endl;
}
}
bool SqliteTransactionImpl::begin()
{
int error = sqlite3_exec(m_dbHandle, "BEGIN TRANSACTION", nullptr, nullptr, nullptr);
if (error != SQLITE_OK)
{
std::cerr << "SqliteTransactionImpl::begin(): sqlite3_exec(): "
<< sqlite3_errmsg(m_dbHandle) << std::endl;
return false;
}
return true;
}
bool SqliteTransactionImpl::commit()
{
int error = sqlite3_exec(m_dbHandle, "COMMIT TRANSACTION", nullptr, nullptr, nullptr);
if (error != SQLITE_OK)
{
std::cout << "SqliteTransactionImpl::commit(): sqlite3_exec(): "
<< sqlite3_errmsg(m_dbHandle) << std::endl;
return false;
}
return true;
}
bool SqliteTransactionImpl::rollback()
{
int error = sqlite3_exec(m_dbHandle, "ROLLBACK TRANSACTION", nullptr, nullptr, nullptr);
if (error != SQLITE_OK)
{
std::cerr << "SqliteTransactionImpl::rollback(): sqlite3_exec(): "
<< sqlite3_errmsg(m_dbHandle) << std::endl;
return false;
}
return true;
}
SqlStatementImpl *SqliteTransactionImpl::createStatement(SqlStatementType type, const String& queryText)
{
std::lock_guard<std::mutex> _guard(m_statementsMutex);
SqliteStatementImpl *statement = new SqliteStatementImpl(type, queryText);
m_statements.push_back(statement);
return statement;
}
bool SqliteTransactionImpl::prepare(SqlStatementImpl *statement)
{
const String& query = statement->queryText();
sqlite3_stmt *stmt;
std::cout << query << std::endl;
int error = sqlite3_prepare_v2(m_dbHandle, query.c_str(), (int)query.size() + 1,
&stmt, nullptr);
if (SQLITE_OK != error)
{
std::cerr << "sqlite3_prepare_v2(): " << sqlite3_errmsg(m_dbHandle) << std::endl;
std::cerr << query << std::endl;
return false;
}
reinterpret_cast<SqliteStatementImpl *>(statement)->setHandle(stmt);
return true;
}
bool SqliteTransactionImpl::execStatement(SqlStatementImpl *statement, int *numRowsAffected)
{
if (!statement->prepared())
throw std::runtime_error("SqliteTransactionImpl::execStatement(): should be prepared first");
int error = sqlite3_step(reinterpret_cast<SqliteStatementImpl *>(statement)->handle());
if (SQLITE_DONE == error)
{
statement->setDone();
if (numRowsAffected) *numRowsAffected = sqlite3_changes(m_dbHandle);
return true;
}
else if (SQLITE_ROW == error)
{
if (numRowsAffected) *numRowsAffected = sqlite3_changes(m_dbHandle);
return true;
}
std::cerr << "sqlite3_step(): " << sqlite3_errmsg(m_dbHandle);
return false;
}
template<typename T>
void assignField(const MetaFieldBase *field, int sqliteType, int expectedType, Object *obj, const T& val)
{
if (field->nullable() && sqliteType == SQLITE_NULL)
field->access<Nullable<T> >(obj).reset();
else {
if (sqliteType != expectedType)
throw std::runtime_error(String(String(field->name()) + ": Type mismatch").c_str());
if (field->nullable())
field->access<Nullable<T> >(obj) = val;
else
field->access<T>(obj) = val;
}
}
bool SqliteTransactionImpl::fetchNext(SqlStatementImpl *statement, SqlStorable *storable)
{
if (!statement->prepared())
throw std::runtime_error("SqliteTransactionImpl::execStatement(): should be prepared first");
// no more rows
if (statement->done())
return false;
sqlite3_stmt *stmt = reinterpret_cast<SqliteStatementImpl *>(statement)->handle();
int error = sqlite3_step(stmt);
if (SQLITE_DONE == error)
{
statement->setDone();
return false;
}
if (SQLITE_ROW == error)
{
int columnCount = sqlite3_data_count(stmt);
for (int i = 0; i < columnCount; ++i)
{
String name = sqlite3_column_name(stmt, i);
auto field = storable->record()->metaObject()->fieldByName(name, false);
if (!field)
{
std::cerr << "Cannot bind sql result to an object field " << name << std::endl;
continue;
}
int sqliteType = sqlite3_column_type(stmt, i);
switch (field->type())
{
case eFieldBool:
assignField<bool>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int(stmt, i) != 0);
break;
case eFieldInt:
assignField<int32_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int(stmt, i));
break;
case eFieldEnum:
case eFieldUint:
assignField<uint32_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), (uint32_t)sqlite3_column_int64(stmt, i));
break;
case eFieldUint64:
assignField<uint64_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int64(stmt, i));
break;
case eFieldInt64:
assignField<int64_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int64(stmt, i));
break;
case eFieldFloat:
assignField<float>(field, sqliteType, SQLITE_FLOAT, storable->record(), (float)sqlite3_column_double(stmt, i));
break;
case eFieldDouble:
assignField<double>(field, sqliteType, SQLITE_FLOAT, storable->record(), sqlite3_column_double(stmt, i));
break;
case eFieldString:
assignField<String>(field, sqliteType, SQLITE_TEXT, storable->record(), (const char *)sqlite3_column_text(stmt, i));
break;
case eFieldDateTime:
assignField<DateTime>(field, sqliteType, SQLITE_TEXT, storable->record(),
DateTime::fromString((const char *)sqlite3_column_text(stmt, i)));
break;
case eFieldObject:
case eFieldArray:
throw std::runtime_error("Cannot handle non-plain objects");
default:
throw std::runtime_error("Unknown field type");
}
}
return true;
}
throw std::runtime_error(std::string("sqlite3_step(): ") + sqlite3_errmsg(m_dbHandle));
}
bool SqliteTransactionImpl::getLastInsertId(SqlStatementImpl *statement, SqlStorable *storable)
{
(void)statement;
auto pkey = storable->primaryKey();
if (pkey)
{
switch (storable->primaryKey()->type())
{
case eFieldInt:
assignField<int32_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
(int32_t)sqlite3_last_insert_rowid(m_dbHandle));
return true;
case eFieldUint:
assignField<uint32_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
(uint32_t)sqlite3_last_insert_rowid(m_dbHandle));
return true;
case eFieldInt64:
assignField<int64_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
sqlite3_last_insert_rowid(m_dbHandle));
return true;
case eFieldUint64:
assignField<uint64_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
sqlite3_last_insert_rowid(m_dbHandle));
return true;
default:
return false;
}
}
return false;
}
bool SqliteTransactionImpl::closeStatement(SqlStatementImpl *statement)
{
std::lock_guard<std::mutex> _guard(m_statementsMutex);
SqliteStatementImpl *sqliteStatement = reinterpret_cast<SqliteStatementImpl *>(statement);
auto it = std::find(m_statements.begin(), m_statements.end(), sqliteStatement);
if (it == m_statements.end())
{
std::cerr << "SqliteTransactionImpl::closeStatement(): there's no such statement" << std::endl;
return false;
}
m_statements.erase(it);
delete sqliteStatement;
return true;
}
} // namespace sqlite
} // namespace connectors
} // namespace sql
} // namespace db
} // namespace metacpp
<commit_msg>debugging stuff<commit_after>/****************************************************************************
* Copyright 2014-2015 Trefilov Dmitrij *
* *
* 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 "SqliteTransactionImpl.h"
#include "SqliteConnector.h"
namespace metacpp
{
namespace db
{
namespace sql
{
namespace connectors
{
namespace sqlite
{
SqliteTransactionImpl::SqliteTransactionImpl(sqlite3 *dbHandle)
: m_dbHandle(dbHandle)
{
}
SqliteTransactionImpl::~SqliteTransactionImpl()
{
std::lock_guard<std::mutex> _guard(m_statementsMutex);
if (m_statements.size())
{
std::cerr << "There's still " << m_statements.size() <<
" unclosed statements while destroing the sqlite transaction" << std::endl;
}
}
bool SqliteTransactionImpl::begin()
{
int error = sqlite3_exec(m_dbHandle, "BEGIN TRANSACTION", nullptr, nullptr, nullptr);
if (error != SQLITE_OK)
{
std::cerr << "SqliteTransactionImpl::begin(): sqlite3_exec(): "
<< sqlite3_errmsg(m_dbHandle) << std::endl;
return false;
}
return true;
}
bool SqliteTransactionImpl::commit()
{
int error = sqlite3_exec(m_dbHandle, "COMMIT TRANSACTION", nullptr, nullptr, nullptr);
if (error != SQLITE_OK)
{
std::cout << "SqliteTransactionImpl::commit(): sqlite3_exec(): "
<< sqlite3_errmsg(m_dbHandle) << std::endl;
return false;
}
return true;
}
bool SqliteTransactionImpl::rollback()
{
int error = sqlite3_exec(m_dbHandle, "ROLLBACK TRANSACTION", nullptr, nullptr, nullptr);
if (error != SQLITE_OK)
{
std::cerr << "SqliteTransactionImpl::rollback(): sqlite3_exec(): "
<< sqlite3_errmsg(m_dbHandle) << std::endl;
return false;
}
return true;
}
SqlStatementImpl *SqliteTransactionImpl::createStatement(SqlStatementType type, const String& queryText)
{
std::lock_guard<std::mutex> _guard(m_statementsMutex);
SqliteStatementImpl *statement = new SqliteStatementImpl(type, queryText);
m_statements.push_back(statement);
return statement;
}
bool SqliteTransactionImpl::prepare(SqlStatementImpl *statement)
{
const String& query = statement->queryText();
sqlite3_stmt *stmt;
// std::cout << query << std::endl;
int error = sqlite3_prepare_v2(m_dbHandle, query.c_str(), (int)query.size() + 1,
&stmt, nullptr);
if (SQLITE_OK != error)
{
std::cerr << "sqlite3_prepare_v2(): " << sqlite3_errmsg(m_dbHandle) << std::endl;
std::cerr << query << std::endl;
return false;
}
reinterpret_cast<SqliteStatementImpl *>(statement)->setHandle(stmt);
return true;
}
bool SqliteTransactionImpl::execStatement(SqlStatementImpl *statement, int *numRowsAffected)
{
if (!statement->prepared())
throw std::runtime_error("SqliteTransactionImpl::execStatement(): should be prepared first");
int error = sqlite3_step(reinterpret_cast<SqliteStatementImpl *>(statement)->handle());
if (SQLITE_DONE == error)
{
statement->setDone();
if (numRowsAffected) *numRowsAffected = sqlite3_changes(m_dbHandle);
return true;
}
else if (SQLITE_ROW == error)
{
if (numRowsAffected) *numRowsAffected = sqlite3_changes(m_dbHandle);
return true;
}
std::cerr << "sqlite3_step(): " << sqlite3_errmsg(m_dbHandle);
return false;
}
template<typename T>
void assignField(const MetaFieldBase *field, int sqliteType, int expectedType, Object *obj, const T& val)
{
if (field->nullable() && sqliteType == SQLITE_NULL)
field->access<Nullable<T> >(obj).reset();
else {
if (sqliteType != expectedType)
throw std::runtime_error(String(String(field->name()) + ": Type mismatch").c_str());
if (field->nullable())
field->access<Nullable<T> >(obj) = val;
else
field->access<T>(obj) = val;
}
}
bool SqliteTransactionImpl::fetchNext(SqlStatementImpl *statement, SqlStorable *storable)
{
if (!statement->prepared())
throw std::runtime_error("SqliteTransactionImpl::execStatement(): should be prepared first");
// no more rows
if (statement->done())
return false;
sqlite3_stmt *stmt = reinterpret_cast<SqliteStatementImpl *>(statement)->handle();
int error = sqlite3_step(stmt);
if (SQLITE_DONE == error)
{
statement->setDone();
return false;
}
if (SQLITE_ROW == error)
{
int columnCount = sqlite3_data_count(stmt);
for (int i = 0; i < columnCount; ++i)
{
String name = sqlite3_column_name(stmt, i);
auto field = storable->record()->metaObject()->fieldByName(name, false);
if (!field)
{
std::cerr << "Cannot bind sql result to an object field " << name << std::endl;
continue;
}
int sqliteType = sqlite3_column_type(stmt, i);
switch (field->type())
{
case eFieldBool:
assignField<bool>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int(stmt, i) != 0);
break;
case eFieldInt:
assignField<int32_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int(stmt, i));
break;
case eFieldEnum:
case eFieldUint:
assignField<uint32_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), (uint32_t)sqlite3_column_int64(stmt, i));
break;
case eFieldUint64:
assignField<uint64_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int64(stmt, i));
break;
case eFieldInt64:
assignField<int64_t>(field, sqliteType, SQLITE_INTEGER, storable->record(), sqlite3_column_int64(stmt, i));
break;
case eFieldFloat:
assignField<float>(field, sqliteType, SQLITE_FLOAT, storable->record(), (float)sqlite3_column_double(stmt, i));
break;
case eFieldDouble:
assignField<double>(field, sqliteType, SQLITE_FLOAT, storable->record(), sqlite3_column_double(stmt, i));
break;
case eFieldString:
assignField<String>(field, sqliteType, SQLITE_TEXT, storable->record(), (const char *)sqlite3_column_text(stmt, i));
break;
case eFieldDateTime:
assignField<DateTime>(field, sqliteType, SQLITE_TEXT, storable->record(),
DateTime::fromString((const char *)sqlite3_column_text(stmt, i)));
break;
case eFieldObject:
case eFieldArray:
throw std::runtime_error("Cannot handle non-plain objects");
default:
throw std::runtime_error("Unknown field type");
}
}
return true;
}
throw std::runtime_error(std::string("sqlite3_step(): ") + sqlite3_errmsg(m_dbHandle));
}
bool SqliteTransactionImpl::getLastInsertId(SqlStatementImpl *statement, SqlStorable *storable)
{
(void)statement;
auto pkey = storable->primaryKey();
if (pkey)
{
switch (storable->primaryKey()->type())
{
case eFieldInt:
assignField<int32_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
(int32_t)sqlite3_last_insert_rowid(m_dbHandle));
return true;
case eFieldUint:
assignField<uint32_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
(uint32_t)sqlite3_last_insert_rowid(m_dbHandle));
return true;
case eFieldInt64:
assignField<int64_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
sqlite3_last_insert_rowid(m_dbHandle));
return true;
case eFieldUint64:
assignField<uint64_t>(pkey, SQLITE_INTEGER, SQLITE_INTEGER, storable->record(),
sqlite3_last_insert_rowid(m_dbHandle));
return true;
default:
return false;
}
}
return false;
}
bool SqliteTransactionImpl::closeStatement(SqlStatementImpl *statement)
{
std::lock_guard<std::mutex> _guard(m_statementsMutex);
SqliteStatementImpl *sqliteStatement = reinterpret_cast<SqliteStatementImpl *>(statement);
auto it = std::find(m_statements.begin(), m_statements.end(), sqliteStatement);
if (it == m_statements.end())
{
std::cerr << "SqliteTransactionImpl::closeStatement(): there's no such statement" << std::endl;
return false;
}
m_statements.erase(it);
delete sqliteStatement;
return true;
}
} // namespace sqlite
} // namespace connectors
} // namespace sql
} // namespace db
} // namespace metacpp
<|endoftext|>
|
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "arrow/util/parsing.h"
#include "arrow/util/double_conversion.h"
namespace arrow {
namespace internal {
struct StringToFloatConverter::Impl {
Impl()
: main_converter_(flags_, main_junk_value_, main_junk_value_, "inf", "nan"),
fallback_converter_(flags_, fallback_junk_value_, fallback_junk_value_, "inf",
"nan") {}
// NOTE: This is only supported in double-conversion 3.1+
static constexpr int flags_ =
util::double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSIBILITY;
// Two unlikely values to signal a parsing error
static constexpr double main_junk_value_ = 0.7066424364107089;
static constexpr double fallback_junk_value_ = 0.40088499148279166;
util::double_conversion::StringToDoubleConverter main_converter_;
util::double_conversion::StringToDoubleConverter fallback_converter_;
};
StringToFloatConverter::StringToFloatConverter() : impl_(new Impl()) {}
StringToFloatConverter::~StringToFloatConverter() {}
bool StringToFloatConverter::StringToFloat(const char* s, size_t length, float* out) {
int processed_length;
float v;
v = impl_->main_converter_.StringToFloat(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == static_cast<float>(impl_->main_junk_value_))) {
v = impl_->fallback_converter_.StringToFloat(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == static_cast<float>(impl_->fallback_junk_value_))) {
return false;
}
}
*out = v;
return true;
}
bool StringToFloatConverter::StringToFloat(const char* s, size_t length, double* out) {
int processed_length;
double v;
v = impl_->main_converter_.StringToDouble(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == impl_->main_junk_value_)) {
v = impl_->fallback_converter_.StringToDouble(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == impl_->fallback_junk_value_)) {
return false;
}
}
*out = v;
return true;
}
} // namespace internal
} // namespace arrow
<commit_msg>ARROW-7250: [C++] Define constexpr symbols explicitly in StringToFloatConverter::Impl<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 "arrow/util/parsing.h"
#include "arrow/util/double_conversion.h"
namespace arrow {
namespace internal {
struct StringToFloatConverter::Impl {
Impl()
: main_converter_(flags_, main_junk_value_, main_junk_value_, "inf", "nan"),
fallback_converter_(flags_, fallback_junk_value_, fallback_junk_value_, "inf",
"nan") {}
// NOTE: This is only supported in double-conversion 3.1+
static constexpr int flags_ =
util::double_conversion::StringToDoubleConverter::ALLOW_CASE_INSENSIBILITY;
// Two unlikely values to signal a parsing error
static constexpr double main_junk_value_ = 0.7066424364107089;
static constexpr double fallback_junk_value_ = 0.40088499148279166;
util::double_conversion::StringToDoubleConverter main_converter_;
util::double_conversion::StringToDoubleConverter fallback_converter_;
};
constexpr int StringToFloatConverter::Impl::flags_;
constexpr double StringToFloatConverter::Impl::main_junk_value_;
constexpr double StringToFloatConverter::Impl::fallback_junk_value_;
StringToFloatConverter::StringToFloatConverter() : impl_(new Impl()) {}
StringToFloatConverter::~StringToFloatConverter() {}
bool StringToFloatConverter::StringToFloat(const char* s, size_t length, float* out) {
int processed_length;
float v;
v = impl_->main_converter_.StringToFloat(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == static_cast<float>(impl_->main_junk_value_))) {
v = impl_->fallback_converter_.StringToFloat(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == static_cast<float>(impl_->fallback_junk_value_))) {
return false;
}
}
*out = v;
return true;
}
bool StringToFloatConverter::StringToFloat(const char* s, size_t length, double* out) {
int processed_length;
double v;
v = impl_->main_converter_.StringToDouble(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == impl_->main_junk_value_)) {
v = impl_->fallback_converter_.StringToDouble(s, static_cast<int>(length),
&processed_length);
if (ARROW_PREDICT_FALSE(v == impl_->fallback_junk_value_)) {
return false;
}
}
*out = v;
return true;
}
} // namespace internal
} // namespace arrow
<|endoftext|>
|
<commit_before>/*
* Copyright (c) [2004-2015] Novell, Inc.
* Copyright (c) [2016-2017] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <fstream>
#include "storage/Utils/AppUtil.h"
#include "storage/Utils/Mockup.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/SystemInfo/CmdParted.h"
#include "storage/Utils/Enum.h"
#include "storage/Devices/PartitionImpl.h"
#include "storage/Utils/StorageTypes.h"
#include "storage/Devices/PartitionTableImpl.h"
namespace storage
{
using namespace std;
Parted::Parted(const string& device)
: device(device), label(PtType::UNKNOWN), region(), implicit(false),
gpt_enlarge(false), gpt_pmbr_boot(false), logical_sector_size(0), physical_sector_size(0)
{
SystemCmd cmd(PARTEDBIN " --script --machine " + quote(device) + " unit s print",
SystemCmd::DoThrow);
// No check for exit status since parted 3.1 exits with 1 if no
// partition table is found.
if ( !cmd.stderr().empty() )
{
this->stderr = cmd.stderr(); // Save stderr output
if ( boost::starts_with( cmd.stderr().front(), "Error: Could not stat device" ) )
ST_THROW( SystemCmdException( &cmd, "parted complains: " + cmd.stderr().front() ) );
else
{
// Intentionally NOT throwing an exception here for just any kind
// of stderr output because it's quite common for the parted
// command to write messages to stderr in certain situations that
// may not necessarily be fatal.
//
// See also bsc#938572, bsc#938561
for ( const string& line: stderr )
{
y2war( "parted stderr> " + line );
}
}
}
parse(cmd.stdout(), cmd.stderr());
}
void
Parted::parse(const vector<string>& stdout, const vector<string>& stderr)
{
implicit = false;
gpt_enlarge = false;
gpt_fix_backup = false;
gpt_pmbr_boot = false;
entries.clear();
if (stdout.size() < 2)
ST_THROW(Exception("wrong number of lines"));
if (stdout[0] != "BYT;")
ST_THROW(ParseException("Bad first line", stdout[0], "BYT;"));
scan_device_line(stdout[1]);
if (label != PtType::UNKNOWN && label != PtType::LOOP)
{
for (size_t i = 2; i < stdout.size(); ++i)
scan_entry_line(stdout[i]);
}
scan_stderr(stderr);
fix_dasd_sector_size();
y2mil(*this);
}
void
Parted::scan_device_line(const string& line)
{
if (!boost::ends_with(line, ";"))
ST_THROW(ParseException("missing semicolon", "", ";"));
string line_without_semicolon = line.substr(0, line.size() - 1);
vector<string> tmp;
boost::split(tmp, line_without_semicolon, boost::is_any_of(":"));
unsigned long long num_sectors = 0;
tmp[1] >> num_sectors;
region.set_length(num_sectors);
tmp[3] >> logical_sector_size;
tmp[4] >> physical_sector_size;
region.set_block_size(logical_sector_size);
label = scan_partition_table_type(tmp[5]);
scan_device_flags(tmp[7]);
}
void
Parted::scan_device_flags(const string& s)
{
implicit = boost::contains(s, "implicit_partition_table");
gpt_pmbr_boot = boost::contains(s, "pmbr_boot");
}
PtType
Parted::scan_partition_table_type(const string& s) const
{
PtType partition_type = PtType::UNKNOWN;
if (s == "msdos")
partition_type = PtType::MSDOS;
else if (s == "gpt" || s == "gpt_sync_mbr")
partition_type = PtType::GPT;
else if (s == "dasd")
partition_type = PtType::DASD;
else if (s == "loop")
partition_type = PtType::LOOP;
else if (s == "unknown")
partition_type = PtType::UNKNOWN;
else
ST_THROW(Exception("unknown partition table type reported by parted"));
return partition_type;
}
void
Parted::scan_entry_line(const string& line)
{
if (!boost::ends_with(line, ";"))
ST_THROW(ParseException("missing semicolon", "", ";"));
string line_without_semicolon = line.substr(0, line.size() - 1);
vector<string> tmp;
boost::split(tmp, line_without_semicolon, boost::is_any_of(":"));
Entry entry;
tmp[0] >> entry.number;
if (entry.number == 0)
ST_THROW(ParseException("Illegal partition number 0", line, ""));
unsigned long long start_sector = 0;
unsigned long long size_sector = 0;
tmp[1] >> start_sector;
tmp[3] >> size_sector;
entry.region = Region(start_sector, size_sector, region.get_block_size());
scan_entry_flags(tmp[6], entry);
entries.push_back(entry);
}
void
Parted::scan_entry_flags(const string& s, Entry& entry) const
{
entry.type = PartitionType::PRIMARY;
// TODO parted has a strange interface to represent partition type
// ids. On GPT it is not possible to distinguish whether the id is
// linux or unknown. Work with upsteam parted to improve the
// interface. The line below should then be entry.id = ID_UNKNOWN
entry.id = ID_LINUX;
entry.boot = false;
entry.legacy_boot = false;
vector<string> flags;
boost::split(flags, s, boost::is_any_of(", "), boost::token_compress_on);
if (contains(flags, "raid"))
entry.id = ID_RAID;
else if (contains(flags, "lvm"))
entry.id = ID_LVM;
else if (contains(flags, "prep"))
entry.id = ID_PREP;
else if (contains(flags, "esp"))
entry.id = ID_ESP;
else if (contains(flags, "swap"))
entry.id = ID_SWAP;
else if (contains(flags, "bios_grub"))
entry.id = ID_BIOS_BOOT;
else if (contains(flags, "msftdata"))
entry.id = ID_WINDOWS_BASIC_DATA;
else if (contains(flags, "msftres"))
entry.id = ID_MICROSOFT_RESERVED;
else if (contains(flags, "diag"))
entry.id = ID_DIAG;
if (label == PtType::MSDOS)
{
entry.boot = contains(flags, "boot");
vector<string>::const_iterator it1 = find_if(flags.begin(), flags.end(),
string_starts_with("type="));
if (it1 != flags.end())
{
string val = string(*it1, 5);
int id = 0;
std::istringstream data(val);
classic(data);
data >> std::hex >> id;
if (id > 0)
entry.id = id;
}
if (entry.number > 4)
entry.type = PartitionType::LOGICAL;
else if (contains(vector<unsigned int>({ 0x05, 0x0f, 0x1f }), entry.id))
entry.type = PartitionType::EXTENDED;
}
if (label == PtType::GPT)
{
entry.legacy_boot = contains(flags, "legacy_boot");
}
}
void
Parted::scan_stderr(const vector<string>& stderr)
{
gpt_enlarge = find_if(stderr, string_contains("fix the GPT to use all")) != stderr.end();
gpt_fix_backup = find_if(stderr, string_contains("backup GPT table is corrupt, but the "
"primary appears OK")) != stderr.end();
}
void
Parted::fix_dasd_sector_size()
{
if (label == PtType::DASD && logical_sector_size == 512 && physical_sector_size == 4096)
{
y2mil("fixing sector size reported by parted");
region.set_length(region.get_length() / 8);
region.set_block_size(region.get_block_size() * 8);
for (Entry& entry : entries)
{
Region& region = entry.region;
region.set_start(region.get_start() / 8);
region.set_length(region.get_length() / 8);
region.set_block_size(region.get_block_size() * 8);
}
}
}
bool
Parted::get_entry(unsigned number, Entry& entry) const
{
for (const_iterator it = entries.begin(); it != entries.end(); ++it)
{
if (it->number == number)
{
entry = *it;
return true;
}
}
return false;
}
std::ostream&
operator<<(std::ostream& s, const Parted& parted)
{
s << "device:" << parted.device << " label:" << toString(parted.label)
<< " region:" << parted.region;
if (parted.implicit)
s << " implicit";
if (parted.gpt_enlarge)
s << " gpt-enlarge";
if (parted.gpt_fix_backup)
s << " gpt-fix-backup";
if (parted.gpt_pmbr_boot)
s << " gpt-pmbr-boot";
s << '\n';
for (const Parted::Entry& entry : parted.entries)
s << entry << '\n';
return s;
}
std::ostream&
operator<<(std::ostream& s, const Parted::Entry& entry)
{
s << "number:" << entry.number << " region:" << entry.region << " type:"
<< toString(entry.type) << " id:" << sformat("0x%02X", entry.id);
if (entry.boot)
s << " boot";
if (entry.legacy_boot)
s << " legacy-boot";
return s;
}
}
<commit_msg>- coding style<commit_after>/*
* Copyright (c) [2004-2015] Novell, Inc.
* Copyright (c) [2016-2017] SUSE LLC
*
* All Rights Reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, contact Novell, Inc.
*
* To contact Novell about this file by physical or electronic mail, you may
* find current contact information at www.novell.com.
*/
#include <fstream>
#include "storage/Utils/AppUtil.h"
#include "storage/Utils/Mockup.h"
#include "storage/Utils/SystemCmd.h"
#include "storage/Utils/StorageDefines.h"
#include "storage/SystemInfo/CmdParted.h"
#include "storage/Utils/Enum.h"
#include "storage/Devices/PartitionImpl.h"
#include "storage/Utils/StorageTypes.h"
#include "storage/Devices/PartitionTableImpl.h"
namespace storage
{
using namespace std;
Parted::Parted(const string& device)
: device(device), label(PtType::UNKNOWN), region(), implicit(false),
gpt_enlarge(false), gpt_pmbr_boot(false), logical_sector_size(0), physical_sector_size(0)
{
SystemCmd cmd(PARTEDBIN " --script --machine " + quote(device) + " unit s print",
SystemCmd::DoThrow);
// No check for exit status since parted 3.1 exits with 1 if no
// partition table is found.
if ( !cmd.stderr().empty() )
{
this->stderr = cmd.stderr(); // Save stderr output
if ( boost::starts_with( cmd.stderr().front(), "Error: Could not stat device" ) )
ST_THROW( SystemCmdException( &cmd, "parted complains: " + cmd.stderr().front() ) );
else
{
// Intentionally NOT throwing an exception here for just any kind
// of stderr output because it's quite common for the parted
// command to write messages to stderr in certain situations that
// may not necessarily be fatal.
//
// See also bsc#938572, bsc#938561
for ( const string& line: stderr )
{
y2war( "parted stderr> " + line );
}
}
}
parse(cmd.stdout(), cmd.stderr());
}
void
Parted::parse(const vector<string>& stdout, const vector<string>& stderr)
{
implicit = false;
gpt_enlarge = false;
gpt_fix_backup = false;
gpt_pmbr_boot = false;
entries.clear();
if (stdout.size() < 2)
ST_THROW(Exception("wrong number of lines"));
if (stdout[0] != "BYT;")
ST_THROW(ParseException("Bad first line", stdout[0], "BYT;"));
scan_device_line(stdout[1]);
if (label != PtType::UNKNOWN && label != PtType::LOOP)
{
for (size_t i = 2; i < stdout.size(); ++i)
scan_entry_line(stdout[i]);
}
scan_stderr(stderr);
fix_dasd_sector_size();
y2mil(*this);
}
void
Parted::scan_device_line(const string& line)
{
if (!boost::ends_with(line, ";"))
ST_THROW(ParseException("missing semicolon", "", ";"));
string line_without_semicolon = line.substr(0, line.size() - 1);
vector<string> tmp;
boost::split(tmp, line_without_semicolon, boost::is_any_of(":"));
unsigned long long num_sectors = 0;
tmp[1] >> num_sectors;
region.set_length(num_sectors);
tmp[3] >> logical_sector_size;
tmp[4] >> physical_sector_size;
region.set_block_size(logical_sector_size);
label = scan_partition_table_type(tmp[5]);
scan_device_flags(tmp[7]);
}
void
Parted::scan_device_flags(const string& s)
{
implicit = boost::contains(s, "implicit_partition_table");
gpt_pmbr_boot = boost::contains(s, "pmbr_boot");
}
PtType
Parted::scan_partition_table_type(const string& s) const
{
PtType partition_type = PtType::UNKNOWN;
if (s == "msdos")
partition_type = PtType::MSDOS;
else if (s == "gpt" || s == "gpt_sync_mbr")
partition_type = PtType::GPT;
else if (s == "dasd")
partition_type = PtType::DASD;
else if (s == "loop")
partition_type = PtType::LOOP;
else if (s == "unknown")
partition_type = PtType::UNKNOWN;
else
ST_THROW(Exception("unknown partition table type reported by parted"));
return partition_type;
}
void
Parted::scan_entry_line(const string& line)
{
if (!boost::ends_with(line, ";"))
ST_THROW(ParseException("missing semicolon", "", ";"));
string line_without_semicolon = line.substr(0, line.size() - 1);
vector<string> tmp;
boost::split(tmp, line_without_semicolon, boost::is_any_of(":"));
Entry entry;
tmp[0] >> entry.number;
if (entry.number == 0)
ST_THROW(ParseException("Illegal partition number 0", line, ""));
unsigned long long start_sector = 0;
unsigned long long size_sector = 0;
tmp[1] >> start_sector;
tmp[3] >> size_sector;
entry.region = Region(start_sector, size_sector, region.get_block_size());
scan_entry_flags(tmp[6], entry);
entries.push_back(entry);
}
void
Parted::scan_entry_flags(const string& s, Entry& entry) const
{
entry.type = PartitionType::PRIMARY;
// TODO parted has a strange interface to represent partition type
// ids. On GPT it is not possible to distinguish whether the id is
// linux or unknown. Work with upsteam parted to improve the
// interface. The line below should then be entry.id = ID_UNKNOWN
entry.id = ID_LINUX;
entry.boot = false;
entry.legacy_boot = false;
vector<string> flags;
boost::split(flags, s, boost::is_any_of(", "), boost::token_compress_on);
if (contains(flags, "raid"))
entry.id = ID_RAID;
else if (contains(flags, "lvm"))
entry.id = ID_LVM;
else if (contains(flags, "prep"))
entry.id = ID_PREP;
else if (contains(flags, "esp"))
entry.id = ID_ESP;
else if (contains(flags, "swap"))
entry.id = ID_SWAP;
else if (contains(flags, "bios_grub"))
entry.id = ID_BIOS_BOOT;
else if (contains(flags, "msftdata"))
entry.id = ID_WINDOWS_BASIC_DATA;
else if (contains(flags, "msftres"))
entry.id = ID_MICROSOFT_RESERVED;
else if (contains(flags, "diag"))
entry.id = ID_DIAG;
if (label == PtType::MSDOS)
{
entry.boot = contains(flags, "boot");
vector<string>::const_iterator it1 = find_if(flags.begin(), flags.end(),
string_starts_with("type="));
if (it1 != flags.end())
{
string val = string(*it1, 5);
int id = 0;
std::istringstream data(val);
classic(data);
data >> std::hex >> id;
if (id > 0)
entry.id = id;
}
if (entry.number > 4)
entry.type = PartitionType::LOGICAL;
else if (contains(vector<unsigned int>({ 0x05, 0x0f, 0x1f }), entry.id))
entry.type = PartitionType::EXTENDED;
}
if (label == PtType::GPT)
{
entry.legacy_boot = contains(flags, "legacy_boot");
}
}
void
Parted::scan_stderr(const vector<string>& stderr)
{
gpt_enlarge = find_if(stderr, string_contains("fix the GPT to use all")) != stderr.end();
gpt_fix_backup = find_if(stderr, string_contains("backup GPT table is corrupt, but the "
"primary appears OK")) != stderr.end();
}
void
Parted::fix_dasd_sector_size()
{
if (label == PtType::DASD && logical_sector_size == 512 && physical_sector_size == 4096)
{
y2mil("fixing sector size reported by parted");
region.set_length(region.get_length() / 8);
region.set_block_size(region.get_block_size() * 8);
for (Entry& entry : entries)
{
Region& region = entry.region;
region.set_start(region.get_start() / 8);
region.set_length(region.get_length() / 8);
region.set_block_size(region.get_block_size() * 8);
}
}
}
bool
Parted::get_entry(unsigned number, Entry& entry) const
{
for (const_iterator it = entries.begin(); it != entries.end(); ++it)
{
if (it->number == number)
{
entry = *it;
return true;
}
}
return false;
}
std::ostream&
operator<<(std::ostream& s, const Parted& parted)
{
s << "device:" << parted.device << " label:" << toString(parted.label)
<< " region:" << parted.region;
if (parted.implicit)
s << " implicit";
if (parted.gpt_enlarge)
s << " gpt-enlarge";
if (parted.gpt_fix_backup)
s << " gpt-fix-backup";
if (parted.gpt_pmbr_boot)
s << " gpt-pmbr-boot";
s << '\n';
for (const Parted::Entry& entry : parted.entries)
s << entry << '\n';
return s;
}
std::ostream&
operator<<(std::ostream& s, const Parted::Entry& entry)
{
s << "number:" << entry.number << " region:" << entry.region << " type:"
<< toString(entry.type) << " id:" << sformat("0x%02X", entry.id);
if (entry.boot)
s << " boot";
if (entry.legacy_boot)
s << " legacy-boot";
return s;
}
}
<|endoftext|>
|
<commit_before>#include "testsettings.hpp"
#ifdef TEST_BASIC_UTILS
#include <tightdb/util/shared_ptr.hpp>
#include <tightdb/util/file.hpp>
#include <tightdb/alloc_slab.hpp>
#include "test.hpp"
using namespace std;
using namespace tightdb;
using namespace tightdb::util;
namespace {
struct Foo {
void func() {}
void modify() { c = 123; }
char c;
};
}
TEST(Utils_SharedPtr)
{
const SharedPtr<Foo> foo1 = new Foo();
Foo* foo2 = foo1.get();
static_cast<void>(foo2);
const SharedPtr<Foo> foo3 = new Foo();
foo3->modify();
SharedPtr<Foo> foo4 = new Foo();
foo4->modify();
SharedPtr<const int> a = new int(1);
const int* b = a.get();
CHECK_EQUAL(1, *b);
const SharedPtr<const int> c = new int(2);
const int* const d = c.get();
CHECK_EQUAL(2, *d);
const SharedPtr<int> e = new int(3);
const int* f = e.get();
static_cast<void>(f);
CHECK_EQUAL(3, *e);
*e = 123;
SharedPtr<int> g = new int(4);
int* h = g.get();
static_cast<void>(h);
CHECK_EQUAL(4, *g);
*g = 123;
}
#endif
<commit_msg>lr_sharedptr: Linux line breaks<commit_after>#include "testsettings.hpp"
#ifdef TEST_BASIC_UTILS
#include <tightdb/util/shared_ptr.hpp>
#include <tightdb/util/file.hpp>
#include <tightdb/alloc_slab.hpp>
#include "test.hpp"
using namespace std;
using namespace tightdb;
using namespace tightdb::util;
namespace {
struct Foo {
void func() {}
void modify() { c = 123; }
char c;
};
}
TEST(Utils_SharedPtr)
{
const SharedPtr<Foo> foo1 = new Foo();
Foo* foo2 = foo1.get();
static_cast<void>(foo2);
const SharedPtr<Foo> foo3 = new Foo();
foo3->modify();
SharedPtr<Foo> foo4 = new Foo();
foo4->modify();
SharedPtr<const int> a = new int(1);
const int* b = a.get();
CHECK_EQUAL(1, *b);
const SharedPtr<const int> c = new int(2);
const int* const d = c.get();
CHECK_EQUAL(2, *d);
const SharedPtr<int> e = new int(3);
const int* f = e.get();
static_cast<void>(f);
CHECK_EQUAL(3, *e);
*e = 123;
SharedPtr<int> g = new int(4);
int* h = g.get();
static_cast<void>(h);
CHECK_EQUAL(4, *g);
*g = 123;
}
#endif
<|endoftext|>
|
<commit_before>//
// test_http_client.cpp
// fibio
//
// Created by Chen Xu on 14-3-12.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#include <iostream>
#include <vector>
#include <chrono>
#include <sstream>
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <fibio/fiber.hpp>
#include <fibio/fiberize.hpp>
#include <fibio/http/client/client.hpp>
#include <fibio/http/server/server.hpp>
#include <fibio/http/server/routing.hpp>
using namespace fibio;
using namespace fibio::http;
using namespace fibio::http::common;
void the_client() {
client c;
client::request req;
req.url="/";
// Default method
assert(req.method==http_method::INVALID);
req.method=http_method::GET;
// Default version
assert(req.version==http_version::INVALID);
req.version=http_version::HTTP_1_1;
assert(req.get_content_length()==0);
req.keep_alive=true;
std::string req_body("hello");
req.body_stream() << req_body;
if(c.connect("127.0.0.1", 23456)) {
assert(false);
}
for(int i=0; i<10; i++) {
client::response resp;
if(c.send_request(req, resp)) {
// This server returns a 200 response
assert(resp.status_code==http_status_code::OK);
assert(resp.status_message=="OK");
assert(resp.version==http_version::HTTP_1_1);
size_t cl=resp.content_length;
std::string s;
std::stringstream ss;
ss << resp.body_stream().rdbuf();
s=ss.str();
assert(s.size()==cl);
// Make sure we triggered eof
resp.body_stream().peek();
assert(resp.body_stream().eof());
} else {
assert(false);
}
}
}
struct path_is {
bool operator()(const std::string &s, match_info &p) const {
return s==path_;
}
std::string path_;
};
bool handler(match_info &mi, server::request &req, server::response &resp, server::connection &c) {
// Write all headers back in a table
resp.set_content_type("text/html");
resp.body_stream() << "<HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>"<< std::endl;
resp.body_stream() << "<H1>Request Info</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
resp.body_stream() << "<TR><TD>URL</TD><TD>" << req.url << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Schema</TD><TD>" << req.parsed_url.schema << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Port</TD><TD>" << req.parsed_url.port << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Path</TD><TD>" << req.parsed_url.path << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Query</TD><TD>" << req.parsed_url.query << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>User Info</TD><TD>" << req.parsed_url.userinfo << "</TD></TR>" << std::endl;
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "<H1>Headers</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
for(auto &p: req.headers) {
resp.body_stream() << "<TR><TD>" << p.first << "</TD><TD>" << p.second << "</TD></TR>" <<std::endl;
}
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "<H1>Parameters</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
for(auto &p: mi) {
resp.body_stream() << "<TR><TD>" << p.first << "</TD><TD>" << p.second << "</TD></TR>" <<std::endl;
}
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "<H1>Query</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
for(auto &p: req.parsed_url.query_params) {
resp.body_stream() << "<TR><TD>" << p.first << "</TD><TD>" << p.second << "</TD></TR>" <<std::endl;
}
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "</BODY></HTML>" << std::endl;
return true;
}
bool handler_404(server::request &req, server::response &resp, server::connection &c) {
resp.status_code=http_status_code::NOT_FOUND;
resp.keep_alive=false;
return true;
}
bool handler_400(match_info &, server::request &req, server::response &resp, server::connection &c) {
resp.status_code=http_status_code::BAD_REQUEST;
resp.keep_alive=false;
return true;
}
int fibio::main(int argc, char *argv[]) {
scheduler::get_instance().add_worker_thread(3);
server svr(server::settings{"127.0.0.1",
23456,
routing_table(routing_table_type{
{url_(starts_with{"/"}), handler},
{path_match("/")
|| path_match("/index.html")
|| path_match("/index.htm"), handler},
{path_match("/test1/:id/test2"), handler},
{path_match("/test2/*p") && method_is(http_method::POST), handler},
{path_match("/test3/*"), handler},
{!method_is(http_method::GET), stock_handler{http_status_code::BAD_REQUEST}}
}, stock_handler{http_status_code::NOT_FOUND})
});
svr.start();
{
// Create some clients, do some requests
fiber_group fibers;
size_t n=10;
for (int i=0; i<n; i++) {
//fibers.create_fiber(the_client);
}
fibers.join_all();
}
//svr.stop();
svr.join();
std::cout << "main_fiber exiting" << std::endl;
return 0;
}
<commit_msg>Clean up test code<commit_after>//
// test_http_client.cpp
// fibio
//
// Created by Chen Xu on 14-3-12.
// Copyright (c) 2014 0d0a.com. All rights reserved.
//
#include <iostream>
#include <vector>
#include <chrono>
#include <sstream>
#include <boost/asio/basic_waitable_timer.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <fibio/fiber.hpp>
#include <fibio/fiberize.hpp>
#include <fibio/http/client/client.hpp>
#include <fibio/http/server/server.hpp>
#include <fibio/http/server/routing.hpp>
using namespace fibio;
using namespace fibio::http;
using namespace fibio::http::common;
void the_client() {
client c;
if(c.connect("127.0.0.1", 23456)) {
assert(false);
}
client::request req;
client::response resp;
{
//std::cout << "GET /" << std::endl;
req.clear();
resp.clear();
req.url="/";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
assert(resp.status_message=="OK");
assert(resp.version==http_version::HTTP_1_1);
}
{
//std::cout << "GET /index.html" << std::endl;
req.clear();
resp.clear();
req.url="/index.html";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
}
{
//std::cout << "GET /index.htm" << std::endl;
req.clear();
resp.clear();
req.url="/index.htm";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
}
{
//std::cout << "GET /index.php" << std::endl;
req.clear();
resp.clear();
req.url="/index.php";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::NOT_FOUND);
}
{
//std::cout << "GET /test1/123/test2" << std::endl;
req.clear();
resp.clear();
req.url="/test1/123/test2";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
}
{
//std::cout << "GET /test1/123" << std::endl;
req.clear();
resp.clear();
req.url="/test1/123";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::NOT_FOUND);
}
{
//std::cout << "POST /test1/123/test2" << std::endl;
req.clear();
resp.clear();
req.url="/test1/123/test2";
req.method=http_method::POST;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::BAD_REQUEST);
}
{
//std::cout << "POST /test2/123" << std::endl;
req.clear();
resp.clear();
req.url="/test2/123";
req.method=http_method::POST;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
}
{
//std::cout << "POST /test2/123/abc/xyz" << std::endl;
req.clear();
resp.clear();
req.url="/test2/123/abc/xyz";
req.method=http_method::POST;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
}
{
//std::cout << "GET /test2/123" << std::endl;
req.clear();
resp.clear();
req.url="/test2/123";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::NOT_FOUND);
}
{
//std::cout << "GET /test3/with/a/long/and/stupid/url" << std::endl;
req.clear();
resp.clear();
req.url="/test3/with/a/long/and/stupid/url";
req.method=http_method::GET;
req.version=http_version::HTTP_1_1;
req.keep_alive=true;
bool ret=c.send_request(req, resp);
assert(ret);
assert(resp.status_code==http_status_code::OK);
}
}
bool handler(match_info &mi, server::request &req, server::response &resp, server::connection &c) {
resp.headers.insert({"Header1", "Value1"});
// Write all headers back in a table
resp.set_content_type("text/html");
resp.body_stream() << "<HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>"<< std::endl;
resp.body_stream() << "<H1>Request Info</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
resp.body_stream() << "<TR><TD>URL</TD><TD>" << req.url << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Schema</TD><TD>" << req.parsed_url.schema << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Port</TD><TD>" << req.parsed_url.port << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Path</TD><TD>" << req.parsed_url.path << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>Query</TD><TD>" << req.parsed_url.query << "</TD></TR>" << std::endl;
resp.body_stream() << "<TR><TD>User Info</TD><TD>" << req.parsed_url.userinfo << "</TD></TR>" << std::endl;
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "<H1>Headers</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
for(auto &p: req.headers) {
resp.body_stream() << "<TR><TD>" << p.first << "</TD><TD>" << p.second << "</TD></TR>" <<std::endl;
}
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "<H1>Parameters</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
for(auto &p: mi) {
resp.body_stream() << "<TR><TD>" << p.first << "</TD><TD>" << p.second << "</TD></TR>" <<std::endl;
}
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "<H1>Query</H1>" << std::endl;
resp.body_stream() << "<TABLE>" << std::endl;
for(auto &p: req.parsed_url.query_params) {
resp.body_stream() << "<TR><TD>" << p.first << "</TD><TD>" << p.second << "</TD></TR>" <<std::endl;
}
resp.body_stream() << "</TABLE>" << std::endl;
resp.body_stream() << "</BODY></HTML>" << std::endl;
return true;
}
int fibio::main(int argc, char *argv[]) {
scheduler::get_instance().add_worker_thread(3);
server svr(server::settings{"127.0.0.1",
23456,
routing_table(routing_table_type{
{path_match("/")
|| path_match("/index.html")
|| path_match("/index.htm"), handler},
{path_match("/test1/:id/test2") && method_is(http_method::GET), handler},
{path_match("/test2/*p") && method_is(http_method::POST), handler},
{path_match("/test3/*"), handler},
{!method_is(http_method::GET), stock_handler{http_status_code::BAD_REQUEST}}
}, stock_handler{http_status_code::NOT_FOUND})
});
svr.start();
{
// Create some clients, do some requests
fiber_group fibers;
size_t n=10;
for (int i=0; i<n; i++) {
fibers.create_fiber(the_client);
}
fibers.join_all();
}
svr.stop();
svr.join();
std::cout << "main_fiber exiting" << std::endl;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
* Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#include <camera/camera.h>
#include <camera/camera_extrinsics.h>
#include <camera/camera_intrinsics.h>
#include <matching/feature_matcher_options.h>
#include <matching/naive_matcher_2d3d.h>
#include <geometry/point_3d.h>
#include <geometry/rotation.h>
#include <matching/feature.h>
#include <math/random_generator.h>
#include <sfm/view.h>
#include <slam/landmark.h>
#include <slam/observation.h>
#include <ransac/pnp_ransac_problem.h>
#include <ransac/ransac.h>
#include <gtest/gtest.h>
#include <gflags/gflags.h>
DEFINE_double(noise_stddev, 0.0,
"Additive Gaussian noise on feature coordinates.");
namespace bsfm {
using Eigen::Matrix3d;
using Eigen::Vector3d;
;
namespace {
// Minimum number of points to constrain the problem. See H&Z pg. 179.
const int kNumLandmarks = 100;
const int kImageWidth = 1920;
const int kImageHeight = 1080;
const double kVerticalFov = D2R(90.0);
// Bounding volume for 3D points.
const double kMinX = -2.0;
const double kMinY = -2.0;
const double kMinZ = -2.0;
const double kMaxX = 2.0;
const double kMaxY = 2.0;
const double kMaxZ = 2.0;
const unsigned int kDescriptorLength = 64;
// Makes a default set of camera intrinsic parameters.
CameraIntrinsics DefaultIntrinsics() {
CameraIntrinsics intrinsics;
intrinsics.SetImageLeft(0);
intrinsics.SetImageTop(0);
intrinsics.SetImageWidth(kImageWidth);
intrinsics.SetImageHeight(kImageHeight);
intrinsics.SetVerticalFOV(kVerticalFov);
intrinsics.SetFU(intrinsics.f_v());
intrinsics.SetCU(0.5 * kImageWidth);
intrinsics.SetCV(0.5 * kImageHeight);
return intrinsics;
}
// Makes a random 3D point.
Point3D RandomPoint() {
CHECK(kMinX <= kMaxX);
CHECK(kMinY <= kMaxY);
CHECK(kMinZ <= kMaxZ);
static math::RandomGenerator rng(0);
const double x = rng.DoubleUniform(kMinX, kMaxX);
const double y = rng.DoubleUniform(kMinY, kMaxY);
const double z = rng.DoubleUniform(kMinZ, kMaxZ);
return Point3D(x, y, z);
}
// Creates one observation for each landmark in the scene, and adds them to the
// view. Also creates 'num_bad_matches' bad observations (of random 3D points).
// Returns indices of landmarks that were successfully projected.
std::vector<LandmarkIndex> CreateObservations(
const std::vector<LandmarkIndex>& landmark_indices,
ViewIndex view_index,
unsigned int num_bad_matches,
double noise_stddev = 0.0) {
View::Ptr view = View::GetView(view_index);
CHECK_NOTNULL(view.get());
// For each landmark that projects into the view, create an observation and
// add it to the view.
std::vector<LandmarkIndex> projected_landmarks;
static math::RandomGenerator rng(0);
for (const auto& landmark_index : landmark_indices) {
Landmark::Ptr landmark = Landmark::GetLandmark(landmark_index);
CHECK_NOTNULL(landmark.get());
double u = 0.0, v = 0.0;
const Point3D point = landmark->Position();
if (!view->Camera().WorldToImage(point.X(), point.Y(), point.Z(), &u, &v))
continue;
// Creating the observation automatically adds it to the view.
Observation::Ptr observation =
Observation::Create(view, Feature(u + rng.DoubleGaussian(0.0, noise_stddev),
v + rng.DoubleGaussian(0.0, noise_stddev)),
landmark->Descriptor());
observation->SetMatchedLandmark(landmark_index);
projected_landmarks.push_back(landmark_index);
}
// Make some bad observations also.
for (unsigned int ii = 0; ii < num_bad_matches; ++ii) {
double u = 0.0, v = 0.0;
Point3D point = RandomPoint();
if (!view->Camera().WorldToImage(point.X(), point.Y(), point.Z(), &u, &v))
continue;
// Creating the observation automatically adds it to the view.
Observation::Ptr observation =
Observation::Create(view,
Feature(u + rng.DoubleGaussian(0.0, noise_stddev),
v + rng.DoubleGaussian(0.0, noise_stddev)),
Descriptor::Random(kDescriptorLength));
// Match to a random landmark.
size_t random_index = static_cast<size_t>(rng.IntegerUniform(landmark_indices.size()));
observation->SetMatchedLandmark(landmark_indices[random_index]);
}
return projected_landmarks;
}
void TestRansac2D3D(unsigned int num_bad_matches,
double noise_stddev) {
// Clean up from other tests.
Landmark::ResetLandmarks();
View::ResetViews();
// Make a camera with a random translation and rotation.
Camera camera;
CameraExtrinsics extrinsics;
const Point3D camera_pose = RandomPoint();
const Vector3d euler_angles(Vector3d::Random() * D2R(180.0));
extrinsics.Translate(camera_pose.X(), camera_pose.Y(), camera_pose.Z());
extrinsics.Rotate(EulerAnglesToMatrix(euler_angles));
camera.SetExtrinsics(extrinsics);
camera.SetIntrinsics(DefaultIntrinsics());
// Initialize a view for this camera.
View::Ptr view = View::Create(camera);
// Make a bunch of randomly positioned landmarks.
for (unsigned int ii = 0; ii < kNumLandmarks; ++ii) {
Point3D point = RandomPoint();
Landmark::Ptr landmark = Landmark::Create();
landmark->SetPosition(point);
landmark->SetDescriptor(Descriptor::Random(kDescriptorLength));
}
std::vector<LandmarkIndex> landmark_indices =
Landmark::ExistingLandmarkIndices();
// Create observations of the landmarks (no bad observations).
std::vector<LandmarkIndex> projected_landmarks =
CreateObservations(landmark_indices, view->Index(), 0, noise_stddev);
ASSERT_LT(0, projected_landmarks.size());
// Make sure the distance metric (which is global across tests) is set up
// correctly.
DistanceMetric& distance = DistanceMetric::Instance();
distance.SetMetric(DistanceMetric::Metric::SCALED_L2);
distance.SetMaximumDistance(std::numeric_limits<double>::max());
// Set up RANSAC.
PnPRansacProblem problem;
CameraIntrinsics intrinsics = DefaultIntrinsics();
problem.SetIntrinsics(intrinsics);
problem.SetData(view->Observations());
// Run RANSAC for a bunch of iterations. It is very likely that in at least 1
// iteration, all samples will be from the set of good matches and will
// therefore result in an error of < 1e-8.
Ransac<Observation::Ptr, PnPRansacModel> solver;
RansacOptions options;
options.iterations = 100;
options.acceptable_error = 1e-8;
options.num_samples = 6;
options.minimum_num_inliers = projected_landmarks.size();
solver.SetOptions(options);
solver.Run(problem);
// Get the solution from the problem object.
ASSERT_TRUE(problem.SolutionFound());
// Iterate over all observations in the view and check that they are correctly
// matched.
std::vector<Observation::Ptr> observations = view->Observations();
for (size_t ii = 0; ii < observations.size(); ++ii) {
if (!observations[ii]->IsMatched())
continue;
EXPECT_FALSE(observations[ii]->IsIncorporated());
EXPECT_EQ(projected_landmarks[ii], observations[ii]->GetLandmark()->Index());
}
// Clean up.
Landmark::ResetLandmarks();
View::ResetViews();
}
} //\namespace
// Test with 1 to 1 correspondence between observations in the view and existing
// landmarks.
TEST(PnPRansac2D3D, TestPnPRansac2D3DNoiseless) {
TestRansac2D3D(0);
}
// Test with many to 1 correspondence between observations in the view and existing
// landmarks.
TEST(PnPRansac2D3D, TestPnPRansac2D3DNoisy) {
TestRansac2D3D(0.5 * kNumLandmarks);
}
// Test with MANY to 1 correspondence between observations in the view and existing
// landmarks.
TEST(PnPRansac2D3D, TestPnPRansac2D3DVeryNoisy) {
TestRansac2D3D(100.0 * kNumLandmarks);
}
} //\namespace bsfm
<commit_msg>passes ransac 2d3d test with high threshold on noisy case<commit_after>/*
* Copyright (c) 2015, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Authors: David Fridovich-Keil ( dfk@eecs.berkeley.edu )
* Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#include <camera/camera.h>
#include <camera/camera_extrinsics.h>
#include <camera/camera_intrinsics.h>
#include <matching/feature_matcher_options.h>
#include <matching/naive_matcher_2d3d.h>
#include <geometry/point_3d.h>
#include <geometry/rotation.h>
#include <matching/feature.h>
#include <math/random_generator.h>
#include <sfm/view.h>
#include <slam/landmark.h>
#include <slam/observation.h>
#include <ransac/pnp_ransac_problem.h>
#include <ransac/ransac.h>
#include <gtest/gtest.h>
#include <gflags/gflags.h>
DEFINE_double(noise_stddev, 1.0,
"Additive Gaussian noise on feature coordinates.");
namespace bsfm {
using Eigen::Matrix3d;
using Eigen::Vector3d;
;
namespace {
// Minimum number of points to constrain the problem. See H&Z pg. 179.
const int kNumLandmarks = 100;
const int kImageWidth = 1920;
const int kImageHeight = 1080;
const double kVerticalFov = D2R(90.0);
// Bounding volume for 3D points.
const double kMinX = -2.0;
const double kMinY = -2.0;
const double kMinZ = -2.0;
const double kMaxX = 2.0;
const double kMaxY = 2.0;
const double kMaxZ = 2.0;
const unsigned int kDescriptorLength = 64;
// Makes a default set of camera intrinsic parameters.
CameraIntrinsics DefaultIntrinsics() {
CameraIntrinsics intrinsics;
intrinsics.SetImageLeft(0);
intrinsics.SetImageTop(0);
intrinsics.SetImageWidth(kImageWidth);
intrinsics.SetImageHeight(kImageHeight);
intrinsics.SetVerticalFOV(kVerticalFov);
intrinsics.SetFU(intrinsics.f_v());
intrinsics.SetCU(0.5 * kImageWidth);
intrinsics.SetCV(0.5 * kImageHeight);
return intrinsics;
}
// Makes a random 3D point.
Point3D RandomPoint() {
CHECK(kMinX <= kMaxX);
CHECK(kMinY <= kMaxY);
CHECK(kMinZ <= kMaxZ);
static math::RandomGenerator rng(0);
const double x = rng.DoubleUniform(kMinX, kMaxX);
const double y = rng.DoubleUniform(kMinY, kMaxY);
const double z = rng.DoubleUniform(kMinZ, kMaxZ);
return Point3D(x, y, z);
}
// Creates one observation for each landmark in the scene, and adds them to the
// view. Also creates 'num_bad_matches' bad observations (of random 3D points).
// Returns indices of landmarks that were successfully projected.
std::vector<LandmarkIndex> CreateObservations(
const std::vector<LandmarkIndex>& landmark_indices,
ViewIndex view_index,
unsigned int num_bad_matches,
double noise_stddev = 0.0) {
View::Ptr view = View::GetView(view_index);
CHECK_NOTNULL(view.get());
// For each landmark that projects into the view, create an observation and
// add it to the view.
std::vector<LandmarkIndex> projected_landmarks;
static math::RandomGenerator rng(0);
for (const auto& landmark_index : landmark_indices) {
Landmark::Ptr landmark = Landmark::GetLandmark(landmark_index);
CHECK_NOTNULL(landmark.get());
double u = 0.0, v = 0.0;
const Point3D point = landmark->Position();
if (!view->Camera().WorldToImage(point.X(), point.Y(), point.Z(), &u, &v))
continue;
// Creating the observation automatically adds it to the view.
Observation::Ptr observation =
Observation::Create(view, Feature(u + rng.DoubleGaussian(0.0, noise_stddev),
v + rng.DoubleGaussian(0.0, noise_stddev)),
landmark->Descriptor());
observation->SetMatchedLandmark(landmark_index);
projected_landmarks.push_back(landmark_index);
}
// Make some bad observations also.
for (unsigned int ii = 0; ii < num_bad_matches; ++ii) {
double u = 0.0, v = 0.0;
Point3D point = RandomPoint();
if (!view->Camera().WorldToImage(point.X(), point.Y(), point.Z(), &u, &v))
continue;
// Creating the observation automatically adds it to the view.
Observation::Ptr observation =
Observation::Create(view,
Feature(u + rng.DoubleGaussian(0.0, noise_stddev),
v + rng.DoubleGaussian(0.0, noise_stddev)),
Descriptor::Random(kDescriptorLength));
// Match to a random landmark.
size_t random_index = static_cast<size_t>(rng.IntegerUniform(landmark_indices.size()));
observation->SetMatchedLandmark(landmark_indices[random_index]);
}
return projected_landmarks;
}
void TestRansac2D3D(unsigned int num_bad_matches,
double noise_stddev) {
// Clean up from other tests.
Landmark::ResetLandmarks();
View::ResetViews();
// Make a camera with a random translation and rotation.
Camera camera;
CameraExtrinsics extrinsics;
const Point3D camera_pose = RandomPoint();
const Vector3d euler_angles(Vector3d::Random() * D2R(180.0));
extrinsics.Translate(camera_pose.X(), camera_pose.Y(), camera_pose.Z());
extrinsics.Rotate(EulerAnglesToMatrix(euler_angles));
camera.SetExtrinsics(extrinsics);
camera.SetIntrinsics(DefaultIntrinsics());
// Initialize a view for this camera.
View::Ptr view = View::Create(camera);
// Make a bunch of randomly positioned landmarks.
for (unsigned int ii = 0; ii < kNumLandmarks; ++ii) {
Point3D point = RandomPoint();
Landmark::Ptr landmark = Landmark::Create();
landmark->SetPosition(point);
landmark->SetDescriptor(Descriptor::Random(kDescriptorLength));
}
std::vector<LandmarkIndex> landmark_indices =
Landmark::ExistingLandmarkIndices();
// Create observations of the landmarks (no bad observations).
std::vector<LandmarkIndex> projected_landmarks =
CreateObservations(landmark_indices, view->Index(), 0, noise_stddev);
ASSERT_LT(0, projected_landmarks.size());
// Make sure the distance metric (which is global across tests) is set up
// correctly.
DistanceMetric& distance = DistanceMetric::Instance();
distance.SetMetric(DistanceMetric::Metric::SCALED_L2);
distance.SetMaximumDistance(std::numeric_limits<double>::max());
// Set up RANSAC.
PnPRansacProblem problem;
CameraIntrinsics intrinsics = DefaultIntrinsics();
problem.SetIntrinsics(intrinsics);
problem.SetData(view->Observations());
// Run RANSAC for a bunch of iterations. It is very likely that in at least 1
// iteration, all samples will be from the set of good matches and will
// therefore result in an error of < 1e-8.
Ransac<Observation::Ptr, PnPRansacModel> solver;
RansacOptions options;
options.iterations = 100;
options.acceptable_error = 1e-8 + 100.0 * noise_stddev;
options.num_samples = 6;
options.minimum_num_inliers = projected_landmarks.size();
solver.SetOptions(options);
solver.Run(problem);
// Get the solution from the problem object.
ASSERT_TRUE(problem.SolutionFound());
// Iterate over all observations in the view and check that they are correctly
// matched.
std::vector<Observation::Ptr> observations = view->Observations();
for (size_t ii = 0; ii < observations.size(); ++ii) {
if (!observations[ii]->IsMatched())
continue;
EXPECT_FALSE(observations[ii]->IsIncorporated());
EXPECT_EQ(projected_landmarks[ii], observations[ii]->GetLandmark()->Index());
}
// Clean up.
Landmark::ResetLandmarks();
View::ResetViews();
}
} //\namespace
// Test with 1 to 1 correspondence between observations in the view and existing
// landmarks.
TEST(PnPRansac2D3D, TestPnPRansac2D3DNoiseless) {
TestRansac2D3D(0, 0.0);
}
// Test with many to 1 correspondence between observations in the view and existing
// landmarks.
TEST(PnPRansac2D3D, TestPnPRansac2D3DNoisy) {
TestRansac2D3D(0.5 * kNumLandmarks, FLAGS_noise_stddev);
}
// Test with MANY to 1 correspondence between observations in the view and existing
// landmarks.
TEST(PnPRansac2D3D, TestPnPRansac2D3DVeryNoisy) {
TestRansac2D3D(100.0 * kNumLandmarks, FLAGS_noise_stddev);
}
} //\namespace bsfm
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ccs/ccs.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file ccs.C
/// @brief Run and manage the CCS engine
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/ccs/ccs.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ccs
{
///
/// @brief Start or stop the CCS engine
/// @param[in] i_target The MCBIST containing the CCS engine
/// @param[in] i_start_stop bool MSS_CCS_START for starting, MSS_CCS_STOP otherwise
/// @return FAPI2_RC_SUCCESS iff success
///
template<>
fapi2::ReturnCode start_stop( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, bool i_start_stop )
{
typedef ccsTraits<TARGET_TYPE_MCBIST> TT;
fapi2::buffer<uint64_t> l_buf;
// Do we need to read this? We are setting the only bit defined in the scomdef? BRS
FAPI_TRY(mss::getScom(i_target, TT::CNTLQ_REG, l_buf));
FAPI_TRY( mss::putScom(i_target, TT::CNTLQ_REG,
i_start_stop ? l_buf.setBit<TT::CCS_START>() : l_buf.setBit<TT::CCS_STOP>()) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Determine the CCS failure type
/// @tparam T the fapi2 target type of the target for this error
/// @param[in] i_target
/// @param[in] i_type the failure type
/// @return ReturnCode associated with the fail.
/// @note FFDC is handled here, caller doesn't need to do it
///
template< fapi2::TargetType T >
fapi2::ReturnCode fail_type( const fapi2::Target<T>& i_target, const uint64_t& i_type )
{
FAPI_ASSERT(STAT_READ_MISCOMPARE != i_type,
fapi2::MSS_CCS_READ_MISCOMPARE().set_TARGET_IN_ERROR(i_target),
"CCS FAIL Read Miscompare");
FAPI_ASSERT(STAT_UE_SUE != i_type,
fapi2::MSS_CCS_UE_SUE().set_TARGET_IN_ERROR(i_target),
"CCS FAIL UE or SUE Error");
FAPI_ASSERT(STAT_CAL_TIMEOUT != i_type,
fapi2::MSS_CCS_CAL_TIMEOUT().set_TARGET_IN_ERROR(i_target),
"CCS FAIL Calibration Operation Time Out");
FAPI_ASSERT(STAT_HUNG != i_type,
fapi2::MSS_CCS_HUNG().set_TARGET_IN_ERROR(i_target),
"CCS appears hung");
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Execute the contents of the CCS array
/// @param[in] i_target The MCBIST containing the array
/// @param[in] i_program the MCBIST ccs program - to get the polling parameters
/// @return FAPI2_RC_SUCCESS iff success
///
template<>
fapi2::ReturnCode execute_inst_array(const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
ccs::program<TARGET_TYPE_MCBIST>& i_program)
{
typedef ccsTraits<TARGET_TYPE_MCBIST> TT;
fapi2::buffer<uint64_t> status;
FAPI_TRY(start_stop(i_target, mss::START));
mss::poll(i_target, TT::STATQ_REG, i_program.iv_poll,
[&status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool
{
FAPI_DBG("ccs statq 0x%llx, remaining: %d", stat_reg, poll_remaining);
status = stat_reg;
return status.getBit<TT::CCS_IN_PROGRESS>() != 1;
},
i_program.iv_probes);
// Check for done and success. DONE being the only bit set.
if (status == STAT_QUERY_SUCCESS)
{
FAPI_DBG("CCS Executed Successfully.");
goto fapi_try_exit;
}
// So we failed or we're still in progress. Mask off the fail bits
// and run this through the FFDC generator.
FAPI_TRY( fail_type(i_target, status & 0x1C00000000000000) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Execute a set of CCS instructions
/// @param[in] i_target the target to effect
/// @param[in] i_program the vector of instructions
/// @param[in] i_ports the vector of ports
/// @return FAPI2_RC_SUCCSS iff ok
/// @note assumes the CCS engine has been configured.
///
template<>
fapi2::ReturnCode execute( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
ccs::program<TARGET_TYPE_MCBIST>& i_program,
const std::vector< fapi2::Target<TARGET_TYPE_MCA> >& i_ports)
{
// Subtract one for the idle we insert at the end
static const size_t CCS_INSTRUCTION_DEPTH = 32 - 1;
static const uint64_t CCS_ARR0_ZERO = MCBIST_CCS_INST_ARR0_00;
static const uint64_t CCS_ARR1_ZERO = MCBIST_CCS_INST_ARR1_00;
ccs::instruction_t<TARGET_TYPE_MCBIST> l_des = ccs::des_command<TARGET_TYPE_MCBIST>();
FAPI_DBG("loading ccs instructions (%d) for %s", i_program.iv_instructions.size(), mss::c_str(i_target));
auto l_inst_iter = i_program.iv_instructions.begin();
while (l_inst_iter != i_program.iv_instructions.end())
{
size_t l_inst_count = 0;
uint64_t l_total_delay = 0;
uint64_t l_delay = 0;
uint64_t l_repeat = 0;
// Shove the instructions into the CCS engine, in 32 instruction chunks, and execute them
for (; l_inst_iter != i_program.iv_instructions.end()
&& l_inst_count < CCS_INSTRUCTION_DEPTH; ++l_inst_count, ++l_inst_iter)
{
// Make sure this instruction leads to the next. Notice this limits this mechanism to pretty
// simple (straight line) CCS programs. Anything with a loop or such will need another mechanism.
l_inst_iter->arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_GOTO_CMD,
MCBIST_CCS_INST_ARR1_00_GOTO_CMD_LEN>(l_inst_count + 1);
FAPI_TRY( mss::putScom(i_target, CCS_ARR0_ZERO + l_inst_count, l_inst_iter->arr0) );
FAPI_TRY( mss::putScom(i_target, CCS_ARR1_ZERO + l_inst_count, l_inst_iter->arr1) );
// arr1 contains a specification of the delay and repeat after this instruction, as well
// as a repeat. Total up the delays as we go so we know how long to wait before polling
// the CCS engine for completion
l_inst_iter->arr1.extractToRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(l_delay);
l_inst_iter->arr1.extractToRight<MCBIST_CCS_INST_ARR1_00_REPEAT_CMD_CNT,
MCBIST_CCS_INST_ARR1_00_REPEAT_CMD_CNT>(l_repeat);
l_total_delay += l_delay * (l_repeat + 1);
FAPI_DBG("css inst %d: 0x%016lX 0x%016lX (0x%lx, 0x%lx) delay: 0x%x (0x%x) %s",
l_inst_count, l_inst_iter->arr0, l_inst_iter->arr1,
CCS_ARR0_ZERO + l_inst_count, CCS_ARR1_ZERO + l_inst_count,
l_delay, l_total_delay, mss::c_str(i_target));
}
// Check our program for any delays. If there isn't a iv_initial_delay configured, then
// we use the delay we just summed from the instructions.
if (i_program.iv_poll.iv_initial_delay == 0)
{
i_program.iv_poll.iv_initial_delay = cycles_to_ns(i_target, l_total_delay);
}
if (i_program.iv_poll.iv_initial_sim_delay == 0)
{
i_program.iv_poll.iv_initial_sim_delay = cycles_to_simcycles(l_total_delay);
}
FAPI_DBG("executing ccs instructions (%d:%d, %d) for %s",
i_program.iv_instructions.size(), l_inst_count, i_program.iv_poll.iv_initial_delay, mss::c_str(i_target));
// Insert a DES as our last instruction. DES is idle state anyway and having this
// here as an instruction forces the CCS engine to wait the delay specified in
// the last instruction in this array (which it otherwise doesn't do.)
l_des.arr1.setBit<MCBIST_CCS_INST_ARR1_00_END>();
FAPI_TRY( mss::putScom(i_target, CCS_ARR0_ZERO + l_inst_count, l_des.arr0) );
FAPI_TRY( mss::putScom(i_target, CCS_ARR1_ZERO + l_inst_count, l_des.arr1) );
FAPI_DBG("css inst %d fixup: 0x%016lX 0x%016lX (0x%lx, 0x%lx) %s",
l_inst_count, l_des.arr0, l_des.arr1,
CCS_ARR0_ZERO + l_inst_count, CCS_ARR1_ZERO + l_inst_count, mss::c_str(i_target));
// Kick off the CCS engine - per port. No broadcast mode for CCS (per Shelton 9/23/15)
for (auto p : i_ports)
{
FAPI_DBG("executing CCS array for port %d (%s)", mss::relative_pos<TARGET_TYPE_MCBIST>(p), mss::c_str(p));
FAPI_TRY( select_ports( i_target, mss::relative_pos<TARGET_TYPE_MCBIST>(p)) );
FAPI_TRY( execute_inst_array(i_target, i_program) );
}
}
fapi_try_exit:
i_program.iv_instructions.clear();
return fapi2::current_err;
}
///
/// @brief Nimbus specialization for modeq_copy_cke_to_spare_cke
/// @tparam T the fapi2::TargetType - derived
/// @tparam TT the ccsTraits associated with T - derived
/// @param[in] fapi2::Target<TARGET_TYPE_MCBIST>& the target to effect
/// @param[in] the buffer representing the mode register
/// @param[in] bool true iff Copy CKE signals to CKE Spare on both ports
/// @return void
/// @note no-op for p9n
///
template<>
void copy_cke_to_spare_cke<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>&, fapi2::buffer<uint64_t>&,
bool )
{
return;
}
} // namespace
} // namespace
<commit_msg>Changes to limit DLL cal on spare DP8, stop CSS before starting<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/ccs/ccs.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file ccs.C
/// @brief Run and manage the CCS engine
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/ccs/ccs.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
namespace ccs
{
///
/// @brief Start or stop the CCS engine
/// @param[in] i_target The MCBIST containing the CCS engine
/// @param[in] i_start_stop bool MSS_CCS_START for starting, MSS_CCS_STOP otherwise
/// @return FAPI2_RC_SUCCESS iff success
///
template<>
fapi2::ReturnCode start_stop( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target, bool i_start_stop )
{
typedef ccsTraits<TARGET_TYPE_MCBIST> TT;
fapi2::buffer<uint64_t> l_buf;
// Do we need to read this? We are setting the only bit defined in the scomdef? BRS
FAPI_TRY(mss::getScom(i_target, TT::CNTLQ_REG, l_buf));
FAPI_TRY( mss::putScom(i_target, TT::CNTLQ_REG,
i_start_stop ? l_buf.setBit<TT::CCS_START>() : l_buf.setBit<TT::CCS_STOP>()) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Determine the CCS failure type
/// @tparam T the fapi2 target type of the target for this error
/// @param[in] i_target
/// @param[in] i_type the failure type
/// @return ReturnCode associated with the fail.
/// @note FFDC is handled here, caller doesn't need to do it
///
template< fapi2::TargetType T >
fapi2::ReturnCode fail_type( const fapi2::Target<T>& i_target, const uint64_t& i_type )
{
FAPI_ASSERT(STAT_READ_MISCOMPARE != i_type,
fapi2::MSS_CCS_READ_MISCOMPARE().set_TARGET_IN_ERROR(i_target),
"CCS FAIL Read Miscompare");
FAPI_ASSERT(STAT_UE_SUE != i_type,
fapi2::MSS_CCS_UE_SUE().set_TARGET_IN_ERROR(i_target),
"CCS FAIL UE or SUE Error");
FAPI_ASSERT(STAT_CAL_TIMEOUT != i_type,
fapi2::MSS_CCS_CAL_TIMEOUT().set_TARGET_IN_ERROR(i_target),
"CCS FAIL Calibration Operation Time Out");
FAPI_ASSERT(STAT_HUNG != i_type,
fapi2::MSS_CCS_HUNG().set_TARGET_IN_ERROR(i_target),
"CCS appears hung");
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Execute the contents of the CCS array
/// @param[in] i_target The MCBIST containing the array
/// @param[in] i_program the MCBIST ccs program - to get the polling parameters
/// @return FAPI2_RC_SUCCESS iff success
///
template<>
fapi2::ReturnCode execute_inst_array(const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
ccs::program<TARGET_TYPE_MCBIST>& i_program)
{
typedef ccsTraits<TARGET_TYPE_MCBIST> TT;
fapi2::buffer<uint64_t> status;
FAPI_TRY(start_stop(i_target, mss::START));
mss::poll(i_target, TT::STATQ_REG, i_program.iv_poll,
[&status](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool
{
FAPI_INF("ccs statq 0x%llx, remaining: %d", stat_reg, poll_remaining);
status = stat_reg;
return status.getBit<TT::CCS_IN_PROGRESS>() != 1;
},
i_program.iv_probes);
// Check for done and success. DONE being the only bit set.
if (status == STAT_QUERY_SUCCESS)
{
FAPI_INF("CCS Executed Successfully.");
goto fapi_try_exit;
}
// So we failed or we're still in progress. Mask off the fail bits
// and run this through the FFDC generator.
FAPI_TRY( fail_type(i_target, status & 0x1C00000000000000) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Execute a set of CCS instructions
/// @param[in] i_target the target to effect
/// @param[in] i_program the vector of instructions
/// @param[in] i_ports the vector of ports
/// @return FAPI2_RC_SUCCSS iff ok
/// @note assumes the CCS engine has been configured.
///
template<>
fapi2::ReturnCode execute( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target,
ccs::program<TARGET_TYPE_MCBIST>& i_program,
const std::vector< fapi2::Target<TARGET_TYPE_MCA> >& i_ports)
{
typedef ccsTraits<TARGET_TYPE_MCBIST> TT;
// Subtract one for the idle we insert at the end
constexpr size_t CCS_INSTRUCTION_DEPTH = 32 - 1;
constexpr uint64_t CCS_ARR0_ZERO = MCBIST_CCS_INST_ARR0_00;
constexpr uint64_t CCS_ARR1_ZERO = MCBIST_CCS_INST_ARR1_00;
ccs::instruction_t<TARGET_TYPE_MCBIST> l_des = ccs::des_command<TARGET_TYPE_MCBIST>();
FAPI_INF("loading ccs instructions (%d) for %s", i_program.iv_instructions.size(), mss::c_str(i_target));
auto l_inst_iter = i_program.iv_instructions.begin();
// Stop the CCS engine just for giggles - it might be running ...
FAPI_TRY( start_stop(i_target, mss::states::STOP) );
FAPI_ASSERT( mss::poll(i_target, TT::STATQ_REG, poll_parameters(),
[](const size_t poll_remaining, const fapi2::buffer<uint64_t>& stat_reg) -> bool
{
FAPI_INF("ccs statq (stop) 0x%llx, remaining: %d", stat_reg, poll_remaining);
return stat_reg.getBit<TT::CCS_IN_PROGRESS>() != 1;
}),
fapi2::MSS_CCS_HUNG_TRYING_TO_STOP().set_TARGET_IN_ERROR(i_target),
"CCS appears hung (trying to stop)");
while (l_inst_iter != i_program.iv_instructions.end())
{
size_t l_inst_count = 0;
uint64_t l_total_delay = 0;
uint64_t l_delay = 0;
uint64_t l_repeat = 0;
// Shove the instructions into the CCS engine, in 32 instruction chunks, and execute them
for (; l_inst_iter != i_program.iv_instructions.end()
&& l_inst_count < CCS_INSTRUCTION_DEPTH; ++l_inst_count, ++l_inst_iter)
{
// Make sure this instruction leads to the next. Notice this limits this mechanism to pretty
// simple (straight line) CCS programs. Anything with a loop or such will need another mechanism.
l_inst_iter->arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_GOTO_CMD,
MCBIST_CCS_INST_ARR1_00_GOTO_CMD_LEN>(l_inst_count + 1);
FAPI_TRY( mss::putScom(i_target, CCS_ARR0_ZERO + l_inst_count, l_inst_iter->arr0) );
FAPI_TRY( mss::putScom(i_target, CCS_ARR1_ZERO + l_inst_count, l_inst_iter->arr1) );
// arr1 contains a specification of the delay and repeat after this instruction, as well
// as a repeat. Total up the delays as we go so we know how long to wait before polling
// the CCS engine for completion
l_inst_iter->arr1.extractToRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(l_delay);
l_inst_iter->arr1.extractToRight<MCBIST_CCS_INST_ARR1_00_REPEAT_CMD_CNT,
MCBIST_CCS_INST_ARR1_00_REPEAT_CMD_CNT>(l_repeat);
l_total_delay += l_delay * (l_repeat + 1);
FAPI_INF("css inst %d: 0x%016lX 0x%016lX (0x%lx, 0x%lx) delay: 0x%x (0x%x) %s",
l_inst_count, l_inst_iter->arr0, l_inst_iter->arr1,
CCS_ARR0_ZERO + l_inst_count, CCS_ARR1_ZERO + l_inst_count,
l_delay, l_total_delay, mss::c_str(i_target));
}
// Check our program for any delays. If there isn't a iv_initial_delay configured, then
// we use the delay we just summed from the instructions.
if (i_program.iv_poll.iv_initial_delay == 0)
{
i_program.iv_poll.iv_initial_delay = cycles_to_ns(i_target, l_total_delay);
}
if (i_program.iv_poll.iv_initial_sim_delay == 0)
{
i_program.iv_poll.iv_initial_sim_delay = cycles_to_simcycles(l_total_delay);
}
FAPI_INF("executing ccs instructions (%d:%d, %d) for %s",
i_program.iv_instructions.size(), l_inst_count, i_program.iv_poll.iv_initial_delay, mss::c_str(i_target));
// Insert a DES as our last instruction. DES is idle state anyway and having this
// here as an instruction forces the CCS engine to wait the delay specified in
// the last instruction in this array (which it otherwise doesn't do.)
l_des.arr1.setBit<MCBIST_CCS_INST_ARR1_00_END>();
FAPI_TRY( mss::putScom(i_target, CCS_ARR0_ZERO + l_inst_count, l_des.arr0) );
FAPI_TRY( mss::putScom(i_target, CCS_ARR1_ZERO + l_inst_count, l_des.arr1) );
FAPI_INF("css inst %d fixup: 0x%016lX 0x%016lX (0x%lx, 0x%lx) %s",
l_inst_count, l_des.arr0, l_des.arr1,
CCS_ARR0_ZERO + l_inst_count, CCS_ARR1_ZERO + l_inst_count, mss::c_str(i_target));
// Kick off the CCS engine - per port. No broadcast mode for CCS (per Shelton 9/23/15)
for (const auto& p : i_ports)
{
FAPI_INF("executing CCS array for port %d (%s)", mss::relative_pos<TARGET_TYPE_MCBIST>(p), mss::c_str(p));
FAPI_TRY( select_ports( i_target, mss::relative_pos<TARGET_TYPE_MCBIST>(p)) );
FAPI_TRY( execute_inst_array(i_target, i_program) );
}
}
fapi_try_exit:
i_program.iv_instructions.clear();
return fapi2::current_err;
}
///
/// @brief Nimbus specialization for modeq_copy_cke_to_spare_cke
/// @tparam T the fapi2::TargetType - derived
/// @tparam TT the ccsTraits associated with T - derived
/// @param[in] fapi2::Target<TARGET_TYPE_MCBIST>& the target to effect
/// @param[in,out] the buffer representing the mode register
/// @param[in] bool true iff Copy CKE signals to CKE Spare on both ports
/// @return void
/// @note no-op for p9n
///
template<>
void copy_cke_to_spare_cke<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>&,
fapi2::buffer<uint64_t>&, bool )
{
return;
}
} // namespace
} // namespace
<|endoftext|>
|
<commit_before>#include "file_assembly.h"
#include "search_engine.h"
#include "entry.h"
#include "code_entry.h"
#include "file_unit.h"
#include "elf_file.h"
#include "file_handler.h"
#include "elfio/elfio.hpp"
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " <executable path>\n";
return 1;
}
FileHandler *fh = new FileHandler;
if (fh->open(std::string(argv[1])))
std::cout << "It works.\n";
else
std::cout << "It doesn't work.\n";
delete fh;
return 0;
}
<commit_msg>Fix an indentation issue<commit_after>#include "file_assembly.h"
#include "search_engine.h"
#include "entry.h"
#include "code_entry.h"
#include "file_unit.h"
#include "elf_file.h"
#include "file_handler.h"
#include "elfio/elfio.hpp"
int main(int argc, char *argv[])
{
if (argc < 2)
{
std::cerr << "Usage: " << argv[0] << " <executable path>\n";
return 1;
}
FileHandler *fh = new FileHandler;
if (fh->open(std::string(argv[1])))
std::cout << "It works.\n";
else
std::cout << "It doesn't work.\n";
delete fh;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011-2015, 2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ron Dreslinski
* Ali Saidi
* Andreas Hansson
* William Wang
*/
/**
* @file
* Declaration of an abstract crossbar base class.
*/
#ifndef __MEM_XBAR_HH__
#define __MEM_XBAR_HH__
#include <deque>
#include <unordered_map>
#include "base/addr_range_map.hh"
#include "base/types.hh"
#include "mem/mem_object.hh"
#include "mem/qport.hh"
#include "params/BaseXBar.hh"
#include "sim/stats.hh"
/**
* The base crossbar contains the common elements of the non-coherent
* and coherent crossbar. It is an abstract class that does not have
* any of the functionality relating to the actual reception and
* transmission of packets, as this is left for the subclasses.
*
* The BaseXBar is responsible for the basic flow control (busy or
* not), the administration of retries, and the address decoding.
*/
class BaseXBar : public MemObject
{
protected:
/**
* A layer is an internal crossbar arbitration point with its own
* flow control. Each layer is a converging multiplexer tree. By
* instantiating one layer per destination port (and per packet
* type, i.e. request, response, snoop request and snoop
* response), we model full crossbar structures like AXI, ACE,
* PCIe, etc.
*
* The template parameter, PortClass, indicates the destination
* port type for the layer. The retry list holds either master
* ports or slave ports, depending on the direction of the
* layer. Thus, a request layer has a retry list containing slave
* ports, whereas a response layer holds master ports.
*/
template <typename SrcType, typename DstType>
class Layer : public Drainable
{
public:
/**
* Create a layer and give it a name. The layer uses
* the crossbar an event manager.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
Layer(DstType& _port, BaseXBar& _xbar, const std::string& _name);
/**
* Drain according to the normal semantics, so that the crossbar
* can tell the layer to drain, and pass an event to signal
* back when drained.
*
* @param de drain event to call once drained
*
* @return 1 if busy or waiting to retry, or 0 if idle
*/
DrainState drain() override;
const std::string name() const { return xbar.name() + _name; }
/**
* Determine if the layer accepts a packet from a specific
* port. If not, the port in question is also added to the
* retry list. In either case the state of the layer is
* updated accordingly.
*
* @param port Source port presenting the packet
*
* @return True if the layer accepts the packet
*/
bool tryTiming(SrcType* src_port);
/**
* Deal with a destination port accepting a packet by potentially
* removing the source port from the retry list (if retrying) and
* occupying the layer accordingly.
*
* @param busy_time Time to spend as a result of a successful send
*/
void succeededTiming(Tick busy_time);
/**
* Deal with a destination port not accepting a packet by
* potentially adding the source port to the retry list (if
* not already at the front) and occupying the layer
* accordingly.
*
* @param src_port Source port
* @param busy_time Time to spend as a result of a failed send
*/
void failedTiming(SrcType* src_port, Tick busy_time);
void occupyLayer(Tick until);
/**
* Send a retry to the port at the head of waitingForLayer. The
* caller must ensure that the list is not empty.
*/
void retryWaiting();
/**
* Handle a retry from a neighbouring module. This wraps
* retryWaiting by verifying that there are ports waiting
* before calling retryWaiting.
*/
void recvRetry();
void regStats();
protected:
/**
* Sending the actual retry, in a manner specific to the
* individual layers. Note that for a MasterPort, there is
* both a RequestLayer and a SnoopResponseLayer using the same
* port, but using different functions for the flow control.
*/
virtual void sendRetry(SrcType* retry_port) = 0;
private:
/** The destination port this layer converges at. */
DstType& port;
/** The crossbar this layer is a part of. */
BaseXBar& xbar;
std::string _name;
/**
* We declare an enum to track the state of the layer. The
* starting point is an idle state where the layer is waiting
* for a packet to arrive. Upon arrival, the layer
* transitions to the busy state, where it remains either
* until the packet transfer is done, or the header time is
* spent. Once the layer leaves the busy state, it can
* either go back to idle, if no packets have arrived while it
* was busy, or the layer goes on to retry the first port
* in waitingForLayer. A similar transition takes place from
* idle to retry if the layer receives a retry from one of
* its connected ports. The retry state lasts until the port
* in questions calls sendTiming and returns control to the
* layer, or goes to a busy state if the port does not
* immediately react to the retry by calling sendTiming.
*/
enum State { IDLE, BUSY, RETRY };
State state;
/**
* A deque of ports that retry should be called on because
* the original send was delayed due to a busy layer.
*/
std::deque<SrcType*> waitingForLayer;
/**
* Track who is waiting for the retry when receiving it from a
* peer. If no port is waiting NULL is stored.
*/
SrcType* waitingForPeer;
/**
* Release the layer after being occupied and return to an
* idle state where we proceed to send a retry to any
* potential waiting port, or drain if asked to do so.
*/
void releaseLayer();
EventFunctionWrapper releaseEvent;
/**
* Stats for occupancy and utilization. These stats capture
* the time the layer spends in the busy state and are thus only
* relevant when the memory system is in timing mode.
*/
Stats::Scalar occupancy;
Stats::Formula utilization;
};
class ReqLayer : public Layer<SlavePort, MasterPort>
{
public:
/**
* Create a request layer and give it a name.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
ReqLayer(MasterPort& _port, BaseXBar& _xbar, const std::string& _name) :
Layer(_port, _xbar, _name)
{}
protected:
void
sendRetry(SlavePort* retry_port) override
{
retry_port->sendRetryReq();
}
};
class RespLayer : public Layer<MasterPort, SlavePort>
{
public:
/**
* Create a response layer and give it a name.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
RespLayer(SlavePort& _port, BaseXBar& _xbar,
const std::string& _name) :
Layer(_port, _xbar, _name)
{}
protected:
void
sendRetry(MasterPort* retry_port) override
{
retry_port->sendRetryResp();
}
};
class SnoopRespLayer : public Layer<SlavePort, MasterPort>
{
public:
/**
* Create a snoop response layer and give it a name.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
SnoopRespLayer(MasterPort& _port, BaseXBar& _xbar,
const std::string& _name) :
Layer(_port, _xbar, _name)
{}
protected:
void
sendRetry(SlavePort* retry_port) override
{
retry_port->sendRetrySnoopResp();
}
};
/**
* Cycles of front-end pipeline including the delay to accept the request
* and to decode the address.
*/
const Cycles frontendLatency;
const Cycles forwardLatency;
const Cycles responseLatency;
/** the width of the xbar in bytes */
const uint32_t width;
AddrRangeMap<PortID, 3> portMap;
/**
* Remember where request packets came from so that we can route
* responses to the appropriate port. This relies on the fact that
* the underlying Request pointer inside the Packet stays
* constant.
*/
std::unordered_map<RequestPtr, PortID> routeTo;
/** all contigous ranges seen by this crossbar */
AddrRangeList xbarRanges;
AddrRange defaultRange;
/**
* Function called by the port when the crossbar is recieving a
* range change.
*
* @param master_port_id id of the port that received the change
*/
virtual void recvRangeChange(PortID master_port_id);
/**
* Find which port connected to this crossbar (if any) should be
* given a packet with this address range.
*
* @param addr_range Address range to find port for.
* @return id of port that the packet should be sent out of.
*/
PortID findPort(AddrRange addr_range);
/**
* Return the address ranges the crossbar is responsible for.
*
* @return a list of non-overlapping address ranges
*/
AddrRangeList getAddrRanges() const;
/**
* Calculate the timing parameters for the packet. Updates the
* headerDelay and payloadDelay fields of the packet
* object with the relative number of ticks required to transmit
* the header and the payload, respectively.
*
* @param pkt Packet to populate with timings
* @param header_delay Header delay to be added
*/
void calcPacketTiming(PacketPtr pkt, Tick header_delay);
/**
* Remember for each of the master ports of the crossbar if we got
* an address range from the connected slave. For convenience,
* also keep track of if we got ranges from all the slave modules
* or not.
*/
std::vector<bool> gotAddrRanges;
bool gotAllAddrRanges;
/** The master and slave ports of the crossbar */
std::vector<QueuedSlavePort*> slavePorts;
std::vector<MasterPort*> masterPorts;
/** Port that handles requests that don't match any of the interfaces.*/
PortID defaultPortID;
/** If true, use address range provided by default device. Any
address not handled by another port and not in default device's
range will cause a fatal error. If false, just send all
addresses not handled by another port to default device. */
const bool useDefaultRange;
BaseXBar(const BaseXBarParams *p);
/**
* Stats for transaction distribution and data passing through the
* crossbar. The transaction distribution is globally counting
* different types of commands. The packet count and total packet
* size are two-dimensional vectors that are indexed by the
* slave port and master port id (thus the neighbouring master and
* neighbouring slave), summing up both directions (request and
* response).
*/
Stats::Vector transDist;
Stats::Vector2d pktCount;
Stats::Vector2d pktSize;
public:
virtual ~BaseXBar();
void init() override;
/** A function used to return the port associated with this object. */
Port &getPort(const std::string &if_name,
PortID idx=InvalidPortID) override;
void regStats() override;
};
#endif //__MEM_XBAR_HH__
<commit_msg>mem: Deleting this init() method was accidentally dropped during rebase.<commit_after>/*
* Copyright (c) 2011-2015, 2018 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ron Dreslinski
* Ali Saidi
* Andreas Hansson
* William Wang
*/
/**
* @file
* Declaration of an abstract crossbar base class.
*/
#ifndef __MEM_XBAR_HH__
#define __MEM_XBAR_HH__
#include <deque>
#include <unordered_map>
#include "base/addr_range_map.hh"
#include "base/types.hh"
#include "mem/mem_object.hh"
#include "mem/qport.hh"
#include "params/BaseXBar.hh"
#include "sim/stats.hh"
/**
* The base crossbar contains the common elements of the non-coherent
* and coherent crossbar. It is an abstract class that does not have
* any of the functionality relating to the actual reception and
* transmission of packets, as this is left for the subclasses.
*
* The BaseXBar is responsible for the basic flow control (busy or
* not), the administration of retries, and the address decoding.
*/
class BaseXBar : public MemObject
{
protected:
/**
* A layer is an internal crossbar arbitration point with its own
* flow control. Each layer is a converging multiplexer tree. By
* instantiating one layer per destination port (and per packet
* type, i.e. request, response, snoop request and snoop
* response), we model full crossbar structures like AXI, ACE,
* PCIe, etc.
*
* The template parameter, PortClass, indicates the destination
* port type for the layer. The retry list holds either master
* ports or slave ports, depending on the direction of the
* layer. Thus, a request layer has a retry list containing slave
* ports, whereas a response layer holds master ports.
*/
template <typename SrcType, typename DstType>
class Layer : public Drainable
{
public:
/**
* Create a layer and give it a name. The layer uses
* the crossbar an event manager.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
Layer(DstType& _port, BaseXBar& _xbar, const std::string& _name);
/**
* Drain according to the normal semantics, so that the crossbar
* can tell the layer to drain, and pass an event to signal
* back when drained.
*
* @param de drain event to call once drained
*
* @return 1 if busy or waiting to retry, or 0 if idle
*/
DrainState drain() override;
const std::string name() const { return xbar.name() + _name; }
/**
* Determine if the layer accepts a packet from a specific
* port. If not, the port in question is also added to the
* retry list. In either case the state of the layer is
* updated accordingly.
*
* @param port Source port presenting the packet
*
* @return True if the layer accepts the packet
*/
bool tryTiming(SrcType* src_port);
/**
* Deal with a destination port accepting a packet by potentially
* removing the source port from the retry list (if retrying) and
* occupying the layer accordingly.
*
* @param busy_time Time to spend as a result of a successful send
*/
void succeededTiming(Tick busy_time);
/**
* Deal with a destination port not accepting a packet by
* potentially adding the source port to the retry list (if
* not already at the front) and occupying the layer
* accordingly.
*
* @param src_port Source port
* @param busy_time Time to spend as a result of a failed send
*/
void failedTiming(SrcType* src_port, Tick busy_time);
void occupyLayer(Tick until);
/**
* Send a retry to the port at the head of waitingForLayer. The
* caller must ensure that the list is not empty.
*/
void retryWaiting();
/**
* Handle a retry from a neighbouring module. This wraps
* retryWaiting by verifying that there are ports waiting
* before calling retryWaiting.
*/
void recvRetry();
void regStats();
protected:
/**
* Sending the actual retry, in a manner specific to the
* individual layers. Note that for a MasterPort, there is
* both a RequestLayer and a SnoopResponseLayer using the same
* port, but using different functions for the flow control.
*/
virtual void sendRetry(SrcType* retry_port) = 0;
private:
/** The destination port this layer converges at. */
DstType& port;
/** The crossbar this layer is a part of. */
BaseXBar& xbar;
std::string _name;
/**
* We declare an enum to track the state of the layer. The
* starting point is an idle state where the layer is waiting
* for a packet to arrive. Upon arrival, the layer
* transitions to the busy state, where it remains either
* until the packet transfer is done, or the header time is
* spent. Once the layer leaves the busy state, it can
* either go back to idle, if no packets have arrived while it
* was busy, or the layer goes on to retry the first port
* in waitingForLayer. A similar transition takes place from
* idle to retry if the layer receives a retry from one of
* its connected ports. The retry state lasts until the port
* in questions calls sendTiming and returns control to the
* layer, or goes to a busy state if the port does not
* immediately react to the retry by calling sendTiming.
*/
enum State { IDLE, BUSY, RETRY };
State state;
/**
* A deque of ports that retry should be called on because
* the original send was delayed due to a busy layer.
*/
std::deque<SrcType*> waitingForLayer;
/**
* Track who is waiting for the retry when receiving it from a
* peer. If no port is waiting NULL is stored.
*/
SrcType* waitingForPeer;
/**
* Release the layer after being occupied and return to an
* idle state where we proceed to send a retry to any
* potential waiting port, or drain if asked to do so.
*/
void releaseLayer();
EventFunctionWrapper releaseEvent;
/**
* Stats for occupancy and utilization. These stats capture
* the time the layer spends in the busy state and are thus only
* relevant when the memory system is in timing mode.
*/
Stats::Scalar occupancy;
Stats::Formula utilization;
};
class ReqLayer : public Layer<SlavePort, MasterPort>
{
public:
/**
* Create a request layer and give it a name.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
ReqLayer(MasterPort& _port, BaseXBar& _xbar, const std::string& _name) :
Layer(_port, _xbar, _name)
{}
protected:
void
sendRetry(SlavePort* retry_port) override
{
retry_port->sendRetryReq();
}
};
class RespLayer : public Layer<MasterPort, SlavePort>
{
public:
/**
* Create a response layer and give it a name.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
RespLayer(SlavePort& _port, BaseXBar& _xbar,
const std::string& _name) :
Layer(_port, _xbar, _name)
{}
protected:
void
sendRetry(MasterPort* retry_port) override
{
retry_port->sendRetryResp();
}
};
class SnoopRespLayer : public Layer<SlavePort, MasterPort>
{
public:
/**
* Create a snoop response layer and give it a name.
*
* @param _port destination port the layer converges at
* @param _xbar the crossbar this layer belongs to
* @param _name the layer's name
*/
SnoopRespLayer(MasterPort& _port, BaseXBar& _xbar,
const std::string& _name) :
Layer(_port, _xbar, _name)
{}
protected:
void
sendRetry(SlavePort* retry_port) override
{
retry_port->sendRetrySnoopResp();
}
};
/**
* Cycles of front-end pipeline including the delay to accept the request
* and to decode the address.
*/
const Cycles frontendLatency;
const Cycles forwardLatency;
const Cycles responseLatency;
/** the width of the xbar in bytes */
const uint32_t width;
AddrRangeMap<PortID, 3> portMap;
/**
* Remember where request packets came from so that we can route
* responses to the appropriate port. This relies on the fact that
* the underlying Request pointer inside the Packet stays
* constant.
*/
std::unordered_map<RequestPtr, PortID> routeTo;
/** all contigous ranges seen by this crossbar */
AddrRangeList xbarRanges;
AddrRange defaultRange;
/**
* Function called by the port when the crossbar is recieving a
* range change.
*
* @param master_port_id id of the port that received the change
*/
virtual void recvRangeChange(PortID master_port_id);
/**
* Find which port connected to this crossbar (if any) should be
* given a packet with this address range.
*
* @param addr_range Address range to find port for.
* @return id of port that the packet should be sent out of.
*/
PortID findPort(AddrRange addr_range);
/**
* Return the address ranges the crossbar is responsible for.
*
* @return a list of non-overlapping address ranges
*/
AddrRangeList getAddrRanges() const;
/**
* Calculate the timing parameters for the packet. Updates the
* headerDelay and payloadDelay fields of the packet
* object with the relative number of ticks required to transmit
* the header and the payload, respectively.
*
* @param pkt Packet to populate with timings
* @param header_delay Header delay to be added
*/
void calcPacketTiming(PacketPtr pkt, Tick header_delay);
/**
* Remember for each of the master ports of the crossbar if we got
* an address range from the connected slave. For convenience,
* also keep track of if we got ranges from all the slave modules
* or not.
*/
std::vector<bool> gotAddrRanges;
bool gotAllAddrRanges;
/** The master and slave ports of the crossbar */
std::vector<QueuedSlavePort*> slavePorts;
std::vector<MasterPort*> masterPorts;
/** Port that handles requests that don't match any of the interfaces.*/
PortID defaultPortID;
/** If true, use address range provided by default device. Any
address not handled by another port and not in default device's
range will cause a fatal error. If false, just send all
addresses not handled by another port to default device. */
const bool useDefaultRange;
BaseXBar(const BaseXBarParams *p);
/**
* Stats for transaction distribution and data passing through the
* crossbar. The transaction distribution is globally counting
* different types of commands. The packet count and total packet
* size are two-dimensional vectors that are indexed by the
* slave port and master port id (thus the neighbouring master and
* neighbouring slave), summing up both directions (request and
* response).
*/
Stats::Vector transDist;
Stats::Vector2d pktCount;
Stats::Vector2d pktSize;
public:
virtual ~BaseXBar();
/** A function used to return the port associated with this object. */
Port &getPort(const std::string &if_name,
PortID idx=InvalidPortID) override;
void regStats() override;
};
#endif //__MEM_XBAR_HH__
<|endoftext|>
|
<commit_before>#include <iomanip>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include "message.h"
#include "status.h"
using std::move;
using std::ostream;
using std::ostringstream;
using std::string;
using std::unique_ptr;
ostream &operator<<(ostream &out, FileSystemAction action)
{
switch (action) {
case ACTION_CREATED: out << "created"; break;
case ACTION_DELETED: out << "deleted"; break;
case ACTION_MODIFIED: out << "modified"; break;
case ACTION_RENAMED: out << "renamed"; break;
default: out << "!! FileSystemAction=" << static_cast<int>(action);
}
return out;
}
ostream &operator<<(ostream &out, EntryKind kind)
{
switch (kind) {
case KIND_FILE: out << "file"; break;
case KIND_DIRECTORY: out << "directory"; break;
case KIND_UNKNOWN: out << "unknown"; break;
default: out << "!! EntryKind=" << static_cast<int>(kind);
}
return out;
}
bool kinds_are_different(EntryKind a, EntryKind b)
{
return a != KIND_UNKNOWN && b != KIND_UNKNOWN && a != b;
}
FileSystemPayload::FileSystemPayload(ChannelID channel_id,
FileSystemAction action,
EntryKind entry_kind,
string &&old_path,
string &&path) :
channel_id{channel_id},
action{action},
entry_kind{entry_kind},
old_path{move(old_path)},
path{move(path)}
{
//
}
FileSystemPayload::FileSystemPayload(FileSystemPayload &&original) noexcept :
channel_id{original.channel_id},
action{original.action},
entry_kind{original.entry_kind},
old_path{move(original.old_path)},
path{move(original.path)}
{
//
}
string FileSystemPayload::describe() const
{
ostringstream builder;
builder << "[FileSystemPayload channel " << channel_id << " " << entry_kind;
builder << " " << action;
if (!old_path.empty()) {
builder << " {" << old_path << " => " << path << "}";
} else {
builder << " " << path;
}
builder << "]";
return builder.str();
}
CommandPayload::CommandPayload(CommandAction action,
CommandID id,
std::string &&root,
uint_fast32_t arg,
bool recursive,
size_t split_count) :
id{id},
action{action},
root{move(root)},
arg{arg},
recursive{recursive},
split_count{split_count}
{
//
}
CommandPayload::CommandPayload(const CommandPayload &original) :
id{original.id},
action{original.action},
root{original.root},
arg{original.arg},
recursive{original.recursive},
split_count{original.split_count}
{
//
}
CommandPayload::CommandPayload(CommandPayload &&original) noexcept :
id{original.id},
action{original.action},
root{move(original.root)},
arg{original.arg},
recursive{original.recursive},
split_count{original.split_count}
{
//
}
string CommandPayload::describe() const
{
ostringstream builder;
builder << "[CommandPayload id " << id << " ";
switch (action) {
case COMMAND_ADD:
builder << "add " << root << " at channel " << arg;
if (!recursive) builder << " (non-recursively)";
break;
case COMMAND_REMOVE: builder << "remove channel " << arg; break;
case COMMAND_LOG_FILE: builder << "log to file " << root; break;
case COMMAND_LOG_DISABLE: builder << "disable logging"; break;
case COMMAND_POLLING_INTERVAL: builder << "polling interval " << arg; break;
case COMMAND_POLLING_THROTTLE: builder << "polling throttle " << arg; break;
case COMMAND_DRAIN: builder << "drain"; break;
case COMMAND_STATUS: builder << "status request " << arg; break;
default: builder << "!!action=" << action; break;
}
if (split_count > 1) {
builder << " split x" << split_count;
}
builder << "]";
return builder.str();
}
AckPayload::AckPayload(CommandID key, ChannelID channel_id, bool success, string &&message) :
key{key},
channel_id{channel_id},
success{success},
message{move(message)}
{
//
}
string AckPayload::describe() const
{
ostringstream builder;
builder << "[AckPayload ack " << key << "]";
return builder.str();
}
ErrorPayload::ErrorPayload(ChannelID channel_id, std::string &&message, bool fatal) :
channel_id{channel_id},
message{move(message)},
fatal{fatal}
{
//
}
string ErrorPayload::describe() const
{
ostringstream builder;
builder << "[ErrorPayload channel " << channel_id << " message \"" << message << '"';
if (fatal) builder << " fatal!";
builder << "]";
return builder.str();
}
StatusPayload::StatusPayload(RequestID request_id, unique_ptr<Status> &&status) :
request_id{request_id},
status{move(status)}
{
//
}
string StatusPayload::describe() const
{
ostringstream builder;
builder << "[StatusPayload request " << request_id << "]";
return builder.str();
}
const FileSystemPayload *Message::as_filesystem() const
{
return kind == MSG_FILESYSTEM ? &filesystem_payload : nullptr;
}
const CommandPayload *Message::as_command() const
{
return kind == MSG_COMMAND ? &command_payload : nullptr;
}
const AckPayload *Message::as_ack() const
{
return kind == MSG_ACK ? &ack_payload : nullptr;
}
const ErrorPayload *Message::as_error() const
{
return kind == MSG_ERROR ? &error_payload : nullptr;
}
const StatusPayload *Message::as_status() const
{
return kind == MSG_STATUS ? &status_payload : nullptr;
}
Message Message::ack(const Message &original, bool success, string &&message)
{
const CommandPayload *payload = original.as_command();
assert(payload != nullptr);
return Message(AckPayload(payload->get_id(), payload->get_channel_id(), success, move(message)));
}
Message Message::ack(const Message &original, const Result<> &result)
{
if (result.is_ok()) {
return ack(original, true, "");
}
return ack(original, false, string(result.get_error()));
}
Message::Message(FileSystemPayload &&payload) : kind{MSG_FILESYSTEM}, filesystem_payload{move(payload)}
{
//
}
Message::Message(CommandPayload &&payload) : kind{MSG_COMMAND}, command_payload{move(payload)}
{
//
}
Message::Message(AckPayload &&payload) : kind{MSG_ACK}, ack_payload{move(payload)}
{
//
}
Message::Message(ErrorPayload &&payload) : kind{MSG_ERROR}, error_payload{move(payload)}
{
//
}
Message::Message(StatusPayload &&payload) : kind{MSG_STATUS}, status_payload{move(payload)}
{
//
}
Message::Message(Message &&original) noexcept : kind{original.kind}, pending{true}
{
switch (kind) {
case MSG_FILESYSTEM: new (&filesystem_payload) FileSystemPayload(move(original.filesystem_payload)); break;
case MSG_COMMAND: new (&command_payload) CommandPayload(move(original.command_payload)); break;
case MSG_ACK: new (&ack_payload) AckPayload(move(original.ack_payload)); break;
case MSG_ERROR: new (&error_payload) ErrorPayload(move(original.error_payload)); break;
case MSG_STATUS: new (&status_payload) StatusPayload(move(original.status_payload)); break;
};
}
Message::~Message()
{
switch (kind) {
case MSG_FILESYSTEM: filesystem_payload.~FileSystemPayload(); break;
case MSG_COMMAND: command_payload.~CommandPayload(); break;
case MSG_ACK: ack_payload.~AckPayload(); break;
case MSG_ERROR: error_payload.~ErrorPayload(); break;
case MSG_STATUS: status_payload.~StatusPayload(); break;
};
}
string Message::describe() const
{
ostringstream builder;
builder << "[Message ";
switch (kind) {
case MSG_FILESYSTEM: builder << filesystem_payload; break;
case MSG_COMMAND: builder << command_payload; break;
case MSG_ACK: builder << ack_payload; break;
case MSG_ERROR: builder << error_payload; break;
case MSG_STATUS: builder << status_payload; break;
default: builder << "!!kind=" << kind; break;
};
builder << "]";
return builder.str();
}
std::ostream &operator<<(std::ostream &stream, const FileSystemPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const CommandPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const AckPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const ErrorPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const StatusPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const Message &e)
{
stream << e.describe();
return stream;
}
<commit_msg>Cache size command string rep<commit_after>#include <iomanip>
#include <memory>
#include <sstream>
#include <string>
#include <utility>
#include "message.h"
#include "status.h"
using std::move;
using std::ostream;
using std::ostringstream;
using std::string;
using std::unique_ptr;
ostream &operator<<(ostream &out, FileSystemAction action)
{
switch (action) {
case ACTION_CREATED: out << "created"; break;
case ACTION_DELETED: out << "deleted"; break;
case ACTION_MODIFIED: out << "modified"; break;
case ACTION_RENAMED: out << "renamed"; break;
default: out << "!! FileSystemAction=" << static_cast<int>(action);
}
return out;
}
ostream &operator<<(ostream &out, EntryKind kind)
{
switch (kind) {
case KIND_FILE: out << "file"; break;
case KIND_DIRECTORY: out << "directory"; break;
case KIND_UNKNOWN: out << "unknown"; break;
default: out << "!! EntryKind=" << static_cast<int>(kind);
}
return out;
}
bool kinds_are_different(EntryKind a, EntryKind b)
{
return a != KIND_UNKNOWN && b != KIND_UNKNOWN && a != b;
}
FileSystemPayload::FileSystemPayload(ChannelID channel_id,
FileSystemAction action,
EntryKind entry_kind,
string &&old_path,
string &&path) :
channel_id{channel_id},
action{action},
entry_kind{entry_kind},
old_path{move(old_path)},
path{move(path)}
{
//
}
FileSystemPayload::FileSystemPayload(FileSystemPayload &&original) noexcept :
channel_id{original.channel_id},
action{original.action},
entry_kind{original.entry_kind},
old_path{move(original.old_path)},
path{move(original.path)}
{
//
}
string FileSystemPayload::describe() const
{
ostringstream builder;
builder << "[FileSystemPayload channel " << channel_id << " " << entry_kind;
builder << " " << action;
if (!old_path.empty()) {
builder << " {" << old_path << " => " << path << "}";
} else {
builder << " " << path;
}
builder << "]";
return builder.str();
}
CommandPayload::CommandPayload(CommandAction action,
CommandID id,
std::string &&root,
uint_fast32_t arg,
bool recursive,
size_t split_count) :
id{id},
action{action},
root{move(root)},
arg{arg},
recursive{recursive},
split_count{split_count}
{
//
}
CommandPayload::CommandPayload(const CommandPayload &original) :
id{original.id},
action{original.action},
root{original.root},
arg{original.arg},
recursive{original.recursive},
split_count{original.split_count}
{
//
}
CommandPayload::CommandPayload(CommandPayload &&original) noexcept :
id{original.id},
action{original.action},
root{move(original.root)},
arg{original.arg},
recursive{original.recursive},
split_count{original.split_count}
{
//
}
string CommandPayload::describe() const
{
ostringstream builder;
builder << "[CommandPayload id " << id << " ";
switch (action) {
case COMMAND_ADD:
builder << "add " << root << " at channel " << arg;
if (!recursive) builder << " (non-recursively)";
break;
case COMMAND_REMOVE: builder << "remove channel " << arg; break;
case COMMAND_LOG_FILE: builder << "log to file " << root; break;
case COMMAND_LOG_DISABLE: builder << "disable logging"; break;
case COMMAND_POLLING_INTERVAL: builder << "polling interval " << arg; break;
case COMMAND_POLLING_THROTTLE: builder << "polling throttle " << arg; break;
case COMMAND_CACHE_SIZE: builder << "cache size " << arg; break;
case COMMAND_DRAIN: builder << "drain"; break;
case COMMAND_STATUS: builder << "status request " << arg; break;
default: builder << "!!action=" << action; break;
}
if (split_count > 1) {
builder << " split x" << split_count;
}
builder << "]";
return builder.str();
}
AckPayload::AckPayload(CommandID key, ChannelID channel_id, bool success, string &&message) :
key{key},
channel_id{channel_id},
success{success},
message{move(message)}
{
//
}
string AckPayload::describe() const
{
ostringstream builder;
builder << "[AckPayload ack " << key << "]";
return builder.str();
}
ErrorPayload::ErrorPayload(ChannelID channel_id, std::string &&message, bool fatal) :
channel_id{channel_id},
message{move(message)},
fatal{fatal}
{
//
}
string ErrorPayload::describe() const
{
ostringstream builder;
builder << "[ErrorPayload channel " << channel_id << " message \"" << message << '"';
if (fatal) builder << " fatal!";
builder << "]";
return builder.str();
}
StatusPayload::StatusPayload(RequestID request_id, unique_ptr<Status> &&status) :
request_id{request_id},
status{move(status)}
{
//
}
string StatusPayload::describe() const
{
ostringstream builder;
builder << "[StatusPayload request " << request_id << "]";
return builder.str();
}
const FileSystemPayload *Message::as_filesystem() const
{
return kind == MSG_FILESYSTEM ? &filesystem_payload : nullptr;
}
const CommandPayload *Message::as_command() const
{
return kind == MSG_COMMAND ? &command_payload : nullptr;
}
const AckPayload *Message::as_ack() const
{
return kind == MSG_ACK ? &ack_payload : nullptr;
}
const ErrorPayload *Message::as_error() const
{
return kind == MSG_ERROR ? &error_payload : nullptr;
}
const StatusPayload *Message::as_status() const
{
return kind == MSG_STATUS ? &status_payload : nullptr;
}
Message Message::ack(const Message &original, bool success, string &&message)
{
const CommandPayload *payload = original.as_command();
assert(payload != nullptr);
return Message(AckPayload(payload->get_id(), payload->get_channel_id(), success, move(message)));
}
Message Message::ack(const Message &original, const Result<> &result)
{
if (result.is_ok()) {
return ack(original, true, "");
}
return ack(original, false, string(result.get_error()));
}
Message::Message(FileSystemPayload &&payload) : kind{MSG_FILESYSTEM}, filesystem_payload{move(payload)}
{
//
}
Message::Message(CommandPayload &&payload) : kind{MSG_COMMAND}, command_payload{move(payload)}
{
//
}
Message::Message(AckPayload &&payload) : kind{MSG_ACK}, ack_payload{move(payload)}
{
//
}
Message::Message(ErrorPayload &&payload) : kind{MSG_ERROR}, error_payload{move(payload)}
{
//
}
Message::Message(StatusPayload &&payload) : kind{MSG_STATUS}, status_payload{move(payload)}
{
//
}
Message::Message(Message &&original) noexcept : kind{original.kind}, pending{true}
{
switch (kind) {
case MSG_FILESYSTEM: new (&filesystem_payload) FileSystemPayload(move(original.filesystem_payload)); break;
case MSG_COMMAND: new (&command_payload) CommandPayload(move(original.command_payload)); break;
case MSG_ACK: new (&ack_payload) AckPayload(move(original.ack_payload)); break;
case MSG_ERROR: new (&error_payload) ErrorPayload(move(original.error_payload)); break;
case MSG_STATUS: new (&status_payload) StatusPayload(move(original.status_payload)); break;
};
}
Message::~Message()
{
switch (kind) {
case MSG_FILESYSTEM: filesystem_payload.~FileSystemPayload(); break;
case MSG_COMMAND: command_payload.~CommandPayload(); break;
case MSG_ACK: ack_payload.~AckPayload(); break;
case MSG_ERROR: error_payload.~ErrorPayload(); break;
case MSG_STATUS: status_payload.~StatusPayload(); break;
};
}
string Message::describe() const
{
ostringstream builder;
builder << "[Message ";
switch (kind) {
case MSG_FILESYSTEM: builder << filesystem_payload; break;
case MSG_COMMAND: builder << command_payload; break;
case MSG_ACK: builder << ack_payload; break;
case MSG_ERROR: builder << error_payload; break;
case MSG_STATUS: builder << status_payload; break;
default: builder << "!!kind=" << kind; break;
};
builder << "]";
return builder.str();
}
std::ostream &operator<<(std::ostream &stream, const FileSystemPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const CommandPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const AckPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const ErrorPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const StatusPayload &e)
{
stream << e.describe();
return stream;
}
std::ostream &operator<<(std::ostream &stream, const Message &e)
{
stream << e.describe();
return stream;
}
<|endoftext|>
|
<commit_before>/*************************************************
* MP Misc Functions Source File *
* (C) 1999-2006 The Botan Project *
*************************************************/
#include <botan/mp_core.h>
#include <botan/mp_asm.h>
namespace Botan {
extern "C" {
/*************************************************
* Core Division Operation *
*************************************************/
u32bit bigint_divcore(word q, word y1, word y2,
word x1, word x2, word x3)
{
word y0 = 0;
y2 = word_madd2(q, y2, y0, &y0);
y1 = word_madd2(q, y1, y0, &y0);
if(y0 > x1) return 1;
if(y0 < x1) return 0;
if(y1 > x2) return 1;
if(y1 < x2) return 0;
if(y2 > x3) return 1;
if(y2 < x3) return 0;
return 0;
}
/*************************************************
* Compare two MP integers *
*************************************************/
s32bit bigint_cmp(const word x[], u32bit x_size,
const word y[], u32bit y_size)
{
if(x_size < y_size) { return (-bigint_cmp(y, y_size, x, x_size)); }
while(x_size > y_size)
{
if(x[x_size-1])
return 1;
x_size--;
}
for(u32bit j = x_size; j > 0; --j)
{
if(x[j-1] > y[j-1]) return 1;
if(x[j-1] < y[j-1]) return -1;
}
return 0;
}
/*************************************************
* Do a 2-word/1-word Division *
*************************************************/
word bigint_divop(word n1, word n0, word d)
{
word high = n1 % d;
word quotient = 0;
for(u32bit j = 0; j != MP_WORD_BITS; ++j)
{
const word mask = (word)1 << (MP_WORD_BITS-1-j);
const bool high_top_bit = (high & MP_WORD_TOP_BIT) ? true : false;
high = (high << 1) | ((n0 & mask) >> (MP_WORD_BITS-1-j));
if(high_top_bit || high >= d)
{
high -= d;
quotient |= mask;
}
}
return quotient;
}
/*************************************************
* Do a 2-word/1-word Modulo *
*************************************************/
word bigint_modop(word n1, word n0, word d)
{
word z = bigint_divop(n1, n0, d);
word dummy = 0;
z = word_madd2(z, d, dummy, &dummy);
return (n0-z);
}
/*************************************************
* Do a word*word->2-word Multiply *
*************************************************/
void bigint_wordmul(word a, word b, word* out_low, word* out_high)
{
const u32bit MP_HWORD_BITS = MP_WORD_BITS / 2;
const word MP_HWORD_MASK = ((word)1 << MP_HWORD_BITS) - 1;
const word a_hi = (a >> MP_HWORD_BITS);
const word a_lo = (a & MP_HWORD_MASK);
const word b_hi = (b >> MP_HWORD_BITS);
const word b_lo = (b & MP_HWORD_MASK);
word x0 = a_hi * b_hi;
word x1 = a_lo * b_hi;
word x2 = a_hi * b_lo;
word x3 = a_lo * b_lo;
x2 += x3 >> (MP_HWORD_BITS);
x2 += x1;
if(x2 < x1)
x0 += ((word)1 << MP_HWORD_BITS);
*out_high = x0 + (x2 >> MP_HWORD_BITS);
*out_low = ((x2 & MP_HWORD_MASK) << MP_HWORD_BITS) + (x3 & MP_HWORD_MASK);
}
}
}
<commit_msg>Simplify the implementation of bigint_divop<commit_after>/*************************************************
* MP Misc Functions Source File *
* (C) 1999-2006 The Botan Project *
*************************************************/
#include <botan/mp_core.h>
#include <botan/mp_asm.h>
namespace Botan {
extern "C" {
/*************************************************
* Core Division Operation *
*************************************************/
u32bit bigint_divcore(word q, word y1, word y2,
word x1, word x2, word x3)
{
word y0 = 0;
y2 = word_madd2(q, y2, y0, &y0);
y1 = word_madd2(q, y1, y0, &y0);
if(y0 > x1) return 1;
if(y0 < x1) return 0;
if(y1 > x2) return 1;
if(y1 < x2) return 0;
if(y2 > x3) return 1;
if(y2 < x3) return 0;
return 0;
}
/*************************************************
* Compare two MP integers *
*************************************************/
s32bit bigint_cmp(const word x[], u32bit x_size,
const word y[], u32bit y_size)
{
if(x_size < y_size) { return (-bigint_cmp(y, y_size, x, x_size)); }
while(x_size > y_size)
{
if(x[x_size-1])
return 1;
x_size--;
}
for(u32bit j = x_size; j > 0; --j)
{
if(x[j-1] > y[j-1]) return 1;
if(x[j-1] < y[j-1]) return -1;
}
return 0;
}
/*************************************************
* Do a 2-word/1-word Division *
*************************************************/
word bigint_divop(word n1, word n0, word d)
{
word high = n1 % d, quotient = 0;
for(u32bit j = 0; j != MP_WORD_BITS; ++j)
{
const bool high_top_bit = (high & MP_WORD_TOP_BIT);
high <<= 1;
high |= (n0 >> MP_WORD_BITS-1-j) & 1;
quotient <<= 1;
if(high_top_bit || high >= d)
{
high -= d;
quotient |= 1;
}
}
return quotient;
}
/*************************************************
* Do a 2-word/1-word Modulo *
*************************************************/
word bigint_modop(word n1, word n0, word d)
{
word z = bigint_divop(n1, n0, d);
word dummy = 0;
z = word_madd2(z, d, dummy, &dummy);
return (n0-z);
}
/*************************************************
* Do a word*word->2-word Multiply *
*************************************************/
void bigint_wordmul(word a, word b, word* out_low, word* out_high)
{
const u32bit MP_HWORD_BITS = MP_WORD_BITS / 2;
const word MP_HWORD_MASK = ((word)1 << MP_HWORD_BITS) - 1;
const word a_hi = (a >> MP_HWORD_BITS);
const word a_lo = (a & MP_HWORD_MASK);
const word b_hi = (b >> MP_HWORD_BITS);
const word b_lo = (b & MP_HWORD_MASK);
word x0 = a_hi * b_hi;
word x1 = a_lo * b_hi;
word x2 = a_hi * b_lo;
word x3 = a_lo * b_lo;
x2 += x3 >> (MP_HWORD_BITS);
x2 += x1;
if(x2 < x1)
x0 += ((word)1 << MP_HWORD_BITS);
*out_high = x0 + (x2 >> MP_HWORD_BITS);
*out_low = ((x2 & MP_HWORD_MASK) << MP_HWORD_BITS) + (x3 & MP_HWORD_MASK);
}
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright 2017 Shusheng Shao <iblackangel@163.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.
*/
#include <mpl/mstring.h>
#ifdef _MSC_VER
# pragma warning (push)
# pragma warning (disable: 4996)
#endif
MPL_BEGIN_NAMESPACE
std::string toXString(const char *fmt, ...)
{
std::string buffer;
va_list vargs;
va_start(vargs, fmt);
int len = vsnprintf(NULL, 0, fmt, vargs);
buffer.resize(len);
va_start(vargs, fmt);
vsnprintf(&buffer[0], len + 1, fmt, vargs);
va_end(vargs);
return buffer;
}
std::string hex2str(const uint8_t *data, size_t len)
{
std::string buffer;
char buf[3] = {0x00};
for (size_t m = 0; m < len; ++m) {
snprintf (buf, sizeof(buf), "%02X", data[m]);
buf[2] = '\0';
buffer += buf;
buffer += " ";
}
if (buffer.size() > 0) {
buffer.erase(buffer.begin() + (buffer.size() - 1));
}
return buffer;
}
std::string toString(char val)
{
return toXString("%c", val);
}
std::string toString(int val)
{
return toXString("%d", val);
}
std::string toString(unsigned val)
{
return toXString("%u", val);
}
std::string toString(long val)
{
return toXString("%ld", val);
}
std::string toString(unsigned long val)
{
return toXString("%lu", val);
}
std::string toString(long long val)
{
return toXString("%lld", val);
}
std::string toString(unsigned long long val)
{
return toXString("%llu", val);
}
std::string toString(float val)
{
return toXString("%f", val);
}
std::string toString(double val)
{
return toXString("%f", val);
}
std::string toString(long double val)
{
return toXString("%Lf", val);
}
std::string toUTF8(const std::string &str)
{
#if defined(_MSC_VER) || defined(M_OS_WIN)
// convert GBK to Unicode
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
wchar_t *strUnicode = new wchar_t[len];
wmemset(strUnicode, 0, len);
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strUnicode, len);
// convert Unicode to UTF-8
len = WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, NULL, 0, NULL, NULL);
char * strUtf8 = new char[len];
WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, strUtf8, len, NULL, NULL);
std::string strOut(strUtf8); // strTemp is encoding UTF-8
delete[]strUnicode;
delete[]strUtf8;
strUnicode = NULL;
strUtf8 = NULL;
return strOut;
#elif defined(HAVE_ICONV_H)
char *gbk = new char[str.size() + 1];
size_t inbytes = str.size();
strcpy(gbk, str.c_str());
char *utf8 = new char[str.size() * 2 + 1]; // twice of gbk
size_t outbytes = str.size() * 2;
char *inptr = gbk;
char *outptr = utf8;
// iconv_open
iconv_t cd = iconv_open("UTF-8", "GB18030");
if (cd == (iconv_t)-1) {
log_error("iconv_open failed: %s", error().c_str());
delete gbk;
delete utf8;
return std::string();
}
// iconv
size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes);
if (res == -1) {
log_error("iconv failed: %s", error().c_str());
iconv_close(cd);
delete gbk;
delete utf8;
return std::string();
}
// iconv_close
std::string outstr = utf8;
iconv_close(cd);
delete gbk;
delete utf8;
return outstr;
#else
return str;
#endif
}
std::string toGBK(const std::string &str)
{
#if defined(_MSC_VER) || defined(M_OS_WIN)
// convert UTF-8 to Unicode
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
unsigned short *wszGBK = new unsigned short[len + 1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)str.c_str(), -1, (LPWSTR)wszGBK, len);
// convert UTF-8 to Unicode
len = WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, szGBK, len, NULL, NULL);
std::string strTemp(szGBK);
delete[]szGBK;
delete[]wszGBK;
return strTemp;
#elif defined(HAVE_ICONV_H)
char *utf8 = new char[str.size() + 1];
size_t inbytes = str.size();
strcpy(utf8, str.c_str());
char *gbk = new char[str.size() * 2 + 1]; // twice size
size_t outbytes = str.size() * 2;
char *inptr = utf8;
char *outptr = gbk;
// iconv_open
iconv_t cd = iconv_open("GB18030", "UTF-8");
if (cd == (iconv_t)-1) {
log_error("iconv_open failed: %s", error().c_str());
delete gbk;
delete utf8;
return std::string();
}
// iconv
size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes);
if (res == -1) {
log_error("iconv failed: %s", error().c_str());
iconv_close(cd);
delete gbk;
delete utf8;
return std::string();
}
// iconv_close
std::string outstr = gbk;
iconv_close(cd);
delete gbk;
delete utf8;
return outstr;
#else
return str;
#endif
}
std::vector<std::string> split(const std::string &src, const std::string &delim)
{
std::vector<std::string> res;
if (src.empty() || delim.empty())
return res;
std::string::size_type start = 0;
std::string::size_type pos = std::string::npos;
while ((pos = src.find(delim, start)) != std::string::npos) {
res.push_back(src.substr(start, pos - start));
start = pos + delim.size();
}
res.push_back(src.substr(start));
return res;
}
std::string trim(const std::string &src)
{
return trim_front(trim_back(src));
}
std::string trim_front(const std::string &src)
{
return src.substr(src.find_first_not_of(" \n\r\t"));
}
std::string trim_back(const std::string &src)
{
return src.substr(0, src.find_last_not_of(" \n\r\t") + 1);
}
void tolower(std::string &src)
{
transform(src.begin(), src.end(), src.begin(), ::tolower);
}
void toupper(std::string &src)
{
transform(src.begin(), src.end(), src.begin(), ::toupper);
}
MString::MString()
{
}
MString::MString(const std::string &str)
: std::string(str)
{
}
MString::MString(const char *s)
: std::string(s)
{
}
MString::~MString()
{
}
std::string& MString::replace(char before, char after)
{
size_type pos = rfind(before);
while (pos != npos) {
std::string::replace(pos, 1, 1, after);
pos = rfind(before);
}
return *this;
}
std::string& MString::replace(const std::string &before, const std::string &after)
{
size_type pos = rfind(before);
while (pos != npos) {
std::string::replace(pos, before.size(), after);
pos = rfind(before);
}
return *this;
}
MPL_END_NAMESPACE
#ifdef _MSC_VER
# pragma warning (pop)
#endif
<commit_msg>内存空间分配之后需要进行置0初始化<commit_after>/**
* Copyright 2017 Shusheng Shao <iblackangel@163.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.
*/
#include <mpl/mstring.h>
#ifdef _MSC_VER
# pragma warning (push)
# pragma warning (disable: 4996)
#endif
MPL_BEGIN_NAMESPACE
std::string toXString(const char *fmt, ...)
{
std::string buffer;
va_list vargs;
va_start(vargs, fmt);
int len = vsnprintf(NULL, 0, fmt, vargs);
buffer.resize(len);
va_start(vargs, fmt);
vsnprintf(&buffer[0], len + 1, fmt, vargs);
va_end(vargs);
return buffer;
}
std::string hex2str(const uint8_t *data, size_t len)
{
std::string buffer;
char buf[3] = {0x00};
for (size_t m = 0; m < len; ++m) {
snprintf (buf, sizeof(buf), "%02X", data[m]);
buf[2] = '\0';
buffer += buf;
buffer += " ";
}
if (buffer.size() > 0) {
buffer.erase(buffer.begin() + (buffer.size() - 1));
}
return buffer;
}
std::string toString(char val)
{
return toXString("%c", val);
}
std::string toString(int val)
{
return toXString("%d", val);
}
std::string toString(unsigned val)
{
return toXString("%u", val);
}
std::string toString(long val)
{
return toXString("%ld", val);
}
std::string toString(unsigned long val)
{
return toXString("%lu", val);
}
std::string toString(long long val)
{
return toXString("%lld", val);
}
std::string toString(unsigned long long val)
{
return toXString("%llu", val);
}
std::string toString(float val)
{
return toXString("%f", val);
}
std::string toString(double val)
{
return toXString("%f", val);
}
std::string toString(long double val)
{
return toXString("%Lf", val);
}
std::string toUTF8(const std::string &str)
{
#if defined(_MSC_VER) || defined(M_OS_WIN)
// convert GBK to Unicode
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0);
wchar_t *strUnicode = new wchar_t[len];
wmemset(strUnicode, 0, len);
MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strUnicode, len);
// convert Unicode to UTF-8
len = WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, NULL, 0, NULL, NULL);
char * strUtf8 = new char[len];
WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, strUtf8, len, NULL, NULL);
std::string strOut(strUtf8); // strTemp is encoding UTF-8
delete[]strUnicode;
delete[]strUtf8;
strUnicode = NULL;
strUtf8 = NULL;
return strOut;
#elif defined(HAVE_ICONV_H)
char *gbk = new char[str.size() + 1];
size_t inbytes = str.size();
strcpy(gbk, str.c_str());
char *utf8 = new char[str.size() * 2 + 1]; // twice of gbk
size_t outbytes = str.size() * 2;
memset(utf8, 0x0, outbytes + 1);
char *inptr = gbk;
char *outptr = utf8;
// iconv_open
iconv_t cd = iconv_open("UTF-8", "GB18030");
if (cd == (iconv_t)-1) {
log_error("iconv_open failed: %s", error().c_str());
delete gbk;
delete utf8;
return std::string();
}
// iconv
size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes);
if (res == -1) {
log_error("iconv failed: %s", error().c_str());
iconv_close(cd);
delete gbk;
delete utf8;
return std::string();
}
// iconv_close
std::string outstr = utf8;
iconv_close(cd);
delete gbk;
delete utf8;
return outstr;
#else
return str;
#endif
}
std::string toGBK(const std::string &str)
{
#if defined(_MSC_VER) || defined(M_OS_WIN)
// convert UTF-8 to Unicode
int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
unsigned short *wszGBK = new unsigned short[len + 1];
memset(wszGBK, 0, len * 2 + 2);
MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)str.c_str(), -1, (LPWSTR)wszGBK, len);
// convert UTF-8 to Unicode
len = WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, NULL, 0, NULL, NULL);
char *szGBK = new char[len + 1];
memset(szGBK, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, szGBK, len, NULL, NULL);
std::string strTemp(szGBK);
delete[]szGBK;
delete[]wszGBK;
return strTemp;
#elif defined(HAVE_ICONV_H)
char *utf8 = new char[str.size() + 1];
size_t inbytes = str.size();
strcpy(utf8, str.c_str());
char *gbk = new char[str.size() * 2 + 1]; // twice size
size_t outbytes = str.size() * 2;
memset(gbk, 0x0, outbytes + 1);
char *inptr = utf8;
char *outptr = gbk;
// iconv_open
iconv_t cd = iconv_open("GB18030", "UTF-8");
if (cd == (iconv_t)-1) {
log_error("iconv_open failed: %s", error().c_str());
delete gbk;
delete utf8;
return std::string();
}
// iconv
size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes);
if (res == -1) {
log_error("iconv failed: %s", error().c_str());
iconv_close(cd);
delete gbk;
delete utf8;
return std::string();
}
// iconv_close
std::string outstr = gbk;
iconv_close(cd);
delete gbk;
delete utf8;
return outstr;
#else
return str;
#endif
}
std::vector<std::string> split(const std::string &src, const std::string &delim)
{
std::vector<std::string> res;
if (src.empty() || delim.empty())
return res;
std::string::size_type start = 0;
std::string::size_type pos = std::string::npos;
while ((pos = src.find(delim, start)) != std::string::npos) {
res.push_back(src.substr(start, pos - start));
start = pos + delim.size();
}
res.push_back(src.substr(start));
return res;
}
std::string trim(const std::string &src)
{
return trim_front(trim_back(src));
}
std::string trim_front(const std::string &src)
{
return src.substr(src.find_first_not_of(" \n\r\t"));
}
std::string trim_back(const std::string &src)
{
return src.substr(0, src.find_last_not_of(" \n\r\t") + 1);
}
void tolower(std::string &src)
{
transform(src.begin(), src.end(), src.begin(), ::tolower);
}
void toupper(std::string &src)
{
transform(src.begin(), src.end(), src.begin(), ::toupper);
}
MString::MString()
{
}
MString::MString(const std::string &str)
: std::string(str)
{
}
MString::MString(const char *s)
: std::string(s)
{
}
MString::~MString()
{
}
std::string& MString::replace(char before, char after)
{
size_type pos = rfind(before);
while (pos != npos) {
std::string::replace(pos, 1, 1, after);
pos = rfind(before);
}
return *this;
}
std::string& MString::replace(const std::string &before, const std::string &after)
{
size_type pos = rfind(before);
while (pos != npos) {
std::string::replace(pos, before.size(), after);
pos = rfind(before);
}
return *this;
}
MPL_END_NAMESPACE
#ifdef _MSC_VER
# pragma warning (pop)
#endif
<|endoftext|>
|
<commit_before>/**
* (C) Copyright Projet SECRET, INRIA, Rocquencourt
* (C) Bhaskar Biswas and Nicolas Sendrier
*
* (C) 2014 cryptosource GmbH
* (C) 2014 Falko Strenzke fstrenzke@cryptosource.de
*
* Distributed under the terms of the Botan license
*
*/
#include <botan/mceliece_key.h>
#include <botan/internal/bit_ops.h>
#include <botan/gf2m_small_m.h>
#include <botan/mceliece.h>
#include <botan/internal/code_based_key_gen.h>
#include <botan/code_based_util.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/workfactor.h>
namespace Botan {
McEliece_PrivateKey::McEliece_PrivateKey(polyn_gf2m const& goppa_polyn,
std::vector<u32bit> const& parity_check_matrix_coeffs,
std::vector<polyn_gf2m> const& square_root_matrix,
std::vector<gf2m> const& inverse_support,
std::vector<byte> const& public_matrix) :
McEliece_PublicKey(public_matrix, goppa_polyn.get_degree(), inverse_support.size()),
m_g(goppa_polyn),
m_sqrtmod(square_root_matrix),
m_Linv(inverse_support),
m_coeffs(parity_check_matrix_coeffs),
m_codimension(ceil_log2(inverse_support.size()) * goppa_polyn.get_degree()),
m_dimension(inverse_support.size() - m_codimension)
{
};
McEliece_PrivateKey::McEliece_PrivateKey(RandomNumberGenerator& rng, size_t code_length, size_t t)
{
u32bit ext_deg = ceil_log2(code_length);
*this = generate_mceliece_key(rng, ext_deg, code_length, t);
}
unsigned McEliece_PublicKey::get_message_word_bit_length() const
{
u32bit codimension = ceil_log2(m_code_length) * m_t;
return m_code_length - codimension;
}
AlgorithmIdentifier McEliece_PublicKey::algorithm_identifier() const
{
return AlgorithmIdentifier(get_oid(), std::vector<byte>());
}
std::vector<byte> McEliece_PublicKey::x509_subject_public_key() const
{
// encode the public key
return unlock(DER_Encoder()
.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.encode(static_cast<size_t>(get_code_length()))
.encode(static_cast<size_t>(get_t()))
.end_cons()
.encode(m_public_matrix, OCTET_STRING)
.end_cons()
.get_contents());
}
McEliece_PublicKey::McEliece_PublicKey(const McEliece_PublicKey & other) :
m_public_matrix(other.m_public_matrix),
m_t(other.m_t),
m_code_length(other.m_code_length)
{
}
size_t McEliece_PublicKey::estimated_strength() const
{
const u32bit ext_deg = ceil_log2(m_code_length);
const size_t k = m_code_length - ext_deg * m_t;
return mceliece_work_factor(m_code_length, k, m_t);
}
McEliece_PublicKey::McEliece_PublicKey(const std::vector<byte>& key_bits)
{
BER_Decoder dec(key_bits);
size_t n;
size_t t;
dec.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.decode(n)
.decode(t)
.end_cons()
.decode(m_public_matrix, OCTET_STRING)
.end_cons();
m_t = t;
m_code_length = n;
}
secure_vector<byte> McEliece_PrivateKey::pkcs8_private_key() const
{
DER_Encoder enc;
enc.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.encode(static_cast<size_t>(get_code_length()))
.encode(static_cast<size_t>(get_t()))
.end_cons()
.encode(m_public_matrix, OCTET_STRING)
.encode(m_g.encode(), OCTET_STRING); // g as octet string
enc.start_cons(SEQUENCE);
for(u32bit i = 0; i < m_sqrtmod.size(); i++)
{
enc.encode(m_sqrtmod[i].encode(), OCTET_STRING);
}
enc.end_cons();
secure_vector<byte> enc_support;
for(u32bit i = 0; i < m_Linv.size(); i++)
{
enc_support.push_back(m_Linv[i] >> 8);
enc_support.push_back(m_Linv[i]);
}
enc.encode(enc_support, OCTET_STRING);
secure_vector<byte> enc_H;
for(u32bit i = 0; i < m_coeffs.size(); i++)
{
enc_H.push_back(m_coeffs[i] >> 24);
enc_H.push_back(m_coeffs[i] >> 16);
enc_H.push_back(m_coeffs[i] >> 8);
enc_H.push_back(m_coeffs[i]);
}
enc.encode(enc_H, OCTET_STRING);
enc.end_cons();
return enc.get_contents();
}
bool McEliece_PrivateKey::check_key(RandomNumberGenerator& rng, bool) const
{
const McEliece_PublicKey* p_pk = dynamic_cast<const McEliece_PublicKey*>(this);
McEliece_Private_Operation priv_op(*this);
McEliece_Public_Operation pub_op(*p_pk, p_pk->get_code_length() );
secure_vector<byte> plaintext((p_pk->get_message_word_bit_length()+7)/8);
rng.randomize(&plaintext[0], plaintext.size() - 1);
secure_vector<gf2m> err_pos = create_random_error_positions(p_pk->get_code_length(), p_pk->get_t(), rng);
mceliece_message_parts parts(err_pos, plaintext, p_pk->get_code_length());
secure_vector<byte> message_and_error_input = parts.get_concat();
secure_vector<byte> ciphertext = pub_op.encrypt(&message_and_error_input[0], message_and_error_input.size(), rng);
secure_vector<byte> message_and_error_output = priv_op.decrypt(&ciphertext[0], ciphertext.size() );
return (message_and_error_input == message_and_error_output);
}
McEliece_PrivateKey::McEliece_PrivateKey(const secure_vector<byte>& key_bits)
{
size_t n, t;
secure_vector<byte> g_enc;
BER_Decoder dec_base(key_bits);
BER_Decoder dec = dec_base.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.decode(n)
.decode(t)
.end_cons()
.decode(m_public_matrix, OCTET_STRING)
.decode(g_enc, OCTET_STRING);
if(t == 0 || n == 0)
throw Decoding_Error("invalid McEliece parameters");
u32bit ext_deg = ceil_log2(n);
m_code_length = n;
m_t = t;
m_codimension = (ext_deg * t);
m_dimension = (n - m_codimension);
std::shared_ptr<gf2m_small_m::Gf2m_Field> sp_field(new gf2m_small_m::Gf2m_Field(ext_deg));
m_g = polyn_gf2m(g_enc, sp_field);
if(m_g.get_degree() != static_cast<int>(t))
{
throw Decoding_Error("degree of decoded Goppa polynomial is incorrect");
}
BER_Decoder dec2 = dec.start_cons(SEQUENCE);
for(u32bit i = 0; i < t/2; i++)
{
secure_vector<byte> sqrt_enc;
dec2.decode(sqrt_enc, OCTET_STRING);
while(sqrt_enc.size() < (t*2))
{
// ensure that the length is always t
sqrt_enc.push_back(0);
sqrt_enc.push_back(0);
}
if(sqrt_enc.size() != t*2)
{
throw Decoding_Error("length of square root polynomial entry is too large");
}
m_sqrtmod.push_back(polyn_gf2m(sqrt_enc, sp_field));
}
secure_vector<byte> enc_support;
BER_Decoder dec3 = dec2.end_cons()
.decode(enc_support, OCTET_STRING);
if(enc_support.size() % 2)
{
throw Decoding_Error("encoded support has odd length");
}
if(enc_support.size() / 2 != n)
{
throw Decoding_Error("encoded support has length different from code length");
}
for(u32bit i = 0; i < n*2; i+=2)
{
gf2m el = (enc_support[i] << 8) | enc_support[i+1];
m_Linv.push_back(el);
}
secure_vector<byte> enc_H;
dec3.decode(enc_H, OCTET_STRING)
.end_cons();
if(enc_H.size() % 4)
{
throw Decoding_Error("encoded parity check matrix has length which is not a multiple of four");
}
if(enc_H.size()/4 != bit_size_to_32bit_size(m_codimension) * m_code_length )
{
throw Decoding_Error("encoded parity check matrix has wrong length");
}
for(u32bit i = 0; i < enc_H.size(); i+=4)
{
u32bit coeff = (enc_H[i] << 24) | (enc_H[i+1] << 16) | (enc_H[i+2] << 8) | enc_H[i+3];
m_coeffs.push_back(coeff);
}
}
bool McEliece_PrivateKey::operator==(const McEliece_PrivateKey & other) const
{
if(*static_cast<const McEliece_PublicKey*>(this) != *static_cast<const McEliece_PublicKey*>(&other))
{
return false;
}
if(m_g != other.m_g)
{
return false;
}
if( m_sqrtmod != other.m_sqrtmod)
{
return false;
}
if( m_Linv != other.m_Linv)
{
return false;
}
if( m_coeffs != other.m_coeffs)
{
return false;
}
if(m_codimension != other.m_codimension || m_dimension != other.m_dimension)
{
return false;
}
return true;
}
bool McEliece_PublicKey::operator==(const McEliece_PublicKey& other) const
{
if(m_public_matrix != other.m_public_matrix)
{
return false;
}
if(m_t != other.m_t )
{
return false;
}
if( m_code_length != other.m_code_length)
{
return false;
}
return true;
}
}
<commit_msg>Cleanup<commit_after>/**
* (C) Copyright Projet SECRET, INRIA, Rocquencourt
* (C) Bhaskar Biswas and Nicolas Sendrier
*
* (C) 2014 cryptosource GmbH
* (C) 2014 Falko Strenzke fstrenzke@cryptosource.de
*
* Distributed under the terms of the Botan license
*
*/
#include <botan/mceliece_key.h>
#include <botan/internal/bit_ops.h>
#include <botan/gf2m_small_m.h>
#include <botan/mceliece.h>
#include <botan/internal/code_based_key_gen.h>
#include <botan/code_based_util.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/workfactor.h>
namespace Botan {
McEliece_PrivateKey::McEliece_PrivateKey(polyn_gf2m const& goppa_polyn,
std::vector<u32bit> const& parity_check_matrix_coeffs,
std::vector<polyn_gf2m> const& square_root_matrix,
std::vector<gf2m> const& inverse_support,
std::vector<byte> const& public_matrix) :
McEliece_PublicKey(public_matrix, goppa_polyn.get_degree(), inverse_support.size()),
m_g(goppa_polyn),
m_sqrtmod(square_root_matrix),
m_Linv(inverse_support),
m_coeffs(parity_check_matrix_coeffs),
m_codimension(ceil_log2(inverse_support.size()) * goppa_polyn.get_degree()),
m_dimension(inverse_support.size() - m_codimension)
{
};
McEliece_PrivateKey::McEliece_PrivateKey(RandomNumberGenerator& rng, size_t code_length, size_t t)
{
u32bit ext_deg = ceil_log2(code_length);
*this = generate_mceliece_key(rng, ext_deg, code_length, t);
}
unsigned McEliece_PublicKey::get_message_word_bit_length() const
{
u32bit codimension = ceil_log2(m_code_length) * m_t;
return m_code_length - codimension;
}
AlgorithmIdentifier McEliece_PublicKey::algorithm_identifier() const
{
return AlgorithmIdentifier(get_oid(), std::vector<byte>());
}
std::vector<byte> McEliece_PublicKey::x509_subject_public_key() const
{
// encode the public key
return unlock(DER_Encoder()
.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.encode(static_cast<size_t>(get_code_length()))
.encode(static_cast<size_t>(get_t()))
.end_cons()
.encode(m_public_matrix, OCTET_STRING)
.end_cons()
.get_contents());
}
McEliece_PublicKey::McEliece_PublicKey(const McEliece_PublicKey & other) :
m_public_matrix(other.m_public_matrix),
m_t(other.m_t),
m_code_length(other.m_code_length)
{
}
size_t McEliece_PublicKey::estimated_strength() const
{
const u32bit ext_deg = ceil_log2(m_code_length);
const size_t k = m_code_length - ext_deg * m_t;
return mceliece_work_factor(m_code_length, k, m_t);
}
McEliece_PublicKey::McEliece_PublicKey(const std::vector<byte>& key_bits)
{
BER_Decoder dec(key_bits);
size_t n;
size_t t;
dec.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.decode(n)
.decode(t)
.end_cons()
.decode(m_public_matrix, OCTET_STRING)
.end_cons();
m_t = t;
m_code_length = n;
}
secure_vector<byte> McEliece_PrivateKey::pkcs8_private_key() const
{
DER_Encoder enc;
enc.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.encode(static_cast<size_t>(get_code_length()))
.encode(static_cast<size_t>(get_t()))
.end_cons()
.encode(m_public_matrix, OCTET_STRING)
.encode(m_g.encode(), OCTET_STRING); // g as octet string
enc.start_cons(SEQUENCE);
for(u32bit i = 0; i < m_sqrtmod.size(); i++)
{
enc.encode(m_sqrtmod[i].encode(), OCTET_STRING);
}
enc.end_cons();
secure_vector<byte> enc_support;
for(u32bit i = 0; i < m_Linv.size(); i++)
{
enc_support.push_back(m_Linv[i] >> 8);
enc_support.push_back(m_Linv[i]);
}
enc.encode(enc_support, OCTET_STRING);
secure_vector<byte> enc_H;
for(u32bit i = 0; i < m_coeffs.size(); i++)
{
enc_H.push_back(m_coeffs[i] >> 24);
enc_H.push_back(m_coeffs[i] >> 16);
enc_H.push_back(m_coeffs[i] >> 8);
enc_H.push_back(m_coeffs[i]);
}
enc.encode(enc_H, OCTET_STRING);
enc.end_cons();
return enc.get_contents();
}
bool McEliece_PrivateKey::check_key(RandomNumberGenerator& rng, bool) const
{
McEliece_Private_Operation priv_op(*this);
McEliece_Public_Operation pub_op(*this, get_code_length());
secure_vector<byte> plaintext((this->get_message_word_bit_length()+7)/8);
rng.randomize(&plaintext[0], plaintext.size() - 1);
const secure_vector<gf2m> err_pos = create_random_error_positions(this->get_code_length(), this->get_t(), rng);
mceliece_message_parts parts(err_pos, plaintext, this->get_code_length());
secure_vector<byte> message_and_error_input = parts.get_concat();
secure_vector<byte> ciphertext = pub_op.encrypt(&message_and_error_input[0], message_and_error_input.size(), rng);
secure_vector<byte> message_and_error_output = priv_op.decrypt(&ciphertext[0], ciphertext.size());
return (message_and_error_input == message_and_error_output);
}
McEliece_PrivateKey::McEliece_PrivateKey(const secure_vector<byte>& key_bits)
{
size_t n, t;
secure_vector<byte> g_enc;
BER_Decoder dec_base(key_bits);
BER_Decoder dec = dec_base.start_cons(SEQUENCE)
.start_cons(SEQUENCE)
.decode(n)
.decode(t)
.end_cons()
.decode(m_public_matrix, OCTET_STRING)
.decode(g_enc, OCTET_STRING);
if(t == 0 || n == 0)
throw Decoding_Error("invalid McEliece parameters");
u32bit ext_deg = ceil_log2(n);
m_code_length = n;
m_t = t;
m_codimension = (ext_deg * t);
m_dimension = (n - m_codimension);
std::shared_ptr<gf2m_small_m::Gf2m_Field> sp_field(new gf2m_small_m::Gf2m_Field(ext_deg));
m_g = polyn_gf2m(g_enc, sp_field);
if(m_g.get_degree() != static_cast<int>(t))
{
throw Decoding_Error("degree of decoded Goppa polynomial is incorrect");
}
BER_Decoder dec2 = dec.start_cons(SEQUENCE);
for(u32bit i = 0; i < t/2; i++)
{
secure_vector<byte> sqrt_enc;
dec2.decode(sqrt_enc, OCTET_STRING);
while(sqrt_enc.size() < (t*2))
{
// ensure that the length is always t
sqrt_enc.push_back(0);
sqrt_enc.push_back(0);
}
if(sqrt_enc.size() != t*2)
{
throw Decoding_Error("length of square root polynomial entry is too large");
}
m_sqrtmod.push_back(polyn_gf2m(sqrt_enc, sp_field));
}
secure_vector<byte> enc_support;
BER_Decoder dec3 = dec2.end_cons()
.decode(enc_support, OCTET_STRING);
if(enc_support.size() % 2)
{
throw Decoding_Error("encoded support has odd length");
}
if(enc_support.size() / 2 != n)
{
throw Decoding_Error("encoded support has length different from code length");
}
for(u32bit i = 0; i < n*2; i+=2)
{
gf2m el = (enc_support[i] << 8) | enc_support[i+1];
m_Linv.push_back(el);
}
secure_vector<byte> enc_H;
dec3.decode(enc_H, OCTET_STRING)
.end_cons();
if(enc_H.size() % 4)
{
throw Decoding_Error("encoded parity check matrix has length which is not a multiple of four");
}
if(enc_H.size()/4 != bit_size_to_32bit_size(m_codimension) * m_code_length )
{
throw Decoding_Error("encoded parity check matrix has wrong length");
}
for(u32bit i = 0; i < enc_H.size(); i+=4)
{
u32bit coeff = (enc_H[i] << 24) | (enc_H[i+1] << 16) | (enc_H[i+2] << 8) | enc_H[i+3];
m_coeffs.push_back(coeff);
}
}
bool McEliece_PrivateKey::operator==(const McEliece_PrivateKey & other) const
{
if(*static_cast<const McEliece_PublicKey*>(this) != *static_cast<const McEliece_PublicKey*>(&other))
{
return false;
}
if(m_g != other.m_g)
{
return false;
}
if( m_sqrtmod != other.m_sqrtmod)
{
return false;
}
if( m_Linv != other.m_Linv)
{
return false;
}
if( m_coeffs != other.m_coeffs)
{
return false;
}
if(m_codimension != other.m_codimension || m_dimension != other.m_dimension)
{
return false;
}
return true;
}
bool McEliece_PublicKey::operator==(const McEliece_PublicKey& other) const
{
if(m_public_matrix != other.m_public_matrix)
{
return false;
}
if(m_t != other.m_t )
{
return false;
}
if( m_code_length != other.m_code_length)
{
return false;
}
return true;
}
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <map>
#include <sstream>
#include "RaZ/Render/Model.hpp"
#include "RaZ/Utils/FileUtils.hpp"
#include "RaZ/Utils/ModelLoader.hpp"
#include "RaZ/Utils/MtlLoader.hpp"
namespace Raz {
namespace {
Vec3f computeTangent(const Vec3f& firstPos, const Vec3f& secondPos, const Vec3f& thirdPos,
const Vec2f& firstTexcoords, const Vec2f& secondTexcoords, const Vec2f& thirdTexcoords) {
const Vec3f firstEdge = secondPos - firstPos;
const Vec3f secondEdge = thirdPos - firstPos;
const Vec2f firstUVDiff = secondTexcoords - firstTexcoords;
const Vec2f secondUVDiff = thirdTexcoords - firstTexcoords;
const float inversionFactor = 1.f / (firstUVDiff[0] * secondUVDiff[1] - secondUVDiff[0] * firstUVDiff[1]);
const Vec3f tangent = (firstEdge * secondUVDiff[1] - secondEdge * firstUVDiff[1]) * inversionFactor;
return tangent;
}
ModelPtr importObj(std::ifstream& file, const std::string& filePath) {
MeshPtr mesh = std::make_unique<Mesh>();
std::unordered_map<std::string, std::size_t> materialCorrespIndices;
std::vector<Vec3f> positions;
std::vector<Vec2f> texcoords;
std::vector<Vec3f> normals;
std::vector<std::vector<int64_t>> posIndices(1);
std::vector<std::vector<int64_t>> texcoordsIndices(1);
std::vector<std::vector<int64_t>> normalsIndices(1);
while (!file.eof()) {
std::string line;
file >> line;
if (line[0] == 'v') {
if (line[1] == 'n') { // Normals
Vec3f normalsTriplet {};
file >> normalsTriplet[0]
>> normalsTriplet[1]
>> normalsTriplet[2];
normals.push_back(normalsTriplet);
} else if (line[1] == 't') { // Texcoords
Vec2f texcoordsTriplet {};
file >> texcoordsTriplet[0]
>> texcoordsTriplet[1];
texcoords.push_back(texcoordsTriplet);
} else { // Vertices
Vec3f positionTriplet {};
file >> positionTriplet[0]
>> positionTriplet[1]
>> positionTriplet[2];
positions.push_back(positionTriplet);
}
} else if (line[0] == 'f') { // Faces
std::getline(file, line);
const char delim = '/';
const auto nbVertices = static_cast<uint16_t>(std::count(line.cbegin(), line.cend(), ' '));
const auto nbParts = static_cast<uint8_t>(std::count(line.cbegin(), line.cend(), delim) / nbVertices + 1);
const bool quadFaces = (nbVertices == 4);
std::stringstream indicesStream(line);
std::vector<int64_t> partIndices(nbParts * nbVertices);
std::string vertex;
for (std::size_t vertIndex = 0; vertIndex < nbVertices; ++vertIndex) {
indicesStream >> vertex;
std::stringstream vertParts(vertex);
std::string part;
uint8_t partIndex = 0;
while (std::getline(vertParts, part, delim)) {
if (!part.empty())
partIndices[partIndex * nbParts + vertIndex + (partIndex * quadFaces)] = std::stol(part);
++partIndex;
}
}
if (quadFaces) {
posIndices.back().emplace_back(partIndices[2]);
posIndices.back().emplace_back(partIndices[0]);
posIndices.back().emplace_back(partIndices[3]);
texcoordsIndices.back().emplace_back(partIndices[6]);
texcoordsIndices.back().emplace_back(partIndices[4]);
texcoordsIndices.back().emplace_back(partIndices[7]);
normalsIndices.back().emplace_back(partIndices[10]);
normalsIndices.back().emplace_back(partIndices[8]);
normalsIndices.back().emplace_back(partIndices[11]);
}
posIndices.back().emplace_back(partIndices[1]);
posIndices.back().emplace_back(partIndices[0]);
posIndices.back().emplace_back(partIndices[2]);
texcoordsIndices.back().emplace_back(partIndices[4 + quadFaces]);
texcoordsIndices.back().emplace_back(partIndices[3 + quadFaces]);
texcoordsIndices.back().emplace_back(partIndices[5 + quadFaces]);
const auto quadStride = static_cast<uint8_t>(quadFaces * 2);
normalsIndices.back().emplace_back(partIndices[7 + quadStride]);
normalsIndices.back().emplace_back(partIndices[6 + quadStride]);
normalsIndices.back().emplace_back(partIndices[8 + quadStride]);
} else if (line[0] == 'm') {
std::string mtlFileName;
file >> mtlFileName;
const auto mtlFilePath = FileUtils::extractPathToFile(filePath) + mtlFileName;
MtlLoader::importMtl(mtlFilePath, mesh->getMaterials(), materialCorrespIndices);
} else if (line[0] == 'u') {
if (!materialCorrespIndices.empty()) {
std::string materialName;
file >> materialName;
mesh->getSubmeshes().back()->setMaterialIndex(materialCorrespIndices.find(materialName)->second);
}
} else if (line[0] == 'o' || line[0] == 'g') {
if (!posIndices.front().empty()) {
const std::size_t newSize = posIndices.size() + 1;
posIndices.resize(newSize);
texcoordsIndices.resize(newSize);
normalsIndices.resize(newSize);
mesh->addSubmesh(std::make_unique<Submesh>());
}
std::getline(file, line);
} else {
std::getline(file, line); // Skip the rest of the line
}
}
std::map<std::array<std::size_t, 3>, unsigned int> indicesMap;
for (std::size_t submeshIndex = 0; submeshIndex < mesh->getSubmeshes().size(); ++submeshIndex) {
SubmeshPtr& submesh = mesh->getSubmeshes()[submeshIndex];
indicesMap.clear();
for (std::size_t partIndex = 0; partIndex < posIndices[submeshIndex].size(); ++partIndex) {
// Face (vertices indices triplets), containing position/texcoords/normals
// vertIndices[i][j] -> vertex i, feature j (j = 0 -> position, j = 1 -> texcoords, j = 2 -> normal)
std::array<std::array<std::size_t, 3>, 3> vertIndices {};
// First vertex informations
int64_t tempIndex = posIndices[submeshIndex][partIndex];
vertIndices[0][0] = (tempIndex < 0 ? tempIndex + positions.size() : tempIndex - 1ul);
tempIndex = texcoordsIndices[submeshIndex][partIndex];
vertIndices[0][1] = (tempIndex < 0 ? tempIndex + texcoords.size() : tempIndex - 1ul);
tempIndex = normalsIndices[submeshIndex][partIndex];
vertIndices[0][2] = (tempIndex < 0 ? tempIndex + normals.size() : tempIndex - 1ul);
++partIndex;
// Second vertex informations
tempIndex = posIndices[submeshIndex][partIndex];
vertIndices[1][0] = (tempIndex < 0 ? tempIndex + positions.size() : tempIndex - 1ul);
tempIndex = texcoordsIndices[submeshIndex][partIndex];
vertIndices[1][1] = (tempIndex < 0 ? tempIndex + texcoords.size() : tempIndex - 1ul);
tempIndex = normalsIndices[submeshIndex][partIndex];
vertIndices[1][2] = (tempIndex < 0 ? tempIndex + normals.size() : tempIndex - 1ul);
++partIndex;
// Third vertex informations
tempIndex = posIndices[submeshIndex][partIndex];
vertIndices[2][0] = (tempIndex < 0 ? tempIndex + positions.size() : tempIndex - 1ul);
tempIndex = texcoordsIndices[submeshIndex][partIndex];
vertIndices[2][1] = (tempIndex < 0 ? tempIndex + texcoords.size() : tempIndex - 1ul);
tempIndex = normalsIndices[submeshIndex][partIndex];
vertIndices[2][2] = (tempIndex < 0 ? tempIndex + normals.size() : tempIndex - 1ul);
const std::array<Vec3f, 3> facePositions = { positions[vertIndices[0][0]],
positions[vertIndices[1][0]],
positions[vertIndices[2][0]] };
Vec3f faceTangent {};
std::array<Vec2f, 3> faceTexcoords {};
if (!texcoords.empty()) {
faceTexcoords[0] = texcoords[vertIndices[0][1]];
faceTexcoords[1] = texcoords[vertIndices[1][1]];
faceTexcoords[2] = texcoords[vertIndices[2][1]];
faceTangent = computeTangent(facePositions[0], facePositions[1], facePositions[2],
faceTexcoords[0], faceTexcoords[1], faceTexcoords[2]);
}
std::array<Vec3f, 3> faceNormals {};
if (!normals.empty()) {
faceNormals[0] = normals[vertIndices[0][2]];
faceNormals[1] = normals[vertIndices[1][2]];
faceNormals[2] = normals[vertIndices[2][2]];
}
for (uint8_t vertPartIndex = 0; vertPartIndex < 3; ++vertPartIndex) {
const auto indexIter = indicesMap.find(vertIndices[vertPartIndex]);
if (indexIter != indicesMap.cend()) {
submesh->getVertices()[indexIter->second].tangent += faceTangent; // Adding current tangent to be averaged later
submesh->getIndices().emplace_back(indexIter->second);
} else {
Vertex vert {};
vert.position = facePositions[vertPartIndex];
vert.texcoords = faceTexcoords[vertPartIndex];
vert.normal = faceNormals[vertPartIndex];
vert.tangent = faceTangent;
submesh->getIndices().emplace_back(indicesMap.size());
indicesMap.emplace(vertIndices[vertPartIndex], indicesMap.size());
submesh->getVertices().push_back(vert);
}
}
}
// Normalizing tangents to become unit vectors & to be averaged after being accumulated
for (auto& vertex : submesh->getVertices())
vertex.tangent = (vertex.tangent - vertex.normal * vertex.tangent.dot(vertex.normal)).normalize();
}
return std::make_unique<Model>(std::move(mesh));
}
ModelPtr importOff(std::ifstream& file) {
MeshPtr mesh = std::make_unique<Mesh>();
mesh->getSubmeshes().emplace_back(std::make_unique<Submesh>());
std::size_t vertexCount, faceCount;
file.ignore(3);
file >> vertexCount >> faceCount;
file.ignore(100, '\n');
mesh->getSubmeshes().front()->getVertices().resize(vertexCount * 3);
for (std::size_t vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex)
file >> mesh->getSubmeshes().front()->getVertices()[vertexIndex].position[0]
>> mesh->getSubmeshes().front()->getVertices()[vertexIndex].position[1]
>> mesh->getSubmeshes().front()->getVertices()[vertexIndex].position[2];
for (std::size_t faceIndex = 0; faceIndex < faceCount; ++faceIndex) {
uint16_t partCount {};
file >> partCount;
mesh->getSubmeshes().front()->getIndices().reserve(mesh->getSubmeshes().front()->getIndices().size() + partCount);
std::vector<std::size_t> indices(partCount);
file >> indices[0] >> indices[1] >> indices[2];
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[0]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[1]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[2]);
for (uint16_t partIndex = 3; partIndex < partCount; ++partIndex) {
file >> indices[partIndex];
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[0]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[partIndex - 1]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[partIndex]);
}
}
return std::make_unique<Model>(std::move(mesh));
}
} // namespace
ModelPtr ModelLoader::importModel(const std::string& filePath) {
ModelPtr model;
std::ifstream file(filePath, std::ios_base::in | std::ios_base::binary);
if (file) {
const std::string format = FileUtils::extractFileExtension(filePath);
if (format == "obj" || format == "OBJ")
model = importObj(file, filePath);
else if (format == "off" || format == "OFF")
model = importOff(file);
else
throw std::runtime_error("Error: '" + format + "' format is not supported");
} else {
throw std::runtime_error("Error: Couldn't open the file '" + filePath + "'");
}
return model;
}
} // namespace Raz
<commit_msg>[Update] OFF loader is now pre-reserving indices (triangles assumed)<commit_after>#include <fstream>
#include <map>
#include <sstream>
#include "RaZ/Render/Model.hpp"
#include "RaZ/Utils/FileUtils.hpp"
#include "RaZ/Utils/ModelLoader.hpp"
#include "RaZ/Utils/MtlLoader.hpp"
namespace Raz {
namespace {
Vec3f computeTangent(const Vec3f& firstPos, const Vec3f& secondPos, const Vec3f& thirdPos,
const Vec2f& firstTexcoords, const Vec2f& secondTexcoords, const Vec2f& thirdTexcoords) {
const Vec3f firstEdge = secondPos - firstPos;
const Vec3f secondEdge = thirdPos - firstPos;
const Vec2f firstUVDiff = secondTexcoords - firstTexcoords;
const Vec2f secondUVDiff = thirdTexcoords - firstTexcoords;
const float inversionFactor = 1.f / (firstUVDiff[0] * secondUVDiff[1] - secondUVDiff[0] * firstUVDiff[1]);
const Vec3f tangent = (firstEdge * secondUVDiff[1] - secondEdge * firstUVDiff[1]) * inversionFactor;
return tangent;
}
ModelPtr importObj(std::ifstream& file, const std::string& filePath) {
MeshPtr mesh = std::make_unique<Mesh>();
std::unordered_map<std::string, std::size_t> materialCorrespIndices;
std::vector<Vec3f> positions;
std::vector<Vec2f> texcoords;
std::vector<Vec3f> normals;
std::vector<std::vector<int64_t>> posIndices(1);
std::vector<std::vector<int64_t>> texcoordsIndices(1);
std::vector<std::vector<int64_t>> normalsIndices(1);
while (!file.eof()) {
std::string line;
file >> line;
if (line[0] == 'v') {
if (line[1] == 'n') { // Normals
Vec3f normalsTriplet {};
file >> normalsTriplet[0]
>> normalsTriplet[1]
>> normalsTriplet[2];
normals.push_back(normalsTriplet);
} else if (line[1] == 't') { // Texcoords
Vec2f texcoordsTriplet {};
file >> texcoordsTriplet[0]
>> texcoordsTriplet[1];
texcoords.push_back(texcoordsTriplet);
} else { // Vertices
Vec3f positionTriplet {};
file >> positionTriplet[0]
>> positionTriplet[1]
>> positionTriplet[2];
positions.push_back(positionTriplet);
}
} else if (line[0] == 'f') { // Faces
std::getline(file, line);
const char delim = '/';
const auto nbVertices = static_cast<uint16_t>(std::count(line.cbegin(), line.cend(), ' '));
const auto nbParts = static_cast<uint8_t>(std::count(line.cbegin(), line.cend(), delim) / nbVertices + 1);
const bool quadFaces = (nbVertices == 4);
std::stringstream indicesStream(line);
std::vector<int64_t> partIndices(nbParts * nbVertices);
std::string vertex;
for (std::size_t vertIndex = 0; vertIndex < nbVertices; ++vertIndex) {
indicesStream >> vertex;
std::stringstream vertParts(vertex);
std::string part;
uint8_t partIndex = 0;
while (std::getline(vertParts, part, delim)) {
if (!part.empty())
partIndices[partIndex * nbParts + vertIndex + (partIndex * quadFaces)] = std::stol(part);
++partIndex;
}
}
if (quadFaces) {
posIndices.back().emplace_back(partIndices[2]);
posIndices.back().emplace_back(partIndices[0]);
posIndices.back().emplace_back(partIndices[3]);
texcoordsIndices.back().emplace_back(partIndices[6]);
texcoordsIndices.back().emplace_back(partIndices[4]);
texcoordsIndices.back().emplace_back(partIndices[7]);
normalsIndices.back().emplace_back(partIndices[10]);
normalsIndices.back().emplace_back(partIndices[8]);
normalsIndices.back().emplace_back(partIndices[11]);
}
posIndices.back().emplace_back(partIndices[1]);
posIndices.back().emplace_back(partIndices[0]);
posIndices.back().emplace_back(partIndices[2]);
texcoordsIndices.back().emplace_back(partIndices[4 + quadFaces]);
texcoordsIndices.back().emplace_back(partIndices[3 + quadFaces]);
texcoordsIndices.back().emplace_back(partIndices[5 + quadFaces]);
const auto quadStride = static_cast<uint8_t>(quadFaces * 2);
normalsIndices.back().emplace_back(partIndices[7 + quadStride]);
normalsIndices.back().emplace_back(partIndices[6 + quadStride]);
normalsIndices.back().emplace_back(partIndices[8 + quadStride]);
} else if (line[0] == 'm') {
std::string mtlFileName;
file >> mtlFileName;
const auto mtlFilePath = FileUtils::extractPathToFile(filePath) + mtlFileName;
MtlLoader::importMtl(mtlFilePath, mesh->getMaterials(), materialCorrespIndices);
} else if (line[0] == 'u') {
if (!materialCorrespIndices.empty()) {
std::string materialName;
file >> materialName;
mesh->getSubmeshes().back()->setMaterialIndex(materialCorrespIndices.find(materialName)->second);
}
} else if (line[0] == 'o' || line[0] == 'g') {
if (!posIndices.front().empty()) {
const std::size_t newSize = posIndices.size() + 1;
posIndices.resize(newSize);
texcoordsIndices.resize(newSize);
normalsIndices.resize(newSize);
mesh->addSubmesh(std::make_unique<Submesh>());
}
std::getline(file, line);
} else {
std::getline(file, line); // Skip the rest of the line
}
}
std::map<std::array<std::size_t, 3>, unsigned int> indicesMap;
for (std::size_t submeshIndex = 0; submeshIndex < mesh->getSubmeshes().size(); ++submeshIndex) {
SubmeshPtr& submesh = mesh->getSubmeshes()[submeshIndex];
indicesMap.clear();
for (std::size_t partIndex = 0; partIndex < posIndices[submeshIndex].size(); ++partIndex) {
// Face (vertices indices triplets), containing position/texcoords/normals
// vertIndices[i][j] -> vertex i, feature j (j = 0 -> position, j = 1 -> texcoords, j = 2 -> normal)
std::array<std::array<std::size_t, 3>, 3> vertIndices {};
// First vertex informations
int64_t tempIndex = posIndices[submeshIndex][partIndex];
vertIndices[0][0] = (tempIndex < 0 ? tempIndex + positions.size() : tempIndex - 1ul);
tempIndex = texcoordsIndices[submeshIndex][partIndex];
vertIndices[0][1] = (tempIndex < 0 ? tempIndex + texcoords.size() : tempIndex - 1ul);
tempIndex = normalsIndices[submeshIndex][partIndex];
vertIndices[0][2] = (tempIndex < 0 ? tempIndex + normals.size() : tempIndex - 1ul);
++partIndex;
// Second vertex informations
tempIndex = posIndices[submeshIndex][partIndex];
vertIndices[1][0] = (tempIndex < 0 ? tempIndex + positions.size() : tempIndex - 1ul);
tempIndex = texcoordsIndices[submeshIndex][partIndex];
vertIndices[1][1] = (tempIndex < 0 ? tempIndex + texcoords.size() : tempIndex - 1ul);
tempIndex = normalsIndices[submeshIndex][partIndex];
vertIndices[1][2] = (tempIndex < 0 ? tempIndex + normals.size() : tempIndex - 1ul);
++partIndex;
// Third vertex informations
tempIndex = posIndices[submeshIndex][partIndex];
vertIndices[2][0] = (tempIndex < 0 ? tempIndex + positions.size() : tempIndex - 1ul);
tempIndex = texcoordsIndices[submeshIndex][partIndex];
vertIndices[2][1] = (tempIndex < 0 ? tempIndex + texcoords.size() : tempIndex - 1ul);
tempIndex = normalsIndices[submeshIndex][partIndex];
vertIndices[2][2] = (tempIndex < 0 ? tempIndex + normals.size() : tempIndex - 1ul);
const std::array<Vec3f, 3> facePositions = { positions[vertIndices[0][0]],
positions[vertIndices[1][0]],
positions[vertIndices[2][0]] };
Vec3f faceTangent {};
std::array<Vec2f, 3> faceTexcoords {};
if (!texcoords.empty()) {
faceTexcoords[0] = texcoords[vertIndices[0][1]];
faceTexcoords[1] = texcoords[vertIndices[1][1]];
faceTexcoords[2] = texcoords[vertIndices[2][1]];
faceTangent = computeTangent(facePositions[0], facePositions[1], facePositions[2],
faceTexcoords[0], faceTexcoords[1], faceTexcoords[2]);
}
std::array<Vec3f, 3> faceNormals {};
if (!normals.empty()) {
faceNormals[0] = normals[vertIndices[0][2]];
faceNormals[1] = normals[vertIndices[1][2]];
faceNormals[2] = normals[vertIndices[2][2]];
}
for (uint8_t vertPartIndex = 0; vertPartIndex < 3; ++vertPartIndex) {
const auto indexIter = indicesMap.find(vertIndices[vertPartIndex]);
if (indexIter != indicesMap.cend()) {
submesh->getVertices()[indexIter->second].tangent += faceTangent; // Adding current tangent to be averaged later
submesh->getIndices().emplace_back(indexIter->second);
} else {
Vertex vert {};
vert.position = facePositions[vertPartIndex];
vert.texcoords = faceTexcoords[vertPartIndex];
vert.normal = faceNormals[vertPartIndex];
vert.tangent = faceTangent;
submesh->getIndices().emplace_back(indicesMap.size());
indicesMap.emplace(vertIndices[vertPartIndex], indicesMap.size());
submesh->getVertices().push_back(vert);
}
}
}
// Normalizing tangents to become unit vectors & to be averaged after being accumulated
for (auto& vertex : submesh->getVertices())
vertex.tangent = (vertex.tangent - vertex.normal * vertex.tangent.dot(vertex.normal)).normalize();
}
return std::make_unique<Model>(std::move(mesh));
}
ModelPtr importOff(std::ifstream& file) {
MeshPtr mesh = std::make_unique<Mesh>();
mesh->getSubmeshes().emplace_back(std::make_unique<Submesh>());
std::size_t vertexCount, faceCount;
file.ignore(3);
file >> vertexCount >> faceCount;
file.ignore(100, '\n');
mesh->getSubmeshes().front()->getVertices().resize(vertexCount * 3);
mesh->getSubmeshes().front()->getIndices().reserve(faceCount * 3);
for (std::size_t vertexIndex = 0; vertexIndex < vertexCount; ++vertexIndex)
file >> mesh->getSubmeshes().front()->getVertices()[vertexIndex].position[0]
>> mesh->getSubmeshes().front()->getVertices()[vertexIndex].position[1]
>> mesh->getSubmeshes().front()->getVertices()[vertexIndex].position[2];
for (std::size_t faceIndex = 0; faceIndex < faceCount; ++faceIndex) {
uint16_t partCount {};
file >> partCount;
std::vector<std::size_t> indices(partCount);
file >> indices[0] >> indices[1] >> indices[2];
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[0]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[1]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[2]);
for (uint16_t partIndex = 3; partIndex < partCount; ++partIndex) {
file >> indices[partIndex];
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[0]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[partIndex - 1]);
mesh->getSubmeshes().front()->getIndices().emplace_back(indices[partIndex]);
}
}
return std::make_unique<Model>(std::move(mesh));
}
} // namespace
ModelPtr ModelLoader::importModel(const std::string& filePath) {
ModelPtr model;
std::ifstream file(filePath, std::ios_base::in | std::ios_base::binary);
if (file) {
const std::string format = FileUtils::extractFileExtension(filePath);
if (format == "obj" || format == "OBJ")
model = importObj(file, filePath);
else if (format == "off" || format == "OFF")
model = importOff(file);
else
throw std::runtime_error("Error: '" + format + "' format is not supported");
} else {
throw std::runtime_error("Error: Couldn't open the file '" + filePath + "'");
}
return model;
}
} // namespace Raz
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: htmlmode.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 17:54:46 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SVX_HTMLMODE_HXX
#define _SVX_HTMLMODE_HXX
// include ---------------------------------------------------------------
// define ----------------------------------------------------------------
#define HTMLMODE_ON 0x0001
#define HTMLMODE_PARA_BORDER 0x0002 /* Absatzumrandungen */
#define HTMLMODE_PARA_DISTANCE 0x0004 /* bestimmte Absatzabstaende */
#define HTMLMODE_SMALL_CAPS 0x0008 /* Kapitaelchen */
#define HTMLMODE_FRM_COLUMNS 0x0010 /* spaltige Rahmen */
#define HTMLMODE_SOME_STYLES 0x0020 /* mind. MS IE */
#define HTMLMODE_FULL_STYLES 0x0040 /* == SW */
#define HTMLMODE_BLINK 0x0080 /* blinkende Zeichen*/
#define HTMLMODE_PARA_BLOCK 0x0100 /* Blocksatz */
#define HTMLMODE_DROPCAPS 0x0200 /* Initialen*/
#define HTMLMODE_FIRSTLINE 0x0400 /* Erstzeileneinzug mit Spacer == NS 3.0 */
#define HTMLMODE_GRAPH_POS 0x0800 /* Grafikpositionen Hintergrund */
#define HTMLMODE_FULL_ABS_POS 0x1000 /* abs. Rahmenpositionierung */
#define HTMLMODE_SOME_ABS_POS 0x2000 /* abs. Rahmenpositionierung vollst.*/
#define HTMLMODE_RESERVED1 0x4000
#define HTMLMODE_RESERVED0 0x8000
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.1256); FILE MERGED 2008/03/31 14:17:56 rt 1.2.1256.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: htmlmode.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVX_HTMLMODE_HXX
#define _SVX_HTMLMODE_HXX
// include ---------------------------------------------------------------
// define ----------------------------------------------------------------
#define HTMLMODE_ON 0x0001
#define HTMLMODE_PARA_BORDER 0x0002 /* Absatzumrandungen */
#define HTMLMODE_PARA_DISTANCE 0x0004 /* bestimmte Absatzabstaende */
#define HTMLMODE_SMALL_CAPS 0x0008 /* Kapitaelchen */
#define HTMLMODE_FRM_COLUMNS 0x0010 /* spaltige Rahmen */
#define HTMLMODE_SOME_STYLES 0x0020 /* mind. MS IE */
#define HTMLMODE_FULL_STYLES 0x0040 /* == SW */
#define HTMLMODE_BLINK 0x0080 /* blinkende Zeichen*/
#define HTMLMODE_PARA_BLOCK 0x0100 /* Blocksatz */
#define HTMLMODE_DROPCAPS 0x0200 /* Initialen*/
#define HTMLMODE_FIRSTLINE 0x0400 /* Erstzeileneinzug mit Spacer == NS 3.0 */
#define HTMLMODE_GRAPH_POS 0x0800 /* Grafikpositionen Hintergrund */
#define HTMLMODE_FULL_ABS_POS 0x1000 /* abs. Rahmenpositionierung */
#define HTMLMODE_SOME_ABS_POS 0x2000 /* abs. Rahmenpositionierung vollst.*/
#define HTMLMODE_RESERVED1 0x4000
#define HTMLMODE_RESERVED0 0x8000
#endif
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** ServerMediaSubsession.cpp
**
** -------------------------------------------------------------------------*/
#include <sstream>
// live555
#include <BasicUsageEnvironment.hh>
#include <GroupsockHelper.hh>
#include <Base64.hh>
// project
#include "ServerMediaSubsession.h"
#include "MJPEGVideoSource.h"
#include "DeviceSource.h"
// ---------------------------------
// BaseServerMediaSubsession
// ---------------------------------
FramedSource* BaseServerMediaSubsession::createSource(UsageEnvironment& env, FramedSource* videoES, const std::string& format)
{
FramedSource* source = NULL;
if (format == "video/MP2T")
{
source = MPEG2TransportStreamFramer::createNew(env, videoES);
}
else if (format == "video/H264")
{
source = H264VideoStreamDiscreteFramer::createNew(env, videoES);
}
else if (format == "video/H265")
{
source = H265VideoStreamDiscreteFramer::createNew(env, videoES);
}
else if (format == "video/JPEG")
{
source = MJPEGVideoSource::createNew(env, videoES);
}
else
{
source = videoES;
}
return source;
}
RTPSink* BaseServerMediaSubsession::createSink(UsageEnvironment& env, Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, const std::string& format)
{
RTPSink* videoSink = NULL;
if (format == "video/MP2T")
{
videoSink = SimpleRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic, 90000, "video", "MP2T", 1, True, False);
}
else if (format == "video/H264")
{
videoSink = H264VideoRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
else if (format == "video/H265")
{
videoSink = H265VideoRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
else if (format == "video/VP8")
{
videoSink = VP8VideoRTPSink::createNew (env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
#if LIVEMEDIA_LIBRARY_VERSION_INT > 1414454400
else if (format == "video/VP9")
{
videoSink = VP9VideoRTPSink::createNew (env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
#endif
else if (format == "video/JPEG")
{
videoSink = JPEGVideoRTPSink::createNew (env, rtpGroupsock);
}
else if (format.find("audio/L16") == 0)
{
std::istringstream is(format);
std::string dummy;
getline(is, dummy, '/');
getline(is, dummy, '/');
std::string sampleRate("44100");
getline(is, sampleRate, '/');
std::string channels("2");
getline(is, channels);
videoSink = SimpleRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic, std::stoi(sampleRate), "audio", "L16", std::stoi(channels), True, False);
}
return videoSink;
}
char const* BaseServerMediaSubsession::getAuxLine(V4L2DeviceSource* source,unsigned char rtpPayloadType)
{
const char* auxLine = NULL;
if (source)
{
std::ostringstream os;
os << "a=fmtp:" << int(rtpPayloadType) << " ";
os << source->getAuxLine();
os << "\r\n";
int width = source->getWidth();
int height = source->getHeight();
if ( (width > 0) && (height>0) ) {
os << "a=x-dimensions:" << width << "," << height << "\r\n";
}
auxLine = strdup(os.str().c_str());
}
return auxLine;
}
// -----------------------------------------
// ServerMediaSubsession for Multicast
// -----------------------------------------
MulticastServerMediaSubsession* MulticastServerMediaSubsession::createNew(UsageEnvironment& env
, struct in_addr destinationAddress
, Port rtpPortNum, Port rtcpPortNum
, int ttl
, StreamReplicator* replicator
, const std::string& format)
{
// Create a source
FramedSource* source = replicator->createStreamReplica();
FramedSource* videoSource = createSource(env, source, format);
// Create RTP/RTCP groupsock
Groupsock* rtpGroupsock = new Groupsock(env, destinationAddress, rtpPortNum, ttl);
Groupsock* rtcpGroupsock = new Groupsock(env, destinationAddress, rtcpPortNum, ttl);
// Create a RTP sink
RTPSink* videoSink = createSink(env, rtpGroupsock, 96, format);
// Create 'RTCP instance'
const unsigned maxCNAMElen = 100;
unsigned char CNAME[maxCNAMElen+1];
gethostname((char*)CNAME, maxCNAMElen);
CNAME[maxCNAMElen] = '\0';
RTCPInstance* rtcpInstance = RTCPInstance::createNew(env, rtcpGroupsock, 500, CNAME, videoSink, NULL);
// Start Playing the Sink
videoSink->startPlaying(*videoSource, NULL, NULL);
return new MulticastServerMediaSubsession(replicator, videoSink, rtcpInstance);
}
char const* MulticastServerMediaSubsession::sdpLines()
{
if (m_SDPLines.empty())
{
// Ugly workaround to give SPS/PPS that are get from the RTPSink
m_SDPLines.assign(PassiveServerMediaSubsession::sdpLines());
m_SDPLines.append(getAuxSDPLine(m_rtpSink,NULL));
}
return m_SDPLines.c_str();
}
char const* MulticastServerMediaSubsession::getAuxSDPLine(RTPSink* rtpSink,FramedSource* inputSource)
{
return this->getAuxLine(dynamic_cast<V4L2DeviceSource*>(m_replicator->inputSource()), rtpSink->rtpPayloadType());
}
// -----------------------------------------
// ServerMediaSubsession for Unicast
// -----------------------------------------
UnicastServerMediaSubsession* UnicastServerMediaSubsession::createNew(UsageEnvironment& env, StreamReplicator* replicator, const std::string& format)
{
return new UnicastServerMediaSubsession(env,replicator,format);
}
FramedSource* UnicastServerMediaSubsession::createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate)
{
FramedSource* source = m_replicator->createStreamReplica();
return createSource(envir(), source, m_format);
}
RTPSink* UnicastServerMediaSubsession::createNewRTPSink(Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource)
{
return createSink(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, m_format);
}
char const* UnicastServerMediaSubsession::getAuxSDPLine(RTPSink* rtpSink,FramedSource* inputSource)
{
return this->getAuxLine(dynamic_cast<V4L2DeviceSource*>(m_replicator->inputSource()), rtpSink->rtpPayloadType());
}
<commit_msg>fix build with old live555 release that doesnot support H265<commit_after>/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** ServerMediaSubsession.cpp
**
** -------------------------------------------------------------------------*/
#include <sstream>
// live555
#include <BasicUsageEnvironment.hh>
#include <GroupsockHelper.hh>
#include <Base64.hh>
// project
#include "ServerMediaSubsession.h"
#include "MJPEGVideoSource.h"
#include "DeviceSource.h"
// ---------------------------------
// BaseServerMediaSubsession
// ---------------------------------
FramedSource* BaseServerMediaSubsession::createSource(UsageEnvironment& env, FramedSource* videoES, const std::string& format)
{
FramedSource* source = NULL;
if (format == "video/MP2T")
{
source = MPEG2TransportStreamFramer::createNew(env, videoES);
}
else if (format == "video/H264")
{
source = H264VideoStreamDiscreteFramer::createNew(env, videoES);
}
else if (format == "video/H265")
{
source = H265VideoStreamDiscreteFramer::createNew(env, videoES);
}
else if (format == "video/JPEG")
{
source = MJPEGVideoSource::createNew(env, videoES);
}
else
{
source = videoES;
}
return source;
}
RTPSink* BaseServerMediaSubsession::createSink(UsageEnvironment& env, Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, const std::string& format)
{
RTPSink* videoSink = NULL;
if (format == "video/MP2T")
{
videoSink = SimpleRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic, 90000, "video", "MP2T", 1, True, False);
}
else if (format == "video/H264")
{
videoSink = H264VideoRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
else if (format == "video/VP8")
{
videoSink = VP8VideoRTPSink::createNew (env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
#if LIVEMEDIA_LIBRARY_VERSION_INT > 1414454400
else if (format == "video/VP9")
{
videoSink = VP9VideoRTPSink::createNew (env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
else if (format == "video/H265")
{
videoSink = H265VideoRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic);
}
#endif
else if (format == "video/JPEG")
{
videoSink = JPEGVideoRTPSink::createNew (env, rtpGroupsock);
}
else if (format.find("audio/L16") == 0)
{
std::istringstream is(format);
std::string dummy;
getline(is, dummy, '/');
getline(is, dummy, '/');
std::string sampleRate("44100");
getline(is, sampleRate, '/');
std::string channels("2");
getline(is, channels);
videoSink = SimpleRTPSink::createNew(env, rtpGroupsock,rtpPayloadTypeIfDynamic, std::stoi(sampleRate), "audio", "L16", std::stoi(channels), True, False);
}
return videoSink;
}
char const* BaseServerMediaSubsession::getAuxLine(V4L2DeviceSource* source,unsigned char rtpPayloadType)
{
const char* auxLine = NULL;
if (source)
{
std::ostringstream os;
os << "a=fmtp:" << int(rtpPayloadType) << " ";
os << source->getAuxLine();
os << "\r\n";
int width = source->getWidth();
int height = source->getHeight();
if ( (width > 0) && (height>0) ) {
os << "a=x-dimensions:" << width << "," << height << "\r\n";
}
auxLine = strdup(os.str().c_str());
}
return auxLine;
}
// -----------------------------------------
// ServerMediaSubsession for Multicast
// -----------------------------------------
MulticastServerMediaSubsession* MulticastServerMediaSubsession::createNew(UsageEnvironment& env
, struct in_addr destinationAddress
, Port rtpPortNum, Port rtcpPortNum
, int ttl
, StreamReplicator* replicator
, const std::string& format)
{
// Create a source
FramedSource* source = replicator->createStreamReplica();
FramedSource* videoSource = createSource(env, source, format);
// Create RTP/RTCP groupsock
Groupsock* rtpGroupsock = new Groupsock(env, destinationAddress, rtpPortNum, ttl);
Groupsock* rtcpGroupsock = new Groupsock(env, destinationAddress, rtcpPortNum, ttl);
// Create a RTP sink
RTPSink* videoSink = createSink(env, rtpGroupsock, 96, format);
// Create 'RTCP instance'
const unsigned maxCNAMElen = 100;
unsigned char CNAME[maxCNAMElen+1];
gethostname((char*)CNAME, maxCNAMElen);
CNAME[maxCNAMElen] = '\0';
RTCPInstance* rtcpInstance = RTCPInstance::createNew(env, rtcpGroupsock, 500, CNAME, videoSink, NULL);
// Start Playing the Sink
videoSink->startPlaying(*videoSource, NULL, NULL);
return new MulticastServerMediaSubsession(replicator, videoSink, rtcpInstance);
}
char const* MulticastServerMediaSubsession::sdpLines()
{
if (m_SDPLines.empty())
{
// Ugly workaround to give SPS/PPS that are get from the RTPSink
m_SDPLines.assign(PassiveServerMediaSubsession::sdpLines());
m_SDPLines.append(getAuxSDPLine(m_rtpSink,NULL));
}
return m_SDPLines.c_str();
}
char const* MulticastServerMediaSubsession::getAuxSDPLine(RTPSink* rtpSink,FramedSource* inputSource)
{
return this->getAuxLine(dynamic_cast<V4L2DeviceSource*>(m_replicator->inputSource()), rtpSink->rtpPayloadType());
}
// -----------------------------------------
// ServerMediaSubsession for Unicast
// -----------------------------------------
UnicastServerMediaSubsession* UnicastServerMediaSubsession::createNew(UsageEnvironment& env, StreamReplicator* replicator, const std::string& format)
{
return new UnicastServerMediaSubsession(env,replicator,format);
}
FramedSource* UnicastServerMediaSubsession::createNewStreamSource(unsigned clientSessionId, unsigned& estBitrate)
{
FramedSource* source = m_replicator->createStreamReplica();
return createSource(envir(), source, m_format);
}
RTPSink* UnicastServerMediaSubsession::createNewRTPSink(Groupsock* rtpGroupsock, unsigned char rtpPayloadTypeIfDynamic, FramedSource* inputSource)
{
return createSink(envir(), rtpGroupsock, rtpPayloadTypeIfDynamic, m_format);
}
char const* UnicastServerMediaSubsession::getAuxSDPLine(RTPSink* rtpSink,FramedSource* inputSource)
{
return this->getAuxLine(dynamic_cast<V4L2DeviceSource*>(m_replicator->inputSource()), rtpSink->rtpPayloadType());
}
<|endoftext|>
|
<commit_before>#include <limits> // for std::numeric_limits<unsigned int>::max()
#include "utility/memory.hpp"
#include "TimeWarpOutputManager.hpp"
namespace warped {
void TimeWarpOutputManager::initialize(unsigned int num_local_objects) {
output_queue_ = make_unique<std::vector<std::shared_ptr<Event>> []>(num_local_objects);
output_queue_lock_ = make_unique<std::mutex []>(num_local_objects);
}
void TimeWarpOutputManager::insertEvent(std::shared_ptr<Event> event,
unsigned int local_object_id) {
output_queue_lock_[local_object_id].lock();
output_queue_[local_object_id].push_back(event);
output_queue_lock_[local_object_id].unlock();
}
unsigned int TimeWarpOutputManager::fossilCollect(unsigned int gvt, unsigned int local_object_id) {
unsigned int retval = std::numeric_limits<unsigned int>::max();
if (output_queue_[local_object_id].empty())
return retval;
output_queue_lock_[local_object_id].lock();
auto min = output_queue_[local_object_id].begin();
while ((min->get()->timestamp() < gvt) && (min != output_queue_[local_object_id].end())) {
output_queue_[local_object_id].erase(min);
}
if (min != output_queue_[local_object_id].end()) {
retval = min->get()->timestamp();
}
output_queue_lock_[local_object_id].unlock();
return retval;
}
void TimeWarpOutputManager::fossilCollectAll(unsigned int gvt) {
for (unsigned int i = 0; i < output_queue_.get()->size(); i++) {
fossilCollect(gvt, i);
}
}
std::unique_ptr<std::vector<std::shared_ptr<Event>>>
TimeWarpOutputManager::removeEventsSentAtOrAfter(unsigned int rollback_time,
unsigned int local_object_id) {
auto events_to_cancel = make_unique<std::vector<std::shared_ptr<Event>>>();
output_queue_lock_[local_object_id].lock();
auto max = std::prev(output_queue_[local_object_id].end());
while ((max->get()->timestamp() >= rollback_time)
&& (max != output_queue_[local_object_id].begin())) {
events_to_cancel->push_back(*max);
output_queue_[local_object_id].erase(max--);
}
if ((max != output_queue_[local_object_id].begin())
&& (max->get()->timestamp() >= rollback_time)) {
events_to_cancel->push_back(*max);
output_queue_[local_object_id].erase(max);
}
output_queue_lock_[local_object_id].unlock();
return std::move(events_to_cancel);
}
std::size_t TimeWarpOutputManager::size(unsigned int local_object_id) {
return output_queue_[local_object_id].size();
}
} // namespace warped
<commit_msg>corrected while check conditions in output manager<commit_after>#include <limits> // for std::numeric_limits<unsigned int>::max()
#include "utility/memory.hpp"
#include "TimeWarpOutputManager.hpp"
namespace warped {
void TimeWarpOutputManager::initialize(unsigned int num_local_objects) {
output_queue_ = make_unique<std::vector<std::shared_ptr<Event>> []>(num_local_objects);
output_queue_lock_ = make_unique<std::mutex []>(num_local_objects);
}
void TimeWarpOutputManager::insertEvent(std::shared_ptr<Event> event,
unsigned int local_object_id) {
output_queue_lock_[local_object_id].lock();
output_queue_[local_object_id].push_back(event);
output_queue_lock_[local_object_id].unlock();
}
unsigned int TimeWarpOutputManager::fossilCollect(unsigned int gvt, unsigned int local_object_id) {
unsigned int retval = std::numeric_limits<unsigned int>::max();
if (output_queue_[local_object_id].empty())
return retval;
output_queue_lock_[local_object_id].lock();
auto min = output_queue_[local_object_id].begin();
while ((min != output_queue_[local_object_id].end()) && (min->get()->timestamp() < gvt)) {
min = output_queue_[local_object_id].erase(min);
}
if (min != output_queue_[local_object_id].end()) {
retval = min->get()->timestamp();
}
output_queue_lock_[local_object_id].unlock();
return retval;
}
void TimeWarpOutputManager::fossilCollectAll(unsigned int gvt) {
for (unsigned int i = 0; i < output_queue_.get()->size(); i++) {
fossilCollect(gvt, i);
}
}
std::unique_ptr<std::vector<std::shared_ptr<Event>>>
TimeWarpOutputManager::removeEventsSentAtOrAfter(unsigned int rollback_time,
unsigned int local_object_id) {
auto events_to_cancel = make_unique<std::vector<std::shared_ptr<Event>>>();
output_queue_lock_[local_object_id].lock();
auto max = std::prev(output_queue_[local_object_id].end());
while ((max != output_queue_[local_object_id].begin()) &&
(max->get()->timestamp() >= rollback_time)) {
events_to_cancel->push_back(*max);
output_queue_[local_object_id].erase(max);
max = std::prev(output_queue_[local_object_id].end());
}
if ((max != output_queue_[local_object_id].begin())
&& (max->get()->timestamp() >= rollback_time)) {
events_to_cancel->push_back(*max);
output_queue_[local_object_id].erase(max);
}
output_queue_lock_[local_object_id].unlock();
return std::move(events_to_cancel);
}
std::size_t TimeWarpOutputManager::size(unsigned int local_object_id) {
return output_queue_[local_object_id].size();
}
} // namespace warped
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.